From 1b15f4a2e0195f22c2e61bc0cae06c12b84d4342 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 05:02:53 -0600 Subject: [PATCH 1/3] feat(atlas): record chunk source occurrences (#3125) --- .../crates/atlas-core/src/aggregate.rs | 54 ++++++++- .../crates/atlas-core/tests/aggregate.rs | 104 ++++++++++++++++++ 2 files changed, 153 insertions(+), 5 deletions(-) diff --git a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs index d1dde6d5d2..89f96958e2 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs @@ -100,9 +100,13 @@ pub struct PromoteReport { struct StagedChunk { item_id: i64, item_source: Option, + observed_at: String, item_sensitivity: String, text: String, content_hash: String, + /// Byte offsets in the original staged item, not the embed-time + /// piece. These are accumulated in staging chunk order below. + span_start: i64, /// 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 @@ -142,7 +146,7 @@ fn read_staged_chunks(db_path: &Path, unit_id: &str) -> Result> } let mut stmt = conn .prepare( - "SELECT i.id, i.source, i.sensitivity, c.text, c.content_hash, c.idx \ + "SELECT i.id, i.source, i.created_at, 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", ) @@ -153,19 +157,26 @@ fn read_staged_chunks(db_path: &Path, unit_id: &str) -> Result> 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)?, + observed_at: r.get(2)?, + item_sensitivity: r.get(3)?, + text: r.get(4)?, + content_hash: r.get(5)?, effective_sensitivity: None, + span_start: 0, }, - r.get::<_, i64>(5)?, + r.get::<_, i64>(6)?, )) }) .map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?; let mut out = Vec::new(); + let mut item_offsets = std::collections::HashMap::::new(); for row in rows { let (mut chunk, idx) = row.map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?; + chunk.span_start = *item_offsets.entry(chunk.item_id).or_default(); + *item_offsets + .get_mut(&chunk.item_id) + .expect("inserted above") += chunk.text.len() as i64; 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. @@ -218,6 +229,7 @@ fn next_shard_part(shard_dir: &Path, tier: Tier, topic: &str) -> Result { /// the embed-time context split. struct ShardChunk { item_source: Option, + observed_at: String, item_sensitivity: String, /// The staged chunk's persisted effective sensitivity (#12628), /// inherited by every embed-time piece of that chunk: pieces are @@ -225,6 +237,8 @@ struct ShardChunk { /// boundary the chunk was cut on and keep its classification. effective_sensitivity: Option, chunk_idx: i64, + span_start: i64, + span_end: i64, text: String, content_hash: String, } @@ -407,6 +421,7 @@ pub fn embed_unit_into_shard( // text), so a repeat gets a hash derived from its position (#10836). let mut used_hashes: std::collections::HashSet = std::collections::HashSet::new(); for c in &chunks { + let mut piece_offset = c.span_start; for piece in split_for_embed(&c.text, embedder)? { let ordinal = item_piece_ordinals.entry(c.item_id).or_insert(0); let chunk_idx = *ordinal; @@ -419,12 +434,16 @@ pub fn embed_unit_into_shard( let content_hash = unique_piece_hash(&mut used_hashes, text_hash, c.item_id, chunk_idx); pieces.push(ShardChunk { item_source: c.item_source.clone(), + observed_at: c.observed_at.clone(), item_sensitivity: c.item_sensitivity.clone(), effective_sensitivity: c.effective_sensitivity, chunk_idx, + span_start: piece_offset, + span_end: piece_offset + piece.len() as i64, content_hash, text: piece, }); + piece_offset = pieces.last().expect("piece just pushed").span_end; } } // Embed each distinct text once (#12628): a document vector is a @@ -486,6 +505,12 @@ pub fn embed_unit_into_shard( chunk_idx INTEGER, text TEXT NOT NULL, content_hash TEXT UNIQUE NOT NULL, \ sensitivity TEXT); \ CREATE TABLE {DEFAULT_VEC_TABLE} (chunk_id INTEGER PRIMARY KEY, vec BLOB NOT NULL); \ + CREATE TABLE chunk_occurrences ( \ + shard_chunk_id INTEGER NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, \ + canonical_hash TEXT NOT NULL, source TEXT NOT NULL, \ + span_start INTEGER NOT NULL, span_end INTEGER NOT NULL, observed_at TEXT NOT NULL, \ + PRIMARY KEY (shard_chunk_id, source, span_start)); \ + CREATE INDEX chunk_occurrences_hash ON chunk_occurrences (canonical_hash); \ CREATE TABLE atlas_manifest (\"key\" TEXT PRIMARY KEY, value TEXT);" )) .map_err(|e| Error::backend(format!("aggregator: shard schema: {e}")))?; @@ -520,6 +545,25 @@ pub fn embed_unit_into_shard( params![id, vec_blob(v)], ) .map_err(|e| Error::backend(format!("aggregator: shard vector {id}: {e}")))?; + let source = c + .item_source + .as_deref() + .map(str::to_owned) + .unwrap_or_else(|| format!("unit:{unit_id}")); + conn.execute( + "INSERT INTO chunk_occurrences \ + (shard_chunk_id, canonical_hash, source, span_start, span_end, observed_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + id, + sha256_hex(&c.text), + source, + c.span_start, + c.span_end, + c.observed_at + ], + ) + .map_err(|e| Error::backend(format!("aggregator: shard occurrence {id}: {e}")))?; } let manifest: [(&str, String); 9] = [ ("shard", shard_name.clone()), diff --git a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs index 6193439f6a..46ae107c51 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs @@ -264,6 +264,25 @@ fn promotion_splits_a_chunk_that_exceeds_the_model_context() { "piece fits: {piece:?}" ); } + let spans = conn + .prepare("SELECT span_start, span_end FROM chunk_occurrences ORDER BY shard_chunk_id") + .unwrap() + .query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?))) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!( + spans.len(), + rows.len(), + "each split piece has an occurrence" + ); + let mut offset = 0; + for ((start, end), piece) in spans.iter().zip(&rows) { + assert_eq!(*start, offset, "source spans are contiguous"); + assert_eq!(*end - *start, piece.len() as i64, "span covers exact bytes"); + offset = *end; + } + assert_eq!(offset, text.len() as i64, "spans cover the original item"); } #[test] @@ -332,3 +351,88 @@ fn promotion_keeps_pieces_and_items_with_identical_text() { assert_eq!(joined, text); } } + +#[test] +fn promotion_records_chunk_occurrences_for_identical_text() { + // #3125 rule 3: every chunk records every place it was found. + // Two items staging byte-identical text must promote to two + // shard chunks with distinct shard-unique content_hashes AND + // one occurrence row each sharing the canonical text hash, so + // the duplication link is recorded instead of silently lost. + // Oracle: SHA-256 of the staged text (content identity); row + // count and shared canonical hash are the acceptance signal. + let dir = temp_dir("occurrences"); + let registry = Registry::open(&dir.join("registry.db")).unwrap(); + let db = dir.join("unit.db"); + registry + .provision(&db, "task-occ", "repo-worker-code", Tier::Internal, NOW) + .unwrap(); + let text = "dns shared block\n"; + for path in ["infra/dns/a.yaml", "infra/dns/b.yaml"] { + let entry = ArtifactEntry { + kind: "config".into(), + repo: "developing-today/code".into(), + path: path.into(), + commit_sha: "abc".into(), + language: "yaml".into(), + sensitivity: Tier::Internal, + text: text.into(), + }; + stage_artifact_in_db(&db, "task-occ", &entry, NOW).unwrap(); + } + + let shard_dir = dir.join("shards"); + let report = embed_unit_into_shard( + ®istry, + "task-occ", + &shard_dir, + "codeconfig", + &KeywordEmbedder, + NOW, + ) + .unwrap(); + assert_eq!(report.chunks, 2, "both occurrences kept as chunks"); + + let conn = rusqlite::Connection::open(&report.shard_path).unwrap(); + let mut stmt = conn + .prepare( + "SELECT shard_chunk_id, canonical_hash, source, span_start, span_end, observed_at \ + FROM chunk_occurrences ORDER BY shard_chunk_id", + ) + .unwrap(); + let rows = stmt + .query_map([], |r| { + Ok(( + r.get::<_, i64>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + r.get::<_, i64>(3)?, + r.get::<_, i64>(4)?, + r.get::<_, String>(5)?, + )) + }) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(rows.len(), 2, "one occurrence row per chunk"); + assert_eq!(rows[0].0, 1); + assert_eq!(rows[1].0, 2); + assert_eq!( + rows[0].1, rows[1].1, + "identical texts share the canonical hash" + ); + assert_ne!(rows[0].2, rows[1].2, "occurrences record distinct sources"); + for row in &rows { + assert_eq!((row.3, row.4), (0, text.len() as i64)); + assert_eq!(row.5, NOW, "observed_at is the staged observation time"); + } + + // The shard-unique content_hashes differ (UNIQUE constraint), + // but the canonical hashes agree with SHA-256 of the text. + use sha2::{Digest, Sha256}; + let want: String = Sha256::digest(text.as_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + assert_eq!(rows[0].1, want, "canonical hash is SHA-256 of the text"); +} From aad8595d01bce6265255f47ea106f5bea3aa04cf Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:48:56 -0600 Subject: [PATCH 2/3] test(atlas): property-check occurrence spans --- .../crates/atlas-core/tests/aggregate.rs | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) diff --git a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs index 46ae107c51..b53dd3fa6d 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs @@ -13,6 +13,7 @@ use atlas_core::filters::Filters; use atlas_core::shards::scan::{FanoutQuery, fanout_scan}; use atlas_core::shards::{Tier, TierCeiling, open_from_spec}; use atlas_core::stage::{ArtifactEntry, Registry, UnitState, stage_artifact_in_db}; +use proptest::prelude::*; const NOW: &str = "2026-11-16T00:00:00Z"; @@ -436,3 +437,119 @@ fn promotion_records_chunk_occurrences_for_identical_text() { .collect(); assert_eq!(rows[0].1, want, "canonical hash is SHA-256 of the text"); } + +/// Oracle: every stored occurrence span selects exactly the persisted +/// chunk bytes from its source item's original UTF-8 text, and the +/// ordered spans form a gap-free, overlap-free partition of each item. +/// Generated documents contain multibyte characters, line boundaries, +/// multiple source items, and enough tokens to exercise embed-time splits. +proptest! { + #![proptest_config(ProptestConfig::with_cases(32))] + + #[test] + fn promotion_occurrence_spans_partition_generated_utf8_sources( + documents in prop::collection::vec( + prop::collection::vec( + prop::collection::vec( + prop_oneof![Just('a'), Just('é'), Just('🦀'), Just('β'), Just(' '), Just('\t')], + 1..16, + ), + 6..14, + ), + 2..5, + ) + ) { + struct FourTokenEmbedder; + impl DocEmbedder for FourTokenEmbedder { + fn embed_doc(&self, _text: &str) -> Result> { + Ok(vec![1.0, 0.0]) + } + + fn token_count(&self, text: &str) -> Option { + Some(text.split_whitespace().count()) + } + + fn max_input_tokens(&self) -> usize { + 4 + } + } + + let originals: Vec = documents + .iter() + .map(|lines| { + lines + .iter() + .map(|line| line.iter().collect::()) + .collect::>() + .join("\n") + + "\n" + }) + .collect(); + let dir = temp_dir("property-spans"); + let registry = Registry::open(&dir.join("registry.db")).unwrap(); + let db = dir.join("unit.db"); + registry.provision(&db, "task-property", "repo-worker-code", Tier::Internal, NOW).unwrap(); + + let mut expected = std::collections::BTreeMap::>::new(); + for (index, text) in originals.iter().enumerate() { + let path = format!("generated/source-{index}.txt"); + let source = format!("developing-today/code:{path}@abc"); + expected.insert(source, text.as_bytes().to_vec()); + let entry = ArtifactEntry { + kind: "prose".into(), + repo: "developing-today/code".into(), + path, + commit_sha: "abc".into(), + language: "txt".into(), + sensitivity: Tier::Internal, + text: text.clone(), + }; + stage_artifact_in_db(&db, "task-property", &entry, NOW).unwrap(); + } + + let report = embed_unit_into_shard( + ®istry, + "task-property", + &dir.join("shards"), + "property", + &FourTokenEmbedder, + NOW, + ).unwrap(); + let conn = rusqlite::Connection::open(&report.shard_path).unwrap(); + let mut stmt = conn.prepare( + "SELECT o.source, o.span_start, o.span_end, c.text \ + FROM chunk_occurrences o JOIN chunks c ON c.id = o.shard_chunk_id \ + ORDER BY o.source, o.span_start, o.shard_chunk_id", + ).unwrap(); + let rows = stmt.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, i64>(1)?, + row.get::<_, i64>(2)?, + row.get::<_, String>(3)?, + )) + }).unwrap().collect::, _>>().unwrap(); + + let mut grouped = std::collections::BTreeMap::>::new(); + for (source, start, end, chunk) in rows { + grouped.entry(source).or_default().push((start, end, chunk)); + } + prop_assert_eq!(grouped.len(), expected.len(), "each source has occurrence rows"); + for (source, original) in &expected { + let spans = grouped.get(source).expect("every staged source is registered"); + let mut cursor = 0usize; + for (start, end, chunk) in spans { + prop_assert_eq!(*start as usize, cursor, "source spans have no gaps or overlaps"); + let end = *end as usize; + prop_assert!(end <= original.len(), "span ends within source bytes"); + prop_assert_eq!( + &original[cursor..end], + chunk.as_bytes(), + "occurrence selects the exact persisted UTF-8 chunk bytes", + ); + cursor = end; + } + prop_assert_eq!(cursor, original.len(), "spans cover all source bytes"); + } + } +} From 2bcc4a9f69d849bde53aba86fd4e284c11ab494f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:56:23 -0600 Subject: [PATCH 3/3] test(atlas): remove macro doc warning --- pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs index b53dd3fa6d..39a65cc166 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs @@ -438,11 +438,11 @@ fn promotion_records_chunk_occurrences_for_identical_text() { assert_eq!(rows[0].1, want, "canonical hash is SHA-256 of the text"); } -/// Oracle: every stored occurrence span selects exactly the persisted -/// chunk bytes from its source item's original UTF-8 text, and the -/// ordered spans form a gap-free, overlap-free partition of each item. -/// Generated documents contain multibyte characters, line boundaries, -/// multiple source items, and enough tokens to exercise embed-time splits. +// Oracle: every stored occurrence span selects exactly the persisted +// chunk bytes from its source item's original UTF-8 text, and the +// ordered spans form a gap-free, overlap-free partition of each item. +// Generated documents contain multibyte characters, line boundaries, +// multiple source items, and enough tokens to exercise embed-time splits. proptest! { #![proptest_config(ProptestConfig::with_cases(32))]