diff --git a/.agents/skills/helm-dev-environment/SKILL.md b/.agents/skills/helm-dev-environment/SKILL.md index 170bdd7c16..36e73951a2 100644 --- a/.agents/skills/helm-dev-environment/SKILL.md +++ b/.agents/skills/helm-dev-environment/SKILL.md @@ -259,9 +259,10 @@ Discovery returns the acknowledged owner's Pod IP and app port; no headless app Service is needed. Exercise HTTP/WebSocket reconnection through graceful downscale and abrupt loss, preserving workload generation/PID/in-memory state and the public hostname. Verify stale-owner rejection independently of the replacement's success. -Shared serving leases expire within fifteen seconds of issuance and do not renew -from configuration alone. Do not claim seamless socket migration or infer external -ingress readiness from an advertisement. +Installed routes and application streams survive gateway outages. Verify explicit +withdrawal and sandbox-attachment ownership changes independently of control-session +liveness. Do not claim seamless socket migration or infer external ingress readiness +from an advertisement. ### 2. Deploy OpenShell @@ -531,7 +532,7 @@ For the opt-in application listener, build/import matching branch images and run `mise run e2e:kubernetes:app-listener`; see `e2e/kubernetes/app-listener/README.md` for image, topology, delivery-mode and takeover inputs. The task owns an isolated Helm release/namespace, temporary TLS material, in-cluster clients, teardown and -evidence under `results/app-listener/`. It checks policy denial, Pod-IP ingress without app Services, shared-owner takeover, gateway-outage expiry and disabled-listener +evidence under `results/app-listener/`. It checks policy denial, Pod-IP ingress without app Services, shared-owner takeover, gateway-outage route retention and disabled-listener gateway compatibility, without discovery or a proxy. CI runs four cases under `test:e2e` and includes them in `Core E2E result`. Its reusable kind setup installs pinned Calico only for this lane; other jobs retain kindnet. Local k3s already diff --git a/crates/openshell-core/src/app_listener.rs b/crates/openshell-core/src/app_listener.rs index 5db86c3cd7..0c0f891660 100644 --- a/crates/openshell-core/src/app_listener.rs +++ b/crates/openshell-core/src/app_listener.rs @@ -6,6 +6,9 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +pub const DEFAULT_APP_MAX_CONNECTIONS: usize = 1024; +pub const DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX: usize = 64; + /// Gateway browser credentials are reserved on both application access paths. pub fn is_gateway_service_auth_cookie(name: &[u8]) -> bool { name.eq_ignore_ascii_case(b"__Host-openshell-service-session") @@ -21,6 +24,10 @@ pub struct AppListenerConfig { pub port: u16, /// Public HTTPS origin used to derive service hostnames and URLs. pub base_url: Option, + /// Concurrent accepted TLS connections per supervisor listener. + pub max_connections: usize, + /// Concurrent connections and backend relays for each sandbox. + pub max_connections_per_sandbox: usize, } impl Default for AppListenerConfig { @@ -29,6 +36,8 @@ impl Default for AppListenerConfig { enabled: false, port: 8443, base_url: None, + max_connections: DEFAULT_APP_MAX_CONNECTIONS, + max_connections_per_sandbox: DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX, } } } @@ -59,6 +68,13 @@ impl AppListenerConfig { if !self.enabled { return Ok(()); } + if self.max_connections == 0 + || self.max_connections > tokio::sync::Semaphore::MAX_PERMITS + || self.max_connections_per_sandbox == 0 + || self.max_connections_per_sandbox > self.max_connections + { + return Err("app listener requires 1 <= max_connections_per_sandbox <= max_connections <= Semaphore::MAX_PERMITS".into()); + } let origin = self.parsed_base_url()?; validate_listener_endpoint(self.port, origin.host_str().unwrap_or_default()) } @@ -199,11 +215,32 @@ fn base32_lower_no_padding(bytes: &[u8]) -> String { output } -/// A synchronous view of installed ingress, evaluated on the sandbox instance -/// runtime. The requested lease must fit entirely within serving freshness. -pub type InstallationSource = std::sync::Arc< - dyn Fn(std::time::Duration) -> crate::proto::SupervisorServiceAdvertisement + Send + Sync, ->; +/// Installed ingress on one sandbox attachment, with change notifications. +#[derive(Clone)] +pub struct InstallationSource { + snapshot: + std::sync::Arc crate::proto::SupervisorServiceAdvertisement + Send + Sync>, + updates: tokio::sync::watch::Receiver<()>, +} + +impl InstallationSource { + pub fn new( + snapshot: std::sync::Arc< + dyn Fn() -> crate::proto::SupervisorServiceAdvertisement + Send + Sync, + >, + updates: tokio::sync::watch::Receiver<()>, + ) -> Self { + Self { snapshot, updates } + } + + pub fn snapshot(&self) -> crate::proto::SupervisorServiceAdvertisement { + (self.snapshot)() + } + + pub async fn changed(&mut self) -> Result<(), tokio::sync::watch::error::RecvError> { + self.updates.changed().await + } +} #[cfg(test)] mod tests { @@ -286,6 +323,26 @@ mod tests { assert!(config.service_url("default", "demo", "web", None).is_none()); } + #[test] + fn listener_connection_budgets_preserve_defaults_and_reject_invalid_bounds() { + let mut config = AppListenerConfig { + enabled: true, + base_url: Some("https://services.example.com".into()), + ..Default::default() + }; + assert_eq!(config.max_connections, 1024); + assert_eq!(config.max_connections_per_sandbox, 64); + assert!(config.validate().is_ok()); + for (total, per_sandbox) in [(0, 1), (64, 0), (64, 65), (usize::MAX, 1)] { + config.max_connections = total; + config.max_connections_per_sandbox = per_sandbox; + assert!(config.validate().is_err()); + } + config.max_connections = 16384; + config.max_connections_per_sandbox = 256; + assert!(config.validate().is_ok()); + } + #[test] fn base_url_is_the_only_authored_service_domain() { let config: AppListenerConfig = serde_json::from_str( diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 18587b10bf..232e8988d4 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -2,6 +2,14 @@ Kubernetes-backed compute driver for OpenShell cluster deployments. +Application endpoint resolution uses a metadata-only Sandbox watch to map each +sandbox ID to its Kubernetes resource. Every resolution still fetches that +resource by name and checks its UID, gateway labels, and deletion state before +validating supervisor placement. The watch must finish its initial list; +ambiguous IDs and watch errors make resolution unavailable until a fresh list +completes. Renewals use point reads to avoid repeated label-selected Sandbox +LISTs exhausting Kubernetes API flow-control capacity. + Caller driver config is disabled by default. External resource references need administrator-controlled approval labels in every workspace mode, including before restart and scheduling-gate release. GPU devices are temporarily exempt. diff --git a/crates/openshell-driver-kubernetes/src/app_endpoint_index.rs b/crates/openshell-driver-kubernetes/src/app_endpoint_index.rs new file mode 100644 index 0000000000..5e51598fcb --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/app_endpoint_index.rs @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Watch-maintained resource locators, never cached endpoint authority. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use futures::StreamExt as _; +use kube::Api; +use kube::core::{DynamicObject, ObjectMeta, PartialObjectMeta}; +use kube::runtime::watcher::{self, Event}; +use openshell_core::driver_utils::{ + LABEL_GATEWAY_ID, LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, +}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Locator { + pub namespace: String, + pub name: String, + uid: String, +} + +impl Locator { + pub fn matches(&self, metadata: &ObjectMeta, sandbox_id: &str, gateway_id: &str) -> bool { + let label = |key| metadata.labels.as_ref().and_then(|labels| labels.get(key)); + metadata.namespace.as_ref() == Some(&self.namespace) + && metadata.name.as_ref() == Some(&self.name) + && metadata.uid.as_ref() == Some(&self.uid) + && metadata.deletion_timestamp.is_none() + && label(LABEL_SANDBOX_ID).is_some_and(|id| id == sandbox_id) + && label(LABEL_GATEWAY_ID).is_some_and(|id| id == gateway_id) + && label(LABEL_MANAGED_BY).is_some_and(|value| value == LABEL_MANAGED_BY_VALUE) + } +} + +#[derive(Default)] +struct State { + ready: bool, + // Key by resource name so label changes replace the previous association. + objects: BTreeMap<(String, String), (String, Locator)>, + by_id: BTreeMap>, +} + +impl State { + fn remove(&mut self, key: &(String, String)) { + if let Some((id, _)) = self.objects.remove(key) + && let Some(locators) = self.by_id.get_mut(&id) + { + locators.remove(key); + if locators.is_empty() { + self.by_id.remove(&id); + } + } + } + + fn apply(&mut self, metadata: ObjectMeta) { + let (Some(namespace), Some(name)) = (&metadata.namespace, &metadata.name) else { + return; + }; + let key = (namespace.clone(), name.clone()); + self.remove(&key); + let Some(uid) = metadata.uid.clone() else { + return; + }; + let Some(id) = metadata + .labels + .as_ref() + .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) + .cloned() + else { + return; + }; + if metadata.deletion_timestamp.is_some() { + return; + } + let locator = Locator { + namespace: namespace.clone(), + name: name.clone(), + uid, + }; + self.by_id + .entry(id.clone()) + .or_default() + .insert(key.clone(), locator.clone()); + self.objects.insert(key, (id, locator)); + } + + fn delete(&mut self, metadata: &ObjectMeta) { + let (Some(namespace), Some(name)) = (&metadata.namespace, &metadata.name) else { + return; + }; + let key = (namespace.clone(), name.clone()); + if self + .objects + .get(&key) + .is_some_and(|(_, locator)| metadata.uid.as_ref() == Some(&locator.uid)) + { + self.remove(&key); + } + } +} + +#[derive(Clone, Default)] +pub struct AppEndpointIndex(Arc>); + +impl AppEndpointIndex { + pub fn lookup(&self, sandbox_id: &str) -> Option { + let state = self.0.lock().ok()?; + if !state.ready { + return None; + } + let locators = state.by_id.get(sandbox_id)?; + if locators.len() != 1 { + return None; + } + locators.values().next().cloned() + } + + pub fn observe(&self, event: Event) { + let Ok(mut state) = self.0.lock() else { return }; + match event { + Event::Init => *state = State::default(), + Event::InitApply(metadata) | Event::Apply(metadata) => state.apply(metadata), + Event::InitDone => state.ready = true, + Event::Delete(metadata) => state.delete(&metadata), + } + } + + pub fn start( + &self, + api: Api>, + selector: String, + mut shutdown: tokio::sync::watch::Receiver, + ) { + let index = self.clone(); + tokio::spawn(async move { + loop { + if *shutdown.borrow() { + break; + } + let stream = + watcher::watcher(api.clone(), watcher::Config::default().labels(&selector)); + tokio::pin!(stream); + loop { + tokio::select! { + _ = shutdown.changed() => { index.observe(Event::Init); return; } + event = stream.next() => match event { + Some(Ok(event)) => index.observe(match event { + Event::Init => Event::Init, + Event::InitDone => Event::InitDone, + Event::Apply(object) => Event::Apply(object.metadata), + Event::InitApply(object) => Event::InitApply(object.metadata), + Event::Delete(object) => Event::Delete(object.metadata), + }), + Some(Err(error)) => { + tracing::warn!(%error, "application endpoint locator watch failed; relisting"); + break; + } + None => break, + } + } + } + // Recreate the watcher after errors so recovery must complete + // a fresh list; incremental events cannot revive a partial index. + index.observe(Event::Init); + tokio::select! { + _ = shutdown.changed() => return, + () = tokio::time::sleep(Duration::from_secs(1)) => {} + } + } + index.observe(Event::Init); + }); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/openshell-driver-kubernetes/src/app_endpoint_index/tests.rs b/crates/openshell-driver-kubernetes/src/app_endpoint_index/tests.rs new file mode 100644 index 0000000000..e1f248363b --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/app_endpoint_index/tests.rs @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +fn metadata(namespace: &str, name: &str, uid: &str, id: &str) -> ObjectMeta { + ObjectMeta { + namespace: Some(namespace.into()), + name: Some(name.into()), + uid: Some(uid.into()), + labels: Some(BTreeMap::from([ + (LABEL_SANDBOX_ID.into(), id.into()), + (LABEL_GATEWAY_ID.into(), "gateway".into()), + (LABEL_MANAGED_BY.into(), LABEL_MANAGED_BY_VALUE.into()), + ])), + ..Default::default() + } +} + +#[test] +fn partial_initialization_and_watch_reset_do_not_publish_locators() { + let index = AppEndpointIndex::default(); + let object = metadata("ns", "sandbox", "uid", "id"); + index.observe(Event::InitApply(object.clone())); + assert!(index.lookup("id").is_none()); + index.observe(Event::InitDone); + assert!(index.lookup("id").is_some()); + index.observe(Event::Init); + index.observe(Event::InitApply(object)); + assert!(index.lookup("id").is_none()); + index.observe(Event::InitDone); + assert!(index.lookup("id").is_some()); + index.observe(Event::Init); + index.observe(Event::InitDone); + assert!( + index.lookup("id").is_none(), + "relisting removes absent resources" + ); +} + +#[test] +fn duplicate_ids_across_namespaces_are_ambiguous() { + let index = AppEndpointIndex::default(); + let first = metadata("ns-a", "same-name", "uid-a", "id"); + let second = metadata("ns-b", "same-name", "uid-b", "id"); + index.observe(Event::InitApply(first)); + index.observe(Event::InitApply(second.clone())); + index.observe(Event::InitDone); + assert!(index.lookup("id").is_none()); + index.observe(Event::Delete(second)); + assert_eq!(index.lookup("id").unwrap().namespace, "ns-a"); +} + +#[test] +fn delayed_deletion_cannot_remove_recreated_resource() { + let index = AppEndpointIndex::default(); + let original = metadata("ns", "sandbox", "old", "id"); + let replacement = metadata("ns", "sandbox", "new", "id"); + index.observe(Event::InitApply(original.clone())); + index.observe(Event::InitDone); + let old = index.lookup("id").unwrap(); + index.observe(Event::Apply(replacement.clone())); + index.observe(Event::Delete(original)); + assert!(!old.matches(&replacement, "id", "gateway")); + assert!( + index + .lookup("id") + .unwrap() + .matches(&replacement, "id", "gateway") + ); +} + +#[test] +fn label_reassignment_replaces_old_id_and_get_must_match_all_identity_fields() { + let index = AppEndpointIndex::default(); + let mut object = metadata("ns", "sandbox", "uid", "old"); + index.observe(Event::InitApply(object.clone())); + index.observe(Event::InitDone); + object + .labels + .as_mut() + .unwrap() + .insert(LABEL_SANDBOX_ID.into(), "new".into()); + index.observe(Event::Apply(object.clone())); + assert!(index.lookup("old").is_none()); + let locator = index.lookup("new").unwrap(); + assert!(locator.matches(&object, "new", "gateway")); + assert!(!locator.matches(&object, "old", "gateway")); + assert!(!locator.matches(&object, "new", "other-gateway")); + object + .labels + .as_mut() + .unwrap() + .insert(LABEL_MANAGED_BY.into(), "foreign".into()); + assert!(!locator.matches(&object, "new", "gateway")); +} diff --git a/crates/openshell-driver-kubernetes/src/app_endpoint_lookup_tests.rs b/crates/openshell-driver-kubernetes/src/app_endpoint_lookup_tests.rs new file mode 100644 index 0000000000..1f98e05930 --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/app_endpoint_lookup_tests.rs @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; + +#[tokio::test] +async fn indexed_resolution_uses_point_reads_and_rejects_recreated_resources() { + let config = KubernetesComputeConfig::default(); + let metadata = ObjectMeta { + namespace: Some("openshell".into()), + name: Some("team-a--sandbox".into()), + uid: Some("original".into()), + labels: Some(BTreeMap::from([ + (LABEL_SANDBOX_ID.into(), "sandbox-id".into()), + (LABEL_MANAGED_BY.into(), LABEL_MANAGED_BY_VALUE.into()), + (LABEL_GATEWAY_ID.into(), config.gateway_id.clone()), + ])), + ..Default::default() + }; + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let response_metadata = metadata.clone(); + let service = tower::service_fn(move |request: http::Request| { + let count = observed.fetch_add(1, Ordering::SeqCst); + assert_eq!(request.method(), http::Method::GET); + assert_eq!( + request.uri().path(), + "/apis/agents.x-k8s.io/v1beta1/namespaces/openshell/sandboxes/team-a--sandbox" + ); + assert!( + request.uri().query().is_none(), + "renewals must not submit label-selected LISTs" + ); + let mut metadata = response_metadata.clone(); + if count == 2 { + metadata.uid = Some("recreated".into()); + } + async move { + Ok::<_, std::convert::Infallible>(http::Response::new(http_body_util::Full::new(bytes::Bytes::from( + serde_json::to_vec(&serde_json::json!({ + "apiVersion":"agents.x-k8s.io/v1beta1", "kind":"Sandbox", "metadata":metadata + })).unwrap() + )))) + } + }); + let client = Client::new(service, "openshell"); + let mut driver = KubernetesComputeDriver::new_for_test(config); + driver.client = client; + driver + .sandbox_api_version + .set(SANDBOX_VERSION_V1BETA1) + .unwrap(); + driver + .app_endpoint_index + .observe(Event::InitApply(metadata)); + driver.app_endpoint_index.observe(Event::InitDone); + assert!( + driver + .app_endpoint_sandbox("sandbox-id") + .await + .unwrap() + .is_some() + ); + assert!( + driver + .app_endpoint_sandbox("sandbox-id") + .await + .unwrap() + .is_some() + ); + assert!( + driver + .app_endpoint_sandbox("sandbox-id") + .await + .unwrap() + .is_none() + ); + assert_eq!(requests.load(Ordering::SeqCst), 3); + driver.app_endpoint_index.observe(Event::Init); + assert!( + driver + .app_endpoint_sandbox("sandbox-id") + .await + .unwrap() + .is_none() + ); + assert_eq!( + requests.load(Ordering::SeqCst), + 3, + "unavailable index must fail closed without a fallback LIST" + ); +} diff --git a/crates/openshell-driver-kubernetes/src/app_listener.rs b/crates/openshell-driver-kubernetes/src/app_listener.rs index 95e5bfe356..acfcb3e202 100644 --- a/crates/openshell-driver-kubernetes/src/app_listener.rs +++ b/crates/openshell-driver-kubernetes/src/app_listener.rs @@ -24,6 +24,14 @@ pub fn configure_supervisor_pod(mut pod: Pod, config: &KubernetesAppListenerConf let env = container.env.get_or_insert_default(); for (name, value) in [ ("OPENSHELL_APP_LISTENER_ENABLED", "true".to_string()), + ( + "OPENSHELL_APP_MAX_CONNECTIONS", + config.common.max_connections.to_string(), + ), + ( + "OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", + config.common.max_connections_per_sandbox.to_string(), + ), ( "OPENSHELL_APP_LISTEN_ADDRESS", format!("0.0.0.0:{}", config.common.port), @@ -107,6 +115,8 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://services.example.com:10443".into()), + max_connections: 16384, + max_connections_per_sandbox: 256, }, tls_secret_name: "app-tls".into(), }; @@ -125,5 +135,10 @@ mod tests { Some("https://services.example.com:10443") ); assert_eq!(value("OPENSHELL_APP_LISTEN_ADDRESS"), Some("0.0.0.0:9443")); + assert_eq!(value("OPENSHELL_APP_MAX_CONNECTIONS"), Some("16384")); + assert_eq!( + value("OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX"), + Some("256") + ); } } diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index ffae5119d2..2feae9e733 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -1292,6 +1292,7 @@ mod tests { base_url: Some("https://services.example.com".into()), enabled: true, port: 9443, + ..Default::default() }; assert!(config.validate().is_ok()); config.app_listener.common.port = config.boundary_port; diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index d3e2c4720f..5e8817b00f 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -1134,6 +1134,7 @@ pub struct KubernetesComputeDriver { watch_client: Client, sandbox_api_version: Arc>, lifecycle_gates: Arc, + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex, config: KubernetesComputeConfig, /// Gateway-normalized destination trust available only to this in-process /// driver. The external driver protocol deliberately has no transport for @@ -1183,6 +1184,7 @@ impl KubernetesComputeDriver { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config, network_trust_bundle: None, operator_allowlist: None, @@ -1356,6 +1358,7 @@ impl KubernetesComputeDriver { watch_client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config, network_trust_bundle, operator_allowlist, @@ -1367,6 +1370,30 @@ impl KubernetesComputeDriver { driver.backfill_gateway_id_labels().await?; } + if driver.config.sandbox_runtime.app_listener.common.enabled { + let api = driver + .supported_sandbox_api_for_lookup(driver.watch_client.clone()) + .await + .map_err(KubernetesDriverError::Message)?; + let metadata_api = if driver.config.is_multi_namespace() { + Api::>::all_with( + driver.watch_client.clone(), + &api.resource, + ) + } else { + Api::>::namespaced_with( + driver.watch_client.clone(), + &driver.config.namespace, + &api.resource, + ) + }; + driver.app_endpoint_index.start( + metadata_api, + driver.openshell_sandbox_selector(), + shutdown_rx.clone(), + ); + } + driver.spawn_warm_pool_reconciler(shutdown_rx); Ok(driver) } @@ -2329,6 +2356,35 @@ impl KubernetesComputeDriver { Ok(()) } + async fn app_endpoint_sandbox( + &self, + sandbox_id: &str, + ) -> Result, KubernetesDriverError> { + let Some(locator) = self.app_endpoint_index.lookup(sandbox_id) else { + return Ok(None); + }; + let api = self + .supported_agent_sandbox_api(self.client.clone(), &locator.namespace) + .await + .map_err(KubernetesDriverError::Message)?; + let Some(object) = api + .api + .get_opt(&locator.name) + .await + .map_err(KubernetesDriverError::from_kube)? + else { + return Ok(None); + }; + // The watch provides a locator only. A fresh GET and the original UID + // pin are required on every resolution; never cache serving authority. + if !locator.matches(&object.metadata, sandbox_id, &self.config.gateway_id) + || self.app_endpoint_index.lookup(sandbox_id).as_ref() != Some(&locator) + { + return Ok(None); + } + Ok(Some(object)) + } + /// Resolve only a unique, live driver-owned supervisor. Multi-member pool /// resolution must use the HA assignment/member API rather than guess. pub async fn supervisor_app_endpoint( @@ -2341,19 +2397,8 @@ impl KubernetesComputeDriver { if !self.config.sandbox_runtime.app_listener.common.enabled { return Ok(None); } - let api = self - .supported_sandbox_api_for_lookup(self.client.clone()) - .await - .map_err(KubernetesDriverError::Message)?; - let objects = api - .api - .list(&ListParams::default().labels(&self.sandbox_lookup_selector(sandbox_id))) - .await - .map_err(KubernetesDriverError::from_kube)? - .items; - let [object]: [DynamicObject; 1] = match objects.try_into() { - Ok(objects) => objects, - Err(_) => return Ok(None), + let Some(object) = self.app_endpoint_sandbox(sandbox_id).await? else { + return Ok(None); }; let namespace = object.metadata.namespace.as_deref().ok_or_else(|| { KubernetesDriverError::Precondition("sandbox namespace missing".into()) @@ -9845,6 +9890,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: KubernetesComputeConfig::default(), network_trust_bundle: None, operator_allowlist: None, @@ -11112,6 +11158,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: KubernetesComputeConfig::default(), operator_allowlist: None, shared_supervisor: None, @@ -11206,6 +11253,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: KubernetesComputeConfig::default(), operator_allowlist: None, shared_supervisor: None, @@ -13984,6 +14032,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config, network_trust_bundle: None, operator_allowlist: None, @@ -14291,6 +14340,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: managed_config(&[]), network_trust_bundle: None, operator_allowlist: None, @@ -15209,3 +15259,7 @@ mod tests { include!("lifecycle_tests.rs"); } + +#[cfg(test)] +#[path = "app_endpoint_lookup_tests.rs"] +mod app_endpoint_lookup_tests; diff --git a/crates/openshell-driver-kubernetes/src/image_update_tests.rs b/crates/openshell-driver-kubernetes/src/image_update_tests.rs index dcda5c8c7d..d8cd65dd5d 100644 --- a/crates/openshell-driver-kubernetes/src/image_update_tests.rs +++ b/crates/openshell-driver-kubernetes/src/image_update_tests.rs @@ -230,6 +230,7 @@ fn fixture( watch_client: client, sandbox_api_version: Arc::new(api_version), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), shared_supervisor: None, warm_supervision: None, network_trust_bundle: None, diff --git a/crates/openshell-driver-kubernetes/src/lib.rs b/crates/openshell-driver-kubernetes/src/lib.rs index 8441d7db37..237fc3e7e6 100644 --- a/crates/openshell-driver-kubernetes/src/lib.rs +++ b/crates/openshell-driver-kubernetes/src/lib.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +mod app_endpoint_index; pub mod app_listener; pub mod config; pub mod driver; diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index 08b127b507..02cf57d2d3 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -142,6 +142,7 @@ mod lifecycle_reconciliation { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: KubernetesComputeConfig::default(), network_trust_bundle: None, operator_allowlist: None, diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 359c9e610a..ecbba2917d 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -193,6 +193,12 @@ replica, independent of which replica runs the compute driver's watch: owners, and only records of terms older than the listed owner, or of instances without one, are removed. + Cached launch material remains available across host-stream reconnects while + its generation is desired. A reconnect can acknowledge all cached assignments + immediately, without waiting for material-loading batches. Retaining material + grants no authority: snapshots and observations still require the current + owning process and term. Withdrawals and generation changes remove it. + Owner records of withdrawn instances are removed once their generation ended, or two minutes after the withdrawal, after their owner was told to stop them. Pool members still authenticate with the one shared supervisor token, so a @@ -404,31 +410,34 @@ acquisition, allowing rotation without restarting the gateway. ## Application route installation records -Supervisor installation reports arrive only through the authenticated sandbox -session. The gateway issues bounded, single-use lease challenges and validates -reports under the sandbox mutation guard. Accepted records contain current -service declarations, configuration/runtime identity, session fencing, a -trusted driver-resolved app endpoint, and gateway lease expiry. The private -`ComputeDriverAppEndpoints.ResolveSupervisorAppEndpoint` extension RPC resolves this endpoint separately -from `GetSandbox`: endpoint lookup failures do not affect ordinary sandbox -observation. Unsupported drivers return `UNIMPLEMENTED`; an absent endpoint -withholds application publication. The gateway resolves the endpoint once before -issuing each challenge and binds that result to the session and lease sequence. -Acceptance rechecks durable ownership, shared member/readiness authority, runtime, -and configuration without another driver lookup. The next challenge resolves -afresh; the saved result never extends the original lease expiry. -In-process factories opt in with -`ComputeDriverBuildContext::register_app_endpoints`; baseline factories need no -changes. Standalone drivers register the extension on their existing endpoint. -The generic -store key is prefixed `service-installation:`; records are ephemeral and do not -change durable sandbox protobufs. Reads revalidate owner, configuration, -generation, and expiry. Cleanup scans bounded pages and uses conditional deletes -so concurrent renewals are preserved. Cursor progress survives partial sweep -timeouts; bounded record attempts prevent a malformed or stalled record from -starving later cleanup. Failed attempts are revisited on the next scan. -Discovery consumers must not treat these -records as application health or external ingress readiness. +Supervisors send complete installed-route snapshots on their authenticated sandbox +session when the attachment/configuration changes and after reconnecting. They +retry an unacknowledged report; acknowledged installations need no periodic +renewal. The gateway checks declarations, configuration-instance and runtime +identity, current session ownership, and the trusted driver-resolved app endpoint +under the sandbox mutation guard before acknowledging durable acceptance. + +The private `ComputeDriverAppEndpoints.ResolveSupervisorAppEndpoint` extension +resolves application endpoints separately from ordinary `GetSandbox` observation. +Unsupported drivers return `UNIMPLEMENTED`; an absent endpoint prevents a new +installation. In-process factories register the extension with +`ComputeDriverBuildContext::register_app_endpoints`; standalone drivers register +it on their existing endpoint. Supervisors cannot supply backend addresses. + +Records use the generic `service-installation:` key without changing sandbox +protobufs. Their lifetime follows the sandbox attachment and ownership generation, +not a serving deadline. A lost control session or stale heartbeat does not revoke +an acknowledged attachment. Explicit stop/deletion, an ownership transition or a +replacement runtime does. Shared publication requires a matching desired +assignment, ownership epoch, and acknowledged ready report. New admission still +requires live member authority. Conditional, bounded cleanup removes obsolete +records without deleting a newer installation. + +Cleanup retains installation evidence during reversible stop, suspend, and delete +transitions. Those routes remain unpublished until rollback restores the attachment; +a completed transition makes the evidence eligible for collection. + +These records establish neither application health nor external ingress readiness. ## Workspace service discovery @@ -442,37 +451,41 @@ user access. Omitted selectors and sandbox principals are rejected. Dedicated reader grants and cross-workspace scopes are described below. Each successful response replaces the complete view. Consumers preserve the -returned hostname as TLS SNI and HTTP authority when dialing the supervisor -endpoint, remove absent routes, and expire cached entries at `expires_at` even -when discovery is unavailable. An error is not an empty replacement. The opaque -snapshot revision includes lease renewals; `installation_version` remains stable -across those renewals and changes when installation identity changes. These -records establish neither application health nor ingress readiness. - -Collection shares the provider catalog, global settings and bounded service -declarations within one scan, and checks their versions before publication. -Large or unsuitable declaration batches retain the per-sandbox lookup. Sandbox -policy, provider records, settings and live ownership remain individually checked. -Before publication, discovery reads the latest accepted receipts: unchanged -serving identities can use renewed deadlines after configuration revalidation; -replacement or withdrawn installations are omitted. Lease renewals do not -invalidate the whole view, and reads never manufacture or extend a lease. -This is not a cross-resource transaction. Reads are bounded -to 1,000 records, 4,096 routes, 4 MiB, and ten seconds. A per-workspace cache shares -one collection for a one-second refresh interval, retains at most 16 workspaces, -and never returns expired routes. At most four collections and 16 unary snapshot -requests run concurrently per gateway. Collections wait for a free slot within -the ten-second timeout. Unary admission permits four requests per -principal and eight per workspace. Overflow returns `RESOURCE_EXHAUSTED`; storage -failure, configuration changes during collection or timeout return `UNAVAILABLE`; -malformed records return `INTERNAL`. +returned hostname as TLS SNI and HTTP authority, and remove absent routes. +`expires_at` is a consumer refresh hint, not serving permission. Consumers choose +how long to retain a cached view during discovery errors; an error is not an +empty replacement. Snapshot revisions include freshness hints. Installation +versions change on attachment/backend/declaration replacement and remain stable +across control-session reconnects and unrelated configuration edits. + +A per-workspace materialized index compares batched durable version headers and +fetches changed declaration/attachment records across replicas. Publication joins +the installed allowlist with current declarations and authoritative attachment +identity. Editing or deleting one service does not withdraw unrelated services. +Each workspace caches only the global owners, assignments, and reports referenced +by its installations; empty workspaces do not hydrate fleet-wide authority state. +This path does not rebuild policy, provider or settings configuration. Authority +records omit duplicate workload configuration. Storage/synchronization errors +remain errors rather than empty replacements. + +The index retains at most 16 workspaces and allows four concurrent refreshes. +Unused workers stop polling after five seconds and restart on demand. Initial +hydration survives an individual caller's timeout, avoiding repeated cold scans. +Requests wait at most ten seconds for a fresh frame and return `UNAVAILABLE` +until one is ready; a frame older than one refresh interval is not served. +Installation payloads per workspace and combined snapshots remain bounded to +4 MiB each, without a fixed installation or route count ceiling. +At most 16 unary requests run concurrently, with four per principal and eight +per explicitly selected workspace. Overflow returns `RESOURCE_EXHAUSTED`; +storage failure, concurrent configuration invalidation, or index readiness +failure returns `UNAVAILABLE`; malformed installation records return `INTERNAL`. Watches recheck bearer authentication and workspace authorization each second, use a one-message buffer, and end after one minute or a five-second blocked send. Each gateway allows 32 watches, at most four per principal. The eight-snapshot / 16-watch per-workspace limits apply only to explicit single-workspace requests; finite and all-workspace consumers use caller/global limits independently. -Cache reuse adds at most one refresh interval to collection freshness; consumers -must independently honor the advertised lease expiry. +Cache reuse adds one refresh interval to synchronization latency. Consumer refresh +hints do not expire supervisor routes. Reconnect and relist on stream termination; revisions are opaque equality tokens, not resumable cursors or an ordering across gateway replicas. @@ -553,11 +566,11 @@ admission budgets remain independent. All-workspaces collection includes future active workspaces and omits terminating ones, without a fixed workspace-count ceiling. Active workspace metadata is bounded to 4 MiB within the collection deadline. Selected-workspace collection -does not scan unrelated workspaces. Combined snapshots retain the 4,096-route/4-MiB output bound +does not scan unrelated workspaces. Combined snapshots retain the 4-MiB output bound and ten-second deadline covering setup, collection, and final reauthorization. Caller/global capacity is reserved before workspace lookups. Watches retain caller capacity, with tenant-local permits only for single-workspace requests. -Each refresh has the same ten-second deadline. Each workspace scan retains its existing -1,000-record/4-MiB input bounds. Overflow and storage failures are errors, never +Each refresh has the same ten-second deadline. Each workspace scan retains its +4-MiB installation payload bound. Overflow and storage failures are errors, never partial successful views. A workspace-set change during collection requires a retry; this is not a cross-resource transactional snapshot. diff --git a/crates/openshell-server/src/grpc/mutation_replay/tests.rs b/crates/openshell-server/src/grpc/mutation_replay/tests.rs index 0a7648c484..98d6484f83 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/tests.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/tests.rs @@ -212,6 +212,7 @@ async fn create_replay_preserves_all_recorded_urls_when_origins_change() { enabled: true, port: 9443, base_url: Some("https://services.example.com:10443".into()), + ..Default::default() }; let replay = run(&state, authed_request(request)).await.unwrap(); assert_eq!(replay.metadata().get("openshell-replayed").unwrap(), "true"); @@ -240,6 +241,7 @@ async fn expose_replay_preserves_recorded_url_when_origins_change_or_are_disable enabled: true, port: 9443, base_url: Some("https://old.example.com:10443".into()), + ..Default::default() }; run( &state, diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 65af25a55a..ecd9f853dc 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -11,13 +11,11 @@ #![allow(clippy::items_after_statements)] // DB_PORTS const inside function mod config_inputs; -mod discovery_inputs; mod endpoint_status; mod provisioning_clock; #[cfg(test)] mod token_grant_owners_tests; pub use config_inputs::{SandboxConfigInputs, load_sandbox_config_inputs}; -pub(super) use discovery_inputs::DiscoveryConfigInputs; pub use provisioning_clock::configuration_change; pub(super) use endpoint_status::{ diff --git a/crates/openshell-server/src/grpc/policy/discovery_inputs.rs b/crates/openshell-server/src/grpc/policy/discovery_inputs.rs deleted file mode 100644 index cef0f0315a..0000000000 --- a/crates/openshell-server/src/grpc/policy/discovery_inputs.rs +++ /dev/null @@ -1,199 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Collection-local inputs. No validated configuration survives a collection. - -use std::collections::HashMap; - -use openshell_core::proto::{Sandbox, SandboxConfigSnapshot, ServiceEndpoint}; -use openshell_core::{ObjectId, ObjectName, ObjectWorkspace, SetResourceVersion}; -use prost::Message as _; -use tonic::Status; - -use super::super::StoredSettings; -use super::super::provider::load_provider_environment_records; -use super::{build_sandbox_config_snapshot_with_sources, load_global_settings}; -use crate::ServerState; -use crate::persistence::{ObjectListQuery, ObjectType}; -use crate::policy_store::PolicyStoreExt as _; -use crate::provider_profile_sources::EffectiveProviderProfileCatalog; - -const MAX_DECLARATIONS: usize = 4096; -const MAX_DECLARATION_BYTES: usize = 4 * 1024 * 1024; - -#[derive(PartialEq)] -struct Declarations { - versions: Vec<(String, u64)>, - by_sandbox: HashMap>, -} - -impl Declarations { - /// Bulk reads are an optimization, not an additional workspace limit. - /// Legacy/unsuitable rows and large workspaces retain the original lookup. - async fn load(state: &ServerState, workspace: &str) -> Result, Status> { - let mut result = Self { - versions: Vec::new(), - by_sandbox: HashMap::new(), - }; - let mut cursor = None; - let mut bytes = 0usize; - loop { - let page = state - .store - .list_object_page( - ServiceEndpoint::object_type(), - ObjectListQuery::Workspace(workspace), - cursor.as_ref(), - 128, - ) - .await - .map_err(|_| Status::unavailable("service declarations unavailable"))?; - for record in page.records { - bytes = bytes - .saturating_add(record.payload.len()) - .saturating_add(record.labels.as_ref().map_or(0, String::len)); - if bytes > MAX_DECLARATION_BYTES || result.versions.len() >= MAX_DECLARATIONS { - return Ok(None); - } - let Ok(mut endpoint) = ServiceEndpoint::decode(record.payload.as_slice()) else { - return Ok(None); - }; - endpoint.set_resource_version(record.resource_version); - let Ok(labels) = serde_json::from_str::>( - record.labels.as_deref().unwrap_or("{}"), - ) else { - return Ok(None); - }; - let Some(meta) = &endpoint.metadata else { - return Ok(None); - }; - if endpoint.object_id() != record.id - || endpoint.object_workspace() != workspace - || meta.labels != labels - { - return Ok(None); - } - result.versions.push((record.id, record.resource_version)); - if let Some(name) = labels.get("sandbox") { - result - .by_sandbox - .entry(name.clone()) - .or_default() - .push(endpoint); - } - } - let Some(next) = page.next_cursor else { - break; - }; - cursor = Some(next); - } - result.versions.sort(); - // Stable equality even if an update changes the store's listing order. - for endpoints in result.by_sandbox.values_mut() { - endpoints.sort_by(|a, b| a.object_id().cmp(b.object_id())); - } - Ok(Some(result)) - } -} - -pub struct DiscoveryConfigInputs { - workspace: String, - catalog: EffectiveProviderProfileCatalog, - global_settings: StoredSettings, - declarations: Option, -} - -impl DiscoveryConfigInputs { - pub(crate) async fn load(state: &ServerState, workspace: &str) -> Result { - let (catalog, global_settings, declarations) = tokio::try_join!( - state - .provider_profile_sources - .snapshot_catalog(&state.store, workspace), - load_global_settings(&state.store), - Declarations::load(state, workspace), - )?; - Ok(Self { - workspace: workspace.into(), - catalog, - global_settings, - declarations, - }) - } - - pub(crate) async fn ensure_current(&self, state: &ServerState) -> Result<(), Status> { - let next = Self::load(state, &self.workspace).await?; - if self.catalog.revision() != next.catalog.revision() - // A source-owned revision cannot replace a content comparison, - // including the platform fallback beneath workspace overrides. - || self.catalog.list_all_scoped_profiles() != next.catalog.list_all_scoped_profiles() - || self.global_settings.record_id != next.global_settings.record_id - || self.global_settings.resource_version != next.global_settings.resource_version - || self.global_settings.revision != next.global_settings.revision - || self.declarations != next.declarations - { - return Err(Status::unavailable( - "discovery configuration changed during collection", - )); - } - Ok(()) - } - - pub(crate) async fn build( - &self, - state: &ServerState, - sandbox: &Sandbox, - ) -> Result { - if sandbox.object_workspace() != self.workspace { - return Err(Status::internal("installation workspace mismatch")); - } - let providers = sandbox - .spec - .as_ref() - .map_or(&[][..], |spec| spec.providers.as_slice()); - let (records, latest) = tokio::try_join!( - load_provider_environment_records( - &state.store, - &state.refresh, - &self.workspace, - providers - ), - async { - state - .store - .get_latest_policy(sandbox.object_id()) - .await - .map_err(|_| Status::unavailable("sandbox policy unavailable")) - }, - )?; - let routes = if let Some(declarations) = &self.declarations { - let endpoints = declarations - .by_sandbox - .get(sandbox.object_name()) - .cloned() - .unwrap_or_default(); - if endpoints.len() - > usize::try_from(super::super::service::MAX_APP_SERVICE_ROUTES) - .expect("bounded route limit") - { - return Err(Status::resource_exhausted( - "too many application service declarations", - )); - } - Some(super::super::service::configured_app_routes_from_endpoints( - state, sandbox, endpoints, - )?) - } else { - None - }; - build_sandbox_config_snapshot_with_sources( - state, - sandbox, - &self.catalog, - &records, - &self.global_settings, - latest.as_ref(), - routes, - ) - .await - } -} diff --git a/crates/openshell-server/src/grpc/service.rs b/crates/openshell-server/src/grpc/service.rs index 5c95fef3b0..a7557d2319 100644 --- a/crates/openshell-server/src/grpc/service.rs +++ b/crates/openshell-server/src/grpc/service.rs @@ -666,6 +666,7 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://services.example.com".into()), + ..Default::default() }; seed_sandbox(&state, "limited").await; state @@ -794,6 +795,7 @@ mod tests { port: 9443, base_url: application_enabled .then(|| "https://services.example.com:10443".into()), + ..Default::default() }; seed_sandbox(&state, "demo").await; for name in ["", "web"] { @@ -875,6 +877,7 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://services.example.com:10443".into()), + ..Default::default() }; let response = handle_expose_service(&state, authed_request(request.clone())) @@ -926,6 +929,7 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://services.example.com:10443".into()), + ..Default::default() }; let response = service_endpoint_response( &state, @@ -968,6 +972,7 @@ mod tests { base_url: Some("https://services.example.com".into()), enabled: true, port: 9443, + ..Default::default() }; seed_sandbox(&state, "first").await; seed_sandbox(&state, "second").await; diff --git a/crates/openshell-server/src/grpc/service_advertisement.rs b/crates/openshell-server/src/grpc/service_advertisement.rs index 77dd8895a9..0a392a2d69 100644 --- a/crates/openshell-server/src/grpc/service_advertisement.rs +++ b/crates/openshell-server/src/grpc/service_advertisement.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Expiring installation evidence. Addresses always cross the trusted driver +//! Attachment-scoped installation evidence. Addresses always cross the trusted driver //! boundary; the authenticated supervisor supplies only installed declarations. use std::sync::Arc; @@ -9,6 +9,7 @@ use std::time::Duration; use openshell_core::proto::{Sandbox, SandboxServiceRoute, SupervisorServiceAdvertisement}; use openshell_core::{ObjectId, ObjectWorkspace}; +#[cfg(test)] use prost::Message as _; use serde::{Deserialize, Serialize}; use tonic::Status; @@ -19,86 +20,10 @@ use crate::persistence::{ObjectCursor, ObjectRecord, WriteCondition, current_tim use crate::supervisor_owner::{OWNER_TTL, OwnerGuard, SupervisorOwnerIndex}; pub const OBJECT_TYPE: &str = "supervisor_service_installation"; -pub const LEASE: Duration = Duration::from_secs(15); -pub const REPORT_INTERVAL: Duration = Duration::from_secs(5); const MAX_ROUTES: usize = 1024; -/// Trusted driver resolution scoped to one session and one lease exchange. -#[derive(Clone)] -pub struct LeaseAuthority { - sandbox_id: String, - session_id: String, - supervisor_instance_id: String, - connection_epoch: u64, - auth_epoch: Option, - endpoint: openshell_core::proto::compute::v1::SupervisorAppEndpoint, -} - -impl LeaseAuthority { - fn matches(&self, owner: &OwnerGuard) -> bool { - self.sandbox_id == owner.sandbox_id - && self.session_id == owner.session_id - && self.supervisor_instance_id == owner.supervisor_instance_id - && self.connection_epoch == owner.connection_epoch - && self.auth_epoch == owner.auth_epoch - } -} - -pub struct ClaimedLease { - authority: LeaseAuthority, - expires_at_ms: i64, -} - -/// A challenge is session-local and single-use. Its monotonic deadline starts -/// before transmission, so delayed answers never receive a fresh receipt lease. -pub struct LeaseWindow { - sequence: u64, - deadline: tokio::time::Instant, - expires_at_ms: i64, - authority: Option, -} - -impl Default for LeaseWindow { - fn default() -> Self { - Self { - sequence: 0, - deadline: tokio::time::Instant::now(), - expires_at_ms: 0, - authority: None, - } - } -} - -impl LeaseWindow { - pub fn issue( - &mut self, - authority: LeaseAuthority, - ) -> Option { - self.sequence = self.sequence.checked_add(1)?; - self.deadline = tokio::time::Instant::now() + LEASE; - self.expires_at_ms = - current_time_ms() + i64::try_from(LEASE.as_millis()).expect("bounded lease"); - self.authority = Some(authority); - Some(openshell_core::proto::ServiceRouteLease { - sequence: self.sequence, - duration: openshell_core::time::duration_from_std(LEASE).ok(), - expires_at: openshell_core::time::timestamp_from_millis(self.expires_at_ms).ok(), - }) - } - - pub fn claim(&mut self, sequence: u64) -> Option { - if sequence != self.sequence || tokio::time::Instant::now() >= self.deadline { - return None; - } - Some(ClaimedLease { - authority: self.authority.take()?, - expires_at_ms: self.expires_at_ms, - }) - } -} - -/// One record per immutable sandbox identity. These records are ephemeral: -/// reads revalidate owner, configuration, generation, and expiry. +/// One acknowledged installation per immutable sandbox identity. Validity follows +/// its declaration and attachment generation, without timed serving permission. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Installation { pub sandbox_id: String, @@ -116,16 +41,17 @@ pub struct Installation { pub sequence: u64, pub host: String, pub port: u32, - pub expires_at_ms: i64, + #[serde(default)] + pub installed_at_ms: i64, pub routes: Vec>, } impl Installation { - /// Lease-only renewals do not change serving identity or declarations. + /// Report ordering and observation time do not change installed configuration. pub(super) fn same_identity(&self, other: &Self) -> bool { let mut identity = self.clone(); identity.sequence = other.sequence; - identity.expires_at_ms = other.expires_at_ms; + identity.installed_at_ms = other.installed_at_ms; identity == *other } } @@ -140,7 +66,7 @@ fn runtime_identity(sandbox: &Sandbox) -> Result<&str, Status> { .ok_or_else(|| Status::failed_precondition("sandbox runtime identity unavailable")) } -fn validate_routes( +pub(super) fn validate_routes( report: &SupervisorServiceAdvertisement, declared: &[SandboxServiceRoute], ) -> Result<(), Status> { @@ -224,93 +150,11 @@ async fn current_endpoint( .then_some(endpoint)) } -/// A serving lease is issued only while the session still has durable runtime -/// authority. This check is repeated for every lease, independently of config. -pub async fn prepare_lease( - state: &ServerState, - owner: &OwnerGuard, -) -> Result, Status> { - let Some(sandbox) = state - .store - .get_message::(&owner.sandbox_id) - .await - .map_err(|_| Status::unavailable("sandbox storage unavailable"))? - else { - return Ok(None); - }; - if sandbox - .metadata - .as_ref() - .is_some_and(|m| m.deletion_time.is_some()) - { - return Ok(None); - } - let current = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL) - .read(&owner.sandbox_id) - .await - .map_err(|_| Status::unavailable("supervisor ownership unavailable"))?; - if current.is_none_or(|current| { - !current.is_fresh(OWNER_TTL) - || current.session_id != owner.session_id - || current.auth_epoch != owner.auth_epoch - || current.supervisor_instance_id != owner.supervisor_instance_id - || current.connection_epoch != owner.connection_epoch - }) { - return Ok(None); - } - if !state.config.supervisor_app_listener.enabled { - return Ok(None); - } - Ok(current_endpoint(state, &sandbox, owner) - .await? - .map(|endpoint| LeaseAuthority { - sandbox_id: owner.sandbox_id.clone(), - session_id: owner.session_id.clone(), - supervisor_instance_id: owner.supervisor_instance_id.clone(), - connection_epoch: owner.connection_epoch, - auth_epoch: owner.auth_epoch, - endpoint, - })) -} - -pub async fn accept_lease( - state: &Arc, - owner: &OwnerGuard, - report: &SupervisorServiceAdvertisement, - lease: ClaimedLease, -) -> Result<(), Status> { - if !lease.authority.matches(owner) { - return Err(Status::failed_precondition( - "service lease session replaced", - )); - } - accept_inner( - state, - owner, - report, - lease.expires_at_ms, - Some(lease.authority.endpoint), - ) - .await -} - -// Tests can install records directly without performing a session exchange. -#[cfg(test)] +/// Accept an installation snapshot on the current authenticated session. pub async fn accept( state: &Arc, owner: &OwnerGuard, report: &SupervisorServiceAdvertisement, - expires_at_ms: i64, -) -> Result<(), Status> { - accept_inner(state, owner, report, expires_at_ms, None).await -} - -async fn accept_inner( - state: &Arc, - owner: &OwnerGuard, - report: &SupervisorServiceAdvertisement, - expires_at_ms: i64, - resolved_endpoint: Option, ) -> Result<(), Status> { if !state.config.supervisor_app_listener.enabled { return Ok(()); @@ -377,7 +221,7 @@ async fn accept_inner( sequence: report.lease_sequence, host: String::new(), port: 0, - expires_at_ms, + installed_at_ms: current_time_ms(), routes: report .routes .iter() @@ -390,32 +234,23 @@ async fn accept_inner( "installed listener domain is not current", )); } - let config = super::policy::build_sandbox_config_snapshot(state, &sandbox).await?; - if !config.configuration_admitted - || config.configuration_instance_id != report.configuration_instance_id - || config.config_revision != report.config_revision - { + let instance_id = sandbox + .status + .as_ref() + .and_then(|status| status.configuration_admission.as_ref()) + .map_or("", |admission| admission.instance_id.as_str()); + if instance_id != report.configuration_instance_id { return Err(Status::failed_precondition( - "installed configuration is not current", + "installed configuration instance replaced", )); } - validate_routes(report, &config.service_routes)?; - let endpoint = if let Some(endpoint) = resolved_endpoint { - // Reuse only the challenge's driver result. Recheck durable pool - // authority after configuration validation and before publication. - if !endpoint_authority_current(state, &sandbox, owner, &endpoint).await? { - return Err(Status::failed_precondition( - "service lease endpoint authority replaced", - )); - } - endpoint - } else { - current_endpoint(state, &sandbox, owner) - .await? - .ok_or_else(|| { - Status::failed_precondition("trusted supervisor app endpoint unavailable") - })? - }; + let declared = super::service::configured_app_routes(state, &sandbox).await?; + validate_routes(report, &declared)?; + let endpoint = current_endpoint(state, &sandbox, owner) + .await? + .ok_or_else(|| { + Status::failed_precondition("trusted supervisor app endpoint unavailable") + })?; record.pool_route = endpoint.pool_route; record.host = endpoint.host; record.port = endpoint.port; @@ -435,11 +270,6 @@ async fn accept_inner( { return Err(Status::failed_precondition("supervisor ownership replaced")); } - if expires_at_ms <= current_time_ms() { - return Err(Status::failed_precondition( - "service installation lease expired", - )); - } let installation_id = format!("service-installation:{}", sandbox.object_id()); let previous = state .store @@ -450,6 +280,9 @@ async fn accept_inner( let old: Installation = serde_json::from_slice(&previous.payload) .map_err(|_| Status::internal("invalid stored installation"))?; if old.session_id == record.session_id && old.sequence >= record.sequence { + if old.sequence == record.sequence && old.same_identity(&record) { + return Ok(()); + } return Err(Status::failed_precondition( "service installation report replayed", )); @@ -476,16 +309,17 @@ async fn accept_inner( } /// Discovery must call this before publishing each persisted installation. -/// Freshness failures are absence; storage/decoding failures are errors. +/// Withdrawn attachments are absence; storage/decoding failures are errors. pub async fn is_current(state: &ServerState, record: &Installation) -> Result { - Ok(current_routes(state, record).await?.is_some()) + Ok(current_sandbox(state, record).await?.is_some()) } +#[cfg(test)] pub(super) async fn current_routes( state: &ServerState, record: &Installation, ) -> Result>, Status> { - Ok(validated_routes(state, record, None) + Ok(validated_routes(state, record) .await? .map(|(_, routes)| routes)) } @@ -495,22 +329,46 @@ pub(super) async fn current_routes( pub(super) async fn current_sandbox( state: &ServerState, record: &Installation, +) -> Result, Status> { + current_sandbox_from(state, record, state.store.as_ref()).await +} + +pub(super) async fn current_sandbox_from( + state: &ServerState, + record: &Installation, + reader: &impl crate::persistence::object_view::ObjectReader, ) -> Result, Status> { if !state.config.supervisor_app_listener.enabled - || record.expires_at_ms <= current_time_ms() || record.service_domain != state.config.supervisor_app_listener.domain() || record.routes.is_empty() { return Ok(None); } - let Some(sandbox) = state - .store - .get_message::(&record.sandbox_id) + // A reconnect or missing heartbeat is not a new attachment. A known + // replacement process is, even before its first installation arrives. + if let Some(owner) = reader + .record( + "supervisor_session_owner", + &format!("supervisor-owner:{}", record.sandbox_id), + ) + .await + .map_err(|_| Status::unavailable("supervisor ownership unavailable"))? + { + let (_, owner) = crate::supervisor_owner::decode_owner_record(&owner) + .map_err(|_| Status::internal("invalid supervisor owner record"))?; + if owner.supervisor_instance_id != record.supervisor_instance_id { + return Ok(None); + } + } + let Some(sandbox) = reader + .record("sandbox", &record.sandbox_id) .await .map_err(|_| Status::unavailable("sandbox storage unavailable"))? else { return Ok(None); }; + let sandbox: Sandbox = crate::persistence::decode_record(sandbox) + .map_err(|_| Status::internal("invalid sandbox record"))?; if sandbox .metadata .as_ref() @@ -519,23 +377,22 @@ pub(super) async fn current_sandbox( { return Ok(None); } - let Some(owner) = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL) - .read(&record.sandbox_id) - .await - .map_err(|_| Status::unavailable("supervisor ownership unavailable"))? - else { - return Ok(None); - }; - if !owner.is_fresh(OWNER_TTL) - || owner.session_id != record.session_id - || owner.supervisor_instance_id != record.supervisor_instance_id - || owner.connection_epoch != record.connection_epoch - || owner - .auth_epoch - .map_or(0, openshell_core::jwt::CredentialEpoch::get) - != record.ownership_epoch - || !sandbox_term_matches(&sandbox, owner.auth_epoch) - { + if sandbox.status.as_ref().is_some_and(|status| { + matches!( + openshell_core::proto::SandboxPhase::try_from(status.phase).ok(), + Some( + openshell_core::proto::SandboxPhase::Stopping + | openshell_core::proto::SandboxPhase::Stopped + | openshell_core::proto::SandboxPhase::Deleting + | openshell_core::proto::SandboxPhase::Completed + | openshell_core::proto::SandboxPhase::Suspending + | openshell_core::proto::SandboxPhase::Suspended + ) + ) + }) || !sandbox_term_matches( + &sandbox, + openshell_core::jwt::CredentialEpoch::new(record.ownership_epoch).ok(), + ) { return Ok(None); } if !record.pool_route.is_empty() { @@ -546,7 +403,7 @@ pub(super) async fn current_sandbox( pool_route: record.pool_route.clone(), ownership_epoch: record.ownership_epoch, }; - if !crate::supervisor_pool::app_endpoint_current(&state.store, &sandbox, &endpoint) + if !crate::supervisor_pool::app_endpoint_attached_from(reader, &sandbox, &endpoint) .await .map_err(|_| Status::unavailable("pool application authority unavailable"))? { @@ -556,53 +413,97 @@ pub(super) async fn current_sandbox( Ok(Some(sandbox)) } +#[cfg(test)] pub(super) async fn validated_routes( state: &ServerState, record: &Installation, - inputs: Option<&super::policy::DiscoveryConfigInputs>, ) -> Result)>, Status> { let Some(sandbox) = current_sandbox(state, record).await? else { return Ok(None); }; - let config = match inputs { - Some(inputs) => inputs.build(state, &sandbox).await?, - None => super::policy::build_sandbox_config_snapshot(state, &sandbox).await?, - }; - if !config.configuration_admitted - || config.configuration_instance_id != record.configuration_instance_id - || config.config_revision != record.config_revision - { - return Ok(None); - } + let declared = super::service::configured_app_routes(state, &sandbox).await?; let routes = record .routes .iter() .map(|bytes| SandboxServiceRoute::decode(bytes.as_slice())) .collect::, _>>() .map_err(|_| Status::internal("invalid stored service route"))?; - let report = SupervisorServiceAdvertisement { - routes, - ..Default::default() - }; - Ok(validate_routes(&report, &config.service_routes) - .is_ok() - .then_some((sandbox, report.routes))) + let routes = routes + .into_iter() + .filter(|route| declared.contains(route)) + .collect(); + Ok(Some((sandbox, routes))) } const CLEANUP_PAGE_SIZE: u16 = 128; const CLEANUP_RECORD_TIMEOUT: Duration = Duration::from_secs(1); +async fn retain_installation( + state: &ServerState, + installation: &Installation, +) -> Result { + if !installation.routes.is_empty() + && state + .store + .get_message::(&installation.sandbox_id) + .await + .map_err(|_| Status::unavailable("sandbox storage unavailable"))? + .and_then(|sandbox| sandbox.status) + .is_some_and(|status| { + matches!( + openshell_core::proto::SandboxPhase::try_from(status.phase).ok(), + Some( + openshell_core::proto::SandboxPhase::Stopping + | openshell_core::proto::SandboxPhase::Suspending + | openshell_core::proto::SandboxPhase::Deleting + ) + ) + }) + { + // Failed lifecycle operations can restore the same attachment without + // changing its acknowledged report. Suppress publication, but retain + // the evidence until the transition commits or rolls back. + return Ok(true); + } + is_current(state, installation).await +} + async fn cleanup_record(state: &ServerState, record: ObjectRecord) -> Result<(), Status> { let installation: Installation = serde_json::from_slice(&record.payload) .map_err(|_| Status::internal("invalid stored service installation"))?; - if installation.expires_at_ms <= current_time_ms() || !is_current(state, &installation).await? { - // Conditional deletion cannot erase a concurrent renewal. - state - .store - .delete_if(OBJECT_TYPE, &record.id, record.resource_version) - .await - .map_err(|_| Status::unavailable("service installation cleanup failed"))?; + if retain_installation(state, &installation).await? { + return Ok(()); } + + // Deleting and recreating a row resets its resource version. Serialize + // with reports and other collectors, then recheck the scanned identity. + let _guard = state + .compute + .mutation_guard(MutationScope::sandbox( + &record.workspace, + &installation.sandbox_id, + )) + .await + .map_err(|_| Status::unavailable("service installation cleanup lock unavailable"))?; + let Some(current) = state + .store + .get(OBJECT_TYPE, &record.id) + .await + .map_err(|_| Status::unavailable("service installation storage unavailable"))? + else { + return Ok(()); + }; + if current.resource_version != record.resource_version + || current.payload != record.payload + || retain_installation(state, &installation).await? + { + return Ok(()); + } + state + .store + .delete_if(OBJECT_TYPE, ¤t.id, current.resource_version) + .await + .map_err(|_| Status::unavailable("service installation cleanup failed"))?; Ok(()) } @@ -663,212 +564,6 @@ mod tests { use super::test_support::installed_fixture; use super::*; - fn test_lease_authority() -> LeaseAuthority { - LeaseAuthority { - sandbox_id: "sandbox".into(), - session_id: "session".into(), - supervisor_instance_id: "instance".into(), - connection_epoch: 1, - auth_epoch: None, - endpoint: openshell_core::proto::compute::v1::SupervisorAppEndpoint { - host: "10.0.0.7".into(), - port: 9443, - runtime_identity: "runtime-a".into(), - ..Default::default() - }, - } - } - - struct CountingEndpointResolver { - calls: std::sync::atomic::AtomicUsize, - fail: std::sync::atomic::AtomicBool, - } - - #[tonic::async_trait] - impl openshell_core::proto::compute::v1::compute_driver_app_endpoints_server::ComputeDriverAppEndpoints for CountingEndpointResolver { - async fn resolve_supervisor_app_endpoint( - &self, - request: tonic::Request, - ) -> Result, Status> { - self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - if self.fail.load(std::sync::atomic::Ordering::SeqCst) { - return Err(Status::unavailable("endpoint lookup failed")); - } - Ok(tonic::Response::new(openshell_core::proto::compute::v1::ResolveSupervisorAppEndpointResponse { - sandbox_id: request.into_inner().sandbox_id, - supervisor_app_endpoint: Some(test_lease_authority().endpoint), - })) - } - } - - async fn counted_fixture() -> ( - Arc, - OwnerGuard, - SupervisorServiceAdvertisement, - Arc, - ) { - let (mut state, owner, report) = installed_fixture().await; - let resolver = Arc::new(CountingEndpointResolver { - calls: std::sync::atomic::AtomicUsize::new(0), - fail: std::sync::atomic::AtomicBool::new(false), - }); - let inner = Arc::get_mut(&mut state).unwrap(); - inner.compute = inner - .compute - .clone() - .with_app_endpoint_resolver(Some(resolver.clone())); - (state, owner, report, resolver) - } - - #[tokio::test] - async fn lease_exchange_resolves_once_and_withdrawals_do_not_resolve_again() { - use std::sync::atomic::Ordering; - let (state, owner, mut report, resolver) = counted_fixture().await; - let mut window = LeaseWindow::default(); - for expected_calls in 1..=2 { - let authority = prepare_lease(&state, &owner).await.unwrap().unwrap(); - let lease = window.issue(authority).unwrap(); - report.lease_sequence = lease.sequence; - let claimed = window.claim(lease.sequence).unwrap(); - let expiry = claimed.expires_at_ms; - accept_lease(&state, &owner, &report, claimed) - .await - .unwrap(); - assert!(window.claim(lease.sequence).is_none()); - assert_eq!(resolver.calls.load(Ordering::SeqCst), expected_calls); - let row = state - .store - .get(OBJECT_TYPE, "service-installation:sandbox") - .await - .unwrap() - .unwrap(); - let record: Installation = serde_json::from_slice(&row.payload).unwrap(); - assert_eq!(record.expires_at_ms, expiry); - } - let lease = window - .issue(prepare_lease(&state, &owner).await.unwrap().unwrap()) - .unwrap(); - resolver.fail.store(true, Ordering::SeqCst); - report.lease_sequence = lease.sequence; - report.routes.clear(); - accept_lease( - &state, - &owner, - &report, - window.claim(lease.sequence).unwrap(), - ) - .await - .unwrap(); - assert_eq!(resolver.calls.load(Ordering::SeqCst), 3); - assert!(prepare_lease(&state, &owner).await.is_err()); - assert_eq!(resolver.calls.load(Ordering::SeqCst), 4); - } - - #[tokio::test] - async fn resolved_lease_rejects_identity_changes_and_durable_owner_replacement() { - let (state, owner, mut report, _) = counted_fixture().await; - let authority = prepare_lease(&state, &owner).await.unwrap().unwrap(); - // None of these mismatches may reuse another session's resolution. - for field in 0..5 { - let mut changed = owner.clone(); - match field { - 0 => changed.sandbox_id = "another-sandbox".into(), - 1 => changed.session_id = "another-session".into(), - 2 => changed.supervisor_instance_id = "another-instance".into(), - 3 => changed.connection_epoch += 1, - _ => changed.auth_epoch = openshell_core::jwt::CredentialEpoch::new(1).ok(), - } - let mut window = LeaseWindow::default(); - let lease = window.issue(authority.clone()).unwrap(); - assert!( - accept_lease( - &state, - &changed, - &report, - window.claim(lease.sequence).unwrap() - ) - .await - .is_err() - ); - } - let mut window = LeaseWindow::default(); - let lease = window.issue(authority).unwrap(); - report.lease_sequence = lease.sequence; - SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL) - .release_if_current(&owner) - .await - .unwrap(); - SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL) - .publish( - "sandbox", - "replacement-session", - "replacement-instance", - 2, - "other-replica", - "local://other", - ) - .await - .unwrap(); - // The passed guard still matches the challenge, but storage no longer does. - assert!( - accept_lease( - &state, - &owner, - &report, - window.claim(lease.sequence).unwrap() - ) - .await - .is_err() - ); - assert!(prepare_lease(&state, &owner).await.unwrap().is_none()); - } - - #[tokio::test] - async fn resolved_lease_rechecks_runtime_configuration_expiry_and_pool_authority() { - for change in 0..4 { - let (state, owner, mut report, _) = counted_fixture().await; - let mut authority = prepare_lease(&state, &owner).await.unwrap().unwrap(); - if change == 3 { - authority.endpoint.pool_route = "replaced-pool-route".into(); - } - let mut window = LeaseWindow::default(); - let lease = window.issue(authority).unwrap(); - report.lease_sequence = lease.sequence; - let mut claimed = window.claim(lease.sequence).unwrap(); - match change { - 0 => { - let mut sandbox = state - .store - .get_message::("sandbox") - .await - .unwrap() - .unwrap(); - sandbox.metadata.as_mut().unwrap().annotations.insert( - COMPUTE_RUNTIME_IDENTITY_ANNOTATION.into(), - "runtime-b".into(), - ); - state.store.put_message(&sandbox).await.unwrap(); - } - 1 => report.config_revision += 1, - 2 => claimed.expires_at_ms = current_time_ms() - 1, - _ => {} - } - assert!( - accept_lease(&state, &owner, &report, claimed) - .await - .is_err() - ); - assert!( - state - .store - .get(OBJECT_TYPE, "service-installation:sandbox") - .await - .unwrap() - .is_none() - ); - } - } - fn cleanup_test_record(index: usize) -> ObjectRecord { ObjectRecord { object_type: OBJECT_TYPE.into(), @@ -951,15 +646,157 @@ mod tests { } #[tokio::test] - async fn cleanup_preserves_concurrent_renewals_and_rejects_malformed_records() { + async fn cleanup_preserves_installation_recreated_after_an_older_scan() { + let (state, owner, report) = installed_fixture().await; + assert_stale_cleanup_preserves_recreated_installation(&state, &state, &owner, report).await; + } + + #[tokio::test] + async fn cleanup_retains_reversible_lifecycle_transitions_until_they_commit() { + use openshell_core::proto::SandboxPhase; + + for (transition, terminal) in [ + (SandboxPhase::Stopping, Some(SandboxPhase::Stopped)), + (SandboxPhase::Suspending, Some(SandboxPhase::Suspended)), + (SandboxPhase::Deleting, None), + ] { + let (state, owner, report) = installed_fixture().await; + let mut sandbox = state + .store + .get_message::("sandbox") + .await + .unwrap() + .unwrap(); + sandbox.status.get_or_insert_with(Default::default).phase = SandboxPhase::Ready.into(); + state.store.put_message(&sandbox).await.unwrap(); + accept(&state, &owner, &report).await.unwrap(); + let id = "service-installation:sandbox"; + let record = state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); + let installation: Installation = serde_json::from_slice(&record.payload).unwrap(); + + sandbox.status.as_mut().unwrap().phase = transition.into(); + state.store.put_message(&sandbox).await.unwrap(); + assert!(!is_current(&state, &installation).await.unwrap()); + cleanup_record(&state, record.clone()).await.unwrap(); + assert_eq!( + state + .store + .get(OBJECT_TYPE, id) + .await + .unwrap() + .unwrap() + .payload, + record.payload + ); + + // Rollback must recover publication without another supervisor report. + sandbox.status.as_mut().unwrap().phase = SandboxPhase::Ready.into(); + state.store.put_message(&sandbox).await.unwrap(); + assert_eq!( + current_routes(&state, &installation) + .await + .unwrap() + .unwrap(), + report.routes + ); + if let Some(terminal) = terminal { + sandbox.status.as_mut().unwrap().phase = terminal.into(); + state.store.put_message(&sandbox).await.unwrap(); + } else { + state.store.delete("sandbox", "sandbox").await.unwrap(); + } + cleanup_record(&state, record).await.unwrap(); + assert!(state.store.get(OBJECT_TYPE, id).await.unwrap().is_none()); + } + } + + async fn assert_stale_cleanup_preserves_recreated_installation( + state: &Arc, + collector: &ServerState, + owner: &OwnerGuard, + mut report: SupervisorServiceAdvertisement, + ) { + let mut empty = report.clone(); + empty.routes.clear(); + accept(state, owner, &empty).await.unwrap(); + let id = "service-installation:sandbox"; + let scanned = collector.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); + + // Another replica cleans up the initial empty report before the + // supervisor installs its services. Recreating the row restarts its + // resource version, so a version check alone cannot identify it. + cleanup_record(state, scanned.clone()).await.unwrap(); + report.lease_sequence += 1; + accept(state, owner, &report).await.unwrap(); + let installed = state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); + assert_eq!(installed.resource_version, scanned.resource_version); + + cleanup_record(collector, scanned).await.unwrap(); + assert!( + state.store.get(OBJECT_TYPE, id).await.unwrap().is_some(), + "an older cleanup scan must not delete the newly acknowledged installation" + ); + } + + #[tokio::test] + #[ignore = "requires OPENSHELL_TEST_POSTGRES_URL; mise run test:rust:postgres"] + async fn postgres_installation_cleanup_preserves_recreation_across_replicas() { + let (mut writer, owner, report) = installed_fixture().await; + let (mut collector, _, _) = installed_fixture().await; + let schema = + crate::persistence::test_postgres::TestSchema::create("installation_cleanup").await; + let store = Arc::new(schema.connect_store().await); + for kind in [ + "workspace", + "sandbox", + "service_endpoint", + "supervisor_session_owner", + "provider_profile", + ] { + for row in writer.store.list_by_type(kind, 1000, 0).await.unwrap() { + store + .put_if( + kind, + &row.id, + &row.name, + &row.workspace, + &row.payload, + row.labels.as_deref(), + WriteCondition::MustCreate, + ) + .await + .unwrap(); + } + } + let other_store = Arc::new(schema.connect_store().await); + for (state, store) in [(&mut writer, store), (&mut collector, other_store)] { + let driver = Arc::new(crate::compute::NoopTestDriver::with_app_endpoint( + openshell_core::proto::compute::v1::SupervisorAppEndpoint { + host: "10.0.0.7".into(), + port: 9443, + runtime_identity: "runtime-a".into(), + ..Default::default() + }, + )); + let inner = Arc::get_mut(state).unwrap(); + inner.compute = + crate::compute::new_test_runtime_with_driver(store.clone(), "test", driver.clone()) + .with_app_endpoint_resolver(Some(driver)); + inner.store = store; + } + assert_stale_cleanup_preserves_recreated_installation(&writer, &collector, &owner, report) + .await; + schema.drop_schema().await; + } + + #[tokio::test] + async fn cleanup_preserves_newer_installations_and_rejects_malformed_records() { let (state, owner, mut report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let id = "service-installation:sandbox"; let row = state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); - let mut expired: Installation = serde_json::from_slice(&row.payload).unwrap(); - expired.expires_at_ms = 0; + let mut obsolete: Installation = serde_json::from_slice(&row.payload).unwrap(); + obsolete.runtime_identity = "old-runtime".into(); state .store .put_if( @@ -967,19 +804,17 @@ mod tests { id, &row.name, &row.workspace, - &serde_json::to_vec(&expired).unwrap(), + &serde_json::to_vec(&obsolete).unwrap(), None, WriteCondition::MatchResourceVersion(row.resource_version), ) .await .unwrap(); - let expired_record = state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); + let obsolete_record = state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); report.lease_sequence += 1; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let renewed = state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); - let _ = cleanup_record(&state, expired_record).await; + let _ = cleanup_record(&state, obsolete_record).await; assert_eq!( state .store @@ -1008,123 +843,78 @@ mod tests { } } - #[tokio::test(start_paused = true)] - async fn lease_is_single_use_and_delayed_or_superseded_reports_do_not_extend_it() { - let mut window = LeaseWindow::default(); - assert!(window.claim(0).is_none()); - let first = window.issue(test_lease_authority()).unwrap(); - let first_expiry = window.expires_at_ms; - tokio::time::advance(Duration::from_secs(8)).await; + #[tokio::test] + async fn reports_are_idempotent_and_old_sessions_or_sequences_are_rejected() { + let (state, owner, mut report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let id = "service-installation:sandbox"; + let first = state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); + accept(&state, &owner, &report).await.unwrap(); assert_eq!( - window - .claim(first.sequence) - .map(|lease| lease.expires_at_ms), - Some(first_expiry) + state + .store + .get(OBJECT_TYPE, id) + .await + .unwrap() + .unwrap() + .resource_version, + first.resource_version ); - assert!(window.claim(first.sequence).is_none()); - let second = window.issue(test_lease_authority()).unwrap(); - assert!(window.claim(first.sequence).is_none()); - tokio::time::advance(LEASE).await; - assert!(window.claim(second.sequence).is_none()); - } - - #[tokio::test] - async fn withdrawals_persist_but_old_sessions_and_replays_are_rejected() { - use openshell_core::proto::datamodel::v1::ObjectMeta; - let mut state = crate::grpc::test_support::test_server_state().await; - Arc::get_mut(&mut state) - .unwrap() - .config - .supervisor_app_listener - .enabled = true; - let sandbox = Sandbox { - metadata: Some(ObjectMeta { - id: "sandbox".into(), - name: "demo".into(), - workspace: "default".into(), - annotations: [( - COMPUTE_RUNTIME_IDENTITY_ANNOTATION.into(), - "runtime-a".into(), - )] - .into(), - ..Default::default() - }), - ..Default::default() - }; - state.store.put_message(&sandbox).await.unwrap(); - let owners = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL); - let first = owners + let mut replay = report.clone(); + replay.lease_sequence = 0; + assert!(accept(&state, &owner, &replay).await.is_err()); + report.lease_sequence += 1; + report.routes.clear(); + accept(&state, &owner, &report).await.unwrap(); + let row = state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); + let installation: Installation = serde_json::from_slice(&row.payload).unwrap(); + assert!(installation.routes.is_empty()); + assert!(!is_current(&state, &installation).await.unwrap()); + SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL) .publish( "sandbox", - "session-a", + "new-session", "instance", - 1, - "replica-a", - "local://replica-a", + 2, + "other", + "local://other", ) .await .unwrap(); - let report = SupervisorServiceAdvertisement { - lease_sequence: 1, - ..Default::default() - }; - let expires = current_time_ms() + 10_000; - accept(&state, &first, &report, expires).await.unwrap(); - let stored = state + assert!(accept(&state, &owner, &report).await.is_err()); + } + + #[tokio::test] + async fn a_missing_control_session_does_not_revoke_an_attached_installation() { + let (state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let row = state .store .get(OBJECT_TYPE, "service-installation:sandbox") .await .unwrap() .unwrap(); - let installation: Installation = serde_json::from_slice(&stored.payload).unwrap(); - assert_eq!(installation.session_id, "session-a"); - assert!(installation.routes.is_empty()); - assert!(!is_current(&state, &installation).await.unwrap()); - assert_eq!( - accept(&state, &first, &report, expires) - .await - .unwrap_err() - .code(), - tonic::Code::FailedPrecondition - ); - let second = owners - .publish( - "sandbox", - "session-b", - "instance", - 2, - "replica-b", - "local://replica-b", - ) + let mut installation: Installation = serde_json::from_slice(&row.payload).unwrap(); + installation.installed_at_ms = 1; + SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL) + .release_if_current(&owner) .await .unwrap(); - let later = SupervisorServiceAdvertisement { - lease_sequence: 2, - ..Default::default() - }; - assert!(accept(&state, &first, &later, expires).await.is_err()); - accept(&state, &second, &report, expires).await.unwrap(); + assert_eq!( + current_routes(&state, &installation).await.unwrap(), + Some(report.routes) + ); assert!( - accept(&state, &second, &later, current_time_ms() - 1) + accept(&state, &owner, &SupervisorServiceAdvertisement::default()) .await .is_err() ); - state.store.close().await; - assert_eq!( - accept(&state, &second, &later, expires) - .await - .unwrap_err() - .code(), - tonic::Code::Unavailable - ); } #[tokio::test] async fn accepted_installs_use_trusted_endpoints_and_withdraw_on_declaration_or_owner_change() { let (state, owner, mut report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let stored = state .store .get(OBJECT_TYPE, "service-installation:sandbox") @@ -1137,11 +927,7 @@ mod tests { assert!(is_current(&state, &installation).await.unwrap()); report.lease_sequence += 1; report.routes[0].resource_version += 1; - assert!( - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .is_err() - ); + assert!(accept(&state, &owner, &report).await.is_err()); let mut endpoint = state .store .get_message::("endpoint") @@ -1150,7 +936,13 @@ mod tests { .unwrap(); endpoint.target_port = 9090; state.store.put_message(&endpoint).await.unwrap(); - assert!(!is_current(&state, &installation).await.unwrap()); + assert!( + current_routes(&state, &installation) + .await + .unwrap() + .unwrap() + .is_empty() + ); let index = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL); index .publish( @@ -1163,11 +955,7 @@ mod tests { ) .await .unwrap(); - assert!( - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .is_err() - ); + assert!(accept(&state, &owner, &report).await.is_err()); } #[test] @@ -1240,6 +1028,7 @@ pub(super) mod test_support { base_url: Some("https://services.example.com".into()), enabled: true, port: 9443, + ..Default::default() }; let inner = Arc::get_mut(&mut state).unwrap(); inner.config.name = gateway.into(); diff --git a/crates/openshell-server/src/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index 1d1d95dcaa..cdcfc0e824 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -5,31 +5,31 @@ #[cfg(test)] mod freshness_tests; +mod index; +#[cfg(test)] +mod index_tests; use std::sync::Arc; use std::time::Duration; +use openshell_core::ObjectName; use openshell_core::proto::{ DiscoveredServiceRoute, GetServiceRouteSnapshotRequest, GetServiceRouteSnapshotResponse, Sandbox, ServiceRouteEndpoint, ServiceRouteSnapshot, WatchServiceRoutesRequest, WatchServiceRoutesResponse, }; -use openshell_core::{ObjectName, ObjectWorkspace}; use prost::Message as _; use tokio_stream::wrappers::ReceiverStream; use tonic::{Request, Response, Status}; -use super::policy::DiscoveryConfigInputs; -use super::service_advertisement::{Installation, OBJECT_TYPE, current_sandbox, validated_routes}; +use super::service_advertisement::{Installation, OBJECT_TYPE}; use crate::ServerState; use crate::auth::principal::Principal; use crate::auth::workspace_authz::{ MinWorkspaceRole, authorize_workspace, require_platform_admin, selected_workspace_name, }; -use crate::persistence::{ObjectCursor, ObjectRecord, current_time_ms}; +use crate::persistence::{ObjectCursor, current_time_ms}; -const MAX_RECORDS: usize = 1000; -const MAX_ROUTES: usize = 4096; const MAX_BYTES: usize = 4 * 1024 * 1024; const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(10); const WATCH_LIFETIME: Duration = Duration::from_mins(1); @@ -44,8 +44,7 @@ const MAX_COLLECTIONS: usize = 4; const MAX_CACHED_WORKSPACES: usize = 16; const UNARY_PER_PRINCIPAL: usize = 4; const WATCHES_PER_WORKSPACE: usize = 16; -type CachedView = Option<(tokio::time::Instant, Result)>; -type CacheSlot = Arc>; +type CacheSlot = Arc; #[derive(Debug)] pub struct DiscoveryState { @@ -198,46 +197,24 @@ impl DiscoveryState { return Err(Status::resource_exhausted("discovery cache busy")); } } - let slot = Arc::new(tokio::sync::Mutex::new(None)); + let slot = Arc::new(index::Slot::new()); cache.insert(workspace.to_string(), (now, slot.clone())); Ok(slot) } } async fn cached_snapshot( - state: &ServerState, + state: &Arc, workspace: &str, ) -> Result { - tokio::time::timeout(SNAPSHOT_TIMEOUT, async { - let slot = state.discovery.slot(workspace).await?; - let mut cached = slot.lock().await; - if let Some((collected, result)) = cached.as_ref() - && collected.elapsed() < REFRESH_INTERVAL - { - // A cached route must never outlive the independently enforced lease. - let snapshot = result.clone()?; - return if snapshot.routes.iter().all(route_is_live) { - Ok(snapshot) - } else { - finish_snapshot(snapshot.routes) - }; - } - let _permit = state - .discovery - .collections - .clone() - .acquire_owned() - .await - .map_err(|_| Status::unavailable("discovery collections closed"))?; - let result = snapshot(state, workspace).await; - *cached = Some((tokio::time::Instant::now(), result.clone())); - result - }) - .await - .map_err(|_| Status::unavailable("service discovery collection timed out"))? + state + .discovery + .slot(workspace) + .await? + .read(state, workspace) + .await } -/// Captured only by discovery streams; credentials are never logged or persisted. #[derive(Clone)] pub struct BearerRecheck { pub(crate) chain: crate::auth::authenticator::AuthenticatorChain, @@ -438,11 +415,13 @@ async fn selection_workspaces( } async fn selected_snapshot( - state: &ServerState, + state: &Arc, principal: &Principal, selection: &Selection, admitted_workspaces: &[String], ) -> Result { + use futures::{StreamExt as _, TryStreamExt as _}; + tokio::time::timeout(SNAPSHOT_TIMEOUT, async { authorize_selection(state, principal, selection).await?; let before = selection_workspaces(state, selection).await?; @@ -454,10 +433,12 @@ async fn selected_snapshot( let names = before.clone(); let mut result = ServiceRouteSnapshot::default(); let mut bytes = 0usize; - for name in names { - let part = cached_snapshot(state, &name).await?; + let mut parts = futures::stream::iter(names) + .map(|name| async move { cached_snapshot(state, &name).await }) + .buffered(MAX_COLLECTIONS); + while let Some(part) = parts.try_next().await? { bytes = bytes.saturating_add(part.encoded_len()); - if bytes > MAX_BYTES - 128 || result.routes.len() + part.routes.len() > MAX_ROUTES { + if bytes > MAX_BYTES - 128 { return Err(Status::resource_exhausted( "combined discovery limit exceeded", )); @@ -495,7 +476,7 @@ struct PreparedSnapshot { /// Caller/global capacity must be held before doing any authorization or /// workspace I/O. One deadline covers preparation through final reauthorization. async fn prepare_snapshot( - state: &ServerState, + state: &Arc, principal: &mut Principal, selection: &Selection, recheck: Option<&BearerRecheck>, @@ -632,184 +613,71 @@ pub async fn watch( Ok(Response::new(ReceiverStream::new(rx))) } -async fn records(state: &ServerState, workspace: &str) -> Result, Status> { - let mut records = Vec::new(); - let mut cursor: Option = None; - let mut bytes = 0usize; - loop { - let page = state - .store - .list_after(OBJECT_TYPE, workspace, cursor.as_ref(), 128) - .await - .map_err(|_| Status::unavailable("service installation storage unavailable"))?; - for record in &page { - bytes = bytes.saturating_add(record.payload.len()); - if bytes > MAX_BYTES || records.len() + page.len() > MAX_RECORDS { - return Err(Status::resource_exhausted( - "service discovery collection limit exceeded", - )); - } - } - let full = page.len() == 128; - cursor = page.last().map(ObjectCursor::from); - records.extend(page); - if !full { - break; - } - } - Ok(records) -} - -pub async fn snapshot( - state: &ServerState, - workspace: &str, -) -> Result { - tokio::time::timeout(SNAPSHOT_TIMEOUT, collect(state, workspace)) - .await - .map_err(|_| Status::unavailable("service discovery collection timed out"))? -} - -async fn collect(state: &ServerState, workspace: &str) -> Result { - let before = records(state, workspace).await?; - if before.is_empty() { - return finish_snapshot(Vec::new()); - } - let inputs = DiscoveryConfigInputs::load(state, workspace).await?; - let validated = validate_installations(state, workspace, &inputs, before).await?; - publish_installations(state, workspace, &inputs, validated).await -} - -struct ValidatedInstallation { - id: String, - installation: Installation, - sandbox: Sandbox, - routes: Vec, -} - -async fn validate_installations( - state: &ServerState, - workspace: &str, - inputs: &DiscoveryConfigInputs, - before: Vec, -) -> Result, Status> { - let mut validated = Vec::new(); - for object in before { - let installation: Installation = serde_json::from_slice(&object.payload) - .map_err(|_| Status::internal("invalid service installation record"))?; - let Some((sandbox, routes)) = validated_routes(state, &installation, Some(inputs)).await? - else { - continue; - }; - if sandbox.object_workspace() != workspace { - return Err(Status::internal("installation workspace mismatch")); - } - validated.push(ValidatedInstallation { - id: object.id, - installation, - sandbox, - routes, - }); - } - Ok(validated) +/// Test-only synchronization; public RPCs read the maintained frame. +#[cfg(test)] +async fn snapshot(state: &ServerState, workspace: &str) -> Result { + let slot = state.discovery.slot(workspace).await?; + let result = slot.index.lock().await.refresh(state, workspace).await; + slot.publish(result.clone()); + result } -async fn publish_installations( +fn materialize_routes( state: &ServerState, workspace: &str, - inputs: &DiscoveryConfigInputs, - validated: Vec, -) -> Result { - // Refresh receipts after expensive validation. Lease resource-version churn - // is expected: compare serving identity, not a transaction-wide row version. - let mut latest: std::collections::HashMap<_, _> = records(state, workspace) - .await? - .into_iter() - .map(|r| (r.id.clone(), r)) - .collect(); + installation: &Installation, + sandbox: &Sandbox, + installed_routes: Vec, +) -> Result, Status> { let mut routes = Vec::new(); - for previous in validated { - let Some(record) = latest.remove(&previous.id) else { - continue; - }; - let installation: Installation = serde_json::from_slice(&record.payload) - .map_err(|_| Status::internal("invalid service installation record"))?; - if !previous.installation.same_identity(&installation) - || installation.sequence < previous.installation.sequence - || (installation.sequence == previous.installation.sequence - && installation.expires_at_ms != previous.installation.expires_at_ms) - { - continue; - } - let Some(sandbox) = current_sandbox(state, &installation).await? else { - continue; - }; - let installed_routes = if installation.sequence != previous.installation.sequence - || sandbox.metadata != previous.sandbox.metadata - { - // A renewed lease is reused only after checking its configuration - // and live authority too. Never manufacture a new expiry at read time. - let Some((_, routes)) = validated_routes(state, &installation, Some(inputs)).await? - else { - continue; - }; - routes + for route in installed_routes { + let bytes = route.encode_to_vec(); + let hostname = if route.application_hostname.is_empty() { + // Legacy reports can only be current against legacy configuration. + state + .config + .supervisor_app_listener + .service_hostname( + workspace, + sandbox.object_name(), + &route.name, + state.config.service_routing_discriminator(), + ) + .ok_or_else(|| { + Status::failed_precondition("application listener hostname unavailable") + })? } else { - previous.routes + route.application_hostname.clone() }; - for (bytes, route) in installation.routes.iter().zip(installed_routes) { - let hostname = if route.application_hostname.is_empty() { - // Legacy reports can only be current against legacy configuration. - state - .config - .supervisor_app_listener - .service_hostname( - workspace, - sandbox.object_name(), - &route.name, - state.config.service_routing_discriminator(), - ) - .ok_or_else(|| { - Status::failed_precondition("application listener hostname unavailable") - })? - } else { - route.application_hostname.clone() - }; - let label = hostname - .strip_suffix(&format!(".{}", installation.service_domain)) - .ok_or_else(|| Status::internal("installed hostname domain mismatch"))?; - if !openshell_core::app_listener::valid_dns_label(label) { - return Err(Status::failed_precondition( - "service hostname exceeds DNS label limit", - )); - } - let version = installation_version(&installation, bytes)?; - routes.push(DiscoveredServiceRoute { - workspace: workspace.to_string(), - sandbox: sandbox.object_name().to_string(), - name: route.name, - hostname, - endpoint: Some(ServiceRouteEndpoint { - host: installation.host.clone(), - port: installation.port, - }), - installation_version: version, - declaration_revision: route.resource_version, - expires_at: Some( - openshell_core::time::timestamp_from_millis(installation.expires_at_ms) - .map_err(|_| Status::internal("invalid installation expiry"))?, - ), - }); - if routes.len() > MAX_ROUTES { - return Err(Status::resource_exhausted( - "too many discovered service routes", - )); - } + let label = hostname + .strip_suffix(&format!(".{}", installation.service_domain)) + .ok_or_else(|| Status::internal("installed hostname domain mismatch"))?; + if !openshell_core::app_listener::valid_dns_label(label) { + return Err(Status::failed_precondition( + "service hostname exceeds DNS label limit", + )); } + let version = installation_version(installation, &bytes)?; + routes.push(DiscoveredServiceRoute { + workspace: workspace.to_string(), + sandbox: sandbox.object_name().to_string(), + name: route.name, + hostname, + endpoint: Some(ServiceRouteEndpoint { + host: installation.host.clone(), + port: installation.port, + }), + installation_version: version, + declaration_revision: route.resource_version, + expires_at: Some( + openshell_core::time::timestamp_from_millis( + (current_time_ms() / 5000) * 5000 + 30_000, + ) + .map_err(|_| Status::internal("invalid discovery freshness deadline"))?, + ), + }); } - // Shared catalog, global settings and bulk declarations are collection-local. - // Changes invalidate the view; normal serving-lease renewal does not. - inputs.ensure_current(state).await?; - finish_snapshot(routes) + Ok(routes) } fn route_is_live(route: &DiscoveredServiceRoute) -> bool { @@ -823,11 +691,6 @@ fn route_is_live(route: &DiscoveredServiceRoute) -> bool { fn finish_snapshot( mut routes: Vec, ) -> Result { - if routes.len() > MAX_ROUTES { - return Err(Status::resource_exhausted( - "too many discovered service routes", - )); - } routes.retain(route_is_live); routes.sort_by(|a, b| { (&a.workspace, &a.sandbox, &a.name).cmp(&(&b.workspace, &b.sandbox, &b.name)) @@ -851,15 +714,12 @@ fn finish_snapshot( fn installation_version(installation: &Installation, bytes: &[u8]) -> Result { let identity = serde_json::to_vec(&( - "openshell-installation-v1", - &installation.session_id, + "openshell-attachment-v2", + &installation.sandbox_id, &installation.supervisor_instance_id, - installation.connection_epoch, + &installation.runtime_identity, installation.ownership_epoch, &installation.pool_route, - &installation.runtime_identity, - &installation.configuration_instance_id, - installation.config_revision, &installation.service_domain, &installation.host, installation.port, @@ -946,9 +806,7 @@ mod tests { async fn disabled_listener_rejects_discovery_without_allocating_a_watch() { let (mut state, owner, report) = installed_fixture().await; // Persist a route first: disabling must reject discovery even with stored evidence. - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); Arc::get_mut(&mut state) .unwrap() .config @@ -987,9 +845,7 @@ mod tests { config.service_routing.enabled = false; config.supervisor_app_listener.base_url = Some("https://services.example.com:10443".into()); - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let discovered = snapshot(&state, "default").await.unwrap(); assert_eq!(discovered.routes.len(), 1); assert_eq!( @@ -1027,9 +883,7 @@ mod tests { .config .supervisor_app_listener .base_url = Some("https://services.example.com:10443".into()); - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let first = snapshot(&state, "default").await.unwrap(); let hostname = &first.routes[0].hostname; let label = crate::service_routing::service_route_hash_label( @@ -1061,10 +915,7 @@ mod tests { Arc::get_mut(&mut state).unwrap().config.name = "gateway-b".into(); assert!(snapshot(&state, "default").await.unwrap().routes.is_empty()); assert_eq!( - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap_err() - .code(), + accept(&state, &owner, &report).await.unwrap_err().code(), tonic::Code::FailedPrecondition ); let sandbox = state @@ -1082,9 +933,7 @@ mod tests { lease_sequence: report.lease_sequence + 1, ..report }; - accept(&state, &owner, &replacement, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &replacement).await.unwrap(); let second = snapshot(&state, "default").await.unwrap(); assert_ne!(first.routes[0].hostname, second.routes[0].hostname); assert_ne!( @@ -1094,11 +943,9 @@ mod tests { } #[tokio::test] - async fn snapshot_is_shared_between_gateway_states_and_rejects_expired_or_replaced_owners() { + async fn snapshot_is_shared_across_replicas_and_transport_reconnects_but_fences_replacement() { let (state, owner, report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let snapshot_a = get_snapshot(&state, authed_request(request())) .await .unwrap() @@ -1143,21 +990,39 @@ mod tests { .into_inner() .snapshot .unwrap(); - assert_eq!(snapshot_a, snapshot_b); - crate::supervisor_owner::SupervisorOwnerIndex::new( + assert_eq!( + snapshot_a.routes[0].installation_version, + snapshot_b.routes[0].installation_version + ); + let owners = crate::supervisor_owner::SupervisorOwnerIndex::new( state.store.clone(), crate::supervisor_owner::OWNER_TTL, - ) - .publish( - "sandbox", - "replacement", - "instance", - 2, - "other-replica", - "local://other", - ) - .await - .unwrap(); + ); + let reconnected = owners + .publish( + "sandbox", + "replacement", + "instance", + 2, + "other-replica", + "local://other", + ) + .await + .unwrap(); + assert_eq!(snapshot(&state, "default").await.unwrap().routes.len(), 1); + assert_eq!(snapshot(&replica, "default").await.unwrap().routes.len(), 1); + owners.release_if_current(&reconnected).await.unwrap(); + owners + .publish( + "sandbox", + "new-process-session", + "new-process", + 3, + "other-replica", + "local://other", + ) + .await + .unwrap(); assert!(snapshot(&state, "default").await.unwrap().routes.is_empty()); assert!( snapshot(&replica, "default") @@ -1169,11 +1034,9 @@ mod tests { } #[tokio::test] - async fn watch_reports_lease_only_renewal_then_withdrawal_and_releases_its_slot() { + async fn watch_reports_changed_installations_and_withdrawal_and_releases_its_slot() { let (state, owner, mut report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let mut stream = watch( &state, authed_request(WatchServiceRoutesRequest { @@ -1188,36 +1051,64 @@ mod tests { state.discovery_watches.available_permits(), state.config.auth.discovery.max_watches - 1 ); - report.lease_sequence = 2; - accept(&state, &owner, &report, current_time_ms() + 14_000) + state + .store + .update_message_cas::( + "endpoint", + 0, + |endpoint| { + endpoint.target_port += 1; + }, + ) .await .unwrap(); - let renewed = tokio::time::timeout(Duration::from_secs(3), stream.next()) + let sandbox = state + .store + .get_message::("sandbox") .await .unwrap() - .unwrap() - .unwrap() - .snapshot .unwrap(); - assert_ne!(first.revision, renewed.revision); - assert_eq!( - first.routes[0].installation_version, - renewed.routes[0].installation_version - ); - assert_ne!(first.routes[0].expires_at, renewed.routes[0].expires_at); - report.lease_sequence = 3; - report.routes.clear(); - accept(&state, &owner, &report, current_time_ms() + 14_000) + report.routes = super::super::service::configured_app_routes(&state, &sandbox) .await .unwrap(); - let withdrawn = tokio::time::timeout(Duration::from_secs(3), stream.next()) - .await - .unwrap() - .unwrap() - .unwrap() - .snapshot - .unwrap(); - assert!(withdrawn.routes.is_empty()); + report.lease_sequence = 2; + report.config_revision += 1; + accept(&state, &owner, &report).await.unwrap(); + let changed = tokio::time::timeout(Duration::from_secs(3), async { + loop { + let snapshot = stream.next().await.unwrap().unwrap().snapshot.unwrap(); + if snapshot.routes.len() == 1 + && snapshot.routes[0].installation_version + != first.routes[0].installation_version + { + break snapshot; + } + } + }) + .await + .unwrap(); + assert!(changed.routes[0].declaration_revision > first.routes[0].declaration_revision); + report.lease_sequence = 3; + report.routes.clear(); + accept(&state, &owner, &report).await.unwrap(); + tokio::time::timeout(Duration::from_secs(3), async { + loop { + if stream + .next() + .await + .unwrap() + .unwrap() + .snapshot + .unwrap() + .routes + .is_empty() + { + break; + } + } + }) + .await + .unwrap(); drop(stream); tokio::time::timeout(Duration::from_secs(2), async { while state.discovery_watches.available_permits() @@ -1471,20 +1362,19 @@ mod tests { } #[test] - fn route_and_wire_size_limits_reject_partial_views() { + fn snapshots_allow_large_route_counts_within_the_wire_size_bound() { + let routes = 6000; assert_eq!( - finish_snapshot(vec![discovered(); MAX_ROUTES]) + finish_snapshot(vec![discovered(); routes]) .unwrap() .routes .len(), - MAX_ROUTES - ); - assert_eq!( - finish_snapshot(vec![discovered(); MAX_ROUTES + 1]) - .unwrap_err() - .code(), - tonic::Code::ResourceExhausted + routes ); + } + + #[test] + fn wire_size_limit_rejects_partial_views() { let mut route = discovered(); route.hostname = "a".repeat(MAX_BYTES); assert_eq!( @@ -1494,11 +1384,9 @@ mod tests { } #[tokio::test] - async fn identity_fingerprint_changes_for_every_identity_input_but_not_renewal() { + async fn identity_fingerprint_tracks_attachments_not_transport_or_observation_changes() { let (state, owner, report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let object = state .store .get(OBJECT_TYPE, "service-installation:sandbox") @@ -1509,14 +1397,11 @@ mod tests { let bytes = &installation.routes[0]; let original = installation_version(&installation, bytes).unwrap(); let mutations: &[fn(&mut Installation)] = &[ - |i| i.session_id.push('x'), + |i| i.sandbox_id.push('x'), |i| i.supervisor_instance_id.push('x'), - |i| i.connection_epoch += 1, |i| i.ownership_epoch += 1, |i| i.pool_route.push('x'), |i| i.runtime_identity.push('x'), - |i| i.configuration_instance_id.push('x'), - |i| i.config_revision += 1, |i| i.service_domain.push('x'), |i| i.host.push('x'), |i| i.port += 1, @@ -1538,16 +1423,18 @@ mod tests { ); let mut renewed = installation.clone(); renewed.sequence += 1; - renewed.expires_at_ms += 1000; + renewed.installed_at_ms += 1000; + renewed.session_id.push('x'); + renewed.connection_epoch += 1; + renewed.configuration_instance_id.push('x'); + renewed.config_revision += 1; assert_eq!(installation_version(&renewed, bytes).unwrap(), original); } #[tokio::test] async fn snapshot_cache_shares_collection_and_refreshes_after_a_tick() { let (state, owner, report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let first = cached_snapshot(&state, "default").await.unwrap(); assert_eq!(first.routes.len(), 1); let busy = state @@ -1582,9 +1469,7 @@ mod tests { #[tokio::test] async fn collection_waits_for_a_slot_and_resumes_when_one_is_released() { let (state, owner, report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let mut busy = state .discovery .collections @@ -1628,14 +1513,20 @@ mod tests { let start = tokio::time::Instant::now(); let error = cached_snapshot(&state, "default").await.unwrap_err(); assert_eq!(error.code(), tonic::Code::Unavailable); - assert_eq!(error.message(), "service discovery collection timed out"); + assert_eq!(error.message(), "service discovery index not ready"); assert!(start.elapsed() >= SNAPSHOT_TIMEOUT); assert!(start.elapsed() < SNAPSHOT_TIMEOUT + Duration::from_secs(1)); drop(busy); - assert_eq!( - state.discovery.collections.available_permits(), - MAX_COLLECTIONS - ); + tokio::time::resume(); + // The background index survives a reader's deadline and releases its + // collection permit when hydration finishes. + tokio::time::timeout(Duration::from_secs(3), async { + while state.discovery.collections.available_permits() != MAX_COLLECTIONS { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); } #[tokio::test] @@ -1645,13 +1536,10 @@ mod tests { let mut route = discovered(); route.expires_at = Some(openshell_core::time::timestamp_from_millis(current_time_ms() - 1).unwrap()); - *slot.lock().await = Some(( - tokio::time::Instant::now(), - Ok(ServiceRouteSnapshot { - routes: vec![route], - revision: "old".into(), - }), - )); + slot.publish(Ok(ServiceRouteSnapshot { + routes: vec![route], + revision: "old".into(), + })); assert!( cached_snapshot(&state, "default") .await @@ -1708,9 +1596,7 @@ mod tests { async fn collection_survives_concurrent_lease_renewals() { use crate::persistence::WriteCondition; let (state, owner, report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 60_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let record = state .store .get(OBJECT_TYPE, "service-installation:sandbox") @@ -1766,6 +1652,13 @@ mod tests { tokio::select! { _=stopped.changed()=>break, ()=tokio::time::sleep(Duration::from_millis(1))=>{} } } }); + tokio::time::timeout(Duration::from_secs(3), async { + while writes.load(std::sync::atomic::Ordering::Relaxed) <= 50 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); for _ in 0..3 { assert_eq!(snapshot(&state, "default").await.unwrap().routes.len(), 51); } @@ -1849,10 +1742,21 @@ mod tests { } #[tokio::test] - async fn record_count_limit_is_enforced_before_decoding() { - let (state, _, _) = installed_fixture().await; - for n in 0..=MAX_RECORDS { + async fn installation_count_is_bounded_by_payload_size_not_a_fixed_count() { + let (state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let record = state + .store + .get(OBJECT_TYPE, "service-installation:sandbox") + .await + .unwrap() + .unwrap(); + let mut installation: Installation = serde_json::from_slice(&record.payload).unwrap(); + for n in 0..1500 { let id = format!("record-{n}"); + // Retained records without a current sandbox are not published. + installation.sandbox_id = id.clone(); + let payload = serde_json::to_vec(&installation).unwrap(); state .store .put_if( @@ -1860,17 +1764,16 @@ mod tests { &id, &id, "default", - b"{}", + &payload, None, crate::persistence::WriteCondition::MustCreate, ) .await .unwrap(); } - assert_eq!( - snapshot(&state, "default").await.unwrap_err().code(), - tonic::Code::ResourceExhausted - ); + let routes = snapshot(&state, "default").await.unwrap().routes; + assert_eq!(routes.len(), 1); + assert_eq!(routes[0].name, report.routes[0].name); } #[tokio::test] @@ -1880,9 +1783,7 @@ mod tests { service_discovery_server::ServiceDiscoveryServer, }; let (state, owner, report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let service = ServiceDiscoveryServer::with_interceptor( @@ -1989,9 +1890,7 @@ mod tests { } async fn reader_fixture(all: bool) -> (Arc, Principal, tempfile::TempDir) { let (mut state, owner, report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); + accept(&state, &owner, &report).await.unwrap(); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("grants.json"); let fingerprint = "a".repeat(64); @@ -2415,11 +2314,16 @@ mod tests { .unwrap() .into_inner(); assert!(watch.next().await.unwrap().is_ok()); - let error = tokio::time::timeout(Duration::from_secs(5), watch.next()) - .await - .unwrap() - .unwrap() - .unwrap_err(); + let error = tokio::time::timeout(Duration::from_secs(5), async { + loop { + match watch.next().await.unwrap() { + Ok(_) => {} // Freshness hints can precede certificate expiry. + Err(error) => break error, + } + } + }) + .await + .unwrap(); assert_eq!(error.code(), tonic::Code::Unauthenticated); } @@ -2549,7 +2453,6 @@ mod tests { config_revision: config.config_revision, routes: config.service_routes, }, - current_time_ms() + 10_000, ) .await .unwrap(); @@ -2610,7 +2513,17 @@ mod tests { .await .unwrap() .into_inner(); - assert!(stream.next().await.unwrap().is_ok()); + let mut expected = stream + .next() + .await + .unwrap() + .unwrap() + .snapshot + .unwrap() + .routes; + for route in &mut expected { + route.expires_at = None; + } let blockers = (0..WATCHES_PER_WORKSPACE) .map(|n| { state @@ -2631,19 +2544,31 @@ mod tests { }) .await .unwrap(); - // An empty new workspace leaves the route revision unchanged. The - // platform watch must survive the refresh despite the tenant quota. - assert!( - tokio::time::timeout(Duration::from_millis(1500), stream.next()) - .await - .is_err() - ); + // Freshness deadlines can advance during this window. The platform + // watch must retain its routes without consuming the new tenant's quota. + let deadline = tokio::time::Instant::now() + Duration::from_millis(1500); + while let Ok(next) = tokio::time::timeout_at(deadline, stream.next()).await { + let mut routes = next + .expect("platform watch remains open") + .expect("tenant saturation must not reject a platform watch") + .snapshot + .unwrap() + .routes; + for route in &mut routes { + route.expires_at = None; + } + assert_eq!(routes, expected); + } std::fs::write(dir.path().join("grants.json"), r#"{"readers":[]}"#).unwrap(); - let error = tokio::time::timeout(Duration::from_secs(3), stream.next()) - .await - .unwrap() - .unwrap() - .unwrap_err(); + let error = tokio::time::timeout(Duration::from_secs(3), async { + loop { + if let Err(error) = stream.next().await.expect("watch must report revocation") { + break error; + } + } + }) + .await + .unwrap(); assert_eq!(error.code(), tonic::Code::PermissionDenied); drop(stream); drop(blockers); diff --git a/crates/openshell-server/src/grpc/service_discovery/freshness_tests.rs b/crates/openshell-server/src/grpc/service_discovery/freshness_tests.rs index 55f1b72708..1d9d8dc549 100644 --- a/crates/openshell-server/src/grpc/service_discovery/freshness_tests.rs +++ b/crates/openshell-server/src/grpc/service_discovery/freshness_tests.rs @@ -3,306 +3,160 @@ use super::*; use crate::grpc::service_advertisement::{accept, test_support::installed_fixture}; -use crate::supervisor_owner::{OWNER_TTL, OwnerGuard, SupervisorOwnerIndex}; -use openshell_core::proto::{ServiceEndpoint, SupervisorServiceAdvertisement}; +use crate::supervisor_owner::{OWNER_TTL, SupervisorOwnerIndex}; -struct Prepared { - state: Arc, - owner: OwnerGuard, - report: SupervisorServiceAdvertisement, - inputs: DiscoveryConfigInputs, - validated: Vec, -} - -impl Prepared { - async fn new() -> Self { - let (state, owner, report) = installed_fixture().await; - accept(&state, &owner, &report, current_time_ms() + 10_000) - .await - .unwrap(); - let inputs = DiscoveryConfigInputs::load(&state, "default") - .await - .unwrap(); - let validated = validate_installations( - &state, - "default", - &inputs, - records(&state, "default").await.unwrap(), +#[tokio::test] +async fn reconnect_and_absent_control_owner_preserve_an_installed_attachment() { + let (state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let mut index = index::Index::default(); + let first = index.refresh(&state, "default").await.unwrap(); + let owners = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL); + owners.release_if_current(&owner).await.unwrap(); + let disconnected = index.refresh(&state, "default").await.unwrap(); + assert_eq!(disconnected.routes.len(), 1); + assert_eq!( + disconnected.routes[0].installation_version, + first.routes[0].installation_version + ); + let reconnected_owner = owners + .publish( + "sandbox", + "reconnected", + "instance", + 2, + "other", + "local://other", ) .await .unwrap(); - assert_eq!(validated.len(), 1); - Self { - state, - owner, - report, - inputs, - validated, - } - } - - async fn publish(self) -> Result { - publish_installations(&self.state, "default", &self.inputs, self.validated).await - } -} - -#[tokio::test] -async fn renewal_after_validation_uses_the_accepted_deadline_and_preserves_identity() { - let mut p = Prepared::new().await; - let before = &p.validated[0].installation; - let version = installation_version(before, &before.routes[0]).unwrap(); - let expiry = current_time_ms() + 14_000; - p.report.lease_sequence += 1; - accept(&p.state, &p.owner, &p.report, expiry).await.unwrap(); - let snapshot = p.publish().await.unwrap(); - assert_eq!(snapshot.routes.len(), 1); + let reconnected = index.refresh(&state, "default").await.unwrap(); + assert_eq!(reconnected.routes.len(), 1); assert_eq!( - snapshot.routes[0].expires_at, - Some(openshell_core::time::timestamp_from_millis(expiry).unwrap()) + reconnected.routes[0].installation_version, + first.routes[0].installation_version ); - assert_eq!(snapshot.routes[0].installation_version, version); -} - -#[tokio::test] -async fn withdrawal_between_validation_and_publication_removes_the_route() { - let mut p = Prepared::new().await; - p.report.lease_sequence += 1; - p.report.routes.clear(); - accept(&p.state, &p.owner, &p.report, current_time_ms() + 14_000) + owners.release_if_current(&reconnected_owner).await.unwrap(); + assert_eq!( + index.refresh(&state, "default").await.unwrap().routes.len(), + 1 + ); + owners + .publish( + "sandbox", + "replacement", + "new-process", + 3, + "other", + "local://other", + ) .await .unwrap(); - assert!(p.publish().await.unwrap().routes.is_empty()); -} - -#[tokio::test] -async fn replaced_owner_cannot_reuse_a_validated_route_or_renewal() { - for renew in [false, true] { - let mut p = Prepared::new().await; - if renew { - p.report.lease_sequence += 1; - accept(&p.state, &p.owner, &p.report, current_time_ms() + 14_000) - .await - .unwrap(); - } - SupervisorOwnerIndex::new(p.state.store.clone(), OWNER_TTL) - .publish( - "sandbox", - "replacement", - "instance", - 2, - "replica", - "local://replica", - ) + assert!( + index + .refresh(&state, "default") .await - .unwrap(); - assert!(p.publish().await.unwrap().routes.is_empty()); - } + .unwrap() + .routes + .is_empty() + ); } #[tokio::test] -async fn renewed_receipt_revalidates_configuration_admission() { - let mut p = Prepared::new().await; - p.report.lease_sequence += 1; - accept(&p.state, &p.owner, &p.report, current_time_ms() + 14_000) +async fn unrelated_policy_and_settings_edits_do_not_revoke_installed_services() { + use crate::policy_store::PolicyStoreExt as _; + let (state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let mut index = index::Index::default(); + let first = index.refresh(&state, "default").await.unwrap(); + let policy = openshell_policy::restrictive_default_policy(); + state + .store + .put_policy_revision( + "other-policy", + "sandbox", + "default", + 2, + &policy.encode_to_vec(), + &openshell_core::policy_identity::deterministic_policy_hash(&policy), + ) .await .unwrap(); - let mut sandbox = p - .state - .store - .get_message::("sandbox") + let mut settings = super::super::policy::load_global_settings(&state.store) .await - .unwrap() .unwrap(); - sandbox - .status - .get_or_insert_with(Default::default) - .configuration_admission = Some(openshell_core::proto::SandboxConfigurationAdmission { - instance_id: "replacement-admission".into(), - ..Default::default() - }); - p.state.store.put_message(&sandbox).await.unwrap(); - assert!(p.publish().await.unwrap().routes.is_empty()); -} - -#[tokio::test] -async fn shared_declaration_edits_invalidate_the_captured_view() { - let p = Prepared::new().await; - let mut endpoint = p - .state - .store - .get_message::("endpoint") + settings.revision += 1; + settings.settings.insert( + "ocsf_json_enabled".into(), + super::super::StoredSettingValue::Bool(true), + ); + super::super::policy::save_global_settings(&state.store, &settings) .await - .unwrap() .unwrap(); - endpoint.target_port += 1; - p.state.store.put_message(&endpoint).await.unwrap(); - let error = p.publish().await.unwrap_err(); - assert_eq!(error.code(), tonic::Code::Unavailable); - assert!(error.message().contains("configuration changed")); -} - -#[tokio::test] -async fn global_settings_and_catalog_changes_invalidate_shared_inputs() { - for catalog in [false, true] { - let p = Prepared::new().await; - if catalog { - let record = p - .state - .store - .list_by_type_after("provider_profile", None, 1) - .await - .unwrap() - .pop() - .unwrap(); - let mut stored = - crate::storage_proto::StoredProviderProfile::decode(record.payload.as_slice()) - .unwrap(); - stored - .profile - .as_mut() - .unwrap() - .display_name - .push_str(" changed"); - p.state - .store - .put( - &record.object_type, - &record.id, - &record.name, - &record.workspace, - &stored.encode_to_vec(), - record.labels.as_deref(), - ) - .await - .unwrap(); - } else { - let mut settings = super::super::policy::load_global_settings(&p.state.store) - .await - .unwrap(); - settings.revision += 1; - super::super::policy::save_global_settings(&p.state.store, &settings) - .await - .unwrap(); - } - let error = p.publish().await.unwrap_err(); - assert_eq!(error.code(), tonic::Code::Unavailable); - assert!(error.message().contains("configuration changed")); - } + let after = index.refresh(&state, "default").await.unwrap(); + assert_eq!(after.routes.len(), 1); + assert_eq!( + after.routes[0].installation_version, + first.routes[0].installation_version + ); } #[tokio::test] -async fn unsuitable_bulk_declarations_fall_back_without_blocking_other_sandboxes() { - for payload in [b"invalid protobuf".to_vec(), vec![0; 4 * 1024 * 1024 + 1]] { - let p = Prepared::new().await; - p.state +async fn explicit_stop_and_generation_replacement_withdraw_installed_routes() { + use crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION; + for stop in [false, true] { + let (state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let mut index = index::Index::default(); + assert_eq!( + index.refresh(&state, "default").await.unwrap().routes.len(), + 1 + ); + let mut sandbox = state .store - .put( - "service_endpoint", - "unrelated", - "unrelated", - "default", - &payload, - Some(r#"{"sandbox":"another"}"#), - ) + .get_message::("sandbox") .await + .unwrap() .unwrap(); - let snapshot = snapshot(&p.state, "default").await.unwrap(); - assert_eq!(snapshot.routes.len(), 1); - } -} - -#[tokio::test] -async fn receipt_identity_changes_and_deletion_cannot_extend_a_validated_route() { - for mutation in 0..3 { - let p = Prepared::new().await; - let id = &p.validated[0].id; - if mutation == 0 { - p.state.store.delete(OBJECT_TYPE, id).await.unwrap(); + if stop { + sandbox.status.get_or_insert_with(Default::default).phase = + openshell_core::proto::SandboxPhase::Stopping.into(); } else { - let mut value = p.validated[0].installation.clone(); - let record = p.state.store.get(OBJECT_TYPE, id).await.unwrap().unwrap(); - value.sequence += 1; - value.expires_at_ms = current_time_ms() + 14_000; - if mutation == 1 { - value.host = "10.0.0.99".into(); - } else { - value.runtime_identity = "replacement-runtime".into(); - } - p.state - .store - .put( - OBJECT_TYPE, - id, - &record.name, - "default", - &serde_json::to_vec(&value).unwrap(), - None, - ) - .await - .unwrap(); + sandbox.metadata.as_mut().unwrap().annotations.insert( + COMPUTE_RUNTIME_IDENTITY_ANNOTATION.into(), + "replacement-runtime".into(), + ); } - assert!(p.publish().await.unwrap().routes.is_empty()); + state.store.put_message(&sandbox).await.unwrap(); + assert!( + index + .refresh(&state, "default") + .await + .unwrap() + .routes + .is_empty() + ); } } #[tokio::test] -async fn renewed_receipts_recheck_policy_and_settings_without_a_sandbox_record_edit() { - use crate::policy_store::PolicyStoreExt as _; - for policy in [false, true] { - let mut p = Prepared::new().await; - p.report.lease_sequence += 1; - accept(&p.state, &p.owner, &p.report, current_time_ms() + 14_000) - .await - .unwrap(); - if policy { - let policy = openshell_policy::restrictive_default_policy(); - let hash = openshell_core::policy_identity::deterministic_policy_hash(&policy); - p.state - .store - .put_policy_revision( - "changed-policy", - "sandbox", - "default", - 2, - &policy.encode_to_vec(), - &hash, - ) - .await - .unwrap(); - } else { - let mut settings = - super::super::policy::load_sandbox_settings(&p.state.store, "default", "demo") - .await - .unwrap(); - settings.revision += 1; - settings.settings.insert( - "ocsf_json_enabled".into(), - super::super::StoredSettingValue::Bool(true), - ); - super::super::policy::save_sandbox_settings( - &p.state.store, - "default", - "demo", - &settings, - ) - .await - .unwrap(); - } - let sandbox = p - .state - .store - .get_message::("sandbox") +async fn explicit_installation_withdrawal_removes_routes_without_waiting_for_expiry() { + let (state, owner, mut report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let mut index = index::Index::default(); + assert_eq!( + index.refresh(&state, "default").await.unwrap().routes.len(), + 1 + ); + report.routes.clear(); + report.lease_sequence += 1; + accept(&state, &owner, &report).await.unwrap(); + assert!( + index + .refresh(&state, "default") .await .unwrap() - .unwrap(); - assert_eq!(sandbox.metadata, p.validated[0].sandbox.metadata); - let changed = super::super::policy::build_sandbox_config_snapshot(&p.state, &sandbox) - .await - .unwrap(); - assert_ne!( - changed.config_revision, - p.validated[0].installation.config_revision - ); - assert!(p.publish().await.unwrap().routes.is_empty()); - } + .routes + .is_empty() + ); } diff --git a/crates/openshell-server/src/grpc/service_discovery/index.rs b/crates/openshell-server/src/grpc/service_discovery/index.rs new file mode 100644 index 0000000000..775cb0963d --- /dev/null +++ b/crates/openshell-server/src/grpc/service_discovery/index.rs @@ -0,0 +1,328 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! A materialized join of desired declarations and acknowledged attachments. +//! Control-session liveness does not revoke an installed route. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use openshell_core::proto::{SandboxStatus, ServiceEndpoint}; + +use super::*; +use crate::persistence::object_view::{ObjectReader, ObjectView}; + +#[cfg(test)] +mod tests; + +const WORKSPACE_TYPES: &[&str] = &[ + "supervisor_service_installation", + "sandbox", + "service_endpoint", +]; + +type Frame = Option<(tokio::time::Instant, Result)>; + +pub(super) struct Slot { + pub index: tokio::sync::Mutex, + frame: tokio::sync::watch::Sender, + usage: std::sync::Mutex, +} + +struct Usage { + used_at: tokio::time::Instant, + running: bool, +} + +impl std::fmt::Debug for Slot { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DiscoveryIndexSlot") + .field("running", &self.usage.lock().is_ok_and(|u| u.running)) + .finish_non_exhaustive() + } +} + +impl Slot { + pub fn new() -> Self { + Self { + index: tokio::sync::Mutex::new(Index::default()), + frame: tokio::sync::watch::channel(None).0, + usage: std::sync::Mutex::new(Usage { + used_at: tokio::time::Instant::now(), + running: false, + }), + } + } + + pub fn publish(&self, result: Result) { + self.frame + .send_replace(Some((tokio::time::Instant::now(), result))); + } + + pub async fn read( + self: &Arc, + state: &Arc, + workspace: &str, + ) -> Result { + let start = { + let mut usage = self.usage.lock().expect("discovery index usage lock"); + usage.used_at = tokio::time::Instant::now(); + !std::mem::replace(&mut usage.running, true) + }; + if start { + let weak_slot = Arc::downgrade(self); + let weak_state = Arc::downgrade(state); + let workspace = workspace.to_string(); + tokio::spawn(async move { + loop { + let (Some(slot), Some(state)) = (weak_slot.upgrade(), weak_state.upgrade()) + else { + return; + }; + { + let mut usage = slot.usage.lock().expect("discovery index usage lock"); + if usage.used_at.elapsed() > Duration::from_secs(5) { + usage.running = false; + return; + } + } + // Startup hydration survives an individual RPC's deadline. + // Eviction/drop stops the worker after its current pass. + let result = async { + let _permit = state + .discovery + .collections + .acquire() + .await + .map_err(|_| Status::unavailable("discovery index closed"))?; + slot.index.lock().await.refresh(&state, &workspace).await + } + .await; + drop(state); + slot.publish(result); + drop(slot); + tokio::time::sleep(REFRESH_INTERVAL).await; + } + }); + } + let mut rx = self.frame.subscribe(); + tokio::time::timeout(SNAPSHOT_TIMEOUT, async { + loop { + if let Some((at, result)) = rx.borrow_and_update().clone() + && at.elapsed() < REFRESH_INTERVAL + { + let snapshot = result?; + return if snapshot.routes.iter().all(route_is_live) { + Ok(snapshot) + } else { + finish_snapshot(snapshot.routes) + }; + } + rx.changed() + .await + .map_err(|_| Status::unavailable("discovery index stopped"))?; + } + }) + .await + .map_err(|_| Status::unavailable("service discovery index not ready"))? + } +} + +#[derive(Default)] +pub(super) struct Index { + view: ObjectView, + authority: ObjectView, + #[cfg(test)] + pub refreshes: usize, +} + +impl Index { + fn installations(&self, workspace: &str) -> Result, Status> { + let records: Vec<_> = self + .view + .records + .values() + .filter(|r| r.object_type == OBJECT_TYPE && r.workspace == workspace) + .collect(); + if records.iter().map(|r| r.payload.len()).sum::() > MAX_BYTES { + return Err(Status::resource_exhausted( + "service discovery collection limit exceeded", + )); + } + records + .into_iter() + .map(|r| { + serde_json::from_slice(&r.payload) + .map_err(|_| Status::internal("invalid service installation record")) + }) + .collect() + } + + pub async fn refresh( + &mut self, + state: &ServerState, + workspace: &str, + ) -> Result { + #[cfg(test)] + { + self.refreshes += 1; + } + let changes = self + .view + .synchronize(&state.store, workspace, WORKSPACE_TYPES) + .await + .map_err(|_| Status::unavailable("discovery index storage unavailable or changing"))?; + for changed in changes { + if changed.object_type == "sandbox" + && let Some(record) = self.view.records.get_mut(&changed.id) + { + let sandbox = crate::persistence::decode_record::(record.clone()) + .map_err(|_| Status::internal("invalid sandbox record"))?; + // Publication needs attachment identity and explicit lifecycle, + // not a duplicate copy of workload configuration or policy. + record.payload = Sandbox { + metadata: sandbox.metadata, + status: sandbox.status.map(|s| SandboxStatus { + phase: s.phase, + ..Default::default() + }), + ..Default::default() + } + .encode_to_vec(); + } + } + let installations = self.installations(workspace)?; + let mut authority_names = BTreeSet::new(); + for installation in &installations { + if installation.routes.is_empty() + || !self + .view + .records + .get(&installation.sandbox_id) + .is_some_and(|r| r.object_type == "sandbox" && r.workspace == workspace) + { + continue; + } + authority_names.insert(("supervisor_session_owner", installation.sandbox_id.clone())); + if !installation.pool_route.is_empty() { + authority_names.extend(crate::supervisor_pool::app_endpoint_authority_names( + &installation.pool_route, + installation.ownership_epoch, + )); + } + } + self.authority + .synchronize_named( + &state.store, + &authority_names.into_iter().collect::>(), + ) + .await + .map_err(|_| { + Status::unavailable("discovery authority storage unavailable or changing") + })?; + let names = self + .view + .records + .values() + .filter(|r| r.object_type == "sandbox" && r.workspace == workspace) + .map(|r| { + crate::persistence::decode_record::(r.clone()) + .map(|sandbox| sandbox.object_name().to_string()) + .map_err(|_| Status::internal("invalid sandbox record")) + }) + .collect::, _>>()?; + let mut declarations: HashMap> = HashMap::new(); + for record in self + .view + .records + .values() + .filter(|r| r.object_type == "service_endpoint" && r.workspace == workspace) + { + let labels: HashMap = + serde_json::from_str(record.labels.as_deref().unwrap_or("{}")) + .map_err(|_| Status::internal("invalid service declaration labels"))?; + if let Some(sandbox) = labels.get("sandbox") + && names.contains(sandbox) + { + let endpoint = crate::persistence::decode_record::(record.clone()) + .map_err(|_| Status::internal("invalid service declaration"))?; + declarations + .entry(sandbox.clone()) + .or_default() + .push(endpoint); + } + } + let mut routes = Vec::new(); + for (position, installation) in installations.into_iter().enumerate() { + if position % 64 == 0 { + tokio::task::yield_now().await; + } + let Some(sandbox) = super::super::service_advertisement::current_sandbox_from( + state, + &installation, + self, + ) + .await? + else { + continue; + }; + let declared = super::super::service::configured_app_routes_from_endpoints( + state, + &sandbox, + declarations + .get(sandbox.object_name()) + .cloned() + .unwrap_or_default(), + )?; + let installed = installation + .routes + .iter() + .map(|bytes| openshell_core::proto::SandboxServiceRoute::decode(bytes.as_slice())) + .collect::, _>>() + .map_err(|_| Status::internal("invalid stored service route"))?; + // A changed or withdrawn service does not revoke unrelated routes + // while the supervisor applies its next complete configuration. + let current = installed + .into_iter() + .filter(|route| declared.contains(route)) + .collect(); + routes.extend(materialize_routes( + state, + workspace, + &installation, + &sandbox, + current, + )?); + } + finish_snapshot(routes) + } +} + +#[async_trait::async_trait] +impl ObjectReader for Index { + async fn record( + &self, + object_type: &str, + id: &str, + ) -> crate::persistence::PersistenceResult> { + match self.view.record(object_type, id).await? { + Some(record) => Ok(Some(record)), + None => self.authority.record(object_type, id).await, + } + } + + async fn named_record( + &self, + object_type: &str, + workspace: &str, + name: &str, + ) -> crate::persistence::PersistenceResult> { + match self.view.named_record(object_type, workspace, name).await? { + Some(record) => Ok(Some(record)), + None => { + self.authority + .named_record(object_type, workspace, name) + .await + } + } + } +} diff --git a/crates/openshell-server/src/grpc/service_discovery/index/tests.rs b/crates/openshell-server/src/grpc/service_discovery/index/tests.rs new file mode 100644 index 0000000000..2852cbb25b --- /dev/null +++ b/crates/openshell-server/src/grpc/service_discovery/index/tests.rs @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::grpc::service_advertisement::{accept, test_support::installed_fixture}; +use crate::supervisor_owner::{OWNER_TTL, SupervisorOwnerIndex}; + +#[tokio::test] +async fn workspace_indexes_retain_only_referenced_authority() { + let (state, owner, mut report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let owners = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL); + for n in 0..50 { + owners + .publish( + &format!("unrelated-{n}"), + "session", + "instance", + 1, + "replica", + "local://replica", + ) + .await + .unwrap(); + } + let mut populated = Index::default(); + assert_eq!( + populated + .refresh(&state, "default") + .await + .unwrap() + .routes + .len(), + 1 + ); + assert_eq!(populated.authority.records.len(), 1); + assert!( + populated + .authority + .records + .contains_key("supervisor-owner:sandbox") + ); + for workspace in ["empty-a", "empty-b"] { + let mut empty = Index::default(); + assert!( + empty + .refresh(&state, workspace) + .await + .unwrap() + .routes + .is_empty() + ); + assert!(empty.authority.records.is_empty()); + assert!(empty.authority.versions.is_empty()); + } + + report.routes.clear(); + report.lease_sequence += 1; + accept(&state, &owner, &report).await.unwrap(); + assert!( + populated + .refresh(&state, "default") + .await + .unwrap() + .routes + .is_empty() + ); + assert!(populated.authority.records.is_empty()); +} diff --git a/crates/openshell-server/src/grpc/service_discovery/index_tests.rs b/crates/openshell-server/src/grpc/service_discovery/index_tests.rs new file mode 100644 index 0000000000..f98c762c38 --- /dev/null +++ b/crates/openshell-server/src/grpc/service_discovery/index_tests.rs @@ -0,0 +1,345 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::grpc::service_advertisement::{accept, test_support::installed_fixture}; +use crate::supervisor_owner::{OWNER_TTL, SupervisorOwnerIndex}; +use openshell_core::proto::{ServiceEndpoint, SupervisorServiceAdvertisement}; + +async fn second_sandbox(state: &Arc) { + let mut sandbox = state + .store + .get_message::("sandbox") + .await + .unwrap() + .unwrap(); + let meta = sandbox.metadata.as_mut().unwrap(); + meta.id = "second".into(); + meta.name = "other".into(); + state.store.put_message(&sandbox).await.unwrap(); + let mut endpoint = state + .store + .get_message::("endpoint") + .await + .unwrap() + .unwrap(); + let meta = endpoint.metadata.as_mut().unwrap(); + meta.id = "second-endpoint".into(); + meta.name = "other--web".into(); + meta.labels.insert("sandbox".into(), "other".into()); + endpoint.sandbox_id = "second".into(); + endpoint.sandbox = "other".into(); + state.store.put_message(&endpoint).await.unwrap(); + let owner = SupervisorOwnerIndex::new(state.store.clone(), OWNER_TTL) + .publish( + "second", + "second-session", + "second-instance", + 1, + "replica", + "local://replica", + ) + .await + .unwrap(); + let config = super::super::policy::build_sandbox_config_snapshot(state, &sandbox) + .await + .unwrap(); + let report = SupervisorServiceAdvertisement { + service_domain: state.config.supervisor_app_listener.domain(), + configuration_instance_id: config.configuration_instance_id, + config_revision: config.config_revision, + routes: config.service_routes, + lease_sequence: 1, + }; + accept(state, &owner, &report).await.unwrap(); +} + +#[tokio::test] +async fn repeated_reports_and_operational_status_keep_the_attachment() { + let (state, owner, mut report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let mut index = index::Index::default(); + let first = index.refresh(&state, "default").await.unwrap(); + assert_eq!(first.routes.len(), 1); + for _ in 0..5 { + report.lease_sequence += 1; + accept(&state, &owner, &report).await.unwrap(); + let mut sandbox = state + .store + .get_message::("sandbox") + .await + .unwrap() + .unwrap(); + sandbox.status.get_or_insert_with(Default::default).phase = + openshell_core::proto::SandboxPhase::Ready.into(); + state.store.put_message(&sandbox).await.unwrap(); + let next = index.refresh(&state, "default").await.unwrap(); + assert_eq!(next.routes.len(), 1); + assert_eq!( + next.routes[0].installation_version, + first.routes[0].installation_version + ); + } +} + +#[tokio::test] +async fn declaration_edits_revalidate_only_the_affected_sandbox() { + let (state, owner, mut report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + second_sandbox(&state).await; + let mut index = index::Index::default(); + let first = index.refresh(&state, "default").await.unwrap(); + assert_eq!(first.routes.len(), 2); + let unaffected = first + .routes + .iter() + .find(|r| r.sandbox == "other") + .unwrap() + .clone(); + + let mut endpoint = state + .store + .get_message::("endpoint") + .await + .unwrap() + .unwrap(); + endpoint.target_port += 1; + state.store.put_message(&endpoint).await.unwrap(); + let withdrawn = index.refresh(&state, "default").await.unwrap(); + assert_eq!(withdrawn.routes, vec![unaffected.clone()]); + // Rejected old evidence is cached until configuration or installation changes. + assert_eq!( + index.refresh(&state, "default").await.unwrap().routes, + vec![unaffected] + ); + + let sandbox = state + .store + .get_message::("sandbox") + .await + .unwrap() + .unwrap(); + let config = super::super::policy::build_sandbox_config_snapshot(&state, &sandbox) + .await + .unwrap(); + report.lease_sequence += 1; + report.config_revision = config.config_revision; + report.routes = config.service_routes; + accept(&state, &owner, &report).await.unwrap(); + assert_eq!( + index.refresh(&state, "default").await.unwrap().routes.len(), + 2 + ); +} + +#[tokio::test] +async fn a_declaration_label_change_invalidates_its_previous_sandbox() { + let (state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + second_sandbox(&state).await; + let mut index = index::Index::default(); + let first = index.refresh(&state, "default").await.unwrap(); + assert_eq!(first.routes.len(), 2); + let unaffected = first + .routes + .into_iter() + .find(|r| r.sandbox == "other") + .unwrap(); + let mut endpoint = state + .store + .get_message::("endpoint") + .await + .unwrap() + .unwrap(); + endpoint + .metadata + .as_mut() + .unwrap() + .labels + .insert("sandbox".into(), "other".into()); + state.store.put_message(&endpoint).await.unwrap(); + assert_eq!( + index.refresh(&state, "default").await.unwrap().routes, + vec![unaffected] + ); +} + +#[tokio::test] +async fn a_newly_accepted_driver_endpoint_replaces_the_cached_address() { + let (mut state, owner, mut report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let first = snapshot(&state, "default").await.unwrap(); + let driver = Arc::new(crate::compute::NoopTestDriver::with_app_endpoint( + openshell_core::proto::compute::v1::SupervisorAppEndpoint { + host: "10.0.0.99".into(), + port: 9443, + runtime_identity: "runtime-a".into(), + ..Default::default() + }, + )); + let inner = Arc::get_mut(&mut state).unwrap(); + inner.compute = inner + .compute + .clone() + .with_app_endpoint_resolver(Some(driver)); + report.lease_sequence += 1; + accept(&state, &owner, &report).await.unwrap(); + let next = snapshot(&state, "default").await.unwrap(); + assert_eq!(next.routes.len(), 1); + assert_eq!(next.routes[0].endpoint.as_ref().unwrap().host, "10.0.0.99"); + assert_ne!( + next.routes[0].installation_version, + first.routes[0].installation_version + ); +} + +#[tokio::test] +async fn cancelling_a_reader_does_not_cancel_hydration() { + let (state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let busy = state + .discovery + .collections + .clone() + .acquire_many_owned(u32::try_from(MAX_COLLECTIONS).unwrap()) + .await + .unwrap(); + assert!( + tokio::time::timeout( + Duration::from_millis(20), + cached_snapshot(&state, "default") + ) + .await + .is_err() + ); + drop(busy); + let view = tokio::time::timeout(Duration::from_secs(3), cached_snapshot(&state, "default")) + .await + .unwrap() + .unwrap(); + assert_eq!(view.routes.len(), 1); +} + +#[tokio::test] +async fn unused_workers_stop_polling_and_restart_on_demand() { + let (state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + assert_eq!( + cached_snapshot(&state, "default") + .await + .unwrap() + .routes + .len(), + 1 + ); + tokio::time::sleep(Duration::from_secs(6)).await; + let slot = state.discovery.slot("default").await.unwrap(); + let stopped_at = slot.index.lock().await.refreshes; + tokio::time::sleep(Duration::from_secs(1)).await; + assert_eq!(slot.index.lock().await.refreshes, stopped_at); + state + .store + .delete("service_endpoint", "endpoint") + .await + .unwrap(); + assert!( + cached_snapshot(&state, "default") + .await + .unwrap() + .routes + .is_empty() + ); +} + +#[tokio::test] +#[ignore = "requires OPENSHELL_TEST_POSTGRES_URL; mise run test:rust:postgres"] +async fn postgres_replicas_hydrate_and_track_remote_renewal_and_configuration_changes() { + use crate::persistence::WriteCondition; + use crate::persistence::test_postgres::TestSchema; + let (mut state, owner, report) = installed_fixture().await; + accept(&state, &owner, &report).await.unwrap(); + let schema = TestSchema::create("discovery_index").await; + let first_store = Arc::new(schema.connect_store().await); + for kind in [ + "sandbox", + "service_endpoint", + "supervisor_session_owner", + "provider_profile", + OBJECT_TYPE, + ] { + for row in state.store.list_by_type(kind, 1000, 0).await.unwrap() { + first_store + .put_if( + kind, + &row.id, + &row.name, + &row.workspace, + &row.payload, + row.labels.as_deref(), + WriteCondition::MustCreate, + ) + .await + .unwrap(); + } + } + Arc::get_mut(&mut state).unwrap().store = first_store.clone(); + let second_store = schema.connect_store().await; + let mut first = index::Index::default(); + let a = first.refresh(&state, "default").await.unwrap(); + assert_eq!(a.routes.len(), 1); + let mut second = index::Index::default(); + assert_eq!( + second.refresh(&state, "default").await.unwrap().routes[0].installation_version, + a.routes[0].installation_version + ); + + let stored = second_store + .get(OBJECT_TYPE, "service-installation:sandbox") + .await + .unwrap() + .unwrap(); + let mut receipt: Installation = serde_json::from_slice(&stored.payload).unwrap(); + receipt.sequence += 1; + receipt.installed_at_ms += 1000; + second_store + .put_if( + OBJECT_TYPE, + &stored.id, + &stored.name, + &stored.workspace, + &serde_json::to_vec(&receipt).unwrap(), + None, + WriteCondition::MatchResourceVersion(stored.resource_version), + ) + .await + .unwrap(); + let renewed = first.refresh(&state, "default").await.unwrap(); + assert_eq!( + renewed.routes[0].installation_version, + a.routes[0].installation_version + ); + + second_store + .delete("service_endpoint", "endpoint") + .await + .unwrap(); + assert!( + first + .refresh(&state, "default") + .await + .unwrap() + .routes + .is_empty() + ); + assert!( + second + .refresh(&state, "default") + .await + .unwrap() + .routes + .is_empty() + ); + second_store.close().await; + first_store.close().await; + schema.drop_schema().await; +} diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index 36ad37d06a..4fb0aa5de9 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -9,6 +9,7 @@ mod legacy_time_wire; pub mod lock_order; mod mutation_admission; pub mod mutation_lock; +pub mod object_view; mod postgres; #[cfg(test)] mod refresh_lock_tests; @@ -347,7 +348,7 @@ pub fn generate_name() -> String { /// Extracted to avoid repeating the identical decode-and-hydrate block across /// `get_message`, `get_message_by_name`, `list_messages`, and /// `list_messages_with_selector`. -fn decode_record( +pub fn decode_record( record: ObjectRecord, ) -> PersistenceResult { let payload = legacy_time_wire::migrate(T::object_type(), &record.payload)?; diff --git a/crates/openshell-server/src/persistence/object_view.rs b/crates/openshell-server/src/persistence/object_view.rs new file mode 100644 index 0000000000..dd57f87ce3 --- /dev/null +++ b/crates/openshell-server/src/persistence/object_view.rs @@ -0,0 +1,300 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Batched durable change tracking for derived in-memory views. + +use std::collections::HashMap; + +use sqlx::Row as _; + +use super::{ObjectRecord, PersistenceResult, PostgresStore, SqliteStore, Store, map_db_error}; + +#[cfg(test)] +mod tests; + +/// A small inventory entry. Payloads are fetched only for changed records. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ObjectVersion { + pub id: String, + pub object_type: String, + pub workspace: String, + pub name: String, + pub scope: Option, + pub labels: Option, + pub resource_version: u64, + pub updated_at_ms: i64, +} + +/// The same authority predicates run against durable storage at admission and +/// against a synchronized object view during discovery publication. +#[async_trait::async_trait] +pub trait ObjectReader: Sync { + async fn record(&self, object_type: &str, id: &str) -> PersistenceResult>; + async fn named_record( + &self, + object_type: &str, + workspace: &str, + name: &str, + ) -> PersistenceResult>; +} + +#[async_trait::async_trait] +impl ObjectReader for Store { + async fn record(&self, object_type: &str, id: &str) -> PersistenceResult> { + self.get(object_type, id).await + } + + async fn named_record( + &self, + object_type: &str, + workspace: &str, + name: &str, + ) -> PersistenceResult> { + self.get_by_name(object_type, workspace, name).await + } +} + +#[derive(Default)] +pub struct ObjectView { + pub versions: HashMap, + pub records: HashMap, + names: HashMap<(String, String, String), String>, +} + +impl ObjectView { + /// One consistent version inventory detects writes and deletions made by + /// any replica. Reading headers also detects a late-committing write; this + /// does not depend on wall-clock or sequence allocation commit ordering. + pub async fn synchronize( + &mut self, + store: &Store, + workspace: &str, + types: &[&str], + ) -> PersistenceResult> { + self.synchronize_versions(store, store.object_versions(workspace, types).await?) + .await + } + + /// Refresh only the globally stored authority objects referenced by a + /// workspace's installations, including removals and same-name replacements. + pub async fn synchronize_named( + &mut self, + store: &Store, + names: &[(&str, String)], + ) -> PersistenceResult> { + self.synchronize_versions(store, store.named_object_versions(names).await?) + .await + } + + async fn synchronize_versions( + &mut self, + store: &Store, + versions: Vec, + ) -> PersistenceResult> { + let mut versions: HashMap<_, _> = versions.into_iter().map(|v| (v.id.clone(), v)).collect(); + let changed: Vec<_> = versions + .values() + .filter(|v| self.versions.get(&v.id) != Some(*v)) + .cloned() + .collect(); + let ids: Vec<_> = changed.iter().map(|v| v.id.as_str()).collect(); + let fetched = store.object_records(&ids).await?; + // Configuration stamps must match their payload. Receipt/authority + // renewal is expected during the read: use its newer identity and + // deadline together, and let the common authority predicates check it. + if changed.iter().any(|v| { + fetched.get(&v.id).is_some_and(|r| { + r.object_type != v.object_type + || r.workspace != v.workspace + || r.name != v.name + || (!v.object_type.starts_with("supervisor_") + && (r.resource_version != v.resource_version + || r.updated_at_ms != v.updated_at_ms)) + }) + }) { + return Err(super::PersistenceError::Unavailable( + "objects changed during view synchronization".into(), + )); + } + for v in &changed { + if let Some(record) = fetched.get(&v.id) { + let current = versions.get_mut(&v.id).expect("inventoried object"); + current.resource_version = record.resource_version; + current.updated_at_ms = record.updated_at_ms; + current.labels.clone_from(&record.labels); + } else { + // A concurrent deletion is a withdrawal, not a reason to + // retain the old object until its deadline. + versions.remove(&v.id); + } + } + let mut events = changed; + events.extend( + self.versions + .values() + // Invalidate the previous dependency as well when a name, + // label or scope moves an object to another sandbox. + .filter(|v| versions.get(&v.id) != Some(*v)) + .cloned(), + ); + for event in &events { + let name = ( + event.object_type.clone(), + event.workspace.clone(), + event.name.clone(), + ); + if self.names.get(&name) == Some(&event.id) { + self.names.remove(&name); + } + if !versions.contains_key(&event.id) { + self.records.remove(&event.id); + } + } + for (id, record) in fetched { + self.names.insert( + ( + record.object_type.clone(), + record.workspace.clone(), + record.name.clone(), + ), + id.clone(), + ); + self.records.insert(id, record); + } + self.versions = versions; + Ok(events) + } +} + +#[async_trait::async_trait] +impl ObjectReader for ObjectView { + async fn record(&self, object_type: &str, id: &str) -> PersistenceResult> { + Ok(self + .records + .get(id) + .filter(|r| r.object_type == object_type) + .cloned()) + } + + async fn named_record( + &self, + object_type: &str, + workspace: &str, + name: &str, + ) -> PersistenceResult> { + Ok(self + .names + .get(&(object_type.into(), workspace.into(), name.into())) + .and_then(|id| self.records.get(id)) + .cloned()) + } +} + +impl Store { + pub(crate) async fn object_versions( + &self, + workspace: &str, + types: &[&str], + ) -> PersistenceResult> { + match self { + Self::Postgres(s) => s.object_versions(workspace, types).await, + Self::Sqlite(s) => s.object_versions(workspace, types).await, + } + } + + pub(crate) async fn named_object_versions( + &self, + names: &[(&str, String)], + ) -> PersistenceResult> { + match self { + Self::Postgres(s) => s.named_object_versions(names).await, + Self::Sqlite(s) => s.named_object_versions(names).await, + } + } + + pub(crate) async fn object_records( + &self, + ids: &[&str], + ) -> PersistenceResult> { + match self { + Self::Postgres(s) => s.object_records(ids).await, + Self::Sqlite(s) => s.object_records(ids).await, + } + } +} + +const VERSION_SELECT: &str = "SELECT id, object_type, workspace, name, scope, CAST(labels AS TEXT) AS labels, resource_version, updated_at_ms FROM objects o WHERE "; + +macro_rules! implement_view_reads { + ($store:ty, $db:ty) => { + impl $store { + async fn object_versions(&self, workspace: &str, types: &[&str]) -> PersistenceResult> { + if types.is_empty() { return Ok(Vec::new()); } + let mut sql = sqlx::QueryBuilder::<$db>::new(VERSION_SELECT); + sql.push("workspace = ").push_bind(workspace).push(" AND object_type IN ("); + let mut items = sql.separated(", "); + for kind in types { items.push_bind(*kind); } + items.push_unseparated(")"); + sql.push(" AND (object_type <> 'sandbox' OR EXISTS (SELECT 1 FROM objects receipt WHERE receipt.object_type = 'supervisor_service_installation' AND receipt.name = o.id AND receipt.workspace = o.workspace))"); + self.read_object_versions(&mut sql).await + } + + async fn named_object_versions(&self, names: &[(&str, String)]) -> PersistenceResult> { + let mut by_type: std::collections::BTreeMap<_, Vec<_>> = std::collections::BTreeMap::new(); + for (kind, name) in names { + by_type.entry(*kind).or_default().push(name); + } + let mut versions = Vec::new(); + // Grouping by type lets the existing (type, workspace, name) + // index serve these lookups on both SQLite and PostgreSQL. + for (kind, names) in by_type { + for batch in names.chunks(super::EXISTING_IDS_BATCH_SIZE - 1) { + let mut sql = sqlx::QueryBuilder::<$db>::new(VERSION_SELECT); + sql.push("workspace = '' AND object_type = ").push_bind(kind).push(" AND name IN ("); + let mut items = sql.separated(", "); + for name in batch { items.push_bind(*name); } + items.push_unseparated(")"); + versions.extend(self.read_object_versions(&mut sql).await?); + } + } + Ok(versions) + } + + async fn read_object_versions(&self, sql: &mut sqlx::QueryBuilder<$db>) -> PersistenceResult> { + sql.build().fetch_all(&self.pool).await.map_err(|e| map_db_error(&e))? + .into_iter().map(|row| { + let version: i64 = row.get("resource_version"); + Ok(ObjectVersion { + id: row.get("id"), object_type: row.get("object_type"), workspace: row.get("workspace"), + name: row.get::,_>("name").unwrap_or_default(), scope: row.get("scope"), + labels: row.get("labels"), resource_version: version.max(1).cast_unsigned(), updated_at_ms: row.get("updated_at_ms"), + }) + }).collect() + } + + async fn object_records(&self, ids: &[&str]) -> PersistenceResult> { + let mut records = HashMap::new(); + for batch in ids.chunks(super::EXISTING_IDS_BATCH_SIZE) { + let mut sql = sqlx::QueryBuilder::<$db>::new("SELECT id, object_type, workspace, name, payload, created_at_ms, updated_at_ms, CAST(labels AS TEXT) AS labels, resource_version FROM objects WHERE id IN ("); + let mut items = sql.separated(", "); + for id in batch { items.push_bind(*id); } + items.push_unseparated(")"); + for row in sql.build().fetch_all(&self.pool).await.map_err(|e| map_db_error(&e))? { + let version: i64 = row.get("resource_version"); + let record = ObjectRecord { + id: row.get("id"), object_type: row.get("object_type"), workspace: row.get("workspace"), + name: row.get::,_>("name").unwrap_or_default(), payload: row.get("payload"), + created_at_ms: row.get("created_at_ms"), updated_at_ms: row.get("updated_at_ms"), labels: row.get("labels"), + resource_version: version.max(1).cast_unsigned(), + }; + records.insert(record.id.clone(), record); + } + } + Ok(records) + } + } + } +} + +implement_view_reads!(PostgresStore, sqlx::Postgres); +implement_view_reads!(SqliteStore, sqlx::Sqlite); diff --git a/crates/openshell-server/src/persistence/object_view/tests.rs b/crates/openshell-server/src/persistence/object_view/tests.rs new file mode 100644 index 0000000000..f743295bc7 --- /dev/null +++ b/crates/openshell-server/src/persistence/object_view/tests.rs @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::persistence::WriteCondition; + +#[tokio::test] +async fn named_authority_views_scope_batch_and_refresh_records() { + let store = Store::connect("sqlite::memory:").await.unwrap(); + assert_scoped_authority(&store).await; +} + +#[tokio::test] +#[ignore = "requires OPENSHELL_TEST_POSTGRES_URL; mise run test:rust:postgres"] +async fn postgres_named_authority_views_scope_batch_and_refresh_records() { + let schema = crate::persistence::test_postgres::TestSchema::create("authority_view").await; + let store = schema.connect_store().await; + assert_scoped_authority(&store).await; + store.close().await; + schema.drop_schema().await; +} + +async fn assert_scoped_authority(store: &Store) { + let count = super::super::EXISTING_IDS_BATCH_SIZE; + let mut names = Vec::new(); + for n in 0..count { + let name = format!("sandbox-{n}"); + store + .put_if( + "supervisor_session_owner", + &format!("owner-{n}"), + &name, + "", + b"owner", + None, + WriteCondition::MustCreate, + ) + .await + .unwrap(); + names.push(("supervisor_session_owner", name)); + } + for (kind, workspace, id) in [ + ("supervisor_instance_owner", "", "unrelated-type"), + ("supervisor_session_owner", "team-a", "unrelated-workspace"), + ] { + store + .put_if( + kind, + id, + "sandbox-0", + workspace, + b"other", + None, + WriteCondition::MustCreate, + ) + .await + .unwrap(); + } + let mut view = ObjectView::default(); + view.synchronize(store, "empty", &["supervisor_session_owner"]) + .await + .unwrap(); + assert!(view.records.is_empty()); + view.synchronize_named(store, &names).await.unwrap(); + assert_eq!(view.records.len(), count); + + store + .delete("supervisor_session_owner", "owner-0") + .await + .unwrap(); + store + .put_if( + "supervisor_session_owner", + "replacement", + "sandbox-0", + "", + b"new owner", + None, + WriteCondition::MustCreate, + ) + .await + .unwrap(); + store + .delete("supervisor_session_owner", "owner-1") + .await + .unwrap(); + view.synchronize_named(store, &names).await.unwrap(); + assert_eq!(view.records.len(), count - 1); + assert!(!view.records.contains_key("owner-0")); + assert_eq!( + view.named_record("supervisor_session_owner", "", "sandbox-0") + .await + .unwrap() + .unwrap() + .payload, + b"new owner" + ); + assert!( + view.named_record("supervisor_session_owner", "", "sandbox-1") + .await + .unwrap() + .is_none() + ); + + view.synchronize_named(store, &names[..1]).await.unwrap(); + assert_eq!(view.records.len(), 1); + view.synchronize_named(store, &[]).await.unwrap(); + assert!(view.records.is_empty()); + assert!(view.versions.is_empty()); + assert!( + view.named_record("supervisor_session_owner", "", "sandbox-0") + .await + .unwrap() + .is_none() + ); +} diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index ac3e51390c..fdc2e8fde8 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -2326,6 +2326,7 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://apps.example.com".into()), + ..Default::default() }; for workspace in ["default", "team-a"] { for service in ["", "web"] { diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 79a63a3f8d..a014baadc3 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -251,8 +251,10 @@ mod tests { // and the public/durable overlap remain unchanged. // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. + // Supervisor installation acknowledgement adds one session-protocol + // message without changing durable schemas or discovery response fields. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "aed3d40bfff8721632e47ef4e918dfe375bec26b69d36873eb5a109c20b7cd6b"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = @@ -820,7 +822,7 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), + (370, 32), (104, 23), (88, 23), PUBLIC_RPC_SCHEMA_SHA256, diff --git a/crates/openshell-server/src/supervisor_owner.rs b/crates/openshell-server/src/supervisor_owner.rs index f83374eb42..4e73388a88 100644 --- a/crates/openshell-server/src/supervisor_owner.rs +++ b/crates/openshell-server/src/supervisor_owner.rs @@ -310,7 +310,7 @@ impl SupervisorOwnerIndex { } } -fn decode_owner_record(record: &ObjectRecord) -> Result<(String, OwnerRecord), OwnerError> { +pub fn decode_owner_record(record: &ObjectRecord) -> Result<(String, OwnerRecord), OwnerError> { let payload: OwnerPayload = serde_json::from_slice(&record.payload) .map_err(|err| PersistenceError::Decode(err.to_string()))?; if payload.sandbox_id != record.name || record.id != owner_object_id(&payload.sandbox_id) { diff --git a/crates/openshell-server/src/supervisor_pool.rs b/crates/openshell-server/src/supervisor_pool.rs index b6259fda95..fb6ad09428 100644 --- a/crates/openshell-server/src/supervisor_pool.rs +++ b/crates/openshell-server/src/supervisor_pool.rs @@ -174,6 +174,15 @@ fn report_object_name(route: &str, auth_epoch: u64) -> String { format!("{route}:{auth_epoch}") } +/// Global records needed to validate one acknowledged application attachment. +pub fn app_endpoint_authority_names(route: &str, auth_epoch: u64) -> [(&'static str, String); 3] { + [ + (ASSIGNMENT_OBJECT_TYPE, route.to_string()), + (OWNER_OBJECT_TYPE, route.to_string()), + (REPORT_OBJECT_TYPE, report_object_name(route, auth_epoch)), + ] +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] struct MemberPayload { member_id: String, @@ -451,8 +460,8 @@ pub struct SupervisorPool { owner_gone_since: Mutex>, /// Takeover credentials minted for terms of members this replica serves. minted: Mutex>, - /// Launch material loaded for instances owned by members this replica - /// serves, or launched here. + /// Launch material of desired generations loaded here. Retained across + /// host reconnects; assignments still require their current owner. materials: Mutex>, /// The last report this replica recorded of each route. /// When each owner record of an instance that is no longer desired was @@ -549,6 +558,33 @@ pub async fn app_endpoint_current( store: &Store, sandbox: &Sandbox, endpoint: &openshell_core::proto::compute::v1::SupervisorAppEndpoint, +) -> Result { + app_endpoint_current_from(store, sandbox, endpoint).await +} + +pub async fn app_endpoint_current_from( + store: &impl crate::persistence::object_view::ObjectReader, + sandbox: &Sandbox, + endpoint: &openshell_core::proto::compute::v1::SupervisorAppEndpoint, +) -> Result { + app_endpoint_authority_from(store, sandbox, endpoint, true).await +} + +/// An acknowledged attachment survives control-stream and member-heartbeat +/// interruption. Assignment withdrawal or replacement still fences it. +pub async fn app_endpoint_attached_from( + store: &impl crate::persistence::object_view::ObjectReader, + sandbox: &Sandbox, + endpoint: &openshell_core::proto::compute::v1::SupervisorAppEndpoint, +) -> Result { + app_endpoint_authority_from(store, sandbox, endpoint, false).await +} + +async fn app_endpoint_authority_from( + store: &impl crate::persistence::object_view::ObjectReader, + sandbox: &Sandbox, + endpoint: &openshell_core::proto::compute::v1::SupervisorAppEndpoint, + require_live_member: bool, ) -> Result { let Some(metadata) = &sandbox.metadata else { return Ok(false); @@ -556,7 +592,7 @@ pub async fn app_endpoint_current( let identity = PersistedSandboxIdentity::read(&metadata.annotations) .map_err(|error| PersistenceError::Decode(error.to_string()))?; let Some(assignment_row) = store - .get_by_name(ASSIGNMENT_OBJECT_TYPE, "", &endpoint.pool_route) + .named_record(ASSIGNMENT_OBJECT_TYPE, "", &endpoint.pool_route) .await? else { return Ok(false); @@ -571,7 +607,7 @@ pub async fn app_endpoint_current( return Ok(false); } let Some(row) = store - .get(OWNER_OBJECT_TYPE, &owner_object_id(&endpoint.pool_route)) + .record(OWNER_OBJECT_TYPE, &owner_object_id(&endpoint.pool_route)) .await? else { return Ok(false); @@ -587,33 +623,35 @@ pub async fn app_endpoint_current( { return Ok(false); } - let Some(member_row) = store - .get(MEMBER_OBJECT_TYPE, &member_object_id(&owner.member_id)) - .await? - else { - return Ok(false); - }; - if now_ms().saturating_sub(member_row.updated_at_ms) - >= i64::try_from(MEMBER_TTL.as_millis()).expect("bounded member TTL") - { - return Ok(false); - } - let member: MemberPayload = serde_json::from_slice(&member_row.payload) - .map_err(|error| PersistenceError::Decode(error.to_string()))?; - if member.member_id != owner.member_id - || member.process_id != owner.process_id - || member.leaving - || member - .runtime_address - .parse::() - .ok() - .map(|a| a.ip()) - != endpoint.host.parse::().ok() - { - return Ok(false); + if require_live_member { + let Some(member_row) = store + .record(MEMBER_OBJECT_TYPE, &member_object_id(&owner.member_id)) + .await? + else { + return Ok(false); + }; + if now_ms().saturating_sub(member_row.updated_at_ms) + >= i64::try_from(MEMBER_TTL.as_millis()).expect("bounded member TTL") + { + return Ok(false); + } + let member: MemberPayload = serde_json::from_slice(&member_row.payload) + .map_err(|error| PersistenceError::Decode(error.to_string()))?; + if member.member_id != owner.member_id + || member.process_id != owner.process_id + || member.leaving + || member + .runtime_address + .parse::() + .ok() + .map(|a| a.ip()) + != endpoint.host.parse::().ok() + { + return Ok(false); + } } let Some(report_row) = store - .get( + .record( REPORT_OBJECT_TYPE, &report_object_id(&owner.route, owner.auth_epoch), ) @@ -628,7 +666,10 @@ pub async fn app_endpoint_current( && report.member_id == owner.member_id && report.process_id == owner.process_id && report.auth_epoch == owner.auth_epoch - && report.ready + // Readiness tracks the gateway control session. A previously accepted + // attachment still serves while that session reconnects; only new + // admission needs a currently accepted control session. + && (!require_live_member || report.ready) && report.phase == SandboxInstancePhase::Supervising as i32) } @@ -2832,9 +2873,8 @@ impl SupervisorPool { } } - /// Launch material of the desired instances owned, or about to be taken - /// over, by member processes this replica serves; at most - /// [`LOAD_PER_PASS`] new loads per pass. + /// Retain loaded material for desired generations across host reconnects. + /// Load at most [`LOAD_PER_PASS`] missing assignments for connected hosts. async fn load_materials( &self, owners: &BTreeMap, @@ -2860,7 +2900,7 @@ impl SupervisorPool { let missing = { let mut materials = lock(&self.materials); materials.retain(|route, assignment| { - wanted.get(route).is_some_and(|record| { + desired.get(route).is_some_and(|record| { record.payload.generation == assignment.generation && record.payload.sandbox_id == assignment.sandbox_id && record.payload.prepared == assignment.prepared @@ -2895,7 +2935,10 @@ impl SupervisorPool { } lock(&self.materials) .iter() - .filter(|(route, _)| wanted.contains_key(*route)) + // A disconnected host may reconnect before the next pass. Keep + // its assignments available for that stream's acknowledgement; + // the controller checks the current owning process and term. + .filter(|(route, _)| desired.contains_key(*route)) .map(|(route, assignment)| (route.clone(), assignment.clone())) .collect() } @@ -3554,6 +3597,8 @@ impl InstancePlacement for PoolPlacement { #[cfg(test)] mod tests { + mod reconnect_tests; + use super::*; use crate::auth::sandbox_session::PersistedSandboxIdentity; use crate::persistence::test_postgres::TestSchema; @@ -5890,7 +5935,7 @@ mod tests { } #[tokio::test] - async fn application_endpoints_require_current_acknowledged_owner_and_live_member() { + async fn application_endpoints_distinguish_admission_liveness_from_attachment_ownership() { let fixture = Fixture::new().await; fixture.member("m1", "p1", false).await; let route = fixture.fill("m1", "p1", 1).await.remove(0); @@ -5925,11 +5970,57 @@ mod tests { connected_at_ms: now_ms(), }; fixture.write_report(report.clone()).await; + let mut authority = crate::persistence::object_view::ObjectView::default(); + authority + .synchronize_named( + &fixture.store, + &app_endpoint_authority_names(&endpoint.pool_route, endpoint.ownership_epoch), + ) + .await + .unwrap(); + assert_eq!(authority.records.len(), 3); + assert!( + app_endpoint_attached_from(&authority, &sandbox, &endpoint) + .await + .unwrap() + ); assert!( app_endpoint_current(&fixture.store, &sandbox, &endpoint) .await .unwrap() ); + fixture + .write_report(ReportPayload { + ready: false, + ..report.clone() + }) + .await; + assert!( + app_endpoint_attached_from(fixture.store.as_ref(), &sandbox, &endpoint) + .await + .unwrap(), + "an existing attachment survives control-session reconnection" + ); + assert!( + !app_endpoint_current(&fixture.store, &sandbox, &endpoint) + .await + .unwrap(), + "new admission still needs an accepted control session" + ); + fixture + .write_report(ReportPayload { + phase: SandboxInstancePhase::Stopping as i32, + ready: false, + ..report.clone() + }) + .await; + assert!( + !app_endpoint_attached_from(fixture.store.as_ref(), &sandbox, &endpoint) + .await + .unwrap(), + "an explicit stop still withdraws the attachment" + ); + fixture.write_report(report.clone()).await; endpoint.host = "10.0.0.2".into(); assert!( !app_endpoint_current(&fixture.store, &sandbox, &endpoint) @@ -5943,6 +6034,29 @@ mod tests { .await .unwrap() ); + assert!( + app_endpoint_attached_from(fixture.store.as_ref(), &sandbox, &endpoint) + .await + .unwrap(), + "a leaving member retains its attachment until ownership actually changes" + ); + fixture + .store + .delete(MEMBER_OBJECT_TYPE, &member_object_id("m1")) + .await + .unwrap(); + assert!( + app_endpoint_attached_from(fixture.store.as_ref(), &sandbox, &endpoint) + .await + .unwrap(), + "a missing control heartbeat does not revoke installed routes" + ); + assert!( + !app_endpoint_current(&fixture.store, &sandbox, &endpoint) + .await + .unwrap(), + "new admission still requires a live member" + ); fixture.member("m1", "p1", false).await; // Returning to the same host process is still a new ownership term. grant_next_term(&fixture, &route, "m1", "p1").await; @@ -5955,6 +6069,12 @@ mod tests { .await .unwrap() ); + assert!( + !app_endpoint_attached_from(fixture.store.as_ref(), &sandbox, &endpoint) + .await + .unwrap(), + "an actual ownership epoch change fences the old installation" + ); endpoint.ownership_epoch = 2; assert!( !app_endpoint_current(&fixture.store, &sandbox, &endpoint) @@ -5962,6 +6082,18 @@ mod tests { .unwrap(), "old acknowledged report cannot authorize the new term" ); + authority + .synchronize_named( + &fixture.store, + &app_endpoint_authority_names(&endpoint.pool_route, endpoint.ownership_epoch), + ) + .await + .unwrap(); + assert!( + !app_endpoint_attached_from(&authority, &sandbox, &endpoint) + .await + .unwrap() + ); fixture .write_report(ReportPayload { auth_epoch: 2, @@ -5973,6 +6105,19 @@ mod tests { .await .unwrap() ); + authority + .synchronize_named( + &fixture.store, + &app_endpoint_authority_names(&endpoint.pool_route, endpoint.ownership_epoch), + ) + .await + .unwrap(); + assert_eq!(authority.records.len(), 3); + assert!( + app_endpoint_attached_from(&authority, &sandbox, &endpoint) + .await + .unwrap() + ); fixture.member("m1", "p2", false).await; assert!( !app_endpoint_current(&fixture.store, &sandbox, &endpoint) @@ -5980,6 +6125,11 @@ mod tests { .unwrap() ); fixture.remove_owner_record(&route).await; + assert!( + !app_endpoint_attached_from(fixture.store.as_ref(), &sandbox, &endpoint) + .await + .unwrap() + ); assert!( !app_endpoint_current(&fixture.store, &sandbox, &endpoint) .await diff --git a/crates/openshell-server/src/supervisor_pool/tests/reconnect_tests.rs b/crates/openshell-server/src/supervisor_pool/tests/reconnect_tests.rs new file mode 100644 index 0000000000..6b376b43f0 --- /dev/null +++ b/crates/openshell-server/src/supervisor_pool/tests/reconnect_tests.rs @@ -0,0 +1,234 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +#[derive(Clone)] +struct TestHostService(SupervisorHostController); + +#[tonic::async_trait] +impl openshell_core::proto::supervisor_host::v1::supervisor_host_server::SupervisorHost + for TestHostService +{ + type RegisterSupervisorStream = tokio_stream::Empty< + Result< + openshell_core::proto::supervisor_host::v1::RegisterSupervisorResponse, + tonic::Status, + >, + >; + + async fn register_supervisor( + &self, + _request: tonic::Request< + openshell_core::proto::supervisor_host::v1::RegisterSupervisorRequest, + >, + ) -> Result, tonic::Status> { + Err(tonic::Status::unimplemented( + "registration is not used by the reconnect fixture", + )) + } + + type AttachStream = tokio_stream::wrappers::ReceiverStream< + Result, + >; + async fn attach( + &self, + request: tonic::Request>, + ) -> Result, tonic::Status> { + let identity = openshell_supervisor_control::controller::HostIdentity { + subject: "repro".into(), + token_id: "repro".into(), + expires_at: i64::MAX, + }; + let (_, stream) = self + .0 + .attach(identity, request.into_inner(), |_, _| None) + .await?; + Ok(tonic::Response::new(stream)) + } +} + +use openshell_core::proto::supervisor_host::v1::{ + HostHello, HostMessage, HostStatus, PoolMember, SandboxInstancePhase, SandboxInstanceStatus, + host_gateway_message, host_message, +}; +use openshell_supervisor_control::ObservedInstance; + +async fn connect_host( + url: String, + epoch: u64, +) -> ( + tokio::sync::mpsc::Sender, + tonic::Streaming, +) { + let mut client = openshell_core::proto::supervisor_host::v1::supervisor_host_client::SupervisorHostClient::connect(url).await.unwrap(); + let (tx, rx) = tokio::sync::mpsc::channel(16); + tx.send(HostMessage { + payload: Some(host_message::Payload::Hello(HostHello { + instance_id: "p1".into(), + connection_epoch: epoch, + member: Some(PoolMember { + member_id: "m1".into(), + runtime_address: "10.0.0.1:5500".into(), + }), + accepts_redirect: false, + })), + }) + .await + .unwrap(); + let mut inbound = client + .attach(tokio_stream::wrappers::ReceiverStream::new(rx)) + .await + .unwrap() + .into_inner(); + assert!(matches!( + inbound.message().await.unwrap().unwrap().payload, + Some(host_gateway_message::Payload::Accepted(_)) + )); + (tx, inbound) +} + +async fn ack_snapshot( + controller: &SupervisorHostController, + tx: &tokio::sync::mpsc::Sender, + inbound: &mut tonic::Streaming, + routes: &[String], +) -> (usize, usize) { + let snapshot = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(host_gateway_message::Payload::Assignments(snapshot)) = + inbound.message().await.unwrap().unwrap().payload + { + break snapshot; + } + } + }) + .await + .unwrap(); + tx.send(HostMessage { + payload: Some(host_message::Payload::Status(HostStatus { + applied_revision: snapshot.revision, + instances: routes + .iter() + .enumerate() + .map(|(i, route)| SandboxInstanceStatus { + route: route.clone(), + sandbox_id: format!("sandbox-repro-{i}"), + phase: SandboxInstancePhase::Supervising as i32, + ready: true, + ..Default::default() + }) + .collect(), + ..Default::default() + })), + }) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while controller.member_reports().len() != snapshot.instances.len() { + tokio::task::yield_now().await; + } + }) + .await + .expect("the host's snapshot acknowledgement must arrive"); + (snapshot.instances.len(), snapshot.keep_routes.len()) +} + +#[tokio::test] +async fn same_process_reconnect_replays_all_cached_assignments() { + let fixture = Fixture::new().await; + fixture.member("m1", "p1", false).await; + let pool = fixture.replica("gw-a"); + let mut routes = Vec::new(); + for i in 0..=LOAD_PER_PASS { + let route = format!("rt-repro-{i:05}"); + let sandbox = format!("sandbox-repro-{i}"); + fixture + .sandbox(&sandbox, "generation-1", SandboxPhase::Ready) + .await; + let a = assignment(&route, &sandbox, "generation-1"); + pool.record_assignment(&a).await.unwrap(); + fixture.own(&route, &sandbox, "m1", "p1").await; + lock(&pool.materials).insert(route.clone(), a); + routes.push(route); + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let service=openshell_core::proto::supervisor_host::v1::supervisor_host_server::SupervisorHostServer::new(TestHostService(pool.controller.clone())); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(service) + .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)), + ); + let url = format!("http://{address}"); + let (tx, mut inbound) = connect_host(url.clone(), 1).await; + pool.reconcile_once().await.unwrap(); + assert_eq!( + ack_snapshot(&pool.controller, &tx, &mut inbound, &routes).await, + (LOAD_PER_PASS + 1, 0) + ); + assert!(matches!( + pool.controller.observed(routes.last().unwrap()), + ObservedInstance::Reported(_) + )); + drop(tx); + drop(inbound); + tokio::time::timeout(Duration::from_secs(2), async { + while !pool.controller.connected_members().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + pool.reconcile_once().await.unwrap(); + assert_eq!(lock(&pool.materials).len(), LOAD_PER_PASS + 1); + let (tx, mut inbound) = connect_host(url, 2).await; + assert!(routes.iter().all(|route| !matches!( + pool.controller.observed(route), + ObservedInstance::Reported(_) + ))); + assert_eq!( + ack_snapshot(&pool.controller, &tx, &mut inbound, &routes).await, + (LOAD_PER_PASS + 1, 0) + ); + assert!( + routes + .iter() + .all(|r| matches!(pool.controller.observed(r), ObservedInstance::Reported(_))) + ); + assert!( + routes + .iter() + .all(|r| pool.controller.pool_view().unwrap().owners[r].auth_epoch == 1) + ); + server.abort(); +} + +#[tokio::test] +async fn cached_material_is_removed_for_withdrawn_or_replaced_generations() { + let fixture = Fixture::new().await; + fixture.member("m1", "p1", false).await; + fixture + .sandbox("sandbox-repro", "generation-1", SandboxPhase::Ready) + .await; + let route = "rt-repro-01234567"; + fixture + .publish(route, "sandbox-repro", "generation-1") + .await; + fixture.own(route, "sandbox-repro", "m1", "p1").await; + let pool = fixture.replica("gw-a"); + let owners = pool.owners().await.unwrap(); + let mut desired = pool.all_assignments().await.unwrap(); + let original = assignment(route, "sandbox-repro", "generation-1"); + lock(&pool.materials).insert(route.into(), original.clone()); + desired.get_mut(route).unwrap().payload.generation = "generation-2".into(); + assert!(pool.load_materials(&owners, &desired).await.is_empty()); + assert!(lock(&pool.materials).is_empty()); + lock(&pool.materials).insert(route.into(), original); + assert!( + pool.load_materials(&owners, &BTreeMap::new()) + .await + .is_empty() + ); + assert!(lock(&pool.materials).is_empty()); +} diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index f9f46b153b..a13532cc23 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -2966,9 +2966,7 @@ async fn run_session_loop( let bootstrap_timeout = tokio::time::sleep(Duration::from_mins(2)); tokio::pin!(bootstrap_timeout); let mut bootstrap_complete = !session.pushes_config; - let mut app_timer = tokio::time::interval(crate::grpc::service_advertisement::REPORT_INTERVAL); - app_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let mut app_lease = crate::grpc::service_advertisement::LeaseWindow::default(); + let mut last_installation: Option = None; loop { tokio::select! { @@ -3004,9 +3002,33 @@ async fn run_session_loop( bootstrap_complete = true; } if let Some(supervisor_message::Payload::ServiceAdvertisement(report)) = &msg.payload { - if let Some(lease) = app_lease.claim(report.lease_sequence) - && !matches!(tokio::time::timeout(Duration::from_secs(2), crate::grpc::service_advertisement::accept_lease(state, owner_guard, report, lease)).await, Ok(Ok(()))) { - debug!(sandbox_id, "service installation report rejected or unavailable"); + if !session.advertises_services { + continue; + } + let accepted = if last_installation.as_ref() == Some(report) { + true + } else { + match tokio::time::timeout(Duration::from_secs(2), + crate::grpc::service_advertisement::accept(state, owner_guard, report)).await { + Ok(Ok(())) => { + last_installation = Some(report.clone()); + true + } + Ok(Err(error)) => { + debug!(sandbox_id, sequence = report.lease_sequence, %error, "service installation report rejected"); + false + } + Err(_) => { + debug!(sandbox_id, sequence = report.lease_sequence, "service installation acceptance timed out; supervisor will retry"); + false + } + } + }; + if accepted { + let ack = GatewayMessage { payload: Some(gateway_message::Payload::ServiceAdvertisementAck( + openshell_core::proto::ServiceAdvertisementAck { sequence: report.lease_sequence } + )) }; + if tx.try_send(ack).is_err() { break; } } continue; } @@ -3040,14 +3062,6 @@ async fn run_session_loop( } } } - _ = app_timer.tick(), if session.advertises_services => { - let Ok(Ok(Some(authority))) = tokio::time::timeout(Duration::from_secs(2), - crate::grpc::service_advertisement::prepare_lease(state, owner_guard)).await - else { continue; }; - let Some(lease) = app_lease.issue(authority) else { break; }; - let message = GatewayMessage { payload: Some(gateway_message::Payload::ServiceRouteLease(lease)) }; - if tx.try_send(message).is_err() { break; } - } _ = heartbeat_timer.tick() => { let hb = GatewayMessage { payload: Some(gateway_message::Payload::Heartbeat( diff --git a/crates/openshell-supervisor-process/src/supervisor_session.rs b/crates/openshell-supervisor-process/src/supervisor_session.rs index bffe40fb8d..160ea5fff7 100644 --- a/crates/openshell-supervisor-process/src/supervisor_session.rs +++ b/crates/openshell-supervisor-process/src/supervisor_session.rs @@ -460,24 +460,49 @@ struct SessionConfig { ready_tx: watch::Sender, } -fn service_route_lease_remaining( - lease: &openshell_core::proto::ServiceRouteLease, -) -> Option { - let duration = lease - .duration - .as_ref() - .and_then(|d| openshell_core::time::duration_to_std(d).ok())?; - if duration.is_zero() || duration > Duration::from_secs(15) { - return None; +/// Only unacknowledged installation snapshots are retried. An acknowledged +/// snapshot remains valid until attachment or configuration changes. +struct InstallationReports { + source: openshell_core::app_listener::InstallationSource, + last_snapshot: Option, + pending: Option, + sequence: u64, +} + +impl InstallationReports { + fn new(source: openshell_core::app_listener::InstallationSource) -> Self { + Self { + source, + last_snapshot: None, + pending: None, + sequence: 0, + } + } + + fn refresh(&mut self) -> Result<(), &'static str> { + let snapshot = self.source.snapshot(); + if self.last_snapshot.as_ref() != Some(&snapshot) { + self.sequence = self + .sequence + .checked_add(1) + .ok_or("installation sequence exhausted")?; + let mut report = snapshot.clone(); + report.lease_sequence = self.sequence; + self.pending = Some(report); + self.last_snapshot = Some(snapshot); + } + Ok(()) + } + + fn acknowledge(&mut self, sequence: u64) { + if self + .pending + .as_ref() + .is_some_and(|report| report.lease_sequence == sequence) + { + self.pending = None; + } } - let expiry = lease - .expires_at - .as_ref() - .and_then(|t| openshell_core::time::timestamp_to_millis(t).ok())?; - let remaining = expiry.checked_sub(openshell_core::time::now_ms())?; - let remaining = Duration::from_millis(u64::try_from(remaining).ok()?); - let duration = duration.min(remaining); - (!duration.is_zero() && duration <= Duration::from_secs(15)).then_some(duration) } async fn run_session_loop(config: SessionConfig) { @@ -816,6 +841,15 @@ async fn run_single_session( let mut heartbeat_interval = tokio::time::interval(Duration::from_secs(heartbeat_secs)); heartbeat_interval.tick().await; // skip immediate tick let mut home = config.gateway_home.clone(); + let mut installations = config + .app_installations + .clone() + .map(InstallationReports::new); + if let Some(reports) = installations.as_mut() { + reports.refresh()?; + } + let mut installation_retry = tokio::time::interval(Duration::from_secs(2)); + installation_retry.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { tokio::select! { @@ -842,15 +876,9 @@ async fn run_single_session( owner_replica_id: r.owner_replica_id.clone(), }); } - if let Some(gateway_message::Payload::ServiceRouteLease(lease)) = &msg.payload { - if let Some(source) = &config.app_installations { - let duration = service_route_lease_remaining(lease); - if let Some(duration) = duration.filter(|d| !d.is_zero() && *d <= Duration::from_secs(15)) { - let mut report = source(duration); - report.lease_sequence = lease.sequence; - tx.send(SupervisorMessage { payload: Some(supervisor_message::Payload::ServiceAdvertisement(report)) }) - .await.map_err(|_| "outbound channel closed")?; - } + if let Some(gateway_message::Payload::ServiceAdvertisementAck(ack)) = &msg.payload { + if let Some(reports) = installations.as_mut() { + reports.acknowledge(ack.sequence); } continue; } @@ -866,6 +894,30 @@ async fn run_single_session( }; handle_gateway_message(&msg, &context); } + changed = async { + match installations.as_mut() { + Some(reports) => reports.source.changed().await, + None => std::future::pending().await, + } + } => { + if changed.is_err() { + installations = None; + continue; + } + if let Some(reports) = installations.as_mut() { + reports.refresh()?; + } + if let Some(report) = installations.as_ref().and_then(|r| r.pending.clone()) { + tx.send(SupervisorMessage { payload: Some(supervisor_message::Payload::ServiceAdvertisement(report)) }) + .await.map_err(|_| "outbound channel closed")?; + } + } + _ = installation_retry.tick(), if installations.as_ref().is_some_and(|r| r.pending.is_some()) => { + if let Some(report) = installations.as_ref().and_then(|r| r.pending.clone()) { + tx.send(SupervisorMessage { payload: Some(supervisor_message::Payload::ServiceAdvertisement(report)) }) + .await.map_err(|_| "outbound channel closed")?; + } + } _ = heartbeat_interval.tick() => { let hb = SupervisorMessage { payload: Some(supervisor_message::Payload::Heartbeat( @@ -2098,25 +2150,43 @@ mod ocsf_event_tests { } #[cfg(test)] -mod app_lease_tests { +mod installation_report_tests { use super::*; #[test] - fn queued_or_expired_challenges_never_get_a_new_full_lease() { - let mut lease = openshell_core::proto::ServiceRouteLease { - sequence: 1, - duration: openshell_core::time::duration_from_std(Duration::from_secs(15)).ok(), - expires_at: openshell_core::time::timestamp_from_millis( - openshell_core::time::now_ms() + 1000, - ) - .ok(), - }; - let remaining = service_route_lease_remaining(&lease).unwrap(); - assert!(remaining <= Duration::from_secs(1)); - lease.expires_at = - openshell_core::time::timestamp_from_millis(openshell_core::time::now_ms() - 1).ok(); - assert!(service_route_lease_remaining(&lease).is_none()); - lease.expires_at = None; - assert!(service_route_lease_remaining(&lease).is_none()); + fn acknowledgement_stops_retries_and_cannot_acknowledge_a_newer_snapshot() { + let snapshot = Arc::new(std::sync::Mutex::new( + openshell_core::proto::SupervisorServiceAdvertisement::default(), + )); + let view = snapshot.clone(); + let (_updates, changes) = watch::channel(()); + let source = openshell_core::app_listener::InstallationSource::new( + Arc::new(move || view.lock().unwrap().clone()), + changes, + ); + let mut reports = InstallationReports::new(source.clone()); + reports.refresh().unwrap(); + assert_eq!(reports.pending.as_ref().unwrap().lease_sequence, 1); + reports.refresh().unwrap(); + assert_eq!(reports.sequence, 1); + reports.acknowledge(1); + assert!(reports.pending.is_none()); + reports.refresh().unwrap(); + assert!( + reports.pending.is_none(), + "unchanged snapshots need no renewal" + ); + snapshot.lock().unwrap().config_revision = 2; + reports.refresh().unwrap(); + reports.acknowledge(1); + assert_eq!(reports.pending.as_ref().unwrap().lease_sequence, 2); + reports.acknowledge(2); + assert!(reports.pending.is_none()); + let mut reconnected = InstallationReports::new(source); + reconnected.refresh().unwrap(); + assert!( + reconnected.pending.is_some(), + "a new session resynchronizes the attachment" + ); } } diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index 0aae46b8ca..16dca9d7f8 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -289,13 +289,15 @@ policy state, limits, and OCSF context. Stopping an instance unregisters only it routes and closes its streams; it does not stop another instance's ingress. Gateway configuration snapshots carry the declared-service allowlist. Successful -poll and push application installs that allowlist; rejected configuration -suspends it. Polling renews a 30-second freshness lease. In push mode, an accepted -live supervisor session renews already installed, unexpired routes even when no -configuration changes. Rejection or a lease lapse cannot revive an old stream. -With the listener enabled, both polling and push maintenance cap their sleep at -five seconds, even if the configured polling interval is longer. Failed polls -do not renew routes. Ending the configuration loop suspends routes. +poll and push application installs it; rejected configuration suspends it. Routes +remain installed while the sandbox attachment is owned, including during gateway +or configuration-channel outages. Polling keeps its configured interval. A route +edit, explicit stop/detach or ownership fence revokes affected streams; reconnect +alone does not. A missed control-plane revocation takes effect when the supervisor +receives the current configuration again. +Initial gateway connection failures retry with backoff capped at four seconds, +retaining the configuration-update receiver while the gateway recovers. Each +connection attempt is bounded to ten seconds; terminal gRPC errors are returned. Rejected route installations emit an OCSF configuration-change failure with the reason, configuration revision, and sandbox/workspace identity when available. @@ -312,6 +314,13 @@ instance's configuration from process environment. TLS configuration uses `openshell-crypto`; certificates are read at process startup. Restart the supervisor to reload application certificates. +`OPENSHELL_APP_MAX_CONNECTIONS` bounds accepted connections for the process +listener (default 1024). `OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX` bounds each +sandbox's connections and backend relays (default 64). Both must be positive, +and the per-sandbox limit cannot exceed the process limit. The gateway's +`supervisor.app_listener` configuration and Kubernetes Helm templates propagate +these budgets; increase supervisor resources before raising them. + This path uses application or trusted-edge authentication independently from gateway authentication. It validates Host against SNI, preserves public Host/Origin and application cookies, strips gateway/edge identity material, and @@ -327,26 +336,19 @@ are not migrated. Runtime ownership fencing must reject stale connectors. ### Installed-route evidence -An enabled listener offers an installation view to the existing authenticated -sandbox supervisor session. The gateway issues a single-use lease challenge -every five seconds. The instance reports the complete installed allowlist only -when its remaining serving freshness covers the challenge's fifteen-second -lease. Expiry starts at gateway challenge issuance, so transport delay cannot -extend publication past confirmed listener freshness. Empty reports withdraw -installation evidence; suspended, expired, stopped, or not-yet-serving instances -cannot report live routes. +An enabled listener exposes its current installed allowlist and change +notifications to the authenticated sandbox session. The session reports on changes +and reconnects, and retries until the gateway acknowledges acceptance. Suspended, +stopped or not-yet-serving instances report no active routes. An acknowledgement +has no serving-expiry deadline; quiet sessions do not generate route renewals. Reports contain declaration identities/revisions and configuration identity, -not backend addresses. The gateway obtains endpoints from the compute driver -and validates runtime identity, declarations, and session ownership before -persisting ephemeral records. Shared Kubernetes pools resolve the acknowledged -owner's Pod IP and app port. Durable pool ownership, credential epoch, membership, -and acknowledged reports fence installation acceptance and discovery. Shared -listeners additionally require a gateway-issued serving lease, capped at fifteen -seconds from issuance, independently of configuration freshness. Expiry closes -streams; later renewal cannot revive them. Takeover preserves the workload and -public hostname while replacing the app endpoint. Clients reconnect after an -interruption; sockets are not migrated. +not backend addresses. The gateway resolves trusted endpoints through the compute +driver and checks attachment authority before storing a snapshot. Shared pools +publish the acknowledged owner's Pod IP and app port. Ownership epochs fence a +superseded attachment at the Sandbox Protocol boundary: confirming a takeover +closes the previous owner's connections. Takeover preserves the workload and +public hostname while replacing the endpoint; sockets are not migrated. The gateway supplies a canonical `application_hostname` with each installed service route. The listener dispatches exact hashed or readable SNI names to diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index 009edaa8a3..b21e678492 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -29,13 +29,13 @@ use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject}; use std::sync::Mutex; use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore, mpsc, watch}; use tokio::task::JoinSet; -use tokio::time::Instant; use tokio_rustls::TlsAcceptor; -const FRESHNESS: Duration = Duration::from_secs(30); const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); -const MAX_INSTANCE_CONNECTIONS: usize = 64; +#[cfg(test)] +const MAX_INSTANCE_CONNECTIONS: usize = + openshell_core::app_listener::DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX; const MAX_HTTP2_STREAMS: u32 = 16; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -81,6 +81,22 @@ pub struct Config { domain: String, certificate: PathBuf, key: PathBuf, + limits: ConnectionLimits, +} + +#[derive(Clone, Copy)] +struct ConnectionLimits { + total: usize, + per_sandbox: usize, +} + +impl Default for ConnectionLimits { + fn default() -> Self { + Self { + total: openshell_core::app_listener::DEFAULT_APP_MAX_CONNECTIONS, + per_sandbox: openshell_core::app_listener::DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX, + } + } } impl Config { @@ -110,10 +126,25 @@ impl Config { )); }; let address: SocketAddr = address.parse().into_diagnostic()?; + let limit = |name: &str, default: usize| -> Result { + read(name).map_or(Ok(default), |value| { + value + .parse() + .map_err(|_| miette::miette!("{name} must be a positive integer")) + }) + }; let listener = openshell_core::app_listener::AppListenerConfig { enabled: true, port: address.port(), base_url: Some(base_url), + max_connections: limit( + "OPENSHELL_APP_MAX_CONNECTIONS", + ConnectionLimits::default().total, + )?, + max_connections_per_sandbox: limit( + "OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", + ConnectionLimits::default().per_sandbox, + )?, }; listener .validate() @@ -124,6 +155,10 @@ impl Config { domain, certificate: certificate.into(), key: key.into(), + limits: ConnectionLimits { + total: listener.max_connections, + per_sandbox: listener.max_connections_per_sandbox, + }, })) } @@ -146,6 +181,7 @@ impl Config { listener, acceptor: TlsAcceptor::from(Arc::new(tls)), domain: self.domain, + limits: self.limits, }) } } @@ -155,8 +191,7 @@ struct Snapshot { routes: BTreeMap, generations: BTreeMap, next_generation: u64, - expires: Option, - authority_expires: Option, + installed: bool, workspace: String, configuration_instance_id: String, config_revision: u64, @@ -169,8 +204,7 @@ impl Snapshot { fn suspend(&mut self) { self.routes.clear(); self.generations.clear(); - self.expires = None; - self.authority_expires = None; + self.installed = false; self.epoch = self.epoch.wrapping_add(1); } } @@ -181,13 +215,13 @@ struct RouteToken { generation: u64, } -/// Shared by policy reconciliation and ingress. Only accepted configuration -/// refreshes this lease; route changes cannot restart or replace the workload. +/// Installed allowlist for one attachment. Control-plane disconnection does not +/// revoke it; route changes cannot restart or replace the workload. #[derive(Clone)] pub struct Routes { registration: Option>, - requires_authority: bool, sender: watch::Sender, + installation_updates: watch::Sender<()>, stopped: Arc, serving: Arc, #[cfg(test)] @@ -204,82 +238,49 @@ impl Default for Routes { fn default() -> Self { Self { sender: watch::channel(Snapshot::default()).0, + installation_updates: watch::channel(()).0, stopped: Arc::new(AtomicBool::new(false)), serving: Arc::new(AtomicBool::new(false)), registration: None, #[cfg(test)] install_probe: None, - requires_authority: false, } } } -pub(crate) struct ConfigurationGuard(Routes); -impl Drop for ConfigurationGuard { - fn drop(&mut self) { - self.0.suspend(); - } -} - impl Routes { pub(crate) fn installation_source(&self) -> openshell_core::app_listener::InstallationSource { let routes = self.clone(); - Arc::new(move |duration| { - let snapshot = routes.sender.borrow(); - if routes.stopped.load(Ordering::Acquire) - || !routes.serving.load(Ordering::Acquire) - || snapshot.expires.is_none_or(|expiry| { - expiry.saturating_duration_since(Instant::now()) < duration - }) - { - return openshell_core::proto::SupervisorServiceAdvertisement::default(); - } - drop(snapshot); - if routes.requires_authority { - routes.sender.send_modify(|snapshot| { - if snapshot - .authority_expires - .is_none_or(|expiry| expiry <= Instant::now()) - { - // A later lease cannot revive a stream that already lost authority. - snapshot.epoch = snapshot.epoch.wrapping_add(1); - } - snapshot.authority_expires = Some(Instant::now() + duration); - }); - } - let snapshot = routes.sender.borrow(); - openshell_core::proto::SupervisorServiceAdvertisement { - service_domain: routes - .registration - .as_ref() - .map_or_else(String::new, |registration| { - registration.router.domain.clone() - }), - configuration_instance_id: snapshot.configuration_instance_id.clone(), - config_revision: snapshot.config_revision, - routes: snapshot.routes.values().cloned().collect(), - ..Default::default() - } - }) - } - - pub(crate) fn configuration_guard(self) -> ConfigurationGuard { - ConfigurationGuard(self) - } - - fn serving_expiry(&self, snapshot: &Snapshot) -> Option { - let config = snapshot.expires?; - if self.requires_authority { - Some(config.min(snapshot.authority_expires?)) - } else { - Some(config) - } + openshell_core::app_listener::InstallationSource::new( + Arc::new(move || { + let snapshot = routes.sender.borrow(); + if routes.stopped.load(Ordering::Acquire) + || !routes.serving.load(Ordering::Acquire) + || !snapshot.installed + { + return openshell_core::proto::SupervisorServiceAdvertisement::default(); + } + openshell_core::proto::SupervisorServiceAdvertisement { + service_domain: routes + .registration + .as_ref() + .map_or_else(String::new, |registration| { + registration.router.domain.clone() + }), + configuration_instance_id: snapshot.configuration_instance_id.clone(), + config_revision: snapshot.config_revision, + routes: snapshot.routes.values().cloned().collect(), + ..Default::default() + } + }), + self.installation_updates.subscribe(), + ) } fn valid(&self, route: &SandboxServiceRoute, token: RouteToken) -> bool { let snapshot = self.sender.borrow(); - self.serving_expiry(&snapshot) - .is_some_and(|expiry| expiry > Instant::now()) + !self.stopped.load(Ordering::Acquire) + && snapshot.installed && snapshot.epoch == token.epoch && snapshot.generations.get(&route.name) == Some(&token.generation) && snapshot.routes.get(&route.name) == Some(route) @@ -336,14 +337,15 @@ impl Routes { let snapshot = self.sender.borrow(); snapshot.routes != routes || snapshot.rejection.is_some() }; + let advertisement_changed = { + let snapshot = self.sender.borrow(); + changed + || !snapshot.installed + || snapshot.workspace != result.workspace + || snapshot.configuration_instance_id != result.configuration_instance_id + || snapshot.config_revision != result.config_revision + }; self.sender.send_modify(|snapshot| { - // Renewal after a lapse cannot revive a connection whose lease expired. - if snapshot - .expires - .is_some_and(|expiry| expiry <= Instant::now()) - { - snapshot.epoch = snapshot.epoch.wrapping_add(1); - } let generations = routes .iter() .map(|(name, route)| { @@ -371,8 +373,11 @@ impl Routes { snapshot.rejection = None; snapshot.routes = routes; snapshot.generations = generations; - snapshot.expires = Some(Instant::now() + FRESHNESS); + snapshot.installed = true; }); + if advertisement_changed { + self.installation_updates.send_replace(()); + } if changed { ocsf_emit!( ConfigStateChangeBuilder::new(crate::ocsf_ctx()) @@ -401,6 +406,7 @@ impl Routes { changed = true; } }); + self.installation_updates.send_replace(()); if changed { let mut event = ConfigStateChangeBuilder::new(crate::ocsf_ctx()) .severity(SeverityId::Low) @@ -423,24 +429,9 @@ impl Routes { } } - /// Renew only already installed routes while a live push session supplies - /// freshness. A rejected configuration is suspended and cannot be revived. - pub(crate) fn renew(&self) { - if self.stopped.load(Ordering::Acquire) { - return; - } - self.sender.send_modify(|snapshot| { - if snapshot - .expires - .is_some_and(|expiry| expiry > Instant::now()) - { - snapshot.expires = Some(Instant::now() + FRESHNESS); - } - }); - } - pub(crate) fn suspend(&self) { self.sender.send_modify(Snapshot::suspend); + self.installation_updates.send_replace(()); } fn resolve( @@ -451,7 +442,7 @@ impl Routes { ) -> Option<(SandboxServiceRoute, RouteToken)> { let encoded = sni.strip_suffix(&format!(".{domain}"))?; let snapshot = self.sender.borrow(); - if self.serving_expiry(&snapshot)? <= Instant::now() { + if self.stopped.load(Ordering::Acquire) || !snapshot.installed { return None; } let service = if let Some(route) = snapshot.routes.values().find(|route| { @@ -475,26 +466,9 @@ impl Routes { async fn revoked(&self, route: &SandboxServiceRoute, token: RouteToken) { let mut receiver = self.sender.subscribe(); loop { - let expiry = { - let snapshot = receiver.borrow_and_update(); - if snapshot.epoch != token.epoch - || snapshot.generations.get(&route.name) != Some(&token.generation) - || snapshot.routes.get(&route.name) != Some(route) - { - return; - } - let Some(expiry) = self.serving_expiry(&snapshot) else { - return; - }; - expiry - }; - tokio::select! { - () = tokio::time::sleep_until(expiry) => { - // A renewal and the old timer can both become ready before - // this task is polled. Check the current lease before closing. - if !self.valid(route, token) { return; } - }, - result = receiver.changed() => if result.is_err() { return; }, + drop(receiver.borrow_and_update()); + if !self.valid(route, token) || receiver.changed().await.is_err() { + return; } } } @@ -504,6 +478,7 @@ pub struct BoundListener { listener: tokio::net::TcpListener, acceptor: TlsAcceptor, domain: String, + limits: ConnectionLimits, } /// Host-level dispatcher. It never shares a sandbox connector or policy @@ -511,7 +486,7 @@ pub struct BoundListener { #[derive(Clone, Default)] pub struct Router { domain: String, - requires_authority: bool, + limits: ConnectionLimits, registrations: Arc>>>, } @@ -640,14 +615,6 @@ impl HostHandle { pub fn router(&self) -> Router { self.router.clone() } - - /// Shared members require short gateway-issued ownership leases as well as - /// accepted configuration; configuration renewal alone cannot extend service. - pub(crate) fn leased_router(&self) -> Router { - let mut router = self.router.clone(); - router.requires_authority = true; - router - } } impl Drop for HostHandle { @@ -660,6 +627,7 @@ pub struct InstanceListener { pub(crate) routes: Routes, receiver: mpsc::Receiver, domain: String, + limits: ConnectionLimits, } pub struct Handle { @@ -685,7 +653,7 @@ impl Router { "app listener requires a canonical sandbox name" )); } - let (sender, receiver) = mpsc::channel(16); + let (sender, receiver) = mpsc::channel(self.limits.per_sandbox); let registration = Arc::new(Registration { router: self.clone(), sandbox: sandbox.to_string(), @@ -696,11 +664,11 @@ impl Router { Ok(InstanceListener { routes: Routes { registration: Some(registration), - requires_authority: self.requires_authority, ..Default::default() }, receiver, domain: self.domain.clone(), + limits: self.limits, }) } } @@ -710,11 +678,12 @@ impl BoundListener { pub fn start(self) -> HostHandle { let router = Router { domain: self.domain.clone(), + limits: self.limits, ..Default::default() }; let dispatch = router.clone(); let task = tokio::spawn(async move { - let permits = Arc::new(Semaphore::new(1024)); + let permits = Arc::new(Semaphore::new(self.limits.total)); let mut connections = JoinSet::new(); loop { tokio::select! { @@ -760,12 +729,13 @@ impl InstanceListener { /// identity even when multiple sandboxes share one listener process. pub(crate) fn start(mut self, connector: Arc) -> Handle { self.routes.serving.store(true, Ordering::Release); + self.routes.installation_updates.send_replace(()); let retained_routes = self.routes.clone(); let task = tokio::spawn(async move { let routes = self.routes.clone(); - let permits = Arc::new(Semaphore::new(MAX_INSTANCE_CONNECTIONS)); + let permits = Arc::new(Semaphore::new(self.limits.per_sandbox)); // Multiplexed requests share the previous per-instance relay budget. - let relays = Arc::new(Semaphore::new(MAX_INSTANCE_CONNECTIONS)); + let relays = Arc::new(Semaphore::new(self.limits.per_sandbox)); let mut connections = JoinSet::new(); ocsf_emit!( AppLifecycleBuilder::new(crate::ocsf_ctx()) @@ -784,7 +754,7 @@ impl InstanceListener { let Some(sni) = tls.get_ref().1.server_name().map(str::to_ascii_lowercase) else { continue; }; let prefix = routes.registration.as_ref().expect("instance registration").prefix.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); let Some((route, token)) = routes.resolve(&sni, &prefix, &self.domain) else { - emit_denial("App listener unknown or expired SNI route"); continue; + emit_denial("App listener unknown SNI route"); continue; }; let routes = routes.clone(); let connector = connector.clone(); @@ -1233,134 +1203,63 @@ mod tests { use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; use tokio_tungstenite::tungstenite::client::IntoClientRequest as _; - #[test] - fn installation_evidence_requires_a_serving_instance_and_sufficient_freshness() { + #[tokio::test] + async fn installation_snapshots_follow_the_running_attachment() { let routes = Routes::default(); - let source = routes.installation_source(); + let mut source = routes.installation_source(); let route = SandboxServiceRoute { - endpoint_id: "endpoint".into(), + endpoint_id: "ep".into(), name: "web".into(), target_port: 8080, - authorization_mode: 1, resource_version: 1, - application_hostname: String::new(), - backend_http_version: 0, + ..Default::default() }; - let mut config = installed(vec![route.clone()]); - config.config_revision = 42; - config.configuration_instance_id = "generation-a".into(); + let config = installed(vec![route.clone()]); routes.install(&config); - assert!(source(Duration::from_secs(15)).routes.is_empty()); + assert!( + source.snapshot().routes.is_empty(), + "not serving before attachment start" + ); routes.serving.store(true, Ordering::Release); - let report = source(Duration::from_secs(15)); - assert_eq!(report.routes, vec![route]); - assert_eq!(report.config_revision, 42); - assert_eq!(report.configuration_instance_id, "generation-a"); - routes.sender.send_modify(|snapshot| { - snapshot.expires = Some(Instant::now() + Duration::from_secs(5)); - }); - assert!(source(Duration::from_secs(15)).routes.is_empty()); - routes.renew(); - assert!(!source(Duration::from_secs(15)).routes.is_empty()); + routes.installation_updates.send_replace(()); + source.changed().await.unwrap(); + assert_eq!(source.snapshot().routes, vec![route]); + routes.stopped.store(true, Ordering::Release); routes.suspend(); - routes.renew(); - assert!(source(Duration::from_secs(15)).routes.is_empty()); + source.changed().await.unwrap(); + assert!(source.snapshot().routes.is_empty()); routes.install(&config); - routes.stopped.store(true, Ordering::Release); - assert!(source(Duration::from_secs(15)).routes.is_empty()); - } - - #[tokio::test(start_paused = true)] - async fn queued_authority_renewal_preserves_stream_until_current_expiry() { - // Exercise selection with both the old timer and renewal notification - // ready, without letting the stream task observe the renewal early. - for _ in 0..64 { - let routes = Routes { - requires_authority: true, - ..Default::default() - }; - routes.serving.store(true, Ordering::Release); - let route = SandboxServiceRoute { - endpoint_id: "endpoint".into(), - name: "web".into(), - target_port: 8080, - authorization_mode: 1, - resource_version: 1, - application_hostname: String::new(), - backend_http_version: 0, - }; - routes.install(&installed(vec![route.clone()])); - let source = routes.installation_source(); - source(Duration::from_secs(15)); - let (_, token) = routes - .resolve(HOST, "default--sandbox-a", "svc.openshell.internal") - .unwrap(); - let revoked = routes.revoked(&route, token); - tokio::pin!(revoked); - assert!(futures::poll!(&mut revoked).is_pending()); - tokio::time::advance(Duration::from_secs(10)).await; - source(Duration::from_secs(15)); - tokio::time::advance(Duration::from_secs(6)).await; - assert!(routes.valid(&route, token)); - assert!(futures::poll!(&mut revoked).is_pending()); - tokio::time::advance(Duration::from_secs(10)).await; - assert!(!routes.valid(&route, token)); - assert!(futures::poll!(&mut revoked).is_ready()); - } + assert!( + source.snapshot().routes.is_empty(), + "a stopped attachment cannot revive" + ); } #[tokio::test(start_paused = true)] - async fn shared_authority_expires_despite_config_renewal_and_fences_old_streams() { - let routes = Routes { - requires_authority: true, - ..Default::default() - }; - routes.serving.store(true, Ordering::Release); + async fn a_control_outage_does_not_expire_routes_or_revoke_current_streams() { + let routes = Routes::default(); let route = SandboxServiceRoute { - endpoint_id: "endpoint".into(), + endpoint_id: "ep".into(), name: "web".into(), target_port: 8080, - authorization_mode: 1, resource_version: 1, - application_hostname: String::new(), - backend_http_version: 0, + ..Default::default() }; routes.install(&installed(vec![route.clone()])); - assert!( - routes - .resolve(HOST, "default--sandbox-a", "svc.openshell.internal") - .is_none() - ); - let source = routes.installation_source(); - assert_eq!(source(Duration::from_secs(15)).routes, vec![route.clone()]); let (_, token) = routes .resolve(HOST, "default--sandbox-a", "svc.openshell.internal") .unwrap(); - tokio::time::advance(Duration::from_secs(10)).await; - routes.renew(); + tokio::time::advance(Duration::from_mins(5)).await; assert!(routes.valid(&route, token)); - tokio::time::advance(Duration::from_secs(6)).await; - assert!(!routes.valid(&route, token)); assert!( - routes - .resolve(HOST, "default--sandbox-a", "svc.openshell.internal") - .is_none() + tokio::time::timeout(Duration::from_millis(1), routes.revoked(&route, token)) + .await + .is_err() ); + routes.install(&installed(Vec::new())); tokio::time::timeout(Duration::from_secs(1), routes.revoked(&route, token)) .await .unwrap(); - source(Duration::from_secs(15)); - assert!( - !routes.valid(&route, token), - "renewal cannot revive a prior stream" - ); - assert!( - routes - .resolve(HOST, "default--sandbox-a", "svc.openshell.internal") - .is_some() - ); - routes.suspend(); - assert!(source(Duration::from_secs(15)).routes.is_empty()); } #[test] @@ -1392,6 +1291,20 @@ mod tests { .unwrap(); assert_eq!(configured.address.port(), 9443); assert_eq!(configured.domain, "services.example.com"); + assert_eq!(configured.limits.total, 1024); + assert_eq!(configured.limits.per_sandbox, 64); + values.insert("OPENSHELL_APP_MAX_CONNECTIONS", "16384"); + values.insert("OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", "256"); + let configured = Config::from_values(|name| values.get(name).map(ToString::to_string)) + .unwrap() + .unwrap(); + assert_eq!(configured.limits.total, 16384); + assert_eq!(configured.limits.per_sandbox, 256); + for invalid in ["0", "-1", "invalid", "20000"] { + values.insert("OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", invalid); + assert!(Config::from_values(|name| values.get(name).map(ToString::to_string)).is_err()); + } + values.insert("OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", "256"); values.remove("OPENSHELL_APP_TLS_KEY"); assert!(Config::from_values(|name| values.get(name).map(ToString::to_string)).is_err()); assert!( @@ -1516,7 +1429,7 @@ mod tests { assert!(!event.to_string().contains("unvalidated-error-details")); let snapshot = instance.routes.sender.borrow(); assert!(snapshot.routes.is_empty()); - assert!(snapshot.expires.is_none()); + assert!(!snapshot.installed); drop(snapshot); if reason == InstallRejection::HostnameInUse { assert!( @@ -1703,6 +1616,7 @@ mod tests { domain: "svc.openshell.internal".into(), certificate: cert_path, key: key_path, + limits: ConnectionLimits::default(), }; let bound = config.bind().unwrap(); let address = bound.listener.local_addr().unwrap(); @@ -2077,7 +1991,7 @@ mod tests { } #[tokio::test(start_paused = true)] - async fn push_freshness_renews_live_routes_but_cannot_revive_rejected_routes() { + async fn installed_routes_survive_without_renewal_and_rejection_revokes_them() { let routes = Routes::default(); let route = SandboxServiceRoute { endpoint_id: "ep".into(), @@ -2091,7 +2005,6 @@ mod tests { routes.install(&installed(vec![route.clone()])); for _ in 0..10 { tokio::time::advance(Duration::from_secs(5)).await; - routes.renew(); } assert!( routes @@ -2101,7 +2014,7 @@ mod tests { let mut rejected = installed(vec![route]); rejected.configuration_admitted = false; routes.install(&rejected); - routes.renew(); + assert!( routes .resolve(HOST, "default--sandbox-a", "svc.openshell.internal") @@ -2196,7 +2109,7 @@ mod tests { } #[tokio::test] - async fn withdrawn_and_expired_routes_never_dial_boundary() { + async fn withdrawn_and_suspended_routes_never_dial_boundary() { let f = fixture(); let (_, old_token) = f .routes @@ -2212,7 +2125,7 @@ mod tests { .await .unwrap(); f.routes.sender.send_modify(|snapshot| { - snapshot.expires = Some(Instant::now() - Duration::from_secs(1)); + snapshot.suspend(); }); assert!(request(&f, HOST, HOST, "").await.is_empty()); f.routes.suspend(); @@ -2396,7 +2309,7 @@ mod tests { rejected.configuration_error = "candidate configuration rejected".into(); f.routes.install(&rejected); // A live push session must not renew rejected configuration. - f.routes.renew(); + assert!(request(&f, HOST, HOST, "").await.is_empty()); echo(&mut unaffected_ws, "peer survives rejection").await; @@ -2451,7 +2364,7 @@ mod tests { } #[tokio::test] - async fn coalesced_recreation_and_lease_lapse_cannot_revive_old_streams() { + async fn coalesced_recreation_and_suspension_cannot_revive_old_streams() { let f = fixture(); let (_, original) = f .routes @@ -2469,7 +2382,7 @@ mod tests { .resolve(HOST, "default--sandbox-a", "svc.openshell.internal") .unwrap(); f.routes.sender.send_modify(|snapshot| { - snapshot.expires = Some(Instant::now() - Duration::from_secs(1)); + snapshot.suspend(); }); f.routes.install(&installed(vec![f.route.clone()])); tokio::time::timeout(Duration::from_secs(1), f.routes.revoked(&f.route, renewed)) diff --git a/crates/openshell-supervisor/src/config_runtime.rs b/crates/openshell-supervisor/src/config_runtime.rs index 46c4f8751b..8bcb7947e9 100644 --- a/crates/openshell-supervisor/src/config_runtime.rs +++ b/crates/openshell-supervisor/src/config_runtime.rs @@ -1177,11 +1177,30 @@ impl ConfigRuntime { } pub async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { - let client = openshell_core::grpc_client::CachedOpenShellClient::connect_with_credentials( - &ctx.gateway, - ctx.extension_credentials.clone(), - ) - .await?; + let mut backoff = Duration::from_secs(1); + let client = loop { + match crate::grpc_attempt( + "Configuration gateway connection", + openshell_core::grpc_client::CachedOpenShellClient::connect_with_credentials( + &ctx.gateway, + ctx.extension_credentials.clone(), + ), + ) + .await + { + Ok(client) => break client, + Err(error) if crate::is_retryable_error(&error) => { + warn!( + %error, + retry_in_secs = backoff.as_secs(), + "Configuration gateway connection failed; retrying" + ); + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(Duration::from_secs(4)); + } + Err(error) => return Err(error), + } + }; run_policy_poll_loop_with_client(ctx, client).await } @@ -1257,10 +1276,6 @@ async fn run_policy_poll_loop_with_client( client: C, ) -> Result<()> { let mut config_apply_rx = ctx.config_apply_rx.take(); - let _app_configuration = ctx - .app_routes - .clone() - .map(crate::app_listener::Routes::configuration_guard); let (status_sender, status_receiver) = tokio::sync::mpsc::unbounded_channel(); tokio::spawn(run_policy_status_reporter( client.clone(), @@ -1395,13 +1410,7 @@ async fn run_policy_poll_loop_with_client( } } - // Accepted configurations must renew app routes before their freshness - // lease expires, including when a gateway uses polling instead of push. - let interval = if ctx.app_routes.is_some() { - Duration::from_secs(ctx.interval_secs).min(Duration::from_secs(5)) - } else { - Duration::from_secs(ctx.interval_secs) - }; + let interval = Duration::from_secs(ctx.interval_secs); loop { if let Some(updates) = config_push_updates.as_ref() { config_push_enabled = *updates.borrow(); @@ -1410,14 +1419,6 @@ async fn run_policy_poll_loop_with_client( // The session's bootstrap supersedes a polled result that was // not reconciled yet. pending_result = None; - // A quiet push stream still has authenticated session freshness. - // Renew only installed, unexpired routes. Poll mode renews by - // successfully applying a complete configuration instead. - if ctx.supervisor_session_id.borrow().is_some() - && let Some(routes) = &ctx.app_routes - { - routes.renew(); - } let delay = next_poll_delay(&ctx.extension_credentials, interval); tokio::select! { changed = async { @@ -3540,6 +3541,48 @@ mod tests { (ctx, config_apply_tx, push_tx) } + #[tokio::test] + async fn configuration_startup_recovers_when_gateway_becomes_available() { + let initial = settings_poll_result( + Some(proto_policy_fixture()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + let (mut ctx, config_apply_tx, _push_tx) = push_session_poll_loop(&initial); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + ctx.gateway = ctx.gateway.with_url(format!("http://{address}")); + let task = tokio::spawn(run_policy_poll_loop(ctx)); + + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!task.is_finished(), "a refused connection must be retried"); + assert!(!config_apply_tx.is_closed()); + + let listener = tokio::net::TcpListener::bind(address).await.unwrap(); + let server = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_routes(tonic::service::Routes::default()) + .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + // This transport-only gateway rejects polls. A complete pushed + // configuration must still apply after the connection recovers. + let applied = deliver_update( + &config_apply_tx, + config_update("after-startup-retry", &initial), + ) + .await; + assert_eq!(applied.outcome, i32::from(ConfigApplyOutcome::Applied)); + assert!(!task.is_finished()); + + task.abort(); + let _ = task.await; + assert!(config_apply_tx.is_closed()); + server.abort(); + } + #[tokio::test] async fn push_session_stops_polling_after_startup() { let initial = settings_poll_result( @@ -3564,7 +3607,7 @@ mod tests { } #[tokio::test(start_paused = true)] - async fn app_listener_caps_polling_interval_without_changing_disabled_behavior() { + async fn app_listener_preserves_configured_polling_interval() { for listener_enabled in [false, true] { let initial = settings_poll_result( Some(proto_policy_fixture()), @@ -3589,7 +3632,7 @@ mod tests { for _ in 0..8 { tokio::task::yield_now().await; } - let expected = 1 + if listener_enabled { step } else { step / 12 }; + let expected = 1 + step / 12; assert_eq!( poll_calls.load(Ordering::SeqCst), expected, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index b9e6327d15..a006a92e14 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -1730,6 +1730,7 @@ pub async fn run_sandbox_instance( return; } if let Err(e) = Box::pin(run_policy_poll_loop(poll_ctx)).await { + tracing::error!(error = %e, "Configuration task stopped"); ocsf_emit!( AppLifecycleBuilder::new(ocsf_ctx()) .activity(ActivityId::Fail) diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 566de3ebd9..073e203126 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -1005,7 +1005,7 @@ impl SharedHost { app_router: self .app_listener .as_ref() - .map(crate::app_listener::HostHandle::leased_router), + .map(crate::app_listener::HostHandle::router), command: main_process.command, workdir: registration.workdir, timeout_secs: 0, diff --git a/deploy/helm/openshell/templates/supervisor.yaml b/deploy/helm/openshell/templates/supervisor.yaml index 96d4a1e687..05d6da6beb 100644 --- a/deploy/helm/openshell/templates/supervisor.yaml +++ b/deploy/helm/openshell/templates/supervisor.yaml @@ -108,6 +108,10 @@ spec: {{- if get $app "enabled" }} - name: OPENSHELL_APP_LISTENER_ENABLED value: "true" + - name: OPENSHELL_APP_MAX_CONNECTIONS + value: {{ get $app "max_connections" | default 1024 | quote }} + - name: OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX + value: {{ get $app "max_connections_per_sandbox" | default 64 | quote }} - name: OPENSHELL_APP_LISTEN_ADDRESS value: {{ printf "%s:%v" $listenHost $appPort | quote }} - name: OPENSHELL_APP_BASE_URL diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 99e5a23fb4..857b118faa 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2508,11 +2508,20 @@ sandbox connection. [Expose long-running services](/how-it-works/sandboxes/overv enabled = true port = 9443 base_url = "https://services.example.com" +max_connections = 1024 +max_connections_per_sandbox = 64 [openshell.drivers.kubernetes.sandbox_runtime.app_listener] tls_secret_name = "openshell-app-tls" ``` +`max_connections` bounds concurrent accepted TLS connections per supervisor +listener and defaults to 1024. `max_connections_per_sandbox` bounds connections +and concurrent backend relays for each sandbox and defaults to 64. Both must be +positive, and the per-sandbox budget cannot exceed the listener budget. Size +these budgets with CPU, memory, and socket capacity when increasing shared +supervisor load. The Helm chart and Kubernetes driver pass them to supervisors. + `base_url = "https://"` replaces `domain`. Remove the old key when updating an existing app-listener configuration. @@ -2530,10 +2539,12 @@ The listener defaults to disabled, with port `8443` and no base URL. Port, the supervisor runtime and health ports. The common `port` controls both the listener and its Kubernetes endpoint. -With the listener enabled, supervisors cap configuration polling delays at five -seconds so healthy routes retain their 30-second freshness lease. Failed polls -do not renew the lease; expiry closes affected application connections. Disabling -the listener preserves the configured polling interval. +Installed routes remain available while the supervisor owns the sandbox +attachment. Gateway disconnects and failed configuration polls do not expire +routes or close their application streams. Explicit route removal, sandbox +stop/detach, rejected configuration, or an ownership change removes the affected +routes. During an outage, the supervisor retains its last accepted configuration; +a revocation it has not received takes effect after reconnection. If services disappear from discovery after a configuration change, check supervisor OCSF events named `App listener service routes rejected` for the @@ -2579,25 +2590,18 @@ hostnames; older supervisors cannot serve the new hashed routes. The discovery API supplies accepted supervisor endpoints. Configure `base_url` to publish the application origin; otherwise CLI URLs retain the gateway path. -Enabled supervisors report installed service routes through their authenticated -gateway sessions. The gateway accepts only current configuration and ownership, -resolves the supervisor endpoint through the compute driver, and expires -installation evidence unless renewed. Reports do not establish application -health or confirm that external ingress is ready. No additional reporting port -or application credentials are required. Shared Kubernetes discovery selects the -acknowledged pool owner's Pod IP and app port. The gateway revalidates the -ownership term and live membership against shared storage. During takeover, -old installations are withdrawn and the new endpoint appears only after the -replacement installs the configuration. Application connections may need to -reconnect; the sandbox workload and public URL remain unchanged. - -Shared listeners require both current configuration and a gateway-issued serving -lease of at most fifteen seconds. Lease deadlines include queueing time; keep -supervisor and gateway clocks synchronized. Loss of serving authority closes -application streams even if configuration continues renewing. Under a partition, -allow for pool membership failure detection before the last serving lease expires. -Storage errors prevent lease renewal. Discovery expiry and serving expiry are -separate from external ingress readiness. +Enabled supervisors report installed service routes on change and reconnect, and +retry until acknowledged. The gateway checks declarations and ownership and +resolves the endpoint through the compute driver. Acknowledged routes have no +serving-lease deadline. Reports do not establish application health or external +ingress readiness, and require no additional reporting port or credentials. + +Shared Kubernetes discovery selects the acknowledged owner's Pod IP and app port. +Publication checks the assignment, ownership epoch, runtime identity and ready +acknowledgement. A missing control heartbeat does not itself remove that location. +A confirmed ownership transition fences the old attachment at the sandbox +boundary. Existing application connections may close during takeover, while the +workload and public URL remain unchanged. Both discovery RPCs require `supervisor_app_listener.enabled = true`. When the listener is disabled, they return `FAILED_PRECONDITION` without collecting routes @@ -2609,25 +2613,31 @@ one explicit workspace selector, `sandbox:read`, and workspace user access. Each response replaces the workspace route view and includes the hostname, supervisor TLS endpoint, installation version, and expiry. Preserve the hostname as TLS SNI and HTTP authority when routing directly to the endpoint. Remove absent routes -and expire cached entries even during discovery errors. An API error does not -mean the workspace has no routes. Watches end after one minute; reconnect and +from successful replacements. `expires_at` is a refresh hint, not a supervisor +serving deadline. Consumers choose cache retention during API errors; an error +does not mean the workspace has no routes. Watches end after one minute; reconnect and relist when they end. Use [discovery reader grants](#discovery-reader-grants) for noninteractive route consumers. -Discovery limits apply per gateway process: 1,000 installation records, 4,096 -routes, and 4 MiB per snapshot, with a ten-second collection timeout. Up to four -collections and 16 unary requests run concurrently. Collections wait for a free -slot within the ten-second timeout; unary requests are limited +Discovery limits apply per gateway process: 4 MiB of installation payloads per +workspace and 4 MiB per combined snapshot, with a ten-second request deadline. +Installation and route counts have no fixed ceiling within these size bounds. Up to four +background index refreshes and 16 unary requests run concurrently. Requests wait +for a fresh index frame within that deadline; unary requests are limited to four per principal and eight per workspace. Watches are limited to 32 total, four per principal, and 16 per workspace for explicit single-workspace queries. Finite and all-workspace queries use caller/global capacity independently of tenant-local quotas. Capacity and size limits return `RESOURCE_EXHAUSTED`; storage failures, configuration changes during collection, and timeouts return `UNAVAILABLE`; corrupt records return `INTERNAL`. Disabling the app listener returns `FAILED_PRECONDITION`. -Consumers share a one-second collection cache, bounded to 16 workspaces. Cache reuse adds at most one refresh interval to collection freshness; -cached routes never outlive their advertised expiry. Collections publish the -latest accepted renewal for an unchanged, revalidated installation; the gateway -does not create a new lease when serving discovery. Watches recheck bearer -credentials and workspace access every second and terminate if either is lost. +Discovery reads a maintained route index that synchronizes durable changes across +gateway replicas once per refresh interval. It joins declarations with installed +attachment state without rebuilding policy or provider configuration. Indexes are +bounded to 16 workspaces; +unused workers stop polling after five seconds. Initial hydration continues if a +caller times out. Retry `UNAVAILABLE` while the index becomes ready. A stale frame +is not returned. Discovery freshness hints do not expire supervisor routes. +Watches recheck +bearer credentials and workspace access every second and terminate if either is lost. OIDC token revocation follows the configured verifier's semantics; offline JWT verification cannot detect issuer-side revocation before token expiry. @@ -2734,7 +2744,7 @@ authority on existing connections. Grant-file reads have a two-second deadline; watches recheck at one-second refreshes and after bounded collection. Allow up to sixteen seconds for collection and a backpressured watch to terminate, plus file propagation to each replica in the deployment's revocation bound. Missing or invalid files fail -closed; consumers must independently expire cached routes during errors. +closed; consumers choose cache retention during discovery errors. Certificates are also checked against their handshake-derived expiry. For rotation, add the replacement fingerprint, project the new certificate/key diff --git a/e2e/kubernetes/app-listener/README.md b/e2e/kubernetes/app-listener/README.md index efb83d17d7..53776f3478 100644 --- a/e2e/kubernetes/app-listener/README.md +++ b/e2e/kubernetes/app-listener/README.md @@ -30,7 +30,7 @@ differs from the repository's mise environment. `OPENSHELL_E2E_APP_TOPOLOGY` accepts `dedicated` (default) or `shared`; `OPENSHELL_E2E_APP_DELIVERY` accepts `push` (default) or `poll`; `OPENSHELL_E2E_APP_TAKEOVER` accepts `graceful` (default) or `abrupt` for shared -supervisors. Dedicated runs include gateway-outage expiry. Every run also +supervisors. Dedicated runs include gateway-outage retention. Every run also disables the listener, explicitly enables gateway routing for the fallback check, and verifies absent app sockets/TLS mounts/Services and continued gateway application ingress. Logs, events, and resource summaries @@ -89,13 +89,13 @@ container, preventing a graceful leave; it requires access to that Docker engine These options deliberately interrupt test resources in the supplied namespace. For dedicated topology, omit `--takeover`. Add -`--expire-gateway statefulset/listener-review` (using the actual workload name) -to scale the isolated gateway to zero, verify route/stream expiry, restore its +`--outage-gateway statefulset/listener-review` (using the actual workload name) +to scale the isolated gateway to zero, verify routes and streams survive a 90-second outage, restore its original replica count, and check application survival. Repeat with gateway `config_delivery_mode` set to `push` and `poll`. The lower-level runner leaves the Helm release and TLS Secret in place. Use -`--disabled --gateway-service ` instead of takeover/expiry flags to +`--disabled --gateway-service ` instead of takeover/outage flags to check an already disabled release. Configuration rejection and the additional deployment cleanup scenarios remain in the manual checklist below. @@ -155,8 +155,9 @@ connection survives. Recreate the sandbox and confirm old streams cannot revive. Exercise configuration polling and push modes. In push mode, leave configuration unchanged for longer than 30 seconds and confirm ingress remains usable while the session is healthy. Reject configuration and confirm ingress closes. Stop -configuration/session refresh and require routes and streams to expire after -the remaining freshness lease once session loss is detected. +configuration/session refresh for at least 90 seconds and require existing +streams and fresh requests to keep working. Resume the gateway and verify +configuration reconciliation, including an explicit route withdrawal. Run with listener configuration omitted, explicitly disabled despite complete TLS/port options, and explicitly enabled. Disabled deployments have no app port, @@ -192,15 +193,14 @@ HA harness's node-runtime SIGKILL procedure. A force-delete alone may still allo an orderly Leave and does not establish expiry-based recovery. Require unchanged workload identity/memory, stable public URLs, replacement endpoint/version, and successful HTTP/WebSocket reconnection. Keep another owner's WebSocket open to -check sibling isolation. A stale installation must disappear even if a consumer -retains it; shared listeners require an independent serving lease capped at -fifteen seconds from issuance. Queued challenges cannot restart that deadline. -Configuration renewal alone cannot extend serving authority. +check sibling isolation. Confirm that the sandbox boundary fences the previous +owner's connections when the replacement ownership epoch is confirmed. A gateway +connection loss alone must not revoke an unchanged attachment or its routes. Also exercise gateway reconnection, discovery-reader revocation/regrant, route -withdrawal, and discovery outage. Measure serving and discovery expiry separately; -include membership failure detection and grant-file projection in the applicable -bounds. These checks do not establish physical node or network-partition behavior +withdrawal, and discovery outage. Distinguish consumer refresh hints from +attachment validity. Include failure detection, actual ownership transitions, +and grant-file projection in the applicable bounds. These checks do not establish physical node or network-partition behavior when run on a single local k3d node. Existing sockets may break during takeover. Hashed multi-gateway hostnames still require the common hostname integration. diff --git a/e2e/kubernetes/app-listener/client.py b/e2e/kubernetes/app-listener/client.py index e218835058..877db45247 100644 --- a/e2e/kubernetes/app-listener/client.py +++ b/e2e/kubernetes/app-listener/client.py @@ -154,7 +154,37 @@ def main(): headers = {k.lower(): v for k, v in body["headers"].items()} assert headers["authorization"] == "Bearer application-test-token" print("PASS explicitly configured bearer passthrough") - elif mode in ("withdraw", "takeover", "expire"): + elif mode == "outage": + status, baseline = request(ip, port, hostname) + assert status == 200 + with ( + websocket(ip, port, hostname) as first, + websocket(*sys.argv[5:8]) as second, + ): + echo(first) + echo(second) + print( + "READY: application streams established before gateway outage", + flush=True, + ) + deadline = time.monotonic() + 90 + iteration = 0 + while time.monotonic() < deadline: + echo(first) + echo(second) + if iteration % 5 == 0: + status, body = request(ip, port, hostname) + assert ( + status == 200 + and body["boot"] == baseline["boot"] + and body["pid"] == baseline["pid"] + ) + iteration += 1 + time.sleep(1) + print( + "PASS existing streams and fresh HTTP requests survive gateway outage" + ) + elif mode in ("withdraw", "takeover"): with ( websocket(ip, port, hostname) as affected, websocket(*sys.argv[5:8]) as unaffected, @@ -164,18 +194,10 @@ def main(): time.sleep(35) echo(affected) echo(unaffected) - print( - "READY: quiet WebSockets survived beyond freshness window", flush=True - ) + print("READY: quiet WebSockets remain active before withdrawal", flush=True) closed(affected) - if mode != "expire": - echo(unaffected) - else: - closed(unaffected) - print( - "PASS affected streams closed" - + ("; unrelated stream survived" if mode != "expire" else "") - ) + echo(unaffected) + print("PASS affected streams closed; unrelated stream survived") else: raise ValueError(mode) diff --git a/e2e/kubernetes/app-listener/run.py b/e2e/kubernetes/app-listener/run.py index ccbc77c39e..69e18c3c99 100644 --- a/e2e/kubernetes/app-listener/run.py +++ b/e2e/kubernetes/app-listener/run.py @@ -262,7 +262,7 @@ def wait_for_shared_hosts(): if args.topology == "shared": command += ["--takeover", args.takeover] else: - command += ["--expire-gateway", "statefulset/listener-e2e"] + command += ["--outage-gateway", "statefulset/listener-e2e"] with (evidence / "enabled.log").open("w") as output: result = subprocess.run( command, diff --git a/e2e/kubernetes/app-listener/verify.py b/e2e/kubernetes/app-listener/verify.py index e42949f269..f38dc79e50 100644 --- a/e2e/kubernetes/app-listener/verify.py +++ b/e2e/kubernetes/app-listener/verify.py @@ -57,8 +57,8 @@ def main(): help="Stop a shared owner Pod; abrupt requires Docker access to the k3d/kind node", ) parser.add_argument( - "--expire-gateway", - help="Scale this isolated gateway workload to zero, verify expiry, then restore it (e.g. statefulset/listener-review)", + "--outage-gateway", + help="Scale this isolated gateway workload to zero, verify route retention, then restore it (e.g. statefulset/listener-review)", ) parser.add_argument( "--network-policy", @@ -333,7 +333,7 @@ def streams(mode, ip, first, second_ip, second, action): import selectors ready = False - end = time.monotonic() + 110 + end = time.monotonic() + (140 if mode == "outage" else 110) assert process.stdout is not None with selectors.DefaultSelector() as selector: selector.register(process.stdout, selectors.EVENT_READ) @@ -613,33 +613,33 @@ def stop_forward(): f"PASS {args.takeover} owner takeover preserves workload Pod, generation, process and memory; peer unaffected", flush=True, ) - if args.expire_gateway: + if args.outage_gateway: obj = json.loads( - run([*k, "get", args.expire_gateway, "-o", "json"]).stdout + run([*k, "get", args.outage_gateway, "-o", "json"]).stdout ) replicas = obj["spec"]["replicas"] assert replicas > 0 - expiry_pod, _ = owner(name) - expiry_ip = expiry_pod["status"]["podIP"] + outage_pod, _ = owner(name) + outage_ip = outage_pod["status"]["podIP"] try: streams( - "expire", - expiry_ip, + "outage", + outage_ip, host, - expiry_ip, + outage_ip, hostname(name, ""), - lambda: run([*k, "scale", args.expire_gateway, "--replicas=0"]), + lambda: run([*k, "scale", args.outage_gateway, "--replicas=0"]), ) - print(probe("reject", expiry_ip, host).stdout, end="", flush=True) + print(probe("http", outage_ip, host).stdout, end="", flush=True) finally: - run([*k, "scale", args.expire_gateway, f"--replicas={replicas}"]) + run([*k, "scale", args.outage_gateway, f"--replicas={replicas}"]) run( - [*k, "rollout", "status", args.expire_gateway, "--timeout=180s"] + [*k, "rollout", "status", args.outage_gateway, "--timeout=180s"] ) _, resumed = owner(name) assert (resumed["boot"], resumed["pid"]) == (body["boot"], body["pid"]) print( - "PASS gateway outage expires streams and routes; recovery preserves application", + "PASS gateway outage retains streams and routes; recovery preserves application", flush=True, ) print("PASS listener Kubernetes e2e", flush=True) diff --git a/proto/openshell.proto b/proto/openshell.proto index 09a5af6e57..07542e07c2 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -3531,6 +3531,7 @@ message GatewayMessage { SessionRedirect session_redirect = 6; ConfigUpdate config_update = 7; ServiceRouteLease service_route_lease = 8; + ServiceAdvertisementAck service_advertisement_ack = 9; } } @@ -4541,7 +4542,8 @@ message EndpointFailure { string request_id = 8; } -// Gateway lease challenge on an authenticated sandbox supervisor session. +// Legacy gateway lease challenge. New deployments acknowledge installation +// snapshots without making serving authority depend on periodic renewal. // Expiry is measured from gateway issuance, never report receipt. message ServiceRouteLease { uint64 sequence = 1; @@ -4551,10 +4553,11 @@ message ServiceRouteLease { google.protobuf.Timestamp expires_at = 3; } -// Complete installed-route replacement for a live lease challenge. The -// supervisor reports only if its remaining serving freshness covers duration. +// Complete installed-route replacement for the current sandbox attachment. // No address is accepted from the supervisor; the compute driver supplies it. +// Unacknowledged reports are retried, without a serving-expiry deadline. message SupervisorServiceAdvertisement { + // Session-local report ordering; the legacy field name is retained on wire. uint64 lease_sequence = 1; string configuration_instance_id = 2; uint64 config_revision = 3; @@ -4563,6 +4566,12 @@ message SupervisorServiceAdvertisement { string service_domain = 5; } +// Acknowledges durable acceptance on the current authenticated supervisor +// session. Reports are retried until acknowledged; this grants no timed lease. +message ServiceAdvertisementAck { + uint64 sequence = 1; +} + // Select one workspace, or all active workspaces with an explicit platform grant. message GetServiceRouteSnapshotRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; @@ -4571,9 +4580,9 @@ message GetServiceRouteSnapshotResponse { ServiceRouteSnapshot snapshot = 1; } // Same workspace authorization as GetServiceRouteSnapshot. A watch sends an -// initial replacement and later replacements, including lease-only renewal. -// Clients reconnect/relist when the bounded stream ends and expire cached -// routes during discovery errors; errors are not empty replacements. +// initial replacement and later replacements, including freshness hints. +// Clients reconnect/relist when the bounded stream ends and choose their cache +// retention policy during discovery errors; errors are not empty replacements. message WatchServiceRoutesRequest { openshell.datamodel.v1.WorkspaceSelector workspace_scope = 1; } @@ -4600,9 +4609,11 @@ message DiscoveredServiceRoute { string name = 3; string hostname = 4; ServiceRouteEndpoint endpoint = 5; - // Changes on owner/backend/declaration replacement, but not lease renewal. + // Changes on attachment/backend/declaration replacement, not control-session reconnect. string installation_version = 6; uint64 declaration_revision = 7; + // Consumer refresh hint for this discovery observation. This does not expire + // the supervisor's installed route or grant/revoke serving authority. google.protobuf.Timestamp expires_at = 8; } diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index cca32b298a..a0905806f3 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1921,55 +1921,56 @@ drop out of discovery. New supervisors require `OPENSHELL_APP_BASE_URL` from the driver; `OPENSHELL_APP_SERVICE_DOMAIN` is not a compatibility input. Plan for service interruption when replacing dedicated Pods. -Service changes arrive through polling or push configuration. Only admitted -service declarations are installed. Polling and accepted live push sessions -renew a 30-second lease; rejected configuration or expired freshness closes -routes. When the listener is enabled, polling delays are capped at five seconds -even if the configured interval is longer; failed polls do not renew the lease. -App traffic uses application/edge authentication independently of gateway -user authentication. The discovery API publishes accepted listener installations. CLI URLs use the -configured application origin when `base_url` is set, otherwise the gateway path. - -When enabled application routes are not published, inspect supervisor OCSF events -whose message starts with `App listener service routes rejected` for the reason -and configuration revision. Identical rejections are suppressed until the -configuration instance/revision or reason changes, or installation succeeds. -Then check the authenticated -supervisor session and installed configuration before checking ingress. The -gateway requests installation evidence every five seconds with a fifteen-second -lease measured from challenge issuance. Instances report only when their serving -freshness covers that lease. Replayed, late, stale-configuration, and replaced -session reports cannot renew evidence. Endpoint resolution comes from the -compute driver once per challenge/report exchange, with fresh resolution for the -next challenge. Acceptance still checks durable ownership and shared member -readiness; ambiguous shared ownership must not publish an address. - -For discovery troubleshooting, request `GetServiceRouteSnapshot` for an explicit -active workspace using an identity with `sandbox:read` and workspace user access. -Both discovery RPCs return `FAILED_PRECONDITION` when -`supervisor_app_listener.enabled` is false; enable the listener before discovering routes. -`WatchServiceRoutes` rechecks access every second and ends after one minute; -clients must reconnect/relist. Compare installation versions separately from -snapshot revisions: lease renewal changes expiry and the snapshot revision while -preserving installation identity. Treat unavailable/corrupt/over-limit results as -errors, and expire cached routes independently. Do not turn an error into an -empty replacement. For shared pools, compare the discovered endpoint to the -acknowledged owner's Pod IP and configured app port, not its runtime port or a -load-balanced supervisor Service. Publication requires a current ownership term, -live member, and acknowledged ready report. During takeover old streams may close; -verify workload identity/memory survives and new connections reach the replacement. -Shared serving leases last at most fifteen seconds from issuance, independently -of configuration renewal; include membership failure detection when measuring a -partition's stale-owner interval. Storage failures prevent renewal. - -Application ingress consumers call the separate `openshell.v1.ServiceDiscovery` -service, rather than `OpenShell`. Discovery snapshots share a one-second cache -per workspace (16 cached workspaces, four concurrent collections). The gateway -admits 16 unary requests (four per principal, eight per workspace), and 32 watches -(four per principal, 16 per workspace). `RESOURCE_EXHAUSTED` means capacity or -record/route/byte limits; `UNAVAILABLE` means storage or collection timeout. -Watches recheck bearer credentials and membership every second. Allow one refresh -interval for withdrawals; route lease expiry remains independently enforced. +Service changes arrive through polling or push configuration. Admitted routes +remain installed for the sandbox attachment; gateway disconnects and failed polls +do not revoke them. Explicit route changes, configuration rejection, instance +stop/detach, and actual ownership changes do. A supervisor cannot apply a revocation +it has not received during a partition. Reconnection reconciles the current +configuration, including removals. Gateway, compute driver and supervisor images +must match the internal installation-acknowledgement protocol. + +Inspect supervisor OCSF events beginning `App listener service routes rejected` +for the reason and configuration revision. Installation snapshots are sent on +change and reconnect and retried until acknowledged. `service installation +acceptance timed out; supervisor will retry` does not expire an earlier accepted +attachment. Endpoint resolution still comes from the trusted compute driver; +new acceptance checks live member authority, current session and declarations. +No application backend address is accepted from the supervisor. + +`Configuration gateway connection failed; retrying` retains the configuration +receiver while reconnecting, with ten-second attempts and backoff capped at four +seconds. `Configuration task stopped` identifies a terminal configuration-task +error; the last installed route set remains until explicit invalidation or +attachment shutdown. + +Both discovery RPCs return `FAILED_PRECONDITION` while the app listener is disabled. +Use `openshell.v1.ServiceDiscovery` with `sandbox:read` and an explicit workspace +or reader grant. Successful responses are complete replacements. Remove absent +routes, preserve the hostname as TLS SNI/HTTP authority, and choose cache retention +during API errors. Never turn an error into an empty replacement. `expires_at` is +a consumer refresh hint, not permission for the supervisor to serve. + +Discovery joins acknowledged routes with current declarations and attachment +identity. The version-header scan tracks cross-replica changes without rebuilding +policy, provider or settings configuration. Each workspace caches only authority +records referenced by its installations. An edit to one service does not +withdraw unrelated services. For shared pools, check assignment generation, +owner epoch and the acknowledged ready report against the returned Pod IP/app +port. A missing member/session heartbeat alone does not withdraw the location. +A confirmed takeover fences previous-owner boundary connections; sockets are not +migrated. Verify unchanged workload identity and successful reconnection. + +Installation versions remain stable across control-session reconnects and +unrelated configuration edits. Snapshot revisions can change as consumer freshness +hints advance. There are at most 16 indexed workspaces and four concurrent +refreshes; idle workers stop after five seconds and restart on demand. Reader +cancellation does not cancel initial hydration. `UNAVAILABLE` includes storage, +synchronization and index readiness failure; ready Pods do not establish healthy +public ingress. Frames are shared for one second. Unary limits remain 16 total, +four per principal and eight per explicit workspace; watches remain 32 total, +four per principal and 16 per explicit workspace. `RESOURCE_EXHAUSTED` also covers +record/route/byte limits. Watches recheck credentials/access each second and end +after one minute; reconnect and relist. For incorrect public service URLs, inspect `[openshell.gateway].enable_gateway_service_routing` first. The Helm chart defaults it @@ -2067,3 +2068,16 @@ fails or stalls. Check Entra egress, the federated credential, and PostgreSQL role mapping; do not suggest CLI login, node identity, or a password fallback. Sandbox ServiceAccounts must not carry gateway database federation. See the published gateway configuration documentation for setup. + +For installation acceptance failures, check the current attachment identity, +configured declarations, trusted endpoint lookup and database latency. Endpoint +resolution uses a metadata watch followed by a fresh GET with UID, labels and +deletion checks. Watch errors and incomplete relists prevent new acceptance; +they do not expire an already acknowledged attachment. + +Size supervisor app-listener connection budgets using +`supervisor.app_listener.max_connections` (default 1024) and +`max_connections_per_sandbox` (default 64). The Kubernetes driver and Helm chart +pass both budgets to supervisors. Keep the per-sandbox budget positive and at +most the listener-wide budget, and provide CPU, memory, and socket capacity for +higher budgets.