Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 138 additions & 3 deletions pkgs/atlas-search/crates/atlas-core/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,23 @@
//!
//! 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.
//! when the source has no timestamp). 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. Reading the LanceDB store directory itself (the native
//! reader) remains 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 — a design slice of its own, not this one.

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::{
Expand Down Expand Up @@ -405,3 +415,128 @@ pub fn stage_memory_export_in_db(
let conn = open(db)?;
stage_memory_export(&conn, unit_id, entries, now)
}

/// 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<i64>,
/// 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<Vec<(String, String)>> {
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::<std::result::Result<Vec<_>, _>>()
.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<RebuildReport> {
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,
})
}
144 changes: 136 additions & 8 deletions pkgs/atlas-search/crates/atlas-core/tests/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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(
&registry,
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::<Vec<_>>(),
["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");
Expand Down
Loading