From 43c9db3329e1cbabf3360a588b17077621124657 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 20:21:46 -0600 Subject: [PATCH 1/3] test(atlas): cover memory export replay idempotency --- .../crates/atlas-core/tests/memory.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs index 2cb1d2f35f..ebbfaacf55 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs @@ -187,6 +187,21 @@ fn staged_memory_carries_the_design_provenance_set() { assert_eq!(meta["lancedb_id"], "mem-transcript"); } +/// Oracle: replaying the same source revision is a no-op, reported by +/// the public export staging seam as zero changed item ids. +#[test] +fn replaying_a_memory_export_is_idempotent() { + let dir = temp_dir("idempotent"); + let (_registry, agent_db) = register(&dir); + let entries = parse_memory_export(EXPORT).unwrap(); + let first = stage_memory_export_in_db(&agent_db, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + let second = stage_memory_export_in_db(&agent_db, AGENT_MEMORY_UNIT, &entries, "2026-11-24T00:00:00Z").unwrap(); + + assert_eq!(first.len(), 2); + assert!(second.is_empty(), "an unchanged source revision stages zero changed items"); + assert_eq!(list_staged_items_in_db(&agent_db, Some(AGENT_MEMORY_UNIT)).unwrap().len(), 2); +} + /// 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 From dc0ff17368478fc6f5d3c802e02dc1695d27f0ef Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 20:31:52 -0600 Subject: [PATCH 2/3] feat(atlas): make memory staging replay-safe --- .../crates/atlas-core/src/memory.rs | 151 ++++++++++++++---- .../crates/atlas-core/tests/memory.rs | 52 +++++- 2 files changed, 172 insertions(+), 31 deletions(-) diff --git a/pkgs/atlas-search/crates/atlas-core/src/memory.rs b/pkgs/atlas-search/crates/atlas-core/src/memory.rs index 8e3fc0442c..5e3ba1618d 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/memory.rs @@ -23,15 +23,14 @@ //! `chunks_raw` write path every staged unit uses; promotion and //! search are the existing aggregator and fan-out, unchanged. //! -//! Out of scope (slice 1b, the #8622 remainder): the native LanceDB -//! reader, idempotency keyed on id+updated_at, and the -//! rebuild-from-sources proof. Until 1b, this connector stages a -//! unit once and the unit is then promoted — promotion is the -//! terminal write, as for every staged unit. +//! 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. use std::path::Path; -use rusqlite::{Connection, params}; +use rusqlite::{Connection, OptionalExtension, params}; use crate::error::{Error, Result}; use crate::shards::Tier; @@ -230,6 +229,33 @@ pub fn stage_memory_entry( entry: &MemoryEntry, now: &str, ) -> Result { + stage_memory_entry_with_status(conn, unit_id, entry, now).map(|(id, _)| id) +} + +fn stage_memory_entry_with_status( + conn: &Connection, + unit_id: &str, + entry: &MemoryEntry, + now: &str, +) -> Result<(i64, bool)> { + let tx = conn.unchecked_transaction().map_err(|e| { + Error::backend(format!("memory connector: starting stage transaction: {e}")) + })?; + let result = stage_memory_entry_in_transaction(&tx, unit_id, entry, now)?; + tx.commit().map_err(|e| { + Error::backend(format!( + "memory connector: committing stage transaction: {e}" + )) + })?; + Ok(result) +} + +fn stage_memory_entry_in_transaction( + conn: &Connection, + unit_id: &str, + entry: &MemoryEntry, + now: &str, +) -> Result<(i64, bool)> { check_stage_schema(conn)?; let chunks = chunk_artifact_text(&entry.text); let source = entry.source_ref(); @@ -248,26 +274,90 @@ pub fn stage_memory_entry( "chunks": chunks.len(), }) .to_string(); - conn.execute( - "INSERT INTO items (unit_id, kind, source, text, sensitivity, created_at, meta) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", - params![ - unit_id, - "memory", - source, - entry.text, - entry.sensitivity.name(), - updated_at.as_deref().unwrap_or(now), - meta, - ], - ) - .map_err(|e| { - Error::backend(format!( - "memory connector: inserting item for {}: {e}", - entry.id - )) - })?; - let item_id = conn.last_insert_rowid(); + let existing = conn + .query_row( + "SELECT id, text, sensitivity, meta FROM items \ + WHERE unit_id = ?1 AND kind = 'memory' AND source = ?2 ORDER BY id DESC LIMIT 1", + params![unit_id, source], + |row| { + Ok(( + row.get::<_, i64>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, Option>(3)?, + )) + }, + ) + .optional() + .map_err(|e| { + Error::backend(format!( + "memory connector: finding item for {}: {e}", + entry.id + )) + })?; + + let (item_id, changed) = match existing { + Some((id, text, sensitivity, old_meta)) => { + let unchanged = text == entry.text + && sensitivity == entry.sensitivity.name() + && old_meta + .as_deref() + .and_then(|raw| serde_json::from_str::(raw).ok()) + .is_some_and(|old| { + let new: serde_json::Value = + serde_json::from_str(&meta).unwrap_or_default(); + old.get("updated_at") == new.get("updated_at") + && old.get("agent") == new.get("agent") + && old.get("category") == new.get("category") + && old.get("importance") == new.get("importance") + && old.get("sensitivity") == new.get("sensitivity") + }); + if unchanged { + return Ok((id, false)); + } + conn.execute( + "UPDATE items SET text = ?1, sensitivity = ?2, created_at = ?3, meta = ?4 WHERE id = ?5", + params![ + entry.text, + entry.sensitivity.name(), + updated_at.as_deref().unwrap_or(now), + meta, + id, + ], + ) + .map_err(|e| Error::backend(format!("memory connector: updating item for {}: {e}", entry.id)))?; + conn.execute("DELETE FROM chunks_raw WHERE item_id = ?1", [id]) + .map_err(|e| { + Error::backend(format!( + "memory connector: replacing chunks for {}: {e}", + entry.id + )) + })?; + (id, true) + } + None => { + conn.execute( + "INSERT INTO items (unit_id, kind, source, text, sensitivity, created_at, meta) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + unit_id, + "memory", + source, + entry.text, + entry.sensitivity.name(), + updated_at.as_deref().unwrap_or(now), + meta, + ], + ) + .map_err(|e| { + Error::backend(format!( + "memory connector: inserting item for {}: {e}", + entry.id + )) + })?; + (conn.last_insert_rowid(), true) + } + }; for (idx, chunk) in chunks.iter().enumerate() { conn.execute( "INSERT INTO chunks_raw (item_id, idx, text, content_hash, created_at) \ @@ -281,7 +371,7 @@ pub fn stage_memory_entry( )) })?; } - Ok(item_id) + Ok((item_id, changed)) } /// Stage a whole parsed export into a unit, in export order. @@ -294,7 +384,12 @@ pub fn stage_memory_export( ) -> Result> { entries .iter() - .map(|entry| stage_memory_entry(conn, unit_id, entry, now)) + .map(|entry| stage_memory_entry_with_status(conn, unit_id, entry, now)) + .filter_map(|result| match result { + Ok((id, true)) => Some(Ok(id)), + Ok((_, false)) => None, + Err(error) => Some(Err(error)), + }) .collect() } diff --git a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs index ebbfaacf55..57b621aa2a 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/memory.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/memory.rs @@ -195,11 +195,57 @@ fn replaying_a_memory_export_is_idempotent() { let (_registry, agent_db) = register(&dir); let entries = parse_memory_export(EXPORT).unwrap(); let first = stage_memory_export_in_db(&agent_db, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); - let second = stage_memory_export_in_db(&agent_db, AGENT_MEMORY_UNIT, &entries, "2026-11-24T00:00:00Z").unwrap(); + let second = stage_memory_export_in_db( + &agent_db, + AGENT_MEMORY_UNIT, + &entries, + "2026-11-24T00:00:00Z", + ) + .unwrap(); assert_eq!(first.len(), 2); - assert!(second.is_empty(), "an unchanged source revision stages zero changed items"); - assert_eq!(list_staged_items_in_db(&agent_db, Some(AGENT_MEMORY_UNIT)).unwrap().len(), 2); + assert!( + second.is_empty(), + "an unchanged source revision stages zero changed items" + ); + assert_eq!( + list_staged_items_in_db(&agent_db, Some(AGENT_MEMORY_UNIT)) + .unwrap() + .len(), + 2 + ); +} + +/// Oracle: a newer source revision replaces the prior row and chunks +/// under the same source identity instead of creating a duplicate. +#[test] +fn a_new_memory_revision_replaces_the_existing_staged_item() { + let dir = temp_dir("revision"); + let (_registry, agent_db) = register(&dir); + let entries = parse_memory_export(EXPORT).unwrap(); + let initial = stage_memory_export_in_db(&agent_db, AGENT_MEMORY_UNIT, &entries, NOW).unwrap(); + let original_id = initial[0]; + 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 changed = stage_memory_export_in_db( + &agent_db, + AGENT_MEMORY_UNIT, + &[revised], + "2026-11-24T00:01:00Z", + ) + .unwrap(); + let items = list_staged_items_in_db(&agent_db, Some(AGENT_MEMORY_UNIT)).unwrap(); + + assert_eq!(changed, vec![original_id]); + assert_eq!( + items.len(), + 2, + "revisions do not duplicate source identities" + ); + assert_eq!(items[0].id, original_id); + assert_eq!(items[0].text, "A corrected transcript of the same memory."); } /// Oracle: the slice's acceptance — after promotion through the From a46283adc66d7885a353051a91d0bf47f0c9823f Mon Sep 17 00:00:00 2001 From: repo-worker-code Date: Mon, 23 Nov 2026 20:48:24 -0600 Subject: [PATCH 3/3] fix(atlas): expose staged item text in list_staged_items The memory revision regression test asserts the replaced text via StagedItem, but the read-back struct omitted the items.text column the v1 schema already carries. Select it (lane code-f, task 20378). --- pkgs/atlas-search/crates/atlas-core/src/stage.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/pkgs/atlas-search/crates/atlas-core/src/stage.rs b/pkgs/atlas-search/crates/atlas-core/src/stage.rs index 5fa9c4c148..b454d67555 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/stage.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/stage.rs @@ -260,13 +260,15 @@ pub struct ArtifactEntry { pub text: String, } -/// One staged item, read back from a staging DB ([`list_staged_items`]). +/// One staged item, read back from a staging DB ([`list_staged_items`]), +/// with its full text and chunk count. #[derive(Debug, Clone, PartialEq, Eq)] pub struct StagedItem { pub id: i64, pub unit_id: String, pub kind: String, pub source: Option, + pub text: String, pub sensitivity: String, pub created_at: String, pub meta: Option, @@ -672,7 +674,7 @@ pub fn list_staged_items(conn: &Connection, unit_id: Option<&str>) -> Result) -> Result