From cf9368e8278e11472818fcaaa43014a5df06c8eb Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Mon, 16 Nov 2026 10:49:27 -0600 Subject: [PATCH] =?UTF-8?q?feat(atlas):=20aggregator=20embed-at-promotion?= =?UTF-8?q?=20=E2=80=94=20staged=20unit=20to=20core=20scan=20shard=20(#151?= =?UTF-8?q?8,=20#5669)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../crates/atlas-core/src/aggregate.rs | 350 ++++++++++++++++++ .../crates/atlas-core/src/embed.rs | 50 +++ .../atlas-search/crates/atlas-core/src/lib.rs | 6 +- .../crates/atlas-core/tests/aggregate.rs | 188 ++++++++++ .../atlas-search/src/bin/atlas-stage.rs | 102 +++++ 5 files changed, 695 insertions(+), 1 deletion(-) create mode 100644 pkgs/atlas-search/crates/atlas-core/src/aggregate.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs diff --git a/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs new file mode 100644 index 0000000000..2b7630c34f --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/aggregate.rs @@ -0,0 +1,350 @@ +//! The staging aggregator's embed-at-promotion step (developing-today/code#5669 +//! aggregator slice; first consumer developing-today/code#1518). +//! +//! The staging design (doc/2026-11-04T21-27-34Z_design_atlas_scaler_revision +//! section 4.1) keeps staging DBs vector-free — "the aggregator embeds at +//! promotion; a staging DB never stores vectors". This module is that +//! aggregator step, scoped to one unit and one new core scan shard: +//! +//! 1. Read the unit's staged `items` + `chunks_raw` from its staging DB +//! (raw SQL, in staging order — the read happens before any stamp, so +//! 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`]). +//! 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 +//! [`DEFAULT_VEC_TABLE`] vector table, `atlas_manifest`), so the +//! 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`]). +//! 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 +//! staging DB, which closes it to further `stage_artifact` writes +//! (the v1 schema check asserts the exact table set): promotion is +//! the unit's terminal write, matching merge-on-close. +//! 5. Promote the unit through [`Registry::promote`], whose gate +//! re-reads the stamp; the unit ends `merged`. +//! +//! Failure shape: any error before the stamp leaves the unit `open` +//! and removes a partially written shard file, so a retry starts +//! clean. An error at the promote step itself leaves a complete, +//! discoverable shard and a stamped unit DB — re-running refuses at +//! the shard-name step only if the file still exists, so the operator +//! removes the recorded shard and retries, or promotes the unit +//! directly through the registry (the gate will pass: the stamp is +//! already in place). +//! +//! Out of scope (later #5669 slices): hosted Turso shard creation (the +//! deployment surface), multi-unit aggregation into one shard, and +//! merge-on-close archival of the staging DB file. + +use std::path::{Path, PathBuf}; + +use rusqlite::{Connection, params}; + +use crate::embed::DocEmbedder; +use crate::error::{Error, Result}; +use crate::shards::{EMBEDDING_MODEL_ID, Tier}; +use crate::stage::{Registry, UnitState}; +use crate::types::DEFAULT_VEC_TABLE; + +/// The scan-vocabulary sensitivity name a chunk of this tier carries +/// in a core shard. The fan-out scan filters `chunks.sensitivity` +/// against the [`crate::filters::Sensitivity`] ladder, whose tier +/// mapping is [`crate::shards::TierCeiling::from_sensitivity`] +/// (shareable -> public; personal / local-only -> internal; +/// secret-bearing -> secret). Promotion writes the canonical +/// representative of the unit's tier, so an internal unit's chunks +/// are admitted under the default `personal` ceiling and a secret +/// unit's chunks only under an explicit `secret-bearing` ceiling. +pub fn tier_sensitivity_name(tier: Tier) -> &'static str { + match tier { + Tier::Public => "shareable", + Tier::Internal => "personal", + Tier::Secret => "secret-bearing", + } +} + +/// What one embed-at-promotion run did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PromoteReport { + pub unit_id: String, + pub shard_name: String, + pub shard_path: PathBuf, + pub items: usize, + pub chunks: usize, + pub dims: usize, +} + +struct StagedChunk { + item_id: i64, + item_source: Option, + item_sensitivity: String, + idx: i64, + text: String, + content_hash: String, +} + +/// Read one unit's staged chunks in staging order (item id, then +/// chunk idx), with each chunk's item source pointer and sensitivity. +fn read_staged_chunks(db_path: &Path, unit_id: &str) -> Result> { + let conn = Connection::open(db_path).map_err(|e| { + Error::backend(format!( + "aggregator: opening staging DB {}: {e}", + db_path.display() + )) + })?; + let mut stmt = conn + .prepare( + "SELECT i.id, i.source, i.sensitivity, c.idx, 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", + ) + .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)?, + idx: r.get(3)?, + text: r.get(4)?, + content_hash: r.get(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}")))?, + ); + } + Ok(out) +} + +/// The next free part number for `(tier, topic)` in `shard_dir`: +/// one past the highest existing shard part, or 0 when none exists. +fn next_shard_part(shard_dir: &Path, tier: Tier, topic: &str) -> Result { + let mut next: u32 = 0; + let rd = match std::fs::read_dir(shard_dir) { + Ok(rd) => rd, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(e) => { + return Err(Error::backend(format!( + "aggregator: listing shard dir {}: {e}", + shard_dir.display() + ))); + } + }; + for ent in rd.flatten() { + let p = ent.path(); + if p.extension().and_then(|x| x.to_str()) != Some("db") { + continue; + } + let Some(stem) = p.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + if let Some((t, tp, part)) = crate::shards::parse_shard_name(stem) { + if t == tier && tp == topic { + next = next.max(part + 1); + } + } + } + Ok(next) +} + +fn vec_blob(v: &[f32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +/// Embed one staging unit's chunks into a new core scan shard and +/// promote the unit (see the module docs for the step order and the +/// failure shape). `topic` is the shard topic the promoted entries +/// land under (e.g. `codeconfig` for #1518 code/config entries). +pub fn embed_unit_into_shard( + registry: &Registry, + unit_id: &str, + shard_dir: &Path, + topic: &str, + embedder: &dyn DocEmbedder, + now: &str, +) -> Result { + let unit = registry.lookup(unit_id)?.ok_or_else(|| { + Error::fatal(format!( + "aggregator: no staging unit {unit_id:?} to promote" + )) + })?; + if unit.state == UnitState::Merged { + return Err(Error::fatal(format!( + "aggregator: staging unit {unit_id:?} is already merged" + ))); + } + if topic.is_empty() + || !topic + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + { + return Err(Error::fatal(format!( + "aggregator: shard topic {topic:?} must be non-empty [A-Za-z0-9-]" + ))); + } + let db_path = PathBuf::from(&unit.db_uri); + let chunks = read_staged_chunks(&db_path, unit_id)?; + if chunks.is_empty() { + return Err(Error::fatal(format!( + "aggregator: staging unit {unit_id:?} has no staged chunks to embed" + ))); + } + let items = { + let mut ids: Vec = Vec::new(); + for c in &chunks { + if !ids.contains(&c.item_id) { + ids.push(c.item_id); + } + } + 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()); + for c in &chunks { + vecs.push(embedder.embed_doc(&c.text)?); + } + let dims = vecs[0].len(); + if dims == 0 || vecs.iter().any(|v| v.len() != dims) { + return Err(Error::fatal(format!( + "aggregator: embedder returned inconsistent vector dims for unit {unit_id:?} (first {dims})" + ))); + } + + std::fs::create_dir_all(shard_dir).map_err(|e| { + Error::backend(format!( + "aggregator: creating shard dir {}: {e}", + shard_dir.display() + )) + })?; + let part = next_shard_part(shard_dir, unit.sensitivity, topic)?; + let shard_name = format!( + "atlas-core-{}-{}-{:02}", + unit.sensitivity.name(), + topic, + part + ); + let shard_path = shard_dir.join(format!("{shard_name}.db")); + if shard_path.exists() { + return Err(Error::fatal(format!( + "aggregator: shard file {} already exists; refusing to overwrite", + shard_path.display() + ))); + } + + let write = (|| -> Result<()> { + let conn = Connection::open(&shard_path).map_err(|e| { + Error::backend(format!( + "aggregator: creating shard {}: {e}", + shard_path.display() + )) + })?; + conn.execute_batch(&format!( + "CREATE TABLE chunks (id INTEGER PRIMARY KEY, message_id TEXT NOT NULL, \ + 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 atlas_manifest (\"key\" TEXT PRIMARY KEY, value TEXT);" + )) + .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() { + 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)); + let message_id = c + .item_source + .clone() + .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], + ) + .map_err(|e| Error::backend(format!("aggregator: shard chunk {id}: {e}")))?; + conn.execute( + &format!("INSERT INTO {DEFAULT_VEC_TABLE} VALUES (?1, ?2)"), + params![id, vec_blob(v)], + ) + .map_err(|e| Error::backend(format!("aggregator: shard vector {id}: {e}")))?; + } + let manifest: [(&str, String); 9] = [ + ("shard", shard_name.clone()), + ("tier", unit.sensitivity.name().to_string()), + ("topic", topic.to_string()), + ("part", part.to_string()), + ("expected_chunks", chunks.len().to_string()), + ("metric", "cosine".to_string()), + ("embedding_model", EMBEDDING_MODEL_ID.to_string()), + ("engine", "tursodb".to_string()), + ("source_unit", unit_id.to_string()), + ]; + for (k, v) in &manifest { + conn.execute( + "INSERT OR REPLACE INTO atlas_manifest VALUES (?1, ?2)", + params![k, v], + ) + .map_err(|e| Error::backend(format!("aggregator: shard manifest {k}: {e}")))?; + } + conn.execute_batch("COMMIT") + .map_err(|e| Error::backend(format!("aggregator: shard commit: {e}")))?; + Ok(()) + })(); + if let Err(e) = write { + let _ = std::fs::remove_file(&shard_path); + return Err(e); + } + + // Stamp the unit DB's embedding-model provenance (the M6 gate's + // record), then promote through the registry gate. On failure the + // shard stays on disk, complete and discoverable, and the report + // path is in the module docs. + let stamp = (|| -> Result<()> { + let conn = Connection::open(&db_path).map_err(|e| { + Error::backend(format!( + "aggregator: opening staging DB {} for the model stamp: {e}", + db_path.display() + )) + })?; + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS atlas_manifest (\"key\" TEXT PRIMARY KEY, value TEXT);", + ) + .map_err(|e| Error::backend(format!("aggregator: model stamp table: {e}")))?; + conn.execute( + "INSERT OR REPLACE INTO atlas_manifest VALUES ('embedding_model', ?1)", + params![EMBEDDING_MODEL_ID], + ) + .map_err(|e| Error::backend(format!("aggregator: model stamp: {e}")))?; + Ok(()) + })(); + if let Err(e) = stamp { + let _ = std::fs::remove_file(&shard_path); + return Err(e); + } + + registry.promote(unit_id, now)?; + + Ok(PromoteReport { + unit_id: unit_id.to_string(), + shard_name, + shard_path, + items, + chunks: chunks.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 75aa875161..5c7d5acd39 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/embed.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/embed.rs @@ -104,6 +104,56 @@ impl QueryEmbedder for AtlasEmbedder { } } +/// A document embedder: raw text in, production-shaped document +/// vector out. The document side of the corpus contract is the +/// mirror of [`QueryEmbedder`]: documents are embedded prompt-free +/// (no `"query: "` prefix) and stored as the model produced them — +/// the scan's cosine distance is scale-invariant, and the query +/// side owns prompt + truncation + renormalization. The staging +/// aggregator (`crate::aggregate`) embeds staged chunks through +/// this trait at promotion time. +pub trait DocEmbedder { + fn embed_doc(&self, text: &str) -> Result>; +} + +/// A fixed-vector document embedder for tests and fixture work: +/// every document gets the same recorded vector, exactly where a +/// test monkeypatches the embedder (the document-side twin of +/// [`FixedEmbedder`]). +pub struct FixedDocEmbedder { + pub raw: Vec, +} + +impl DocEmbedder for FixedDocEmbedder { + fn embed_doc(&self, _text: &str) -> Result> { + Ok(self.raw.clone()) + } +} + +impl AtlasEmbedder { + /// The raw full-dimension document vector for `text`: no query + /// prompt, no truncation, no renormalization — the shape the + /// production corpus was embedded in on the document side. + pub fn embed_doc_raw(&self, text: &str) -> Result> { + let mut guard = self + .inner + .lock() + .map_err(|_| Error::Embed("embedder mutex poisoned".to_string()))?; + let out = guard + .embed(&[text]) + .map_err(|e| Error::Embed(e.to_string()))?; + out.into_iter().next().map(|a| a.to_vec()).ok_or_else(|| { + Error::Embed("embedder returned no vector for a single input".to_string()) + }) + } +} + +impl DocEmbedder for AtlasEmbedder { + fn embed_doc(&self, text: &str) -> Result> { + self.embed_doc_raw(text) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/pkgs/atlas-search/crates/atlas-core/src/lib.rs b/pkgs/atlas-search/crates/atlas-core/src/lib.rs index ac85aa397d..ce4cf51b45 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/lib.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/lib.rs @@ -27,6 +27,7 @@ //! mutex; session load (~1.6 GB RSS) is shared state by design, //! never per-request. +pub mod aggregate; pub mod backend; pub mod embed; pub mod embed_cache; @@ -54,8 +55,11 @@ pub mod types; /// Keep this aligned with the service's get-chunk neighbors ceiling. pub const MAX_EXPAND_NEIGHBORS: usize = 100; +pub use aggregate::{PromoteReport, embed_unit_into_shard, tier_sensitivity_name}; pub use backend::SearchBackend; -pub use embed::{AtlasEmbedder, FixedEmbedder, QUERY_PROMPT, QueryEmbedder}; +pub use embed::{ + AtlasEmbedder, DocEmbedder, FixedDocEmbedder, FixedEmbedder, QUERY_PROMPT, QueryEmbedder, +}; pub use embed_cache::{ CachingEmbedder, QueryEmbeddingCache, RawQueryEmbedder, SharedEmbeddingStore, TursoEmbeddingStore, cache_key, normalize_query_text, diff --git a/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs new file mode 100644 index 0000000000..b203bc9699 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/tests/aggregate.rs @@ -0,0 +1,188 @@ +//! Oracle tests for the staging aggregator's embed-at-promotion +//! step (#5669 aggregator slice, #1518): a staged code/config unit +//! is embedded into a new core scan shard, the shard is discoverable +//! and searchable by the production fan-out, and the unit ends +//! promoted (merged) through the M6 gate. + +use std::path::{Path, PathBuf}; + +use atlas_core::aggregate::{embed_unit_into_shard, tier_sensitivity_name}; +use atlas_core::embed::DocEmbedder; +use atlas_core::error::Result; +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}; + +const NOW: &str = "2026-11-16T00:00:00Z"; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("atlas-aggregate-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).expect("temp dir"); + d +} + +/// A document embedder keyed on content: DNS text lands on the +/// first axis, everything else on the second — enough structure for +/// the fan-out oracle to rank by. +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]) + } + } +} + +fn stage_unit(dir: &Path) -> (Registry, PathBuf) { + let registry_path = dir.join("registry.db"); + let registry = Registry::open(®istry_path).unwrap(); + let db = dir.join("unit.db"); + registry + .provision(&db, "task-17164", "repo-worker-code", Tier::Internal, NOW) + .unwrap(); + let dns = ArtifactEntry { + kind: "config".into(), + repo: "developing-today/code".into(), + path: "infra/dns/dns_config.yaml".into(), + commit_sha: "d85bd4ff1f3b73700f881aa99357adeae997e1bd".into(), + language: "yaml".into(), + sensitivity: Tier::Internal, + text: "dns:\n zones:\n - name: example.internal\n".into(), + }; + stage_artifact_in_db(&db, "task-17164", &dns, NOW).unwrap(); + let prose = ArtifactEntry { + kind: "prose".into(), + repo: "developing-today/code".into(), + path: "doc/notes.md".into(), + commit_sha: "d85bd4ff1f3b73700f881aa99357adeae997e1bd".into(), + language: "md".into(), + sensitivity: Tier::Internal, + text: "release checklist and meeting notes".into(), + }; + stage_artifact_in_db(&db, "task-17164", &prose, NOW).unwrap(); + (registry, db) +} + +#[test] +fn promotion_embeds_the_unit_into_a_searchable_shard_and_merges_it() { + let dir = temp_dir("promote"); + let (registry, _db) = stage_unit(&dir); + let shard_dir = dir.join("shards"); + + // Before the aggregator runs, the registry gate refuses: the + // unit DB records no embedding model (unknown provenance). + assert!(registry.promote("task-17164", NOW).is_err()); + assert_eq!( + registry.lookup("task-17164").unwrap().unwrap().state, + UnitState::Open + ); + + let report = embed_unit_into_shard( + ®istry, + "task-17164", + &shard_dir, + "codeconfig", + &KeywordEmbedder, + NOW, + ) + .unwrap(); + assert_eq!(report.items, 2); + assert_eq!(report.chunks, 2); + assert_eq!(report.dims, 3); + assert_eq!(report.shard_name, "atlas-core-internal-codeconfig-00"); + assert!(report.shard_path.exists()); + assert_eq!( + registry.lookup("task-17164").unwrap().unwrap().state, + UnitState::Merged + ); + + // The shard is discoverable by the production path and the + // fan-out ranks the DNS config chunk first for a DNS-shaped + // query vector. + let set = open_from_spec( + &format!("dir:{}", shard_dir.display()), + TierCeiling(Tier::Internal), + atlas_core::DEFAULT_VEC_TABLE, + ) + .unwrap(); + assert_eq!(set.shards().len(), 1); + assert_eq!(set.shards()[0].chunks, 2); + 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(), 2); + assert_eq!(hits[0].chunk_id, 1, "the DNS config chunk ranks first"); + assert!(hits[0].dist < hits[1].dist); +} + +#[test] +fn promotion_refuses_an_empty_unit_and_a_second_run() { + let dir = temp_dir("refusals"); + let registry = Registry::open(&dir.join("registry.db")).unwrap(); + let db = dir.join("empty.db"); + registry + .provision(&db, "task-empty", "repo-worker-code", Tier::Internal, NOW) + .unwrap(); + let shard_dir = dir.join("shards"); + let err = embed_unit_into_shard( + ®istry, + "task-empty", + &shard_dir, + "codeconfig", + &KeywordEmbedder, + NOW, + ) + .unwrap_err(); + assert!(err.to_string().contains("no staged chunks"), "{err}"); + assert_eq!( + registry.lookup("task-empty").unwrap().unwrap().state, + UnitState::Open + ); + + // A second promotion of a merged unit refuses. + let dir2 = temp_dir("second-run"); + let (registry2, _db2) = stage_unit(&dir2); + let shard_dir2 = dir2.join("shards"); + embed_unit_into_shard( + ®istry2, + "task-17164", + &shard_dir2, + "codeconfig", + &KeywordEmbedder, + NOW, + ) + .unwrap(); + let err = embed_unit_into_shard( + ®istry2, + "task-17164", + &shard_dir2, + "codeconfig", + &KeywordEmbedder, + NOW, + ) + .unwrap_err(); + assert!(err.to_string().contains("already merged"), "{err}"); +} + +#[test] +fn tier_sensitivity_names_match_the_scan_ladder() { + assert_eq!(tier_sensitivity_name(Tier::Public), "shareable"); + assert_eq!(tier_sensitivity_name(Tier::Internal), "personal"); + assert_eq!(tier_sensitivity_name(Tier::Secret), "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 759ec3ab24..e7472da427 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 @@ -19,6 +19,16 @@ //! * `atlas-stage items --db [--unit ]` — list the //! items staged in a unit's DB, with chunk counts. //! +//! * `atlas-stage promote --registry --unit +//! --shard-dir [--topic codeconfig]` — the aggregator's +//! embed-at-promotion step (#5669 aggregator slice, #1518): embed +//! the unit's staged chunks with the mandated model, write a new +//! core scan shard in the shard dir, stamp the unit DB's +//! embedding-model provenance, and promote the unit to `merged` +//! through the registry's M6 gate. Needs the embedding model + +//! ONNX runtime (ATLAS_MODEL_DIR / ATLAS_ORT_LIB, the same +//! resolution the atlas-search binary uses). +//! //! All three are offline: a staging DB is a local libSQL/SQLite file //! today; hosted Turso creation is the aggregator slice's deployment //! surface, not this foundation. @@ -106,6 +116,23 @@ enum Command { #[arg(long)] unit: Option, }, + /// Embed a unit's staged chunks into a new core scan shard and + /// promote the unit to merged (aggregator embed-at-promotion). + Promote { + /// The registry store file. + #[arg(long)] + registry: PathBuf, + /// The staging-unit id to promote. + #[arg(long)] + unit: String, + /// Directory the new core scan shard is written into + /// (created if missing). + #[arg(long)] + shard_dir: PathBuf, + /// Shard topic for the promoted entries. + #[arg(long, default_value = "codeconfig")] + topic: String, + }, /// List units in a lifecycle state (open|closing|merged). Units { #[arg(long, default_value = "open")] @@ -238,6 +265,34 @@ fn run(cli: Cli) -> Result<(), String> { } Ok(()) } + Command::Promote { + registry, + unit, + shard_dir, + topic, + } => { + let registry = Registry::open(®istry).map_err(|e| e.to_string())?; + let embedder = load_doc_embedder()?; + let report = atlas_core::aggregate::embed_unit_into_shard( + ®istry, + &unit, + &shard_dir, + &topic, + &embedder, + &now_utc(), + ) + .map_err(|e| e.to_string())?; + println!( + "{{\"unit\":{},\"shard\":{},\"shard_path\":{},\"items\":{},\"chunks\":{},\"dims\":{}}}", + json_str(&report.unit_id), + json_str(&report.shard_name), + json_str(&report.shard_path.display().to_string()), + report.items, + report.chunks, + report.dims, + ); + Ok(()) + } Command::Units { state, registry } => { let state = parse_state(&state)?; let registry = Registry::open(®istry).map_err(|e| e.to_string())?; @@ -250,6 +305,53 @@ fn run(cli: Cli) -> Result<(), String> { } } +/// Build the production document embedder for `promote`: the +/// pinned Snowflake model via atlas-embed, resolved exactly as the +/// atlas-search binary resolves it (ATLAS_MODEL_DIR, then the +/// state-dir / HF-cache snapshots; ATLAS_ORT_LIB, then the state-dir +/// runtime). A missing model or runtime is a loud error, never a +/// silent downgrade. +fn load_doc_embedder() -> Result { + let home = std::env::var_os("HOME") + .map(PathBuf::from) + .ok_or_else(|| "HOME is not set".to_string())?; + let model_dir = std::env::var("ATLAS_MODEL_DIR") + .ok() + .filter(|d| !d.is_empty()) + .map(PathBuf::from) + .filter(|p| p.is_dir()) + .or_else(|| { + let state = home.join(".local/state/atlas-search/model/95c2741480856aa9666782eb4afe11959938017f"); + if state.is_dir() { + return Some(state); + } + let hf = home.join(".cache/huggingface/hub/models--Snowflake--snowflake-arctic-embed-m-v2.0/snapshots/95c2741480856aa9666782eb4afe11959938017f"); + if hf.is_dir() { Some(hf) } else { None } + }) + .ok_or_else(|| { + "Snowflake model not found (looked in ATLAS_MODEL_DIR, ~/.local/state/atlas-search/model/, and the HF cache snapshot)".to_string() + })?; + let ort_lib = std::env::var("ATLAS_ORT_LIB") + .ok() + .filter(|d| !d.is_empty()) + .map(PathBuf::from) + .filter(|p| p.is_file()) + .or_else(|| { + let cand = home.join(".local/state/atlas-search/ort/libonnxruntime.so"); + if cand.is_file() { + return Some(cand); + } + let venv = home.join("atlas/v3-venv/lib/python3.14/site-packages/onnxruntime/capi/libonnxruntime.so.1.31.1"); + if venv.is_file() { Some(venv) } else { None } + }) + .ok_or_else(|| { + "ONNX Runtime library not found: set ATLAS_ORT_LIB".to_string() + })?; + let emb = atlas_embed::Embedder::load(&model_dir, &ort_lib) + .map_err(|e| format!("embedder load failed: {e}"))?; + Ok(atlas_core::AtlasEmbedder::new(emb)) +} + fn unit_json(unit: &atlas_core::stage::StagingUnit) -> String { format!( "{{\"unit_id\":{},\"db_uri\":{},\"owner\":{},\"sensitivity\":{},\"state\":{},\"schema_version\":{},\"created_at\":{},\"updated_at\":{}}}",