From 5b4b259e1aed342ee13d1fa00a0eac4b5180f247 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 01:37:50 +0000 Subject: [PATCH] fix(atlas): keep identical split pieces from tripping the shard's UNIQUE hash The aggregator's shard table has `content_hash TEXT UNIQUE`. A chunk that repeats a block splits into identical pieces, and two items can stage the same file, so promotion failed with "UNIQUE constraint failed". The first piece with a given text keeps its plain hash; a repeat gets a hash derived from the text hash, item id and chunk index. Every piece is still kept, so each item's pieces still partition its text. Refs #10836 Co-Authored-By: Claude Opus 5.5 --- .../crates/atlas-core/src/aggregate.rs | 49 ++++++++++++-- .../crates/atlas-core/tests/aggregate.rs | 67 +++++++++++++++++++ 2 files changed, 109 insertions(+), 7 deletions(-) diff --git a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs index 52bea6dfab..c4aa6d5d32 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs @@ -179,6 +179,30 @@ fn sha256_hex(text: &str) -> String { digest.iter().map(|b| format!("{b:02x}")).collect() } +/// Claim a shard-unique content hash for one piece. The first piece +/// with a given text keeps the plain SHA-256 of that text; a later +/// piece with the same text gets a hash of the text hash, its item id +/// and its chunk index (plus a counter in the unlikely case that is +/// taken too), so the shard insert never trips the UNIQUE constraint. +fn unique_piece_hash( + used: &mut std::collections::HashSet, + text_hash: String, + item_id: i64, + chunk_idx: i64, +) -> String { + if used.insert(text_hash.clone()) { + return text_hash; + } + let mut attempt = 0u64; + loop { + let candidate = sha256_hex(&format!("{text_hash}\0{item_id}\0{chunk_idx}\0{attempt}")); + if used.insert(candidate.clone()) { + return candidate; + } + attempt += 1; + } +} + /// Split `text` into pieces the embedder accepts: each piece /// tokenizes to at most `embedder.max_input_tokens()`. Pieces break /// at line boundaries (lines keep their terminators, so the pieces @@ -196,7 +220,9 @@ fn split_for_embed(text: &str, embedder: &dyn DocEmbedder) -> Result } let count = |s: &str| -> Result { embedder.token_count(s).ok_or_else(|| { - Error::fatal("aggregator: embedder stopped returning token counts mid-split".to_string()) + Error::fatal( + "aggregator: embedder stopped returning token counts mid-split".to_string(), + ) }) }; let mut pieces: Vec = Vec::new(); @@ -232,7 +258,8 @@ fn split_for_embed(text: &str, embedder: &dyn DocEmbedder) -> Result } if lo == 0 { return Err(Error::fatal( - "aggregator: a single character exceeds the embedder token budget".to_string(), + "aggregator: a single character exceeds the embedder token budget" + .to_string(), )); } let split_at = rest @@ -317,20 +344,28 @@ pub fn embed_unit_into_shard( let mut pieces: Vec = Vec::new(); let mut item_piece_ordinals: std::collections::HashMap = std::collections::HashMap::new(); + // The shard's `content_hash` column is UNIQUE, but two pieces can + // carry the same text: a file that repeats a block splits into + // identical pieces, and two items can stage identical whole files. + // Every piece is kept (the pieces must still partition each item's + // 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 { 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; *ordinal += 1; + let text_hash = if piece == c.text { + c.content_hash.clone() + } else { + sha256_hex(&piece) + }; + 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(), item_sensitivity: c.item_sensitivity.clone(), chunk_idx, - content_hash: if piece == c.text { - c.content_hash.clone() - } else { - sha256_hex(&piece) - }, + content_hash, text: piece, }); } diff --git a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs index f3a5a7dd2f..6193439f6a 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs @@ -265,3 +265,70 @@ fn promotion_splits_a_chunk_that_exceeds_the_model_context() { ); } } + +#[test] +fn promotion_keeps_pieces_and_items_with_identical_text() { + // #10836: the shard's content_hash is UNIQUE, so a chunk that + // splits into identical pieces, or two items staging the same + // file, must still promote with every piece kept. + let dir = temp_dir("dup-pieces"); + let registry = Registry::open(&dir.join("registry.db")).unwrap(); + let db = dir.join("unit.db"); + registry + .provision(&db, "task-dup", "repo-worker-code", Tier::Internal, NOW) + .unwrap(); + let text = "dns alpha beta\ndns alpha beta\ndns alpha beta\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-dup", &entry, NOW).unwrap(); + } + + let shard_dir = dir.join("shards"); + let report = embed_unit_into_shard( + ®istry, + "task-dup", + &shard_dir, + "codeconfig", + &WordEmbedder, + NOW, + ) + .unwrap(); + assert_eq!(report.chunks, 6, "three pieces per item, none dropped"); + + let conn = rusqlite::Connection::open(&report.shard_path).unwrap(); + let mut stmt = conn + .prepare("SELECT message_id, text, content_hash FROM chunks ORDER BY id") + .unwrap(); + let rows = stmt + .query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + )) + }) + .unwrap() + .collect::, _>>() + .unwrap(); + let hashes: std::collections::HashSet<&str> = rows.iter().map(|r| r.2.as_str()).collect(); + assert_eq!(hashes.len(), rows.len(), "every content_hash is unique"); + let mut by_source: std::collections::BTreeMap<&str, String> = std::collections::BTreeMap::new(); + for (source, piece, _) in &rows { + by_source + .entry(source.as_str()) + .or_default() + .push_str(piece); + } + assert_eq!(by_source.len(), 2, "both items keep their pieces"); + for joined in by_source.values() { + assert_eq!(joined, text); + } +}