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
10 changes: 10 additions & 0 deletions pkgs/atlas-search/book/concepts/corpus-and-provenance.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ 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.
Three read-side slices followed on 2026-11-23/24 and closed the
loop from occurrence rows back to roots: `lookup_by_hash` fans out
over the shards the caller's ceiling admits (keyed by canonical
hash, per-row sensitivity enforced, pre-registry shards skipped)
and `get-chunk` attaches the rows as an `occurrences` array;
`resolve_source` answers exact-match, read-only root lookups; and
the lookup takes an optional registry connection so each
occurrence carries its `root_id` when registered — unregistered
locators stay unattributed, and the no-registry wire shape is
unchanged. Serving-side wiring of the catalog path remains open.

**Phase 2 — the extracts store and its backfill (landed 2026-11-23).** The
extracts store lives on the laptop under `~/atlas/extracts/`. Objects are
Expand Down
37 changes: 34 additions & 3 deletions pkgs/atlas-search/crates/atlas-core/src/occurrences.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@

use serde_json::Value as Json;

use rusqlite::Connection;

use crate::error::{Error, Result};
use crate::filters::Sensitivity;
use crate::shards::{ShardSet, Tier, TierCeiling};
use crate::source_registry::resolve_source;
use crate::types::{Stmt, Value};

/// One recorded place a chunk's content was found (#3125 rule 3).
Expand All @@ -37,21 +40,33 @@ pub struct ChunkOccurrence {
pub span_end: i64,
/// When the aggregator observed the content.
pub observed_at: String,
/// When the lookup ran with a source registry attached
/// (#3125 slice 6) and `source` is registered under a root,
/// that root's id. `None` when no registry was attached or the
/// locator is unregistered — the occurrence is then unattributed,
/// never misattributed.
pub root_id: Option<String>,
}

impl ChunkOccurrence {
/// The wire form `get-chunk` attaches as one `occurrences`
/// array element.
/// array element. `root_id` is present only when the lookup
/// attributed the occurrence to a registered root, so the
/// no-registry wire shape is unchanged.
pub fn to_json(&self) -> Json {
serde_json::json!({
let mut v = 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,
})
});
if let Some(root_id) = &self.root_id {
v["root_id"] = Json::String(root_id.clone());
}
v
}
}

Expand All @@ -70,11 +85,23 @@ impl ChunkOccurrence {
/// 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).
///
/// `registry` is the phase-4-catalog-side source registry (#3125
/// slice 6: `source_registry`'s tables in whichever database the
/// caller opens). When attached, each occurrence's `source` locator
/// is resolved to its registered root and carried as `root_id`;
/// unregistered locators stay unattributed (`None`), never guessed.
/// `None` keeps the pre-registry behavior exactly: unattributed rows
/// and no wire change. A registry that answers with a genuine
/// failure fails the lookup — same fail-closed philosophy as a
/// failing shard: a partial attribution presented as complete would
/// be as wrong as a partial search answer.
pub fn lookup_by_hash(
set: &ShardSet,
tier_ceiling: TierCeiling,
caller_ceiling: Sensitivity,
canonical_hash: &str,
registry: Option<&Connection>,
) -> Result<Vec<ChunkOccurrence>> {
let mut out = Vec::new();
for shard in set.select(tier_ceiling, None)? {
Expand Down Expand Up @@ -132,6 +159,10 @@ pub fn lookup_by_hash(
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(),
root_id: match registry {
Some(conn) => resolve_source(conn, &source)?.map(|r| r.root_id),
None => None,
},
});
}
}
Expand Down
29 changes: 29 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 @@ -11,6 +11,8 @@ use std::collections::BTreeSet;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};

use rusqlite::Connection;

use super::content::ContentStores;
use super::{ShardInfo, ShardSet, Tier, TierCeiling};
use crate::backend::SearchBackend;
Expand Down Expand Up @@ -205,6 +207,11 @@ pub struct ShardedBackend<B> {
fallback_notes: Mutex<Vec<String>>,
/// Tier content stores for hydration (#6664), when attached.
content: Option<Arc<ContentStores>>,
/// Source registry for occurrence attribution (#3125 slice 6),
/// when attached: `lookup_by_hash` resolves each occurrence's
/// source locator to its registered root. Absent, occurrence
/// rows are unattributed exactly as before.
source_registry: Mutex<Option<Connection>>,
/// The successor switch (#6664): serve hydration from
/// `content` instead of the wrapped monolith. The service's
/// successor protocol field (coordination issue #5668) maps
Expand All @@ -221,6 +228,7 @@ impl<B: SearchBackend> ShardedBackend<B> {
topics: None,
fallback_notes: Mutex::new(Vec::new()),
content: None,
source_registry: Mutex::new(None),
hydrate_from_content: false,
}
}
Expand Down Expand Up @@ -254,6 +262,22 @@ impl<B: SearchBackend> ShardedBackend<B> {
self
}

/// Attach a source registry for occurrence attribution (#3125
/// slice 6). The connection is the caller's — typically the
/// phase-4 catalog database holding `source_registry`'s tables —
/// and is used read-only by occurrence lookups (resolution never
/// creates or alters rows beyond the registry's own additive
/// `ensure`). Without it, `occurrences` serves unattributed rows
/// exactly as before; serving-side wiring of the catalog path is
/// the named next slice.
pub fn with_source_registry(self, conn: Connection) -> ShardedBackend<B> {
*self
.source_registry
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(conn);
self
}

pub fn inner(&self) -> &B {
&self.inner
}
Expand Down Expand Up @@ -540,11 +564,16 @@ impl<B: SearchBackend> SearchBackend for ShardedBackend<B> {
tier_ceiling: TierCeiling,
caller_ceiling: crate::filters::Sensitivity,
) -> Result<Vec<crate::occurrences::ChunkOccurrence>> {
let guard = self
.source_registry
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
crate::occurrences::lookup_by_hash(
&self.current_set(),
tier_ceiling,
caller_ceiling,
canonical_hash,
guard.as_ref(),
)
}
}
Expand Down
140 changes: 139 additions & 1 deletion pkgs/atlas-search/crates/atlas-core/tests/occurrences.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ fn lookup_finds_every_occurrence_across_shards_and_skips_legacy_shards() {
TierCeiling(Tier::Internal),
Sensitivity::LocalOnly,
HASH,
None,
)
.unwrap();
assert_eq!(
Expand All @@ -202,6 +203,7 @@ fn lookup_finds_every_occurrence_across_shards_and_skips_legacy_shards() {
span_start: 0,
span_end: 17,
observed_at: NOW.into(),
root_id: None,
},
ChunkOccurrence {
shard: "atlas-core-internal-work-01".into(),
Expand All @@ -211,6 +213,7 @@ fn lookup_finds_every_occurrence_across_shards_and_skips_legacy_shards() {
span_start: 0,
span_end: 17,
observed_at: NOW.into(),
root_id: None,
},
],
"internal rows only, ordered by shard; legacy shard contributes nothing and no error"
Expand All @@ -222,6 +225,7 @@ fn lookup_finds_every_occurrence_across_shards_and_skips_legacy_shards() {
TierCeiling(Tier::Secret),
Sensitivity::SecretBearing,
HASH,
None,
)
.unwrap();
assert_eq!(secret.len(), 3, "secret ceiling adds the secret-tier row");
Expand All @@ -232,7 +236,8 @@ fn lookup_finds_every_occurrence_across_shards_and_skips_legacy_shards() {
&set,
TierCeiling(Tier::Internal),
Sensitivity::LocalOnly,
"00"
"00",
None,
)
.unwrap()
.is_empty()
Expand Down Expand Up @@ -418,6 +423,7 @@ fn occurrence_rows_are_filtered_by_their_own_chunk_sensitivity_not_just_shard_ti
TierCeiling(Tier::Internal),
Sensitivity::Personal,
HASH,
None,
)
.unwrap();
assert_eq!(
Expand All @@ -434,6 +440,7 @@ fn occurrence_rows_are_filtered_by_their_own_chunk_sensitivity_not_just_shard_ti
TierCeiling(Tier::Internal),
Sensitivity::LocalOnly,
HASH,
None,
)
.unwrap();
assert_eq!(
Expand All @@ -451,3 +458,134 @@ fn _unused(_r: &Mutex<()>) -> BranchHit {
dist: None,
}
}

/// An in-memory source registry holding one root (`repo`, based at
/// `repo@abc:`) with one registered locator; any other locator is
/// unregistered by construction.
fn registry_with_one_root() -> rusqlite::Connection {
use atlas_core::source_registry::{register_locator, register_source_root};
let conn = rusqlite::Connection::open_in_memory().expect("in-memory registry");
register_source_root(&conn, "repo", "repo@abc:", NOW).expect("root");
register_locator(&conn, "repo", "repo@abc:infra/dns/a.yaml", NOW).expect("locator");
conn
}

#[test]
fn lookup_attributes_occurrences_to_registered_roots_only() {
// #3125 slice 6: with a registry attached, the occurrence whose
// source locator is registered resolves to its root; the
// unregistered locator stays unattributed (None), never guessed.
// Oracle: slice 5's exact-match resolution contract — the
// registry answers "which root holds this locator", and the
// lookup carries that answer onto the row.
let dir = temp_dir("attribution");
fixture(
&dir,
"atlas-core-internal-work-01",
&[
("repo@abc:infra/dns/a.yaml", 0, 17),
("repo@abc:infra/dns/b.yaml", 0, 17),
],
false,
);
let set = discover_set(&dir, Tier::Internal);
let registry = registry_with_one_root();

let found = lookup_by_hash(
&set,
TierCeiling(Tier::Internal),
Sensitivity::LocalOnly,
HASH,
Some(&registry),
)
.unwrap();
assert_eq!(found.len(), 2, "both shard rows surface under the ceiling");
let by_source: std::collections::HashMap<&str, &ChunkOccurrence> =
found.iter().map(|o| (o.source.as_str(), o)).collect();
assert_eq!(
by_source["repo@abc:infra/dns/a.yaml"].root_id.as_deref(),
Some("repo"),
"registered locator attributes to its root"
);
assert_eq!(
by_source["repo@abc:infra/dns/b.yaml"].root_id, None,
"unregistered locator stays unattributed, never misattributed"
);

// Without a registry the same lookup is unattributed and the
// wire form carries no root_id key at all.
let plain = lookup_by_hash(
&set,
TierCeiling(Tier::Internal),
Sensitivity::LocalOnly,
HASH,
None,
)
.unwrap();
assert!(
plain.iter().all(|o| o.root_id.is_none()),
"no registry means no attribution"
);
assert!(
plain.iter().all(|o| o.to_json().get("root_id").is_none()),
"unattributed occurrences keep the pre-registry wire shape"
);
}

#[test]
fn sharded_backend_with_registry_serves_attribution_in_get_chunk() {
// End to end: a registry-attached ShardedBackend reports
// root_id on the registered occurrence through get-chunk, and
// omits the key on the unregistered one; without the
// attachment neither row carries the key.
let dir = temp_dir("attribchunk");
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,
);
let set = std::sync::Arc::new(discover_set(&dir, Tier::Secret));

let plain = ShardedBackend::new(Monolith { chunk_id: 7 }, set.clone());
let out = run_get_chunk(&plain, 7, 0).unwrap();
let occ = out.get("occurrences").unwrap().as_array().unwrap();
assert!(
occ.iter().all(|o| o.get("root_id").is_none()),
"no registry attached: wire shape unchanged"
);

let registry = registry_with_one_root();
let attributed =
ShardedBackend::new(Monolith { chunk_id: 7 }, set).with_source_registry(registry);
let out = run_get_chunk(&attributed, 7, 0).unwrap();
let occ = out
.get("occurrences")
.expect("occurrences present")
.as_array()
.unwrap();
assert_eq!(occ.len(), 2);
let by_source: std::collections::HashMap<&str, &serde_json::Value> = occ
.iter()
.map(|o| (o.get("source").and_then(|s| s.as_str()).unwrap(), o))
.collect();
assert_eq!(
by_source["repo@abc:infra/dns/a.yaml"]
.get("root_id")
.and_then(|v| v.as_str()),
Some("repo"),
"registered occurrence resolves through get-chunk"
);
assert!(
by_source["repo@abc:infra/dns/b.yaml"]
.get("root_id")
.is_none(),
"unregistered occurrence keeps the old wire shape"
);
}