diff --git a/pkgs/atlas-search/crates/atlas-core/src/memory.rs b/pkgs/atlas-search/crates/atlas-core/src/memory.rs index 98b6ad3ca..6c4921745 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/memory.rs @@ -29,11 +29,19 @@ //! [`sync_memory_entries`], which restages only the entries whose //! content changed since the last sync (idempotent by source_ref). The //! replay-safe staging path remains the prior #14024 implementation. +//! +//! The rebuild proof ([`rebuild_agent_memory_index`]) shows the Atlas +//! index is disposable: the same source rebuilt into a fresh staging +//! area yields the same shard fingerprints and fan-out ranking, and a +//! rebuild from a revised source carries only the current source +//! rows. -use std::path::Path; +use std::path::{Path, PathBuf}; use rusqlite::{Connection, OptionalExtension, params}; +use crate::aggregate::embed_unit_into_shard; +use crate::embed::DocEmbedder; use crate::error::{Error, Result}; use crate::shards::Tier; use crate::stage::{ @@ -558,3 +566,128 @@ pub fn sync_memory_entries( } Ok(report) } + +/// What one rebuild-from-sources run did: the promotion report plus +/// the staging delta and the rebuilt shard's chunk fingerprints, so +/// two builds from the same source can be compared for equality and +/// a build from a revised source can be compared for convergence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RebuildReport { + /// The staging-unit id that was rebuilt. + pub unit_id: String, + /// The new core scan shard's file name. + pub shard_name: String, + /// The new core scan shard's path. + pub shard_path: PathBuf, + /// Staged items embedded into the shard. + pub items: usize, + /// Staged chunks embedded into the shard. + pub chunks: usize, + /// The embedding dimension the shard's vectors carry. + pub dims: usize, + /// Item ids the staging step changed in this run (new or + /// revised rows). In a fresh staging area this is every row; + /// the rebuild's convergence claim is about the shard, not + /// this list. + pub staged_changed: Vec, + /// The rebuilt shard's chunk fingerprints, in shard order: + /// (source-of-truth pointer, content hash) per shard chunk. + /// Two builds from the same source must produce the same list. + pub fingerprints: Vec<(String, String)>, +} + +/// Read a core scan shard's chunk fingerprints, in shard order: +/// (source-of-truth pointer, content hash) per `chunks` row. The +/// fingerprint is the rebuild comparison's oracle: the hash is a +/// pure function of the staged chunk text (and, for repeated text, +/// its position), so equal fingerprints mean equal index content. +pub fn shard_chunk_fingerprints(shard_db: &Path) -> Result> { + let conn = Connection::open(shard_db).map_err(|e| { + Error::backend(format!( + "memory connector: opening shard {}: {e}", + shard_db.display() + )) + })?; + let mut stmt = conn + .prepare("SELECT message_id, content_hash FROM chunks ORDER BY id") + .map_err(|e| { + Error::backend(format!( + "memory connector: reading fingerprints from {}: {e}", + shard_db.display() + )) + })?; + let rows = stmt + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + }) + .map_err(|e| { + Error::backend(format!( + "memory connector: reading fingerprints from {}: {e}", + shard_db.display() + )) + })? + .collect::, _>>() + .map_err(|e| { + Error::backend(format!( + "memory connector: reading fingerprints from {}: {e}", + shard_db.display() + )) + })?; + Ok(rows) +} + +/// Rebuild the agent-memory Atlas index from its sources +/// (developing-today/code#14039, remaining acceptance: the index is +/// disposable, the corpora never are — design section 2). +/// +/// One call, in order: register the five design corpora (idempotent), +/// stage the source entries into the agent-memory unit through the +/// replay-safe staging path, and promote the unit into a new core +/// scan shard in `shard_dir` (embed-at-promotion, so the shard's +/// vectors come from the mandated model, never from the source +/// store's own vectors). +/// +/// The staging area is disposable by design: promotion stamps the +/// staging DB and closes it to further writes, and a merged unit +/// refuses a second promotion — so a rebuild targets a fresh +/// registry + staging dir, and the rebuilt shard is compared with +/// the previous build's [`RebuildReport::fingerprints`], not by +/// re-promoting into the same area. A rebuild from a revised source +/// carries only the current source's rows: rows the source dropped +/// are absent from the fresh staging area, so they are absent from +/// the rebuilt shard. (Incremental staging is different by design: +/// a partial export never deletes — see the adapter-fixtures record. +/// Deletion converges at rebuild, never at incremental stage.) +pub fn rebuild_agent_memory_index( + registry: &Registry, + staging_dir: &Path, + entries: &[MemoryEntry], + shard_dir: &Path, + embedder: &dyn DocEmbedder, + now: &str, +) -> Result { + let units = register_memory_corpora(registry, staging_dir, now)?; + let agent_db = units + .iter() + .find(|u| u.unit_id == AGENT_MEMORY_UNIT) + .map(|u| PathBuf::from(&u.db_uri)) + .ok_or_else(|| { + Error::fatal(format!( + "memory connector: {AGENT_MEMORY_UNIT} unit missing after registration" + )) + })?; + let staged_changed = stage_memory_export_in_db(&agent_db, AGENT_MEMORY_UNIT, entries, now)?; + let promote = + embed_unit_into_shard(registry, AGENT_MEMORY_UNIT, shard_dir, "agent-memory", embedder, now)?; + let fingerprints = shard_chunk_fingerprints(&promote.shard_path)?; + Ok(RebuildReport { + unit_id: promote.unit_id, + shard_name: promote.shard_name, + shard_path: promote.shard_path, + items: promote.items, + chunks: promote.chunks, + dims: promote.dims, + staged_changed, + fingerprints, + }) +} diff --git a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs index ff98e9268..4fb51f3fe 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs @@ -14,8 +14,8 @@ use atlas_core::embed::DocEmbedder; use atlas_core::error::Result; use atlas_core::filters::Filters; use atlas_core::memory::{ - AGENT_MEMORY_UNIT, MEMORY_CORPORA, parse_memory_export, register_memory_corpora, - stage_memory_export_in_db, + AGENT_MEMORY_UNIT, MEMORY_CORPORA, MemoryEntry, parse_memory_export, + rebuild_agent_memory_index, register_memory_corpora, stage_memory_export_in_db, }; use atlas_core::shards::scan::{FanoutQuery, fanout_scan}; use atlas_core::shards::{Tier, TierCeiling, open_from_spec}; @@ -248,12 +248,140 @@ fn a_new_memory_revision_replaces_the_existing_staged_item() { assert_eq!(items[0].text, "A corrected transcript of the same memory."); } -/// Oracle: the slice's acceptance — after promotion through the -/// aggregator (embed-at-promotion under the mandated model gate), -/// the production fan-out returns the agent-memory hit for a -/// matching query, the shard chunk carries the memory's -/// source-of-truth pointer, and the unit ends merged with its -/// merge manifest recorded. +/// Rebuild the agent-memory index from a source export into a +/// fresh staging area and return the report plus the fan-out +/// ranking for a transcript-shaped query vector. +fn rebuild_and_rank( + dir: &Path, + entries: &[MemoryEntry], +) -> (atlas_core::memory::RebuildReport, Vec<(i64, f64)>) { + let registry = Registry::open(&dir.join("registry.db")).unwrap(); + let report = rebuild_agent_memory_index( + ®istry, + dir, + entries, + &dir.join("shards"), + &KeywordEmbedder, + NOW, + ) + .unwrap(); + (report, fanout_ranking(&dir.join("shards"))) +} + +/// The fan-out ranking for a transcript-shaped query over one shard +/// dir: (chunk id, distance) in rank order. +fn fanout_ranking(shard_dir: &Path) -> Vec<(i64, f64)> { + let set = open_from_spec( + &format!("dir:{}", shard_dir.display()), + TierCeiling(Tier::Internal), + atlas_core::DEFAULT_VEC_TABLE, + ) + .unwrap(); + let filters = Filters::new(vec![], vec![], vec![], vec![], "personal", None, None).unwrap(); + 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 + .iter() + .map(|h| (h.chunk_id, h.dist)) + .collect() +} + +/// Oracle: the rebuild proof (design section 2 — the index is +/// disposable, the corpora never are). Two builds from the same +/// source, each into its own fresh staging area, produce the same +/// shard name, the same chunk fingerprints, and the same fan-out +/// ranking for a matching query: the rebuilt index is the same +/// index. +#[test] +fn rebuilt_agent_memory_index_matches_the_first_build() { + let entries = parse_memory_export(EXPORT).unwrap(); + let (first, first_ranking) = rebuild_and_rank(&temp_dir("rebuild-first"), &entries); + let (second, second_ranking) = rebuild_and_rank(&temp_dir("rebuild-second"), &entries); + + assert_eq!(first.items, 2); + assert_eq!(first.chunks, 2); + assert_eq!(first.staged_changed.len(), 2, "fresh area stages all rows"); + assert_eq!(first.shard_name, second.shard_name); + assert_eq!(first.items, second.items); + assert_eq!(first.chunks, second.chunks); + assert_eq!(first.dims, second.dims); + assert_eq!( + first.fingerprints, second.fingerprints, + "same source rebuilds to the same shard content" + ); + assert_eq!( + first + .fingerprints + .iter() + .map(|(source, _)| source.as_str()) + .collect::>(), + ["memory-lancedb:mem-transcript", "memory-lancedb:mem-deploy"], + "fingerprints name each row's source-of-truth pointer" + ); + assert_eq!( + first_ranking, second_ranking, + "the rebuilt index ranks the same hits in the same order" + ); + assert_eq!(first_ranking.len(), 2); + assert_eq!(first_ranking[0].0, 1, "the transcript memory ranks first"); +} + +/// Oracle: a rebuild from a revised source converges to the current +/// source. The revised export edits one memory and drops the other; +/// the rebuilt shard carries the revised text under the same source +/// pointer, with a new content hash, and no longer contains the +/// dropped row at all. (Incremental staging never deletes on a +/// partial export — that guard stays; deletion converges at +/// rebuild, when the staging area is fresh.) +#[test] +fn rebuild_after_a_source_revision_carries_only_the_current_source() { + let entries = parse_memory_export(EXPORT).unwrap(); + let (first, _) = rebuild_and_rank(&temp_dir("rebuild-rev-first"), &entries); + + let mut revised = entries[0].clone(); + revised.text = "A corrected transcript of the same memory.".to_string(); + revised.created_at_ms = Some(revised.created_at_ms.unwrap() + 60_000.0); + let (second, second_ranking) = + rebuild_and_rank(&temp_dir("rebuild-rev-second"), std::slice::from_ref(&revised)); + + assert_eq!(second.items, 1); + assert_eq!(second.chunks, 1); + assert_eq!(second.fingerprints.len(), 1); + assert_eq!( + second.fingerprints[0].0, "memory-lancedb:mem-transcript", + "the revised row keeps its source identity" + ); + assert_ne!( + first.fingerprints[0].1, second.fingerprints[0].1, + "the revised text hashes differently" + ); + assert!( + !second + .fingerprints + .iter() + .any(|(source, _)| source.contains("mem-deploy")), + "a row the source dropped is absent from the rebuilt index" + ); + assert_eq!(second_ranking.len(), 1); + assert_eq!(second_ranking[0].0, 1); + + // The rebuilt shard's stored text is the revised text. + let conn = rusqlite::Connection::open(&second.shard_path).unwrap(); + let text: String = conn + .query_row("SELECT text FROM chunks ORDER BY id", [], |r| r.get(0)) + .unwrap(); + assert_eq!(text, "A corrected transcript of the same memory."); +} #[test] fn promoted_agent_memory_is_searchable_by_the_fanout() { let dir = temp_dir("search"); 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 fa5f961e1..fb077d1bb 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 @@ -3,7 +3,7 @@ //! versioned schema, provisioning tool and registry; design //! `doc/2026-11-04T21-27-34Z_design_atlas_scaler_revision` section 4.1). //! -//! Six verbs: +//! Nine verbs: //! * `atlas-stage provision --db --unit --owner //! [--sensitivity internal] --registry ` — create the unit's //! staging DB, apply the v1 schema, and register the unit as `open`. @@ -47,12 +47,21 @@ //! 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). +//! * `atlas-stage rebuild-memory --export +//! --registry --dir --shard-dir ` — rebuild +//! the agent-memory Atlas index from its sources (#14039): the +//! provision-corpora + ingest-memory + promote steps in one +//! command, into a fresh registry/dir (the staging area is +//! disposable and promotion closes it). Prints the rebuild +//! report: shard, items, chunks, staged-changed count, and +//! fingerprint count. Needs the embedding model + ONNX runtime, +//! like `promote`. //! -//! Five of the six are offline: a staging DB is a local libSQL/SQLite +//! Seven of the nine 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. `promote` is the -//! exception: it needs the embedding model + ONNX runtime, as its -//! entry above states. +//! deployment surface, not this foundation. `promote` and +//! `rebuild-memory` are the exceptions: they need the embedding +//! model + ONNX runtime, as their entries above state. use std::path::PathBuf; use std::process::ExitCode; @@ -200,6 +209,25 @@ enum Command { #[arg(long, default_value = "codeconfig")] topic: String, }, + /// Rebuild the agent-memory Atlas index from its sources + /// (#14039): provision-corpora + ingest-memory + promote in one + /// command, into a fresh registry/dir. Needs the embedding + /// model + ONNX runtime, like `promote`. + RebuildMemory { + /// The read-only JSON export of the memory-lancedb store. + #[arg(long)] + export: PathBuf, + /// The registry store file (created if missing). + #[arg(long)] + registry: PathBuf, + /// Directory each corpus unit's staging DB is provisioned in. + #[arg(long)] + dir: PathBuf, + /// Directory the new core scan shard is written into + /// (created if missing). + #[arg(long)] + shard_dir: PathBuf, + }, /// List units in a lifecycle state (open|closing|merged). Units { #[arg(long, default_value = "open")] @@ -477,6 +505,40 @@ fn run(cli: Cli) -> Result<(), String> { } Ok(()) } + Command::RebuildMemory { + export, + registry, + dir, + shard_dir, + } => { + let raw = std::fs::read_to_string(&export) + .map_err(|e| format!("reading {}: {e}", export.display()))?; + let entries = + atlas_core::memory::parse_memory_export(&raw).map_err(|e| e.to_string())?; + let registry = Registry::open(®istry).map_err(|e| e.to_string())?; + let embedder = load_doc_embedder()?; + let report = atlas_core::memory::rebuild_agent_memory_index( + ®istry, + &dir, + &entries, + &shard_dir, + &embedder, + &now_utc(), + ) + .map_err(|e| e.to_string())?; + println!( + "{{\"unit\":{},\"shard\":{},\"shard_path\":{},\"items\":{},\"chunks\":{},\"dims\":{},\"staged_changed\":{},\"fingerprints\":{}}}", + json_str(&report.unit_id), + json_str(&report.shard_name), + json_str(&report.shard_path.display().to_string()), + report.items, + report.chunks, + report.dims, + report.staged_changed.len(), + report.fingerprints.len(), + ); + Ok(()) + } } }