Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 49 additions & 5 deletions pkgs/atlas-search/crates/atlas-core/src/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,13 @@ pub struct PromoteReport {
struct StagedChunk {
item_id: i64,
item_source: Option<String>,
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
Expand Down Expand Up @@ -142,7 +146,7 @@ fn read_staged_chunks(db_path: &Path, unit_id: &str) -> Result<Vec<StagedChunk>>
}
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",
)
Expand All @@ -153,19 +157,26 @@ fn read_staged_chunks(db_path: &Path, unit_id: &str) -> Result<Vec<StagedChunk>>
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::<i64, i64>::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.
Expand Down Expand Up @@ -218,13 +229,16 @@ fn next_shard_part(shard_dir: &Path, tier: Tier, topic: &str) -> Result<u32> {
/// the embed-time context split.
struct ShardChunk {
item_source: Option<String>,
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
/// split *within* one staged chunk, so they never cross the
/// boundary the chunk was cut on and keep its classification.
effective_sensitivity: Option<Sensitivity>,
chunk_idx: i64,
span_start: i64,
span_end: i64,
text: String,
content_hash: String,
}
Expand Down Expand Up @@ -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<String> = 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;
Expand All @@ -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
Expand Down Expand Up @@ -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}")))?;
Expand Down Expand Up @@ -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()),
Expand Down
221 changes: 221 additions & 0 deletions pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -264,6 +265,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::<std::result::Result<Vec<_>, _>>()
.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");
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}

#[test]
Expand Down Expand Up @@ -332,3 +352,204 @@ 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(
&registry,
"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::<std::result::Result<Vec<_>, _>>()
.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");
}

// 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<Vec<f32>> {
Ok(vec![1.0, 0.0])
}

fn token_count(&self, text: &str) -> Option<usize> {
Some(text.split_whitespace().count())
}

fn max_input_tokens(&self) -> usize {
4
}
}

let originals: Vec<String> = documents
.iter()
.map(|lines| {
lines
.iter()
.map(|line| line.iter().collect::<String>())
.collect::<Vec<_>>()
.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::<String, Vec<u8>>::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(
&registry,
"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::<std::result::Result<Vec<_>, _>>().unwrap();

let mut grouped = std::collections::BTreeMap::<String, Vec<(i64, i64, String)>>::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");
}
}
}