diff --git a/pkgs/atlas-search/crates/atlas-core/src/backend.rs b/pkgs/atlas-search/crates/atlas-core/src/backend.rs index 41039f2186..7d5f23bc04 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/backend.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/backend.rs @@ -7,6 +7,9 @@ use crate::error::Result; use crate::filters::Filters; +use crate::filters::Sensitivity; +use crate::occurrences::ChunkOccurrence; +use crate::shards::TierCeiling; use crate::types::{BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow}; /// The window (in chunk_idx units) the default @@ -81,6 +84,23 @@ pub trait SearchBackend { self.neighbors(message_id, 0, MESSAGE_CHUNKS_WINDOW) } + /// Every recorded occurrence of the chunk content whose + /// canonical hash is `canonical_hash` (#3125): the shard + /// fan-out answers from its `chunk_occurrences` registries + /// under `ceiling`; every other backend answers empty. + /// `ceiling` admits a shard only under the SAME tier ladder + /// the vector fan-out enforces, so a restricted caller never + /// learns higher-tier source locators from a hash it holds. + fn occurrences( + &self, + canonical_hash: &str, + tier_ceiling: TierCeiling, + caller_ceiling: Sensitivity, + ) -> Result> { + let _ = (canonical_hash, tier_ceiling, caller_ceiling); + Ok(Vec::new()) + } + /// One message row by id (for `--with-message` payloads). fn message(&self, message_id: &str) -> Result>; } @@ -114,6 +134,14 @@ impl SearchBackend for Box { fn message_chunks(&self, message_id: &str) -> Result> { (**self).message_chunks(message_id) } + fn occurrences( + &self, + canonical_hash: &str, + tier_ceiling: TierCeiling, + caller_ceiling: Sensitivity, + ) -> Result> { + (**self).occurrences(canonical_hash, tier_ceiling, caller_ceiling) + } fn message(&self, message_id: &str) -> Result> { (**self).message(message_id) } diff --git a/pkgs/atlas-search/crates/atlas-core/src/lib.rs b/pkgs/atlas-search/crates/atlas-core/src/lib.rs index 7006920074..de4f837962 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/lib.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/lib.rs @@ -59,6 +59,7 @@ pub mod join; pub mod local; pub mod manifest; pub mod memory; +pub mod occurrences; pub mod owner_inventory; pub mod search; pub mod shards; @@ -134,6 +135,7 @@ pub use manifest::{ pub use owner_inventory::{ INVENTORY_FORMAT, OwnerInventory, OwnerInventoryFinding, PatternClass, SECRET_REFERENCE_ENV, }; +pub use occurrences::{ChunkOccurrence, lookup_by_hash}; pub use search::{ BackendBranchExecutor, BranchPoolExecutor, SearchMode, SearchOptions, TraceJob, run_get_chunk, run_get_chunk_with_context, run_search, run_search_traced, run_search_with_executor, diff --git a/pkgs/atlas-search/crates/atlas-core/src/occurrences.rs b/pkgs/atlas-search/crates/atlas-core/src/occurrences.rs new file mode 100644 index 0000000000..d3a671716d --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/occurrences.rs @@ -0,0 +1,145 @@ +//! Reading the `chunk_occurrences` provenance registry (#3125): +//! the rows the aggregator's promotion writes (aggregate.rs) are +//! resolved back to "every place this content was found" — the +//! read side rule 3 requires. +//! +//! The lookup key is the **canonical hash** (SHA-256 of the piece +//! text, the same digest the aggregator records), not a chunk id: +//! chunk ids are unique only within one shard, while the canonical +//! hash is global content identity. A lookup fans out over the +//! shards a caller's ceiling admits, reads each shard's +//! `chunk_occurrences_hash` index, and tolerates shards promoted +//! before the registry existed (no `chunk_occurrences` table): +//! they contribute no rows, never an error — a provenance read +//! must not take search down with it. + +use serde_json::Value as Json; + +use crate::error::{Error, Result}; +use crate::filters::Sensitivity; +use crate::shards::{ShardSet, Tier, TierCeiling}; +use crate::types::{Stmt, Value}; + +/// One recorded place a chunk's content was found (#3125 rule 3). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChunkOccurrence { + /// The shard that recorded the occurrence. + pub shard: String, + /// That shard's physical tier. + pub tier: Tier, + /// SHA-256 of the piece text (content identity, the lookup key). + pub canonical_hash: String, + /// The source locator: `repo@commit:path`, `system@host@date`, + /// or `unit:` for unit-staged items without a source. + pub source: String, + /// Byte offsets in the original staged item. + pub span_start: i64, + pub span_end: i64, + /// When the aggregator observed the content. + pub observed_at: String, +} + +impl ChunkOccurrence { + /// The wire form `get-chunk` attaches as one `occurrences` + /// array element. + pub fn to_json(&self) -> Json { + serde_json::json!({ + "shard": self.shard, + "tier": self.tier.name(), + "canonical_hash": self.canonical_hash, + "source": self.source, + "span_start": self.span_start, + "span_end": self.span_end, + "observed_at": self.observed_at, + }) + } +} + +/// Every recorded occurrence of the content whose canonical hash +/// is `canonical_hash`, across the shards `tier_ceiling` admits, in a +/// deterministic order (shard, source, span_start). Shards with +/// no `chunk_occurrences` table (promoted before the registry) +/// are skipped; a shard that answers with a genuine failure fails +/// the lookup — a partial provenance answer is as wrong as a +/// partial search answer. +/// +/// `caller_ceiling` is the full Sensitivity ladder ceiling (the +/// intersection of the caller's grant and the disclosure context). +/// Each occurrence is joined to its referenced chunk and the chunk's +/// per-row sensitivity is checked against this ceiling — an admitted +/// physical shard can contain chunks classified above the caller's +/// ceiling (promotion names the shard from unit.sensitivity but +/// writes each chunk's effective sensitivity separately). +pub fn lookup_by_hash( + set: &ShardSet, + tier_ceiling: TierCeiling, + caller_ceiling: Sensitivity, + canonical_hash: &str, +) -> Result> { + let mut out = Vec::new(); + for shard in set.select(tier_ceiling, None)? { + let Some(transport) = set.transport(&shard.name) else { + return Err(Error::backend(format!( + "occurrences: {} has no open transport", + shard.name + ))); + }; + // Join occurrences to chunks to enforce per-row sensitivity. + // The occurrence row has shard_chunk_id -> chunks.id. + let stmt = Stmt::new( + "SELECT o.source, o.span_start, o.span_end, o.observed_at, c.sensitivity \ + FROM chunk_occurrences o \ + JOIN chunks c ON c.id = o.shard_chunk_id \ + WHERE o.canonical_hash = ?1 \ + ORDER BY o.source, o.span_start", + vec![Value::text(canonical_hash)], + ); + let rows = match transport.pipeline(&[stmt]) { + Ok(mut batches) => batches.pop().unwrap_or_default(), + Err(e) => { + let msg = e.to_string(); + if msg.contains("no such table") && msg.contains("chunk_occurrences") { + // A shard promoted before the registry (#3125 + // slice 2): no rows to contribute. + continue; + } + return Err(Error::backend(format!("occurrences: {}: {e}", shard.name))); + } + }; + for r in rows { + let (Some(source), Some(observed_at), Some(chunk_sens)) = ( + r.get_text("source"), + r.get_text("observed_at"), + r.get_text("sensitivity"), + ) else { + return Err(Error::backend(format!( + "occurrences: {}: malformed occurrence row", + shard.name + ))); + }; + // Fail-closed: unrecognized sensitivity -> SecretBearing (excluded by caller_ceiling) + let chunk_sensitivity = + Sensitivity::from_name(chunk_sens).unwrap_or(Sensitivity::SecretBearing); + if chunk_sensitivity > caller_ceiling { + // This occurrence references a chunk above the caller's ceiling — withhold. + continue; + } + out.push(ChunkOccurrence { + shard: shard.name.clone(), + tier: shard.tier, + canonical_hash: canonical_hash.to_string(), + source: source.to_string(), + span_start: r.get_i64("span_start").unwrap_or_default(), + span_end: r.get_i64("span_end").unwrap_or_default(), + observed_at: observed_at.to_string(), + }); + } + } + out.sort_by(|a, b| { + a.shard + .cmp(&b.shard) + .then(a.source.cmp(&b.source)) + .then(a.span_start.cmp(&b.span_start)) + }); + Ok(out) +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/search.rs b/pkgs/atlas-search/crates/atlas-core/src/search.rs index 2a6ed16e96..8e9c6fc778 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/search.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/search.rs @@ -21,6 +21,7 @@ use crate::trace::{TraceContext, TraceSink, build_trace_record, new_query_id}; use crate::types::{ BranchPools, BranchQuery, ChunkDetail, DEFAULT_MODEL, NeighborRow, VectorBackend, round6, }; +use crate::{classify::sha256_hex, shards::TierCeiling}; /// The Python's `MESSAGE_TEXT_CAP`. pub const MESSAGE_TEXT_CAP: usize = 50_000; @@ -657,7 +658,13 @@ fn hydrate_entry( /// `excluded_personal_life` content, ineligible in every /// context (design section 4). pub fn run_get_chunk(backend: &dyn SearchBackend, chunk_id: i64, neighbors: usize) -> Result { - run_get_chunk_with_context(backend, chunk_id, neighbors, DisclosureContext::LocalOwner) + run_get_chunk_with_context( + backend, + chunk_id, + neighbors, + DisclosureContext::LocalOwner, + Sensitivity::SecretBearing, + ) } /// `run_get_chunk` under an explicit disclosure context: the @@ -665,11 +672,19 @@ pub fn run_get_chunk(backend: &dyn SearchBackend, chunk_id: i64, neighbors: usiz /// chunk reads exactly like a missing one — the lookup must not /// confirm that classified content exists), and neighbor /// expansion is filtered by each neighbor's own classification. +/// +/// `grant` is the caller's sensitivity ceiling. `get-chunk` stays +/// an explicit-id tool with no caller ceiling on the chunk gate +/// (the context alone decides, as the Python did), but every +/// derived payload — occurrence provenance and neighbor +/// expansion — is bounded by grant ∩ context, so a narrower +/// caller never learns higher-ceiling source locators. pub fn run_get_chunk_with_context( backend: &dyn SearchBackend, chunk_id: i64, neighbors: usize, context: DisclosureContext, + grant: Sensitivity, ) -> Result { let details = backend.chunk_details(&[chunk_id])?; let Some(d) = details.iter().find(|d| d.chunk_id == chunk_id) else { @@ -678,6 +693,7 @@ pub fn run_get_chunk_with_context( if !context.permits(chunk_classification(d.eff_sensitivity.as_deref())) { return Err(Error::fatal(format!("chunk {chunk_id} not found"))); } + let effective = context.effective_ceiling(grant); let mut msg = Map::new(); msg.insert("id".into(), Json::String(d.message_id.clone())); msg.insert( @@ -694,10 +710,28 @@ pub fn run_get_chunk_with_context( out.insert("message".into(), Json::Object(msg)); out.insert("session".into(), session_obj(d)); out.insert("session_id".into(), Json::String(d.session_id.clone())); + // #3125 rule 3 read side: every recorded place this chunk's + // content was found. The lookup key is the canonical hash + // (content identity, not the per-shard chunk id); the caller's + // ceiling gates which tiers may contribute, exactly as the + // vector fan-out enforces it. Backends with no registry + // (monolith, local publish) report none, and the field is + // then absent rather than empty — same shape rule as `notes`. + let occurrences = backend.occurrences( + &sha256_hex(d.text.as_bytes()), + TierCeiling::from_sensitivity(effective), + effective, + )?; + if !occurrences.is_empty() { + out.insert( + "occurrences".into(), + Json::Array(occurrences.iter().map(|o| o.to_json()).collect()), + ); + } if neighbors > 0 { out.insert( "context".into(), - neighbor_map(backend, d, neighbors, context, context.ceiling())?, + neighbor_map(backend, d, neighbors, context, effective)?, ); } let notes = backend.notes(); diff --git a/pkgs/atlas-search/crates/atlas-core/src/shards/scan.rs b/pkgs/atlas-search/crates/atlas-core/src/shards/scan.rs index 84b5f6dd80..f66bdc71ca 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/shards/scan.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/shards/scan.rs @@ -525,6 +525,28 @@ impl SearchBackend for ShardedBackend { } self.inner.message(message_id) } + + /// #3125 rule 3 read side: resolve a canonical content hash + /// against every shard the caller's ceiling admits. Occurrence + /// rows live in the scan shards themselves (written at + /// promotion, aggregate.rs), so this is one indexed lookup per + /// shard — no content-store or monolith involvement. The + /// ceiling is the caller's, enforced inside + /// [`lookup_by_hash`] exactly as the vector fan-out enforces + /// it in [`ShardSet::select`]. + fn occurrences( + &self, + canonical_hash: &str, + tier_ceiling: TierCeiling, + caller_ceiling: crate::filters::Sensitivity, + ) -> Result> { + crate::occurrences::lookup_by_hash( + &self.current_set(), + tier_ceiling, + caller_ceiling, + canonical_hash, + ) + } } #[cfg(test)] diff --git a/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs b/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs index 44d9a6e967..5e2ea926aa 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs @@ -24,7 +24,8 @@ use atlas_core::types::{ BranchHit, BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow, }; use atlas_core::{ - DisclosureContext, SearchMode, SearchOptions, run_get_chunk_with_context, run_search, + DisclosureContext, SearchMode, SearchOptions, Sensitivity, run_get_chunk_with_context, + run_search, }; use atlas_proto::RawMode; use serde_json::Value as Json; @@ -339,26 +340,56 @@ fn get_chunk_gates_on_context_and_never_serves_excluded() { // Excluded: not found even for the owner — and the error is // the same shape as a missing chunk, so the lookup cannot // confirm the content exists. - let err = run_get_chunk_with_context(&LeakBackend, 5, 0, DisclosureContext::LocalOwner) - .expect_err("excluded chunk must not be served"); + let err = run_get_chunk_with_context( + &LeakBackend, + 5, + 0, + DisclosureContext::LocalOwner, + Sensitivity::SecretBearing, + ) + .expect_err("excluded chunk must not be served"); assert_eq!(err.to_string(), "chunk 5 not found"); // Secret-bearing: served to the owner, withheld publicly. - let owner = run_get_chunk_with_context(&LeakBackend, 4, 0, DisclosureContext::LocalOwner) - .expect("owner get-chunk"); + let owner = run_get_chunk_with_context( + &LeakBackend, + 4, + 0, + DisclosureContext::LocalOwner, + Sensitivity::SecretBearing, + ) + .expect("owner get-chunk"); assert_eq!(owner["text"], "SECRET production API key"); - let err = run_get_chunk_with_context(&LeakBackend, 4, 0, DisclosureContext::PublicSurface) - .expect_err("secret chunk must not cross to a public surface"); + let err = run_get_chunk_with_context( + &LeakBackend, + 4, + 0, + DisclosureContext::PublicSurface, + Sensitivity::SecretBearing, + ) + .expect_err("secret chunk must not cross to a public surface"); assert_eq!(err.to_string(), "chunk 4 not found"); // Shareable crosses everywhere. - let public = run_get_chunk_with_context(&LeakBackend, 1, 0, DisclosureContext::PublicSurface) - .expect("public get-chunk"); + let public = run_get_chunk_with_context( + &LeakBackend, + 1, + 0, + DisclosureContext::PublicSurface, + Sensitivity::SecretBearing, + ) + .expect("public get-chunk"); assert_eq!(public["text"], "shareable deployment notes"); } #[test] fn get_chunk_neighbors_are_filtered() { - let out = run_get_chunk_with_context(&LeakBackend, 1, 2, DisclosureContext::FleetInternal) - .expect("get-chunk"); + let out = run_get_chunk_with_context( + &LeakBackend, + 1, + 2, + DisclosureContext::FleetInternal, + Sensitivity::SecretBearing, + ) + .expect("get-chunk"); let after = out["context"]["after"].as_array().expect("after"); assert_eq!(after.len(), 1); assert_eq!(after[0]["chunk_id"], 2); @@ -694,3 +725,95 @@ fn unlocatable_sibling_span_withholds_the_whole_payload() { "notes record the payload withholding: {out}" ); } + +/// Records the ceiling pair a get-chunk occurrence lookup receives: +/// the tier fan-out ceiling and the full caller Sensitivity +/// ceiling. The oracle is the intersection rule (#12404): the +/// occurrence lookup must be gated by the SAME effective ceiling +/// as the chunk itself, not by the destination context's standalone +/// ceiling. +struct OccurrenceCeilingProbe { + seen: std::sync::Mutex>, +} + +impl SearchBackend for OccurrenceCeilingProbe { + fn name(&self) -> &'static str { + "probe" + } + fn vec_table(&self) -> &str { + "vec_chunks" + } + fn notes(&self) -> Vec { + Vec::new() + } + fn branch_pools(&self, _q: &BranchQuery, _f: &Filters) -> Result { + Ok(BranchPools::default()) + } + fn chunk_details(&self, ids: &[i64]) -> Result> { + Ok(ids.iter().map(|&id| detail(id)).collect()) + } + fn neighbors(&self, _m: &str, _i: i64, _n: i64) -> Result> { + Ok(Vec::new()) + } + fn occurrences( + &self, + _canonical_hash: &str, + tier_ceiling: atlas_core::shards::TierCeiling, + caller_ceiling: Sensitivity, + ) -> Result> { + *self.seen.lock().unwrap() = Some((tier_ceiling, caller_ceiling)); + Ok(Vec::new()) + } + fn message(&self, _m: &str) -> Result> { + Ok(None) + } +} + +#[test] +fn get_chunk_occurrence_lookup_uses_the_effective_ceiling() { + use atlas_core::shards::{Tier, TierCeiling}; + + // A personal grant under fleet-internal (ceiling local-only): + // the intersection is personal. The occurrence lookup must ask + // for the INTERNAL tier (personal maps there) and the personal + // row ceiling — not the secret tier the bare LocalOwner context + // used to request (P1: a personal-capped caller on a + // secret-tier service received secret-tier source locators, or, + // on a personal-only service, every get-chunk failed). + let probe = OccurrenceCeilingProbe { + seen: std::sync::Mutex::new(None), + }; + run_get_chunk_with_context( + &probe, + 2, + 0, + DisclosureContext::FleetInternal, + Sensitivity::Personal, + ) + .expect("personal chunk under fleet-internal"); + assert_eq!( + *probe.seen.lock().unwrap(), + Some((TierCeiling(Tier::Internal), Sensitivity::Personal)), + "occurrence lookup gated by grant ∩ context (personal ∩ local-only = personal)" + ); + + // A secret grant under public-surface: the intersection is + // shareable, so the lookup asks for the PUBLIC tier and the + // shareable row ceiling. + let probe = OccurrenceCeilingProbe { + seen: std::sync::Mutex::new(None), + }; + run_get_chunk_with_context( + &probe, + 1, + 0, + DisclosureContext::PublicSurface, + Sensitivity::SecretBearing, + ) + .expect("shareable chunk on a public surface"); + assert_eq!( + *probe.seen.lock().unwrap(), + Some((TierCeiling(Tier::Public), Sensitivity::Shareable)), + "occurrence lookup gated by grant ∩ context (secret ∩ shareable = shareable)" + ); +} diff --git a/pkgs/atlas-search/crates/atlas-core/tests/occurrences.rs b/pkgs/atlas-search/crates/atlas-core/tests/occurrences.rs new file mode 100644 index 0000000000..9684ad3e36 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/tests/occurrences.rs @@ -0,0 +1,453 @@ +//! Oracle tests for reading the `chunk_occurrences` provenance +//! registry (#3125 slice 3): the registry slice 2 writes becomes +//! readable through the shard set, tolerant of shards that +//! predate the registry, and surfaces in `get-chunk` output. +//! +//! Oracle: content identity by SHA-256 — the canonical hash the +//! aggregator records is the SHA-256 of the piece text, so a +//! lookup by that hash must find every shard row that recorded +//! it, regardless of which shard or item id the piece landed on. + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use atlas_core::error::Result; +use atlas_core::filters::Sensitivity; +use atlas_core::occurrences::{ChunkOccurrence, lookup_by_hash}; +use atlas_core::search::run_get_chunk; +use atlas_core::shards::scan::ShardedBackend; +use atlas_core::shards::{ + DirLister, DiscoveryOptions, ShardConnector, ShardEndpoint, ShardSet, Tier, TierCeiling, + discover, +}; +use atlas_core::types::{ + BranchHit, BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow, +}; +use atlas_core::{DEFAULT_VEC_TABLE, SearchBackend}; + +const NOW: &str = "2026-11-23T00:00:00Z"; +const TEXT: &str = "dns shared block\n"; +/// SHA-256 of TEXT — the canonical content hash the aggregator +/// records (the oracle: content identity). +const HASH: &str = "ecead345a7a4b99b26d42d2e839838ee261516fe54136d287847852a0ffe4f9f"; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("atlas-occ-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).expect("temp dir"); + d +} + +/// One (source, span) pair a fixture shard records for HASH. +fn fixture(dir: &Path, name: &str, occurrences: &[(&str, i64, i64)], legacy: bool) -> PathBuf { + fixture_with_sens(dir, name, occurrences, legacy, &["personal"]) +} + +/// Same as [`fixture`], but each chunk row's `sensitivity` is taken +/// from `sens` positionally (cycling when shorter): the per-row +/// classification promotion writes separately from the shard tier +/// (#3125 slice 3 P1: an admitted shard can hold rows above the +/// caller's ceiling). +fn fixture_with_sens( + dir: &Path, + name: &str, + occurrences: &[(&str, i64, i64)], + legacy: bool, + sens: &[&str], +) -> PathBuf { + use rusqlite::params; + let (tier, topic, part) = + atlas_core::shards::parse_shard_name(name).expect("shard name parses"); + let path = dir.join(format!("{name}.db")); + let _ = std::fs::remove_file(&path); + let con = rusqlite::Connection::open(&path).expect("create store"); + con.execute_batch(&format!( + "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 {DEFAULT_VEC_TABLE} (chunk_id INTEGER PRIMARY KEY, vec BLOB NOT NULL); + CREATE TABLE atlas_manifest (\"key\" TEXT PRIMARY KEY, value TEXT);" + )) + .expect("schema"); + if !legacy { + con.execute_batch( + "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)); \ + CREATE INDEX chunk_occurrences_hash ON chunk_occurrences (canonical_hash);", + ) + .expect("occurrence schema"); + } + for (i, (source, start, end)) in occurrences.iter().enumerate() { + let id = (i + 1) as i64; + let chunk_sens = sens.get(i % sens.len()).copied().unwrap_or("personal"); + con.execute( + "INSERT INTO chunks VALUES (?1, ?2, 0, ?3, ?4, ?5)", + params![id, source, TEXT, format!("h{id}"), chunk_sens], + ) + .expect("chunk"); + con.execute( + &format!("INSERT INTO {DEFAULT_VEC_TABLE} VALUES (?1, x'00000000')"), + params![id], + ) + .expect("vec"); + if !legacy { + con.execute( + "INSERT INTO chunk_occurrences \ + (shard_chunk_id, canonical_hash, source, span_start, span_end, observed_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![id, HASH, source, start, end, NOW], + ) + .expect("occurrence"); + } + } + for (k, v) in [ + ("shard", name), + ("tier", tier.name()), + ("topic", &topic), + ("part", &part.to_string()), + ("expected_chunks", &occurrences.len().to_string()), + ("metric", "cosine"), + ("embedding_model", atlas_core::shards::EMBEDDING_MODEL_ID), + ("engine", "tursodb"), + ] { + con.execute( + "INSERT OR REPLACE INTO atlas_manifest VALUES (?, ?)", + params![k, v], + ) + .expect("manifest"); + } + path +} + +struct OpenConnector; +impl ShardConnector for OpenConnector { + fn can_open(&self, _tier: Tier) -> bool { + true + } + fn connect( + &self, + ep: &ShardEndpoint, + _tier: Tier, + ) -> Result> { + use atlas_core::shards::ShardLocation; + let ShardLocation::File(p) = &ep.location else { + panic!("tests use files"); + }; + Ok(std::sync::Arc::new( + atlas_core::shards::LocalShardTransport::open(p)?, + )) + } +} + +fn discover_set(dir: &Path, ceiling: Tier) -> ShardSet { + discover( + &DirLister { + dir: dir.to_path_buf(), + }, + &OpenConnector, + &DiscoveryOptions::new(TierCeiling(ceiling)), + ) + .expect("discovery") +} + +#[test] +fn lookup_finds_every_occurrence_across_shards_and_skips_legacy_shards() { + // #3125 rule 3: every chunk records EVERY place it was found. + // The same text hash occurs in three registry-carrying shards + // (internal x2, secret x1) plus one legacy shard with no + // chunk_occurrences table at all — a lookup under an internal + // ceiling returns exactly the two internal rows, and the + // legacy shard is a note, not a failure. + let dir = temp_dir("lookup"); + fixture( + &dir, + "atlas-core-internal-work-01", + &[("repo@abc:infra/dns/a.yaml", 0, 17)], + false, + ); + fixture( + &dir, + "atlas-core-internal-media-01", + &[("repo@abc:infra/dns/b.yaml", 0, 17)], + false, + ); + fixture( + &dir, + "atlas-core-secret-main-01", + &[("repo@abc:infra/dns/secret.yaml", 0, 17)], + false, + ); + // Legacy: promoted before slice 2 — no registry table. + fixture(&dir, "atlas-core-internal-misc-01", &[], true); + let set = discover_set(&dir, Tier::Secret); + + let found = lookup_by_hash( + &set, + TierCeiling(Tier::Internal), + Sensitivity::LocalOnly, + HASH, + ) + .unwrap(); + assert_eq!( + found, + vec![ + ChunkOccurrence { + shard: "atlas-core-internal-media-01".into(), + tier: Tier::Internal, + canonical_hash: HASH.into(), + source: "repo@abc:infra/dns/b.yaml".into(), + span_start: 0, + span_end: 17, + observed_at: NOW.into(), + }, + ChunkOccurrence { + shard: "atlas-core-internal-work-01".into(), + tier: Tier::Internal, + canonical_hash: HASH.into(), + source: "repo@abc:infra/dns/a.yaml".into(), + span_start: 0, + span_end: 17, + observed_at: NOW.into(), + }, + ], + "internal rows only, ordered by shard; legacy shard contributes nothing and no error" + ); + + // A secret ceiling sees the third occurrence too. + let secret = lookup_by_hash( + &set, + TierCeiling(Tier::Secret), + Sensitivity::SecretBearing, + HASH, + ) + .unwrap(); + assert_eq!(secret.len(), 3, "secret ceiling adds the secret-tier row"); + + // An unknown hash reads as empty, never as an error. + assert!( + lookup_by_hash( + &set, + TierCeiling(Tier::Internal), + Sensitivity::LocalOnly, + "00" + ) + .unwrap() + .is_empty() + ); +} + +/// Stands in for the wrapped monolith: serves one chunk detail +/// whose text is the fixture text, records nothing else. +struct Monolith { + chunk_id: i64, +} +impl SearchBackend for Monolith { + fn name(&self) -> &'static str { + "turso" + } + fn vec_table(&self) -> &str { + DEFAULT_VEC_TABLE + } + fn notes(&self) -> Vec { + Vec::new() + } + fn branch_pools( + &self, + _q: &BranchQuery, + _f: &atlas_core::filters::Filters, + ) -> Result { + Ok(BranchPools::default()) + } + fn chunk_details(&self, ids: &[i64]) -> Result> { + Ok(ids + .iter() + .filter(|id| **id == self.chunk_id) + .map(|id| ChunkDetail { + chunk_id: *id, + text: TEXT.into(), + chunk_idx: 0, + message_id: "m1".into(), + m_role: Some("user".into()), + session_id: "s1".into(), + s_title: None, + s_client: None, + s_created_at: None, + l_kind: None, + l_topics: None, + l_projects: None, + eff_sensitivity: Some("personal".into()), + }) + .collect()) + } + fn neighbors(&self, _m: &str, _c: i64, _n: i64) -> Result> { + Ok(Vec::new()) + } + fn message(&self, _m: &str) -> Result> { + Ok(None) + } +} + +#[test] +fn get_chunk_reports_occurrences_from_the_shard_fan_out() { + // After slice 3, `get-chunk` resolves the chunk's canonical + // hash through the serving SearchBackend and reports every + // recorded place the text was found. On the wrapped monolith + // alone (no shards, default trait method) the field is + // absent; through the ShardedBackend it carries both internal + // sources with their spans. + let dir = temp_dir("getchunk"); + fixture( + &dir, + "atlas-core-internal-work-01", + &[("repo@abc:infra/dns/a.yaml", 0, 17)], + false, + ); + fixture( + &dir, + "atlas-core-internal-media-01", + &[("repo@abc:infra/dns/b.yaml", 4, 21)], + false, + ); + // The get-chunk path runs under the LocalOwner disclosure + // context (ceiling secret-bearing), so the set must be + // discovered with a secret-capable connector; fail-closed is + // the correct answer otherwise. + let set = std::sync::Arc::new(discover_set(&dir, Tier::Secret)); + + let inner = Monolith { chunk_id: 7 }; + let out = run_get_chunk(&inner, 7, 0).unwrap(); + assert!( + out.get("occurrences").is_none(), + "no shards behind the monolith: the field is absent, not empty" + ); + + let sharded = ShardedBackend::new(inner, set); + let out = run_get_chunk(&sharded, 7, 0).unwrap(); + let occ = out + .get("occurrences") + .expect("occurrences present") + .as_array() + .unwrap(); + assert_eq!(occ.len(), 2, "both internal shard rows surface"); + let sources: Vec<&str> = occ + .iter() + .filter_map(|o| o.get("source").and_then(|s| s.as_str())) + .collect(); + assert_eq!( + sources, + ["repo@abc:infra/dns/b.yaml", "repo@abc:infra/dns/a.yaml"], + "ordered by shard name (media < work)" + ); + assert_eq!( + occ[0].get("span_start").and_then(|v| v.as_i64()), + Some(4), + "the media shard's row carries its own span" + ); + assert_eq!(occ[0].get("span_end").and_then(|v| v.as_i64()), Some(21)); + assert_eq!( + occ[0].get("observed_at").and_then(|v| v.as_str()), + Some(NOW) + ); + assert_eq!( + occ[0].get("shard").and_then(|v| v.as_str()), + Some("atlas-core-internal-media-01") + ); +} + +#[test] +fn sharded_backend_occurrences_respect_the_caller_ceiling() { + // The SearchBackend seam routes occurrence reads through the + // shard fan-out with the caller's ceiling: a secret-tier row + // is invisible to an internal caller and visible to a + // secret-bearing caller. + let dir = temp_dir("ceiling"); + fixture( + &dir, + "atlas-core-internal-work-01", + &[("repo@abc:infra/dns/a.yaml", 0, 17)], + false, + ); + fixture( + &dir, + "atlas-core-secret-main-01", + &[("repo@abc:infra/dns/secret.yaml", 0, 17)], + false, + ); + let set = std::sync::Arc::new(discover_set(&dir, Tier::Secret)); + let sharded = ShardedBackend::new(Monolith { chunk_id: 1 }, set); + + let internal = sharded + .occurrences(HASH, TierCeiling(Tier::Internal), Sensitivity::LocalOnly) + .unwrap(); + assert_eq!(internal.len(), 1, "secret-tier occurrence withheld"); + let secret = sharded + .occurrences(HASH, TierCeiling(Tier::Secret), Sensitivity::SecretBearing) + .unwrap(); + assert_eq!(secret.len(), 2, "secret ceiling adds the secret row"); +} + +#[test] +fn occurrence_rows_are_filtered_by_their_own_chunk_sensitivity_not_just_shard_tier() { + // #3125 slice 3 P1: promotion names a shard from the unit's + // tier but writes each chunk's effective sensitivity + // separately, so an admitted shard can hold rows above the + // caller's ceiling. Both occurrences live in the SAME + // internal shard (admitted by an internal tier ceiling); only + // the per-row sensitivity decides which surface: a personal + // caller must not see the local-only row, and the + // personal/local-only distinction must survive (an internal + // TierCeiling alone cannot tell them apart). + let dir = temp_dir("rowsens"); + fixture_with_sens( + &dir, + "atlas-core-internal-work-01", + &[ + ("repo@abc:infra/dns/shared.yaml", 0, 17), + ("repo@abc:infra/dns/local.yaml", 0, 17), + ], + false, + &["personal", "local-only"], + ); + let set = discover_set(&dir, Tier::Internal); + + let personal = lookup_by_hash( + &set, + TierCeiling(Tier::Internal), + Sensitivity::Personal, + HASH, + ) + .unwrap(); + assert_eq!( + personal + .iter() + .map(|o| o.source.as_str()) + .collect::>(), + ["repo@abc:infra/dns/shared.yaml"], + "personal caller sees only the personal row; the local-only row in the same admitted shard is withheld" + ); + + let local = lookup_by_hash( + &set, + TierCeiling(Tier::Internal), + Sensitivity::LocalOnly, + HASH, + ) + .unwrap(); + assert_eq!( + local.len(), + 2, + "local-only ceiling sees both rows in the admitted shard" + ); +} + +// Silence unused warnings for helpers the monolith mock keeps. +#[allow(dead_code)] +fn _unused(_r: &Mutex<()>) -> BranchHit { + BranchHit { + chunk_id: 0, + dist: None, + } +} diff --git a/pkgs/atlas-search/crates/atlas-search/src/main.rs b/pkgs/atlas-search/crates/atlas-search/src/main.rs index 73ec64f1b7..c9a27aae2b 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/main.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/main.rs @@ -1035,8 +1035,14 @@ fn cmd_get_chunk(args: GetChunkArgs) -> Result<(), CliError> { // The Python's get-chunk takes no vector args: pick_backend // sees the defaults (getattr fallbacks in its main()). let backend = pick_backend(&args.backend, atlas_core::DEFAULT_VEC_TABLE, 0)?; - let mut out = run_get_chunk_with_context(backend.as_ref(), args.chunk_id, neighbors, context) - .map_err(|e| map_get_chunk_err(e, args.chunk_id))?; + let mut out = run_get_chunk_with_context( + backend.as_ref(), + args.chunk_id, + neighbors, + context, + context.ceiling(), + ) + .map_err(|e| map_get_chunk_err(e, args.chunk_id))?; if let Some(note) = note { push_note(&mut out, note); } diff --git a/pkgs/atlas-search/crates/atlas-search/src/server.rs b/pkgs/atlas-search/crates/atlas-search/src/server.rs index 616be677e7..19500704ef 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/server.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/server.rs @@ -33,7 +33,7 @@ use atlas_core::{ JsonlFeedbackSink, JsonlTraceSink, QueryEmbedder, SearchBackend, SearchMode as CoreSearchMode, SearchOptions, Sensitivity as CoreSensitivity, TraceContext, VectorBackend as CoreVectorBackend, chunk_classification, feedback_for, load_feedback_dir, - record_feedback, run_get_chunk, run_search_with_executor_traced, + record_feedback, run_get_chunk_with_context, run_search_with_executor_traced, }; use atlas_proto::{ BranchState, BranchStates, EmbedRequest, EmbedResponse, ErrorResponse, HealthResponse, @@ -775,8 +775,23 @@ where if !allowed || excluded { return Err(not_found()); } - run_get_chunk(self.backend.as_ref(), chunk_id, neighbors) - .map_err(|e| ServerError::from_core(&e)) + // The explicit-id gate keeps its documented form (a + // by-id lookup with no caller ceiling; the LocalOwner + // context applies, exactly like the Python), while the + // caller's actual ceiling is threaded through so the + // occurrence provenance is bounded by it — never by the + // destination context's standalone ceiling (P1: a + // personal-capped caller must not receive secret-tier + // source locators, and a personal-only service must not + // request a secret-tier fan-out). + run_get_chunk_with_context( + self.backend.as_ref(), + chunk_id, + neighbors, + DisclosureContext::LocalOwner, + core_sensitivity(ceiling), + ) + .map_err(|e| ServerError::from_core(&e)) } fn embed_query(&self, text: &str, trunc: usize) -> Result, ServerError> {