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): keep the served surface when an authoritative export shrinks it (#270)
Krisztian Gajdarc65aee57224d
diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex e4334ea36..5733529a3 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -5,16 +5,16 @@//! authoritative state in two phases://!//! 1. `GET /v1/configs/bundles` (+ per-bundle `GET /v1/configs/bundles/{id}`)-//! — fetches the bundle/adapter surface and installs it via-//! `ModelRegistry::install_bundles`. This MUST happen before the model-//! fetch because `add_model_config` rejects any adapter not in a known-//! bundle. Historically the gateway image baked these bundles in, which-//! drifted from `sie-config`'s view and made every published model fail-//! validation with `Adapter(s) not in any known bundle`. Pulling them-//! over HTTP makes `sie-config` the single source of truth.+//! — fetches the bundle/adapter surface. Historically the gateway image+//! baked these bundles in, which drifted from `sie-config`'s view and made+//! every published model fail validation with `Adapter(s) not in any+//! known bundle`. Pulling them over HTTP makes `sie-config` the single+//! source of truth.//! 2. `GET /v1/configs/export` (admin-auth) — fetches every persisted model-//! config and replaces the registry's model set so the gateway's served-//! view matches `sie-config`'s view, including removals.+//! config. Both halves are then installed as ONE snapshot via+//! `ModelRegistry::replace_authoritative_surface`, which validates each+//! model's adapters against the bundles it was exported with and replaces+//! the served view, including removals.//!//! Live updates after bootstrap arrive via NATS deltas//! (`sie.config.models.*`), which the `NatsManager` feeds into@@ -206,12 +206,20 @@ pub enum BootstrapError {failed: usize,total: usize,},+ /// The bundle surface changed between the reads that make up one+ /// bootstrap, so the bundles and the model export may come from different+ /// `sie-config` generations. Nothing was installed; the next attempt+ /// re-reads both.+ #[error("torn read: bundles hash moved from {before} to {after} during bootstrap")]+ TornRead { before: String, after: String },}pub(crate) fn telemetry_outcome(error: &BootstrapError) -> ConfigOutcome {match error {BootstrapError::PartialApply { .. } => ConfigOutcome::PartialApply,- BootstrapError::Http(_) | BootstrapError::BadStatus { .. } => ConfigOutcome::FetchError,+ BootstrapError::Http(_)+ | BootstrapError::BadStatus { .. }+ | BootstrapError::TornRead { .. } => ConfigOutcome::FetchError,}}@@ -488,9 +496,10 @@ impl BootstrapClient {Ok(out)}- /// Fetch bundles + the model snapshot, install both into `registry`.- /// Bundles MUST be installed first so the model-apply loop can validate- /// each profile's `adapter_path` against the freshly-fetched adapter set.+ /// Fetch bundles + the model snapshot and install both into `registry`+ /// as one matched snapshot, so every profile's `adapter_path` is+ /// validated against the bundle set it was exported with and neither half+ /// can land without the other.pub async fn bootstrap(&self,registry: &ModelRegistry,@@ -502,7 +511,6 @@ impl BootstrapClient {// caught up on a stale registry.let pre_bootstrap = self.fetch_epoch().await?;let bundles = self.fetch_bundles().await?;- registry.install_bundles(bundles);let url = format!("{}/v1/configs/export", self.base_url.trim_end_matches('/'));let req = self.apply_auth(self.http.get(&url));@@ -548,9 +556,36 @@ impl BootstrapClient {}}+ // The bundles and the export are separate reads, and `sie-config`+ // serves them from different structures: the export from its locked+ // internal snapshot, the bundles from files that change on redeploy.+ // Re-read the epoch and refuse the pair if the bundle surface moved in+ // between, so the two halves installed together always belong to one+ // generation; the retry loop simply reads both again.+ let post_bootstrap = self.fetch_epoch().await?;+ let hash_published =+ !pre_bootstrap.bundles_hash.is_empty() && !post_bootstrap.bundles_hash.is_empty();+ if hash_published {+ if post_bootstrap.bundles_hash != pre_bootstrap.bundles_hash {+ return Err(BootstrapError::TornRead {+ before: pre_bootstrap.bundles_hash,+ after: post_bootstrap.bundles_hash,+ });+ }+ } else {+ // A control plane that publishes no bundle fingerprint cannot+ // vouch for the pair, and two empty hashes prove nothing. Read the+ // bundle surface again and compare the two reads directly.+ let before = bundle_fingerprint(&bundles);+ let after = bundle_fingerprint(&self.fetch_bundles().await?);+ if before != after {+ return Err(BootstrapError::TornRead { before, after });+ }+ }+let mut applied = 0usize;if failed == 0 {- match registry.replace_model_configs_authoritative(configs) {+ match registry.replace_authoritative_surface(bundles, configs) {Ok(count) => {applied = count;registry.install_bundle_config_hashes(snapshot.bundle_config_hashes);@@ -574,6 +609,27 @@ impl BootstrapClient {}}+/// Order-independent identity of a bundle read, for comparing two reads of+/// the bundle surface when the control plane publishes no hash for it.+fn bundle_fingerprint(bundles: &[BundleInfo]) -> String {+ let mut lines: Vec<String> = bundles+ .iter()+ .map(|b| {+ let mut adapters = b.adapters.clone();+ adapters.sort();+ format!(+ "{}|{}|{}|{}",+ b.name,+ b.priority,+ b.engine,+ adapters.join(",")+ )+ })+ .collect();+ lines.sort();+ lines.join("\n")+}+fn parse_exported_model(model: &ExportedModel) -> Result<Option<ModelConfig>, String> {if let Some(yaml) = model.raw_yaml.as_deref() {let trimmed = yaml.trim();@@ -957,6 +1013,154 @@ mod tests {);}+ /// A bundle redeploy landing between the bundle read and the export read+ /// would pair one generation's bundles with another's models. The+ /// post-read epoch check refuses the pair and installs nothing.+ #[tokio::test]+ async fn bootstrap_refuses_a_bundle_surface_that_moved_during_the_reads() {+ let server = MockServer::start().await;+ let (registry, _tmp) = make_registry();+ mount_default_bundles(&server).await;+ // First epoch read sees "before"; every later read sees "after".+ Mock::given(method("GET"))+ .and(path("/v1/configs/epoch"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "epoch": 0,+ "bundles_hash": "before",+ "bundle_config_hashes_hash": "bundle_config_hashes_hash",+ })))+ .up_to_n_times(1)+ .mount(&server)+ .await;+ mount_default_epoch(&server, 0, "after").await;++ let body = serde_json::json!({+ "snapshot_version": 1,+ "epoch": 7,+ "generated_at": "2026-04-17T00:00:00Z",+ "bundle_config_hashes": {"default": "control-plane-hash"},+ "models": [{+ "model_id": "kept/model",+ "raw_yaml": "sie_id: kept/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.sentence_transformer:Adapter\n",+ "affected_bundles": ["default"],+ }],+ });+ Mock::given(method("GET"))+ .and(path("/v1/configs/export"))+ .respond_with(ResponseTemplate::new(200).set_body_json(&body))+ .mount(&server)+ .await;++ let client = BootstrapClient::new(server.uri(), None).unwrap();+ let err = client+ .bootstrap(registry.as_ref())+ .await+ .expect_err("a moved bundle surface must refuse the pair");+ assert!(+ matches!(err, BootstrapError::TornRead { .. }),+ "expected TornRead, got {err:?}"+ );+ assert!(+ registry.get_model_info("kept/model").is_none(),+ "nothing may be installed from a torn read"+ );+ }++ async fn mount_epoch_without_bundles_hash(server: &MockServer) {+ Mock::given(method("GET"))+ .and(path("/v1/configs/epoch"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "epoch": 0,+ "bundle_config_hashes_hash": "bundle_config_hashes_hash",+ })))+ .mount(server)+ .await;+ }++ fn kept_model_export() -> serde_json::Value {+ serde_json::json!({+ "snapshot_version": 1,+ "epoch": 7,+ "generated_at": "2026-04-17T00:00:00Z",+ "bundle_config_hashes": {"default": "control-plane-hash"},+ "models": [{+ "model_id": "kept/model",+ "raw_yaml": "sie_id: kept/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.sentence_transformer:Adapter\n",+ "affected_bundles": ["default"],+ }],+ })+ }++ /// Two empty hashes prove nothing: when the control plane publishes no+ /// bundle fingerprint the bundle surface is read twice and compared, so a+ /// change between the reads is still refused.+ #[tokio::test]+ async fn bootstrap_refuses_a_moved_bundle_surface_when_no_hash_is_published() {+ let server = MockServer::start().await;+ let (registry, _tmp) = make_registry();+ mount_epoch_without_bundles_hash(&server).await;+ Mock::given(method("GET"))+ .and(path("/v1/configs/bundles"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "bundles": [{"bundle_id": "default", "priority": 10, "adapter_count": 1, "source": "filesystem"}],+ })))+ .mount(&server)+ .await;+ // First bundle read carries one adapter set, every later read another.+ Mock::given(method("GET"))+ .and(path("/v1/configs/bundles/default"))+ .respond_with(ResponseTemplate::new(200).set_body_string(+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",+ ))+ .up_to_n_times(1)+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/v1/configs/bundles/default"))+ .respond_with(ResponseTemplate::new(200).set_body_string(+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.pytorch_embedding\n",+ ))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/v1/configs/export"))+ .respond_with(ResponseTemplate::new(200).set_body_json(kept_model_export()))+ .mount(&server)+ .await;++ let client = BootstrapClient::new(server.uri(), None).unwrap();+ let err = client+ .bootstrap(registry.as_ref())+ .await+ .expect_err("a moved bundle surface must be refused even without a hash");+ assert!(+ matches!(err, BootstrapError::TornRead { .. }),+ "got {err:?}"+ );+ assert!(registry.get_model_info("kept/model").is_none());+ }++ #[tokio::test]+ async fn bootstrap_applies_when_no_hash_is_published_and_the_bundle_reads_agree() {+ let server = MockServer::start().await;+ let (registry, _tmp) = make_registry();+ mount_epoch_without_bundles_hash(&server).await;+ mount_default_bundles(&server).await;+ Mock::given(method("GET"))+ .and(path("/v1/configs/export"))+ .respond_with(ResponseTemplate::new(200).set_body_json(kept_model_export()))+ .mount(&server)+ .await;++ let client = BootstrapClient::new(server.uri(), None).unwrap();+ let outcome = client+ .bootstrap(registry.as_ref())+ .await+ .expect("agreeing bundle reads are a consistent pair");+ assert_eq!(outcome.failed, 0);+ assert!(registry.get_model_info("kept/model").is_some());+ }+#[tokio::test]async fn bootstrap_replaces_authoritative_model_set_and_drops_stale_models() {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 ebfca0dea..13dafc0fb 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -1,7 +1,8 @@use std::collections::{BTreeMap, HashMap, HashSet};use std::fmt::Write as _;use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, OnceLock};use arc_swap::ArcSwap;use sha2::{Digest, Sha256};@@ -162,6 +163,30 @@ struct RegistrySnapshot {/// [`ModelRegistry::with_current_generation`]. Holding the `Arc` also prevents/// pointer reuse, so the identity check is ABA-safe.#[allow(dead_code)] // consumed by the managed gateway wrapper, not the standalone binary+/// Floor on how much of the served surface an authoritative snapshot may+/// remove in one apply, as a fraction of what is currently served. `0`+/// disables the guard, which is the escape hatch for a deliberate bulk+/// removal.+const MIN_RETAINED_RATIO_ENV: &str = "SIE_CONFIG_MIN_RETAINED_RATIO";+const DEFAULT_MIN_RETAINED_RATIO: f64 = 0.5;++/// Resolved once: the gateway's environment does not change after boot, and+/// this is read on the config-apply path.+fn min_retained_ratio() -> f64 {+ static RATIO: OnceLock<f64> = OnceLock::new();+ *RATIO.get_or_init(|| {+ std::env::var(MIN_RETAINED_RATIO_ENV)+ .ok()+ .and_then(|raw| raw.trim().parse::<f64>().ok())+ .filter(|ratio| (0.0..=1.0).contains(ratio))+ .unwrap_or(DEFAULT_MIN_RETAINED_RATIO)+ })+}++/// Expanded model entries plus their lower-cased name index, as one+/// authoritative export produces them.+type AuthoritativeModels = (HashMap<String, ModelEntry>, HashMap<String, String>);+pub struct ModelRegistryGeneration {snapshot: Arc<RegistrySnapshot>,}@@ -186,6 +211,12 @@ pub struct ModelRegistry {/// Ordinary readers remain lock-free and see one consistent snapshot per/// access.write_lock: Mutex<()>,+ /// Whether the served surface was installed by the control plane. A+ /// filesystem seed is a bootstrap convenience the first authoritative+ /// export may replace wholesale; only a surface the authority itself+ /// installed is protected by the retention guard, so a config service+ /// that later restarts empty cannot take it down.+ authoritative_surface: AtomicBool,}impl ModelRegistry {@@ -199,6 +230,7 @@ impl ModelRegistry {models_dir: models_dir.as_ref().to_path_buf(),snapshot: ArcSwap::from_pointee(RegistrySnapshot::default()),write_lock: Mutex::new(()),+ authoritative_surface: AtomicBool::new(false),};if auto_load {registry.reload();@@ -368,6 +400,7 @@ impl ModelRegistry {bundle_pool_config_hashes,};self.snapshot.store(Arc::new(snap));+ self.authoritative_surface.store(false, Ordering::Release);}fn load_bundle_file(path: &Path) -> Result<BundleInfo, Box<dyn std::error::Error>> {@@ -1448,6 +1481,12 @@ impl ModelRegistry {/// (every subsequent `add_model_config` will then reject every adapter as/// unknown — that's the correct behavior when `sie-config` is unreachable/// and we have no seed).+ /// `dead_code`-allowed because the `sie-gateway` BINARY compiles this+ /// module tree independently of the library (see the note in `lib.rs`):+ /// the bootstrap now installs bundles and models together through+ /// [`Self::replace_authoritative_surface`], and this standalone path is+ /// kept for the library's downstream consumers.+ #[allow(dead_code)]pub fn install_bundles(&self, bundles: Vec<BundleInfo>) {let _write = self.write_lock@@ -1491,6 +1530,35 @@ impl ModelRegistry {model_entry.bundles = matching.into_iter().map(|(_, name)| name).collect();}+ // A bundle set that strands the served models is the same outage as+ // an empty model export: every affected adapter becomes unroutable.+ // Judged on routability after the rebuild rather than on bundle+ // counts, so an equal-sized set of incompatible bundles is caught.+ // `install_bundles` has no error channel, so a refusal is a warn and+ // the existing bundles stand.+ let served = old_snap+ .models+ .values()+ .filter(|entry| !entry.bundles.is_empty())+ .count();+ let retained = old_snap+ .models+ .iter()+ .filter(|(id, entry)| {+ !entry.bundles.is_empty()+ && snap+ .models+ .get(id.as_str())+ .is_some_and(|rebuilt| !rebuilt.bundles.is_empty())+ })+ .count();+ if self.authoritative_surface.load(Ordering::Acquire) {+ if let Some(refusal) = Self::shrink_refusal(served, retained, min_retained_ratio()) {+ warn!(reason = %refusal, "refused authoritative bundle install");+ return;+ }+ }+let bundle_config_hashes = Self::rebuild_bundle_config_hashes(&new_bundles, &snap.models);let bundle_pool_config_hashes =Self::rebuild_bundle_pool_config_hashes(&new_bundles, &snap.models);@@ -2045,18 +2113,138 @@ impl ModelRegistry {/// profile variants that disappeared from `sie-config` instead of overlaying/// exported rows onto the existing snapshot. Use this only for/// `/v1/configs/export`, never for live NATS deltas.+ /// Refuse an authoritative snapshot that retains fewer than+ /// `min_retained_ratio` of the identities currently served.+ ///+ /// The control plane is authoritative for WHICH models exist, not for+ /// whether it is itself healthy. A well-formed empty or near-empty export+ /// — a config service restarted against an empty database, a filtered+ /// query, a half-finished migration — is indistinguishable on the wire+ /// from a deliberate removal, and applying it takes the whole model+ /// surface out on every replica at once, within one poll interval.+ /// Refusing keeps the last good surface and leaves the caller's retry loop+ /// to apply the real snapshot once the control plane serves one.+ ///+ /// `retained` counts identities served both before and after the+ /// replacement, so an equal-sized snapshot naming entirely different+ /// models (the wrong environment's export) is caught, not just a smaller+ /// one. `served == 0` never refuses: the first bootstrap has nothing to+ /// protect.+ fn shrink_refusal(served: usize, retained: usize, min_retained_ratio: f64) -> Option<String> {+ if served == 0 || min_retained_ratio <= 0.0 {+ return None;+ }+ let floor = ((served as f64) * min_retained_ratio).ceil() as usize;+ if retained >= floor {+ return None;+ }+ Some(format!(+ "authoritative snapshot would retain only {retained} of the {served} identities \+ served now, below the floor of {floor} ({MIN_RETAINED_RATIO_ENV}={min_retained_ratio}); \+ keeping the current surface. Set {MIN_RETAINED_RATIO_ENV}=0 to apply a deliberate \+ bulk removal."+ ))+ }++ /// `dead_code`-allowed for the same reason as [`Self::install_bundles`]:+ /// the binary no longer calls it, the downstream composition crate does.+ #[allow(dead_code)]pub fn replace_model_configs_authoritative(&self,configs: Vec<ModelConfig>,+ ) -> Result<usize, String> {+ self.apply_authoritative(None, configs)+ }++ /// Install a matched bundle set and model export as ONE snapshot.+ ///+ /// The bootstrap fetches both from the control plane; validating the+ /// models against the bundles they were exported with, and judging+ /// 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.+ pub fn replace_authoritative_surface(+ &self,+ bundles: Vec<BundleInfo>,+ configs: Vec<ModelConfig>,+ ) -> Result<usize, String> {+ self.apply_authoritative(Some(bundles), configs)+ }++ fn apply_authoritative(+ &self,+ bundles: Option<Vec<BundleInfo>>,+ configs: Vec<ModelConfig>,) -> Result<usize, String> {let _write = self.write_lock.lock().expect("ModelRegistry write_lock poisoned");let old_snap = self.snapshot.load();+ 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(),+ };+ let applied = configs.len();+ 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 =+ Self::rebuild_bundle_pool_config_hashes(&new_bundles, &new_models);++ if self.authoritative_surface.load(Ordering::Acquire) {+ let served = old_snap+ .models+ .values()+ .filter(|entry| !entry.bundles.is_empty())+ .count();+ let retained = old_snap+ .models+ .iter()+ .filter(|(id, entry)| {+ !entry.bundles.is_empty()+ && new_models+ .get(id.as_str())+ .is_some_and(|candidate| !candidate.bundles.is_empty())+ })+ .count();+ if let Some(refusal) = Self::shrink_refusal(served, retained, min_retained_ratio()) {+ return Err(refusal);+ }+ }++ info!(+ old_models = old_snap.models.len(),+ models = new_models.len(),+ bundles = new_bundles.len(),+ "replaced model configs from authoritative export"+ );++ self.snapshot.store(Arc::new(RegistrySnapshot {+ bundles: new_bundles,+ models: new_models,+ model_names_lower: new_model_names_lower,+ bundle_config_hashes,+ bundle_pool_config_hashes,+ }));+ self.authoritative_surface.store(true, Ordering::Release);++ Ok(applied)+ }++ /// Validate and expand an exported model set against the bundle set it+ /// will be served with.+ fn build_authoritative_models(+ configs: Vec<ModelConfig>,+ bundles: &HashMap<String, BundleInfo>,+ ) -> Result<AuthoritativeModels, String> {let mut new_models: HashMap<String, ModelEntry> = HashMap::new();let mut new_model_names_lower: HashMap<String, String> = HashMap::new();- let applied = configs.len();+ let all_bundle_adapters: HashSet<String> = bundles+ .values()+ .flat_map(|b| b.adapters.iter().cloned())+ .collect();for config in configs {let sie_id = &config.name;@@ -2086,11 +2274,6 @@ impl ModelRegistry {}}- let all_bundle_adapters: HashSet<String> = old_snap- .bundles- .values()- .flat_map(|b| b.adapters.iter().cloned())- .collect();let unroutable: Vec<&String> = adapter_modules.iter().filter(|a| !all_bundle_adapters.contains(a.as_str()))@@ -2107,33 +2290,12 @@ impl ModelRegistry {}for mut entry in Self::expand_model_config_into_profile_variants(&config)? {- Self::assign_bundles(&mut entry, &old_snap.bundles);+ Self::assign_bundles(&mut entry, bundles);new_model_names_lower.insert(entry.name.to_lowercase(), entry.name.clone());new_models.insert(entry.name.clone(), entry);}}-- let bundle_config_hashes =- Self::rebuild_bundle_config_hashes(&old_snap.bundles, &new_models);- let bundle_pool_config_hashes =- Self::rebuild_bundle_pool_config_hashes(&old_snap.bundles, &new_models);-- info!(- old_models = old_snap.models.len(),- models = new_models.len(),- bundles = old_snap.bundles.len(),- "replaced model configs from authoritative export"- );-- self.snapshot.store(Arc::new(RegistrySnapshot {- bundles: old_snap.bundles.clone(),- models: new_models,- model_names_lower: new_model_names_lower,- bundle_config_hashes,- bundle_pool_config_hashes,- }));-- Ok(applied)+ Ok((new_models, new_model_names_lower))}fn add_model_config_inner(@@ -4789,6 +4951,310 @@ adapters:/// conflict override behavior. Production export replay now uses/// `replace_model_configs_authoritative`, but this still guards the shared/// merge code for divergent stored profiles.+ fn named_cfg_for_test(name: &str) -> ModelConfig {+ ModelConfig {+ name: name.to_string(),+ ..cfg_for_test_model(+ "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter",+ 4096,+ )+ }+ }++ #[test]+ fn test_shrink_refusal_bounds() {+ let half = 0.5;+ // Nothing to protect on the first bootstrap.+ assert!(ModelRegistry::shrink_refusal(0, 0, half).is_none());+ // Full retention and exactly-at-floor retention are allowed.+ assert!(ModelRegistry::shrink_refusal(10, 10, half).is_none());+ assert!(ModelRegistry::shrink_refusal(10, 5, half).is_none());+ // One identity below the floor is not.+ assert!(ModelRegistry::shrink_refusal(10, 4, half).is_some());+ // The whole point: nothing retained (an empty export, or an export+ // naming entirely different models).+ assert!(ModelRegistry::shrink_refusal(40, 0, half).is_some());+ // Ratio 0 is the documented escape hatch for a deliberate bulk removal.+ assert!(ModelRegistry::shrink_refusal(40, 0, 0.0).is_none());+ // A single served model can be dropped only through the hatch:+ // ceil(1 * 0.5) == 1.+ assert!(ModelRegistry::shrink_refusal(1, 0, half).is_some());+ }++ #[test]+ fn test_empty_authoritative_export_keeps_the_current_model_surface() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - sie_server.adapters.sentence_transformer+"#,+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ let seed: Vec<ModelConfig> = (0..4)+ .map(|i| named_cfg_for_test(&format!("test/model-{i}")))+ .collect();+ registry+ .replace_model_configs_authoritative(seed)+ .expect("seed apply");+ let served = registry.list_models();+ assert!(served.len() >= 4, "seed must serve something: {served:?}");++ // sie-config answers 200 with an empty model set — a restarted config+ // service, not a deliberate removal.+ let refusal = registry+ .replace_model_configs_authoritative(Vec::new())+ .expect_err("an empty authoritative export must be refused");+ assert!(+ refusal.contains("keeping the current surface"),+ "refusal must say what it did: {refusal}"+ );+ assert_eq!(+ registry.list_models().len(),+ served.len(),+ "the served surface must survive a refused snapshot"+ );+ }++ #[test]+ fn test_matched_bundle_and_model_change_applies_as_one_snapshot() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - sie_server.adapters.sentence_transformer+"#,+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ registry+ .replace_authoritative_surface(+ registry+ .list_bundles()+ .into_iter()+ .map(|name| BundleInfo {+ name,+ priority: 10,+ adapters: vec!["sie_server.adapters.sentence_transformer".to_string()],+ engine: DEFAULT_ENGINE.to_string(),+ })+ .collect(),+ vec![named_cfg_for_test("test/model-0")],+ )+ .expect("seed the authoritative surface");++ // The authority moves the served model onto a new adapter and ships+ // the bundle that routes it in the same export. Installing the bundle+ // alone would strand the model; applied together it stays routable.+ let moved = ModelConfig {+ profiles: {+ let mut m = HashMap::new();+ m.insert(+ "default".to_string(),+ crate::types::model::ProfileConfig {+ adapter_path: Some(+ "sie_server.adapters.pytorch_embedding:PyTorchEmbeddingAdapter"+ .to_string(),+ ),+ max_batch_tokens: Some(4096),+ kv_budget_tokens: None,+ max_output_tokens: None,+ grammar_profile: None,+ chat_template_kwargs: None,+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ m+ },+ ..named_cfg_for_test("test/model-0")+ };+ let new_bundles = vec![BundleInfo {+ name: "torch".to_string(),+ priority: 10,+ adapters: vec!["sie_server.adapters.pytorch_embedding".to_string()],+ engine: DEFAULT_ENGINE.to_string(),+ }];+ registry+ .replace_authoritative_surface(new_bundles, vec![moved])+ .expect("a matched bundle+model change is one ordinary apply");+ assert_eq!(registry.list_bundles(), vec!["torch".to_string()]);+ assert!(registry.list_models().iter().any(|n| n == "test/model-0"));++ // And the guard still holds on the joint result: a matched export that+ // strands the served models is refused as a whole.+ let stranding = vec![BundleInfo {+ name: "other".to_string(),+ priority: 10,+ adapters: vec!["sie_server.adapters.nothing_served_uses".to_string()],+ engine: DEFAULT_ENGINE.to_string(),+ }];+ registry+ .replace_authoritative_surface(stranding, vec![named_cfg_for_test("other/model")])+ .expect_err("a matched export retaining none of the served models must be refused");+ assert_eq!(registry.list_bundles(), vec!["torch".to_string()]);+ }++ #[test]+ fn test_first_authoritative_export_replaces_a_local_seed_freely() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - sie_server.adapters.sentence_transformer+"#,+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ registry+ .add_model_config(named_cfg_for_test("stale/model"))+ .expect("seed a gateway-local model");++ // The seed is a convenience, not the authority: the first export may+ // drop every seeded model, exactly as bootstrap relies on.+ registry+ .replace_model_configs_authoritative(vec![named_cfg_for_test("kept/model")])+ .expect("the first authoritative export replaces a local seed");+ let names = registry.list_models();+ assert!(names.iter().any(|n| n == "kept/model"));+ assert!(!names.iter().any(|n| n == "stale/model"));++ // From here the surface is the authority's own, and the guard applies.+ registry+ .replace_model_configs_authoritative(Vec::new())+ .expect_err("a later empty export must be refused");+ assert!(registry.list_models().iter().any(|n| n == "kept/model"));+ }++ #[test]+ fn test_equal_sized_export_naming_different_models_is_refused() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - sie_server.adapters.sentence_transformer+"#,+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let seed: Vec<ModelConfig> = (0..4)+ .map(|i| named_cfg_for_test(&format!("test/model-{i}")))+ .collect();+ registry+ .replace_model_configs_authoritative(seed)+ .expect("seed apply");+ let served = registry.list_models();++ // Same cardinality, disjoint identities: another environment's export.+ let strangers: Vec<ModelConfig> = (0..4)+ .map(|i| named_cfg_for_test(&format!("other/model-{i}")))+ .collect();+ registry+ .replace_model_configs_authoritative(strangers)+ .expect_err("an export retaining none of the served models must be refused");+ assert_eq!(registry.list_models(), served);+ }++ #[test]+ fn test_export_retaining_the_floor_is_applied() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - sie_server.adapters.sentence_transformer+"#,+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let seed: Vec<ModelConfig> = (0..4)+ .map(|i| named_cfg_for_test(&format!("test/model-{i}")))+ .collect();+ registry+ .replace_model_configs_authoritative(seed)+ .expect("seed apply");++ // Two of four retained meets ceil(4 * 0.5); two are genuinely replaced.+ let rotated: Vec<ModelConfig> = [+ "test/model-0",+ "test/model-1",+ "test/model-9",+ "test/model-8",+ ]+ .into_iter()+ .map(named_cfg_for_test)+ .collect();+ registry+ .replace_model_configs_authoritative(rotated)+ .expect("retaining the floor is an ordinary apply");+ let names = registry.list_models();+ assert!(names.iter().any(|n| n == "test/model-9"));+ assert!(!names.iter().any(|n| n == "test/model-3"));+ }++ #[test]+ fn test_bundle_install_that_strands_the_served_models_is_refused() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ r#"+name: default+priority: 10+adapters:+ - sie_server.adapters.sentence_transformer+"#,+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ registry+ .replace_model_configs_authoritative(vec![named_cfg_for_test("test/model-0")])+ .expect("seed apply");+ let before = registry.list_bundles();+ assert!(!before.is_empty(), "fixture must seed a bundle");++ // Same bundle count, but nothing that routes the served adapter.+ let incompatible = registry+ .list_bundles()+ .into_iter()+ .map(|_| BundleInfo {+ name: "unrelated".to_string(),+ priority: 10,+ adapters: vec!["sie_server.adapters.nothing_served_uses".to_string()],+ engine: DEFAULT_ENGINE.to_string(),+ })+ .collect();+ registry.install_bundles(incompatible);+ assert_eq!(+ registry.list_bundles(),+ before,+ "a bundle set that strands every served model must be refused"+ );++ registry.install_bundles(Vec::new());+ assert_eq!(+ registry.list_bundles(),+ before,+ "an empty bundle install must be refused"+ );+ }+#[test]fn test_add_model_config_authoritative_overrides_conflicting_profile() {let (_dir, bundles_dir, models_dir) = create_test_dirs();