From 99098e82f8fab93f426a973bdc01faf94ce63b4f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 11:05:51 -0600 Subject: [PATCH] feat(atlas-search): stable source-root + locator registration (#3125 slice 4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New atlas-core module `source_registry`: the registration layer the #3125 provenance programme's phase-4 resolution builds on. A source root is a stable named origin (a pinned repository, an extracts corpus); locators — the source strings occurrence rows carry — hang from a root. Registration is stable and additive only: - repeating a registration returns the first row unchanged (created: false), including its original registered_at; - re-pointing an existing root id to a different base locator is refused — it would rewrite the meaning of recorded locators; - a locator under an unknown root is refused; - registration never updates or deletes any row, in its own tables or any other table of the database it is given. Six oracle tests pin each property, including a non-alteration oracle that snapshots a seeded shard schema (chunks + chunk_occurrences, the aggregator's DDL) across registrations. Book: corpus-and-provenance chapter records the slice. --- .../book/concepts/corpus-and-provenance.md | 9 + .../atlas-search/crates/atlas-core/src/lib.rs | 5 + .../crates/atlas-core/src/source_registry.rs | 224 +++++++++++++++ .../atlas-core/tests/source_registry.rs | 263 ++++++++++++++++++ 4 files changed, 501 insertions(+) create mode 100644 pkgs/atlas-search/crates/atlas-core/src/source_registry.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/tests/source_registry.rs diff --git a/pkgs/atlas-search/book/concepts/corpus-and-provenance.md b/pkgs/atlas-search/book/concepts/corpus-and-provenance.md index 00a268a3cd..ee231757bb 100644 --- a/pkgs/atlas-search/book/concepts/corpus-and-provenance.md +++ b/pkgs/atlas-search/book/concepts/corpus-and-provenance.md @@ -115,6 +115,15 @@ recording its canonical text hash, source locator, byte span, and staged observation time. That slice is explicitly not the full criterion — historical occurrence recovery, canonical dedup identity, and the CAS/source-root registry remain open work. +A further slice landed the same day: the in-repo source registry +('s module) — stable source-root and +locator registration, where a root is a named origin (a pinned +repository, an extracts corpus) and locators hang from it. +Registration is idempotent and additive only: a repeat returns the +first registration unchanged, re-pointing a root or registering a +locator under an unknown root is refused, and registration never +alters existing chunk or occurrence data — each property pinned by +oracle tests. **Phase 2 — the extracts store and its backfill (landed 2026-11-23).** The extracts store lives on the laptop under `~/atlas/extracts/`. Objects are diff --git a/pkgs/atlas-search/crates/atlas-core/src/lib.rs b/pkgs/atlas-search/crates/atlas-core/src/lib.rs index 7006920074..f94380f880 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/lib.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/lib.rs @@ -63,6 +63,7 @@ pub mod owner_inventory; pub mod search; pub mod shards; pub mod shingles; +pub mod source_registry; pub mod stage; pub mod sweep; pub mod trace; @@ -139,6 +140,10 @@ pub use search::{ run_get_chunk_with_context, run_search, run_search_traced, run_search_with_executor, run_search_with_executor_traced, }; +pub use source_registry::{ + LocatorRegistration, RootRegistration, SOURCE_REGISTRY_DDL, SourceRoot, ensure_source_registry, + locators_for_root, register_locator, register_source_root, source_root, +}; pub use stage::{ ChunkClassification, REGISTRY_V1_DDL, Registry, STAGE_SCHEMA_VERSION, STAGE_V1_DDL, STAGE_V1_TABLES, StagingUnit, UnitState, check_stage_schema, chunk_classifications, diff --git a/pkgs/atlas-search/crates/atlas-core/src/source_registry.rs b/pkgs/atlas-search/crates/atlas-core/src/source_registry.rs new file mode 100644 index 0000000000..aea16e6584 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/source_registry.rs @@ -0,0 +1,224 @@ +//! The provenance source registry (developing-today/code#3125, +//! slice 4): stable source-root and source-locator registration. +//! +//! The occurrence registry ([`crate::aggregate`]'s shard-side +//! `chunk_occurrences`) records, for every promoted chunk, the source +//! locator it was found at. Locators hang from **source roots**: a +//! root is a stable named origin — a pinned repository +//! (`repo@commit`), an extracts corpus, a filesystem base — and a +//! locator is the full source string as it appears in occurrence +//! rows (a plain path, or the pinned form `repo:path@rev` the book's +//! corpus-and-provenance chapter uses). Phase 4 of #3125 resolves an +//! ID to a file, a chunk, or a section through a catalog; resolution +//! starts from knowing, stably, which roots and locators exist. This +//! module is that registration layer. +//! +//! The stability contract, which the oracle tests in +//! `tests/source_registry.rs` pin: +//! +//! - Registering the same root with the same base locator, or the +//! same locator under the same root, any number of times yields +//! exactly one row. The first registration wins: a repeat returns +//! the stored row unchanged (including its original +//! `registered_at`) and reports `created: false`. +//! - A root id may not be re-pointed: registering an existing root +//! id with a *different* base locator is refused, because silently +//! moving a root would rewrite the meaning of every locator and +//! occurrence already recorded under it. +//! - A locator may only be registered under a root that exists; +//! an unknown root is refused rather than leaving an orphan row +//! resolution could never anchor. +//! - Registration is additive only. It creates the two registry +//! tables when absent and inserts registration rows; it never +//! updates or deletes any row, in its own tables or in any other +//! table of the database it is given (the non-alteration oracle +//! snapshots a seeded shard schema — `chunks` plus +//! `chunk_occurrences` — across registrations). +//! +//! The registry lives in whichever database the caller opens — in +//! production the phase-4 catalog database; the functions here take +//! the connection, mirroring how [`crate::stage`] takes its unit +//! databases. + +use rusqlite::{Connection, OptionalExtension, params}; + +use crate::error::{Error, Result}; + +/// DDL for the source registry's two tables. The registry is code, +/// built once per database; only registrations are data. +pub const SOURCE_REGISTRY_DDL: &str = "CREATE TABLE IF NOT EXISTS source_roots (\ + root_id TEXT PRIMARY KEY, \ + base_locator TEXT NOT NULL, \ + registered_at TEXT NOT NULL); \ + CREATE TABLE IF NOT EXISTS source_locators (\ + root_id TEXT NOT NULL REFERENCES source_roots(root_id), \ + locator TEXT NOT NULL, \ + registered_at TEXT NOT NULL, \ + PRIMARY KEY (root_id, locator))"; + +/// One registered source root: a stable id, the base locator every +/// locator under it hangs from, and when it was first registered. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SourceRoot { + pub root_id: String, + pub base_locator: String, + pub registered_at: String, +} + +/// The outcome of a root registration: the stored root (the first +/// registration's row on a repeat) and whether this call created it. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RootRegistration { + pub root: SourceRoot, + pub created: bool, +} + +/// The outcome of a locator registration: whether this call created +/// the row. A repeat leaves the stored row — including its original +/// `registered_at` — untouched. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct LocatorRegistration { + pub created: bool, +} + +/// Create the registry tables in `conn`'s database when absent. +/// Idempotent and additive: existing tables and rows are untouched. +pub fn ensure_source_registry(conn: &Connection) -> Result<()> { + conn.execute_batch(SOURCE_REGISTRY_DDL) + .map_err(|e| Error::backend(format!("source registry: creating tables: {e}"))) +} + +fn require_non_empty(field: &str, value: &str) -> Result<()> { + if value.trim().is_empty() { + return Err(Error::fatal(format!( + "source registry: {field} must not be empty" + ))); + } + Ok(()) +} + +/// Read one root back, or `None` when it was never registered. +pub fn source_root(conn: &Connection, root_id: &str) -> Result> { + ensure_source_registry(conn)?; + conn.query_row( + "SELECT root_id, base_locator, registered_at FROM source_roots WHERE root_id = ?1", + params![root_id], + |r| { + Ok(SourceRoot { + root_id: r.get(0)?, + base_locator: r.get(1)?, + registered_at: r.get(2)?, + }) + }, + ) + .optional() + .map_err(|e| Error::backend(format!("source registry: reading root {root_id:?}: {e}"))) +} + +/// Register a source root, stably. +/// +/// The first registration stores `(root_id, base_locator, +/// registered_at)` and reports `created: true`. A repeat with the +/// same base locator returns the stored row with `created: false` +/// and changes nothing — the original `registered_at` stands. A +/// repeat with a different base locator is refused: a root id may +/// not be re-pointed. +pub fn register_source_root( + conn: &Connection, + root_id: &str, + base_locator: &str, + registered_at: &str, +) -> Result { + require_non_empty("root_id", root_id)?; + require_non_empty("base_locator", base_locator)?; + require_non_empty("registered_at", registered_at)?; + ensure_source_registry(conn)?; + if let Some(existing) = source_root(conn, root_id)? { + if existing.base_locator != base_locator { + return Err(Error::fatal(format!( + "source registry: root {root_id:?} is already registered with base locator \ + {:?}; refusing to re-point it to {base_locator:?}", + existing.base_locator + ))); + } + return Ok(RootRegistration { + root: existing, + created: false, + }); + } + conn.execute( + "INSERT INTO source_roots (root_id, base_locator, registered_at) VALUES (?1, ?2, ?3)", + params![root_id, base_locator, registered_at], + ) + .map_err(|e| { + Error::backend(format!( + "source registry: registering root {root_id:?}: {e}" + )) + })?; + Ok(RootRegistration { + root: SourceRoot { + root_id: root_id.to_owned(), + base_locator: base_locator.to_owned(), + registered_at: registered_at.to_owned(), + }, + created: true, + }) +} + +/// Register a source locator under an existing root, stably. +/// +/// The first registration stores the `(root_id, locator)` row and +/// reports `created: true`. A repeat returns `created: false` and +/// changes nothing. Registering under a root that does not exist is +/// refused — a locator with no root could never be resolved. +pub fn register_locator( + conn: &Connection, + root_id: &str, + locator: &str, + registered_at: &str, +) -> Result { + require_non_empty("root_id", root_id)?; + require_non_empty("locator", locator)?; + require_non_empty("registered_at", registered_at)?; + ensure_source_registry(conn)?; + if source_root(conn, root_id)?.is_none() { + return Err(Error::fatal(format!( + "source registry: refusing to register locator {locator:?} under unknown root \ + {root_id:?}; register the root first" + ))); + } + let inserted = conn + .execute( + "INSERT OR IGNORE INTO source_locators (root_id, locator, registered_at) \ + VALUES (?1, ?2, ?3)", + params![root_id, locator, registered_at], + ) + .map_err(|e| { + Error::backend(format!( + "source registry: registering locator {locator:?} under root {root_id:?}: {e}" + )) + })?; + Ok(LocatorRegistration { + created: inserted == 1, + }) +} + +/// The locators registered under one root, sorted — the stable +/// order resolution and listings consume. An unknown root yields an +/// empty list. +pub fn locators_for_root(conn: &Connection, root_id: &str) -> Result> { + ensure_source_registry(conn)?; + let mut stmt = conn + .prepare("SELECT locator FROM source_locators WHERE root_id = ?1 ORDER BY locator") + .map_err(|e| Error::backend(format!("source registry: listing locators: {e}")))?; + let rows = stmt + .query_map(params![root_id], |r| r.get::<_, String>(0)) + .map_err(|e| Error::backend(format!("source registry: listing locators: {e}")))?; + let mut locators = Vec::new(); + for row in rows { + locators.push( + row.map_err(|e| Error::backend(format!("source registry: listing locators: {e}")))?, + ); + } + Ok(locators) +} diff --git a/pkgs/atlas-search/crates/atlas-core/tests/source_registry.rs b/pkgs/atlas-search/crates/atlas-core/tests/source_registry.rs new file mode 100644 index 0000000000..7b72a7b1ec --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/tests/source_registry.rs @@ -0,0 +1,263 @@ +//! Oracle tests for the provenance source registry (#3125 slice 4): +//! source-root and source-locator registration is stable — the same +//! registration repeated yields exactly one stored row, the first +//! registration's data wins — and registration is additive only: it +//! never alters existing data, proven against a seeded shard schema +//! (`chunks` + `chunk_occurrences`, the DDL the aggregator writes) +//! snapshotted across registrations. + +use std::path::PathBuf; + +use atlas_core::source_registry::{ + ensure_source_registry, locators_for_root, register_locator, register_source_root, source_root, +}; +use rusqlite::{Connection, params}; + +const T1: &str = "2026-11-23T00:00:00Z"; +const T2: &str = "2026-11-24T00:00:00Z"; + +fn temp_db(tag: &str) -> (PathBuf, Connection) { + let dir = std::env::temp_dir().join(format!( + "atlas-source-registry-{}-{tag}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("temp dir"); + let path = dir.join("registry.db"); + let conn = Connection::open(&path).expect("open registry db"); + (path, conn) +} + +fn count(conn: &Connection, table: &str) -> i64 { + conn.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0)) + .expect("count rows") +} + +#[test] +fn registration_is_stable_and_idempotent() { + let (_path, conn) = temp_db("stable"); + + let first = register_source_root( + &conn, + "code-repo", + "developing-today/code@d85bd4ff1f3b73700f881aa99357adeae997e1bd", + T1, + ) + .unwrap(); + assert!(first.created); + assert_eq!(first.root.registered_at, T1); + + // A repeat with a later clock changes nothing: the stored row is + // the first registration's, byte for byte. + let repeat = register_source_root( + &conn, + "code-repo", + "developing-today/code@d85bd4ff1f3b73700f881aa99357adeae997e1bd", + T2, + ) + .unwrap(); + assert!(!repeat.created); + assert_eq!(repeat.root, first.root); + assert_eq!(count(&conn, "source_roots"), 1); + + let loc = "developing-today/code:doc/notes.md@d85bd4ff1f3b73700f881aa99357adeae997e1bd"; + let first_loc = register_locator(&conn, "code-repo", loc, T1).unwrap(); + assert!(first_loc.created); + let repeat_loc = register_locator(&conn, "code-repo", loc, T2).unwrap(); + assert!(!repeat_loc.created); + assert_eq!(count(&conn, "source_locators"), 1); + // The stored registered_at is still the first registration's. + let stored_at: String = conn + .query_row( + "SELECT registered_at FROM source_locators WHERE root_id = ?1 AND locator = ?2", + params!["code-repo", loc], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(stored_at, T1); +} + +#[test] +fn registration_never_alters_existing_data() { + let (_path, conn) = temp_db("non-alteration"); + // Seed the shard schema the aggregator writes (#3125 slice 2), + // with data, in the same database the registry will live in. + conn.execute_batch( + "CREATE TABLE chunks (id INTEGER PRIMARY KEY, message_id TEXT NOT NULL, \ + chunk_idx INTEGER, text TEXT NOT NULL, content_hash TEXT UNIQUE NOT NULL, \ + sensitivity TEXT); \ + CREATE TABLE chunk_occurrences ( \ + shard_chunk_id INTEGER NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, \ + canonical_hash TEXT NOT NULL, source TEXT NOT NULL, \ + span_start INTEGER NOT NULL, span_end INTEGER NOT NULL, observed_at TEXT NOT NULL, \ + PRIMARY KEY (shard_chunk_id, source, span_start));", + ) + .unwrap(); + conn.execute( + "INSERT INTO chunks VALUES (1, 'msg-1', 0, 'hello provenance', 'hash-1', 'internal')", + [], + ) + .unwrap(); + conn.execute( + "INSERT INTO chunk_occurrences VALUES (1, 'hash-1', \ + 'developing-today/code:doc/notes.md@d85bd4ff1f3b73700f881aa99357adeae997e1bd', \ + 0, 16, ?1)", + params![T1], + ) + .unwrap(); + + let snapshot = |conn: &Connection| -> (Vec>, Vec>) { + let dump = |table: &str, cols: &str| -> Vec> { + let mut stmt = conn + .prepare(&format!("SELECT {cols} FROM {table} ORDER BY 1, 2")) + .unwrap(); + let n = stmt.column_count(); + let rows = stmt + .query_map([], |r| { + let mut row = Vec::new(); + for i in 0..n { + let v = r.get::<_, rusqlite::types::Value>(i)?; + row.push(match v { + rusqlite::types::Value::Text(s) => s, + rusqlite::types::Value::Integer(v) => v.to_string(), + other => format!("{other:?}"), + }); + } + Ok(row) + }) + .unwrap(); + rows.map(|r| r.unwrap()).collect() + }; + ( + dump( + "chunks", + "id, message_id, chunk_idx, text, content_hash, sensitivity", + ), + dump( + "chunk_occurrences", + "shard_chunk_id, canonical_hash, source, span_start, span_end, observed_at", + ), + ) + }; + let before = snapshot(&conn); + + // New registrations and repeats alike must leave the seeded + // tables byte-identical. + register_source_root( + &conn, + "code-repo", + "developing-today/code@d85bd4ff1f3b73700f881aa99357adeae997e1bd", + T1, + ) + .unwrap(); + register_locator( + &conn, + "code-repo", + "developing-today/code:doc/notes.md@d85bd4ff1f3b73700f881aa99357adeae997e1bd", + T1, + ) + .unwrap(); + register_source_root( + &conn, + "code-repo", + "developing-today/code@d85bd4ff1f3b73700f881aa99357adeae997e1bd", + T2, + ) + .unwrap(); + register_locator( + &conn, + "code-repo", + "developing-today/code:doc/notes.md@d85bd4ff1f3b73700f881aa99357adeae997e1bd", + T2, + ) + .unwrap(); + + assert_eq!(snapshot(&conn), before, "existing data is untouched"); +} + +#[test] +fn conflicting_root_repoint_is_refused() { + let (_path, conn) = temp_db("repoint"); + register_source_root(&conn, "code-repo", "developing-today/code@aaaa", T1).unwrap(); + let err = register_source_root(&conn, "code-repo", "developing-today/code@bbbb", T2) + .expect_err("re-pointing a root must be refused"); + assert!( + err.to_string().contains("refusing to re-point"), + "unexpected error: {err}" + ); + // The original registration stands, unaltered. + let stored = source_root(&conn, "code-repo").unwrap().unwrap(); + assert_eq!(stored.base_locator, "developing-today/code@aaaa"); + assert_eq!(stored.registered_at, T1); + assert_eq!(count(&conn, "source_roots"), 1); +} + +#[test] +fn locator_under_unknown_root_is_refused() { + let (_path, conn) = temp_db("unknown-root"); + let err = register_locator(&conn, "nope", "some/path.md", T1) + .expect_err("a locator under an unknown root must be refused"); + assert!( + err.to_string().contains("unknown root"), + "unexpected error: {err}" + ); + assert_eq!(count(&conn, "source_locators"), 0); +} + +#[test] +fn locators_resolve_under_their_root() { + let (_path, conn) = temp_db("resolve"); + ensure_source_registry(&conn).unwrap(); + register_source_root(&conn, "code-repo", "developing-today/code@aaaa", T1).unwrap(); + register_source_root(&conn, "extracts", "laptop-extracts/sandbox-agents", T1).unwrap(); + register_locator( + &conn, + "code-repo", + "developing-today/code:doc/notes.md@aaaa", + T1, + ) + .unwrap(); + register_locator( + &conn, + "code-repo", + "developing-today/code:Cargo.toml@aaaa", + T1, + ) + .unwrap(); + register_locator(&conn, "extracts", "sandbox-agents/run-1/log.txt", T1).unwrap(); + + // Sorted, and separated per root. + assert_eq!( + locators_for_root(&conn, "code-repo").unwrap(), + vec![ + "developing-today/code:Cargo.toml@aaaa".to_string(), + "developing-today/code:doc/notes.md@aaaa".to_string(), + ] + ); + assert_eq!( + locators_for_root(&conn, "extracts").unwrap(), + vec!["sandbox-agents/run-1/log.txt".to_string()] + ); + // Unknown roots resolve to nothing rather than erroring. + assert!(locators_for_root(&conn, "nope").unwrap().is_empty()); + assert!(source_root(&conn, "nope").unwrap().is_none()); + assert_eq!( + source_root(&conn, "extracts") + .unwrap() + .unwrap() + .base_locator, + "laptop-extracts/sandbox-agents" + ); +} + +#[test] +fn empty_fields_are_refused() { + let (_path, conn) = temp_db("empty"); + assert!(register_source_root(&conn, "", "base", T1).is_err()); + assert!(register_source_root(&conn, "root", " ", T1).is_err()); + assert!(register_source_root(&conn, "root", "base", "").is_err()); + register_source_root(&conn, "root", "base", T1).unwrap(); + assert!(register_locator(&conn, "root", "", T1).is_err()); + assert_eq!(count(&conn, "source_roots"), 1); + assert_eq!(count(&conn, "source_locators"), 0); +}