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
28 changes: 28 additions & 0 deletions pkgs/atlas-search/crates/atlas-core/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Vec<ChunkOccurrence>> {
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<Option<MessageRow>>;
}
Expand Down Expand Up @@ -114,6 +134,14 @@ impl<T: SearchBackend + ?Sized> SearchBackend for Box<T> {
fn message_chunks(&self, message_id: &str) -> Result<Vec<NeighborRow>> {
(**self).message_chunks(message_id)
}
fn occurrences(
&self,
canonical_hash: &str,
tier_ceiling: TierCeiling,
caller_ceiling: Sensitivity,
) -> Result<Vec<ChunkOccurrence>> {
(**self).occurrences(canonical_hash, tier_ceiling, caller_ceiling)
}
fn message(&self, message_id: &str) -> Result<Option<MessageRow>> {
(**self).message(message_id)
}
Expand Down
2 changes: 2 additions & 0 deletions pkgs/atlas-search/crates/atlas-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
145 changes: 145 additions & 0 deletions pkgs/atlas-search/crates/atlas-core/src/occurrences.rs
Original file line number Diff line number Diff line change
@@ -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:<id>` 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<Vec<ChunkOccurrence>> {
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)
}
38 changes: 36 additions & 2 deletions pkgs/atlas-search/crates/atlas-core/src/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -657,19 +658,33 @@ 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<Json> {
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
/// chunk itself must be permitted by the context (a withheld
/// 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<Json> {
let details = backend.chunk_details(&[chunk_id])?;
let Some(d) = details.iter().find(|d| d.chunk_id == chunk_id) else {
Expand All @@ -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(
Expand All @@ -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,
)?;
Comment thread
dezren39 marked this conversation as resolved.
Resolved
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();
Expand Down
22 changes: 22 additions & 0 deletions pkgs/atlas-search/crates/atlas-core/src/shards/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,28 @@ impl<B: SearchBackend> SearchBackend for ShardedBackend<B> {
}
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<Vec<crate::occurrences::ChunkOccurrence>> {
crate::occurrences::lookup_by_hash(
&self.current_set(),
tier_ceiling,
caller_ceiling,
canonical_hash,
)
}
}

#[cfg(test)]
Expand Down
Loading