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(gateway): coordinate threshold demand with bounded leases (#554)
Krisztian Gajdar6e1424a20551
diff --git a/packages/sie_gateway/docs/threshold-routing.md b/packages/sie_gateway/docs/threshold-routing.mdnew file mode 100644index 000000000..2e39f6369--- /dev/null+++ b/packages/sie_gateway/docs/threshold-routing.md@@ -0,0 +1,86 @@+# Threshold demand coordinator++This is the shared-state prerequisite for the `threshold` policy in issue+[#415](https://github.com/superlinked/sie/issues/415). Request routing still+refuses `threshold`: the deployment flag, coordinator lifecycle, shared caller+validation and request-path integration are separate delivery steps.++`ThresholdCoordinator` accepts a JetStream context for an **isolated control+broker endpoint**. Do not pass the inference queue connection. The coordinator+has no upstream credentials and performs no inference calls. Inference workers+and config publishers must have no credentials for the control endpoint.+Subject permissions inside the inference broker's shared account do not prove+who produced a stored record. Keeping a separate endpoint also preserves the+existing inference broker's account, stream namespace and persisted work.++The credential-free integration fixture is+[`sie-threshold-nats.conf`](../../../tools/ci/fixtures/sie-threshold-nats.conf).+It accepts only gateway authentication, grants only the three exact threshold+stream APIs and key subjects, and denies consumer APIs. Integration tests start+this fixture independently from the unchanged inference-broker fixture.++## Shared demand and decisions++Every gateway counts validated ingress locally with per-model atomic counters.+`record_request` and `decision` are synchronous and perform no broker I/O. The+caller must count once after shared validation and before profile recursion.+Each gateway calls `sample` once per second; standby gateways flush their demand+before checking sampler ownership. Drained deltas are added to the shared+per-model counter with bounded compare-and-set retries. Requests racing a drain+stay in the following batch. An uncertain acknowledgement never restores a delta,+which could count a committed batch twice; the next successful flush breaks+shared sampling continuity. Long publication gaps discard delayed demand and+also reset evidence. A sampler elected by a five-second broker lease reads+aggregate requests per second on that cadence. `wake_above` and `sleep_below`+therefore use requests per second across all gateways, rather than per replica.+Windows and cooldowns have at least one-second resolution and are capped at a+day. Only consecutive samples beyond the relevant bound count; gaps longer than+2.5 seconds discard the accumulated evidence. Equality does not cross a bound.++The sampler starts undetermined. Demand above `wake_above` for `window_s`+selects `WakeLocal`. Demand below `sleep_below` for `cooldown_s` selects `Remote`.+Values between the bounds retain an established decision. An undetermined,+unavailable or incompatible decision must not authorize suppressing local+warm-up; the request integration must preserve the ordinary local/fallback path.++## Configuration and lifetime++All targets bind the same nonzero authoritative configuration generation, the+model name, exact execution fingerprint and all routing-policy fields. The+lease also binds the full target set, independent of listing order. A newer+generation can replace a lease by compare-and-set; an older generation or a+conflicting target set at the same generation is refused. On replacement,+old counters reset to zero without requiring traffic or adding demand.++Decisions bind that generation, execution contract, sampler owner and a UUID+term minted for each lease acquisition. Renewals preserve the term so an earlier+valid decision remains usable while the next sampling cycle publishes decisions.+Expiry, a configuration takeover or tombstone recreation mints a new term and+requires fresh timer evidence. DEL and PURGE retain their stream revision for+subsequent compare-and-set recovery. Counter recreation also mints an incarnation+UUID, so even a replacement total larger than the old total resets evidence.+Failed sampling clears local ownership,+term, cached decisions and timer evidence.++Background refresh verifies the complete lease authority before and after+reading decisions. A verified decision is cached for at most one sampling+interval, measured from the verification's start on the local monotonic clock.+Its deadline is also capped by a proven lower bound on the lease's expiry:+owners know when their renewal began; standby readers establish that bound by+observing a revision advance within one unchanged term. A newly attached standby+uses the ordinary local path until it observes a renewal. This avoids shared+wall clocks and prevents a nearly expired lease from gaining another cache+interval. Malformed, missing or changed authority clears the cache; unavailable+or expired cached decisions must allow ordinary local warm-up.+Removed sampler model state is pruned; broker counters expire after one day+without requests, so retired model keys are not retained forever. Expiry+rebuilds a conservative baseline and cannot count as fresh demand. There are at most 256 current targets, 2 KiB per+value, 1 MiB per bucket, 16 compare-and-set attempts and a two-second deadline+per background broker operation. Counter overflow, malformed records, incompatible+stream configurations and unavailable storage all return typed errors.++Coordination state uses memory streams. A broker restart loses decisions and+restarts the evidence window; it does not move or consume inference work.+One or three JetStream replicas are accepted, and the external endpoint must+supply the corresponding topology. These bounds are implementation limits,+not measured throughput or latency claims.diff --git a/packages/sie_gateway/src/state/mod.rs b/packages/sie_gateway/src/state/mod.rsindex 61dd24ecf..945500759 100644--- a/packages/sie_gateway/src/state/mod.rs+++ b/packages/sie_gateway/src/state/mod.rs@@ -10,5 +10,7 @@ pub mod k8s_pool_watcher;pub mod model_registry;pub mod pinned_models;pub mod pool_manager;+#[allow(dead_code)] // Prerequisite; flag/routing wiring is the next layer.+pub mod threshold_coordinator;pub mod warm_floor;pub mod worker_registry;diff --git a/packages/sie_gateway/src/state/threshold_coordinator.rs b/packages/sie_gateway/src/state/threshold_coordinator.rsnew file mode 100644index 000000000..f25b62662--- /dev/null+++ b/packages/sie_gateway/src/state/threshold_coordinator.rs@@ -0,0 +1,924 @@+//! Shared demand accounting and lease-fenced threshold decisions.+//!+//! This prerequisite does not activate routing. Only validated, policy-eligible+//! requests may call `record_request`; neither inference payloads nor caller+//! identifiers enter the broker. A sampler measures counter deltas with its+//! monotonic clock, and consumers require its current broker lease revision.++use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::RwLock;+use std::time::{Duration, Instant};++use async_nats::jetstream::{self, kv, stream};+use bytes::Bytes;+use serde::{de::DeserializeOwned, Deserialize, Serialize};+use sha2::{Digest, Sha256};+use uuid::Uuid;++use crate::types::model::{RoutingConfig, RoutingPolicy};++pub const MAX_THRESHOLD_MODELS: usize = 256;+pub const THRESHOLD_SAMPLE_INTERVAL: Duration = Duration::from_secs(1);+const MAX_SAMPLE_GAP: Duration = Duration::from_millis(2500);+const LEASE_TTL: Duration = Duration::from_secs(5);+const COUNTER_TTL: Duration = Duration::from_secs(86400);+const IO_TIMEOUT: Duration = Duration::from_secs(2);+const MAX_VALUE_BYTES: usize = 2048;+const MAX_BUCKET_BYTES: i64 = 1 << 20;+const CAS_ATTEMPTS: usize = 16;+const LEASE_KEY: &str = "sampler";++#[derive(Debug, thiserror::Error, PartialEq, Eq)]+pub enum ThresholdError {+ #[error("threshold configuration is invalid or exceeds its bounds")]+ Configuration,+ #[error("threshold broker state is unavailable")]+ Unavailable,+ #[error("threshold broker state is malformed or untrusted")]+ Untrusted,+ #[error("threshold configuration generation does not match")]+ Generation,+ #[error("threshold counter contention exceeded its bound")]+ Contended,+}++/// Exact snapshot authority, including the policy and local/remote execution+/// contracts. The generation must come from the authoritative config epoch.+#[derive(Clone, Debug)]+pub struct ThresholdTarget {+ key: String,+ generation: u64,+ contract: String,+ wake_above: f64,+ sleep_below: f64,+ window: Duration,+ cooldown: Duration,+}++impl ThresholdTarget {+ pub fn new(+ model: &str,+ generation: u64,+ execution_fingerprint: &str,+ routing: &RoutingConfig,+ ) -> Result<Self, ThresholdError> {+ if generation == 0+ || model.is_empty()+ || model.len() > 256+ || model.contains(':')+ || execution_fingerprint.len() != 64+ || !execution_fingerprint+ .bytes()+ .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())+ || routing.policy != RoutingPolicy::Threshold+ || routing.validate().is_err()+ {+ return Err(ThresholdError::Configuration);+ }+ let window = routing.window_s.ok_or(ThresholdError::Configuration)?;+ let cooldown = routing.cooldown_s.ok_or(ThresholdError::Configuration)?;+ if window > 86400.0 || cooldown > 86400.0 {+ return Err(ThresholdError::Configuration);+ }+ let policy = serde_json::to_vec(routing).map_err(|_| ThresholdError::Configuration)?;+ let mut contract = Sha256::new();+ contract.update(execution_fingerprint.as_bytes());+ contract.update(policy);+ Ok(Self {+ key: digest_key(model),+ generation,+ contract: hex_digest(&contract.finalize()),+ wake_above: routing.wake_above.ok_or(ThresholdError::Configuration)?,+ sleep_below: routing.sleep_below.ok_or(ThresholdError::Configuration)?,+ window: Duration::from_secs_f64(window.max(1.0)),+ cooldown: Duration::from_secs_f64(cooldown.max(1.0)),+ })+ }+}++#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ThresholdDecision {+ Undetermined,+ Remote,+ WakeLocal,+}++#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct Counter {+ generation: u64,+ contract: String,+ total: u64,+ incarnation: String,+ #[serde(default)]+ continuity: u64,+}++#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct Decision {+ generation: u64,+ contract: String,+ owner: String,+ term: String,+ decision: ThresholdDecision,+}++#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]+#[serde(deny_unknown_fields)]+struct Lease {+ owner: String,+ generation: u64,+ contract: String,+ term: String,+}++/// One process owns one sampler token. Replacement/expired ownership loses all+/// timer evidence; the broker's TTL decides expiry, never a gateway wall clock.+pub struct ThresholdSampler {+ owner: String,+ lease_revision: u64,+ term: Option<String>,+ models: HashMap<String, SampleState>,+}++impl Default for ThresholdSampler {+ fn default() -> Self {+ Self {+ owner: Uuid::new_v4().to_string(),+ lease_revision: 0,+ term: None,+ models: HashMap::new(),+ }+ }+}++struct SamplingAttempt<'a> {+ sampler: &'a mut ThresholdSampler,+ succeeded: bool,+}++impl Drop for SamplingAttempt<'_> {+ fn drop(&mut self) {+ if !self.succeeded {+ self.sampler.lease_revision = 0;+ self.sampler.term = None;+ self.sampler.models.clear();+ }+ }+}++struct SampleState {+ contract: String,+ generation: u64,+ total: u64,+ continuity: u64,+ incarnation: Option<String>,+ sampled_at: Instant,+ decision: ThresholdDecision,+ crossing_since: Option<Instant>,+ crossing_target: Option<ThresholdDecision>,+}++impl SampleState {+ fn baseline(target: &ThresholdTarget, total: u64, now: Instant) -> Self {+ Self {+ contract: target.contract.clone(),+ generation: target.generation,+ total,+ continuity: 0,+ incarnation: None,+ sampled_at: now,+ decision: ThresholdDecision::Undetermined,+ crossing_since: None,+ crossing_target: None,+ }+ }++ fn sample(&mut self, target: &ThresholdTarget, total: u64, now: Instant) -> ThresholdDecision {+ let elapsed = now.saturating_duration_since(self.sampled_at);+ if self.contract != target.contract+ || self.generation != target.generation+ || total < self.total+ || elapsed > MAX_SAMPLE_GAP+ {+ *self = Self::baseline(target, total, now);+ return self.decision;+ }+ // Calling faster than the declared cadence must not discard counts or+ // manufacture consecutive evidence from the same sampling interval.+ if elapsed < THRESHOLD_SAMPLE_INTERVAL {+ return self.decision;+ }+ let rate = (total - self.total) as f64 / elapsed.as_secs_f64();+ self.total = total;+ self.sampled_at = now;+ let crossing = match self.decision {+ ThresholdDecision::Remote if rate > target.wake_above => {+ Some(ThresholdDecision::WakeLocal)+ }+ ThresholdDecision::WakeLocal if rate < target.sleep_below => {+ Some(ThresholdDecision::Remote)+ }+ ThresholdDecision::Undetermined if rate > target.wake_above => {+ Some(ThresholdDecision::WakeLocal)+ }+ ThresholdDecision::Undetermined if rate < target.sleep_below => {+ Some(ThresholdDecision::Remote)+ }+ _ => None,+ };+ if crossing != self.crossing_target {+ self.crossing_since = None;+ self.crossing_target = crossing;+ }+ if let Some(next) = crossing {+ let required = if next == ThresholdDecision::WakeLocal {+ target.window+ } else {+ target.cooldown+ };+ let since = *self.crossing_since.get_or_insert(now);+ if now.saturating_duration_since(since) >= required {+ self.decision = next;+ self.crossing_since = None;+ self.crossing_target = None;+ }+ }+ self.decision+ }+}++struct TargetState {+ target: ThresholdTarget,+ pending: AtomicU64,+ interrupted: AtomicBool,+ cached: RwLock<Option<CachedDecision>>,+}++struct DrainedDemand<'a> {+ state: &'a TargetState,+ delta: u64,+ interrupted: bool,+ committed: bool,+}++impl Drop for DrainedDemand<'_> {+ fn drop(&mut self) {+ if !self.committed {+ // Includes cancellation while a publish acknowledgement is in flight.+ self.state.interrupted.store(true, Ordering::Relaxed);+ }+ }+}++#[derive(Clone, Copy)]+struct CachedDecision {+ decision: ThresholdDecision,+ expires_at: Instant,+}++struct LeaseObservation {+ revision: u64,+ lease: Lease,+ read_started: Instant,+ expires_at: Option<Instant>,+}++struct TickState {+ last_started: Instant,+ observed: Option<LeaseObservation>,+}++/// Control-state connection for a separate NATS endpoint. Inference workers+/// and configuration publishers must not have credentials for that endpoint.+/// Do not pass the inference queue's JetStream context: subject ACLs cannot+/// establish control-record provenance inside a shared account.+pub struct ThresholdCoordinator {+ counters: kv::Store,+ decisions: kv::Store,+ leases: kv::Store,+ targets: HashMap<String, TargetState>,+ generation: u64,+ contract: String,+ tick: tokio::sync::Mutex<TickState>,+}++impl ThresholdCoordinator {+ pub async fn connect(+ context: &jetstream::Context,+ replicas: usize,+ targets: Vec<ThresholdTarget>,+ ) -> Result<Self, ThresholdError> {+ if targets.is_empty() || targets.len() > MAX_THRESHOLD_MODELS || !matches!(replicas, 1 | 3)+ {+ return Err(ThresholdError::Configuration);+ }+ let generation = targets[0].generation;+ if targets.iter().any(|target| target.generation != generation) {+ return Err(ThresholdError::Configuration);+ }+ let mut contracts = targets+ .iter()+ .map(|target| (&target.key, &target.contract))+ .collect::<Vec<_>>();+ contracts.sort_unstable();+ let mut digest = Sha256::new();+ for (key, contract) in contracts {+ digest.update(key.as_bytes());+ digest.update(contract.as_bytes());+ }+ let contract = hex_digest(&digest.finalize());+ let count = targets.len();+ let targets = targets+ .into_iter()+ .map(|target| {+ (+ target.key.clone(),+ TargetState {+ target,+ pending: AtomicU64::new(0),+ interrupted: AtomicBool::new(false),+ cached: RwLock::new(None),+ },+ )+ })+ .collect::<HashMap<_, _>>();+ if targets.len() != count {+ return Err(ThresholdError::Configuration);+ }+ timeout(async {+ Ok(Self {+ counters: bucket(context, "SIE_THRESHOLD_COUNTS", COUNTER_TTL, replicas).await?,+ decisions: bucket(context, "SIE_THRESHOLD_DECISIONS", LEASE_TTL * 2, replicas)+ .await?,+ leases: bucket(context, "SIE_THRESHOLD_LEASE", LEASE_TTL, replicas).await?,+ targets,+ generation,+ contract,+ tick: tokio::sync::Mutex::new(TickState {+ last_started: Instant::now(),+ observed: None,+ }),+ })+ })+ .await+ }++ /// Count once after shared caller validation, before profile recursion.+ /// Request handling never waits for the control broker.+ pub fn record_request(&self, model: &str) -> Result<(), ThresholdError> {+ let state = self+ .targets+ .get(&digest_key(model))+ .ok_or(ThresholdError::Configuration)?;+ state+ .pending+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |total| {+ total.checked_add(1)+ })+ .map_err(|_| {+ state.interrupted.store(true, Ordering::Relaxed);+ ThresholdError::Untrusted+ })?;+ Ok(())+ }++ async fn counter_total(+ &self,+ target: &ThresholdTarget,+ delta: u64,+ interrupted: bool,+ ) -> Result<Counter, ThresholdError> {+ for _ in 0..CAS_ATTEMPTS {+ let (revision, existing) = read::<Counter>(&self.counters, &target.key).await?;+ let (mut counter, current) = match existing {+ Some(counter) => {+ if counter.generation > target.generation+ || (counter.generation == target.generation+ && counter.contract != target.contract)+ {+ return Err(ThresholdError::Generation);+ }+ let current = counter.generation == target.generation;+ let counter = if current {+ counter+ } else {+ Counter {+ generation: target.generation,+ contract: target.contract.clone(),+ total: 0,+ incarnation: Uuid::new_v4().to_string(),+ continuity: 0,+ }+ };+ (counter, current)+ }+ None => (+ Counter {+ generation: target.generation,+ contract: target.contract.clone(),+ total: 0,+ incarnation: Uuid::new_v4().to_string(),+ continuity: 0,+ },+ false,+ ),+ };+ if Uuid::parse_str(&counter.incarnation).is_err() {+ return Err(ThresholdError::Untrusted);+ }+ if delta == 0 && !interrupted && current {+ return Ok(counter);+ }+ counter.total = counter+ .total+ .checked_add(delta)+ .ok_or(ThresholdError::Untrusted)?;+ if interrupted {+ counter.continuity = counter+ .continuity+ .checked_add(1)+ .ok_or(ThresholdError::Untrusted)?;+ }+ match self+ .counters+ .update(&target.key, encode(&counter)?, revision)+ .await+ {+ Ok(_) => return Ok(counter),+ Err(error) if error.kind() == kv::UpdateErrorKind::WrongLastRevision => {}+ // An uncertain acknowledgement may follow a successful commit.+ // Never restore or retry its already-drained demand delta.+ Err(_) => return Err(ThresholdError::Unavailable),+ }+ tokio::task::yield_now().await;+ }+ Err(ThresholdError::Contended)+ }++ /// Every replica calls this once per second, including standby gateways.+ /// It flushes local demand before election and refreshes local decisions.+ pub async fn sample(&self, sampler: &mut ThresholdSampler) -> Result<(), ThresholdError> {+ let mut attempt = SamplingAttempt {+ sampler,+ succeeded: false,+ };+ let sampler = &mut *attempt.sampler;+ let mut standby_refreshed = false;+ let result = timeout(async {+ let mut tick = self.tick.lock().await;+ let now = Instant::now();+ let gap = now.saturating_duration_since(tick.last_started) > MAX_SAMPLE_GAP;+ tick.last_started = now;+ // Drain atomically before I/O. Requests racing this swap stay in the+ // next batch; a timed-out batch is never restored or counted twice.+ let deltas = self+ .targets+ .values()+ .map(|state| {+ let delta = state.pending.swap(0, Ordering::Relaxed);+ let interrupted = state.interrupted.swap(false, Ordering::Relaxed) || gap;+ DrainedDemand {+ state,+ delta: if gap { 0 } else { delta },+ interrupted,+ committed: false,+ }+ })+ .collect::<Vec<_>>();+ for mut demand in deltas {+ self.counter_total(&demand.state.target, demand.delta, demand.interrupted)+ .await?;+ demand.committed = true;+ }+ let (previous_revision, previous) = read::<Lease>(&self.leases, LEASE_KEY).await?;+ let mut renewal_started = None;+ let term = match previous {+ Some(lease) => {+ validate_lease(&lease)?;+ if lease.generation > self.generation+ || (lease.generation == self.generation && lease.contract != self.contract)+ {+ return Err(ThresholdError::Generation);+ }+ if lease.generation < self.generation {+ sampler.models.clear();+ Some(Uuid::new_v4().to_string())+ } else if lease.owner == sampler.owner+ && previous_revision == sampler.lease_revision+ && sampler.term.as_deref() == Some(lease.term.as_str())+ {+ Some(lease.term)+ } else {+ None+ }+ }+ None => {+ sampler.models.clear();+ Some(Uuid::new_v4().to_string())+ }+ };+ if let Some(term) = term {+ let started = Instant::now();+ sampler.lease_revision = self+ .leases+ .update(+ LEASE_KEY,+ encode(&Lease {+ owner: sampler.owner.clone(),+ generation: self.generation,+ contract: self.contract.clone(),+ term: term.clone(),+ })?,+ previous_revision,+ )+ .await+ .map_err(|_| ThresholdError::Unavailable)?;+ sampler.term = Some(term.clone());+ renewal_started = Some(started);+ sampler+ .models+ .retain(|key, _| self.targets.contains_key(key));+ for state in self.targets.values() {+ let target = &state.target;+ let counter = self.counter_total(target, 0, false).await?;+ let now = Instant::now();+ let sampled = sampler+ .models+ .entry(target.key.clone())+ .or_insert_with(|| SampleState::baseline(target, counter.total, now));+ if gap+ || sampled.continuity != counter.continuity+ || sampled.incarnation.as_deref() != Some(counter.incarnation.as_str())+ {+ *sampled = SampleState::baseline(target, counter.total, now);+ sampled.continuity = counter.continuity;+ sampled.incarnation = Some(counter.incarnation.clone());+ }+ let decision = sampled.sample(target, counter.total, now);+ self.decisions+ .put(+ &target.key,+ encode(&Decision {+ generation: target.generation,+ contract: target.contract.clone(),+ owner: sampler.owner.clone(),+ term: term.clone(),+ decision,+ })?,+ )+ .await+ .map_err(|_| ThresholdError::Unavailable)?;+ }+ }+ self.refresh_decisions(&mut tick, renewal_started).await?;+ if renewal_started.is_none() {+ standby_refreshed = true;+ Err(ThresholdError::Unavailable)+ } else {+ Ok(())+ }+ })+ .await;+ if result.is_err() && !standby_refreshed {+ for state in self.targets.values() {+ state.interrupted.store(true, Ordering::Relaxed);+ if let Ok(mut cached) = state.cached.write() {+ *cached = None;+ }+ }+ }+ attempt.succeeded = result.is_ok();+ result+ }++ async fn refresh_decisions(+ &self,+ tick: &mut TickState,+ renewal_started: Option<Instant>,+ ) -> Result<(), ThresholdError> {+ let started = Instant::now();+ let (revision, lease) = read::<Lease>(&self.leases, LEASE_KEY).await?;+ let lease = lease.ok_or(ThresholdError::Unavailable)?;+ validate_lease(&lease)?;+ if lease.generation != self.generation || lease.contract != self.contract {+ return Err(ThresholdError::Generation);+ }+ let mut verified = Vec::with_capacity(self.targets.len());+ for state in self.targets.values() {+ let (_, decision) = read::<Decision>(&self.decisions, &state.target.key).await?;+ let decision = if let Some(decision) = decision {+ if decision.generation != state.target.generation+ || decision.contract != state.target.contract+ {+ return Err(ThresholdError::Generation);+ }+ if decision.owner != lease.owner || decision.term != lease.term {+ return Err(ThresholdError::Unavailable);+ }+ (decision.decision != ThresholdDecision::Undetermined).then_some(decision.decision)+ } else {+ None+ };+ verified.push((state, decision));+ }+ let latest_started = Instant::now();+ let (latest_revision, latest) = read::<Lease>(&self.leases, LEASE_KEY).await?;+ if latest.as_ref() != Some(&lease) {+ return Err(ThresholdError::Unavailable);+ }+ // A reader cannot know a lease's age on first sight without shared+ // clocks. A locally-started renewal or an observed revision advance+ // proves a lower bound on its commit time on this monotonic clock.+ let mut expires_at = renewal_started.map(|at| at + LEASE_TTL);+ if latest_revision != revision {+ expires_at = Some(started + LEASE_TTL);+ }+ if let Some(previous) = &tick.observed {+ if previous.lease == lease {+ let bound = if previous.revision != latest_revision {+ Some(previous.read_started + LEASE_TTL)+ } else {+ previous.expires_at+ };+ expires_at = expires_at.max(bound);+ }+ }+ tick.observed = Some(LeaseObservation {+ revision: latest_revision,+ lease,+ read_started: latest_started,+ expires_at,+ });+ let deadline = expires_at.map(|bound| bound.min(started + THRESHOLD_SAMPLE_INTERVAL));+ for (state, decision) in verified {+ *state+ .cached+ .write()+ .map_err(|_| ThresholdError::Unavailable)? =+ deadline+ .zip(decision)+ .map(|(expires_at, decision)| CachedDecision {+ decision,+ expires_at,+ });+ }+ Ok(())+ }++ /// Return only a recently verified local value. Expired or unavailable+ /// authority must preserve the ordinary local warm-up/fallback path.+ pub fn decision(&self, model: &str) -> Result<ThresholdDecision, ThresholdError> {+ let state = self+ .targets+ .get(&digest_key(model))+ .ok_or(ThresholdError::Configuration)?;+ let cached = state+ .cached+ .read()+ .map_err(|_| ThresholdError::Unavailable)?;+ match *cached {+ Some(cached) if Instant::now() < cached.expires_at => Ok(cached.decision),+ _ => Err(ThresholdError::Unavailable),+ }+ }+}++fn validate_lease(lease: &Lease) -> Result<(), ThresholdError> {+ if lease.generation == 0+ || lease.contract.len() != 64+ || !lease+ .contract+ .bytes()+ .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())+ || Uuid::parse_str(&lease.owner).is_err()+ || Uuid::parse_str(&lease.term).is_err()+ {+ return Err(ThresholdError::Untrusted);+ }+ Ok(())+}++async fn timeout<T>(+ future: impl std::future::Future<Output = Result<T, ThresholdError>>,+) -> Result<T, ThresholdError> {+ tokio::time::timeout(IO_TIMEOUT, future)+ .await+ .map_err(|_| ThresholdError::Unavailable)?+}++fn encode(value: &impl Serialize) -> Result<Bytes, ThresholdError> {+ let bytes = serde_json::to_vec(value).map_err(|_| ThresholdError::Untrusted)?;+ if bytes.len() > MAX_VALUE_BYTES {+ return Err(ThresholdError::Untrusted);+ }+ Ok(bytes.into())+}++async fn read<T: DeserializeOwned>(+ store: &kv::Store,+ key: &str,+) -> Result<(u64, Option<T>), ThresholdError> {+ let subject = format!("$KV.{}.{key}", store.name);+ // The leader API preserves stored headers. Direct-get and ordinary KV+ // helpers lose the distinction between a gateway publish and a worker's+ // server-republished bytes, which must never authorize remote routing.+ let message = match store.stream.get_last_raw_message_by_subject(&subject).await {+ Ok(message) => message,+ Err(error) if error.kind() == stream::RawMessageErrorKind::NoMessageFound => {+ return Ok((0, None))+ }+ Err(_) => return Err(ThresholdError::Unavailable),+ };+ if message.subject.as_str() != subject || message.payload.len() > MAX_VALUE_BYTES {+ return Err(ThresholdError::Untrusted);+ }+ let mut seen = HashSet::new();+ let mut operation = None;+ let mut rollup = None;+ for (name, values) in message.headers.iter() {+ let name: &str = name.as_ref();+ if values.len() != 1 || !seen.insert(name.to_ascii_lowercase()) {+ return Err(ThresholdError::Untrusted);+ }+ if name.eq_ignore_ascii_case("Nats-Expected-Last-Subject-Sequence") {+ if values[0].as_str().parse::<u64>().is_err() {+ return Err(ThresholdError::Untrusted);+ }+ } else if name.eq_ignore_ascii_case("KV-Operation") {+ operation = Some(values[0].as_str());+ } else if name.eq_ignore_ascii_case("Nats-Rollup") {+ rollup = Some(values[0].as_str());+ } else {+ return Err(ThresholdError::Untrusted);+ }+ }+ if rollup.is_some() && (rollup != Some("sub") || operation != Some("PURGE")) {+ return Err(ThresholdError::Untrusted);+ }+ if let Some(operation) = operation {+ return if matches!(operation, "DEL" | "PURGE") {+ Ok((message.sequence, None))+ } else {+ Err(ThresholdError::Untrusted)+ };+ }+ let value = serde_json::from_slice(&message.payload).map_err(|_| ThresholdError::Untrusted)?;+ Ok((message.sequence, Some(value)))+}++async fn bucket(+ context: &jetstream::Context,+ name: &str,+ age: Duration,+ replicas: usize,+) -> Result<kv::Store, ThresholdError> {+ let store = context+ .create_key_value(kv::Config {+ bucket: name.to_string(),+ max_value_size: MAX_VALUE_BYTES as i32,+ max_bytes: MAX_BUCKET_BYTES,+ history: 1,+ max_age: age,+ storage: stream::StorageType::Memory,+ num_replicas: replicas,+ ..Default::default()+ })+ .await+ .map_err(|_| ThresholdError::Unavailable)?;+ let config = &store.stream.cached_info().config;+ if config.max_age != age+ || config.max_message_size != MAX_VALUE_BYTES as i32+ || config.max_bytes != MAX_BUCKET_BYTES+ || config.max_messages_per_subject != 1+ || config.num_replicas != replicas+ || config.storage != stream::StorageType::Memory+ || config.subjects != [format!("$KV.{name}.>")]+ || config.republish.is_some()+ || config.mirror.is_some()+ || config+ .sources+ .as_ref()+ .is_some_and(|sources| !sources.is_empty())+ {+ return Err(ThresholdError::Untrusted);+ }+ Ok(store)+}++fn digest_key(model: &str) -> String {+ hex_digest(&Sha256::digest(model.as_bytes()))+}++fn hex_digest(bytes: &[u8]) -> String {+ bytes.iter().map(|byte| format!("{byte:02x}")).collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn target() -> ThresholdTarget {+ let routing: RoutingConfig = serde_json::from_value(json!({+ "policy":"threshold", "fallback_profile":"remote", "wake_above":2,+ "sleep_below":0.5, "window_s":2, "cooldown_s":2+ }))+ .unwrap();+ ThresholdTarget::new("acme/chat", 1, &"a".repeat(64), &routing).unwrap()+ }++ #[test]+ fn sustained_shared_rate_wakes_and_idle_cooldown_returns_remote() {+ let target = target();+ let now = Instant::now();+ let mut state = SampleState::baseline(&target, 0, now);+ for second in 1..=2 {+ assert_eq!(+ state.sample(&target, second * 3, now + Duration::from_secs(second)),+ ThresholdDecision::Undetermined+ );+ }+ assert_eq!(+ state.sample(&target, 9, now + Duration::from_secs(3)),+ ThresholdDecision::WakeLocal+ );+ for second in 4..=5 {+ assert_eq!(+ state.sample(&target, 9, now + Duration::from_secs(second)),+ ThresholdDecision::WakeLocal+ );+ }+ assert_eq!(+ state.sample(&target, 9, now + Duration::from_secs(6)),+ ThresholdDecision::Remote+ );+ }++ #[test]+ fn interrupted_rates_and_timer_gaps_do_not_manufacture_sustained_demand() {+ let target = target();+ let now = Instant::now();+ let mut state = SampleState::baseline(&target, 0, now);+ assert_eq!(+ state.sample(&target, 3, now + Duration::from_secs(1)),+ ThresholdDecision::Undetermined+ );+ // Equality is not above the wake boundary.+ assert_eq!(+ state.sample(&target, 5, now + Duration::from_secs(2)),+ ThresholdDecision::Undetermined+ );+ assert_eq!(+ state.sample(&target, 8, now + Duration::from_secs(3)),+ ThresholdDecision::Undetermined+ );+ assert_eq!(+ state.sample(&target, 11, now + Duration::from_secs(4)),+ ThresholdDecision::Undetermined+ );+ assert_eq!(+ state.sample(&target, 14, now + Duration::from_secs(5)),+ ThresholdDecision::WakeLocal+ );+ // A suspended sampler discards its window evidence and rate baseline.+ assert_eq!(+ state.sample(&target, 999, now + Duration::from_secs(10)),+ ThresholdDecision::Undetermined+ );+ assert_eq!(+ state.sample(&target, 1002, now + Duration::from_secs(11)),+ ThresholdDecision::Undetermined+ );+ let mut changed = target.clone();+ changed.generation += 1;+ assert_eq!(+ state.sample(&changed, 1005, now + Duration::from_secs(12)),+ ThresholdDecision::Undetermined+ );+ assert_eq!(state.generation, changed.generation);+ }++ #[test]+ fn rapid_sampling_keeps_the_counter_baseline_and_binds_all_policy_fields() {+ let target = target();+ let now = Instant::now();+ let mut state = SampleState::baseline(&target, 0, now);+ state.sample(&target, 10, now + Duration::from_millis(10));+ assert_eq!(state.total, 0);+ assert_eq!(state.sampled_at, now);+ let routing: RoutingConfig = serde_json::from_value(json!({+ "policy":"threshold", "fallback_profile":"remote", "wake_above":3,+ "sleep_below":0.5, "window_s":2, "cooldown_s":2+ }))+ .unwrap();+ let changed = ThresholdTarget::new("acme/chat", 1, &"a".repeat(64), &routing).unwrap();+ assert_ne!(target.contract, changed.contract);+ assert_eq!(target.key, changed.key);+ assert!(ThresholdTarget::new("acme/chat:remote", 1, &"a".repeat(64), &routing).is_err());+ assert!(ThresholdTarget::new("acme/chat", 1, "unverified", &routing).is_err());+ }+}diff --git a/packages/sie_gateway/tests/nats_auth.rs b/packages/sie_gateway/tests/nats_auth.rsindex 8ddf2050c..9a9ddcee2 100644--- a/packages/sie_gateway/tests/nats_auth.rs+++ b/packages/sie_gateway/tests/nats_auth.rs@@ -54,6 +54,10 @@ fn nats_server_binary() -> Option<PathBuf> {}async fn start_nats() -> Option<NatsServer> {+ start_nats_fixture("sie-cluster-nats.conf").await+}++async fn start_nats_fixture(fixture: &str) -> Option<NatsServer> {let Some(binary) = nats_server_binary() else {assert!(std::env::var_os("NATS_URL").is_none(),@@ -62,8 +66,9 @@ async fn start_nats() -> Option<NatsServer> {eprintln!("skipping: nats-server not on PATH");return None;};- let config =- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/ci/fixtures/sie-cluster-nats.conf");+ let config = Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../tools/ci/fixtures")+ .join(fixture);let dir = tempfile::tempdir().expect("tempdir");let log = std::fs::File::create(dir.path().join("nats.log")).expect("log file");let passwords = Passwords {@@ -106,6 +111,30 @@ async fn start_nats() -> Option<NatsServer> {panic!("nats-server did not start:\n{log}");}+// Broker expiry is asynchronous; elapsed gateway time alone does not prove+// that its leader API has stopped exposing the five-second lease.+async fn wait_for_threshold_lease_expiry(leases: &jetstream::kv::Store) {+ tokio::time::timeout(Duration::from_secs(7), async {+ loop {+ match leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ {+ Err(error)+ if error.kind() == jetstream::stream::RawMessageErrorKind::NoMessageFound =>+ {+ return;+ }+ Ok(_) => tokio::time::sleep(Duration::from_millis(50)).await,+ Err(error) => panic!("failed to observe threshold lease expiry: {error}"),+ }+ }+ })+ .await+ .expect("threshold broker must expire the lease within five seconds plus scheduling margin");+}+/// The client URL from the `*.ports` file nats-server writes once it listens.fn listening_url(dir: &Path) -> Option<String> {let ports = std::fs::read_dir(dir)@@ -431,3 +460,579 @@ async fn dlq_forwards_only_advisories_the_server_emits() {"the republished advisory is not forwarded");}++#[tokio::test]+async fn threshold_decisions_share_demand_and_require_current_sampler_authority() {+ use sha2::{Digest, Sha256};+ use sie_gateway::state::threshold_coordinator::{+ ThresholdCoordinator, ThresholdDecision, ThresholdError, ThresholdSampler, ThresholdTarget,+ };++ let Some(mut nats) = start_nats_fixture("sie-threshold-nats.conf").await else {+ return;+ };+ let gateway = connect_as(&nats.url, "sie-gateway", &nats.passwords.gateway).await;+ let context = jetstream::new(gateway.clone());+ let policy = serde_json::from_value(serde_json::json!({+ "policy":"threshold", "fallback_profile":"remote", "wake_above":1,+ "sleep_below":0.5, "window_s":1, "cooldown_s":1+ }))+ .unwrap();+ let target = ThresholdTarget::new("acme/chat", 1, &"a".repeat(64), &policy).unwrap();+ let first = Arc::new(+ ThresholdCoordinator::connect(&context, 1, vec![target.clone()])+ .await+ .unwrap(),+ );+ let second = Arc::new(+ ThresholdCoordinator::connect(&context, 1, vec![target])+ .await+ .unwrap(),+ );+ let mut owner = ThresholdSampler::default();+ let mut standby = ThresholdSampler::default();+ first.sample(&mut owner).await.unwrap();+ assert_eq!(+ second.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );++ let mut tasks = Vec::new();+ for replica in [first.clone(), second.clone()] {+ for _ in 0..4 {+ let replica = replica.clone();+ tasks.push(tokio::spawn(+ async move { replica.record_request("acme/chat") },+ ));+ }+ }+ for task in tasks {+ task.await.unwrap().unwrap();+ }+ let key = Sha256::digest(b"acme/chat")+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>();+ let subject = format!("$KV.SIE_THRESHOLD_COUNTS.{key}");+ let stream = context.get_stream("KV_SIE_THRESHOLD_COUNTS").await.unwrap();+ tokio::time::sleep(Duration::from_millis(1050)).await;+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ first.sample(&mut owner).await.unwrap();+ let counter = stream+ .get_last_raw_message_by_subject(&subject)+ .await+ .unwrap();+ let counter: serde_json::Value = serde_json::from_slice(&counter.payload).unwrap();+ assert_eq!(+ counter["total"], 8,+ "standby and owner flush each local ingress once into the aggregate"+ );+ assert_eq!(+ second.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ for replica in [&first, &second] {+ replica.record_request("acme/chat").unwrap();+ }+ tokio::time::sleep(Duration::from_millis(1050)).await;+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ first.sample(&mut owner).await.unwrap();+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ assert_eq!(+ first.decision("acme/chat").unwrap(),+ ThresholdDecision::WakeLocal+ );+ assert_eq!(+ second.decision("acme/chat").unwrap(),+ ThresholdDecision::WakeLocal+ );+ for _ in 0..2 {+ tokio::time::sleep(Duration::from_millis(1050)).await;+ first.sample(&mut owner).await.unwrap();+ }+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ assert_eq!(+ second.decision("acme/chat").unwrap(),+ ThresholdDecision::Remote+ );++ // First sight provides no clock-free bound on the age of a lease.+ let newcomer = ThresholdCoordinator::connect(+ &context,+ 1,+ vec![ThresholdTarget::new("acme/chat", 1, &"a".repeat(64), &policy).unwrap()],+ )+ .await+ .unwrap();+ let mut newcomer_sampler = ThresholdSampler::default();+ assert_eq!(+ newcomer.sample(&mut newcomer_sampler).await,+ Err(ThresholdError::Unavailable)+ );+ assert_eq!(+ newcomer.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ first.sample(&mut owner).await.unwrap();+ assert_eq!(+ newcomer.sample(&mut newcomer_sampler).await,+ Err(ThresholdError::Unavailable)+ );+ assert_eq!(+ newcomer.decision("acme/chat").unwrap(),+ ThresholdDecision::Remote+ );++ // A normal renewal keeps the acquisition term and accepts its earlier+ // decision even before the sampler publishes the next model decision.+ let leases = context.get_key_value("SIE_THRESHOLD_LEASE").await.unwrap();+ let old = leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ .unwrap();+ let old_lease: serde_json::Value = serde_json::from_slice(&old.payload).unwrap();+ leases+ .update("sampler", old.payload, old.sequence)+ .await+ .unwrap();+ let renewed_at = tokio::time::Instant::now();+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ assert_eq!(+ second.decision("acme/chat").unwrap(),+ ThresholdDecision::Remote+ );+ let renewed = leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ .unwrap();+ let renewed: serde_json::Value = serde_json::from_slice(&renewed.payload).unwrap();+ assert_eq!(old_lease["term"], renewed["term"]);+ tokio::time::sleep_until(renewed_at + Duration::from_millis(1050)).await;+ assert_eq!(+ second.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );++ // Refreshing near expiry cannot extend the lease with another cache TTL.+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ tokio::time::sleep_until(renewed_at + Duration::from_millis(2500)).await;+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ tokio::time::sleep_until(renewed_at + Duration::from_millis(4250)).await;+ assert!(+ (renewed_at + Duration::from_secs(5))+ .saturating_duration_since(tokio::time::Instant::now())+ > Duration::from_millis(500),+ "near-expiry refresh requires a safe margin before broker lease expiry"+ );+ assert_eq!(+ second.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ assert_eq!(+ second.decision("acme/chat").unwrap(),+ ThresholdDecision::Remote+ );+ tokio::time::sleep_until(renewed_at + Duration::from_millis(5100)).await;+ assert_eq!(+ second.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );++ // The broker, rather than either replica's wall clock, expires ownership.+ assert_eq!(+ first.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ wait_for_threshold_lease_expiry(&leases).await;+ second.sample(&mut standby).await.unwrap();+ assert_eq!(+ first.sample(&mut owner).await,+ Err(ThresholdError::Unavailable)+ );+ assert_eq!(+ first.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );++ let next = ThresholdTarget::new("acme/chat", 2, &"b".repeat(64), &policy).unwrap();+ let changed = ThresholdCoordinator::connect(&context, 1, vec![next])+ .await+ .unwrap();+ // A new generation takes over even when the model receives no request.+ changed.sample(&mut standby).await.unwrap();+ assert_eq!(+ first.sample(&mut owner).await,+ Err(ThresholdError::Generation)+ );+ assert_eq!(+ first.sample(&mut owner).await,+ Err(ThresholdError::Generation)+ );+ // Request recording is local even on a stale replica. Its flush refuses+ // the newer authority and cannot add this demand to the new generation.+ first.record_request("acme/chat").unwrap();+ assert_eq!(+ first.sample(&mut owner).await,+ Err(ThresholdError::Generation)+ );+ assert_eq!(+ first.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ let reset = stream+ .get_last_raw_message_by_subject(&subject)+ .await+ .unwrap();+ let reset: serde_json::Value = serde_json::from_slice(&reset.payload).unwrap();+ assert_eq!(reset["generation"], 2);+ assert_eq!(+ reset["total"], 0,+ "sampling does not manufacture ingress demand"+ );+ for _ in 0..2 {+ tokio::time::sleep(Duration::from_millis(1050)).await;+ changed.sample(&mut standby).await.unwrap();+ }+ assert_eq!(+ changed.decision("acme/chat").unwrap(),+ ThresholdDecision::Remote+ );++ // Broker errors discard sustained-window evidence and prevent renewal.+ let mut newest_target = ThresholdTarget::new("acme/chat", 3, &"c".repeat(64), &policy).unwrap();+ let newest = ThresholdCoordinator::connect(&context, 1, vec![newest_target.clone()])+ .await+ .unwrap();+ newest.sample(&mut standby).await.unwrap();+ for _ in 0..4 {+ newest.record_request("acme/chat").unwrap();+ }+ tokio::time::sleep(Duration::from_millis(1050)).await;+ newest.sample(&mut standby).await.unwrap();+ let counts = context.get_key_value("SIE_THRESHOLD_COUNTS").await.unwrap();+ counts+ .put(&key, bytes::Bytes::from_static(b"invalid"))+ .await+ .unwrap();+ assert_eq!(+ newest.sample(&mut standby).await,+ Err(ThresholdError::Untrusted)+ );+ assert_eq!(+ newest.sample(&mut standby).await,+ Err(ThresholdError::Untrusted)+ );+ let failed_lease = leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ .unwrap();+ let restored = serde_json::json!({"generation":2,"contract":"obsolete","total":0,+ "incarnation":uuid::Uuid::new_v4().to_string()});+ counts+ .put(&key, serde_json::to_vec(&restored).unwrap().into())+ .await+ .unwrap();+ // Repairing storage cannot restore the failed sampler's old ownership.+ // Until actual broker expiry it must refuse to renew, even with valid data.+ assert_eq!(+ newest.sample(&mut standby).await,+ Err(ThresholdError::Unavailable)+ );+ let refused_lease = leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ .unwrap();+ assert_eq!(+ refused_lease.sequence, failed_lease.sequence,+ "failed sampler must leave the existing lease revision unchanged"+ );+ wait_for_threshold_lease_expiry(&leases).await;+ // A single recovery call must succeed once the leader confirms expiry;+ // timeouts or unavailable storage remain test failures, not retry cases.+ newest.sample(&mut standby).await.unwrap();+ assert_eq!(+ newest.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ for tick in 0..2 {+ for _ in 0..4 {+ newest.record_request("acme/chat").unwrap();+ }+ tokio::time::sleep(Duration::from_millis(1050)).await;+ newest.sample(&mut standby).await.unwrap();+ if tick == 0 {+ assert_eq!(+ newest.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ }+ }+ assert_eq!(+ newest.decision("acme/chat").unwrap(),+ ThresholdDecision::WakeLocal+ );++ // DEL and PURGE preserve their broker revisions for the next CAS.+ // Lease recreation also changes the UUID term, fencing old decisions.+ let before = leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ .unwrap();+ let before: serde_json::Value = serde_json::from_slice(&before.payload).unwrap();+ for purge in [false, true] {+ if purge {+ counts.purge(&key).await.unwrap();+ leases.purge("sampler").await.unwrap();+ } else {+ counts.delete(&key).await.unwrap();+ leases.delete("sampler").await.unwrap();+ }+ newest.sample(&mut standby).await.unwrap();+ let reset = counts+ .stream+ .get_last_raw_message_by_subject(&subject)+ .await+ .unwrap();+ let reset: serde_json::Value = serde_json::from_slice(&reset.payload).unwrap();+ assert_eq!(reset["total"], 0);+ assert_eq!(+ newest.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ let recreated = leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ .unwrap();+ let recreated: serde_json::Value = serde_json::from_slice(&recreated.payload).unwrap();+ assert_ne!(before["term"], recreated["term"]);+ }++ // A long publication gap discards accumulated demand and window evidence.+ for _ in 0..100 {+ newest.record_request("acme/chat").unwrap();+ }+ tokio::time::sleep(Duration::from_millis(2600)).await;+ newest.sample(&mut standby).await.unwrap();+ let reset = counts+ .stream+ .get_last_raw_message_by_subject(&subject)+ .await+ .unwrap();+ let reset: serde_json::Value = serde_json::from_slice(&reset.payload).unwrap();+ assert_eq!(+ reset["total"], 0,+ "late demand is never presented as a fresh burst"+ );+ assert_eq!(+ newest.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );++ // Ingress racing an asynchronous drain stays in exactly one batch.+ let ((), sampled) = tokio::join!(+ async {+ for _ in 0..1000 {+ newest.record_request("acme/chat").unwrap();+ tokio::task::yield_now().await;+ }+ },+ newest.sample(&mut standby)+ );+ sampled.unwrap();+ newest.sample(&mut standby).await.unwrap();+ let total = counts+ .stream+ .get_last_raw_message_by_subject(&subject)+ .await+ .unwrap();+ let total: serde_json::Value = serde_json::from_slice(&total.payload).unwrap();+ assert_eq!(+ total["total"], 1000,+ "racing ingress is neither lost nor doubled"+ );++ // Duplicate, oversized or mixed-generation configurations never reach I/O.+ assert!(matches!(+ ThresholdCoordinator::connect(&context, 1, vec![]).await,+ Err(ThresholdError::Configuration)+ ));+ assert!(matches!(+ ThresholdCoordinator::connect(+ &context,+ 1,+ vec![newest_target.clone(), newest_target.clone()]+ )+ .await,+ Err(ThresholdError::Configuration)+ ));+ assert!(matches!(+ ThresholdCoordinator::connect(&context, 1, vec![newest_target.clone(); 257]).await,+ Err(ThresholdError::Configuration)+ ));+ newest_target = ThresholdTarget::new("acme/other", 4, &"c".repeat(64), &policy).unwrap();+ assert!(matches!(+ ThresholdCoordinator::connect(+ &context,+ 1,+ vec![+ ThresholdTarget::new("acme/chat", 3, &"c".repeat(64), &policy).unwrap(),+ newest_target+ ]+ )+ .await,+ Err(ThresholdError::Configuration)+ ));++ // Inference-component credentials have no authority on this endpoint.+ for (user, password) in [+ ("sie-worker", &nats.passwords.worker),+ ("sie-config", &nats.passwords.config),+ ] {+ assert!(async_nats::ConnectOptions::new()+ .user_and_password(user.into(), password.clone())+ .connect(&nats.url)+ .await+ .is_err());+ }+ // Local request handling remains available with the control broker down.+ nats.child.kill().unwrap();+ nats.child.wait().unwrap();+ newest.record_request("acme/chat").unwrap();+ assert_eq!(+ newest.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ assert!(newest.sample(&mut standby).await.is_err());+}++#[tokio::test]+async fn threshold_counter_recreation_discards_evidence_even_when_totals_increase() {+ use sha2::{Digest, Sha256};+ use sie_gateway::state::threshold_coordinator::{+ ThresholdCoordinator, ThresholdDecision, ThresholdError, ThresholdSampler, ThresholdTarget,+ };+ let Some(nats) = start_nats_fixture("sie-threshold-nats.conf").await else {+ return;+ };+ let gateway = connect_as(&nats.url, "sie-gateway", &nats.passwords.gateway).await;+ let context = jetstream::new(gateway);+ let policy = serde_json::from_value(serde_json::json!({+ "policy":"threshold", "fallback_profile":"remote", "wake_above":5,+ "sleep_below":2, "window_s":1, "cooldown_s":1+ }))+ .unwrap();+ let target = ThresholdTarget::new("acme/chat", 1, &"a".repeat(64), &policy).unwrap();+ let owner = ThresholdCoordinator::connect(&context, 1, vec![target.clone()])+ .await+ .unwrap();+ let standby = ThresholdCoordinator::connect(&context, 1, vec![target])+ .await+ .unwrap();+ let mut owner_sampler = ThresholdSampler::default();+ let mut standby_sampler = ThresholdSampler::default();+ owner.sample(&mut owner_sampler).await.unwrap();+ assert_eq!(+ standby.sample(&mut standby_sampler).await,+ Err(ThresholdError::Unavailable)+ );+ let key = Sha256::digest(b"acme/chat")+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>();+ let subject = format!("$KV.SIE_THRESHOLD_COUNTS.{key}");+ let counts = context.get_key_value("SIE_THRESHOLD_COUNTS").await.unwrap();+ let leases = context.get_key_value("SIE_THRESHOLD_LEASE").await.unwrap();+ for purge in [false, true] {+ for _ in 0..2 {+ for _ in 0..500 {+ owner.record_request("acme/chat").unwrap();+ }+ tokio::time::sleep(Duration::from_millis(1050)).await;+ owner.sample(&mut owner_sampler).await.unwrap();+ }+ assert_eq!(+ owner.decision("acme/chat").unwrap(),+ ThresholdDecision::WakeLocal+ );+ let prior = counts+ .stream+ .get_last_raw_message_by_subject(&subject)+ .await+ .unwrap();+ let prior: serde_json::Value = serde_json::from_slice(&prior.payload).unwrap();+ let lease = leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ .unwrap();+ let lease: serde_json::Value = serde_json::from_slice(&lease.payload).unwrap();+ if purge {+ counts.purge(&key).await.unwrap();+ } else {+ counts.delete(&key).await.unwrap();+ }+ // The new counter can already exceed the previous cumulative total.+ // Total rollback and a continuity integer alone cannot detect this.+ for _ in 0..=prior["total"].as_u64().unwrap() {+ standby.record_request("acme/chat").unwrap();+ }+ assert_eq!(+ standby.sample(&mut standby_sampler).await,+ Err(ThresholdError::Unavailable)+ );+ owner.sample(&mut owner_sampler).await.unwrap();+ assert_eq!(+ owner.decision("acme/chat"),+ Err(ThresholdError::Unavailable)+ );+ let recreated = counts+ .stream+ .get_last_raw_message_by_subject(&subject)+ .await+ .unwrap();+ let recreated: serde_json::Value = serde_json::from_slice(&recreated.payload).unwrap();+ assert!(recreated["total"].as_u64().unwrap() > prior["total"].as_u64().unwrap());+ assert_ne!(recreated["incarnation"], prior["incarnation"]);+ let renewed = leases+ .stream+ .get_last_raw_message_by_subject("$KV.SIE_THRESHOLD_LEASE.sampler")+ .await+ .unwrap();+ let renewed: serde_json::Value = serde_json::from_slice(&renewed.payload).unwrap();+ assert_eq!(+ renewed["term"], lease["term"],+ "counter recreation does not replace the lease"+ );+ }+}diff --git a/tools/ci/fixtures/sie-threshold-nats.conf b/tools/ci/fixtures/sie-threshold-nats.confnew file mode 100644index 000000000..03f2b4308--- /dev/null+++ b/tools/ci/fixtures/sie-threshold-nats.conf@@ -0,0 +1,29 @@+# Isolated threshold control broker. Never load into the inference broker.+port: 4222+http_port: 8222+jetstream { max_memory_store: 16MB, max_file_store: 0 }+max_payload: 64KB+authorization {+ users: [{+ user: sie-gateway+ password: $SIE_NATS_AUTH_GATEWAY_PASSWORD+ permissions: {+ publish: { allow: [+ "$JS.API.INFO",+ "$JS.API.STREAM.CREATE.KV_SIE_THRESHOLD_COUNTS",+ "$JS.API.STREAM.CREATE.KV_SIE_THRESHOLD_DECISIONS",+ "$JS.API.STREAM.CREATE.KV_SIE_THRESHOLD_LEASE",+ "$JS.API.STREAM.INFO.KV_SIE_THRESHOLD_COUNTS",+ "$JS.API.STREAM.INFO.KV_SIE_THRESHOLD_DECISIONS",+ "$JS.API.STREAM.INFO.KV_SIE_THRESHOLD_LEASE",+ "$JS.API.STREAM.MSG.GET.KV_SIE_THRESHOLD_COUNTS",+ "$JS.API.STREAM.MSG.GET.KV_SIE_THRESHOLD_DECISIONS",+ "$JS.API.STREAM.MSG.GET.KV_SIE_THRESHOLD_LEASE",+ "$KV.SIE_THRESHOLD_COUNTS.>",+ "$KV.SIE_THRESHOLD_DECISIONS.>",+ "$KV.SIE_THRESHOLD_LEASE.sampler"+ ] }+ subscribe: { allow: ["_INBOX.>"] }+ }+ }]+}