Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(worker): fence verified dispatch with versioned queues (#545)
Krisztian Gajdar2ba3d6e3d028
diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 12352788f..88ddec1d2 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -344,9 +344,32 @@ backend advertises support, while Candle remains closed until it implementsthe same contract. Capability discovery cannot replace the method fence: abackend child can restart after its last positive capability response.-These entrypoints prepare the backend boundary; current producers still use-the existing methods. Gateway activation also requires a distinct versioned-worker-direct queue subject and consumer that older sidecars cannot receive.+Authority work uses the worker-direct subject with an eighth token,+`execution-authority-v1`. The sidecar creates `WORK_AUTHORITY_V1_<worker>` and+`authority-v1-<worker>` separately from its ordinary pool/direct stream and+consumer. The stream retains the existing bounded age, message and delivery+limits. Older six-token pool and seven-token direct filters cannot receive this+work or change the authority consumer when reconciling their own streams.+Redelivery preserves the subject and rechecks the live configuration hash.+Verified subject and payload model ids must match exactly before any subject+rewrite, readiness check or offloaded payload retrieval. This refuses lossy+`__`/`_dot_` normalization collisions instead of retargeting another model+covered by the same configuration hash.++The sidecar derives the required contract from that subject. Before readiness+or fetching offloaded inputs, it requires a nonempty matching hash, live config+authority, and positively verified backend support. Numeric work also requires+the complete scheduler lifecycle; its scheduler batches are partitioned by+execution contract so older empty-hash work cannot invalidate verified work.+Batch and generation dispatch use the updated-only IPC methods, preserving the+final locked execution checks. The sidecar's health capability requires every+ready backend child to report support and the authority pull consumer to run.+Missing or unavailable children close that admission signal. The method fence+still applies independently if a backend changes after the last health probe.++Current gateway producers use the existing queue subjects. Gateway activation+must select positively capable workers and publish only on the versioned+subject for verified work.Every publish and retry must retain both fences, with no legacy pool or IPCfallback. A missing, stale, unsupported, or unavailable authority refuses workbefore inputs execute. This extends the queue contract while preserving thediff --git a/packages/sie_server_sidecar/src/backend/adapter_pool.rs b/packages/sie_server_sidecar/src/backend/adapter_pool.rsindex 86c7aeb61..4af57d76e 100644--- a/packages/sie_server_sidecar/src/backend/adapter_pool.rs+++ b/packages/sie_server_sidecar/src/backend/adapter_pool.rs@@ -65,6 +65,7 @@ impl AdapterWorkerChild {/// Shared pool state used by the backend, heartbeat, config fanout, and/// generation cancel fanout.pub struct AdapterWorkerPool {+ execution_authority_v1: Arc<AtomicBool>,children: Vec<Arc<AdapterWorkerChild>>,placements: Mutex<HashMap<String, usize>>,pinned_models: Mutex<HashSet<String>>,@@ -106,6 +107,7 @@ impl AdapterWorkerPool {"AdapterWorkerPool requires at least one IPC socket");let pool = Arc::new(Self {+ execution_authority_v1: Arc::new(AtomicBool::new(false)),children,placements: Mutex::new(HashMap::new()),pinned_models: Mutex::new(HashSet::new()),@@ -129,6 +131,10 @@ impl AdapterWorkerPool {self.children.len()}+ pub fn execution_authority_v1(&self) -> Arc<AtomicBool> {+ Arc::clone(&self.execution_authority_v1)+ }+pub fn pinned_assignment_revision(&self) -> u64 {self.pinned_assignment_revision.load(Ordering::Acquire)}@@ -144,16 +150,31 @@ impl AdapterWorkerPool {&self,timestamp_ms: f64,) -> Vec<(usize, Result<PingResponse, IpcError>)> {- let out = join_all(self.children.iter().map(|child| async move {+ let results = join_all(self.children.iter().map(|child| async move {let result = child.ipc.ping(timestamp_ms).await;if result.as_ref().is_ok_and(|resp| resp.ready) {self.mark_child_ready_from_health_success(child);} else {child.ready.store(false, Ordering::Release);}- (child.index, result)+ let supports_authority = result.as_ref().is_ok_and(|resp| resp.ready)+ && tokio::time::timeout(Duration::from_secs(2), child.ipc.worker_capabilities())+ .await+ .ok()+ .and_then(Result::ok)+ .is_some_and(|resp| resp.supports_execution_authority_v1);+ (child.index, result, supports_authority)})).await;+ self.execution_authority_v1.store(+ !self.config_quarantined.load(Ordering::Acquire)+ && results.iter().all(|(_, _, supports)| *supports),+ Ordering::Release,+ );+ let out = results+ .into_iter()+ .map(|(index, result, _)| (index, result))+ .collect();self.runtime_state.worker_gpu_slots_ready.set(self.ready_child_count() as i64);@@ -161,12 +182,17 @@ impl AdapterWorkerPool {}pub async fn worker_capabilities(&self) -> Result<WorkerCapabilitiesResponse, IpcError> {- let mut combined = WorkerCapabilitiesResponse::default();+ let mut combined = WorkerCapabilitiesResponse {+ supports_execution_authority_v1: true,+ ..Default::default()+ };let mut any_success = false;let mut last_err = None;for child in &self.children {match child.ipc.worker_capabilities().await {Ok(resp) => {+ combined.supports_execution_authority_v1 &=+ resp.supports_execution_authority_v1;any_success = true;self.mark_child_ready_from_health_success(child);combined.has_generation_models |= resp.has_generation_models;@@ -177,6 +203,7 @@ impl AdapterWorkerPool {}}Err(e) => {+ combined.supports_execution_authority_v1 = false;child.ready.store(false, Ordering::Release);last_err = Some(e);}@@ -345,6 +372,20 @@ impl AdapterWorkerPool {req: ProcessGenerateRequest,on_event: F,) -> Result<(), IpcError>+ where+ F: FnMut(GenerateEvent) -> Fut,+ Fut: std::future::Future<Output = Result<(), IpcError>>,+ {+ self.process_generate_with_authority(req, on_event, false)+ .await+ }++ pub async fn process_generate_with_authority<F, Fut>(+ &self,+ req: ProcessGenerateRequest,+ on_event: F,+ require_authority: bool,+ ) -> Result<(), IpcError>whereF: FnMut(GenerateEvent) -> Fut,Fut: std::future::Future<Output = Result<(), IpcError>>,@@ -353,7 +394,14 @@ impl AdapterWorkerPool {let model_id = req.model_id.clone();let child = self.child_for_model(&model_id);let _inflight_guard = ChildInflightGuard::enter(Arc::clone(&child));- let result = child.ipc.process_generate(req, on_event).await;+ let result = if require_authority {+ child+ .ipc+ .process_generate_with_execution_authority_v1(req, on_event)+ .await+ } else {+ child.ipc.process_generate(req, on_event).await+ };match &result {Ok(()) => self.mark_child_call_succeeded(&child),Err(_) => {@@ -838,6 +886,20 @@ impl InferenceBackend for AdapterWorkerPool {.map_err(map_ipc_error)}+ async fn run_batch_with_execution_authority_v1(+ &self,+ req: RunBatchRequest,+ budget: Option<Duration>,+ ) -> Result<BatchOutcome, BackendError> {+ let model_id = req.model_id.clone();+ let child = self.child_for_model(&model_id);+ self.run_child_batch(model_id, child, |ipc| async move {+ ipc.run_batch_with_execution_authority_v1(req, budget).await+ })+ .await+ .map_err(map_ipc_error)+ }+async fn drain(&self, deadline_ms: u64) {for (index, result) in self.drain_all(deadline_ms).await {match result {@@ -926,6 +988,175 @@ mod tests {pool}+ #[derive(Default)]+ struct CapabilityProbeGate {+ enabled: AtomicBool,+ entered: tokio::sync::Notify,+ release: tokio::sync::Notify,+ }++ async fn spawn_capability_worker(+ path: PathBuf,+ supports: Arc<AtomicBool>,+ gate: Option<Arc<CapabilityProbeGate>>,+ ) -> tokio::task::JoinHandle<()> {+ let listener = UnixListener::bind(path).unwrap();+ tokio::spawn(async move {+ loop {+ let Ok((mut socket, _)) = listener.accept().await else {+ return;+ };+ let supports = Arc::clone(&supports);+ let gate = gate.clone();+ tokio::spawn(async move {+ loop {+ let mut length = [0_u8; 4];+ if socket.read_exact(&mut length).await.is_err() {+ return;+ }+ let mut bytes = vec![0; u32::from_be_bytes(length) as usize];+ if socket.read_exact(&mut bytes).await.is_err() {+ return;+ }+ let request: serde_json::Value = rmp_serde::from_slice(&bytes).unwrap();+ let method = request["method"].as_str().unwrap();+ if method == "WorkerCapabilities" {+ if let Some(gate) = &gate {+ if gate.enabled.load(Ordering::Acquire) {+ gate.entered.notify_one();+ gate.release.notified().await;+ }+ }+ }+ let capable = supports.load(Ordering::Acquire);+ let body = match method {+ "Ping" => Some(+ serde_json::json!({"timestamp_ms": 0.0, "worker_id": "child", "ready": true}),+ ),+ "WorkerCapabilities" if capable => {+ Some(serde_json::json!({"supports_execution_authority_v1": true}))+ }+ "WorkerCapabilities" => Some(serde_json::json!({})),+ "RunBatchWithExecutionAuthorityV1" if capable => {+ Some(serde_json::json!({"outcomes": []}))+ }+ _ => None,+ };+ let response = rmp_serde::to_vec_named(&serde_json::json!({+ "version": crate::ipc_types::IPC_VERSION,+ "request_id": request["request_id"],+ "ok": body.is_some(),+ "error": if body.is_none() { Some("unknown method") } else { None },+ "body": body,+ }))+ .unwrap();+ if socket+ .write_all(&(response.len() as u32).to_be_bytes())+ .await+ .is_err()+ || socket.write_all(&response).await.is_err()+ {+ return;+ }+ }+ });+ }+ })+ }++ #[tokio::test]+ async fn every_child_must_support_authority_and_old_replacement_cannot_downgrade() {+ let dir = tempfile::Builder::new()+ .prefix("sie-a-")+ .tempdir_in("/tmp")+ .unwrap();+ let new_path = dir.path().join("new.sock");+ let old_path = dir.path().join("old.sock");+ let old_supports = Arc::new(AtomicBool::new(false));+ let new_server =+ spawn_capability_worker(new_path.clone(), Arc::new(AtomicBool::new(true)), None).await;+ let old_server =+ spawn_capability_worker(old_path.clone(), Arc::clone(&old_supports), None).await;+ let pool = pool_with_paths(&[new_path.clone(), old_path.clone()]);+ pool.ping_all(0.0).await;+ assert_eq!(pool.ready_child_count(), 2);+ assert!(!pool.execution_authority_v1().load(Ordering::Acquire));+ assert!(+ !pool+ .worker_capabilities()+ .await+ .unwrap()+ .supports_execution_authority_v1+ );+ old_supports.store(true, Ordering::Release);+ pool.ping_all(0.0).await;+ assert!(pool.execution_authority_v1().load(Ordering::Acquire));++ // Health is still positive when the placed child becomes an older+ // backend. The per-call discriminator must independently refuse it.+ pool.placements.lock().unwrap().insert("m".into(), 1);+ old_supports.store(false, Ordering::Release);+ let result = pool+ .run_batch_with_execution_authority_v1(+ RunBatchRequest {+ model_id: "m".into(),+ batch_id: 1,+ lora_key: String::new(),+ total_cost: 1,+ items: Vec::new(),+ accepts_batched_f16_multivectors: true,+ },+ None,+ )+ .await;+ assert!(matches!(result, Err(BackendError::Transient(_))));+ pool.ping_all(0.0).await;+ assert!(!pool.execution_authority_v1().load(Ordering::Acquire));++ let unavailable = pool_with_paths(&[new_path, dir.path().join("missing.sock")]);+ unavailable.ping_all(0.0).await;+ assert!(!unavailable.execution_authority_v1().load(Ordering::Acquire));+ assert!(+ !unavailable+ .worker_capabilities()+ .await+ .unwrap()+ .supports_execution_authority_v1+ );+ new_server.abort();+ old_server.abort();+ }++ #[tokio::test]+ async fn successful_authority_heartbeat_does_not_temporarily_revoke_support() {+ let dir = tempfile::Builder::new()+ .prefix("ipc-cap-refresh-")+ .tempdir_in("/tmp")+ .unwrap();+ let path = dir.path().join("child.sock");+ let gate = Arc::new(CapabilityProbeGate::default());+ let server = spawn_capability_worker(+ path.clone(),+ Arc::new(AtomicBool::new(true)),+ Some(gate.clone()),+ )+ .await;+ let pool = pool_with_paths(&[path]);+ pool.ping_all(0.0).await;+ assert!(pool.execution_authority_v1().load(Ordering::Acquire));+ gate.enabled.store(true, Ordering::Release);+ let task_pool = pool.clone();+ let refresh = tokio::spawn(async move { task_pool.ping_all(0.0).await });+ tokio::time::timeout(Duration::from_secs(1), gate.entered.notified())+ .await+ .unwrap();+ assert!(pool.execution_authority_v1().load(Ordering::Acquire));+ gate.release.notify_one();+ refresh.await.unwrap();+ assert!(pool.execution_authority_v1().load(Ordering::Acquire));+ server.abort();+ }+fn pool_with_paths(paths: &[PathBuf]) -> Arc<AdapterWorkerPool> {let pool = AdapterWorkerPool::new(paths, 1, 1, 900, Arc::new(RuntimeState::new()));for child in &pool.children {diff --git a/packages/sie_server_sidecar/src/backend/mod.rs b/packages/sie_server_sidecar/src/backend/mod.rsindex d3eff1681..c7fef822a 100644--- a/packages/sie_server_sidecar/src/backend/mod.rs+++ b/packages/sie_server_sidecar/src/backend/mod.rs@@ -226,6 +226,18 @@ pub trait InferenceBackend: Send + Sync {self.run_batch(req).await}+ /// Verified work must never fall back to an older backend method.+ async fn run_batch_with_execution_authority_v1(+ &self,+ _req: RunBatchRequest,+ _budget: Option<Duration>,+ ) -> Result<BatchOutcome, BackendError> {+ Err(BackendError::UnsupportedModel(format!(+ "execution authority unsupported on {}",+ self.name()+ )))+ }+/// Graceful shutdown. Called once when the worker has stopped/// pulling from NATS. Backends should:///diff --git a/packages/sie_server_sidecar/src/backend/python_ipc.rs b/packages/sie_server_sidecar/src/backend/python_ipc.rsindex a99119950..efb0e4216 100644--- a/packages/sie_server_sidecar/src/backend/python_ipc.rs+++ b/packages/sie_server_sidecar/src/backend/python_ipc.rs@@ -125,6 +125,17 @@ impl InferenceBackend for PythonIpcBackend {.map_err(map_ipc_error)}+ async fn run_batch_with_execution_authority_v1(+ &self,+ req: RunBatchRequest,+ budget: Option<Duration>,+ ) -> Result<BatchOutcome, BackendError> {+ self.ipc+ .run_batch_with_execution_authority_v1(req, budget)+ .await+ .map_err(map_ipc_error)+ }+async fn drain(&self, deadline_ms: u64) {match self.ipc.drain(deadline_ms).await {Ok(resp) => debug!(diff --git a/packages/sie_server_sidecar/src/backend/router.rs b/packages/sie_server_sidecar/src/backend/router.rsindex 9ba05f342..205ae740b 100644--- a/packages/sie_server_sidecar/src/backend/router.rs+++ b/packages/sie_server_sidecar/src/backend/router.rs@@ -382,6 +382,29 @@ impl InferenceBackend for BackendRouter {result}+ async fn run_batch_with_execution_authority_v1(+ &self,+ req: RunBatchRequest,+ budget: Option<Duration>,+ ) -> Result<BatchOutcome, BackendError> {+ let model_id = req.model_id.clone();+ let batch_size = req.items.len();+ self.dispatch(+ &model_id,+ "run_batch_authority_v1",+ batch_size,+ move |backend| {+ let req = req.clone();+ async move {+ backend+ .run_batch_with_execution_authority_v1(req, budget)+ .await+ }+ },+ )+ .await+ }+async fn drain(&self, deadline_ms: u64) {self.drain_all(deadline_ms).await;}diff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rsindex 0623f69cc..2472c6b10 100644--- a/packages/sie_server_sidecar/src/config.rs+++ b/packages/sie_server_sidecar/src/config.rs@@ -364,6 +364,28 @@ impl WorkerConfig {crate::subject::normalize_model_id(&self.worker_id))}++ pub fn authority_stream_name(&self) -> String {+ format!(+ "WORK_AUTHORITY_V1_{}",+ crate::subject::normalize_model_id(&self.worker_id)+ )+ }++ pub fn authority_consumer_name(&self) -> String {+ format!(+ "authority-v1-{}",+ crate::subject::normalize_model_id(&self.worker_id)+ )+ }++ pub fn authority_subject_filter(&self) -> String {+ format!(+ "{}.{}",+ self.worker_subject_filter(),+ crate::subject::EXECUTION_AUTHORITY_V1_TOKEN+ )+ }}#[cfg(test)]diff --git a/packages/sie_server_sidecar/src/delivery.rs b/packages/sie_server_sidecar/src/delivery.rsindex 81de6bb39..943f58d10 100644--- a/packages/sie_server_sidecar/src/delivery.rs+++ b/packages/sie_server_sidecar/src/delivery.rs@@ -120,6 +120,19 @@ pub enum Delivery {}impl Delivery {+ pub fn execution_authority_model_matches(&self, model_id: &str) -> bool {+ match self {+ Self::Nats(message, ..) => {+ crate::subject::execution_authority_model_matches(&message.subject, model_id)+ }+ Self::Local(..) => true,+ }+ }++ pub fn requires_execution_authority_v1(&self) -> bool {+ matches!(self, Self::Nats(msg, ..) if crate::subject::requires_execution_authority_v1(&msg.subject))+ }+/// True when this delivery arrived worker-directly rather than via the/// pool subject: a NATS message on a worker-specific direct-dispatch/// subject, or any local-ingest delivery (the caller addressed THISdiff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 7c5737563..2e1c5bd10 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -53,7 +53,10 @@ use crate::scheduler::{ProductionSchedulerRegistry, SchedulerItem, SchedulerMeta,};use crate::shutdown::Shutdown;-use crate::subject::{extract_model_id, is_worker_direct_work_subject};+use crate::subject::{+ execution_authority_model_matches, extract_model_id, is_worker_direct_work_subject,+ requires_execution_authority_v1,+};use crate::tokenize::TokenizerRegistry;use crate::work_deadline::{apparent_age_ms, unix_now_s, ClockSkewSignal, DeadlineStatus, WorkDeadlinePolicy,@@ -666,6 +669,18 @@ pub struct Dispatcher {}impl Dispatcher {+ fn execution_authority_is_available(&self, wi: &WorkItem, needs_scheduler: bool) -> bool {+ !wi.bundle_config_hash.is_empty()+ && self.config_apply_state.is_some()+ && unknown_bundle_config_hash(std::iter::once(wi), self.config_apply_state.as_deref())+ .is_none()+ && self+ .worker_pool+ .execution_authority_v1()+ .load(Ordering::Acquire)+ && (!needs_scheduler || (self.scheduler_registry.is_some() && self.shutdown.is_some()))+ }+/// Construct with a default-sized concurrency semaphore from env.////// `scheduler_registry` + `shutdown` together gate the scheduler@@ -1268,6 +1283,23 @@ impl Dispatcher {};match rmp_serde::from_slice::<WorkItem>(&msg.payload) {Ok(mut wi) => {+ // This contract is derived from the consumer's versioned+ // subject, never an additive payload field an old worker+ // could ignore. Refuse before readiness or payload fetch.+ if requires_execution_authority_v1(&msg.subject)+ && (!execution_authority_model_matches(&msg.subject, &wi.model_id)+ || !self+ .execution_authority_is_available(&wi, wi.operation != "generate"))+ {+ nak_one_with_reason(+ &Delivery::Nats(msg, admission_permit, None),+ base_delay_ms,+ &self.runtime_state.telemetry,+ "execution_authority_unavailable",+ )+ .await;+ continue;+ }if !reply_subject_is_safe(&wi.reply_subject) {// ACK-to-drop (not NAK): the subject is attacker-// controlled; retrying just amplifies the attempt.@@ -1466,6 +1498,19 @@ impl Dispatcher {(!wi.profile_id.trim().is_empty()).then(|| wi.profile_id.trim().to_string());let delivery = DeliveryContext::from_message(&msg);let base_delay_ms = base_nak_delay_ms();+ if requires_execution_authority_v1(&msg.subject)+ && (!execution_authority_model_matches(&msg.subject, &wi.model_id)+ || !self.execution_authority_is_available(&wi, false))+ {+ nak_msg_with_reason(+ &msg,+ base_delay_ms,+ &self.runtime_state.telemetry,+ "execution_authority_unavailable",+ )+ .await;+ return;+ }info!(work_item_id = %wi.work_item_id,request_id = %wi.request_id,@@ -1982,9 +2027,10 @@ impl Dispatcher {// cancellation — would be entirely absent from the age distribution.record_work_item_ages(&self.runtime_state.telemetry, std::iter::once(&wi));self.runtime_state.inflight_batches.inc();+ let requires_authority = requires_execution_authority_v1(&msg.subject);let result = self.worker_pool- .process_generate(+ .process_generate_with_authority(ProcessGenerateRequest {model_id: model_id.clone(),work_item_msgpack,@@ -2010,6 +2056,7 @@ impl Dispatcher {.map_err(|e| IpcError::Server(e.to_string()))}},+ requires_authority,).await;decrement_gauge(&self.runtime_state.inflight_batches, 1);@@ -2205,6 +2252,14 @@ impl Dispatcher {let group_started = Instant::now();let group_size = items.len();let base_delay_ms = base_nak_delay_ms();+ if items.iter().any(|(wi, delivery)| {+ delivery.requires_execution_authority_v1()+ && (!delivery.execution_authority_model_matches(&wi.model_id)+ || !self.execution_authority_is_available(wi, true))+ }) {+ nak_all(&items, base_delay_ms, &self.runtime_state.telemetry).await;+ return Ok(());+ }if let Some((expected_hash, unknown_hash_count)) = unknown_bundle_config_hash(items.iter().map(|(wi, _)| wi),self.config_apply_state.as_deref(),@@ -5063,6 +5118,65 @@ async fn process_scheduler_batch(lora: crate::scheduler::LoraKey,batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,role: WaveRole,+) {+ assert_eq!(+ batch.items.len(),+ batch.metadata.len(),+ "FormattedBatch items and metadata must stay aligned"+ );+ // Keep the execution contracts separate even when the scheduler coalesces+ // a verified request with an older producer's empty-hash work. The legacy+ // sibling must not invalidate or downgrade the verified request's RPC.+ let flush_reason = batch.flush_reason;+ let mut partitions = [+ crate::scheduler::FormattedBatch {+ items: Vec::new(),+ metadata: Vec::new(),+ total_cost: 0,+ flush_reason,+ },+ crate::scheduler::FormattedBatch {+ items: Vec::new(),+ metadata: Vec::new(),+ total_cost: 0,+ flush_reason,+ },+ ];+ for (item, meta) in batch.items.into_iter().zip(batch.metadata) {+ let index = usize::from(!meta.delivery.requires_execution_authority_v1());+ partitions[index].total_cost += item.cost();+ partitions[index].items.push(item);+ partitions[index].metadata.push(meta);+ }+ let mut partition_role = role;+ for partition in partitions {+ if partition.items.is_empty() {+ continue;+ }+ process_scheduler_contract_batch(+ model_id,+ dispatcher,+ scheduler,+ op,+ lora.clone(),+ partition,+ partition_role,+ )+ .await;+ // Both RPCs retain one wave/pipeline permit. Preserve its Primary/Drain+ // roles and the configured controller cadence across the two RPCs.+ partition_role = WaveRole::Drain;+ }+}++async fn process_scheduler_contract_batch(+ model_id: &str,+ dispatcher: &Arc<Dispatcher>,+ scheduler: &Arc<ProductionScheduler>,+ op: SchedOp,+ lora: crate::scheduler::LoraKey,+ batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,+ role: WaveRole,) {if batch.items.is_empty() {return;@@ -5327,11 +5441,22 @@ async fn process_scheduler_batch(// the backend roundtrip.let dispatch_started_at = Instant::now();- let outcome = match dispatcher- .backend- .run_batch_with_budget(req, run_batch_budget)- .await- {+ let requires_authority = batch+ .metadata+ .iter()+ .any(|meta| meta.delivery.requires_execution_authority_v1());+ let result = if requires_authority {+ dispatcher+ .backend+ .run_batch_with_execution_authority_v1(req, run_batch_budget)+ .await+ } else {+ dispatcher+ .backend+ .run_batch_with_budget(req, run_batch_budget)+ .await+ };+ let outcome = match result {Ok(o) => o,Err(e) => {dispatcher.runtime_state.inflight_batches.dec();@@ -6744,6 +6869,88 @@ mod tests {Delivery::Nats(message, None, None)}+ async fn authority_test_delivery() -> Delivery {+ let mut delivery = unacknowledgeable_nats_delivery().await;+ if let Delivery::Nats(message, ..) = &mut delivery {+ message.message.subject =+ "sie.work.test.machine.bundle.cold.worker.execution-authority-v1".into();+ }+ delivery+ }++ #[tokio::test]+ async fn stale_authority_generation_refuses_before_readiness_or_payload_fetch() {+ let backend = LoadingModelBackend::new("cold");+ let mut dispatcher = dispatcher_with_backend(backend.clone());+ Arc::get_mut(&mut dispatcher).unwrap().config_apply_state =+ Some(Arc::new(ConfigApplyState::new("fresh".into())));+ dispatcher+ .worker_pool+ .execution_authority_v1()+ .store(true, Ordering::Release);+ let mut work = wi("verified", 0, "cold", "generate");+ work.bundle_config_hash = "stale".into();+ work.payload_ref = Some("must-not-fetch".into());+ let Delivery::Nats(message, permit, _) = authority_test_delivery().await else {+ unreachable!()+ };+ dispatcher+ .handle_generate_item(work, QueuedMessage::new(message, permit))+ .await;+ assert_eq!(backend.probes.load(Ordering::SeqCst), 0);+ assert!(backend.encoded_models().is_empty());+ }++ #[tokio::test]+ async fn mismatched_authority_generation_refuses_before_readiness_or_payload_fetch() {+ let backend = LoadingModelBackend::new("cold");+ let mut dispatcher = dispatcher_with_backend(backend.clone());+ Arc::get_mut(&mut dispatcher).unwrap().config_apply_state =+ Some(Arc::new(ConfigApplyState::new("fresh".into())));+ dispatcher+ .worker_pool+ .execution_authority_v1()+ .store(true, Ordering::Release);+ let mut work = wi("verified", 0, "another", "generate");+ work.bundle_config_hash = "fresh".into();+ work.payload_ref = Some("must-not-fetch".into());+ let Delivery::Nats(message, permit, _) = authority_test_delivery().await else {+ unreachable!()+ };+ dispatcher+ .handle_generate_item(work, QueuedMessage::new(message, permit))+ .await;+ assert_eq!(backend.probes.load(Ordering::SeqCst), 0);+ assert!(backend.encoded_models().is_empty());+ }++ #[tokio::test]+ async fn half_wired_scheduler_cannot_downgrade_verified_numeric_work() {+ let backend = LoadingModelBackend::new("cold");+ let mut dispatcher = dispatcher_with_backend(backend.clone());+ let mutable = Arc::get_mut(&mut dispatcher).unwrap();+ mutable.config_apply_state = Some(Arc::new(ConfigApplyState::new("fresh".into())));+ mutable.scheduler_registry = Some(Arc::new(ProductionSchedulerRegistry::new(+ crate::scheduler::BatchConfig::from_env_or_default(),+ )));+ mutable.shutdown = None;+ dispatcher+ .worker_pool+ .execution_authority_v1()+ .store(true, Ordering::Release);+ let mut work = wi("verified", 0, "cold", "encode");+ work.bundle_config_hash = "fresh".into();+ dispatcher+ .dispatch_decoded(+ vec![(work, authority_test_delivery().await)],+ 1,+ Instant::now(),+ )+ .await;+ assert_eq!(backend.probes.load(Ordering::SeqCst), 0);+ assert!(backend.encoded_models().is_empty());+ }+#[tokio::test(start_paused = true)]async fn a_failed_progress_ack_ends_the_parked_wait() {let slow_probe = Duration::from_secs(crate::nats_consumer::ACK_WAIT_SECS * 3);diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rsindex 9ec3d7cb3..1d094cdb5 100644--- a/packages/sie_server_sidecar/src/health_publisher.rs+++ b/packages/sie_server_sidecar/src/health_publisher.rs@@ -41,6 +41,7 @@//! [`WorkerStatusMessage`]: https://github.com/superlinked/sie/blob/main/packages/sie_gateway/src/types/worker.rs//! [`resolve_queue_route`]: https://github.com/superlinked/sie/blob/main/packages/sie_gateway/src/state/worker_registry.rs+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::sync::RwLock;use std::time::Duration;@@ -113,6 +114,10 @@ pub struct HealthPublisherConfig {/// Models the colocated backend reports as loaded. Updated by the IPC/// heartbeat, not by config apply.pub loaded_models: SharedLoadedModels,+ /// Positive only when every backend child supports the method fence.+ pub execution_authority_v1: Arc<AtomicBool>,+ /// The versioned pull consumer must also be running.+ pub authority_consumer_ready: Arc<AtomicBool>,/// Runtime pressure/capacity gauges mirrored into the heartbeat payload.pub runtime_state: Arc<RuntimeState>,/// How often to publish. Defaults to [`DEFAULT_PUBLISH_INTERVAL`].@@ -144,6 +149,7 @@ struct WorkerStatusPayload<'a> {name: &'a str,ready: bool,terminated: bool,+ supports_execution_authority_v1: bool,gpu_count: i32,total_gpu_slots: i32,ready_gpu_slots: i32,@@ -222,6 +228,11 @@ fn encode_payload(name: &config.worker_id,ready,terminated,+ supports_execution_authority_v1: ready+ && !terminated+ && !hash.is_empty()+ && config.execution_authority_v1.load(Ordering::Acquire)+ && config.authority_consumer_ready.load(Ordering::Acquire),gpu_count: config.gpu_count,total_gpu_slots,ready_gpu_slots,@@ -415,6 +426,8 @@ mod tests {bundle_config_hash: Arc::new(RwLock::new("hash-abc".into())),unsupported_models: Arc::new(RwLock::new(Vec::new())),loaded_models: Arc::new(RwLock::new(Vec::new())),+ execution_authority_v1: Arc::new(AtomicBool::new(false)),+ authority_consumer_ready: Arc::new(AtomicBool::new(false)),runtime_state: Arc::new(RuntimeState::new()),interval: DEFAULT_PUBLISH_INTERVAL,}@@ -429,6 +442,29 @@ mod tests {assert_eq!(cfg().subject(), "sie.health.worker-l4-0");}+ #[test]+ fn authority_health_requires_every_positive_prerequisite() {+ for missing in ["none", "backend", "consumer", "hash", "ready", "terminated"] {+ let c = cfg();+ c.execution_authority_v1+ .store(missing != "backend", Ordering::Release);+ c.authority_consumer_ready+ .store(missing != "consumer", Ordering::Release);+ if missing == "hash" {+ c.bundle_config_hash.write().unwrap().clear();+ }+ let payload: serde_json::Value = serde_json::from_slice(+ &encode_payload(&c, missing != "ready", missing == "terminated").unwrap(),+ )+ .unwrap();+ assert_eq!(+ payload["supports_execution_authority_v1"],+ missing == "none",+ "{missing}"+ );+ }+ }+#[test]fn payload_roundtrips_to_gateway_shape() {// Serialises to the exact field set@@ -441,6 +477,7 @@ mod tests {name: &c.worker_id,ready: true,terminated: false,+ supports_execution_authority_v1: false,gpu_count: c.gpu_count,total_gpu_slots: 1,ready_gpu_slots: 1,@@ -487,6 +524,7 @@ mod tests {name: &c.worker_id,ready: true,terminated: false,+ supports_execution_authority_v1: false,gpu_count: c.gpu_count,total_gpu_slots: 1,ready_gpu_slots: 1,diff --git a/packages/sie_server_sidecar/src/ipc_client.rs b/packages/sie_server_sidecar/src/ipc_client.rsindex e58f041aa..de4151482 100644--- a/packages/sie_server_sidecar/src/ipc_client.rs+++ b/packages/sie_server_sidecar/src/ipc_client.rs@@ -52,9 +52,10 @@ use crate::ipc_types::{SetPinnedModelsResponse, SignalGenerateCancelRequest, SignalGenerateCancelResponse,WorkerCapabilitiesRequest, WorkerCapabilitiesResponse, IPC_VERSION, METHOD_APPLY_MODEL_CONFIG,METHOD_DRAIN, METHOD_ENSURE_MODEL_READY, METHOD_PING, METHOD_PROCESS_ENCODE_BATCH,- METHOD_PROCESS_EXTRACT_BATCH, METHOD_PROCESS_GENERATE, METHOD_PROCESS_SCORE_BATCH,- METHOD_REPLACE_MODEL_CONFIGS, METHOD_RUN_BATCH, METHOD_SET_PINNED_MODELS,- METHOD_SIGNAL_GENERATE_CANCEL, METHOD_WORKER_CAPABILITIES,+ METHOD_PROCESS_EXTRACT_BATCH, METHOD_PROCESS_GENERATE,+ METHOD_PROCESS_GENERATE_WITH_EXECUTION_AUTHORITY_V1, METHOD_PROCESS_SCORE_BATCH,+ METHOD_REPLACE_MODEL_CONFIGS, METHOD_RUN_BATCH, METHOD_RUN_BATCH_WITH_EXECUTION_AUTHORITY_V1,+ METHOD_SET_PINNED_MODELS, METHOD_SIGNAL_GENERATE_CANCEL, METHOD_WORKER_CAPABILITIES,};use crate::log_util::ErrChain;use crate::observability::metrics::SidecarTelemetry;@@ -903,9 +904,40 @@ impl IpcClient {/// message settlement; the backend owns generation adapter execution and/// chunk encoding.pub async fn process_generate<F, Fut>(+ &self,+ req: ProcessGenerateRequest,+ on_event: F,+ ) -> Result<(), IpcError>+ where+ F: FnMut(GenerateEvent) -> Fut,+ Fut: std::future::Future<Output = Result<(), IpcError>>,+ {+ self.process_generate_method(req, on_event, METHOD_PROCESS_GENERATE)+ .await+ }++ pub async fn process_generate_with_execution_authority_v1<F, Fut>(+ &self,+ req: ProcessGenerateRequest,+ on_event: F,+ ) -> Result<(), IpcError>+ where+ F: FnMut(GenerateEvent) -> Fut,+ Fut: std::future::Future<Output = Result<(), IpcError>>,+ {+ self.process_generate_method(+ req,+ on_event,+ METHOD_PROCESS_GENERATE_WITH_EXECUTION_AUTHORITY_V1,+ )+ .await+ }++ async fn process_generate_method<F, Fut>(&self,req: ProcessGenerateRequest,mut on_event: F,+ method: &'static str,) -> Result<(), IpcError>whereF: FnMut(GenerateEvent) -> Fut,@@ -914,7 +946,7 @@ impl IpcClient {let request_id = self.next_id();let envelope = RequestEnvelope {version: IPC_VERSION,- method: METHOD_PROCESS_GENERATE,+ method,request_id: request_id.clone(),accepts_ipc_response_chunks_v1: false,body: req,@@ -929,7 +961,7 @@ impl IpcClient {Ok(()) => "ok",Err(e) => error_label(e),};- self.record_rpc(METHOD_PROCESS_GENERATE, start, label);+ self.record_rpc(method, start, label);result}@@ -1062,6 +1094,19 @@ impl IpcClient {.await}+ pub async fn run_batch_with_execution_authority_v1(+ &self,+ req: RunBatchRequest,+ budget: Option<Duration>,+ ) -> Result<BatchOutcome, IpcError> {+ self.call_with_timeout(+ METHOD_RUN_BATCH_WITH_EXECUTION_AUTHORITY_V1,+ req,+ self.run_batch_timeout(budget),+ )+ .await+ }+fn run_batch_timeout(&self, budget: Option<Duration>) -> Duration {budget.map_or(self.request_timeout, |budget| {budget.max(self.request_timeout)@@ -1294,6 +1339,74 @@ mod tests {);}+ #[tokio::test]+ async fn authority_methods_reject_old_backend_without_legacy_retry() {+ let path = short_sock_path();+ let calls = Arc::new(std::sync::Mutex::new(Vec::new()));+ let recorded = Arc::clone(&calls);+ let server = spawn_echo_async(path.clone(), move |bytes| {+ let req: rmpv::Value = rmp_serde::from_slice(&bytes).unwrap();+ let field = |name| {+ req.as_map()+ .unwrap()+ .iter()+ .find(|(key, _)| key.as_str() == Some(name))+ .unwrap()+ .1+ .as_str()+ .unwrap()+ .to_string()+ };+ let method = field("method");+ let request_id = field("request_id");+ recorded.lock().unwrap().push(method);+ async move {+ rmp_serde::to_vec_named(&serde_json::json!({+ "version": IPC_VERSION,+ "request_id": request_id,+ "ok": false,+ "body": null,+ "error": "unknown method",+ }))+ .unwrap()+ }+ })+ .await;+ let client = IpcClient::new(&path);+ let result = client+ .run_batch_with_execution_authority_v1(+ RunBatchRequest {+ model_id: "m".into(),+ batch_id: 1,+ lora_key: String::new(),+ total_cost: 1,+ items: Vec::new(),+ accepts_batched_f16_multivectors: true,+ },+ None,+ )+ .await;+ assert!(matches!(result, Err(IpcError::Server(_))));+ let result = client+ .process_generate_with_execution_authority_v1(+ ProcessGenerateRequest {+ model_id: "m".into(),+ work_item_msgpack: Vec::new(),+ },+ |_| async { panic!("old backend must not produce a generation event") },+ )+ .await;+ assert!(matches!(result, Err(IpcError::Server(_))));+ assert_eq!(+ *calls.lock().unwrap(),+ [+ METHOD_RUN_BATCH_WITH_EXECUTION_AUTHORITY_V1,+ METHOD_PROCESS_GENERATE_WITH_EXECUTION_AUTHORITY_V1,+ ]+ );+ server.abort();+ }+#[tokio::test]async fn run_batch_budget_outlasts_a_shorter_request_timeout() {let path = short_sock_path();diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex 21c9588c6..0d6b68559 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -63,9 +63,9 @@ use crate::dispatcher::{Dispatcher, QueuedMessage};use crate::latency::{FetchExpiryController, LatencyTracker};use crate::log_util::ErrChain;use crate::nats_consumer::{- connect, ensure_stream_and_consumer, ensure_worker_stream_and_consumer,- reconcile_stream_and_consumer, reconcile_worker_stream_and_consumer, work_cancel_tombstone_ttl,- NatsConsumer,+ connect, ensure_authority_stream_and_consumer, ensure_stream_and_consumer,+ ensure_worker_stream_and_consumer, reconcile_stream_and_consumer,+ reconcile_worker_stream_and_consumer, work_cancel_tombstone_ttl, NatsConsumer,};use crate::payload_store::{create_payload_store, with_telemetry as payload_store_with_telemetry};use crate::pool_admission::PoolAdmissionGate;@@ -562,6 +562,8 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {bundle_config_hash: config_apply_state.bundle_config_hash(),unsupported_models: config_apply_state.unsupported_models(),loaded_models: Arc::clone(&loaded_models),+ execution_authority_v1: worker_pool.execution_authority_v1(),+ authority_consumer_ready: Arc::clone(&generation_direct_dispatch.authority_active),runtime_state: Arc::clone(&runtime_state),interval: Duration::from_millis(config.health_publish_interval_ms),})@@ -956,6 +958,7 @@ pub async fn run_local(config: WorkerConfig) -> anyhow::Result<()> {#[derive(Default)]struct GenerationDirectHandles {pull: Option<JoinHandle<()>>,+ authority_pull: Option<JoinHandle<()>>,generation_cancel: Option<JoinHandle<()>>,batch_cancel: Option<JoinHandle<()>>,work_cancel: Option<JoinHandle<()>>,@@ -977,6 +980,7 @@ struct GenerationDirectDispatch {pool_admission: Option<Arc<PoolAdmissionGate>>,worker_pool: Arc<AdapterWorkerPool>,active: Arc<AtomicBool>,+ authority_active: Arc<AtomicBool>,batch_cancel_state: BatchCancelState,request_cancel_state: RequestCancelState,handles: Mutex<GenerationDirectHandles>,@@ -1009,6 +1013,7 @@ impl GenerationDirectDispatch {pool_admission,worker_pool,active,+ authority_active: Arc::new(AtomicBool::new(false)),batch_cancel_state,request_cancel_state,handles: Mutex::new(GenerationDirectHandles::default()),@@ -1091,8 +1096,49 @@ impl GenerationDirectDispatch {Arc::clone(&self.shutdown),);+ let authority_dispatcher = Arc::clone(&self.dispatcher);+ let authority_shutdown = Arc::clone(&self.shutdown);+ let authority_fetch_ctrl = self.fetch_ctrl.clone();+ let authority_latency_tracker = Arc::clone(&self.latency_tracker);+ let authority_pool_admission = self.pool_admission.clone();+ let authority_active = Arc::clone(&self.authority_active);+ let authority_jetstream = self.jetstream.clone();+ let authority_config = self.config.clone();+ let authority_pull = tokio::spawn(async move {+ // Authority setup is independent of the ordinary pull loops. Keep+ // its capability closed and retry boundedly while legacy work runs.+ let authority_consumer = loop {+ let result = tokio::select! {+ _ = authority_shutdown.wait() => return,+ result = ensure_authority_stream_and_consumer(&authority_jetstream, &authority_config) => result,+ };+ match result {+ Ok(consumer) => break consumer,+ Err(error) => {+ warn!(%error, "authority consumer setup failed; retrying without blocking ordinary dispatch")+ }+ }+ tokio::select! {+ _ = authority_shutdown.wait() => return,+ _ = tokio::time::sleep(Duration::from_secs(5)) => {},+ }+ };+ let _ready = AuthorityConsumerReady(Arc::clone(&authority_active));+ authority_active.store(true, Ordering::Release);+ run_pull_loop(+ &NatsConsumer::new(authority_consumer),+ authority_dispatcher,+ authority_shutdown,+ &authority_fetch_ctrl,+ authority_latency_tracker,+ authority_pool_admission,+ )+ .await;+ });+let mut handles = self.handles.lock().await;handles.pull = Some(pull);+ handles.authority_pull = Some(authority_pull);handles.generation_cancel = Some(generation_cancel);handles.batch_cancel = Some(batch_cancel);handles.work_cancel = Some(work_cancel);@@ -1105,6 +1151,7 @@ impl GenerationDirectDispatch {let mut guard = self.handles.lock().await;GenerationDirectHandles {pull: guard.pull.take(),+ authority_pull: guard.authority_pull.take(),generation_cancel: guard.generation_cancel.take(),batch_cancel: guard.batch_cancel.take(),work_cancel: guard.work_cancel.take(),@@ -1117,6 +1164,12 @@ impl GenerationDirectDispatch {}let _ = h.await;}+ if let Some(h) = handles.authority_pull {+ if !h.is_finished() {+ h.abort();+ }+ let _ = h.await;+ }if let Some(h) = handles.generation_cancel {h.abort();let _ = h.await;@@ -1132,6 +1185,14 @@ impl GenerationDirectDispatch {}}+struct AuthorityConsumerReady(Arc<AtomicBool>);++impl Drop for AuthorityConsumerReady {+ fn drop(&mut self) {+ self.0.store(false, Ordering::Release);+ }+}+fn spawn_nats_consumer_reconciler(jetstream: async_nats::jetstream::Context,config: WorkerConfig,@@ -1166,6 +1227,9 @@ fn spawn_nats_consumer_reconciler("nats-consumer: worker direct-dispatch reconcile failed"),}+ if let Err(e) = ensure_authority_stream_and_consumer(&jetstream, &config).await {+ warn!(error = %e, "nats-consumer: execution authority stream/durable reconcile failed");+ }}}}))diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rsindex a780ef9e7..5598b2a13 100644--- a/packages/sie_server_sidecar/src/nats_consumer.rs+++ b/packages/sie_server_sidecar/src/nats_consumer.rs@@ -601,9 +601,36 @@ pub async fn ensure_worker_stream_and_consumer(js: &JsContext,config: &WorkerConfig,) -> Result<PullConsumer, NatsSetupError> {- let stream_name = config.worker_stream_name();- let subject = config.worker_subject_filter();- let consumer_name = config.worker_consumer_name();+ ensure_direct_stream_and_consumer(js, config, false).await+}++/// Separate, bounded durable authority stream; older worker reconciliation+/// only knows its ordinary stream and cannot broaden this consumer's filter.+pub async fn ensure_authority_stream_and_consumer(+ js: &JsContext,+ config: &WorkerConfig,+) -> Result<PullConsumer, NatsSetupError> {+ ensure_direct_stream_and_consumer(js, config, true).await+}++async fn ensure_direct_stream_and_consumer(+ js: &JsContext,+ config: &WorkerConfig,+ authority_v1: bool,+) -> Result<PullConsumer, NatsSetupError> {+ let (stream_name, subject, consumer_name) = if authority_v1 {+ (+ config.authority_stream_name(),+ config.authority_subject_filter(),+ config.authority_consumer_name(),+ )+ } else {+ (+ config.worker_stream_name(),+ config.worker_subject_filter(),+ config.worker_consumer_name(),+ )+ };let desired_max_age = Duration::from_secs(generation_stream_max_age_secs());let desired_storage = stream_storage();diff --git a/packages/sie_server_sidecar/src/subject.rs b/packages/sie_server_sidecar/src/subject.rsindex a00c74912..1245c80fa 100644--- a/packages/sie_server_sidecar/src/subject.rs+++ b/packages/sie_server_sidecar/src/subject.rs@@ -15,6 +15,23 @@ const MIN_SUBJECT_PARTS: usize = 6;/// Exact token count for worker-direct work subjects.const DIRECT_WORK_SUBJECT_PARTS: usize = 7;+/// Incompatible execution contract: older pool/direct filters have fewer tokens.+pub const EXECUTION_AUTHORITY_V1_TOKEN: &str = "execution-authority-v1";++pub fn requires_execution_authority_v1(subject: &str) -> bool {+ let parts: Vec<&str> = subject.split('.').collect();+ parts.len() == DIRECT_WORK_SUBJECT_PARTS + 1+ && parts.first() == Some(&"sie")+ && parts.get(1) == Some(&"work")+ && parts.last() == Some(&EXECUTION_AUTHORITY_V1_TOKEN)+}++/// Verified subjects may not silently retarget a lossy-normalized model id.+pub fn execution_authority_model_matches(subject: &str, model_id: &str) -> bool {+ !requires_execution_authority_v1(subject)+ || extract_model_id(subject).as_deref() == Some(model_id)+}+/// Inverse of [`normalize_model_id`]. Best-effort: `__` → `/`, `_dot_` → `.`.pub fn denormalize_model_id(normalized: &str) -> String {normalized.replace("__", "/").replace("_dot_", ".")@@ -41,7 +58,7 @@ pub fn extract_model_id(subject: &str) -> Option<String> {/// True when the subject addresses one concrete worker rather than the pool.pub fn is_worker_direct_work_subject(subject: &str) -> bool {let parts: Vec<&str> = subject.split('.').collect();- parts.len() == DIRECT_WORK_SUBJECT_PARTS+ (parts.len() == DIRECT_WORK_SUBJECT_PARTS || requires_execution_authority_v1(subject))&& parts.first() == Some(&"sie")&& parts.get(1) == Some(&"work")}@@ -106,6 +123,49 @@ mod tests {assert_eq!(normalize_model_id("a/b.c"), "a__b_dot_c");}+ #[test]+ fn execution_authority_subject_excludes_legacy_consumer_filters() {+ let subject = "sie.work.pool.machine.bundle.model.worker.execution-authority-v1";+ assert!(requires_execution_authority_v1(subject));+ assert!(is_worker_direct_work_subject(subject));+ assert_eq!(extract_model_id(subject), Some("model".into()));+ assert!(!subjects_overlap("sie.work.pool.*.*.*", subject));+ assert!(!subjects_overlap(+ "sie.work.pool.machine.bundle.*.worker",+ subject+ ));+ for invalid in [+ "sie.work.pool.machine.bundle.model.worker",+ "sie.work.pool.machine.bundle.model.worker.execution-authority-v2",+ "sie.work.pool.machine.bundle.model.worker.extra.execution-authority-v1",+ ] {+ assert!(!requires_execution_authority_v1(invalid));+ }+ }++ #[test]+ fn authority_subject_cannot_retarget_normalization_collisions() {+ for (original, decoded) in [+ ("Org__model", "Org/model"),+ ("Org/model_dot_v1", "Org/model.v1"),+ ] {+ let subject = format!(+ "sie.work.pool.machine.bundle.{}.worker.execution-authority-v1",+ normalize_model_id(original)+ );+ assert!(!execution_authority_model_matches(&subject, original));+ assert!(execution_authority_model_matches(&subject, decoded));+ assert!(execution_authority_model_matches(+ "sie.work.pool.machine.bundle.legacy.worker",+ original+ ));+ }+ assert!(execution_authority_model_matches(+ "sie.work.pool.machine.bundle.Org__model.worker.execution-authority-v1",+ "Org/model"+ ));+ }+#[test]fn denormalize_is_inverse_of_normalize_for_safe_ids() {for id in ["BAAI/bge-m3", "openai/text-embedding-3-small", "x.y"] {diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rsindex bec9bac2f..dc30116a6 100644--- a/packages/sie_server_sidecar/tests/integration_smoke.rs+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs@@ -1283,6 +1283,19 @@ async fn smoke_generation_direct_dispatch_is_active_before_capability_reconcile(let pool = "smoke-gen-hot-add";let bundle = "default";+ let client = async_nats::connect(&nats.url)+ .await+ .expect("client connect");+ let js = async_nats::jetstream::new(client.clone());+ js.create_stream(async_nats::jetstream::stream::Config {+ name: "AUTHORITY_SETUP_BLOCKER".into(),+ subjects: vec![format!(+ "sie.work.{pool}.{pool}.{bundle}.*.smoke-worker.execution-authority-v1"+ )],+ ..Default::default()+ })+ .await+ .expect("create temporary authority subject conflict");let probe_port = find_free_tcp_port();let _worker =WorkerHarness::spawn_with_env(&nats.url, &sock.path, pool, bundle, probe_port, None, &[]);@@ -1364,6 +1377,27 @@ async fn smoke_generation_direct_dispatch_is_active_before_capability_reconcile(assert_eq!(body["smoke"], "generate");assert_eq!(body["model_id"], model_id);assert_eq!(body["request_id"], request_id);+ assert!(js+ .get_stream("WORK_AUTHORITY_V1_smoke-worker")+ .await+ .is_err());+ js.delete_stream("AUTHORITY_SETUP_BLOCKER")+ .await+ .expect("remove temporary authority conflict");+ timeout(Duration::from_secs(15), async {+ loop {+ if js+ .get_stream("WORK_AUTHORITY_V1_smoke-worker")+ .await+ .is_ok()+ {+ break;+ }+ sleep(Duration::from_millis(100)).await;+ }+ })+ .await+ .expect("authority setup retries and recovers");drop(_worker);drop(python);@@ -3352,5 +3386,84 @@ async fn ensure_paths_reconcile_stream_discard_policy_to_new() {);}+ // Verified work lives on a separately named, bounded stream. Replacing+ // this worker with an older binary can only reconcile its pool/direct+ // streams; it cannot make those old filters receive the verified work.+ let authority =+ sie_server_sidecar::nats_consumer::ensure_authority_stream_and_consumer(&js, &config)+ .await+ .expect("authority stream and consumer");+ let subject = config.authority_subject_filter().replace('*', "model");+ js.publish(subject.clone(), "verified-work".into())+ .await+ .unwrap()+ .await+ .unwrap();+ sie_server_sidecar::nats_consumer::ensure_stream_and_consumer(&js, &config)+ .await+ .unwrap();+ sie_server_sidecar::nats_consumer::ensure_worker_stream_and_consumer(&js, &config)+ .await+ .unwrap();+ for name in [config.stream_name(), config.worker_stream_name()] {+ assert_eq!(+ js.get_stream(name)+ .await+ .unwrap()+ .info()+ .await+ .unwrap()+ .state+ .messages,+ 0+ );+ }+ let mut stream = js.get_stream(config.authority_stream_name()).await.unwrap();+ let info = stream.info().await.unwrap();+ assert_eq!(info.config.subjects, [config.authority_subject_filter()]);+ assert!(info.config.max_messages > 0);+ assert!(!info.config.max_age.is_zero());+ assert_eq!(info.state.messages, 1);+ let mut messages = authority+ .stream()+ .max_messages_per_batch(1)+ .expires(Duration::from_millis(100))+ .messages()+ .await+ .unwrap();+ let delivery = timeout(Duration::from_secs(3), messages.next())+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ assert_eq!(delivery.subject.as_str(), subject);+ delivery+ .ack_with(async_nats::jetstream::AckKind::Nak(None))+ .await+ .unwrap();+ drop(messages);++ // A newer worker may resume the same durable and recheck live authority.+ // Redelivery stays on the authority contract rather than the legacy pool.+ let resumed =+ sie_server_sidecar::nats_consumer::ensure_authority_stream_and_consumer(&js, &config)+ .await+ .unwrap();+ let mut messages = resumed+ .stream()+ .max_messages_per_batch(1)+ .expires(Duration::from_millis(100))+ .messages()+ .await+ .unwrap();+ let redelivery = timeout(Duration::from_secs(3), messages.next())+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ assert_eq!(redelivery.subject.as_str(), subject);+ assert!(redelivery.info().unwrap().delivered >= 2);+ redelivery.double_ack().await.unwrap();+drop(nats);}diff --git a/packages/wire-fixtures/worker_status.json b/packages/wire-fixtures/worker_status.jsonindex abf30631e..37c65c068 100644--- a/packages/wire-fixtures/worker_status.json+++ b/packages/wire-fixtures/worker_status.json@@ -4,6 +4,7 @@"name","ready","terminated",+ "supports_execution_authority_v1","gpu_count","total_gpu_slots","ready_gpu_slots",@@ -25,6 +26,7 @@"name": "worker-l4-0","ready": true,"terminated": false,+ "supports_execution_authority_v1": true,"gpu_count": 1,"total_gpu_slots": 1,"ready_gpu_slots": 1,