diff --git a/pkgs/atlas-search/crates/atlas-core/src/backend.rs b/pkgs/atlas-search/crates/atlas-core/src/backend.rs index df39a4dba4..41039f2186 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/backend.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/backend.rs @@ -9,6 +9,14 @@ use crate::error::Result; use crate::filters::Filters; use crate::types::{BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow}; +/// The window (in chunk_idx units) the default +/// [`SearchBackend::message_chunks`] composes from +/// [`SearchBackend::neighbors`]: wide enough to cover any +/// message in the corpus — chunk_idx is sparse in the publish +/// corpus (observed span 0..=1730, measured 2026-11-22 for +/// #12624) — with orders of magnitude of headroom. +pub const MESSAGE_CHUNKS_WINDOW: i64 = 1_000_000; + pub trait SearchBackend { /// `"turso"` or `"local"` (the envelope's `backend` field). fn name(&self) -> &'static str; @@ -60,6 +68,19 @@ pub trait SearchBackend { /// `chunk_idx` in the window), ordered by chunk_idx. fn neighbors(&self, message_id: &str, chunk_idx: i64, n: i64) -> Result>; + /// Every chunk row of one message, ordered by chunk_idx: + /// the enumeration the full-content span filter (#12624) + /// classifies before a `--with-message` / hydration payload + /// may cross the output boundary. The default composes + /// [`Self::neighbors`] with a window wide enough to cover + /// any message ([`MESSAGE_CHUNKS_WINDOW`]); backends with a + /// native unbounded query override it. Wrappers that route + /// `neighbors` (the shard fan-out) inherit correct routing + /// through the default. + fn message_chunks(&self, message_id: &str) -> Result> { + self.neighbors(message_id, 0, MESSAGE_CHUNKS_WINDOW) + } + /// One message row by id (for `--with-message` payloads). fn message(&self, message_id: &str) -> Result>; } @@ -90,6 +111,9 @@ impl SearchBackend for Box { fn neighbors(&self, message_id: &str, chunk_idx: i64, n: i64) -> Result> { (**self).neighbors(message_id, chunk_idx, n) } + fn message_chunks(&self, message_id: &str) -> Result> { + (**self).message_chunks(message_id) + } fn message(&self, message_id: &str) -> Result> { (**self).message(message_id) } diff --git a/pkgs/atlas-search/crates/atlas-core/src/filters.rs b/pkgs/atlas-search/crates/atlas-core/src/filters.rs index bd59abaf44..7601d8c075 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/filters.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/filters.rs @@ -466,6 +466,12 @@ pub fn details_sql(shape: BackendShape, n_ids: usize) -> String { pub const NEIGHBORS_SQL: &str = "SELECT id, chunk_idx, text FROM chunks \ WHERE message_id = ? AND chunk_idx BETWEEN ? AND ? ORDER BY chunk_idx"; +/// Every chunk row of one message, ordered by chunk_idx — the +/// enumeration the full-content span filter (#12624) classifies +/// before a message payload may cross the output boundary. +pub const MESSAGE_CHUNKS_SQL: &str = "SELECT id, chunk_idx, text FROM chunks \ + WHERE message_id = ? ORDER BY chunk_idx"; + pub const MESSAGE_SQL: &str = "SELECT id, role, text FROM messages WHERE id = ?"; // ------------------------------------------------------------- dates ---- diff --git a/pkgs/atlas-search/crates/atlas-core/src/local.rs b/pkgs/atlas-search/crates/atlas-core/src/local.rs index 15baa09202..325ebff6df 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/local.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/local.rs @@ -15,7 +15,8 @@ use rusqlite::{Connection, OpenFlags}; use crate::backend::SearchBackend; use crate::error::{Error, Result}; use crate::filters::{ - Filters, LOCAL_SHAPE, MESSAGE_SQL, NEIGHBORS_SQL, details_sql, fts_stmt, local_allowed_stmt, + Filters, LOCAL_SHAPE, MESSAGE_CHUNKS_SQL, MESSAGE_SQL, NEIGHBORS_SQL, details_sql, fts_stmt, + local_allowed_stmt, }; use crate::types::{ BranchHit, BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow, Row, Stmt, Value, @@ -684,6 +685,23 @@ impl SearchBackend for LocalBackend { .collect()) } + fn message_chunks(&self, message_id: &str) -> Result> { + let rows = self.execute(&Stmt::new( + MESSAGE_CHUNKS_SQL, + vec![Value::text(message_id)], + ))?; + Ok(rows + .iter() + .filter_map(|r| { + Some(NeighborRow { + chunk_id: r.get_i64("id")?, + chunk_idx: r.get_i64("chunk_idx")?, + text: r.get_text("text")?.to_string(), + }) + }) + .collect()) + } + fn message(&self, message_id: &str) -> Result> { let rows = self.execute(&Stmt::new(MESSAGE_SQL, vec![Value::text(message_id)]))?; Ok(rows.first().and_then(|r| { diff --git a/pkgs/atlas-search/crates/atlas-core/src/search.rs b/pkgs/atlas-search/crates/atlas-core/src/search.rs index 6ce0f270c5..2a6ed16e96 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/search.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/search.rs @@ -18,7 +18,9 @@ use crate::error::{Error, Result}; use crate::filters::{Filters, Sensitivity}; use crate::fusion::{FusedEntry, fts_match_expr, fuse_with_parameters}; use crate::trace::{TraceContext, TraceSink, build_trace_record, new_query_id}; -use crate::types::{BranchPools, BranchQuery, ChunkDetail, DEFAULT_MODEL, VectorBackend, round6}; +use crate::types::{ + BranchPools, BranchQuery, ChunkDetail, DEFAULT_MODEL, NeighborRow, VectorBackend, round6, +}; /// The Python's `MESSAGE_TEXT_CAP`. pub const MESSAGE_TEXT_CAP: usize = 50_000; @@ -374,7 +376,11 @@ fn run_search_impl( // paged payloads inherit the same filter. Details are // resolved for every ranked candidate (the traced path // already pays this) because a candidate's classification - // is a property of its detail row. + // is a property of its detail row. Full-content payloads + // (the parent message, hydration) carry text beyond the + // admitted chunk, so at render time they are additionally + // span-filtered per sibling chunk (#12624, + // `span_filter_payload`). let all_ids: Vec = ranked.iter().map(|e| e.chunk_id).collect(); let all_details = details_map(backend, &all_ids)?; let mut permitted: std::collections::HashSet = std::collections::HashSet::new(); @@ -458,6 +464,7 @@ fn run_search_impl( // filter-before-serve rule the branch queries apply // to the caller ceiling). let mut results = Vec::new(); + let mut span_record = SpanRecord::default(); for e in &ranked { if results.len() >= opts.k { break; @@ -468,13 +475,32 @@ fn run_search_impl( let Some(d) = all_details.get(&e.chunk_id) else { continue; }; - let mut entry = result_entry(backend, opts, filters.max_sensitivity, e, d, &vec_dist)?; + let mut entry = result_entry( + backend, + opts, + filters.max_sensitivity, + e, + d, + &vec_dist, + &mut span_record, + )?; // Hydration: the first `hydrate` RENDERED results // (details present) gain full content — except on a // public surface, where full-content payloads are - // withheld outright (see the disclosure pass above). - if !withhold_full_content && results.len() < opts.parameters.hydrate { - let hydrated = hydrate_entry(backend, d)?; + // withheld outright (see the disclosure pass above), + // and except a payload the span filter cannot make + // safe (#12624), which is omitted whole and counted + // in the notes below. + if !withhold_full_content + && results.len() < opts.parameters.hydrate + && let Some(hydrated) = hydrate_entry( + backend, + d, + opts.context, + filters.max_sensitivity, + &mut span_record, + )? + { entry .as_object_mut() .expect("result entry is an object") @@ -482,6 +508,7 @@ fn run_search_impl( } results.push(entry); } + span_record.push_notes(&mut notes, opts.context, filters.max_sensitivity); let mut env = envelope(backend, opts, filters, Json::Array(results), ¬es); if opts.parameters.raw_mode == RawMode::Ungrouped { env.as_object_mut() @@ -582,20 +609,44 @@ fn collect_served(v: Option<&Json>, acc: &mut Vec) { /// the shard path the tier content stores hydrate separately, /// #6664; this covers the monolith backends, whose message store /// IS the content store.) -fn hydrate_entry(backend: &dyn SearchBackend, d: &ChunkDetail) -> Result { +/// +/// The message text is a full-content payload, so it is +/// span-filtered per sibling chunk (#12624, see +/// [`span_filter_payload`]). `None` means the payload could not +/// be safely filtered and is withheld whole: the caller omits +/// the `hydrated` field, and the withholding is tallied in +/// `record` for the envelope notes. +fn hydrate_entry( + backend: &dyn SearchBackend, + d: &ChunkDetail, + context: DisclosureContext, + grant: Sensitivity, + record: &mut SpanRecord, +) -> Result> { let message = match backend.message(&d.message_id)? { - Some(m) => json!({ - "id": m.id, - "role": m.role, - "text": m.text, - "truncated": false, - }), + Some(m) => { + match span_filter_payload(backend, &d.message_id, &m.text, &m.text, context, grant)? { + Some((text, withheld)) => { + record.spans_withheld += withheld; + json!({ + "id": m.id, + "role": m.role, + "text": text, + "truncated": false, + }) + } + None => { + record.payloads_withheld += 1; + return Ok(None); + } + } + } None => Json::Null, }; - Ok(json!({ + Ok(Some(json!({ "chunk_text": d.text, "message": message, - })) + }))) } /// The Python's `run_get_chunk`: a by-id lookup with NO caller @@ -723,6 +774,7 @@ fn session_obj(d: &ChunkDetail) -> Json { Json::Object(s) } +#[allow(clippy::too_many_arguments)] fn result_entry( backend: &dyn SearchBackend, opts: &SearchOptions, @@ -730,6 +782,7 @@ fn result_entry( e: &FusedEntry, d: &ChunkDetail, vec_dist: &HashMap>, + record: &mut SpanRecord, ) -> Result { let mut entry = Map::new(); entry.insert("chunk_id".into(), json!(e.chunk_id)); @@ -738,12 +791,13 @@ fn result_entry( entry.insert("rank_sources".into(), e.rank_sources_json()); entry.insert("text".into(), Json::String(d.text.clone())); entry.insert("session".into(), session_obj(d)); - entry_chunk_extras(backend, opts, grant, e, d, vec_dist, &mut entry)?; + entry_chunk_extras(backend, opts, grant, e, d, vec_dist, &mut entry, record)?; Ok(Json::Object(entry)) } /// vector_distance / context / message — the trailing fields /// shared by flat result entries and grouped chunk entries. +#[allow(clippy::too_many_arguments)] fn entry_chunk_extras( backend: &dyn SearchBackend, opts: &SearchOptions, @@ -752,6 +806,7 @@ fn entry_chunk_extras( d: &ChunkDetail, vec_dist: &HashMap>, entry: &mut Map, + record: &mut SpanRecord, ) -> Result<()> { if let Some(Some(dist)) = vec_dist.get(&e.chunk_id) { entry.insert("vector_distance".into(), json!(round6(*dist))); @@ -766,9 +821,13 @@ fn entry_chunk_extras( // text beyond the classified chunk, so on a public surface // it is withheld outright (design section 4). Other // contexts gate it on the served chunk's own classification - // via the disclosure pass that admitted the chunk. + // via the disclosure pass that admitted the chunk, and + // span-filter it per sibling chunk (#12624). if opts.with_message && opts.context != DisclosureContext::PublicSurface { - entry.insert("message".into(), message_obj(backend, d)?); + entry.insert( + "message".into(), + message_obj(backend, d, opts.context, grant, record)?, + ); } Ok(()) } @@ -809,19 +868,197 @@ fn neighbor_map( Ok(json!({"before": before, "after": after})) } -/// The Python's `message_obj` (null when the message is gone). -fn message_obj(backend: &dyn SearchBackend, d: &ChunkDetail) -> Result { +/// The span filter's running tally for one search: how many +/// message spans were omitted from full-content payloads, and +/// how many payloads were withheld whole because they could +/// not be safely filtered (#12624). Rendered into the envelope +/// notes by [`SpanRecord::push_notes`] — withholding is on the +/// record, never silent (the #12404 note idiom). +#[derive(Debug, Default)] +struct SpanRecord { + spans_withheld: usize, + payloads_withheld: usize, +} + +impl SpanRecord { + fn push_notes(&self, notes: &mut Vec, context: DisclosureContext, grant: Sensitivity) { + if self.spans_withheld > 0 { + notes.push(format!( + "disclosure: context {} withheld {} message span(s) (context ceiling {}, caller ceiling {})", + context.name(), + self.spans_withheld, + context.ceiling().name(), + grant.name(), + )); + } + if self.payloads_withheld > 0 { + notes.push(format!( + "disclosure: context {} withheld {} message payload(s) that could not be span-filtered (context ceiling {}, caller ceiling {})", + context.name(), + self.payloads_withheld, + context.ceiling().name(), + grant.name(), + )); + } + } +} + +/// Span-level disclosure filtering for full-content payloads +/// (#12624): the rule for `--with-message` and hydration +/// payloads under the non-public contexts. (A public surface +/// withholds these payloads outright — see the disclosure pass +/// in `run_search_impl`.) +/// +/// A payload is the whole text of the served chunk's message, +/// and a message spans every chunk cut from it. Chunk +/// classification is per-chunk, so the payload can carry text +/// belonging to sibling chunks that classify higher than the +/// served chunk. The rule: every chunk of the message is +/// classified from its detail row and tested with the same +/// grant ∩ context intersection the disclosure pass applies +/// to candidates ([`DisclosureContext::permits_with_grant`] — +/// so `excluded_personal_life` text never crosses, in any +/// context, and a chunk with no detail row fails closed). The +/// text of a chunk that fails is a withheld span: every +/// occurrence of it in the message text is omitted from the +/// served text (omission is this codebase's withholding idiom; +/// the count is recorded in the envelope notes). Text that +/// belongs to no chunk — measured at roughly two-thirds of +/// message text in the publish corpus, the chunker is +/// selective — is not a sibling chunk's text and rides on the +/// served chunk's own gate, as #12404 established. +/// +/// Corpus measurement (2026-11-22, the publish corpus: +/// 107,639 chunks over 71,551 messages with chunks, 6,044 of +/// them multi-chunk): zero messages mix classifications today +/// — per-chunk sensitivity is uniform within every message — +/// so this filter is a guard for the day per-embed +/// classification (#12408) starts diverging inside a message, +/// not a fix for a live leak. +/// +/// Returns `Some((served_text, spans_withheld))`, or `None` +/// when the payload cannot be safely filtered: a failing +/// chunk whose text occurs nowhere in the message text (a +/// store inconsistency — its span cannot be proven absent in +/// the form the payload carries) withholds the payload whole, +/// per design section 4's rule for outputs that cannot be +/// safely filtered. `served` is the exact text about to be +/// served (the capped prefix for `--with-message`, the full +/// text for hydration) and must be a prefix of `full_text`; +/// spans are located in `full_text`, and only the part inside +/// `served` is filtered or counted. +fn span_filter_payload( + backend: &dyn SearchBackend, + message_id: &str, + full_text: &str, + served: &str, + context: DisclosureContext, + grant: Sensitivity, +) -> Result> { + let chunks = backend.message_chunks(message_id)?; + if chunks.is_empty() { + return Ok(Some((served.to_string(), 0))); + } + let ids: Vec = chunks.iter().map(|c| c.chunk_id).collect(); + let details = details_map(backend, &ids)?; + // The message's chunks that fail the intersection. A chunk + // with no detail row is withheld (fail-closed), matching + // neighbor_map's rule for unclassified neighbors. + let failing: Vec<&NeighborRow> = chunks + .iter() + .filter(|c| { + !details.get(&c.chunk_id).is_some_and(|d| { + context + .permits_with_grant(chunk_classification(d.eff_sensitivity.as_deref()), grant) + }) + }) + .collect(); + if failing.is_empty() { + return Ok(Some((served.to_string(), 0))); + } + // Locate every occurrence of every failing chunk's text in + // the message text: those byte ranges may not cross. (All + // occurrences, not one located span per chunk — a failing + // chunk's text can repeat in the message, and a repeat is + // the same classified text.) + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for c in &failing { + if c.text.is_empty() { + // An empty chunk contributes no text to withhold. + continue; + } + let mut found = false; + let mut from = 0usize; + while let Some(off) = full_text[from..].find(c.text.as_str()) { + let start = from + off; + ranges.push((start, start + c.text.len())); + found = true; + from = start + 1; + } + if !found { + return Ok(None); + } + } + // Merge the ranges against the served prefix and rebuild + // the text without them. Ranges are byte ranges on char + // boundaries (each is a found &str occurrence), and + // `served` is a prefix of `full_text` ending on a char + // boundary, so every slice below is boundary-safe. + ranges.sort_unstable(); + let limit = served.len(); + let mut out = String::with_capacity(limit); + let mut cursor = 0usize; + let mut withheld = 0usize; + for (start, end) in ranges { + if start >= limit { + break; + } + let end = end.min(limit); + if start > cursor { + out.push_str(&full_text[cursor..start]); + } + if end > cursor { + withheld += 1; + cursor = end; + } + } + if cursor < limit { + out.push_str(&full_text[cursor..limit]); + } + Ok(Some((out, withheld))) +} + +/// The Python's `message_obj` (null when the message is gone — +/// or when its payload cannot be safely span-filtered, #12624: +/// a withheld payload reads exactly like an absent one, and +/// the withholding is tallied in `record`). +fn message_obj( + backend: &dyn SearchBackend, + d: &ChunkDetail, + context: DisclosureContext, + grant: Sensitivity, + record: &mut SpanRecord, +) -> Result { let Some(m) = backend.message(&d.message_id)? else { return Ok(Json::Null); }; let truncated = m.text.chars().count() > MESSAGE_TEXT_CAP; - let text: String = m.text.chars().take(MESSAGE_TEXT_CAP).collect(); - Ok(json!({ - "id": m.id, - "role": m.role, - "text": text, - "truncated": truncated, - })) + let capped: String = m.text.chars().take(MESSAGE_TEXT_CAP).collect(); + match span_filter_payload(backend, &d.message_id, &m.text, &capped, context, grant)? { + Some((text, withheld)) => { + record.spans_withheld += withheld; + Ok(json!({ + "id": m.id, + "role": m.role, + "text": text, + "truncated": truncated, + })) + } + None => { + record.payloads_withheld += 1; + Ok(Json::Null) + } + } } struct Group { @@ -901,6 +1138,7 @@ fn grouped_output( }); sorted.truncate(opts.k); let mut results = Vec::new(); + let mut span_record = SpanRecord::default(); for g in &sorted { let mut chunks = Vec::new(); for (e, d) in g.chunks.iter().take(5) { @@ -917,6 +1155,7 @@ fn grouped_output( d, vec_dist, &mut ce, + &mut span_record, )?; chunks.push(Json::Object(ce)); } @@ -928,12 +1167,14 @@ fn grouped_output( entry.insert("chunks".into(), Json::Array(chunks)); results.push(Json::Object(entry)); } + let mut notes = notes.to_vec(); + span_record.push_notes(&mut notes, opts.context, filters.max_sensitivity); Ok(envelope( backend, opts, filters, Json::Array(results), - notes, + ¬es, )) } diff --git a/pkgs/atlas-search/crates/atlas-core/src/turso.rs b/pkgs/atlas-search/crates/atlas-core/src/turso.rs index 1081b6b601..b2bfd02f76 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/turso.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/turso.rs @@ -776,6 +776,23 @@ impl SearchBackend for TursoBackend { .collect()) } + fn message_chunks(&self, message_id: &str) -> Result> { + let rows = self.execute(&Stmt::new( + crate::filters::MESSAGE_CHUNKS_SQL, + vec![Value::text(message_id)], + ))?; + Ok(rows + .iter() + .filter_map(|r| { + Some(NeighborRow { + chunk_id: r.get_i64("id")?, + chunk_idx: r.get_i64("chunk_idx")?, + text: r.get_text("text")?.to_string(), + }) + }) + .collect()) + } + fn message(&self, message_id: &str) -> Result> { let rows = self.execute(&Stmt::new( crate::filters::MESSAGE_SQL, diff --git a/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs b/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs index a7c665c765..44d9a6e967 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/disclosure.rs @@ -119,10 +119,22 @@ impl SearchBackend for LeakBackend { .collect()) } fn message(&self, message_id: &str) -> Result> { + // Message m1's text is composed of its chunks' texts + // (1, 2, 4) joined by gap text — the real corpus shape, + // which the #12624 span filter locates spans in. Other + // messages hold a single chunk each, so their text + // needs no span structure. + let text = if message_id == "m1" { + "FULL MESSAGE TEXT: shareable deployment notes; \ + personal project journal; SECRET production API key" + .to_string() + } else { + format!("FULL MESSAGE TEXT of {message_id}, beyond any single chunk") + }; Ok(Some(MessageRow { id: message_id.to_string(), role: Some("user".to_string()), - text: format!("FULL MESSAGE TEXT of {message_id}, beyond any single chunk"), + text, })) } } @@ -377,4 +389,308 @@ fn public_surface_withholds_full_content_payloads() { let entry = &fleet["results"][0]; assert!(entry.get("message").is_some()); assert!(entry.get("hydrated").is_some()); + // And under #12624 the payloads are span-filtered: chunk + // 4's secret-bearing span is omitted from chunk 1's + // message, while chunk 2's personal span still crosses. + let text = entry["message"]["text"].as_str().expect("message text"); + assert!(text.contains("personal project journal"), "{text}"); + assert!( + !text.contains("SECRET production API key"), + "secret-bearing sibling span crossed: {text}" + ); +} + +// --------------------------------------------------------------- +// #12624: span-level filtering of full-content payloads. A +// message's chunks can classify differently from the chunk a +// payload is attached to; the payload may contain only the +// spans whose own chunks pass the same grant ∩ context +// intersection the disclosure pass applies to candidates. +// Withheld spans are omitted (the codebase's withholding +// idiom) and counted in the envelope notes; a failing chunk +// whose text cannot be located in the message text makes the +// payload unfilterable and it is withheld whole (design +// section 4: an output that cannot be safely filtered is +// withheld). + +/// (chunk_id, label, text, message, chunk_idx) +const SPAN_CORPUS: [(i64, Option<&str>, &str, &str, i64); 6] = [ + ( + 101, + Some("shareable"), + "the deploy window opens at dawn", + "mmix", + 0, + ), + ( + 102, + Some("secret-bearing"), + "the vault code is 493812", + "mmix", + 1, + ), + ( + 103, + Some("personal"), + "remember to water the plants", + "mmix", + 2, + ), + ( + 104, + Some("excluded_personal_life"), + "diary entry: the diagnosis results", + "mmix", + 3, + ), + ( + 105, + Some("shareable"), + "a perfectly ordinary opening", + "mbad", + 0, + ), + ( + 106, + Some("secret-bearing"), + "an unlocatable secret passage", + "mbad", + 1, + ), +]; + +/// Message `mmix`'s text is its chunks' texts joined by +/// unattributed gap text ("LOG", the separators, "END") — the +/// shape the real corpus takes: chunk texts occur verbatim in +/// the message text, and not all message text belongs to a +/// chunk. Message `mbad` models a store inconsistency: chunk +/// 106's text does not occur in its text at all. +const MIX_MESSAGE: &str = "LOG the deploy window opens at dawn; \ + the vault code is 493812; remember to water the plants; \ + diary entry: the diagnosis results END"; +const BAD_MESSAGE: &str = "a perfectly ordinary opening followed by completely different words"; + +struct SpanBackend; + +fn span_detail(id: i64) -> ChunkDetail { + let (_, label, text, message, idx) = SPAN_CORPUS + .iter() + .find(|(cid, _, _, _, _)| *cid == id) + .unwrap_or_else(|| panic!("unknown chunk {id}")); + ChunkDetail { + chunk_id: id, + text: text.to_string(), + chunk_idx: *idx, + message_id: message.to_string(), + m_role: Some("user".to_string()), + session_id: "smix".to_string(), + s_title: Some("session".to_string()), + s_client: None, + s_created_at: None, + l_kind: None, + l_topics: None, + l_projects: None, + eff_sensitivity: label.map(str::to_string), + } +} + +impl SearchBackend for SpanBackend { + fn name(&self) -> &'static str { + "fake" + } + fn vec_table(&self) -> &str { + "vec_chunks" + } + fn notes(&self) -> Vec { + Vec::new() + } + fn branch_pools(&self, _q: &BranchQuery, _f: &Filters) -> Result { + Ok(BranchPools { + fts: [101, 105] + .iter() + .map(|&chunk_id| BranchHit { + chunk_id, + dist: None, + }) + .collect(), + vector: Vec::new(), + candidate_models: Default::default(), + }) + } + fn chunk_details(&self, ids: &[i64]) -> Result> { + Ok(ids.iter().map(|&id| span_detail(id)).collect()) + } + fn neighbors(&self, message_id: &str, _idx: i64, _n: i64) -> Result> { + let ids: &[i64] = match message_id { + "mmix" => &[102, 103, 104], + "mbad" => &[106], + _ => &[], + }; + Ok(ids + .iter() + .map(|&id| { + let d = span_detail(id); + NeighborRow { + chunk_id: id, + chunk_idx: d.chunk_idx, + text: d.text, + } + }) + .collect()) + } + fn message(&self, message_id: &str) -> Result> { + let text = match message_id { + "mmix" => MIX_MESSAGE, + "mbad" => BAD_MESSAGE, + _ => return Ok(None), + }; + Ok(Some(MessageRow { + id: message_id.to_string(), + role: Some("user".to_string()), + text: text.to_string(), + })) + } +} + +fn span_search( + context: DisclosureContext, + ceiling: &str, + tweak: impl Fn(&mut SearchOptions), +) -> Json { + let mut o = SearchOptions::new("deployment"); + o.mode = SearchMode::Fts; + o.k = 10; + o.context = context; + tweak(&mut o); + run_search(&SpanBackend, &FakeEmbedder, &filters(ceiling), &o).expect("search") +} + +fn entry_for(out: &Json, chunk_id: i64) -> &Json { + out["results"] + .as_array() + .expect("results array") + .iter() + .find(|r| r["chunk_id"] == chunk_id) + .unwrap_or_else(|| panic!("no result entry for chunk {chunk_id}: {out}")) +} + +#[test] +fn with_message_payload_omits_spans_above_the_intersection() { + // Oracle: #12624 — the payload attached to the served + // shareable chunk 101 contains only spans whose own chunks + // pass fleet-internal ∩ the caller's grant; the served + // chunk's span, the personal sibling's span, and + // unattributed gap text still cross. + let out = span_search(DisclosureContext::FleetInternal, "secret-bearing", |o| { + o.with_message = true; + }); + let entry = entry_for(&out, 101); + assert_eq!(entry["text"], "the deploy window opens at dawn"); + let text = entry["message"]["text"] + .as_str() + .expect("payload served on a non-public surface"); + assert!(text.contains("the deploy window opens at dawn"), "{text}"); + assert!(text.contains("remember to water the plants"), "{text}"); + assert!( + text.contains("LOG"), + "gap text rides on the served chunk's gate: {text}" + ); + assert!( + !text.contains("493812"), + "secret-bearing sibling span crossed: {text}" + ); + assert!( + !text.contains("diagnosis"), + "excluded sibling span crossed: {text}" + ); + // The withholding is on the record, not silent. + assert!( + out["notes"] + .as_array() + .expect("notes") + .iter() + .any(|n| n.as_str().unwrap_or("").contains("message span(s)")), + "notes record the span withholding: {out}" + ); +} + +#[test] +fn excluded_sibling_span_never_crosses_even_for_the_owner() { + // The owner's context admits the secret-bearing span, but + // excluded_personal_life is ineligible in every context — + // as a candidate (#12404) and as a payload span alike. + let out = span_search(DisclosureContext::LocalOwner, "secret-bearing", |o| { + o.with_message = true; + }); + let text = entry_for(&out, 101)["message"]["text"] + .as_str() + .expect("payload served"); + assert!( + text.contains("493812"), + "owner receives the secret-bearing span: {text}" + ); + assert!( + !text.contains("diagnosis"), + "excluded sibling span crossed to the owner: {text}" + ); +} + +#[test] +fn hosted_payload_omits_spans_above_personal() { + let out = span_search(DisclosureContext::HostedPerUser, "secret-bearing", |o| { + o.with_message = true; + }); + let text = entry_for(&out, 101)["message"]["text"] + .as_str() + .expect("payload served"); + assert!(text.contains("remember to water the plants"), "{text}"); + assert!(!text.contains("493812"), "secret span crossed: {text}"); + assert!(!text.contains("diagnosis"), "excluded span crossed: {text}"); +} + +#[test] +fn hydration_payload_omits_spans_above_the_intersection() { + // Hydration is the uncapped full-content path; the span + // rule is the same as --with-message's. + let out = span_search(DisclosureContext::FleetInternal, "secret-bearing", |o| { + o.parameters.hydrate = 1; + }); + let h = &entry_for(&out, 101)["hydrated"]; + assert_eq!(h["chunk_text"], "the deploy window opens at dawn"); + let text = h["message"]["text"] + .as_str() + .expect("hydrated payload served"); + assert!(text.contains("remember to water the plants"), "{text}"); + assert!( + !text.contains("493812"), + "secret-bearing sibling span crossed: {text}" + ); + assert!( + !text.contains("diagnosis"), + "excluded sibling span crossed: {text}" + ); +} + +#[test] +fn unlocatable_sibling_span_withholds_the_whole_payload() { + // Chunk 106 fails the intersection and its text cannot be + // located in its message's text, so the payload cannot be + // safely filtered: it is withheld whole (the served + // chunk's own row still serves), and the notes say so. + let out = span_search(DisclosureContext::FleetInternal, "secret-bearing", |o| { + o.with_message = true; + }); + let entry = entry_for(&out, 105); + assert_eq!(entry["text"], "a perfectly ordinary opening"); + assert!( + entry["message"].is_null(), + "unfilterable payload was served: {entry}" + ); + assert!( + out["notes"].as_array().expect("notes").iter().any(|n| n + .as_str() + .unwrap_or("") + .contains("could not be span-filtered")), + "notes record the payload withholding: {out}" + ); }