From ac03c70ca885d92bda1d55191fb0de20d98036a2 Mon Sep 17 00:00:00 2001 From: felix Date: Sun, 22 Nov 2026 17:07:27 +0000 Subject: [PATCH] feat(atlas): wire boundary-safe chunks into staging and promotion (#12628) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Staging: stage_classified_artifact composes a producer's declared classification segments through split_by_boundaries into boundary-safe chunks_raw, and persists one #12408 classification record per chunk in the item meta — exact source offsets (record extras start/end) and effective sensitivity, read back fail-closed by chunk_classifications. Oversized boundary chunks sub-split at line boundaries inside the chunk only. atlas-stage ingest gains --segments for the declared segments JSON. Promotion: embed_unit_into_shard resolves each staged chunk's persisted effective sensitivity and writes it as the shard chunk's sensitivity (a chunk missing from a classified item fails closed to secret-bearing; legacy items keep the item-tier behaviour). Embed-time context pieces inherit their chunk's classification, and each distinct piece text is embedded once per run, so unchanged chunks keep the one computed vector. Refs #12403. Segment declaration stays with producers (the classifier / boundary detector); this slice is the staging and promotion wiring the splitter PR left open. --- .../crates/atlas-core/src/aggregate.rs | 119 +++- .../crates/atlas-core/src/boundary.rs | 12 +- .../atlas-search/crates/atlas-core/src/lib.rs | 6 +- .../crates/atlas-core/src/stage.rs | 265 ++++++++ .../atlas-core/tests/boundary_wiring.rs | 607 ++++++++++++++++++ .../atlas-search/src/bin/atlas-stage.rs | 89 ++- 6 files changed, 1068 insertions(+), 30 deletions(-) create mode 100644 pkgs/atlas-search/crates/atlas-core/tests/boundary_wiring.rs diff --git a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs index 03a38ef0dc..d1dde6d5d2 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs @@ -19,7 +19,11 @@ //! pipeline's own contract is that the embedder only ever sees //! in-context inputs, and atlas-embed refuses longer ones. The //! pieces partition the chunk text exactly and become separate -//! shard chunks under the same source pointer, in order. +//! shard chunks under the same source pointer, in order. Pieces +//! split within one staged chunk, so a piece never crosses the +//! classification boundary its chunk was cut on (#12628), and +//! each distinct piece text is embedded once per run: identical +//! texts share the one computed vector. //! 3. Write one new local core scan shard in `shard_dir` — //! `atlas-core---.db` carrying exactly the shard //! schema shard discovery and the fan-out scan read (`chunks`, the @@ -27,7 +31,9 @@ //! promoted entries are searchable by the existing fan-out with no //! new read path. The shard's tier is the unit's recorded //! sensitivity; each chunk's `sensitivity` is written in the scan -//! vocabulary (see [`tier_sensitivity_name`]). +//! vocabulary (see [`tier_sensitivity_name`]) — for an item staged +//! with classification records (#12628), the chunk's own persisted +//! effective sensitivity; otherwise its item's tier. //! 4. Stamp the unit DB's `atlas_manifest` `embedding_model` with the //! mandated model — the provenance record [`Registry::promote`]'s //! M6 gate (#7648) reads. Stamping adds the manifest table to the @@ -58,8 +64,9 @@ use rusqlite::{Connection, params}; use crate::embed::DocEmbedder; use crate::error::{Error, Result}; +use crate::filters::Sensitivity; use crate::shards::{EMBEDDING_MODEL_ID, Tier}; -use crate::stage::{Registry, UnitState}; +use crate::stage::{Registry, UnitState, chunk_classifications}; use crate::types::DEFAULT_VEC_TABLE; /// The scan-vocabulary sensitivity name a chunk of this tier carries @@ -96,6 +103,13 @@ struct StagedChunk { item_sensitivity: String, text: String, content_hash: String, + /// The chunk's persisted effective sensitivity (#12628), for + /// items staged with classification records: `Some` whenever the + /// item carries records — a chunk whose record is missing from a + /// classified item resolves to `secret-bearing` here, never to + /// the item's tier — and `None` for legacy items staged without + /// records, whose chunks keep the item-tier behaviour. + effective_sensitivity: Option, } /// Read one unit's staged chunks in staging order (item id, then @@ -107,29 +121,64 @@ fn read_staged_chunks(db_path: &Path, unit_id: &str) -> Result> db_path.display() )) })?; + // The unit's per-item classification records, resolved once per + // item: item id -> (records present?, per-chunk classifications). + let mut classifications: std::collections::HashMap< + i64, + Option>, + > = std::collections::HashMap::new(); + { + let mut stmt = conn + .prepare("SELECT id FROM items WHERE unit_id = ?1") + .map_err(|e| Error::backend(format!("aggregator: reading staged items: {e}")))?; + let ids = stmt + .query_map(params![unit_id], |r| r.get::<_, i64>(0)) + .map_err(|e| Error::backend(format!("aggregator: reading staged items: {e}")))?; + for id in ids { + let id = + id.map_err(|e| Error::backend(format!("aggregator: reading staged items: {e}")))?; + classifications.insert(id, chunk_classifications(&conn, id)?); + } + } let mut stmt = conn .prepare( - "SELECT i.id, i.source, i.sensitivity, c.text, c.content_hash \ + "SELECT i.id, i.source, i.sensitivity, c.text, c.content_hash, c.idx \ FROM chunks_raw c JOIN items i ON i.id = c.item_id \ WHERE i.unit_id = ?1 ORDER BY i.id, c.idx", ) .map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?; let rows = stmt .query_map(params![unit_id], |r| { - Ok(StagedChunk { - item_id: r.get(0)?, - item_source: r.get(1)?, - item_sensitivity: r.get(2)?, - text: r.get(3)?, - content_hash: r.get(4)?, - }) + Ok(( + StagedChunk { + item_id: r.get(0)?, + item_source: r.get(1)?, + item_sensitivity: r.get(2)?, + text: r.get(3)?, + content_hash: r.get(4)?, + effective_sensitivity: None, + }, + r.get::<_, i64>(5)?, + )) }) .map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?; let mut out = Vec::new(); for row in rows { - out.push( - row.map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?, - ); + let (mut chunk, idx) = + row.map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?; + chunk.effective_sensitivity = match classifications.get(&chunk.item_id) { + // Classified item: the chunk's own record governs; a + // chunk with no record in a classified item fails closed. + Some(Some(records)) => Some( + records + .get(idx as usize) + .map(|record| record.sensitivity) + .unwrap_or(Sensitivity::SecretBearing), + ), + // Legacy item (or item not seen above): no records. + _ => None, + }; + out.push(chunk); } Ok(out) } @@ -170,6 +219,11 @@ fn next_shard_part(shard_dir: &Path, tier: Tier, topic: &str) -> Result { struct ShardChunk { item_source: Option, item_sensitivity: String, + /// The staged chunk's persisted effective sensitivity (#12628), + /// inherited by every embed-time piece of that chunk: pieces are + /// split *within* one staged chunk, so they never cross the + /// boundary the chunk was cut on and keep its classification. + effective_sensitivity: Option, chunk_idx: i64, text: String, content_hash: String, @@ -366,15 +420,31 @@ pub fn embed_unit_into_shard( pieces.push(ShardChunk { item_source: c.item_source.clone(), item_sensitivity: c.item_sensitivity.clone(), + effective_sensitivity: c.effective_sensitivity, chunk_idx, content_hash, text: piece, }); } } + // Embed each distinct text once (#12628): a document vector is a + // pure function of (text, model), and this run uses one model, + // so identical pieces — repeated blocks, identical items, and + // chunks a boundary revision left unchanged — share the single + // computed vector instead of being re-embedded. Only a text that + // actually changed is embedded anew. let mut vecs: Vec> = Vec::with_capacity(pieces.len()); + let mut vec_by_text: std::collections::HashMap> = + std::collections::HashMap::new(); for piece in &pieces { - vecs.push(embedder.embed_doc(&piece.text)?); + let key = sha256_hex(&piece.text); + if let Some(vec) = vec_by_text.get(&key) { + vecs.push(vec.clone()); + continue; + } + let vec = embedder.embed_doc(&piece.text)?; + vec_by_text.insert(key, vec.clone()); + vecs.push(vec); } let dims = vecs[0].len(); if dims == 0 || vecs.iter().any(|v| v.len() != dims) { @@ -423,12 +493,19 @@ pub fn embed_unit_into_shard( .map_err(|e| Error::backend(format!("aggregator: shard begin: {e}")))?; for (i, (c, v)) in pieces.iter().zip(vecs.iter()).enumerate() { let id = (i + 1) as i64; - // The chunk's sensitivity is its item's recorded tier, - // in scan vocabulary; an unparseable record falls back - // to the unit's tier rather than widening access. - let sens = Tier::parse(&c.item_sensitivity) - .map(tier_sensitivity_name) - .unwrap_or_else(|| tier_sensitivity_name(unit.sensitivity)); + // The chunk's sensitivity: for a classified item, its + // persisted effective sensitivity, whose name is already + // scan vocabulary (the fan-out filters chunk sensitivity + // against the Sensitivity ladder). Otherwise its item's + // recorded tier, in scan vocabulary; an unparseable + // record falls back to the unit's tier rather than + // widening access. + let sens = match c.effective_sensitivity { + Some(sensitivity) => sensitivity.name(), + None => Tier::parse(&c.item_sensitivity) + .map(tier_sensitivity_name) + .unwrap_or_else(|| tier_sensitivity_name(unit.sensitivity)), + }; let message_id = c .item_source .clone() diff --git a/pkgs/atlas-search/crates/atlas-core/src/boundary.rs b/pkgs/atlas-search/crates/atlas-core/src/boundary.rs index ada700d947..2f79d9a78e 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/boundary.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/boundary.rs @@ -21,10 +21,14 @@ //! other chunk keeps its exact byte range and text, so its //! classification and vector stay valid (design §3, #6038). //! -//! This is the splitting primitive only. Wiring declared boundaries -//! into staging (`stage`) and promotion (`aggregate`) is the next -//! slice; until then the staging path keeps its current behaviour -//! and this module is exercised by its own tests. +//! This module is the splitting primitive. Declared boundaries are +//! wired into staging by [`crate::stage::stage_classified_artifact`] +//! (boundary-safe `chunks_raw` plus one persisted classification +//! record per chunk) and into promotion by [`crate::aggregate`], +//! which writes each chunk's effective sensitivity into the shard +//! and embeds identical texts once (#12628). The legacy staging +//! path ([`crate::stage::stage_artifact`]) keeps its current +//! behaviour for producers that declare no segments. use crate::filters::Sensitivity; diff --git a/pkgs/atlas-search/crates/atlas-core/src/lib.rs b/pkgs/atlas-search/crates/atlas-core/src/lib.rs index 3892b61d15..0464d75314 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/lib.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/lib.rs @@ -112,8 +112,10 @@ pub use search::{ run_search_with_executor_traced, }; pub use stage::{ - REGISTRY_V1_DDL, Registry, STAGE_SCHEMA_VERSION, STAGE_V1_DDL, STAGE_V1_TABLES, StagingUnit, - UnitState, check_stage_schema, provision_staging_db, schema_version, + ChunkClassification, REGISTRY_V1_DDL, Registry, STAGE_SCHEMA_VERSION, STAGE_V1_DDL, + STAGE_V1_TABLES, StagingUnit, UnitState, check_stage_schema, chunk_classifications, + provision_staging_db, schema_version, stage_classified_artifact, + stage_classified_artifact_in_db, }; pub use trace::{JsonlTraceSink, TRACE_SCHEMA, TraceContext, TraceSink}; pub use trace_ingest::{ diff --git a/pkgs/atlas-search/crates/atlas-core/src/stage.rs b/pkgs/atlas-search/crates/atlas-core/src/stage.rs index f54ac67fca..5d26d33c3d 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/stage.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/stage.rs @@ -21,6 +21,14 @@ //! embedding entries (#1518): one `items` row plus its //! `chunks_raw`, carrying the confirmed definition's metadata //! (repo, path, commit SHA, kind, language, unit). +//! * [`stage_classified_artifact`] is the classified item writer +//! (#12628): the producer's declared source-native classification +//! segments are composed through the boundary splitter +//! ([`crate::boundary::split_by_boundaries`]) into boundary-safe +//! chunks, and one #12408 classification record per chunk — exact +//! source offsets and effective sensitivity — is persisted in the +//! item's `meta` for promotion to enforce +//! ([`chunk_classifications`]). //! * [`Registry::promote`] is the merge-on-close transition, gated on //! the embedding-model contract (#7648, M6 of the #6060 decision //! record): a unit is promoted only when its database's recorded @@ -43,7 +51,10 @@ use std::path::{Path, PathBuf}; use rusqlite::{Connection, OptionalExtension, params}; +use crate::boundary::{ClassificationSegment, split_by_boundaries}; +use crate::classification::{ClassificationProvenance, ClassificationRecord}; use crate::error::{Error, Result}; +use crate::filters::Sensitivity; use crate::shards::{EMBEDDING_MODEL_ID, Tier}; /// The staging schema version this build knows how to provision and @@ -398,6 +409,260 @@ pub fn stage_artifact_in_db( stage_artifact(&conn, unit_id, entry, now) } +/// One chunk's persisted classification, read back from a staged +/// item's per-embed records ([`stage_classified_artifact`]): the +/// chunk's exact byte range in the item's text, its effective +/// sensitivity, and whether the boundary/decision behind it was +/// uncertain (and therefore handled at `secret-bearing`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChunkClassification { + pub start: usize, + pub end: usize, + pub sensitivity: Sensitivity, + pub uncertain: bool, + pub embed_id: String, +} + +/// The provenance actor recorded on classification records written +/// by [`stage_classified_artifact`]. +pub const CLASSIFICATION_ACTOR: &str = "atlas-stage"; + +/// The decision method recorded on those records: the records are +/// the staging-time composition of the producer's declared segments +/// through the boundary splitter (#12403). +pub const CLASSIFICATION_METHOD: &str = "boundary-split"; + +/// Build the #12408 classification record for one staged chunk, as +/// JSON. The chunk's exact byte range and uncertainty ride as record +/// extras (`start` / `end` / `uncertain`), which +/// [`ClassificationRecord`] preserves verbatim, so the persisted +/// record carries offsets and effective sensitivity together. +fn classification_record_json( + source: &str, + idx: usize, + start: usize, + end: usize, + sensitivity: Sensitivity, + uncertain: bool, + now: &str, +) -> serde_json::Value { + let mut extras = serde_json::Map::new(); + extras.insert("start".into(), serde_json::json!(start)); + extras.insert("end".into(), serde_json::json!(end)); + extras.insert("uncertain".into(), serde_json::json!(uncertain)); + ClassificationRecord { + schema_version: 1, + embed_id: format!("{source}#chunk-{idx}"), + sensitivity, + disposition: None, + provenance: ClassificationProvenance { + actor: CLASSIFICATION_ACTOR.to_string(), + decided_at: now.to_string(), + method: CLASSIFICATION_METHOD.to_string(), + method_version: "1".to_string(), + config_version: "1".to_string(), + evidence_refs: vec![source.to_string()], + previous_decision_id: None, + extras: serde_json::Map::new(), + }, + extras, + } + .to_json() +} + +/// Read one persisted classification record back, failing closed: a +/// record that does not parse, or whose uncertainty flag is absent, +/// is `secret-bearing` and uncertain (the #12408 convention: an +/// unrecognized sensitivity already resolves to `secret-bearing` +/// inside [`ClassificationRecord::parse`]). +fn chunk_classification_from_json(value: &serde_json::Value) -> ChunkClassification { + let Ok(record) = ClassificationRecord::parse(value.clone()) else { + return ChunkClassification { + start: 0, + end: 0, + sensitivity: Sensitivity::SecretBearing, + uncertain: true, + embed_id: String::new(), + }; + }; + ChunkClassification { + start: record + .extras + .get("start") + .and_then(serde_json::Value::as_u64) + .unwrap_or(0) as usize, + end: record + .extras + .get("end") + .and_then(serde_json::Value::as_u64) + .unwrap_or(0) as usize, + sensitivity: record.sensitivity, + uncertain: record + .extras + .get("uncertain") + .and_then(serde_json::Value::as_bool) + .unwrap_or(true), + embed_id: record.embed_id, + } +} + +/// The persisted per-chunk classifications of one staged item, in +/// chunk order: `None` for an item staged without classification +/// (the legacy [`stage_artifact`] path — promotion falls back to the +/// item's recorded tier for those), `Some` for an item staged by +/// [`stage_classified_artifact`]. Malformed records fail closed per +/// record (see [`chunk_classification_from_json`]). +pub fn chunk_classifications( + conn: &Connection, + item_id: i64, +) -> Result>> { + let meta: Option = conn + .query_row( + "SELECT meta FROM items WHERE id = ?1", + params![item_id], + |r| r.get(0), + ) + .optional() + .map_err(|e| Error::backend(format!("staging: reading item {item_id} meta: {e}")))? + .flatten(); + let Some(meta) = meta else { + return Ok(None); + }; + let meta: serde_json::Value = serde_json::from_str(&meta) + .map_err(|e| Error::backend(format!("staging: item {item_id} meta is not JSON: {e}")))?; + let Some(records) = meta.get("classification").and_then(|v| v.as_array()) else { + return Ok(None); + }; + Ok(Some( + records.iter().map(chunk_classification_from_json).collect(), + )) +} + +/// Split one boundary chunk's byte range further at line +/// boundaries so no piece exceeds [`MAX_CHUNK_BYTES`]. Pieces stay +/// inside the chunk's range, so they inherit its classification and +/// can never cross a boundary; a single line over the ceiling stays +/// whole (no boundary exists inside it), as in +/// [`chunk_artifact_text`]. +fn split_range_at_lines(text: &str, start: usize, end: usize) -> Vec<(usize, usize)> { + let piece = &text[start..end]; + let mut out = Vec::new(); + let mut piece_start = 0usize; + let mut acc = 0usize; + for line in piece.split_inclusive('\n') { + if acc > 0 && acc + line.len() > MAX_CHUNK_BYTES { + out.push((start + piece_start, start + piece_start + acc)); + piece_start += acc; + acc = 0; + } + acc += line.len(); + } + if acc > 0 { + out.push((start + piece_start, start + piece_start + acc)); + } + out +} + +/// Stage one code/config artifact whose producer declared +/// source-native classification segments (#12403 wiring, #12628): +/// like [`stage_artifact`], but the `chunks_raw` chunks are the +/// boundary-safe chunks of [`split_by_boundaries`] over the declared +/// `segments` — no chunk crosses a declared boundary, and gaps, +/// overlaps and uncertain declarations fail closed to +/// `secret-bearing` chunks — and the item's `meta` carries one #12408 +/// classification record per chunk (see +/// [`classification_record_json`]) with the chunk's exact source +/// offsets and effective sensitivity. The item row's own +/// `sensitivity` keeps the [`ArtifactEntry`] semantics (the entry's +/// declared tier); the per-chunk records are the effective +/// classification promotion enforces. Segment *declaration* stays +/// with the producer (the classifier / boundary detector); staging +/// composes declarations into chunks and records. +pub fn stage_classified_artifact( + conn: &Connection, + unit_id: &str, + entry: &ArtifactEntry, + segments: &[ClassificationSegment], + now: &str, +) -> Result { + check_stage_schema(conn)?; + // Final chunk ranges: boundary chunks, sub-split at line + // boundaries only where one chunk exceeds the chunk ceiling. + let mut ranges: Vec<(usize, usize, Sensitivity, bool)> = Vec::new(); + for chunk in split_by_boundaries(&entry.text, segments) { + if chunk.end - chunk.start <= MAX_CHUNK_BYTES { + ranges.push((chunk.start, chunk.end, chunk.sensitivity, chunk.uncertain)); + } else { + for (s, e) in split_range_at_lines(&entry.text, chunk.start, chunk.end) { + ranges.push((s, e, chunk.sensitivity, chunk.uncertain)); + } + } + } + let source = artifact_source(entry); + let records: Vec = ranges + .iter() + .enumerate() + .map(|(idx, &(start, end, sensitivity, uncertain))| { + classification_record_json(&source, idx, start, end, sensitivity, uncertain, now) + }) + .collect(); + let meta = serde_json::json!({ + "repo": entry.repo, + "path": entry.path, + "commit_sha": entry.commit_sha, + "kind": entry.kind, + "language": entry.language, + "unit": "boundary", + "embedded_at": now, + "chunks": ranges.len(), + "classification": records, + }) + .to_string(); + conn.execute( + "INSERT INTO items (unit_id, kind, source, text, sensitivity, created_at, meta) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + unit_id, + entry.kind, + source, + entry.text, + entry.sensitivity.name(), + now, + meta, + ], + ) + .map_err(|e| Error::backend(format!("staging: inserting item for {}: {e}", entry.path)))?; + let item_id = conn.last_insert_rowid(); + for (idx, &(start, end, _, _)) in ranges.iter().enumerate() { + let chunk = &entry.text[start..end]; + conn.execute( + "INSERT INTO chunks_raw (item_id, idx, text, content_hash, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![item_id, idx as i64, chunk, sha256_hex(chunk), now], + ) + .map_err(|e| { + Error::backend(format!( + "staging: inserting chunk {idx} for {}: {e}", + entry.path + )) + })?; + } + Ok(item_id) +} + +/// [`stage_classified_artifact`] against a staging DB file: the +/// form the `atlas-stage ingest --segments` tool calls. +pub fn stage_classified_artifact_in_db( + db: &Path, + unit_id: &str, + entry: &ArtifactEntry, + segments: &[ClassificationSegment], + now: &str, +) -> Result { + let conn = open(db)?; + stage_classified_artifact(&conn, unit_id, entry, segments, now) +} + /// Read back the items staged in a v1 staging DB, optionally only /// one unit's, each with its chunk count. pub fn list_staged_items(conn: &Connection, unit_id: Option<&str>) -> Result> { diff --git a/pkgs/atlas-search/crates/atlas-core/tests/boundary_wiring.rs b/pkgs/atlas-search/crates/atlas-core/tests/boundary_wiring.rs new file mode 100644 index 0000000000..4dd142cdb9 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/tests/boundary_wiring.rs @@ -0,0 +1,607 @@ +//! Oracle tests for the #12628 wiring of boundary-safe chunks into +//! staging (`stage_classified_artifact`) and promotion +//! (`embed_unit_into_shard`): +//! +//! * staging composes a producer's declared classification segments +//! through `split_by_boundaries` — chunks never cross a declared +//! boundary, and gaps / overlaps / uncertain declarations fail +//! closed to `secret-bearing`; +//! * one #12408 classification record per chunk is persisted with +//! the chunk's exact source offsets and effective sensitivity; +//! * promotion writes each chunk's effective sensitivity into the +//! shard (not the item's blanket tier) and embeds each distinct +//! text once, so unchanged chunks keep their one vector. + +use std::cell::RefCell; +use std::path::{Path, PathBuf}; + +use atlas_core::aggregate::embed_unit_into_shard; +use atlas_core::boundary::ClassificationSegment; +use atlas_core::embed::DocEmbedder; +use atlas_core::error::Result; +use atlas_core::filters::{Filters, Sensitivity}; +use atlas_core::shards::scan::{FanoutQuery, fanout_scan}; +use atlas_core::shards::{Tier, TierCeiling, open_from_spec}; +use atlas_core::stage::{ + ArtifactEntry, ChunkClassification, Registry, UnitState, chunk_classifications, + stage_classified_artifact_in_db, +}; + +const NOW: &str = "2026-11-22T00:00:00Z"; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("atlas-wiring-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).expect("temp dir"); + d +} + +fn entry(path: &str, text: &str) -> ArtifactEntry { + ArtifactEntry { + kind: "prose".into(), + repo: "developing-today/code".into(), + path: path.into(), + commit_sha: "abc123".into(), + language: "md".into(), + sensitivity: Tier::Internal, + text: text.into(), + } +} + +fn provision(dir: &Path, unit: &str) -> (Registry, PathBuf) { + let registry = Registry::open(&dir.join("registry.db")).unwrap(); + let db = dir.join("unit.db"); + registry + .provision(&db, unit, "repo-worker", Tier::Internal, NOW) + .unwrap(); + (registry, db) +} + +/// The staged chunks of one item, in chunk order. +fn staged_chunks(db: &Path, item_id: i64) -> Vec { + let conn = rusqlite::Connection::open(db).unwrap(); + let mut stmt = conn + .prepare("SELECT text FROM chunks_raw WHERE item_id = ?1 ORDER BY idx") + .unwrap(); + let rows = stmt + .query_map([item_id], |r| r.get::<_, String>(0)) + .unwrap() + .collect::, _>>() + .unwrap(); + rows +} + +fn classifications(db: &Path, item_id: i64) -> Vec { + let conn = rusqlite::Connection::open(db).unwrap(); + chunk_classifications(&conn, item_id) + .unwrap() + .expect("classified item carries records") +} + +#[test] +fn staging_transcript_turns_become_boundary_chunks_with_records() { + let dir = temp_dir("turns"); + let (_registry, db) = provision(&dir, "unit-turns"); + let trip = "Trip: book flights for the offsite next week.\n"; + let deploy = "Deploy: roll out the new queue worker tonight.\n"; + let text = format!("{trip}{deploy}"); + let segments = [ + ClassificationSegment::certain(0, trip.len(), Sensitivity::Personal), + ClassificationSegment::certain(trip.len(), text.len(), Sensitivity::Shareable), + ]; + let item_id = stage_classified_artifact_in_db( + &db, + "unit-turns", + &entry("doc/chat.md", &text), + &segments, + NOW, + ) + .unwrap(); + + // Oracle: the chunks are exactly the two turns — no chunk + // carries text from the other turn. + assert_eq!(staged_chunks(&db, item_id), vec![trip, deploy]); + + // Oracle: one persisted record per chunk with exact offsets and + // effective sensitivity. + let records = classifications(&db, item_id); + assert_eq!(records.len(), 2); + assert_eq!( + (records[0].start, records[0].end, records[0].sensitivity), + (0, trip.len(), Sensitivity::Personal) + ); + assert_eq!( + (records[1].start, records[1].end, records[1].sensitivity), + (trip.len(), text.len(), Sensitivity::Shareable) + ); + assert!(!records[0].uncertain && !records[1].uncertain); + assert!( + records[0].embed_id.ends_with("doc/chat.md@abc123#chunk-0"), + "embed id names the source and chunk: {}", + records[0].embed_id + ); + assert!(records[1].embed_id.ends_with("#chunk-1")); +} + +#[test] +fn staging_embedded_secret_is_isolated_in_its_own_chunk() { + let dir = temp_dir("secret"); + let (_registry, db) = provision(&dir, "unit-secret"); + let before = "fn deploy() {\n let region = \"eu-west-1\";\n"; + let secret = " let token = \"AKIAIOSFODNN7EXAMPLE\";\n"; + let after = " start_server(region);\n}\n"; + let text = format!("{before}{secret}{after}"); + let secret_start = before.len(); + let secret_end = secret_start + secret.len(); + let segments = [ + ClassificationSegment::certain(0, secret_start, Sensitivity::Shareable), + ClassificationSegment::certain(secret_start, secret_end, Sensitivity::SecretBearing), + ClassificationSegment::certain(secret_end, text.len(), Sensitivity::Shareable), + ]; + let mut e = entry("src/deploy.rs", &text); + e.kind = "code".into(); + e.language = "rust".into(); + let item_id = stage_classified_artifact_in_db(&db, "unit-secret", &e, &segments, NOW).unwrap(); + + let chunks = staged_chunks(&db, item_id); + assert_eq!(chunks, vec![before, secret, after]); + // Oracle: the secret text appears in exactly one chunk — no + // overlap copies it into a neighbour. + let carriers = chunks + .iter() + .filter(|c| c.contains("AKIAIOSFODNN7EXAMPLE")) + .count(); + assert_eq!(carriers, 1); + assert_eq!(chunks.concat(), text, "chunks partition the source"); + + let records = classifications(&db, item_id); + let sensitivities: Vec = records.iter().map(|r| r.sensitivity).collect(); + assert_eq!( + sensitivities, + vec![ + Sensitivity::Shareable, + Sensitivity::SecretBearing, + Sensitivity::Shareable + ] + ); + assert_eq!( + (records[1].start, records[1].end), + (secret_start, secret_end) + ); +} + +#[test] +fn staging_code_and_log_units_align_to_declared_units() { + let dir = temp_dir("units"); + let (_registry, db) = provision(&dir, "unit-units"); + + // Code: one segment per declaration. + let code = "fn alpha() {}\nfn beta() {}\n"; + let segments = [ + ClassificationSegment::certain(0, 14, Sensitivity::Shareable), + ClassificationSegment::certain(14, code.len(), Sensitivity::Personal), + ]; + let mut e = entry("src/lib.rs", code); + e.kind = "code".into(); + let item_id = stage_classified_artifact_in_db(&db, "unit-units", &e, &segments, NOW).unwrap(); + assert_eq!( + staged_chunks(&db, item_id), + vec!["fn alpha() {}\n", "fn beta() {}\n"] + ); + + // Logs: one segment per record. + let logs = "2026-11-22T09:00:00Z INFO started\n2026-11-22T09:01:00Z ERROR boom\n"; + let first_len = "2026-11-22T09:00:00Z INFO started\n".len(); + let segments = [ + ClassificationSegment::certain(0, first_len, Sensitivity::Shareable), + ClassificationSegment::certain(first_len, logs.len(), Sensitivity::LocalOnly), + ]; + let item_id = stage_classified_artifact_in_db( + &db, + "unit-units", + &entry("logs/run.log", logs), + &segments, + NOW, + ) + .unwrap(); + let records = classifications(&db, item_id); + assert_eq!(records.len(), 2); + assert_eq!(records[1].sensitivity, Sensitivity::LocalOnly); + assert_eq!((records[1].start, records[1].end), (first_len, logs.len())); +} + +#[test] +fn staging_uncertain_segment_fails_closed() { + let dir = temp_dir("uncertain"); + let (_registry, db) = provision(&dir, "unit-uncertain"); + let text = "aaaaBBBBcccc"; + let segments = [ + ClassificationSegment::certain(0, 4, Sensitivity::Shareable), + ClassificationSegment::uncertain(4, 8, Sensitivity::Personal), + ClassificationSegment::certain(8, 12, Sensitivity::Shareable), + ]; + let item_id = stage_classified_artifact_in_db( + &db, + "unit-uncertain", + &entry("doc/x.md", text), + &segments, + NOW, + ) + .unwrap(); + let records = classifications(&db, item_id); + assert_eq!(records.len(), 3); + assert_eq!(records[0].sensitivity, Sensitivity::Shareable); + // Oracle: uncertain material is secret-bearing and marked + // uncertain — never joined to the less restricted neighbours. + assert_eq!(records[1].sensitivity, Sensitivity::SecretBearing); + assert!(records[1].uncertain); + assert_eq!(records[2].sensitivity, Sensitivity::Shareable); + assert_eq!(staged_chunks(&db, item_id).concat(), text); +} + +#[test] +fn staging_undeclared_gap_and_missing_segments_fail_closed() { + let dir = temp_dir("gap"); + let (_registry, db) = provision(&dir, "unit-gap"); + + // A gap between declared segments. + let text = "aaaa----bbbb"; + let segments = [ + ClassificationSegment::certain(0, 4, Sensitivity::Shareable), + ClassificationSegment::certain(8, 12, Sensitivity::Shareable), + ]; + let item_id = stage_classified_artifact_in_db( + &db, + "unit-gap", + &entry("doc/gap.md", text), + &segments, + NOW, + ) + .unwrap(); + let records = classifications(&db, item_id); + assert_eq!(records.len(), 3); + assert_eq!(records[1].sensitivity, Sensitivity::SecretBearing); + assert!(records[1].uncertain); + assert_eq!(&text[records[1].start..records[1].end], "----"); + + // No declarations at all: the whole artifact is one + // secret-bearing, uncertain chunk. + let item_id = stage_classified_artifact_in_db( + &db, + "unit-gap", + &entry("doc/none.md", "unclassified material"), + &[], + NOW, + ) + .unwrap(); + let records = classifications(&db, item_id); + assert_eq!(records.len(), 1); + assert_eq!(records[0].sensitivity, Sensitivity::SecretBearing); + assert!(records[0].uncertain); +} + +#[test] +fn staging_overlapping_declarations_fail_closed() { + let dir = temp_dir("overlap"); + let (_registry, db) = provision(&dir, "unit-overlap"); + let text = "abcdefgh"; + let segments = [ + ClassificationSegment::certain(0, 6, Sensitivity::Shareable), + ClassificationSegment::certain(4, 8, Sensitivity::Personal), + ]; + let item_id = stage_classified_artifact_in_db( + &db, + "unit-overlap", + &entry("doc/o.md", text), + &segments, + NOW, + ) + .unwrap(); + let records = classifications(&db, item_id); + // Oracle: only the contradicted overlap fails closed; the + // uncontested ranges keep their declared sensitivity. + let got: Vec<(usize, usize, Sensitivity, bool)> = records + .iter() + .map(|r| (r.start, r.end, r.sensitivity, r.uncertain)) + .collect(); + assert_eq!( + got, + vec![ + (0, 4, Sensitivity::Shareable, false), + (4, 6, Sensitivity::SecretBearing, true), + (6, 8, Sensitivity::Personal, false), + ] + ); +} + +#[test] +fn staging_boundary_revision_changes_only_affected_records() { + let dir = temp_dir("revision"); + let (_registry, db) = provision(&dir, "unit-revision"); + let text = "aaaabbbbcccc"; + let v1 = [ + ClassificationSegment::certain(0, 4, Sensitivity::Shareable), + ClassificationSegment::certain(4, 8, Sensitivity::Personal), + ClassificationSegment::certain(8, 12, Sensitivity::Shareable), + ]; + let first = + stage_classified_artifact_in_db(&db, "unit-revision", &entry("doc/r.md", text), &v1, NOW) + .unwrap(); + // Revise only the middle segment's decision. + let v2 = [ + ClassificationSegment::certain(0, 4, Sensitivity::Shareable), + ClassificationSegment::certain(4, 8, Sensitivity::LocalOnly), + ClassificationSegment::certain(8, 12, Sensitivity::Shareable), + ]; + let second = + stage_classified_artifact_in_db(&db, "unit-revision", &entry("doc/r.md", text), &v2, NOW) + .unwrap(); + + let before = classifications(&db, first); + let after = classifications(&db, second); + assert_eq!(before.len(), after.len()); + // Oracle: unaffected chunks' records are identical — same embed + // id, offsets and sensitivity, so their classifications (and + // vectors) stay valid; only the revised chunk's record changes, + // and only in its sensitivity. + assert_eq!(before[0], after[0]); + assert_eq!(before[2], after[2]); + assert_eq!(before[1].start, after[1].start); + assert_eq!(before[1].end, after[1].end); + assert_eq!(before[1].embed_id, after[1].embed_id); + assert_eq!(before[1].sensitivity, Sensitivity::Personal); + assert_eq!(after[1].sensitivity, Sensitivity::LocalOnly); +} + +/// A document embedder keyed on content: DNS text lands on the +/// first axis, everything else on the second (mirrors the +/// aggregator oracle tests). +struct KeywordEmbedder; + +impl DocEmbedder for KeywordEmbedder { + fn embed_doc(&self, text: &str) -> Result> { + if text.contains("dns") || text.contains("DNS") { + Ok(vec![1.0, 0.0, 0.0]) + } else { + Ok(vec![0.0, 1.0, 0.0]) + } + } +} + +#[test] +fn promotion_applies_per_chunk_effective_sensitivity() { + let dir = temp_dir("promote-sens"); + let (registry, db) = provision(&dir, "unit-promote-sens"); + let public = "dns zone config for example.internal\n"; + let secret = "dns token hunter2 do not share\n"; + let text = format!("{public}{secret}"); + let segments = [ + ClassificationSegment::certain(0, public.len(), Sensitivity::Shareable), + ClassificationSegment::certain(public.len(), text.len(), Sensitivity::SecretBearing), + ]; + stage_classified_artifact_in_db( + &db, + "unit-promote-sens", + &entry("infra/dns.yaml", &text), + &segments, + NOW, + ) + .unwrap(); + + let shard_dir = dir.join("shards"); + let report = embed_unit_into_shard( + ®istry, + "unit-promote-sens", + &shard_dir, + "codeconfig", + &KeywordEmbedder, + NOW, + ) + .unwrap(); + assert_eq!(report.chunks, 2); + assert_eq!( + registry.lookup("unit-promote-sens").unwrap().unwrap().state, + UnitState::Merged + ); + + // Oracle: the shard carries each chunk's own effective + // sensitivity — not the item's blanket internal tier + // ("personal"), which the legacy path would have written for + // both chunks. + let conn = rusqlite::Connection::open(&report.shard_path).unwrap(); + let mut stmt = conn + .prepare("SELECT text, sensitivity FROM chunks ORDER BY id") + .unwrap(); + let rows = stmt + .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!( + rows, + vec![ + (public.to_string(), "shareable".to_string()), + (secret.to_string(), "secret-bearing".to_string()), + ] + ); + + // Oracle: at a personal ceiling the fan-out serves the shareable + // chunk and withholds the secret-bearing one, even though both + // live in the same internal-tier shard. + let set = open_from_spec( + &format!("dir:{}", shard_dir.display()), + TierCeiling(Tier::Internal), + atlas_core::DEFAULT_VEC_TABLE, + ) + .unwrap(); + let filters = Filters::new(vec![], vec![], vec![], vec![], "personal", None, None).unwrap(); + let hits = fanout_scan( + &set, + &FanoutQuery { + qvec: &[1.0, 0.0, 0.0], + shard_top_k: 10, + global_top_k: 10, + filters: &filters, + topics: None, + ceiling: TierCeiling(Tier::Internal), + }, + ) + .unwrap() + .hits; + assert_eq!(hits.len(), 1, "only the shareable chunk is served"); + assert_eq!(hits[0].chunk_id, 1); +} + +/// A document embedder that counts its calls: the oracle for +/// "unchanged chunks are not re-embedded". Its vector is a pure +/// function of the text, like the production model's. +struct CountingEmbedder { + calls: RefCell, +} + +impl DocEmbedder for CountingEmbedder { + fn embed_doc(&self, text: &str) -> Result> { + *self.calls.borrow_mut() += 1; + Ok(vec![ + text.len() as f32, + text.bytes().filter(|b| *b == b'a').count() as f32, + 1.0, + ]) + } +} + +#[test] +fn promotion_preserves_unchanged_vectors_embeds_each_text_once() { + let dir = temp_dir("promote-dedup"); + let (registry, db) = provision(&dir, "unit-dedup"); + // Two items with identical text and identical declared segments + // (the same file staged twice), plus one distinct chunk: three + // distinct chunk texts across four chunks... two per item, the + // pair repeated. + let head = "alpha zone header\n"; + let tail = "omega zone footer\n"; + let text = format!("{head}{tail}"); + let segments = [ + ClassificationSegment::certain(0, head.len(), Sensitivity::Shareable), + ClassificationSegment::certain(head.len(), text.len(), Sensitivity::Personal), + ]; + for path in ["infra/a.yaml", "infra/b.yaml"] { + stage_classified_artifact_in_db(&db, "unit-dedup", &entry(path, &text), &segments, NOW) + .unwrap(); + } + + let embedder = CountingEmbedder { + calls: RefCell::new(0), + }; + let shard_dir = dir.join("shards"); + let report = embed_unit_into_shard( + ®istry, + "unit-dedup", + &shard_dir, + "codeconfig", + &embedder, + NOW, + ) + .unwrap(); + assert_eq!(report.chunks, 4, "every chunk is kept"); + // Oracle: only the two distinct texts were embedded — the + // repeated item's chunks kept the first computation's vectors. + assert_eq!(*embedder.calls.borrow(), 2); + + // Oracle: identical texts carry bit-identical vectors in the + // shard. + let conn = rusqlite::Connection::open(&report.shard_path).unwrap(); + let mut stmt = conn + .prepare(&format!( + "SELECT c.text, v.vec FROM chunks c JOIN {} v ON v.chunk_id = c.id \ + ORDER BY c.id", + atlas_core::DEFAULT_VEC_TABLE + )) + .unwrap(); + let rows = stmt + .query_map([], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, Vec>(1)?)) + }) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(rows.len(), 4); + assert_eq!(rows[0].0, rows[2].0); + assert_eq!(rows[0].1, rows[2].1, "same text, same vector bytes"); + assert_eq!(rows[1].1, rows[3].1); + assert_ne!(rows[0].1, rows[1].1); +} + +/// A document embedder whose token is a word, with a tiny context: +/// forces the aggregator's embed-time split at a readable scale +/// (mirrors the aggregator oracle tests). +struct WordEmbedder; + +impl DocEmbedder for WordEmbedder { + fn embed_doc(&self, text: &str) -> Result> { + if text.contains("dns") { + Ok(vec![1.0, 0.0]) + } else { + Ok(vec![0.0, 1.0]) + } + } + + fn token_count(&self, text: &str) -> Option { + Some(text.split_whitespace().count()) + } + + fn max_input_tokens(&self) -> usize { + 3 + } +} + +#[test] +fn promotion_embed_split_pieces_inherit_effective_sensitivity() { + let dir = temp_dir("promote-split"); + let (registry, db) = provision(&dir, "unit-promote-split"); + // One secret-bearing chunk of 8 word-tokens; the embedder's + // context is 3, so promotion must split it — the pieces stay + // within the chunk, so none may drop the classification. + let text = "alpha beta gamma delta\nepsilon zeta eta theta\n"; + let segments = [ClassificationSegment::certain( + 0, + text.len(), + Sensitivity::SecretBearing, + )]; + stage_classified_artifact_in_db( + &db, + "unit-promote-split", + &entry("doc/secret.md", text), + &segments, + NOW, + ) + .unwrap(); + + let shard_dir = dir.join("shards"); + let report = embed_unit_into_shard( + ®istry, + "unit-promote-split", + &shard_dir, + "codeconfig", + &WordEmbedder, + NOW, + ) + .unwrap(); + assert!(report.chunks >= 3, "split into pieces: {}", report.chunks); + + let conn = rusqlite::Connection::open(&report.shard_path).unwrap(); + let mut stmt = conn + .prepare("SELECT text, sensitivity FROM chunks ORDER BY id") + .unwrap(); + let rows = stmt + .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))) + .unwrap() + .collect::, _>>() + .unwrap(); + // Oracle: pieces partition the chunk exactly and every piece + // keeps the chunk's secret-bearing classification. + assert_eq!(rows.iter().map(|r| r.0.as_str()).collect::(), text); + for (_, sensitivity) in &rows { + assert_eq!(sensitivity, "secret-bearing"); + } +} diff --git a/pkgs/atlas-search/crates/atlas-search/src/bin/atlas-stage.rs b/pkgs/atlas-search/crates/atlas-search/src/bin/atlas-stage.rs index e7472da427..9f6587c4ab 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/bin/atlas-stage.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/bin/atlas-stage.rs @@ -13,9 +13,13 @@ //! in a lifecycle state (what the aggregator's poll reads). //! * `atlas-stage ingest --db --unit --repo //! --path

--file --commit [--kind config] -//! [--language yaml] [--sensitivity internal]` — stage one +//! [--language yaml] [--sensitivity internal] +//! [--segments ]` — stage one //! code/config artifact as an embedding entry (#1518): one //! `items` row plus its `chunks_raw` in the unit's staging DB. +//! With `--segments`, the artifact is staged classified (#12628): +//! boundary-safe chunks from the declared classification segments, +//! with one persisted classification record per chunk. //! * `atlas-stage items --db [--unit ]` — list the //! items staged in a unit's DB, with chunk counts. //! @@ -106,6 +110,15 @@ enum Command { /// Physical sensitivity level (public|internal|secret; default internal). #[arg(long, default_value = "internal")] sensitivity: String, + /// Optional JSON file declaring the artifact's source-native + /// classification segments (#12628): an array of + /// {"start": , "end": , "sensitivity": + /// shareable|personal|local-only|secret-bearing, + /// "certain": }. When given, the + /// artifact is staged classified: boundary-safe chunks plus + /// one persisted classification record per chunk. + #[arg(long)] + segments: Option, }, /// List the items staged in a unit's staging DB. Items { @@ -175,6 +188,62 @@ fn parse_state(s: &str) -> Result { UnitState::parse(s).ok_or_else(|| format!("unknown state {s:?} (want open|closing|merged)")) } +/// Load the declared classification segments for `ingest +/// --segments`: a JSON array of {"start", "end", "sensitivity", +/// "certain"?} objects over the artifact's byte offsets. Parsed +/// strictly — a missing or mistyped field, or an unknown sensitivity +/// name, is a usage error, never a silent default. +fn load_segments( + path: &PathBuf, +) -> Result, String> { + let raw = std::fs::read_to_string(path) + .map_err(|e| format!("reading segments {}: {e}", path.display()))?; + let value: serde_json::Value = serde_json::from_str(&raw) + .map_err(|e| format!("parsing segments {}: {e}", path.display()))?; + let array = value + .as_array() + .ok_or("segments file must be a JSON array of segment objects")?; + let mut out = Vec::with_capacity(array.len()); + for (i, entry) in array.iter().enumerate() { + let field = |name: &str| { + entry + .get(name) + .ok_or_else(|| format!("segments[{i}]: missing field {name:?}")) + }; + let start = field("start")? + .as_u64() + .ok_or_else(|| format!("segments[{i}]: \"start\" must be an unsigned integer"))? + as usize; + let end = field("end")? + .as_u64() + .ok_or_else(|| format!("segments[{i}]: \"end\" must be an unsigned integer"))? + as usize; + let sensitivity_name = field("sensitivity")? + .as_str() + .ok_or_else(|| format!("segments[{i}]: \"sensitivity\" must be a string"))?; + let sensitivity = atlas_core::filters::Sensitivity::from_name(sensitivity_name) + .ok_or_else(|| { + format!( + "segments[{i}]: unknown sensitivity {sensitivity_name:?} \ + (want shareable|personal|local-only|secret-bearing)" + ) + })?; + let certain = match entry.get("certain") { + None => true, + Some(v) => v + .as_bool() + .ok_or_else(|| format!("segments[{i}]: \"certain\" must be a boolean"))?, + }; + out.push(atlas_core::boundary::ClassificationSegment { + start, + end, + sensitivity, + certain, + }); + } + Ok(out) +} + fn run(cli: Cli) -> Result<(), String> { match cli.command { Command::Provision { @@ -212,6 +281,7 @@ fn run(cli: Cli) -> Result<(), String> { kind, language, sensitivity, + segments, } => { let sensitivity = parse_tier(&sensitivity)?; let text = std::fs::read_to_string(&file) @@ -233,8 +303,21 @@ fn run(cli: Cli) -> Result<(), String> { sensitivity, text, }; - let item_id = atlas_core::stage::stage_artifact_in_db(&db, &unit, &entry, &now_utc()) - .map_err(|e| e.to_string())?; + let item_id = match &segments { + Some(segments_path) => { + let declared = load_segments(segments_path)?; + atlas_core::stage::stage_classified_artifact_in_db( + &db, + &unit, + &entry, + &declared, + &now_utc(), + ) + .map_err(|e| e.to_string())? + } + None => atlas_core::stage::stage_artifact_in_db(&db, &unit, &entry, &now_utc()) + .map_err(|e| e.to_string())?, + }; println!( "{{\"item_id\":{item_id},\"unit\":{},\"source\":{}}}", json_str(&unit),