Skip to content
Merged
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
151 changes: 123 additions & 28 deletions pkgs/atlas-search/crates/atlas-core/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -230,6 +229,33 @@ pub fn stage_memory_entry(
entry: &MemoryEntry,
now: &str,
) -> Result<i64> {
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();
Expand All @@ -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<String>>(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::<serde_json::Value>(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) \
Expand All @@ -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.
Expand All @@ -294,7 +384,12 @@ pub fn stage_memory_export(
) -> Result<Vec<i64>> {
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()
}

Expand Down
15 changes: 9 additions & 6 deletions pkgs/atlas-search/crates/atlas-core/src/stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
pub text: String,
pub sensitivity: String,
pub created_at: String,
pub meta: Option<String>,
Expand Down Expand Up @@ -672,7 +674,7 @@ pub fn list_staged_items(conn: &Connection, unit_id: Option<&str>) -> Result<Vec
check_stage_schema(conn)?;
let mut stmt = conn
.prepare(
"SELECT i.id, i.unit_id, i.kind, i.source, i.sensitivity, i.created_at, i.meta, \
"SELECT i.id, i.unit_id, i.kind, i.source, i.text, i.sensitivity, i.created_at, i.meta, \
(SELECT COUNT(*) FROM chunks_raw c WHERE c.item_id = i.id) \
FROM items i WHERE (?1 IS NULL OR i.unit_id = ?1) ORDER BY i.id",
)
Expand All @@ -684,10 +686,11 @@ pub fn list_staged_items(conn: &Connection, unit_id: Option<&str>) -> Result<Vec
unit_id: r.get(1)?,
kind: r.get(2)?,
source: r.get(3)?,
sensitivity: r.get(4)?,
created_at: r.get(5)?,
meta: r.get(6)?,
chunk_count: r.get(7)?,
text: r.get(4)?,
sensitivity: r.get(5)?,
created_at: r.get(6)?,
meta: r.get(7)?,
chunk_count: r.get(8)?,
})
})
.map_err(|e| Error::backend(format!("staging: listing items: {e}")))?;
Expand Down
61 changes: 61 additions & 0 deletions pkgs/atlas-search/crates/atlas-core/tests/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,67 @@ 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: 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
/// aggregator (embed-at-promotion under the mandated model gate),
/// the production fan-out returns the agent-memory hit for a
Expand Down