From d703619819ebff529e198eafcc745a5e2e0f07b9 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Tue, 24 Nov 2026 17:41:10 -0500 Subject: [PATCH] feat(datasets)!: support replacing and clearing row tags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > 🤖 **This text was AI-generated.** Dataset updates previously combined incoming tags with the row's existing tags, so an empty list could not clear them. The update command and its add and refresh aliases now replace tags when the field is present. Supply a list of unique strings, use [] to clear all tags, or omit the field to preserve the current tags. A tag-only update needs just the row ID and the new list. ```sh bt datasets update my-dataset --rows '[{"id":"case-1","tags":["reviewed"]}]' ``` BREAKING CHANGE: To keep existing tags while adding new ones, pass the complete list of tags you want the row to have. Refs: SDK-956 Upstream: https://github.com/braintrustdata/braintrust/pull/26086 --- README.md | 1 + src/datasets/mod.rs | 3 ++ src/datasets/records.rs | 105 +++++++++++++++++++++++++++++++++------- 3 files changed, 91 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 241945bd..9a1203f9 100644 --- a/README.md +++ b/README.md @@ -392,6 +392,7 @@ Use `--max-concurrency ` to limit how many evaluators run at once. This does - `bt datasets refresh my-dataset --file records.jsonl --id-field metadata.case_id` — alias for `update` with explicit id path (fails if the dataset does not exist, and does not delete remote rows missing from the input). - `bt datasets view my-dataset` — show dataset metadata and previewed row payloads; defaults to loading up to 200 rows. Use `--limit ` to adjust, `--all-rows` to load every row, `--full` for exact values, or `bt sync pull dataset:` to export full rows to files. - `update`/`add`/`refresh` require explicit stable IDs via `id` or `--id-field`. +- To update only tags, run `bt datasets update my-dataset --rows '[{"id":"case-1","tags":["reviewed"]}]'`. The array replaces the row's tags and must contain unique strings. Use `"tags":[]` to clear the tags or omit `tags` to preserve them. - `--id-field` uses dot-separated paths; escape literal dots as `\.` and literal backslashes as `\\`. - `update`/`add`/`refresh` submit the provided rows directly and report success/failure without diffing remote rows first. - Accepted top-level record fields are `id`, `input`, `expected`, `metadata`, `tags`, and `origin` (plus the root field referenced by `--id-field`, if different). diff --git a/src/datasets/mod.rs b/src/datasets/mod.rs index 78de751a..f3468653 100644 --- a/src/datasets/mod.rs +++ b/src/datasets/mod.rs @@ -112,6 +112,9 @@ enum DatasetsCommands { /// Create a new dataset, optionally seeding rows from a file, --rows, or stdin Create(CreateArgs), /// Upsert remote dataset rows by record id + /// + /// Include a tags array of unique strings to replace a row's tags. Use [] to clear + /// the tags or omit the field to preserve them. A row can contain just its id and tags. #[command(visible_aliases = ["add", "refresh"])] Update(UpdateArgs), /// View a dataset diff --git a/src/datasets/records.rs b/src/datasets/records.rs index 092afe3a..591f75a2 100644 --- a/src/datasets/records.rs +++ b/src/datasets/records.rs @@ -8,7 +8,7 @@ use std::{ use anyhow::{anyhow, bail, Context, Result}; use chrono::Utc; use serde::{Deserialize, Deserializer}; -use serde_json::{Map, Value}; +use serde_json::{json, Map, Value}; use crate::utils::{lookup_object_path, new_uuid_id}; @@ -67,6 +67,10 @@ impl PreparedDatasetRecord { "tags".to_string(), Value::Array(tags.iter().cloned().map(Value::String).collect()), ); + if is_merge { + // Tags are unioned by default on merge. Replace the entire array. + row.insert("_merge_paths".to_string(), json!([["tags"]])); + } } if let Some(origin) = &self.origin { row.insert("origin".to_string(), origin.clone()); @@ -209,7 +213,7 @@ fn expect_record_object(value: Value, record_number: Option) -> Result>, id_field: &str, - require_ids: bool, + is_update: bool, ) -> Result> { let id_path = parse_id_field_path(id_field)?; let id_root = id_path.first().cloned().expect("id path must be non-empty"); @@ -217,10 +221,26 @@ pub(crate) fn prepare_records( let mut seen_ids = HashSet::new(); for (row_index, raw_record) in raw_records.into_iter().enumerate() { + let updates_tags = is_update && raw_record.contains_key("tags"); let (input_record, explicit_id) = deserialize_input_record(raw_record, &id_path, &id_root, row_index)?; + if updates_tags { + let tags = input_record.tags.as_ref().ok_or_else(|| { + anyhow!( + "dataset record {} tags must be an array of strings", + row_index + 1 + ) + })?; + let mut seen_tags = HashSet::new(); + if !tags.iter().all(|tag| seen_tags.insert(tag)) { + bail!( + "dataset record {} tags must not contain duplicates", + row_index + 1 + ); + } + } let record = - prepare_record_from_input(input_record, explicit_id, id_field, require_ids, row_index)?; + prepare_record_from_input(input_record, explicit_id, id_field, is_update, row_index)?; if !seen_ids.insert(record.id.clone()) { bail!("duplicate dataset record id '{}' in input", record.id); } @@ -542,6 +562,70 @@ mod tests { .contains("update`/`add`/`refresh` require explicit ids")); } + #[test] + fn update_rows_replace_tags_only_when_provided() { + let records = load_refresh_records( + None, + Some( + r#"[ + {"id":"case-1","tags":["reviewed","verified"]}, + {"id":"case-2","tags":[],"expected":"gold"}, + {"id":"case-3","expected":"gold"}, + {"id":"case-4"} + ]"#, + ), + "id", + ) + .expect("valid update rows"); + + let mut updates = records + .iter() + .map(|record| record.to_upload_row("dataset_1", true)) + .collect::>(); + for row in &mut updates { + assert_eq!(row.remove("dataset_id"), Some(json!("dataset_1"))); + assert_eq!(row.remove("_is_merge"), Some(json!(true))); + assert!(row.remove("created").is_some()); + } + assert_eq!( + json!(updates), + json!([ + {"id": "case-1", "tags": ["reviewed", "verified"], "_merge_paths": [["tags"]]}, + {"id": "case-2", "tags": [], "expected": "gold", "_merge_paths": [["tags"]]}, + {"id": "case-3", "expected": "gold"}, + {"id": "case-4"} + ]) + ); + + let inserted = records[0].to_upload_row("dataset_1", false); + assert!(!inserted.contains_key("_merge_paths")); + assert_eq!(inserted.get("tags"), Some(&json!(["reviewed", "verified"]))); + } + + #[test] + fn load_refresh_records_rejects_duplicate_tags() { + let err = load_refresh_records( + None, + Some(r#"[{"id":"case-1","tags":[]},{"id":"case-2","tags":["smoke","smoke"]}]"#), + "id", + ) + .expect_err("update should reject duplicate tags"); + assert_eq!( + err.to_string(), + "dataset record 2 tags must not contain duplicates" + ); + } + + #[test] + fn load_refresh_records_rejects_null_tags() { + let err = load_refresh_records(None, Some(r#"[{"id":"case-1","tags":null}]"#), "id") + .expect_err("update should require an array when tags are provided"); + assert_eq!( + err.to_string(), + "dataset record 1 tags must be an array of strings" + ); + } + #[test] fn prepare_records_rejects_duplicate_ids() { let first = serde_json::from_value(serde_json::json!({"id": "dup"})).expect("map"); @@ -656,21 +740,6 @@ mod tests { assert!(row.get("_is_merge").is_none()); } - #[test] - fn to_upload_row_marks_merge_rows() { - let record = PreparedDatasetRecord { - id: "case-1".to_string(), - input: None, - expected: None, - metadata: None, - tags: None, - origin: None, - }; - - let row = record.to_upload_row("dataset_1", true); - assert_eq!(row.get("_is_merge"), Some(&Value::Bool(true))); - } - #[test] fn prepare_records_rejects_system_fields() { let record = serde_json::from_value(serde_json::json!({