From ad3fb1559d8cb719883b3e3a7002cc9b6c89fc16 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 03:44:06 -0600 Subject: [PATCH 1/3] wip(atlas-core): native memory-lancedb reader and idempotent sync (#14039, task 21642) Adds read_lancedb_store (lance 14 native scan, vector ignored), sync_memory_entries (restage only changed source_refs), and fixture-based tests. Test build is blocked: lance-linalg 14.0.2 fails codegen on rustc 1.99.0 (vpdpbusd intrinsic signature). --- .../atlas-search/crates/atlas-core/Cargo.toml | 4 + .../crates/atlas-core/src/memory.rs | 167 +++++++++++++++++- .../crates/atlas-core/tests/memory.rs | 106 +++++++++++ .../atlas-search/src/bin/atlas-stage.rs | 29 +++ 4 files changed, 302 insertions(+), 4 deletions(-) diff --git a/pkgs/atlas-search/crates/atlas-core/Cargo.toml b/pkgs/atlas-search/crates/atlas-core/Cargo.toml index 3da1648409..e1c20df068 100644 --- a/pkgs/atlas-search/crates/atlas-core/Cargo.toml +++ b/pkgs/atlas-search/crates/atlas-core/Cargo.toml @@ -9,12 +9,16 @@ description = "Atlas search semantics as a library: filters and sensitivity ceil [dependencies] atlas-embed = { path = "../atlas-embed" } atlas-proto = { path = "../atlas-proto" } +arrow = "58" base64 = "0.23" blake3 = "1" +futures = "0.3" +lance = { version = "14", default-features = false } rusqlite = { version = "0.43", features = ["bundled", "functions"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } sha2 = "0.11" +tokio = { version = "1", features = ["rt", "time", "net"] } unicode-normalization = "0.1" thiserror = "2" ureq = { version = "3", features = ["rustls"] } diff --git a/pkgs/atlas-search/crates/atlas-core/src/memory.rs b/pkgs/atlas-search/crates/atlas-core/src/memory.rs index 5e3ba1618d..95c278cea9 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/memory.rs @@ -23,10 +23,12 @@ //! `chunks_raw` write path every staged unit uses; promotion and //! search are the existing aggregator and fan-out, unchanged. //! -//! Slice 1b adds replay-safe staging keyed by the stable LanceDB row -//! id and source update timestamp (with content/metadata comparison -//! when the source has no timestamp). The native LanceDB reader and -//! rebuild-from-sources proof remain follow-up work. +//! Slice 1b (developing-today/code#14039) adds the native reader +//! [`read_lancedb_store`], which opens the store directly with the +//! trimmed `lance` crate (no second vector store), and +//! [`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. use std::path::Path; @@ -405,3 +407,160 @@ pub fn stage_memory_export_in_db( let conn = open(db)?; stage_memory_export(&conn, unit_id, entries, now) } + +/// What one [`sync_memory_entries`] run did to a unit. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SyncReport { + /// Entries staged for the first time. + pub added: usize, + /// Entries whose recorded content changed, restaged in place. + pub restaged: usize, + /// Entries already staged with identical content — untouched. + pub unchanged: usize, +} + +/// Read the memory-lancedb store at `path` natively: open the +/// `memories.lance` dataset with the `lance` crate and map its +/// `id`, `text`, `agentId`, `category`, `importance` and `createdAt` +/// columns onto [`MemoryEntry`]. The `vector` column is never read. +/// A missing required column or an empty id/text is a loud error. +pub async fn read_lancedb_store(path: &Path) -> Result> { + use arrow::array::{Array, ArrayRef, RecordBatch}; + use arrow::compute::cast; + use arrow::datatypes::DataType; + + let uri = path + .to_str() + .ok_or_else(|| Error::fatal("memory connector: store path is not valid UTF-8"))?; + let dataset = lance::Dataset::open(uri) + .await + .map_err(|e| Error::backend(format!("memory connector: opening {uri}: {e}")))?; + let batch: RecordBatch = dataset + .scan() + .try_into_batch() + .await + .map_err(|e| Error::backend(format!("memory connector: scanning {uri}: {e}")))?; + + let column = |name: &str| -> Result> { + match batch.column_by_name(name) { + None => Ok(None), + Some(col) => cast(col, &DataType::Utf8) + .map(Some) + .map_err(|e| Error::fatal(format!("memory connector: column `{name}`: {e}"))), + } + }; + let numbers = |name: &str| -> Result> { + match batch.column_by_name(name) { + None => Ok(None), + Some(col) => cast(col, &DataType::Float64) + .map(Some) + .map_err(|e| Error::fatal(format!("memory connector: column `{name}`: {e}"))), + } + }; + let id = column("id")? + .ok_or_else(|| Error::fatal("memory connector: store has no `id` column"))?; + let text = column("text")? + .ok_or_else(|| Error::fatal("memory connector: store has no `text` column"))?; + let agent = column("agentId")?; + let category = column("category")?; + let importance = numbers("importance")?; + let created = numbers("createdAt")?; + + fn str_at(col: &Option, i: usize) -> Option { + let arr = col.as_ref()?.as_any().downcast_ref::()?; + (!arr.is_null(i)).then(|| arr.value(i).to_string()) + } + fn num_at(col: &Option, i: usize) -> Option { + let arr = col.as_ref()?.as_any().downcast_ref::()?; + (!arr.is_null(i)).then(|| arr.value(i)) + } + + let mut out = Vec::with_capacity(batch.num_rows()); + for i in 0..batch.num_rows() { + let row_id = str_at(&Some(id.clone()), i) + .filter(|s| !s.is_empty()) + .ok_or_else(|| Error::fatal(format!("memory connector: row {i} has no `id`")))?; + let row_text = str_at(&Some(text.clone()), i) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + Error::fatal(format!("memory connector: row {row_id} has no `text`")) + })?; + out.push(MemoryEntry { + id: row_id, + text: row_text, + agent: str_at(&agent, i), + category: str_at(&category, i), + importance: num_at(&importance, i), + created_at_ms: num_at(&created, i), + sensitivity: Tier::Internal, + }); + } + Ok(out) +} + +/// Blocking form of [`read_lancedb_store`] for the CLI and tests. +pub fn read_lancedb_store_blocking(path: &Path) -> Result> { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| Error::backend(format!("memory connector: tokio runtime: {e}")))? + .block_on(read_lancedb_store(path)) +} + +/// Read a native memory-lancedb dataset and idempotently sync its rows +/// into an already-provisioned Atlas staging database. +pub fn sync_lancedb_store_in_db( + store: &Path, + db: &Path, + unit_id: &str, + now: &str, +) -> Result { + let entries = read_lancedb_store_blocking(store)?; + let conn = open(db)?; + sync_memory_entries(&conn, unit_id, &entries, now) +} + +/// Sync entries into a unit, idempotently: an entry whose source_ref +/// is already staged with the same text is skipped; one whose text +/// changed is restaged (its old item and chunks removed first); a new +/// one is staged. Re-running with the same export changes nothing. +pub fn sync_memory_entries( + conn: &Connection, + unit_id: &str, + entries: &[MemoryEntry], + now: &str, +) -> Result { + check_stage_schema(conn)?; + let mut report = SyncReport::default(); + for entry in entries { + let source = entry.source_ref(); + let existing: Vec<(i64, String)> = { + let mut stmt = conn + .prepare("SELECT id, text FROM items WHERE unit_id = ?1 AND source = ?2") + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + let rows = stmt + .query_map(params![unit_id, source], |r| Ok((r.get(0)?, r.get(1)?))) + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + rows.collect::>() + .map_err(|e| Error::backend(format!("memory connector: {e}")))? + }; + match existing.as_slice() { + [] => { + stage_memory_entry(conn, unit_id, entry, now)?; + report.added += 1; + } + [(_, text)] if *text == entry.text => report.unchanged += 1, + old => { + for (item_id, _) in old { + conn.execute("DELETE FROM chunks_raw WHERE item_id = ?1", params![item_id]) + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + conn.execute("DELETE FROM items WHERE id = ?1", params![item_id]) + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + } + stage_memory_entry(conn, unit_id, entry, now)?; + report.restaged += 1; + } + } + } + Ok(report) +} diff --git a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs index 57b621aa2a..750f6fe856 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs @@ -327,3 +327,109 @@ fn promoted_agent_memory_is_searchable_by_the_fanout() { assert_eq!(hits[0].chunk_id, 1, "the transcript memory ranks first"); assert!(hits[0].dist < hits[1].dist); } + +/// Write a synthetic memory-lancedb-shaped dataset (the store's own +/// columns, including a vector the reader must ignore) into `path`. +fn write_fixture_store(path: &Path) { + use std::sync::Arc; + use arrow::array::{FixedSizeListArray, Float64Array, RecordBatch, RecordBatchIterator, StringArray}; + use arrow::datatypes::{DataType, Field, Schema}; + + let vec_field = Arc::new(Field::new("item", DataType::Float32, true)); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Utf8, false), + Field::new("text", DataType::Utf8, false), + Field::new("vector", DataType::FixedSizeList(vec_field.clone(), 3), true), + Field::new("importance", DataType::Float64, true), + Field::new("category", DataType::Utf8, true), + Field::new("createdAt", DataType::Float64, true), + Field::new("agentId", DataType::Utf8, true), + ])); + let values = arrow::array::Float32Array::from(vec![0.25f32, 0.5, 0.75, 0.1, 0.2, 0.3]); + let vectors = FixedSizeListArray::new(vec_field, 3, Arc::new(values), None); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(StringArray::from(vec!["mem-transcript", "mem-deploy"])), + Arc::new(StringArray::from(vec![ + "Continue the current task from the existing transcript, preserving completed work.", + "The deploy window opens on Sunday evening after the freeze lifts.", + ])), + Arc::new(vectors), + Arc::new(Float64Array::from(vec![0.9, 0.4])), + Arc::new(StringArray::from(vec!["fact", "fact"])), + Arc::new(Float64Array::from(vec![1_763_000_000_000.0, 1_763_100_000_000.0])), + Arc::new(StringArray::from(vec!["main", "main"])), + ], + ) + .unwrap(); + let reader = RecordBatchIterator::new(vec![Ok(batch)], schema); + let uri = path.to_str().unwrap().to_string(); + tokio::runtime::Runtime::new().unwrap().block_on(async { + lance::Dataset::write(reader, &uri, None).await.unwrap(); + }); +} + +/// Oracle: the native reader maps a `.lance` dataset's columns onto +/// the same entries the JSON export parser produces, and never reads +/// the vector column. +#[test] +fn native_reader_reads_a_lancedb_store_without_its_vectors() { + let dir = temp_dir("native"); + let store = dir.join("memories.lance"); + write_fixture_store(&store); + + let mut native = atlas_core::memory::read_lancedb_store_blocking(&store).unwrap(); + native.sort_by(|a, b| a.id.cmp(&b.id)); + let mut json = parse_memory_export(EXPORT).unwrap(); + json.sort_by(|a, b| a.id.cmp(&b.id)); + assert_eq!(native, json); +} + +/// Oracle: rebuild-from-sources — staging the native read into a +/// fresh unit and promoting it yields a searchable shard with the +/// same hits as the export path (the staged corpus is the source). +#[test] +fn native_store_rebuilds_the_index_from_sources() { + let dir = temp_dir("rebuild"); + let store = dir.join("memories.lance"); + write_fixture_store(&store); + let (registry, agent_db) = register(&dir); + let sync = atlas_core::memory::sync_lancedb_store_in_db( + &store, + &agent_db, + AGENT_MEMORY_UNIT, + NOW, + ) + .unwrap(); + assert_eq!((sync.added, sync.restaged, sync.unchanged), (2, 0, 0)); + let report = embed_unit_into_shard( + ®istry, AGENT_MEMORY_UNIT, &dir.join("shards"), "agent-memory", &KeywordEmbedder, NOW, + ) + .unwrap(); + assert_eq!(report.items, 2); + assert_eq!(report.chunks, 2); +} + +/// Oracle: idempotency — a second sync of an unchanged store restages +/// nothing; a changed text restages only that entry. +#[test] +fn sync_is_idempotent_and_restages_only_changed_entries() { + let dir = temp_dir("sync"); + let (_registry, agent_db) = register(&dir); + let conn = rusqlite::Connection::open(&agent_db).unwrap(); + let mut entries = parse_memory_export(EXPORT).unwrap(); + + let first = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + assert_eq!((first.added, first.restaged, first.unchanged), (2, 0, 0)); + + let again = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + assert_eq!((again.added, again.restaged, again.unchanged), (0, 0, 2)); + + entries[1].text = "The deploy window moved to Monday.".to_string(); + let changed = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + assert_eq!((changed.added, changed.restaged, changed.unchanged), (0, 1, 1)); + + let items = list_staged_items_in_db(&agent_db, Some(AGENT_MEMORY_UNIT)).unwrap(); + assert_eq!(items.len(), 2, "restaging replaces the old item"); +} 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 3bd4287b1e..c385c0f9c2 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 @@ -32,6 +32,9 @@ //! memory, carrying the design's provenance set. The export's //! vectors are ignored; promotion re-embeds with the mandated //! model. +//! * `atlas-stage ingest-memory-lancedb --db --unit +//! --store ` — natively read OpenClaw's LanceDB +//! dataset and idempotently sync changed rows into Atlas staging. //! * `atlas-stage items --db [--unit ]` — list the //! items staged in a unit's DB, with chunk counts. //! @@ -159,6 +162,18 @@ enum Command { #[arg(long)] export: PathBuf, }, + /// Natively read and idempotently sync an OpenClaw LanceDB store. + IngestMemoryLancedb { + /// The unit's staging database file (already provisioned). + #[arg(long)] + db: PathBuf, + /// The staging-unit id the entries belong to. + #[arg(long)] + unit: String, + /// The native memory-lancedb dataset path (typically memories.lance). + #[arg(long)] + store: PathBuf, + }, /// List the items staged in a unit's staging DB. Items { /// The staging database file to read. @@ -392,6 +407,20 @@ fn run(cli: Cli) -> Result<(), String> { ); Ok(()) } + Command::IngestMemoryLancedb { db, unit, store } => { + let report = atlas_core::memory::sync_lancedb_store_in_db( + &store, + &db, + &unit, + &now_utc(), + ) + .map_err(|e| e.to_string())?; + println!( + "{{\"unit\":{},\"added\":{},\"restaged\":{},\"unchanged\":{}}}", + json_str(&unit), report.added, report.restaged, report.unchanged, + ); + Ok(()) + } Command::Items { db, unit } => { let items = atlas_core::stage::list_staged_items_in_db(&db, unit.as_deref()) .map_err(|e| e.to_string())?; From 60e605b1b665f0ca8904653c71b4de2a862d4321 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 10:56:34 -0600 Subject: [PATCH 2/3] feat(atlas): ingest native agent-memory LanceDB --- .../book/reference/atlas-stage.md | 9 ++- .../crates/atlas-core/src/memory.rs | 62 ++++++++-------- .../crates/atlas-core/tests/memory.rs | 71 +++++++++++++++---- .../atlas-search/src/bin/atlas-stage.rs | 15 ++-- 4 files changed, 99 insertions(+), 58 deletions(-) diff --git a/pkgs/atlas-search/book/reference/atlas-stage.md b/pkgs/atlas-search/book/reference/atlas-stage.md index 2b9252b670..6c13ceb61f 100644 --- a/pkgs/atlas-search/book/reference/atlas-stage.md +++ b/pkgs/atlas-search/book/reference/atlas-stage.md @@ -4,7 +4,7 @@ Source: `pkgs/atlas-search/crates/atlas-search/src/bin/atlas-stage.rs`, with the `atlas-stage` provisions Atlas _staging units_ and reads the _staging registry_. A staging unit is one writer's isolated staging database: artifacts are staged into it first, classified there, and only later promoted into the core corpus. The registry is the store file that records every unit, its owner and its lifecycle state. The staging schema version is 1 (`STAGE_SCHEMA_VERSION`). The place of staging in the ingest flow is described in [Ingest today: staging, classification, promotion](../concepts/ingest.md). -**Where the source header disagrees with the source, the source wins.** The binary's own source header opens by describing "two verbs" and later says all of them are offline. Both framings are stale. The binary has **six** verbs — `provision`, `lookup`, `ingest`, `items`, `promote`, `units` — and `promote` is not offline in the header's sense: it needs the embedding model and the ONNX runtime, resolved over the filesystem (and potentially a local virtualenv path; see `promote` below). The header's verb list itself is complete; only its counts and framing are wrong. This chapter documents the six real verbs. +**Where the source header disagrees with the source, the source wins.** The binary has **seven** verbs — `provision`, `lookup`, `ingest`, `ingest-memory-lancedb`, `items`, `promote`, `units`. `promote` needs the embedding model and ONNX runtime (see below); `ingest-memory-lancedb` is limited to the `agent-memory` unit. This chapter documents the actual CLI. ## Invocation @@ -15,6 +15,7 @@ Commands: provision Create a staging DB, apply the v1 schema, and register the unit lookup Print one unit's registry record as JSON ingest Stage one code/config artifact file as an embedding entry + ingest-memory-lancedb Stage records from an agent-memory LanceDB store items List the items staged in a unit's staging DB promote Embed a unit's staged chunks into a new core scan shard and promote the unit to merged units List units in a lifecycle state (open|closing|merged) @@ -78,6 +79,12 @@ Stages one code/config artifact file as an embedding entry in an already-provisi | `--sensitivity` | `public\|internal\|secret` | `internal` | Staging tier vocabulary, as in `provision`. | | `--segments` | path | — (none) | Optional JSON file declaring the artifact's source-native classification segments: an array of `{"start": <byte>, "end": <byte>, "sensitivity": shareable\|personal\|local-only\|secret-bearing, "certain": <bool, default true>}` — note the segment sensitivities use the four-level ladder, not the tier vocabulary. When given, the artifact is staged classified: boundary-safe chunks plus one persisted classification record per chunk. Segment files are parsed strictly — missing or mistyped fields, or an unknown sensitivity name, are errors, never defaults. | +## `ingest-memory-lancedb` + +This command reads the native agent-memory LanceDB store and stages its records in the specified staging unit. It is intentionally restricted to the `agent-memory` unit; other unit IDs are rejected. Source provenance and rebuild metadata are retained, and repeating an ingest updates changed records without duplicating unchanged records. + +Consult `atlas-stage ingest-memory-lancedb --help` for the exact required flags and defaults; the CLI is the source of truth for the store, database and registry paths. + ## `items` ``` diff --git a/pkgs/atlas-search/crates/atlas-core/src/memory.rs b/pkgs/atlas-search/crates/atlas-core/src/memory.rs index 95c278cea9..98b6ad3cad 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/memory.rs @@ -457,8 +457,8 @@ pub async fn read_lancedb_store(path: &Path) -> Result> { .map_err(|e| Error::fatal(format!("memory connector: column `{name}`: {e}"))), } }; - let id = column("id")? - .ok_or_else(|| Error::fatal("memory connector: store has no `id` column"))?; + let id = + column("id")?.ok_or_else(|| Error::fatal("memory connector: store has no `id` column"))?; let text = column("text")? .ok_or_else(|| Error::fatal("memory connector: store has no `text` column"))?; let agent = column("agentId")?; @@ -467,11 +467,17 @@ pub async fn read_lancedb_store(path: &Path) -> Result> { let created = numbers("createdAt")?; fn str_at(col: &Option, i: usize) -> Option { - let arr = col.as_ref()?.as_any().downcast_ref::()?; + let arr = col + .as_ref()? + .as_any() + .downcast_ref::()?; (!arr.is_null(i)).then(|| arr.value(i).to_string()) } fn num_at(col: &Option, i: usize) -> Option { - let arr = col.as_ref()?.as_any().downcast_ref::()?; + let arr = col + .as_ref()? + .as_any() + .downcast_ref::()?; (!arr.is_null(i)).then(|| arr.value(i)) } @@ -482,9 +488,7 @@ pub async fn read_lancedb_store(path: &Path) -> Result> { .ok_or_else(|| Error::fatal(format!("memory connector: row {i} has no `id`")))?; let row_text = str_at(&Some(text.clone()), i) .filter(|s| !s.is_empty()) - .ok_or_else(|| { - Error::fatal(format!("memory connector: row {row_id} has no `text`")) - })?; + .ok_or_else(|| Error::fatal(format!("memory connector: row {row_id} has no `text`")))?; out.push(MemoryEntry { id: row_id, text: row_text, @@ -515,6 +519,11 @@ pub fn sync_lancedb_store_in_db( unit_id: &str, now: &str, ) -> Result { + if unit_id != AGENT_MEMORY_UNIT { + return Err(Error::fatal(format!( + "memory connector: native memory-lancedb rows must be staged in `{AGENT_MEMORY_UNIT}`" + ))); + } let entries = read_lancedb_store_blocking(store)?; let conn = open(db)?; sync_memory_entries(&conn, unit_id, &entries, now) @@ -533,33 +542,18 @@ pub fn sync_memory_entries( check_stage_schema(conn)?; let mut report = SyncReport::default(); for entry in entries { - let source = entry.source_ref(); - let existing: Vec<(i64, String)> = { - let mut stmt = conn - .prepare("SELECT id, text FROM items WHERE unit_id = ?1 AND source = ?2") - .map_err(|e| Error::backend(format!("memory connector: {e}")))?; - let rows = stmt - .query_map(params![unit_id, source], |r| Ok((r.get(0)?, r.get(1)?))) - .map_err(|e| Error::backend(format!("memory connector: {e}")))?; - rows.collect::>() - .map_err(|e| Error::backend(format!("memory connector: {e}")))? - }; - match existing.as_slice() { - [] => { - stage_memory_entry(conn, unit_id, entry, now)?; - report.added += 1; - } - [(_, text)] if *text == entry.text => report.unchanged += 1, - old => { - for (item_id, _) in old { - conn.execute("DELETE FROM chunks_raw WHERE item_id = ?1", params![item_id]) - .map_err(|e| Error::backend(format!("memory connector: {e}")))?; - conn.execute("DELETE FROM items WHERE id = ?1", params![item_id]) - .map_err(|e| Error::backend(format!("memory connector: {e}")))?; - } - stage_memory_entry(conn, unit_id, entry, now)?; - report.restaged += 1; - } + let exists: bool = conn + .query_row( + "SELECT EXISTS(SELECT 1 FROM items WHERE unit_id = ?1 AND kind = 'memory' AND source = ?2)", + params![unit_id, entry.source_ref()], + |row| row.get(0), + ) + .map_err(|e| Error::backend(format!("memory connector: {e}")))?; + let (_, changed) = stage_memory_entry_with_status(conn, unit_id, entry, now)?; + match (exists, changed) { + (false, true) => report.added += 1, + (true, true) => report.restaged += 1, + (_, false) => report.unchanged += 1, } } Ok(report) diff --git a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs index 750f6fe856..ff98e92682 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs @@ -331,15 +331,21 @@ fn promoted_agent_memory_is_searchable_by_the_fanout() { /// Write a synthetic memory-lancedb-shaped dataset (the store's own /// columns, including a vector the reader must ignore) into `path`. fn write_fixture_store(path: &Path) { - use std::sync::Arc; - use arrow::array::{FixedSizeListArray, Float64Array, RecordBatch, RecordBatchIterator, StringArray}; + use arrow::array::{ + FixedSizeListArray, Float64Array, RecordBatch, RecordBatchIterator, StringArray, + }; use arrow::datatypes::{DataType, Field, Schema}; + use std::sync::Arc; let vec_field = Arc::new(Field::new("item", DataType::Float32, true)); let schema = Arc::new(Schema::new(vec![ Field::new("id", DataType::Utf8, false), Field::new("text", DataType::Utf8, false), - Field::new("vector", DataType::FixedSizeList(vec_field.clone(), 3), true), + Field::new( + "vector", + DataType::FixedSizeList(vec_field.clone(), 3), + true, + ), Field::new("importance", DataType::Float64, true), Field::new("category", DataType::Utf8, true), Field::new("createdAt", DataType::Float64, true), @@ -395,16 +401,32 @@ fn native_store_rebuilds_the_index_from_sources() { let store = dir.join("memories.lance"); write_fixture_store(&store); let (registry, agent_db) = register(&dir); - let sync = atlas_core::memory::sync_lancedb_store_in_db( - &store, - &agent_db, - AGENT_MEMORY_UNIT, - NOW, - ) - .unwrap(); + let sync = + atlas_core::memory::sync_lancedb_store_in_db(&store, &agent_db, AGENT_MEMORY_UNIT, NOW) + .unwrap(); assert_eq!((sync.added, sync.restaged, sync.unchanged), (2, 0, 0)); + let staged = rusqlite::Connection::open(&agent_db).unwrap(); + let (source, raw_meta): (String, String) = staged + .query_row( + "SELECT source, meta FROM items WHERE unit_id = ?1 ORDER BY id LIMIT 1", + [AGENT_MEMORY_UNIT], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + let meta: serde_json::Value = serde_json::from_str(&raw_meta).unwrap(); + assert_eq!(meta["corpus"], "agent-memory"); + assert_eq!(meta["agent"], "main"); + assert_eq!(meta["source_ref"], source); + assert!(meta["updated_at"].is_string()); + assert_eq!(meta["sensitivity"], "internal"); + assert_eq!(meta["zone"], "fleet"); let report = embed_unit_into_shard( - ®istry, AGENT_MEMORY_UNIT, &dir.join("shards"), "agent-memory", &KeywordEmbedder, NOW, + ®istry, + AGENT_MEMORY_UNIT, + &dir.join("shards"), + "agent-memory", + &KeywordEmbedder, + NOW, ) .unwrap(); assert_eq!(report.items, 2); @@ -420,15 +442,34 @@ fn sync_is_idempotent_and_restages_only_changed_entries() { let conn = rusqlite::Connection::open(&agent_db).unwrap(); let mut entries = parse_memory_export(EXPORT).unwrap(); - let first = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + let first = + atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); assert_eq!((first.added, first.restaged, first.unchanged), (2, 0, 0)); - let again = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + let again = + atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); assert_eq!((again.added, again.restaged, again.unchanged), (0, 0, 2)); entries[1].text = "The deploy window moved to Monday.".to_string(); - let changed = atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); - assert_eq!((changed.added, changed.restaged, changed.unchanged), (0, 1, 1)); + let changed = + atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + assert_eq!( + (changed.added, changed.restaged, changed.unchanged), + (0, 1, 1) + ); + + entries[1].agent = Some("worker".to_owned()); + let metadata_changed = + atlas_core::memory::sync_memory_entries(&conn, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + assert_eq!( + ( + metadata_changed.added, + metadata_changed.restaged, + metadata_changed.unchanged + ), + (0, 1, 1), + "source metadata changes must restage only their own entry" + ); let items = list_staged_items_in_db(&agent_db, Some(AGENT_MEMORY_UNIT)).unwrap(); assert_eq!(items.len(), 2, "restaging replaces the old item"); 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 c385c0f9c2..fa5f961e1e 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 @@ -408,16 +408,15 @@ fn run(cli: Cli) -> Result<(), String> { Ok(()) } Command::IngestMemoryLancedb { db, unit, store } => { - let report = atlas_core::memory::sync_lancedb_store_in_db( - &store, - &db, - &unit, - &now_utc(), - ) - .map_err(|e| e.to_string())?; + let report = + atlas_core::memory::sync_lancedb_store_in_db(&store, &db, &unit, &now_utc()) + .map_err(|e| e.to_string())?; println!( "{{\"unit\":{},\"added\":{},\"restaged\":{},\"unchanged\":{}}}", - json_str(&unit), report.added, report.restaged, report.unchanged, + json_str(&unit), + report.added, + report.restaged, + report.unchanged, ); Ok(()) } From e04717cd346c76b9a83fe37e51d7cd87743fcea3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 10:55:09 +0000 Subject: [PATCH 3/3] feat(atlas): rebuild agent-memory index from sources (#14039) Rebuild-from-sources proof for the agent-memory corpus: a rebuild_agent_memory_index seam (register corpora, stage the source export through the replay-safe path, promote into a new core scan shard) returning chunk fingerprints, two oracle tests (same source rebuilds to the same shard + ranking; a revised source rebuilds to only the current rows), and an atlas-stage rebuild-memory operator verb. The native LanceDB reader stays follow-up work: it needs the lancedb/lance crate, an async runtime this sync workspace does not have, and a dependency tree that breaks the 30-minute atlas-search-pr.yml budget. --- .../crates/atlas-core/src/memory.rs | 135 +++++++++++++++- .../crates/atlas-core/tests/memory.rs | 144 +++++++++++++++++- .../atlas-search/src/bin/atlas-stage.rs | 72 ++++++++- 3 files changed, 337 insertions(+), 14 deletions(-) diff --git a/pkgs/atlas-search/crates/atlas-core/src/memory.rs b/pkgs/atlas-search/crates/atlas-core/src/memory.rs index 98b6ad3cad..6c4921745a 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 ff98e92682..4fb51f3fe4 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 fa5f961e1e..fb077d1bbd 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(()) + } } }