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
115 changes: 106 additions & 9 deletions pkgs/atlas-search/crates/atlas-core/src/shards/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
//! against a single-store oracle.

use std::collections::BTreeSet;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};

use super::content::ContentStores;
use super::{ShardInfo, ShardSet, Tier, TierCeiling};
Expand Down Expand Up @@ -164,6 +165,20 @@ pub fn fanout_scan(set: &ShardSet, q: &FanoutQuery<'_>) -> Result<FanoutResult>
})
}

/// Periodic shard re-discovery for a serving [`ShardedBackend`]
/// (#6666 slice 1): re-open the shard set from `spec` on an
/// interval and swap it in atomically when its snapshot changes,
/// so new shards and promotion batches are observed without a
/// restart. The swap is the whole mechanism: the result cache is
/// snapshot-bound (#9943), so a changed `snapshot_id()` invalidates
/// cached results on the next query.
pub struct ShardRefresh {
spec: String,
ceiling: TierCeiling,
interval: Duration,
last_check: Mutex<Instant>,
}

/// A [`SearchBackend`] that serves the **vector** branch from the
/// shard core and delegates everything else (FTS, details,
/// neighbors, messages, notes) to the wrapped backend — the libSQL
Expand All @@ -180,7 +195,8 @@ pub fn fanout_scan(set: &ShardSet, q: &FanoutQuery<'_>) -> Result<FanoutResult>
/// itself still refuses such filters loudly for direct callers.
pub struct ShardedBackend<B> {
inner: B,
set: Arc<ShardSet>,
set: RwLock<Arc<ShardSet>>,
refresh: Option<ShardRefresh>,
topics: Option<Vec<String>>,
/// Per-query diagnostics recorded during `branch_pools` (the
/// monolith-fallback notices, #6665). `notes()` surfaces them;
Expand All @@ -200,7 +216,8 @@ impl<B: SearchBackend> ShardedBackend<B> {
pub fn new(inner: B, set: Arc<ShardSet>) -> ShardedBackend<B> {
ShardedBackend {
inner,
set,
set: RwLock::new(set),
refresh: None,
topics: None,
fallback_notes: Mutex::new(Vec::new()),
content: None,
Expand Down Expand Up @@ -241,8 +258,87 @@ impl<B: SearchBackend> ShardedBackend<B> {
&self.inner
}

pub fn shard_set(&self) -> &Arc<ShardSet> {
&self.set
pub fn shard_set(&self) -> Arc<ShardSet> {
self.set
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone()
}

/// Enable periodic re-discovery (#6666 slice 1): every
/// `interval`, the shard set is re-opened from `spec` at
/// `ceiling` and swapped in when its snapshot changed. A
/// zero interval disables the opportunistic checks (explicit
/// [`ShardedBackend::refresh_shard_set`] calls still work).
pub fn with_refresh(
mut self,
spec: String,
ceiling: TierCeiling,
interval: Duration,
) -> ShardedBackend<B> {
self.refresh = Some(ShardRefresh {
spec,
ceiling,
interval,
// Backdate so the first query after the interval has
// elapsed checks; construction itself just discovered.
last_check: Mutex::new(Instant::now()),
});
self
}

/// Re-open the shard set from the refresh spec now and swap it
/// in if its snapshot changed. Returns true when a swap
/// happened. A discovery failure keeps the current set and
/// records a diagnostic note; it never fails the caller.
pub fn refresh_shard_set(&self) -> bool {
let Some(refresh) = &self.refresh else {
return false;
};
let new = match super::open_from_spec(
&refresh.spec,
refresh.ceiling,
self.set
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.vec_table(),
) {
Ok(new) => new,
Err(e) => {
if let Ok(mut notes) = self.fallback_notes.lock() {
let note = format!("shard re-discovery failed; serving the previous set: {e}");
if !notes.contains(&note) {
notes.push(note);
}
}
return false;
}
};
let mut guard = self
.set
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if guard.snapshot_id() == new.snapshot_id() {
return false;
}
*guard = new;
true
}

/// The shard set to serve from: when refresh is configured and
/// the interval has elapsed, re-discover first (the check is
/// cheap and at most once per interval per backend).
fn current_set(&self) -> Arc<ShardSet> {
if let Some(refresh) = &self.refresh
&& !refresh.interval.is_zero()
&& let Ok(mut last) = refresh.last_check.lock()
&& last.elapsed() >= refresh.interval
{
*last = Instant::now();
drop(last);
self.refresh_shard_set();
}
self.shard_set()
}
}

Expand Down Expand Up @@ -314,7 +410,7 @@ impl<B: SearchBackend> SearchBackend for ShardedBackend<B> {
// The shard set IS the corpus state for this backend: its
// snapshot id moves on every re-shard / promotion, which
// is exactly the result-cache invalidation signal (#9943).
Some(self.set.snapshot_id())
Some(self.current_set().snapshot_id())
}

fn vec_table(&self) -> &str {
Expand All @@ -325,8 +421,8 @@ impl<B: SearchBackend> SearchBackend for ShardedBackend<B> {
let mut notes = self.inner.notes();
notes.push(format!(
"vector branch served by shard fan-out over {} shards (snapshot {})",
self.set.shards().len(),
&self.set.snapshot_id()[..12]
self.shard_set().shards().len(),
&self.shard_set().snapshot_id()[..12]
));
if let Ok(fallback) = self.fallback_notes.lock() {
notes.extend(fallback.iter().cloned());
Expand Down Expand Up @@ -387,7 +483,8 @@ impl<B: SearchBackend> SearchBackend for ShardedBackend<B> {
global_top_k: q.global_top_k,
vector_backend: q.vector_backend,
};
let (set, topics) = (&*self.set, self.topics.as_deref());
let set = self.current_set();
let (set, topics) = (&*set, self.topics.as_deref());
std::thread::scope(|scope| {
let vec_handle = q
.query_vector
Expand Down
46 changes: 45 additions & 1 deletion pkgs/atlas-search/crates/atlas-core/tests/shards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,50 @@ impl SearchBackend for Monolith {
}
}

#[test]
fn sharded_backend_refresh_swaps_in_new_shards_and_moves_the_snapshot() {
// #6666 slice 1 oracle: the shard files on disk. A shard file
// that appears after the set was opened is invisible until
// re-discovery; after refresh it is served, and the snapshot
// id — the result-cache binding (#9943) — has moved, which is
// what invalidates serve-mode cached results on rotation.
let dir = temp_dir("refresh");
let mut rng = Rng(7);
let chunks: Vec<Chunk> = (1..=5)
.map(|id| Chunk {
id,
sens: "personal",
vec: rng.vec(),
})
.collect();
write_shard(&dir, "atlas-core-internal-work-01", &chunks);
let spec = format!("dir:{}", dir.display());
let set =
atlas_core::shards::open_from_spec(&spec, TierCeiling(Tier::Internal), DEFAULT_VEC_TABLE)
.unwrap();
let be = ShardedBackend::new(
Monolith {
seen: Mutex::new(vec![]),
},
set,
)
.with_refresh(spec, TierCeiling(Tier::Internal), Duration::ZERO);
let before = be.snapshot_id().unwrap();
assert_eq!(be.shard_set().shards().len(), 1);
assert!(!be.refresh_shard_set(), "nothing changed on disk: no swap");
let more: Vec<Chunk> = (6..=9)
.map(|id| Chunk {
id,
sens: "personal",
vec: rng.vec(),
})
.collect();
write_shard(&dir, "atlas-core-internal-media-01", &more);
assert!(be.refresh_shard_set(), "the new shard file must swap in");
assert_eq!(be.shard_set().shards().len(), 2);
assert_ne!(be.snapshot_id().unwrap(), before);
}

#[test]
fn sharded_backend_reports_the_shard_set_snapshot_id() {
// #9943: the service's result cache binds entries to the
Expand Down Expand Up @@ -984,7 +1028,7 @@ fn sharded_backend_routes_filtered_queries_to_the_monolith() {
// fanout_scan itself still refuses the same filters loudly.
assert!(
fanout_scan(
be.shard_set(),
&be.shard_set(),
&FanoutQuery {
qvec: &q,
shard_top_k: 10,
Expand Down
45 changes: 45 additions & 0 deletions pkgs/atlas-search/crates/atlas-search/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -998,6 +998,32 @@ fn cmd_get_chunk(args: GetChunkArgs) -> Result<(), CliError> {
Ok(())
}

/// The shard discovery ceiling for serve mode (#6666 slice 1):
/// the highest client ceiling cap in the service config.
/// Discovery opens at the service maximum; per-caller ceilings
/// only narrow the set at query time (`ShardSet::select`).
fn serve_discovery_ceiling(clients: &[server::ClientConfig]) -> atlas_core::shards::TierCeiling {
fn height(t: atlas_core::shards::Tier) -> u8 {
match t {
atlas_core::shards::Tier::Public => 0,
atlas_core::shards::Tier::Internal => 1,
atlas_core::shards::Tier::Secret => 2,
}
}
let mut ceiling =
atlas_core::shards::TierCeiling::from_sensitivity(atlas_core::Sensitivity::Shareable);
for c in clients {
let cap = atlas_core::shards::TierCeiling::from_sensitivity(
atlas_core::Sensitivity::from_name(c.ceiling_cap.name())
.unwrap_or(atlas_core::Sensitivity::Personal),
);
if height(cap.0) > height(ceiling.0) {
ceiling = cap;
}
}
ceiling
}

fn cmd_serve(args: ServeArgs) -> Result<(), CliError> {
let path = server::resolve_service_config_path(args.config.as_deref());
let settings = server::load_service_settings(
Expand All @@ -1014,6 +1040,25 @@ fn cmd_serve(args: ServeArgs) -> Result<(), CliError> {
CliEmbedder::new(atlas_core::DEFAULT_MODEL.to_string(), EmbedderChoice::Auto),
)));
let state_fn = shared.state_fn();
// Serve-mode shard fan-out (#6666 slice 1): with a `shards`
// spec in the service config, the vector branch is served by
// the shard set, re-discovered on the configured interval;
// without one the monolith serves exactly as before.
if let Some(spec) = &settings.shards {
let ceiling = serve_discovery_ceiling(&settings.clients);
let set = open_from_spec(spec, ceiling, &settings.vec_table).map_err(map_err)?;
let backend = ShardedBackend::new(backend, set).with_refresh(
spec.clone(),
ceiling,
settings.shard_refresh,
);
let engine = std::sync::Arc::new(server::CoreSearchEngine::new(
std::sync::Arc::new(backend),
shared,
state_fn,
));
return server::serve_forever(settings, engine).map_err(|m| (1, m));
}
let engine = std::sync::Arc::new(server::CoreSearchEngine::new(
std::sync::Arc::new(backend),
shared,
Expand Down
Loading