Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

49.7 KB
Raw Blame
//! Handler test fixtures: a gateway with a local lane and a remote lane, and a
//! dispatcher that records what it publishes and answers every request.

use std::any::Any;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use serde_json::json;
use tokio::sync::{broadcast, oneshot, Notify};

use crate::config::{Config, StreamStorage};
use crate::queue::dispatch::{
    ChunkEnvelope, DispatchBackpressure, DispatchDurability, DispatchError,
    PendingGenerationSnapshot, PublishTarget, StreamOutcome, WorkDispatcher, WorkParams,
    WorkResult,
};
use crate::queue::lane_admission::LaneKey;
use crate::queue::streaming::{ChunkApplied, StreamCollector};
use crate::server::AppState;
use crate::state::config_epoch::ConfigEpoch;
use crate::state::demand_tracker::{DemandTracker, PhysicalLane, PhysicalLaneCatalog};
use crate::state::model_registry::ModelRegistry;
use crate::state::pool_manager::PoolManager;
use crate::state::worker_registry::WorkerRegistry;
use crate::types::model::FallbackTrigger;
use crate::types::WorkerStatusMessage;

/// The local lane's `(pool, machine_profile, bundle)`.
pub(crate) const LOCAL_LANE: (&str, &str, &str) = ("default", "l4", "default");
/// The remote lane's `(pool, machine_profile, bundle)`.
pub(crate) const REMOTE_LANE: (&str, &str, &str) = ("default", "cpu", "remote");

const DEFAULT_BUNDLE: &str = "name: default\ndefault: true\nadapters:\n  - sie_server.adapters.bert_flash\n  - sie_server.adapters.sglang\n  - sie_server.adapters.whisper.adapter\n  - sie_server.adapters.gliner2.decide\n  - sie_server.adapters.remote.sie\n";
const REMOTE_BUNDLE: &str =
    "name: remote\npriority: 1\ndefault: false\nadapters:\n  - sie_server.adapters.remote.sie\n";

/// A local encode model.
pub(crate) const LOCAL_ENCODE_MODEL: &str = "\
sie_id: acme/local
hf_id: acme/local
tasks:
  encode:
    dense:
      dim: 2
profiles:
  default:
    adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter
    max_batch_tokens: 4096
";

/// An encode model with no local weights, served by the `team-sie` upstream.
pub(crate) const REMOTE_ENCODE_MODEL: &str = "\
sie_id: acme/remote
remote_backed: true
tasks:
  encode:
    dense:
      dim: 2
profiles:
  default:
    adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter
    max_batch_tokens: 8192
    adapter_options:
      loadtime:
        upstream: team-sie
        upstream_model: acme/remote
";

/// An encode model served locally, with a remote profile on `team-sie`.
pub(crate) const HYBRID_ENCODE_MODEL: &str = "\
sie_id: acme/hybrid-encode
hf_id: acme/hybrid-encode
tasks:
  encode:
    dense:
      dim: 2
profiles:
  default:
    adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter
    max_batch_tokens: 4096
  remote:
    adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter
    max_batch_tokens: 8192
    adapter_options:
      loadtime:
        upstream: team-sie
        upstream_model: acme/hybrid-encode
";

/// A generation model served locally, with a remote profile on `team-sie`.
pub(crate) const HYBRID_GENERATE_MODEL: &str = "\
sie_id: acme/chat
hf_id: acme/chat
tasks:
  generate: {}
profiles:
  default:
    adapter_path: sie_server.adapters.sglang:SGLangAdapter
    max_batch_tokens: 8192
  remote:
    adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter
    max_batch_tokens: 8192
    adapter_options:
      loadtime:
        upstream: team-sie
        upstream_model: acme/chat
";

/// An extraction model with local audio weights and a native SIE bridge.
pub(crate) const HYBRID_EXTRACT_MODEL: &str = "\
sie_id: acme/extract
hf_id: acme/extract
inputs:
  audio: true
tasks:
  extract: {}
profiles:
  default:
    adapter_path: sie_server.adapters.whisper.adapter:WhisperAdapter
    max_batch_tokens: 8192
  remote:
    adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter
    max_batch_tokens: 8192
    adapter_options:
      loadtime:
        upstream: team-sie
        upstream_model: acme/extract
";

/// A local typed-decision model (GLiNER2.5-Decide) for `/v1/systemone`.
pub(crate) const LOCAL_DECISION_MODEL: &str = "\
sie_id: acme/decide
hf_id: acme/decide
tasks:
  extract: {}
profiles:
  default:
    adapter_path: sie_server.adapters.gliner2.decide:GLiNER2DecideAdapter
    max_batch_tokens: 8192
";

/// One request as the transport received it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Dispatched {
    pub endpoint: String,
    pub pool: String,
    pub machine_profile: String,
    pub bundle: String,
    pub model: String,
}

impl Dispatched {
    fn new(endpoint: &str, target: &PublishTarget) -> Self {
        Self {
            endpoint: endpoint.to_string(),
            pool: target.pool().to_string(),
            machine_profile: target.machine_profile().to_string(),
            bundle: target.bundle().to_string(),
            model: target.model().to_string(),
        }
    }
}

/// A dispatcher that records every publish and answers it at once, unless a
/// test withholds remote answers.
#[derive(Default)]
pub(crate) struct RecordingDispatcher {
    without_execution_authority: AtomicBool,
    local_backpressure: AtomicBool,
    local_lane_cold: AtomicBool,
    remote_lane_starting: AtomicBool,
    load_refused: AtomicBool,
    generate_refused: AtomicBool,
    work_refused: AtomicBool,
    extract_data: Mutex<Option<serde_json::Value>>,
    stream_error: AtomicBool,
    stream_mid_error: AtomicBool,
    stream_terminal_failure: Mutex<Option<&'static str>>,
    remote_refusal: Mutex<Option<(&'static str, Option<u32>)>>,
    remote_failure_reason: Mutex<Option<&'static str>>,
    remote_silence: Mutex<Option<bool>>,
    unanswered: Mutex<Vec<Box<dyn Any + Send>>>,
    first_chunk_republish: AtomicBool,
    bridged_refusal: Mutex<Option<(&'static str, u32)>>,
    redelivered: Mutex<Vec<oneshot::Sender<Vec<WorkResult>>>>,
    dispatched: Mutex<Vec<Dispatched>>,
    execution_authority: Mutex<Vec<bool>>,
    fallback_reasons: Mutex<Vec<Option<FallbackTrigger>>>,
    numerical_admissions: Mutex<Vec<Option<String>>>,
    on_model_load: Mutex<Option<Box<dyn FnOnce() + Send>>>,
    on_remote_work: Mutex<Option<RemoteWorkAction>>,
    provisioning_estimates: Mutex<HashMap<LaneKey, Duration>>,
}

type RemoteWorkAction = Box<dyn FnOnce(&RecordingDispatcher) + Send>;

impl RecordingDispatcher {
    /// Estimate that the `(pool, machine_profile, bundle)` lane needs
    /// `estimate` before it can accept work.
    pub(crate) fn estimate_provisioning(&self, lane: (&str, &str, &str), estimate: Duration) {
        self.provisioning_estimates
            .lock()
            .unwrap()
            .insert(LaneKey::new(lane.0, lane.1, lane.2), estimate);
    }

    /// Stop estimating the `(pool, machine_profile, bundle)` lane.
    pub(crate) fn forget_provisioning_estimate(&self, lane: (&str, &str, &str)) {
        self.provisioning_estimates
            .lock()
            .unwrap()
            .remove(&LaneKey::new(lane.0, lane.1, lane.2));
    }

    /// Run `action` once, when the next load-only item is published.
    pub(crate) fn on_model_load(&self, action: Box<dyn FnOnce() + Send>) {
        *self.on_model_load.lock().unwrap() = Some(action);
    }

    /// Run `action` once, when the next remote-lane work is published.
    pub(crate) fn on_remote_work(&self, action: RemoteWorkAction) {
        *self.on_remote_work.lock().unwrap() = Some(action);
    }

    /// Answer remote-lane work as a remote worker does when its upstream cannot
    /// serve now: a published `code` error with the upstream's wait, if any.
    pub(crate) fn refuse_remote_work(&self, code: &'static str, retry_after_s: Option<u32>) {
        *self.remote_refusal.lock().unwrap() = Some((code, retry_after_s));
    }

    /// Answer remote-lane generation as a remote worker does when its
    /// upstream failed: a `code` terminal with the upstream's wait, if any,
    /// that names `reason`.
    pub(crate) fn fail_remote_generation(
        &self,
        code: &'static str,
        retry_after_s: Option<u32>,
        reason: &'static str,
    ) {
        *self.remote_refusal.lock().unwrap() = Some((code, retry_after_s));
        *self.remote_failure_reason.lock().unwrap() = Some(reason);
    }

    fn remote_generation_error(&self, refusal: (&str, Option<u32>)) -> serde_json::Value {
        let mut error = refusal_error(refusal);
        error["reason"] = json!(*self.remote_failure_reason.lock().unwrap());
        error
    }

    /// Leave remote-lane work unanswered. With `after_output`, a generation
    /// reports that its first chunk has arrived.
    pub(crate) fn withhold_remote_answers(&self, after_output: bool) {
        *self.remote_silence.lock().unwrap() = Some(after_output);
    }

    /// Behave as a transport that supports republishing generation work at
    /// its first-chunk deadline, so a generation that is not republished ends
    /// at that deadline.
    pub(crate) fn enable_first_chunk_deadline(&self) {
        self.first_chunk_republish.store(true, Ordering::SeqCst);
    }

    fn remote_answer(&self, target: &PublishTarget) -> RemoteAnswer {
        if target.bundle() != REMOTE_LANE.2 {
            return RemoteAnswer::Served;
        }
        if let Some(refusal) = *self.remote_refusal.lock().unwrap() {
            return RemoteAnswer::Refused(refusal);
        }
        if self.remote_silence.lock().unwrap().is_some() {
            return RemoteAnswer::Withheld;
        }
        RemoteAnswer::Served
    }

    fn keep_unanswered(&self, pending: impl Any + Send) {
        self.unanswered.lock().unwrap().push(Box::new(pending));
    }

    pub(crate) fn dispatched(&self) -> Vec<Dispatched> {
        self.dispatched.lock().unwrap().clone()
    }

    pub(crate) fn execution_authority(&self) -> Vec<bool> {
        self.execution_authority.lock().unwrap().clone()
    }

    /// The fallback reason each published work request carried, in order.
    pub(crate) fn fallback_reasons(&self) -> Vec<Option<FallbackTrigger>> {
        self.fallback_reasons.lock().unwrap().clone()
    }

    /// The numerical admission each published work request named, in order.
    pub(crate) fn numerical_admissions(&self) -> Vec<Option<String>> {
        self.numerical_admissions.lock().unwrap().clone()
    }

    /// Answer remote-lane work the way a remote worker whose backend asks for
    /// redelivery does: a remote attempt that carries a fallback reason or a
    /// numerical admission gets a retryable `code` result with the upstream's
    /// hint at once, while other work is redelivered, so its result never
    /// arrives.
    pub(crate) fn answer_only_bridged_remote_work(&self, code: &'static str, retry_after_s: u32) {
        *self.bridged_refusal.lock().unwrap() = Some((code, retry_after_s));
    }

    /// Behave as a transport that cannot keep the execution-authority fence.
    pub(crate) fn withdraw_execution_authority(&self) {
        self.without_execution_authority
            .store(true, Ordering::SeqCst);
    }

    pub(crate) fn saturate_local_queue(&self) {
        self.local_backpressure.store(true, Ordering::SeqCst);
    }

    /// Report the local lane as having no ready capacity, as a transport that
    /// manages its own capacity does while the registry still lists workers.
    pub(crate) fn report_cold_local_lane(&self) {
        self.local_lane_cold.store(true, Ordering::SeqCst);
    }

    /// Refuse remote-lane work as a transport does while that lane starts.
    pub(crate) fn report_remote_lane_starting(&self) {
        self.remote_lane_starting.store(true, Ordering::SeqCst);
    }

    pub(crate) fn refuse_model_loads(&self) {
        self.load_refused.store(true, Ordering::SeqCst);
    }
    pub(crate) fn refuse_generation(&self) {
        self.generate_refused.store(true, Ordering::SeqCst);
    }

    pub(crate) fn refuse_work(&self) {
        self.work_refused.store(true, Ordering::SeqCst);
    }

    pub(crate) fn return_extract_data(&self, data: serde_json::Value) {
        *self.extract_data.lock().unwrap() = Some(data);
    }

    pub(crate) fn fail_stream(&self, after_output: bool) {
        self.stream_error.store(true, Ordering::SeqCst);
        self.stream_mid_error.store(after_output, Ordering::SeqCst);
    }

    pub(crate) fn fail_stream_terminal(&self, reason: &'static str) {
        *self.stream_terminal_failure.lock().unwrap() = Some(reason);
    }

    fn record(&self, dispatched: Dispatched) {
        let remote_work = dispatched.bundle == REMOTE_LANE.2 && dispatched.endpoint != "load";
        self.dispatched.lock().unwrap().push(dispatched);
        if remote_work {
            let action = self.on_remote_work.lock().unwrap().take();
            if let Some(action) = action {
                action(self);
            }
        }
    }

    fn record_authority(&self, target: &PublishTarget, params: &WorkParams) {
        assert!(
            !(params.require_execution_authority_v1 || params.numerical_admission_sha256.is_some())
                || matches!(target, PublishTarget::VerifiedWorker { .. }),
            "verified execution requires a verified worker target"
        );
        self.execution_authority
            .lock()
            .unwrap()
            .push(params.require_execution_authority_v1);
    }
}

enum RemoteAnswer {
    Served,
    Refused((&'static str, Option<u32>)),
    Withheld,
}

fn refusal_error((code, retry_after_s): (&str, Option<u32>)) -> serde_json::Value {
    json!({
        "code": code,
        "message": "The upstream serving the model is busy, please retry",
        "retry_after_s": retry_after_s,
    })
}

fn successful_result(request_id: &str, item_index: u32, payload: serde_json::Value) -> WorkResult {
    let mut result: WorkResult = serde_json::from_value(json!({
        "work_item_id": format!("{request_id}.{item_index}"),
        "request_id": request_id,
        "item_index": item_index,
        "success": true,
    }))
    .unwrap();
    result.result_msgpack = rmp_serde::to_vec_named(&payload).unwrap();
    result
}

fn refused_result(
    request_id: &str,
    item_index: u32,
    (code, retry_after_s): (&str, Option<u32>),
) -> WorkResult {
    serde_json::from_value(json!({
        "work_item_id": format!("{request_id}.{item_index}"),
        "request_id": request_id,
        "item_index": item_index,
        "success": false,
        "error": "The upstream serving the model is busy, please retry",
        "error_code": code,
        "retry_after_s": retry_after_s,
    }))
    .unwrap()
}

fn terminal_chunk_collector(
    display_model: &str,
    bundle_config_hash: &str,
) -> (
    oneshot::Receiver<StreamOutcome>,
    broadcast::Receiver<ChunkEnvelope>,
) {
    stream_chunk_collector(display_model, bundle_config_hash, None, false, None)
}

fn stream_chunk_collector(
    display_model: &str,
    bundle_config_hash: &str,
    error: Option<serde_json::Value>,
    after_output: bool,
    terminal_failure: Option<&str>,
) -> (
    oneshot::Receiver<StreamOutcome>,
    broadcast::Receiver<ChunkEnvelope>,
) {
    let fail = error.is_some();
    let (tx, rx) = oneshot::channel();
    let mut collector = StreamCollector::new(tx, display_model.to_string(), "default".to_string());
    let tap = collector.install_chunk_tap();
    if fail && after_output {
        let delta = serde_json::from_value(json!({
            "kind":"chunk", "request_id":"request-1", "attempt_id":"attempt-1",
            "seq":0, "text_delta":"ok", "done":false, "is_first":true,
        }))
        .unwrap();
        assert_eq!(collector.apply(delta), ChunkApplied::Delta);
    }
    let terminal = serde_json::from_value(json!({
        "kind": "chunk", "request_id": "request-1", "attempt_id": "attempt-1",
        "seq": u64::from(fail && after_output), "text_delta": if fail || terminal_failure.is_some() {""} else {"ok"}, "done": true, "is_first": !(fail && after_output),
        "finish_reason": terminal_failure.unwrap_or(if fail {"error"} else {"stop"}),
        "error": error.unwrap_or(serde_json::Value::Null),
        "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
        "executed_bundle_config_hash": bundle_config_hash,
    }))
    .unwrap();
    assert_eq!(collector.apply(terminal), ChunkApplied::Terminal);
    let outcome = collector.build_outcome().unwrap();
    collector.sender.take().unwrap().send(outcome).unwrap();
    (rx, tap)
}

#[async_trait::async_trait]
impl WorkDispatcher for RecordingDispatcher {
    fn supports_execution_authority_v1(&self) -> bool {
        !self.without_execution_authority.load(Ordering::SeqCst)
    }

    fn lane_provisioning(&self, lane: &LaneKey, _model: &str) -> bool {
        self.local_lane_cold.load(Ordering::SeqCst)
            && lane == &LaneKey::new(LOCAL_LANE.0, LOCAL_LANE.1, LOCAL_LANE.2)
    }

    fn provisioning_retry_after(&self, target: &PublishTarget) -> Option<Duration> {
        assert!(matches!(target, PublishTarget::Pool { .. }));
        self.provisioning_estimates
            .lock()
            .unwrap()
            .get(&target.lane())
            .copied()
    }

    fn pre_dispatch_backpressure(&self, lane: &LaneKey) -> Result<(), DispatchBackpressure> {
        if lane.bundle == LOCAL_LANE.2 && self.local_backpressure.load(Ordering::SeqCst) {
            Err("backpressure: local lane is full".into())
        } else {
            Ok(())
        }
    }

    async fn publish_model_load(
        &self,
        target: PublishTarget,
        _engine: &str,
        hash: &str,
    ) -> Result<(String, DispatchDurability), DispatchError> {
        assert!(!hash.is_empty());
        if self.local_lane_cold.load(Ordering::SeqCst) {
            assert!(matches!(target, PublishTarget::Pool { .. }));
        } else {
            assert!(matches!(target, PublishTarget::VerifiedWorker { .. }));
        }
        self.record(Dispatched::new("load", &target));
        if let Some(action) = self.on_model_load.lock().unwrap().take() {
            action();
        }
        if self.load_refused.load(Ordering::SeqCst) {
            return Err(DispatchError::Other("load was not durably accepted".into()));
        }
        Ok(("load-1".into(), DispatchDurability::accepted()))
    }

    async fn publish_work(
        self: Arc<Self>,
        target: PublishTarget,
        _admission_pool: &str,
        endpoint: &str,
        _model: &str,
        _display_model: &str,
        _engine: &str,
        _bundle_config_hash: &str,
        items: Vec<rmpv::Value>,
        params: &WorkParams,
    ) -> Result<
        (
            String,
            oneshot::Receiver<Vec<WorkResult>>,
            DispatchDurability,
        ),
        DispatchError,
    > {
        self.record_authority(&target, params);
        self.record(Dispatched::new(endpoint, &target));
        self.fallback_reasons
            .lock()
            .unwrap()
            .push(params.fallback_reason);
        self.numerical_admissions
            .lock()
            .unwrap()
            .push(params.numerical_admission_sha256.clone());
        if self.work_refused.load(Ordering::SeqCst) {
            return Err(DispatchError::Other("private upstream failure".into()));
        }
        if self.remote_lane_starting.load(Ordering::SeqCst) && target.bundle() == REMOTE_LANE.2 {
            return Err(DispatchError::Other(
                "no consumers ready: the lane is starting".into(),
            ));
        }
        let request_id = "request-1".to_string();
        let bridged_refusal = *self.bridged_refusal.lock().unwrap();
        if let Some((code, retry_after_s)) =
            bridged_refusal.filter(|_| target.bundle() == REMOTE_LANE.2)
        {
            let (tx, rx) = oneshot::channel();
            if params.fallback_reason.is_some() || params.numerical_admission_sha256.is_some() {
                let refused = (0..items.len().max(1) as u32)
                    .map(|index| refused_result(&request_id, index, (code, Some(retry_after_s))))
                    .collect();
                tx.send(refused).unwrap();
            } else {
                self.redelivered.lock().unwrap().push(tx);
            }
            return Ok((request_id, rx, DispatchDurability::accepted()));
        }
        let answer = self.remote_answer(&target);
        if matches!(answer, RemoteAnswer::Withheld) {
            let (tx, rx) = oneshot::channel::<Vec<WorkResult>>();
            self.keep_unanswered(tx);
            return Ok((request_id, rx, DispatchDurability::accepted()));
        }
        let results = if let RemoteAnswer::Refused(refusal) = answer {
            (0..items.len().max(1) as u32)
                .map(|index| refused_result(&request_id, index, refusal))
                .collect()
        } else if endpoint == "score" {
            vec![successful_result(
                &request_id,
                0,
                json!([{"item_id": "0", "score": 0.5, "rank": 0}]),
            )]
        } else if endpoint == "extract" {
            let data = self
                .extract_data
                .lock()
                .unwrap()
                .clone()
                .unwrap_or_else(|| json!({"text":"hello world", "duration_ms":1234}));
            (0..items.len() as u32)
                .map(|index| {
                    successful_result(
                        &request_id,
                        index,
                        json!({"id":index.to_string(), "data":data}),
                    )
                })
                .collect()
        } else {
            (0..items.len() as u32)
                .map(|index| successful_result(&request_id, index, json!({"dense": [0.5, 0.25]})))
                .collect()
        };
        let (tx, rx) = oneshot::channel();
        tx.send(results).unwrap();
        Ok((request_id, rx, DispatchDurability::accepted()))
    }

    async fn publish_generate_streaming(
        &self,
        target: PublishTarget,
        display_model: &str,
        _engine: &str,
        bundle_config_hash: &str,
        params: &WorkParams,
        _admission_pool: &str,
    ) -> Result<
        (
            String,
            oneshot::Receiver<StreamOutcome>,
            Arc<Notify>,
            DispatchDurability,
        ),
        String,
    > {
        if self.generate_refused.load(Ordering::SeqCst) {
            return Err("private upstream failure".into());
        }
        if self.remote_lane_starting.load(Ordering::SeqCst) && target.bundle() == REMOTE_LANE.2 {
            return Err("no consumers ready: the lane is starting".into());
        }
        self.record_authority(&target, params);
        self.record(Dispatched::new("generate", &target));
        self.fallback_reasons
            .lock()
            .unwrap()
            .push(params.fallback_reason);
        let (rx, _tap) = match self.remote_answer(&target) {
            RemoteAnswer::Served => terminal_chunk_collector(display_model, bundle_config_hash),
            RemoteAnswer::Refused(refusal) => stream_chunk_collector(
                display_model,
                bundle_config_hash,
                Some(self.remote_generation_error(refusal)),
                false,
                None,
            ),
            RemoteAnswer::Withheld => {
                let (tx, rx) = oneshot::channel();
                self.keep_unanswered(tx);
                (rx, broadcast::channel(1).1)
            }
        };
        Ok((
            "request-1".to_string(),
            rx,
            Arc::new(Notify::new()),
            DispatchDurability::accepted(),
        ))
    }

    async fn publish_generate_streaming_sse(
        &self,
        target: PublishTarget,
        display_model: &str,
        _engine: &str,
        bundle_config_hash: &str,
        params: &WorkParams,
        _admission_pool: &str,
    ) -> Result<
        (
            String,
            oneshot::Receiver<StreamOutcome>,
            broadcast::Receiver<ChunkEnvelope>,
            DispatchDurability,
        ),
        String,
    > {
        self.record_authority(&target, params);
        self.record(Dispatched::new("generate", &target));
        self.fallback_reasons
            .lock()
            .unwrap()
            .push(params.fallback_reason);
        if self.generate_refused.load(Ordering::SeqCst) {
            return Err("private upstream failure".into());
        }
        if self.remote_lane_starting.load(Ordering::SeqCst) && target.bundle() == REMOTE_LANE.2 {
            return Err("no consumers ready: the lane is starting".into());
        }
        let error = match self.remote_answer(&target) {
            RemoteAnswer::Refused(refusal) => Some(self.remote_generation_error(refusal)),
            RemoteAnswer::Withheld => {
                let (tx, rx) = oneshot::channel();
                let mut collector =
                    StreamCollector::new(tx, display_model.to_string(), "default".to_string());
                let tap = collector.install_chunk_tap();
                self.keep_unanswered(collector);
                return Ok((
                    "request-1".to_string(),
                    rx,
                    tap,
                    DispatchDurability::accepted(),
                ));
            }
            RemoteAnswer::Served => self
                .stream_error
                .load(Ordering::SeqCst)
                .then(|| json!({"code":"inference_error","message":"private upstream failure"})),
        };
        let (rx, tap) = stream_chunk_collector(
            display_model,
            bundle_config_hash,
            error,
            self.stream_mid_error.load(Ordering::SeqCst),
            *self.stream_terminal_failure.lock().unwrap(),
        );
        Ok((
            "request-1".to_string(),
            rx,
            tap,
            DispatchDurability::accepted(),
        ))
    }

    async fn publish_cancel(&self, _request_id: &str) {}

    fn begin_work_abandonment(&self, _request_id: &str) -> bool {
        true
    }

    async fn finish_work_abandonment(&self, _request_id: &str) {}

    async fn republish_to_pool(
        &self,
        _request_id: &str,
        _reason: &'static str,
    ) -> Result<bool, String> {
        Ok(false)
    }

    async fn republish_pending_result_to_pool(
        &self,
        _request_id: &str,
        _reason: &'static str,
    ) -> Result<bool, String> {
        Ok(false)
    }

    fn drop_pending_stream(&self, _request_id: &str) {}

    fn pending_generation_snapshot(&self) -> PendingGenerationSnapshot {
        PendingGenerationSnapshot::default()
    }

    fn pending_generation_for_model(&self, _model_id: &str) -> PendingGenerationSnapshot {
        PendingGenerationSnapshot::default()
    }

    fn stream_observed_first_chunk(&self, _request_id: &str) -> bool {
        false
    }

    fn supports_first_chunk_pool_republish(&self) -> bool {
        self.first_chunk_republish.load(Ordering::SeqCst)
    }

    fn stream_chunk_timing(&self, _request_id: &str) -> Option<(Option<Instant>, Option<Instant>)> {
        let now = Instant::now();
        (*self.remote_silence.lock().unwrap() == Some(true)).then_some((Some(now), Some(now)))
    }
}

/// A gateway whose registry holds `models` (model config YAML documents) and
/// whose lane catalog has [`LOCAL_LANE`] and [`REMOTE_LANE`]. No worker is
/// registered until [`TestGateway::add_worker`].
pub(crate) struct TestGateway {
    pub state: Arc<AppState>,
    pub dispatcher: Arc<RecordingDispatcher>,
    _bundles_dir: tempfile::TempDir,
    _models_dir: tempfile::TempDir,
}

impl TestGateway {
    pub(crate) async fn new(models: &[&str]) -> Self {
        Self::with_threshold_routing(models, false).await
    }

    pub(crate) async fn with_threshold_routing(models: &[&str], threshold: bool) -> Self {
        Self::build(models, threshold, None).await
    }

    /// A gateway that also has the remote lane in the static queue pool
    /// `pool`, so a test owns that pool's queue stream.
    pub(crate) async fn with_remote_queue_pool(models: &[&str], pool: &str) -> Self {
        Self::build(models, false, Some(pool)).await
    }

    async fn build(models: &[&str], threshold: bool, remote_pool: Option<&str>) -> Self {
        let bundles_dir = tempfile::TempDir::new().unwrap();
        let models_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(bundles_dir.path().join("default.yaml"), DEFAULT_BUNDLE).unwrap();
        std::fs::write(bundles_dir.path().join("remote.yaml"), REMOTE_BUNDLE).unwrap();
        for (index, model) in models.iter().enumerate() {
            std::fs::write(models_dir.path().join(format!("model-{index}.yaml")), model).unwrap();
        }
        let profiles = vec![LOCAL_LANE.1.to_string(), REMOTE_LANE.1.to_string()];
        let mut lane_tuples: Vec<(&str, &str, &str)> = vec![LOCAL_LANE, REMOTE_LANE];
        if let Some(pool) = remote_pool {
            lane_tuples.push((pool, REMOTE_LANE.1, REMOTE_LANE.2));
        }
        let lanes =
            PhysicalLaneCatalog::try_new(lane_tuples.into_iter().map(|(pool, profile, bundle)| {
                PhysicalLane::try_new(pool, profile, bundle).unwrap()
            }))
            .unwrap();
        let pool_manager = Arc::new(PoolManager::new(profiles.clone()));
        pool_manager.create_default_pool().await;
        if let Some(pool) = remote_pool {
            let gpus = serde_json::Map::from_iter([(REMOTE_LANE.1.to_string(), json!(1))]);
            let spec = serde_json::from_value(json!({
                "name": pool,
                "queue_pool": pool,
                "bundle": REMOTE_LANE.2,
                "gpus": gpus,
            }))
            .unwrap();
            pool_manager.sync_static_pools(&[spec]).await.unwrap();
        }
        let dispatcher = Arc::new(RecordingDispatcher::default());
        let state = AppState {
            registry: Arc::new(WorkerRegistry::new(Duration::from_secs(30), None)),
            config: Arc::new(test_config(
                bundles_dir.path().to_str().unwrap(),
                models_dir.path().to_str().unwrap(),
                profiles,
                lanes.clone(),
            )),
            model_registry: Arc::new(ModelRegistry::with_threshold_routing(
                bundles_dir.path(),
                models_dir.path(),
                true,
                threshold,
            )),
            pool_manager,
            work_publisher: Some(dispatcher.clone()),
            lane_backlog_source: None,
            demand_tracker: Arc::new(DemandTracker::new(lanes)),
            config_epoch: ConfigEpoch::new(),
            model_access_policy: None,
        };
        Self {
            state: Arc::new(state),
            dispatcher,
            _bundles_dir: bundles_dir,
            _models_dir: models_dir,
        }
    }

    /// Install a deployment's model access policy.
    pub(crate) fn install_policy(&mut self, policy: Arc<dyn crate::server::ModelAccessPolicy>) {
        Arc::get_mut(&mut self.state)
            .expect("the gateway state is not shared yet")
            .model_access_policy = Some(policy);
    }

    /// Resolve `alias` to `target`, as an operator's model alias does.
    pub(crate) fn add_model_alias(&mut self, alias: &str, target: &str) {
        let state = Arc::get_mut(&mut self.state).expect("the gateway state is not shared yet");
        Arc::get_mut(&mut state.config)
            .expect("the gateway config is not shared yet")
            .model_aliases
            .insert(alias.to_string(), target.to_string());
    }

    /// Wait at most `seconds` for queued results.
    pub(crate) fn set_request_timeout(&mut self, seconds: f64) {
        let state = Arc::get_mut(&mut self.state).expect("the gateway state is not shared yet");
        Arc::get_mut(&mut state.config)
            .expect("the gateway config is not shared yet")
            .request_timeout = seconds;
    }

    /// Register a healthy worker on `lane` that reports `loaded` as loaded.
    pub(crate) async fn add_worker(&self, name: &str, lane: (&str, &str, &str), loaded: &[&str]) {
        self.add_worker_with_authority(name, lane, loaded, false, false)
            .await;
    }

    pub(crate) async fn add_verified_worker(
        &self,
        name: &str,
        lane: (&str, &str, &str),
        loaded: &[&str],
    ) {
        self.add_worker_with_authority(name, lane, loaded, true, false)
            .await;
    }

    pub(crate) async fn add_saturated_worker(
        &self,
        name: &str,
        lane: (&str, &str, &str),
        loaded: &[&str],
    ) {
        self.add_worker_with_authority(name, lane, loaded, true, true)
            .await;
    }

    /// Register a verified worker whose heartbeat also reports `inventory`,
    /// with `numerical` support for re-verifying a numerical admission.
    pub(crate) async fn add_numerical_worker(
        &self,
        name: &str,
        lane: (&str, &str, &str),
        loaded: &[&str],
        numerical: bool,
        inventory: serde_json::Value,
    ) {
        let (pool, machine_profile, bundle) = lane;
        let status = WorkerStatusMessage {
            supports_execution_authority_v1: true,
            supports_numerical_admission_v1: numerical,
            supports_numerical_admission_subject_v1: numerical,
            name: name.to_string(),
            ready: true,
            gpu_count: 1,
            machine_profile: machine_profile.to_string(),
            pool_name: pool.to_string(),
            bundle: bundle.to_string(),
            bundle_config_hash: self
                .state
                .model_registry
                .compute_bundle_config_hash_for_pool(bundle, pool),
            loaded_models: loaded.iter().map(|model| model.to_string()).collect(),
            numerical_process_inventory: Some(serde_json::from_value(inventory).unwrap()),
            ..Default::default()
        };
        self.state
            .registry
            .update_worker(&format!("http://{name}:8080"), status)
            .await;
        self.state.registry.settle_health_view_for_tests();
    }

    async fn add_worker_with_authority(
        &self,
        name: &str,
        lane: (&str, &str, &str),
        loaded: &[&str],
        authority: bool,
        saturated: bool,
    ) {
        let (pool, machine_profile, bundle) = lane;
        let status = WorkerStatusMessage {
            supports_execution_authority_v1: authority,
            saturated,
            name: name.to_string(),
            ready: true,
            gpu_count: 1,
            machine_profile: machine_profile.to_string(),
            pool_name: pool.to_string(),
            bundle: bundle.to_string(),
            bundle_config_hash: self
                .state
                .model_registry
                .compute_bundle_config_hash_for_pool(bundle, pool),
            loaded_models: loaded.iter().map(|model| model.to_string()).collect(),
            ..Default::default()
        };
        self.state
            .registry
            .update_worker(&format!("http://{name}:8080"), status)
            .await;
    }
}

fn test_config(
    bundles_dir: &str,
    models_dir: &str,
    profiles: Vec<String>,
    lanes: PhysicalLaneCatalog,
) -> Config {
    Config {
        host: "127.0.0.1".to_string(),
        port: 0,
        worker_urls: Vec::new(),
        use_kubernetes: false,
        k8s_namespace: "default".to_string(),
        k8s_service: String::new(),
        k8s_port: 0,
        health_mode: "nats".to_string(),
        nats_url: String::new(),
        nats_user: String::new(),
        nats_password: String::new(),
        nats_config_trusted_producers: Vec::new(),
        auth_mode: "none".to_string(),
        auth_tokens: Vec::new(),
        admin_token: String::new(),
        auth_exempt_operational: false,
        log_level: "info".to_string(),
        json_logs: false,
        enable_pools: true,
        hot_reload: false,
        watch_polling: false,
        multi_router: false,
        request_timeout: 30.0,
        max_item_text_bytes: 2 * 1024 * 1024,
        max_stream_pending: 1024,
        max_lane_in_flight_items: crate::queue::lane_admission::DEFAULT_MAX_LANE_IN_FLIGHT_ITEMS,
        lane_backpressure_enforce: false,
        stream_max_age_s: 300,
        stream_storage: StreamStorage::Memory,
        stream_num_replicas: 1,
        configured_gpus: profiles.clone(),
        gpu_profile_map: profiles
            .into_iter()
            .map(|profile| (profile.clone(), profile))
            .collect::<HashMap<_, _>>(),
        configured_physical_lanes: lanes,
        static_queue_pools: Vec::new(),
        model_aliases: HashMap::new(),
        published_model_aliases: Default::default(),
        retired_models: HashMap::new(),
        bundles_dir: bundles_dir.to_string(),
        models_dir: models_dir.to_string(),
        config_service_url: None,
        config_service_token: None,
        config_modal_proxy_token: None,
        payload_store_url: String::new(),
        public_base_url: None,
    }
}

/// Independent authenticated control broker for request-path regressions.
/// The inference dispatcher remains the recording fixture above.
pub(crate) struct ThresholdBroker {
    pub context: async_nats::jetstream::Context,
    _process: tokio::process::Child,
    _config: tempfile::NamedTempFile,
    _store_dir: tempfile::TempDir,
    _ports_dir: tempfile::TempDir,
    _logs: tempfile::NamedTempFile,
    url: String,
    server_name: String,
    password: String,
}

impl ThresholdBroker {
    pub(crate) async fn start() -> Option<Self> {
        Self::start_on_port(-1)
            .await
            .unwrap_or_else(|error| panic!("control fixture start failed: {error}"))
    }

    // NATS 2.11.8 binds port -1 itself, then writes <executable>_<pid>.ports.
    // Keeping port allocation in the child avoids the reserve/drop/spawn race.
    async fn start_on_port(port: i32) -> Result<Option<Self>, String> {
        let server_name = format!("sie-threshold-test-{}", uuid::Uuid::new_v4());
        // An alphabetic prefix keeps NATS environment substitution from parsing
        // a digit-leading UUID as a number rather than an authentication string.
        let password = format!("ThresholdTest{}", uuid::Uuid::new_v4().simple());
        let fixture = include_str!("../../../../tools/ci/fixtures/sie-threshold-nats.conf")
            .replace("port: 4222", &format!("host: 127.0.0.1\nport: {port}"))
            .replace("http_port: 8222", "http_port: -1");
        let fixture = format!("{fixture}\nserver_name: {server_name}\n");
        let store_dir = tempfile::tempdir().unwrap();
        let ports_dir = tempfile::tempdir().unwrap();
        let config = tempfile::NamedTempFile::new().unwrap();
        let logs = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(config.path(), fixture).unwrap();
        let process = tokio::process::Command::new("nats-server")
            .args(["-c", config.path().to_str().unwrap()])
            .arg("-sd")
            .arg(store_dir.path())
            .arg("--ports_file_dir")
            .arg(ports_dir.path())
            .env("SIE_NATS_AUTH_GATEWAY_PASSWORD", &password)
            .stdout(logs.as_file().try_clone().unwrap())
            .stderr(logs.as_file().try_clone().unwrap())
            .kill_on_drop(true)
            .spawn();
        let mut process = match process {
            Ok(process) => process,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                assert!(
                    std::env::var("NATS_URL").is_err(),
                    "NATS integration requires nats-server"
                );
                return Ok(None);
            }
            Err(error) => return Err(error.to_string()),
        };
        let pid = process.id().expect("spawned control fixture pid");
        let ports_file = ports_dir.path().join(format!("nats-server_{pid}.ports"));
        let ready = Self::wait_ready(&mut process, &ports_file, &server_name, &password).await;
        let (client, url) = match ready {
            Ok(ready) => ready,
            Err(error) => {
                // Do not leave a failed owned child running while reporting its logs.
                let cleanup = tokio::time::timeout(Duration::from_secs(1), process.kill()).await;
                let output = std::fs::read_to_string(logs.path())
                    .unwrap_or_else(|error| format!("could not read broker output: {error}"));
                return Err(format!(
                    "{error}; pid={pid}, server_name={server_name}, cleanup={cleanup:?}\n{output}"
                ));
            }
        };
        eprintln!(
            "threshold broker ready: pid={pid}, server_name={server_name}, server_id={}, url={url}",
            client.server_info().server_id
        );
        Ok(Some(Self {
            context: async_nats::jetstream::new(client),
            _process: process,
            _config: config,
            _store_dir: store_dir,
            _ports_dir: ports_dir,
            _logs: logs,
            url,
            server_name,
            password,
        }))
    }

    fn owned_url(ports_file: &std::path::Path) -> Result<Option<String>, String> {
        let bytes = match std::fs::read(ports_file) {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(format!("control fixture ports file: {error}")),
        };
        #[derive(serde::Deserialize)]
        struct Ports {
            nats: Vec<String>,
        }
        let ports: Ports = match serde_json::from_slice(&bytes) {
            Ok(ports) => ports,
            // NATS writes this small file directly; a concurrent read may be partial.
            Err(error) if error.is_eof() => return Ok(None),
            Err(error) => return Err(format!("invalid control fixture ports file: {error}")),
        };
        let [url] = ports.nats.as_slice() else {
            return Err("control fixture must advertise exactly one NATS listener".into());
        };
        if !url
            .strip_prefix("nats://127.0.0.1:")
            .and_then(|port| port.parse::<u16>().ok())
            .is_some_and(|port| port > 0)
        {
            return Err("control fixture advertised a non-loopback or invalid listener".into());
        }
        Ok(Some(url.clone()))
    }

    async fn connect_owned(
        url: &str,
        server_name: &str,
        password: &str,
    ) -> Result<Option<async_nats::Client>, String> {
        let Ok(client) = async_nats::ConnectOptions::new()
            .user_and_password("sie-gateway".into(), password.into())
            .connect(url)
            .await
        else {
            return Ok(None);
        };
        if client.flush().await.is_err() {
            return Ok(None);
        }
        let info = client.server_info();
        if info.server_name != server_name || info.server_id.is_empty() {
            return Err(format!(
                "control fixture server identity mismatch: expected {server_name}, got {} ({})",
                info.server_name, info.server_id
            ));
        }
        Ok(Some(client))
    }

    async fn wait_ready(
        process: &mut tokio::process::Child,
        ports_file: &std::path::Path,
        server_name: &str,
        password: &str,
    ) -> Result<(async_nats::Client, String), String> {
        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(10);
        while tokio::time::Instant::now() < ready_deadline {
            if let Some(status) = process.try_wait().map_err(|error| error.to_string())? {
                return Err(format!("control fixture exited before readiness: {status}"));
            }
            if let Some(url) = Self::owned_url(ports_file)? {
                let remaining =
                    ready_deadline.saturating_duration_since(tokio::time::Instant::now());
                let result = tokio::time::timeout(
                    remaining.min(Duration::from_millis(250)),
                    Self::connect_owned(&url, server_name, password),
                )
                .await;
                if let Ok(result) = result {
                    if let Some(client) = result? {
                        // A foreign listener cannot hide the owned child's bind failure.
                        if let Some(status) =
                            process.try_wait().map_err(|error| error.to_string())?
                        {
                            return Err(format!(
                                "control fixture exited during readiness: {status}"
                            ));
                        }
                        return Ok((client, url));
                    }
                }
            }
            tokio::time::sleep(
                Duration::from_millis(20)
                    .min(ready_deadline.saturating_duration_since(tokio::time::Instant::now())),
            )
            .await;
        }
        Err("control broker did not become ready within 10 seconds".into())
    }

    pub(crate) fn credentials(&self) -> crate::config::NatsCredentials {
        crate::config::NatsCredentials {
            user: "sie-gateway".into(),
            password: self.password.clone(),
        }
    }

    pub(crate) async fn bind(
        &self,
        gateway: &TestGateway,
    ) -> Arc<crate::state::threshold_runtime::ThresholdBinding> {
        use crate::state::threshold_coordinator::ThresholdCoordinator;
        use crate::state::threshold_runtime::ThresholdBinding;
        gateway.state.config_epoch.set_max(1);
        let (generation, targets) = gateway.state.model_registry.threshold_targets(1).unwrap();
        let binding = Arc::new(ThresholdBinding {
            generation,
            epoch: 1,
            coordinator: ThresholdCoordinator::connect(&self.context, 1, targets)
                .await
                .unwrap(),
        });
        gateway
            .state
            .model_registry
            .install_threshold_binding(Arc::clone(&binding));
        binding
    }
}

/// An object schema whose ``properties`` each ``$ref`` one shared
/// definition of ``fields`` string fields, each with a
/// ``description_len``-byte description. Expanding the refs copies the
/// definition once per property.
pub(crate) fn schema_with_shared_definition(
    properties: usize,
    fields: usize,
    description_len: usize,
) -> serde_json::Value {
    let description = "d".repeat(description_len);
    let shared_fields: serde_json::Map<String, serde_json::Value> = (0..fields)
        .map(|i| {
            (
                format!("f{i}"),
                serde_json::json!({"type": "string", "description": description}),
            )
        })
        .collect();
    let refs: serde_json::Map<String, serde_json::Value> = (0..properties)
        .map(|i| {
            (
                format!("p{i}"),
                serde_json::json!({"$ref": "#/$defs/Shared"}),
            )
        })
        .collect();
    serde_json::json!({
        "type": "object",
        "$defs": {"Shared": {"type": "object", "properties": shared_fields}},
        "properties": refs,
    })
}

#[cfg(test)]
mod threshold_broker_tests {
    use super::ThresholdBroker;
    use std::time::Duration;

    #[tokio::test]
    async fn threshold_broker_rejects_foreign_identity_and_credentials() {
        let Some(mut first) = ThresholdBroker::start().await else {
            return;
        };
        let Some(mut second) = ThresholdBroker::start().await else {
            return;
        };
        assert_ne!(first.url, second.url);
        assert_ne!(first.server_name, second.server_name);
        assert_ne!(first.password, second.password);
        let foreign = tokio::time::timeout(
            Duration::from_secs(10),
            ThresholdBroker::connect_owned(&first.url, &second.server_name, &first.password),
        )
        .await
        .expect("foreign identity check must finish");
        assert!(foreign.unwrap_err().contains("server identity mismatch"));
        let wrong_password = tokio::time::timeout(
            Duration::from_secs(10),
            ThresholdBroker::connect_owned(&first.url, &first.server_name, &second.password),
        )
        .await
        .expect("foreign credential check must finish")
        .unwrap();
        assert!(wrong_password.is_none());
        first._process.kill().await.unwrap();
        second._process.kill().await.unwrap();
    }

    #[tokio::test]
    async fn threshold_broker_collision_fails_with_owned_child_diagnostics() {
        let Some(mut broker) = ThresholdBroker::start().await else {
            return;
        };
        let port: i32 = broker.url.rsplit(':').next().unwrap().parse().unwrap();
        let failure = tokio::time::timeout(
            Duration::from_secs(12),
            ThresholdBroker::start_on_port(port),
        )
        .await
        .expect("owned startup and cleanup must finish within their existing bounds");
        let error = match failure {
            Err(error) => error,
            Ok(_) => panic!("colliding fixture must not accept the existing broker"),
        };
        assert!(error.contains("exited before readiness"), "{error}");
        assert!(error.contains("pid="), "{error}");
        assert!(error.contains("server_name="), "{error}");
        assert!(error.contains("address already in use"), "{error}");
        assert!(
            ThresholdBroker::connect_owned(&broker.url, &broker.server_name, &broker.password)
                .await
                .unwrap()
                .is_some()
        );
        broker._process.kill().await.unwrap();
    }

    #[test]
    fn threshold_broker_accepts_only_complete_single_loopback_port_metadata() {
        let file = tempfile::NamedTempFile::new().unwrap();
        assert!(ThresholdBroker::owned_url(file.path()).unwrap().is_none());
        for body in [
            r#"{"nats": []}"#,
            r#"{"nats": ["nats://127.0.0.1:1234", "nats://127.0.0.1:1235"]}"#,
            r#"{"nats": ["nats://other-host:1234"]}"#,
            r#"{"nats": ["nats://127.0.0.1:0"]}"#,
            r#"{"nats": ["nats://127.0.0.1:1234/path"]}"#,
        ] {
            std::fs::write(file.path(), body).unwrap();
            assert!(ThresholdBroker::owned_url(file.path()).is_err(), "{body}");
        }
        std::fs::write(file.path(), r#"{"nats": ["nats://127.0.0.1:1234"]}"#).unwrap();
        assert_eq!(
            ThresholdBroker::owned_url(file.path()).unwrap().as_deref(),
            Some("nats://127.0.0.1:1234")
        );
    }
}