diff --git a/pkgs/atlas-search/crates/atlas-core/examples/retrieval_proof.rs b/pkgs/atlas-search/crates/atlas-core/examples/retrieval_proof.rs new file mode 100644 index 0000000000..a5841e5070 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/examples/retrieval_proof.rs @@ -0,0 +1,83 @@ +//! Live retrieval proof for task 17164 (manual example, not a CI +//! test): embed a semantic query with the production query +//! embedder, fan out over a local shard dir, and print the top +//! hits with their chunk text read back from the shard itself. +//! +//! Run on the laptop: +//! ATLAS_ORT_LIB= ATLAS_MODEL_DIR= \ +//! cargo run --release -p atlas-core --example retrieval_proof -- + +use std::path::PathBuf; + +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::{AtlasEmbedder, DEFAULT_VEC_TABLE, QueryEmbedder}; + +fn main() { + let args: Vec = std::env::args().collect(); + let shard_dir = args + .get(1) + .expect("usage: retrieval_proof "); + let query = args + .get(2) + .expect("usage: retrieval_proof "); + + let model_dir = std::env::var("ATLAS_MODEL_DIR").expect("ATLAS_MODEL_DIR"); + let ort_lib = std::env::var("ATLAS_ORT_LIB").expect("ATLAS_ORT_LIB"); + let emb = atlas_embed::Embedder::load(&PathBuf::from(model_dir), &PathBuf::from(ort_lib)) + .expect("embedder load"); + let embedder = AtlasEmbedder::new(emb); + let qvec = embedder.embed_query(query, 768).expect("embed query"); + println!("query: {query}"); + println!("query vector dims: {}", qvec.len()); + + let set = open_from_spec( + &format!("dir:{shard_dir}"), + TierCeiling(Tier::Internal), + DEFAULT_VEC_TABLE, + ) + .expect("discover shards"); + for s in set.shards() { + println!( + "shard: {} tier={} topic={} chunks={} model={}", + s.name, + s.tier.name(), + s.topic, + s.chunks, + s.embedding_model + ); + } + let filters = Filters::new(vec![], vec![], vec![], vec![], "personal", None, None).unwrap(); + let result = fanout_scan( + &set, + &FanoutQuery { + qvec: &qvec, + shard_top_k: 10, + global_top_k: 10, + filters: &filters, + topics: None, + ceiling: TierCeiling(Tier::Internal), + }, + ) + .expect("fanout scan"); + for hit in &result.hits { + println!( + "hit: chunk_id={} dist={:.6} shard={}", + hit.chunk_id, hit.dist, hit.shard + ); + // Read the chunk text back from the shard file itself. + let db = PathBuf::from(shard_dir).join(format!("{}.db", hit.shard)); + let conn = rusqlite::Connection::open(&db).expect("open shard"); + let (message_id, text): (String, String) = conn + .query_row( + "SELECT message_id, text FROM chunks WHERE id = ?1", + rusqlite::params![hit.chunk_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .expect("chunk row"); + let preview: String = text.chars().take(240).collect(); + println!(" source (message_id): {message_id}"); + println!(" text preview: {}", preview.replace('\n', " | ")); + } +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs index 2b7630c34f..52bea6dfab 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs @@ -11,7 +11,15 @@ //! the v1 schema invariant still holds at read time). //! 2. Embed every chunk document-side (prompt-free, the production //! corpus convention; see [`crate::embed::DocEmbedder`]) with the -//! mandated model identity ([`EMBEDDING_MODEL_ID`]). +//! mandated model identity ([`EMBEDDING_MODEL_ID`]). A staged +//! chunk that tokenizes past the model context (a whole-file +//! config unit can: infra/dns/dns_config.yaml is 10,413 tokens +//! against the 8,192 context) is split at embed time into +//! context-fitting pieces at line boundaries — the corpus +//! 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. //! 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 @@ -84,7 +92,6 @@ struct StagedChunk { item_id: i64, item_source: Option, item_sensitivity: String, - idx: i64, text: String, content_hash: String, } @@ -100,7 +107,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.idx, c.text, c.content_hash \ + "SELECT i.id, i.source, i.sensitivity, c.text, c.content_hash \ FROM chunks_raw c JOIN items i ON i.id = c.item_id \ WHERE i.unit_id = ?1 ORDER BY i.id, c.idx", ) @@ -111,9 +118,8 @@ fn read_staged_chunks(db_path: &Path, unit_id: &str) -> Result> item_id: r.get(0)?, item_source: r.get(1)?, item_sensitivity: r.get(2)?, - idx: r.get(3)?, - text: r.get(4)?, - content_hash: r.get(5)?, + text: r.get(3)?, + content_hash: r.get(4)?, }) }) .map_err(|e| Error::backend(format!("aggregator: reading staged chunks: {e}")))?; @@ -157,6 +163,101 @@ fn next_shard_part(shard_dir: &Path, tier: Tier, topic: &str) -> Result { Ok(next) } +/// One shard-bound chunk: a staged chunk, or one piece of it after +/// the embed-time context split. +struct ShardChunk { + item_source: Option, + item_sensitivity: String, + chunk_idx: i64, + text: String, + content_hash: String, +} + +fn sha256_hex(text: &str) -> String { + use sha2::{Digest, Sha256}; + let digest = Sha256::digest(text.as_bytes()); + digest.iter().map(|b| format!("{b:02x}")).collect() +} + +/// 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 +/// partition `text` exactly); a single line still over the limit is +/// split mid-line at the largest fitting char prefix. An embedder +/// that cannot count tokens gets the text whole — its own +/// `embed_doc` is then the only bound, as for fixture embedders. +fn split_for_embed(text: &str, embedder: &dyn DocEmbedder) -> Result> { + let Some(total) = embedder.token_count(text) else { + return Ok(vec![text.to_string()]); + }; + let budget = embedder.max_input_tokens(); + if total <= budget { + return Ok(vec![text.to_string()]); + } + let count = |s: &str| -> Result { + embedder.token_count(s).ok_or_else(|| { + Error::fatal("aggregator: embedder stopped returning token counts mid-split".to_string()) + }) + }; + let mut pieces: Vec = Vec::new(); + let mut cur = String::new(); + let mut cur_tokens = 0usize; + for line in text.split_inclusive('\n') { + let line_tokens = count(line)?; + if line_tokens > budget { + if !cur.is_empty() { + pieces.push(std::mem::take(&mut cur)); + cur_tokens = 0; + } + // Mid-line split: binary search the largest char-boundary + // prefix that fits (token count is monotone in prefix + // length for the model's BPE tokenizer). + let mut rest = line; + while !rest.is_empty() { + if count(rest)? <= budget { + cur_tokens = count(rest)?; + cur = rest.to_string(); + break; + } + let mut lo = 0usize; // chars known to fit + let mut hi = rest.chars().count(); // chars known not to fit + while lo + 1 < hi { + let mid = (lo + hi) / 2; + let prefix: String = rest.chars().take(mid).collect(); + if count(&prefix)? <= budget { + lo = mid; + } else { + hi = mid; + } + } + if lo == 0 { + return Err(Error::fatal( + "aggregator: a single character exceeds the embedder token budget".to_string(), + )); + } + let split_at = rest + .char_indices() + .nth(lo) + .map(|(b, _)| b) + .unwrap_or(rest.len()); + pieces.push(rest[..split_at].to_string()); + rest = &rest[split_at..]; + } + continue; + } + if cur_tokens + line_tokens > budget && !cur.is_empty() { + pieces.push(std::mem::take(&mut cur)); + cur_tokens = 0; + } + cur.push_str(line); + cur_tokens += line_tokens; + } + if !cur.is_empty() { + pieces.push(cur); + } + Ok(pieces) +} + fn vec_blob(v: &[f32]) -> Vec { v.iter().flat_map(|x| x.to_le_bytes()).collect() } @@ -209,11 +310,34 @@ pub fn embed_unit_into_shard( ids.len() }; - // Embed everything before writing anything: a model failure - // leaves no partial shard and an unstamped, still-open unit. - let mut vecs: Vec> = Vec::with_capacity(chunks.len()); + // Split over-context chunks into embeddable pieces (module + // docs, step 2), then embed everything before writing anything: + // a model failure leaves no partial shard and an unstamped, + // still-open unit. + let mut pieces: Vec = Vec::new(); + let mut item_piece_ordinals: std::collections::HashMap = + std::collections::HashMap::new(); for c in &chunks { - vecs.push(embedder.embed_doc(&c.text)?); + 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; + 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) + }, + text: piece, + }); + } + } + let mut vecs: Vec> = Vec::with_capacity(pieces.len()); + for piece in &pieces { + vecs.push(embedder.embed_doc(&piece.text)?); } let dims = vecs[0].len(); if dims == 0 || vecs.iter().any(|v| v.len() != dims) { @@ -260,7 +384,7 @@ pub fn embed_unit_into_shard( .map_err(|e| Error::backend(format!("aggregator: shard schema: {e}")))?; conn.execute_batch("BEGIN") .map_err(|e| Error::backend(format!("aggregator: shard begin: {e}")))?; - for (i, (c, v)) in chunks.iter().zip(vecs.iter()).enumerate() { + 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 @@ -274,7 +398,7 @@ pub fn embed_unit_into_shard( .unwrap_or_else(|| format!("unit:{unit_id}")); conn.execute( "INSERT INTO chunks VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - params![id, message_id, c.idx, c.text, c.content_hash, sens], + params![id, message_id, c.chunk_idx, c.text, c.content_hash, sens], ) .map_err(|e| Error::backend(format!("aggregator: shard chunk {id}: {e}")))?; conn.execute( @@ -288,7 +412,7 @@ pub fn embed_unit_into_shard( ("tier", unit.sensitivity.name().to_string()), ("topic", topic.to_string()), ("part", part.to_string()), - ("expected_chunks", chunks.len().to_string()), + ("expected_chunks", pieces.len().to_string()), ("metric", "cosine".to_string()), ("embedding_model", EMBEDDING_MODEL_ID.to_string()), ("engine", "tursodb".to_string()), @@ -344,7 +468,7 @@ pub fn embed_unit_into_shard( shard_name, shard_path, items, - chunks: chunks.len(), + chunks: pieces.len(), dims, }) } diff --git a/pkgs/atlas-search/crates/atlas-core/src/embed.rs b/pkgs/atlas-search/crates/atlas-core/src/embed.rs index 5c7d5acd39..8bf6c6a3b3 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/embed.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/embed.rs @@ -114,6 +114,24 @@ impl QueryEmbedder for AtlasEmbedder { /// this trait at promotion time. pub trait DocEmbedder { fn embed_doc(&self, text: &str) -> Result>; + + /// The embedder's token count for `text`, when it can count + /// (the production embedder tokenizes with the model's own + /// tokenizer). The staging aggregator splits staged chunks + /// against this count before embedding; embedders that cannot + /// count return `None` and their inputs are embedded as-is. + fn token_count(&self, _text: &str) -> Option { + None + } + + /// The maximum tokens one `embed_doc` input may carry. The + /// production bound is the model's real context + /// (`atlas_embed::MODEL_CONTEXT`): atlas-embed refuses longer + /// inputs loudly, matching the corpus pipeline's contract, so + /// the aggregator splits before it ever asks. + fn max_input_tokens(&self) -> usize { + atlas_embed::MODEL_CONTEXT + } } /// A fixed-vector document embedder for tests and fixture work: @@ -152,6 +170,11 @@ impl DocEmbedder for AtlasEmbedder { fn embed_doc(&self, text: &str) -> Result> { self.embed_doc_raw(text) } + + fn token_count(&self, text: &str) -> Option { + let guard = self.inner.lock().ok()?; + guard.tokenize(text).ok().map(|ids| ids.len()) + } } #[cfg(test)] diff --git a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs index b203bc9699..f3a5a7dd2f 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs @@ -186,3 +186,82 @@ fn tier_sensitivity_names_match_the_scan_ladder() { assert_eq!(tier_sensitivity_name(Tier::Internal), "personal"); assert_eq!(tier_sensitivity_name(Tier::Secret), "secret-bearing"); } + +/// A document embedder whose token is a word, with a tiny context: +/// forces the aggregator's embed-time split at a readable scale. +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_splits_a_chunk_that_exceeds_the_model_context() { + let dir = temp_dir("split"); + let registry = Registry::open(&dir.join("registry.db")).unwrap(); + let db = dir.join("unit.db"); + registry + .provision(&db, "task-split", "repo-worker-code", Tier::Internal, NOW) + .unwrap(); + // One staged whole-file chunk of 8 word-tokens; the embedder's + // context is 3, so promotion must split it into pieces of at + // most 3 words that partition the text exactly. + let text = "dns alpha beta\ndns gamma delta\ndns epsilon zeta\n"; + let entry = ArtifactEntry { + kind: "config".into(), + repo: "developing-today/code".into(), + path: "infra/dns/dns_config.yaml".into(), + commit_sha: "abc".into(), + language: "yaml".into(), + sensitivity: Tier::Internal, + text: text.into(), + }; + stage_artifact_in_db(&db, "task-split", &entry, NOW).unwrap(); + + let shard_dir = dir.join("shards"); + let report = embed_unit_into_shard( + ®istry, + "task-split", + &shard_dir, + "codeconfig", + &WordEmbedder, + NOW, + ) + .unwrap(); + assert!( + report.chunks >= 3, + "split into pieces, got {}", + report.chunks + ); + + // The pieces, read back from the shard in chunk order, + // partition the staged text exactly. + let conn = rusqlite::Connection::open(&report.shard_path).unwrap(); + let mut stmt = conn.prepare("SELECT text FROM chunks ORDER BY id").unwrap(); + let rows = stmt + .query_map([], |r| r.get::<_, String>(0)) + .unwrap() + .collect::, _>>() + .unwrap(); + assert_eq!(rows.concat(), text); + for piece in &rows { + assert!( + piece.split_whitespace().count() <= 3, + "piece fits: {piece:?}" + ); + } +}