Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(gateway): fence configuration exports against concurrent updates (#387)
Attila László Nagy1b83d3e06cf4
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex dec776a1f..d58ca63e6 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -149,6 +149,18 @@ Startup short-circuits:Returns `BootstrapOutcome { epoch, bundles_hash, bundle_config_hashes_hash, applied, failed, total }`.+The fetch captures the local registry generation before its first request.+Installation checks that generation under the registry's write lock and publishes+the model/bundle surface and exported bundle/pool hashes together. A delta,+reload, or another bootstrap that changes the registry during the fetch makes+the export stale: it is refused without changing the registry or advancing its+epoch/fingerprints, and the caller retries. This prevents an older in-flight+export from erasing a newer model update while leaving the epoch ahead of the+installed models. The network fetch never holds the registry write lock.+The poller retains a pending retry after a failed bootstrap, even if a concurrent+delta makes epochs and fingerprints match. Only a successful bootstrap clears+that retry; failed epoch reads leave it pending.+- If **any** model entry failed (`outcome.failed > 0`), `bootstrap_once` returns `BootstrapError::PartialApply` and **advances neither `ConfigEpoch`, `BundlesHash`, nor `BundleConfigHashesHash`**. The poller will detect drift on the next tick and retry.- If all entries applied, `bootstrap_once` advances `ConfigEpoch` via `set_max(outcome.epoch)`, stores `outcome.bundles_hash` into `BundlesHash`, stores `outcome.bundle_config_hashes_hash` into `BundleConfigHashesHash`, and the retry task exits.diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex 5733529a3..1e3dc6db1 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -76,7 +76,7 @@ use crate::observability::metrics::{self as telemetry, ConfigOperation, ConfigOuuse crate::state::bundle_config_hashes_hash::BundleConfigHashesHash;use crate::state::bundles_hash::BundlesHash;use crate::state::config_epoch::ConfigEpoch;-use crate::state::model_registry::ModelRegistry;+use crate::state::model_registry::{AuthoritativeHashes, ModelRegistry};use crate::types::bundle::{BundleInfo, DEFAULT_ENGINE, KNOWN_ENGINES};use crate::types::model::ModelConfig;@@ -504,6 +504,7 @@ impl BootstrapClient {&self,registry: &ModelRegistry,) -> Result<BootstrapOutcome, BootstrapError> {+ let generation = registry.capture_generation();// Snapshot the bundles hash BEFORE fetching bundles. See the// `BootstrapOutcome::bundles_hash` doc comment for why the pre-fetch// ordering matters — storing a hash that's NEWER than the bundle@@ -585,11 +586,17 @@ impl BootstrapClient {let mut applied = 0usize;if failed == 0 {- match registry.replace_authoritative_surface(bundles, configs) {+ match registry.replace_authoritative_surface_if_current(+ &generation,+ bundles,+ configs,+ AuthoritativeHashes {+ bundle: snapshot.bundle_config_hashes,+ pool: snapshot.bundle_pool_config_hashes,+ },+ ) {Ok(count) => {applied = count;- registry.install_bundle_config_hashes(snapshot.bundle_config_hashes);- registry.install_bundle_pool_config_hashes(snapshot.bundle_pool_config_hashes);}Err(e) => {warn!(error = %e, "failed to install authoritative config export");@@ -1255,6 +1262,45 @@ mod tests {.unwrap();}+ #[tokio::test]+ async fn bootstrap_preserves_delta_applied_while_export_is_in_flight() {+ let server = MockServer::start().await;+ let (registry, _tmp) = make_registry();+ mount_default_bundles(&server).await;+ mount_default_epoch(&server, 2, "deadbeef").await;+ let epoch = ConfigEpoch::new();+ let delta_registry = registry.clone();+ let delta_epoch = epoch.clone();+ Mock::given(method("GET"))+ .and(path("/v1/configs/export"))+ .respond_with(move |_: &wiremock::Request| {+ delta_registry+ .add_model_config(model_config("test/new-model"))+ .unwrap();+ delta_epoch.set_max(2);+ ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "snapshot_version": 1,+ "epoch": 1,+ "generated_at": "2026-04-17T00:00:00Z",+ "models": [],+ }))+ })+ .mount(&server)+ .await;+ let client = BootstrapClient::new(server.uri(), None).unwrap();+ let outcome = bootstrap_once(+ &client,+ registry.as_ref(),+ &epoch,+ &BundlesHash::new(),+ &BundleConfigHashesHash::new(),+ )+ .await;+ assert!(outcome.is_err(), "stale in-flight export must be retried");+ assert_eq!(epoch.get(), 2);+ assert!(registry.get_model_info("test/new-model").is_some());+ }+#[tokio::test]async fn bootstrap_once_updates_config_epoch() {let server = MockServer::start().await;diff --git a/packages/sie_gateway/src/state/config_poller.rs b/packages/sie_gateway/src/state/config_poller.rsindex 8b4bb183f..6b8a4150a 100644--- a/packages/sie_gateway/src/state/config_poller.rs+++ b/packages/sie_gateway/src/state/config_poller.rs@@ -115,6 +115,7 @@ pub fn spawn(// No need to hammer /epoch before at least one interval has passed.ticker.tick().await;+ let mut retry_bootstrap = false;loop {ticker.tick().await;let local_epoch_val = config_epoch.get();@@ -207,6 +208,7 @@ pub fn spawn(.await{Ok(_) => {+ retry_bootstrap = false;// `bootstrap_once` advanced via `set_max`, which is// a no-op while local > remote. Unconditionally// reset now that the registry is in a known state.@@ -221,6 +223,7 @@ pub fn spawn();}Err(e) => {+ retry_bootstrap = true;telemetry::record_config_operation(ConfigOperation::Reconcile,telemetry_outcome(&e),@@ -231,7 +234,8 @@ pub fn spawn();}}- } else if remote_epoch > local_epoch_val+ } else if retry_bootstrap+ || remote_epoch > local_epoch_val|| bundles_hash_drift|| bundle_config_hashes_hash_drift{@@ -240,7 +244,9 @@ pub fn spawn(remote_epoch = remote_epoch,bundles_hash_drift,bundle_config_hashes_hash_drift,- reason = if remote_epoch > local_epoch_val {+ reason = if retry_bootstrap {+ "previous bootstrap failed"+ } else if remote_epoch > local_epoch_val {"epoch ahead"} else if bundles_hash_drift {"bundle hash changed"@@ -258,11 +264,15 @@ pub fn spawn().await{- Ok(_) => telemetry::record_config_operation(- ConfigOperation::Reconcile,- ConfigOutcome::Success,- ),+ Ok(_) => {+ retry_bootstrap = false;+ telemetry::record_config_operation(+ ConfigOperation::Reconcile,+ ConfigOutcome::Success,+ );+ }Err(e) => {+ retry_bootstrap = true;telemetry::record_config_operation(ConfigOperation::Reconcile,telemetry_outcome(&e),@@ -356,6 +366,66 @@ mod tests {/// Without this, a sie-config redeploy that adds a bundle would not/// propagate to the gateway until the next model write bumped the/// epoch — exactly the operational gap that motivates this change.+ #[tokio::test]+ async fn fenced_bootstrap_retries_after_delta_closes_epoch_gap() {+ let server = MockServer::start().await;+ mount_bundle_endpoints(&server).await;+ Mock::given(method("GET"))+ .and(path("/v1/configs/epoch"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "epoch": 2,+ "bundles_hash": "stable",+ })))+ .mount(&server)+ .await;+ let (registry, _tmp) = make_registry();+ let epoch = ConfigEpoch::new();+ let hashes = BundlesHash::new();+ hashes.store("stable".into());+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let observed = attempts.clone();+ let delta_registry = registry.clone();+ let delta_epoch = epoch.clone();+ Mock::given(method("GET"))+ .and(path("/v1/configs/export"))+ .respond_with(move |_: &wiremock::Request| {+ if observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {+ delta_registry.reload();+ delta_epoch.set_max(2);+ }+ ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "snapshot_version": 1,+ "epoch": 2,+ "generated_at": "2026-04-17T00:00:00Z",+ "models": [],+ }))+ })+ .mount(&server)+ .await;+ let handle = spawn(+ Some(&server.uri()),+ None,+ None,+ registry,+ epoch.clone(),+ hashes,+ BundleConfigHashesHash::new(),+ Duration::from_millis(20),+ )+ .unwrap();+ let result = tokio::time::timeout(Duration::from_secs(3), async {+ while attempts.load(std::sync::atomic::Ordering::SeqCst) < 2 {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await;+ tokio::time::sleep(Duration::from_millis(100)).await;+ handle.abort();+ result.expect("fenced export must retry even when epochs and hashes match");+ assert_eq!(epoch.get(), 2);+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 2);+ }+#[tokio::test]async fn bundles_hash_drift_triggers_bootstrap_without_epoch_advance() {let server = MockServer::start().await;diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 13dafc0fb..6710bf138 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -156,6 +156,12 @@ struct RegistrySnapshot {bundle_pool_config_hashes: HashMap<(String, String), String>,}+#[derive(Default)]+pub(crate) struct AuthoritativeHashes {+ pub bundle: HashMap<String, String>,+ pub pool: HashMap<String, HashMap<String, String>>,+}+/// Opaque handle to one immutable [`ModelRegistry`] snapshot generation.////// Derived-state publishers can compute every value from this handle, perform@@ -2153,7 +2159,7 @@ impl ModelRegistry {&self,configs: Vec<ModelConfig>,) -> Result<usize, String> {- self.apply_authoritative(None, configs)+ self.apply_authoritative(None, configs, None, AuthoritativeHashes::default())}/// Install a matched bundle set and model export as ONE snapshot.@@ -2163,24 +2169,42 @@ impl ModelRegistry {/// retention on the combined result, means a bundle change that only/// makes sense together with its model change can never be half-applied/// or refused on the strength of the half already installed.+ #[allow(dead_code)]pub fn replace_authoritative_surface(&self,bundles: Vec<BundleInfo>,configs: Vec<ModelConfig>,) -> Result<usize, String> {- self.apply_authoritative(Some(bundles), configs)+ self.apply_authoritative(Some(bundles), configs, None, AuthoritativeHashes::default())+ }++ pub(crate) fn replace_authoritative_surface_if_current(+ &self,+ generation: &ModelRegistryGeneration,+ bundles: Vec<BundleInfo>,+ configs: Vec<ModelConfig>,+ hashes: AuthoritativeHashes,+ ) -> Result<usize, String> {+ self.apply_authoritative(Some(bundles), configs, Some(generation), hashes)}fn apply_authoritative(&self,bundles: Option<Vec<BundleInfo>>,configs: Vec<ModelConfig>,+ generation: Option<&ModelRegistryGeneration>,+ hashes: AuthoritativeHashes,) -> Result<usize, String> {let _write = self.write_lock.lock().expect("ModelRegistry write_lock poisoned");let old_snap = self.snapshot.load();+ if generation.is_some_and(|expected| !Arc::ptr_eq(&old_snap, &expected.snapshot)) {+ return Err(+ "registry changed while fetching authoritative export; retry required".into(),+ );+ }let new_bundles: HashMap<String, BundleInfo> = match bundles {Some(bundles) => bundles.into_iter().map(|b| (b.name.clone(), b)).collect(),None => old_snap.bundles.clone(),@@ -2189,9 +2213,39 @@ impl ModelRegistry {let (new_models, new_model_names_lower) =Self::build_authoritative_models(configs, &new_bundles)?;- let bundle_config_hashes = Self::rebuild_bundle_config_hashes(&new_bundles, &new_models);- let bundle_pool_config_hashes =+ let mut bundle_config_hashes =+ Self::rebuild_bundle_config_hashes(&new_bundles, &new_models);+ let mut bundle_pool_config_hashes =Self::rebuild_bundle_pool_config_hashes(&new_bundles, &new_models);+ for (bundle, hash) in hashes.bundle {+ if !new_bundles.contains_key(&bundle) {+ continue;+ }+ if hash.is_empty() {+ bundle_config_hashes.remove(&bundle);+ } else {+ bundle_config_hashes.insert(bundle, hash);+ }+ }+ for (bundle, pools) in hashes.pool {+ if !new_bundles.contains_key(&bundle) {+ continue;+ }+ for (pool, hash) in pools {+ let pool = pool.trim().to_lowercase();+ let pool = if pool.is_empty() {+ DEFAULT_MODEL_POOL.to_string()+ } else {+ pool+ };+ let key = (bundle.clone(), pool);+ if hash.is_empty() {+ bundle_pool_config_hashes.remove(&key);+ } else {+ bundle_pool_config_hashes.insert(key, hash);+ }+ }+ }if self.authoritative_surface.load(Ordering::Acquire) {let served = old_snap@@ -4961,6 +5015,55 @@ adapters:}}+ #[test]+ fn authoritative_generation_can_only_be_installed_once() {+ let temp = TempDir::new().unwrap();+ let registry = ModelRegistry::new(temp.path(), temp.path(), false);+ let generation = registry.capture_generation();+ let bundles = vec![BundleInfo {+ name: "default".into(),+ priority: 10,+ adapters: vec!["sie_server.adapters.sentence_transformer".into()],+ engine: DEFAULT_ENGINE.into(),+ }];+ registry+ .replace_authoritative_surface_if_current(+ &generation,+ bundles.clone(),+ vec![named_cfg_for_test("test/model")],+ AuthoritativeHashes {+ bundle: HashMap::from([("default".into(), "authority-hash".into())]),+ pool: HashMap::from([(+ "default".into(),+ HashMap::from([(" CUSTOM ".into(), "pool-hash".into())]),+ )]),+ },+ )+ .unwrap();+ let installed = registry.capture_generation();+ assert_eq!(+ installed.snapshot.bundle_config_hashes["default"],+ "authority-hash"+ );+ assert_eq!(+ installed.snapshot.bundle_pool_config_hashes[&("default".into(), "custom".into())],+ "pool-hash"+ );+ assert!(registry+ .replace_authoritative_surface_if_current(+ &generation,+ bundles,+ vec![named_cfg_for_test("test/other")],+ AuthoritativeHashes::default(),+ )+ .is_err());+ assert!(registry+ .with_current_generation(&installed, || ())+ .is_some());+ assert!(registry.get_model_info("test/model").is_some());+ assert!(registry.get_model_info("test/other").is_none());+ }+#[test]fn test_shrink_refusal_bounds() {let half = 0.5;