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 c67d91051c..84b5f6dd80 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/shards/scan.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/shards/scan.rs @@ -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}; @@ -164,6 +165,20 @@ pub fn fanout_scan(set: &ShardSet, q: &FanoutQuery<'_>) -> Result }) } +/// 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, +} + /// 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 @@ -180,7 +195,8 @@ pub fn fanout_scan(set: &ShardSet, q: &FanoutQuery<'_>) -> Result /// itself still refuses such filters loudly for direct callers. pub struct ShardedBackend { inner: B, - set: Arc, + set: RwLock>, + refresh: Option, topics: Option>, /// Per-query diagnostics recorded during `branch_pools` (the /// monolith-fallback notices, #6665). `notes()` surfaces them; @@ -200,7 +216,8 @@ impl ShardedBackend { pub fn new(inner: B, set: Arc) -> ShardedBackend { ShardedBackend { inner, - set, + set: RwLock::new(set), + refresh: None, topics: None, fallback_notes: Mutex::new(Vec::new()), content: None, @@ -241,8 +258,87 @@ impl ShardedBackend { &self.inner } - pub fn shard_set(&self) -> &Arc { - &self.set + pub fn shard_set(&self) -> Arc { + 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 { + 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(¬e) { + 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 { + 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() } } @@ -314,7 +410,7 @@ impl SearchBackend for ShardedBackend { // 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 { @@ -325,8 +421,8 @@ impl SearchBackend for ShardedBackend { 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()); @@ -387,7 +483,8 @@ impl SearchBackend for ShardedBackend { 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 diff --git a/pkgs/atlas-search/crates/atlas-core/tests/shards.rs b/pkgs/atlas-search/crates/atlas-core/tests/shards.rs index a40979ff68..ca95cf080d 100644 --- a/pkgs/atlas-search/crates/atlas-core/tests/shards.rs +++ b/pkgs/atlas-search/crates/atlas-core/tests/shards.rs @@ -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 = (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 = (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 @@ -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, diff --git a/pkgs/atlas-search/crates/atlas-search/src/main.rs b/pkgs/atlas-search/crates/atlas-search/src/main.rs index 986ff7361f..a3b0990b5f 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/main.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/main.rs @@ -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( @@ -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, diff --git a/pkgs/atlas-search/crates/atlas-search/src/server.rs b/pkgs/atlas-search/crates/atlas-search/src/server.rs index 7a03de8f7d..a017258fd8 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/server.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/server.rs @@ -205,6 +205,13 @@ struct RawClientConfig { struct ServiceConfigFile { listen: Option, vec_table: Option, + /// Shard spec for serve-mode fan-out (#6666 slice 1): the + /// standalone `--shards` grammar (`dir:` or + /// `turso[:]`). Absent = monolith only, as before. + shards: Option, + /// Seconds between shard re-discoveries in serve mode + /// (#6666 slice 1). Default 60; ignored without `shards`. + shard_refresh_seconds: Option, limits: Option, clients: Vec, } @@ -215,8 +222,19 @@ pub struct ServeSettings { pub clients: Vec, pub vec_table: String, pub limits: RuntimeLimits, + /// Shard spec for serve-mode fan-out (#6666 slice 1), in the + /// standalone `--shards` grammar. `None` = monolith only. + pub shards: Option, + /// Interval between shard re-discoveries when `shards` is + /// set; a changed shard set is swapped in atomically and the + /// snapshot-bound result cache invalidates on the new + /// snapshot id. + pub shard_refresh: Duration, } +/// Default shard re-discovery interval for serve mode (#6666). +pub const DEFAULT_SHARD_REFRESH_SECONDS: u64 = 60; + fn home_dir() -> PathBuf { // Home-resolution contract (issues #5640 / #5762): a missing or // empty HOME is an error naming HOME, never a substitute @@ -324,6 +342,19 @@ pub fn load_service_settings( limits.hard_ttl = Duration::from_millis(ms); } validate_limits(&limits)?; + let shards = match raw.shards { + Some(spec) if !spec.trim().is_empty() => Some(spec), + Some(_) => { + return Err("service config shards spec must not be empty".to_string()); + } + None => None, + }; + let shard_refresh_seconds = raw + .shard_refresh_seconds + .unwrap_or(DEFAULT_SHARD_REFRESH_SECONDS); + if shard_refresh_seconds == 0 { + return Err("service config shard_refresh_seconds must be at least 1".to_string()); + } Ok(ServeSettings { listen, clients, @@ -331,6 +362,8 @@ pub fn load_service_settings( .vec_table .unwrap_or_else(|| atlas_core::DEFAULT_VEC_TABLE.to_string()), limits, + shards, + shard_refresh: Duration::from_secs(shard_refresh_seconds), }) } @@ -2646,6 +2679,8 @@ mod tests { ], vec_table: atlas_core::DEFAULT_VEC_TABLE.to_string(), limits, + shards: None, + shard_refresh: Duration::from_secs(DEFAULT_SHARD_REFRESH_SECONDS), } } @@ -2675,6 +2710,47 @@ mod tests { ); } + #[test] + fn service_config_shards_spec_round_trips() { + // #6666 slice 1: `shards` + `shard_refresh_seconds` in the + // service config land on ServeSettings; without `shards` + // the settings keep the monolith default (None). + use std::os::unix::fs::PermissionsExt; + let dir = + std::env::temp_dir().join(format!("atlas-service-shards-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let write = |name: &str, body: &str| { + let path = dir.join(name); + std::fs::write(&path, body).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + path + }; + let client = r#"{"name": "probe", "token": "tok", "ceiling_cap": "personal"}"#; + let sharded = write( + "sharded.json", + &format!( + r#"{{"shards": "dir:/tmp/shards", "shard_refresh_seconds": 5, "clients": [{client}]}}"# + ), + ); + let settings = load_service_settings(&sharded, ServeOverrides::default()).unwrap(); + assert_eq!(settings.shards.as_deref(), Some("dir:/tmp/shards")); + assert_eq!(settings.shard_refresh, Duration::from_secs(5)); + let plain = write("plain.json", &format!(r#"{{"clients": [{client}]}}"#)); + let settings = load_service_settings(&plain, ServeOverrides::default()).unwrap(); + assert_eq!(settings.shards, None); + assert_eq!( + settings.shard_refresh, + Duration::from_secs(DEFAULT_SHARD_REFRESH_SECONDS) + ); + let empty = write( + "empty.json", + &format!(r#"{{"shards": " ", "clients": [{client}]}}"#), + ); + let err = load_service_settings(&empty, ServeOverrides::default()).unwrap_err(); + assert!(err.contains("shards spec must not be empty"), "got: {err}"); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn service_config_rejects_unknown_keys() { // #5632: a misspelled key in service.json must be a loud diff --git a/pkgs/fleet/crates/fleet-search/src/serve.rs b/pkgs/fleet/crates/fleet-search/src/serve.rs index 8b373d7171..d9d3bf8988 100644 --- a/pkgs/fleet/crates/fleet-search/src/serve.rs +++ b/pkgs/fleet/crates/fleet-search/src/serve.rs @@ -327,13 +327,60 @@ pub fn run_with_args(args: ServeArgs) -> i32 { run_settings(settings) } +/// 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 run_settings(settings: ServeSettings) -> i32 { - // The role's only backend: the read-only Turso chain. This is + // The role's backend base: the read-only Turso chain. This is // the whole write-posture story — see the module docs. let backend = match TursoBackend::new(&settings.vec_table) { Ok(b) => b, Err(e) => return fail(EXIT_FAILURE, &e.to_string()), }; + // 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 = match atlas_core::shards::open_from_spec(spec, ceiling, &settings.vec_table) { + Ok(s) => s, + Err(e) => return fail(EXIT_FAILURE, &e.to_string()), + }; + let backend = atlas_core::shards::ShardedBackend::new(backend, set).with_refresh( + spec.clone(), + ceiling, + settings.shard_refresh, + ); + let engine = build_engine(backend, Arc::new(LazyEmbedder::new())); + return match server::serve_forever(settings, engine) { + Ok(()) => EXIT_FAILURE, + Err(m) => fail(EXIT_FAILURE, &m), + }; + } let engine = build_engine(backend, Arc::new(LazyEmbedder::new())); match server::serve_forever(settings, engine) { Ok(()) => EXIT_FAILURE, diff --git a/pkgs/fleet/crates/fleet-search/src/server.rs b/pkgs/fleet/crates/fleet-search/src/server.rs index 61d90ccec6..591c0e8bda 100644 --- a/pkgs/fleet/crates/fleet-search/src/server.rs +++ b/pkgs/fleet/crates/fleet-search/src/server.rs @@ -205,6 +205,13 @@ struct RawClientConfig { struct ServiceConfigFile { listen: Option, vec_table: Option, + /// Shard spec for serve-mode fan-out (#6666 slice 1): the + /// standalone `--shards` grammar (`dir:` or + /// `turso[:]`). Absent = monolith only, as before. + shards: Option, + /// Seconds between shard re-discoveries in serve mode + /// (#6666 slice 1). Default 60; ignored without `shards`. + shard_refresh_seconds: Option, limits: Option, clients: Vec, } @@ -215,8 +222,19 @@ pub struct ServeSettings { pub clients: Vec, pub vec_table: String, pub limits: RuntimeLimits, + /// Shard spec for serve-mode fan-out (#6666 slice 1), in the + /// standalone `--shards` grammar. `None` = monolith only. + pub shards: Option, + /// Interval between shard re-discoveries when `shards` is + /// set; a changed shard set is swapped in atomically and the + /// snapshot-bound result cache invalidates on the new + /// snapshot id. + pub shard_refresh: Duration, } +/// Default shard re-discovery interval for serve mode (#6666). +pub const DEFAULT_SHARD_REFRESH_SECONDS: u64 = 60; + fn home_dir() -> PathBuf { // Home-resolution contract (issues #5640 / #5762): a missing or // empty HOME is an error naming HOME, never a substitute @@ -324,6 +342,19 @@ pub fn load_service_settings( limits.hard_ttl = Duration::from_millis(ms); } validate_limits(&limits)?; + let shards = match raw.shards { + Some(spec) if !spec.trim().is_empty() => Some(spec), + Some(_) => { + return Err("service config shards spec must not be empty".to_string()); + } + None => None, + }; + let shard_refresh_seconds = raw + .shard_refresh_seconds + .unwrap_or(DEFAULT_SHARD_REFRESH_SECONDS); + if shard_refresh_seconds == 0 { + return Err("service config shard_refresh_seconds must be at least 1".to_string()); + } Ok(ServeSettings { listen, clients, @@ -331,6 +362,8 @@ pub fn load_service_settings( .vec_table .unwrap_or_else(|| atlas_core::DEFAULT_VEC_TABLE.to_string()), limits, + shards, + shard_refresh: Duration::from_secs(shard_refresh_seconds), }) } @@ -2646,6 +2679,8 @@ mod tests { ], vec_table: atlas_core::DEFAULT_VEC_TABLE.to_string(), limits, + shards: None, + shard_refresh: Duration::from_secs(DEFAULT_SHARD_REFRESH_SECONDS), } } @@ -2675,6 +2710,47 @@ mod tests { ); } + #[test] + fn service_config_shards_spec_round_trips() { + // #6666 slice 1: `shards` + `shard_refresh_seconds` in the + // service config land on ServeSettings; without `shards` + // the settings keep the monolith default (None). + use std::os::unix::fs::PermissionsExt; + let dir = + std::env::temp_dir().join(format!("atlas-service-shards-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let write = |name: &str, body: &str| { + let path = dir.join(name); + std::fs::write(&path, body).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + path + }; + let client = r#"{"name": "probe", "token": "tok", "ceiling_cap": "personal"}"#; + let sharded = write( + "sharded.json", + &format!( + r#"{{"shards": "dir:/tmp/shards", "shard_refresh_seconds": 5, "clients": [{client}]}}"# + ), + ); + let settings = load_service_settings(&sharded, ServeOverrides::default()).unwrap(); + assert_eq!(settings.shards.as_deref(), Some("dir:/tmp/shards")); + assert_eq!(settings.shard_refresh, Duration::from_secs(5)); + let plain = write("plain.json", &format!(r#"{{"clients": [{client}]}}"#)); + let settings = load_service_settings(&plain, ServeOverrides::default()).unwrap(); + assert_eq!(settings.shards, None); + assert_eq!( + settings.shard_refresh, + Duration::from_secs(DEFAULT_SHARD_REFRESH_SECONDS) + ); + let empty = write( + "empty.json", + &format!(r#"{{"shards": " ", "clients": [{client}]}}"#), + ); + let err = load_service_settings(&empty, ServeOverrides::default()).unwrap_err(); + assert!(err.contains("shards spec must not be empty"), "got: {err}"); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn service_config_rejects_unknown_keys() { // #5632: a misspelled key in service.json must be a loud diff --git a/pkgs/fleet/crates/fleet-search/tests/serve_contract.rs b/pkgs/fleet/crates/fleet-search/tests/serve_contract.rs index 3e3d6cf665..838a2af1b1 100644 --- a/pkgs/fleet/crates/fleet-search/tests/serve_contract.rs +++ b/pkgs/fleet/crates/fleet-search/tests/serve_contract.rs @@ -165,6 +165,8 @@ fn start() -> Harness { ], vec_table: atlas_core::DEFAULT_VEC_TABLE.to_string(), limits: RuntimeLimits::default(), + shards: None, + shard_refresh: std::time::Duration::from_secs(60), }; let handle = start_server(settings, engine).expect("service starts on loopback"); Harness {