Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(remote): carry admitted numerical work on its own subject (#589)

Krisztian Gajdar6d4d74b13fcb
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index 0df3cc0bc..6aa4ffbc6 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -310,9 +310,10 @@ Generation is outside this numerical probe. The routing policy is excluded from
the model digest, so evidence can be measured before enabling hybrid routing;
all local and remote profile settings remain bound. Version 3 records bind the
local profile's runtime options, float32 output and remote execution digest
-explicitly. Both measured
-profiles receive those same local runtime options; remote-only runtime defaults
-are refused because a fallback would not apply them. Older records must be remeasured.
+explicitly. A bridged request runs with the remote profile's own runtime
+options, so those options must equal the local profile's. A remote profile that
+adds, omits or changes an option is refused by the probe and by admission, and
+each measured profile receives its own options. Older records must be remeasured.
A pass requires matching layouts and finite values whose maximum absolute
error against both local runs does not exceed the difference measured between
@@ -489,11 +490,15 @@ IPC connections so they do not occupy serving or readiness connection slots.
A remote-lane process also reports, for each model with a hybrid `encode` or
`score` policy, the local identities its current evidence covers, as an
`admission` with an expiry and a digest, together with the remote profile's
-contract and serving-code digests. Before such a process sends an admitted
-remote attempt upstream, it derives its admission again and refuses the item
-unless the item names the current digest, requests only admitted outputs and
-keeps the measured runtime options; a bridged caller then receives its local
-refusal with `X-SIE-Fallback-Error: INFERENCE_ERROR`.
+contract and serving-code digests. Admitted remote attempts travel on a worker
+subject of their own that only a sidecar with the admission check consumes.
+Before such a process sends an admitted remote attempt upstream, it derives its
+admission again and refuses the item unless the item names the current digest,
+requests only admitted outputs and keeps the measured runtime options. A bridged
+caller then receives its local refusal with
+`X-SIE-Fallback-Error: INFERENCE_ERROR`. The check covers batches that start
+after a change: a batch that has already passed it completes its upstream calls,
+and an SIE upstream's identity comes from a cache trusted for up to 30 seconds.
These observations and the evidence file grant no gateway routing authority.
An `observed` child can still lack a local identity. Numerical gateway routing
diff --git a/packages/sie_server/src/sie_server/config/hybrid_admission.py b/packages/sie_server/src/sie_server/config/hybrid_admission.py
index b94e6c8ed..4d6355dd0 100644
--- a/packages/sie_server/src/sie_server/config/hybrid_admission.py
+++ b/packages/sie_server/src/sie_server/config/hybrid_admission.py
@@ -8,15 +8,19 @@ admission alive.
from __future__ import annotations
+import threading
+import time
from collections.abc import Collection, Mapping
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
+from pathlib import Path
from pydantic import ValidationError
from sie_sdk.types import DEFAULT_OUTPUT_DTYPE
from sie_server.config.engine import EngineConfig
from sie_server.config.equivalence import (
+ EquivalenceRecord,
canonical_digest,
model_contract_digest,
remote_profile_contract_digest,
@@ -29,6 +33,10 @@ from sie_server.config.upstreams import UpstreamKind, installed_upstreams
from sie_server.core.profile_identity import local_profile_identity, serving_code_digest
_NUMERICAL_OUTPUTS = frozenset({"dense", "sparse", "multivector", "score"})
+_MAX_CACHED_EVIDENCE_FILES = 64
+_SETTLED_EVIDENCE_NS = 2_000_000_000
+_evidence_lock = threading.Lock()
+_evidence_cache: dict[str, tuple[tuple[int, ...], tuple[tuple[EquivalenceRecord, str], ...]]] = {}
@dataclass(frozen=True)
@@ -43,6 +51,29 @@ class NumericalAdmission:
expires_at: datetime
+def _evidence_version(path: str) -> tuple[int, ...]:
+ status = Path(path).stat()
+ return (status.st_dev, status.st_ino, status.st_size, status.st_mtime_ns, status.st_ctime_ns)
+
+
+def _digested_evidence(path: str) -> tuple[tuple[EquivalenceRecord, str], ...]:
+ """Each record of an evidence file with its digest, parsed once per version of the file."""
+ version = _evidence_version(path)
+ with _evidence_lock:
+ cached = _evidence_cache.get(path)
+ if cached is not None and cached[0] == version:
+ return cached[1]
+ evidence = tuple((record, equivalence_record_digest(record)) for record in read_equivalence_evidence(path))
+ # A file rewritten within the filesystem's timestamp granularity can keep
+ # its version, so only a version older than that is reused.
+ if _evidence_version(path) == version and time.time_ns() - max(version[-2:]) > _SETTLED_EVIDENCE_NS:
+ with _evidence_lock:
+ if path not in _evidence_cache and len(_evidence_cache) >= _MAX_CACHED_EVIDENCE_FILES:
+ _evidence_cache.pop(next(iter(_evidence_cache)))
+ _evidence_cache[path] = (version, evidence)
+ return evidence
+
+
def openai_admission(config: ModelConfig, *, now: datetime | None = None) -> NumericalAdmission | str:
"""Return the admission of the model's remote profile, or a fixed refusal reason.
@@ -65,15 +96,18 @@ def openai_admission(config: ModelConfig, *, now: datetime | None = None) -> Num
if policy is None or config.sie_id not in policy.record_files:
return "hybrid profile has no operator-owned equivalence record"
default_runtime = config.resolve_profile("default").runtime
- if profile.runtime.keys() - default_runtime.keys():
- return "hybrid remote profile adds unmeasured runtime defaults"
if default_runtime.get("output_dtype", DEFAULT_OUTPUT_DTYPE) != DEFAULT_OUTPUT_DTYPE:
return "hybrid output dtype differs from the measured float32 contract"
+ try:
+ if canonical_digest(dict(profile.runtime)) != canonical_digest(dict(default_runtime)):
+ return "hybrid remote profile runtime differs from the measured local runtime"
+ except (TypeError, ValueError, RecursionError):
+ return "hybrid runtime defaults cannot be identified"
remote_execution = serving_code_digest()
if remote_execution is None:
return "hybrid remote execution cannot be identified"
try:
- records = read_equivalence_evidence(policy.record_files[config.sie_id])
+ evidence = _digested_evidence(policy.record_files[config.sie_id])
except (OSError, ValueError, ValidationError, RecursionError):
return "hybrid equivalence record cannot be validated"
remote_contract = remote_profile_contract_digest(config, profile_name, upstreams)
@@ -92,8 +126,8 @@ def openai_admission(config: ModelConfig, *, now: datetime | None = None) -> Num
"remote_execution_sha256": remote_execution,
}
matching = [
- record
- for record in records
+ (record, digest)
+ for record, digest in evidence
if all(getattr(record, field) == value for field, value in contract.items())
and record.local_observation_sha256
== canonical_digest({"identity": record.local_identity, "revision": config.hf_revision})
@@ -102,7 +136,9 @@ def openai_admission(config: ModelConfig, *, now: datetime | None = None) -> Num
return "hybrid equivalence record differs from the current serving contract"
observed = now or datetime.now(UTC)
admitted = [
- record for record in matching if record.passed and record.is_fresh(max_age_s=policy.max_age_s, now=observed)
+ (record, digest)
+ for record, digest in matching
+ if record.passed and record.is_fresh(max_age_s=policy.max_age_s, now=observed)
]
if not admitted:
return "hybrid equivalence record failed or is outside its configured age"
@@ -114,14 +150,14 @@ def openai_admission(config: ModelConfig, *, now: datetime | None = None) -> Num
"model": config.sie_id,
"remote_profile": profile_name,
"remote_contract_sha256": remote_contract,
- "records": sorted(equivalence_record_digest(record) for record in admitted),
+ "records": sorted(digest for _, digest in admitted),
}
),
kind=UpstreamKind.OPENAI.value,
- local_identities=frozenset(record.local_identity for record in admitted),
+ local_identities=frozenset(record.local_identity for record, _ in admitted),
model_contract_sha256=contract["model_contract_sha256"],
outputs=contract["outputs"],
- expires_at=min(record.measured_at for record in admitted) + timedelta(seconds=policy.max_age_s),
+ expires_at=min(record.measured_at for record, _ in admitted) + timedelta(seconds=policy.max_age_s),
)
diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.py
index 67114bed1..7f890a8ef 100644
--- a/packages/sie_server/src/sie_server/ipc_server.py
+++ b/packages/sie_server/src/sie_server/ipc_server.py
@@ -9,7 +9,7 @@ import logging
import os
import struct
import time
-from collections.abc import AsyncIterator, Iterable
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Mapping
from pathlib import Path
from types import TracebackType
from typing import Any, Self, cast
@@ -27,6 +27,7 @@ from sie_server.core.gpu_health import gpu_is_healthy_async
from sie_server.core.grammar_routing import resolve_grammar_serving_model
from sie_server.core.profile_identity import local_profile_identity, runtime_instance_id, serving_code_digest
from sie_server.core.readiness import is_ready
+from sie_server.core.score_cost import SCORE_MEDIA_COST
from sie_server.ipc_types import (
IPC_VERSION,
METHOD_APPLY_MODEL_CONFIG,
@@ -48,6 +49,7 @@ from sie_server.ipc_types import (
METHOD_WORKER_CAPABILITIES,
ApplyModelConfigRequest,
ApplyModelConfigResponse,
+ BatchedF16MultivectorOutput,
BatchOutcome,
DrainResponse,
EnsureModelReadyRequest,
@@ -97,6 +99,9 @@ _MAX_NUMERICAL_PROFILES = 1024
_MAX_ADMITTED_IDENTITIES = 8
_MAX_NUMERICAL_MODEL_ID_BYTES = 1024
_NUMERICAL_ADMISSION_RETRY_MS = 1000
+_UNVERIFIED_ADMISSION = "this method does not verify numerical admissions"
+_ADMISSION_CHECK_FAILED = "numerical admission check failed"
+_ADMITTED_ITEM_UNANSWERED = "the backend returned no outcome for this admitted item"
# A negotiated response may exceed one legacy IPC frame, but remains tightly
# bounded so a malformed or unexpectedly large backend output cannot grow the
@@ -226,6 +231,33 @@ def _observe_remote_profile(observation: NumericalProfileObservation, config: Mo
)
+def _named_admission(item: Any) -> str | None:
+ """The numerical admission digest that a batch item names, if any."""
+ payloads = (item.encode, item.score) if isinstance(item, RunBatchItem) else (item,)
+ tokens = [getattr(payload, "numerical_admission_sha256", None) for payload in payloads]
+ return next((token for token in tokens if token is not None), None)
+
+
+def _score_side_cost(item: Mapping[str, Any]) -> int:
+ text = item["text"] if "text" in item else item.get("content")
+ images = item.get("images")
+ media = (len(images) if isinstance(images, list) else 0) + sum(
+ item.get(key) is not None for key in ("audio", "video", "document")
+ )
+ return (len(text) if isinstance(text, str) else 0) + media * SCORE_MEDIA_COST
+
+
+def _run_batch_item_cost(item: RunBatchItem) -> int:
+ """The sidecar scheduler's batching cost of an encode or score item."""
+ payload = item.encode if item.encode is not None else item.score
+ if payload is not None and payload.prepared_tokens is not None:
+ return max(1, sum(len(ids) for ids in payload.prepared_tokens.input_ids))
+ if item.score is None:
+ return 1
+ query = _score_side_cost(item.score.query_item)
+ return max(1, sum(query + _score_side_cost(document) for document in item.score.score_items))
+
+
class IpcServer:
"""UDS msgpack RPC server fronting the QueueExecutor.
@@ -740,13 +772,17 @@ class IpcServer:
async with self._execution_config(req.model_id, (item.bundle_config_hash for item in req.items)) as valid:
if not valid:
return self._config_retry(req.items)
- return await self._executor.process_encode_batch(req)
+ return await self._run_unrefused(
+ req, self._unverified_admissions(req.model_id, req.items), self._executor.process_encode_batch
+ )
async def _handle_process_score(self, req: ProcessScoreBatchRequest) -> BatchOutcome:
async with self._execution_config(req.model_id, (item.bundle_config_hash for item in req.items)) as valid:
if not valid:
return self._config_retry(req.items)
- return await self._executor.process_score_batch(req)
+ return await self._run_unrefused(
+ req, self._unverified_admissions(req.model_id, req.items), self._executor.process_score_batch
+ )
async def _handle_process_extract(self, req: ProcessExtractBatchRequest) -> BatchOutcome:
async with self._execution_config(req.model_id, (item.bundle_config_hash for item in req.items)) as valid:
@@ -768,30 +804,65 @@ class IpcServer:
async with self._execution_config(req.model_id, hashes) as valid:
if not valid:
return self._config_retry(req.items)
- if not require_admission:
- return await handle_run_batch(self._executor, req)
- refused = await asyncio.to_thread(self._numerical_admission_refusals, req)
- admitted = [item for item in req.items if item.work_item_id not in refused]
- outcomes: dict[str, ItemOutcome] = {}
- if admitted:
- result = await handle_run_batch(self._executor, msgspec.structs.replace(req, items=admitted))
- outcomes = {outcome.work_item_id: outcome for outcome in result.outcomes}
- return BatchOutcome(
- outcomes=[
- outcomes[item.work_item_id]
- if item.work_item_id in outcomes
- else self._numerical_admission_refusal(item)
- for item in req.items
- ]
+ refused = (
+ await asyncio.to_thread(self._numerical_admission_refusals, req)
+ if require_admission
+ else self._unverified_admissions(req.model_id, req.items)
)
+ return await self._run_unrefused(req, refused, lambda batch: handle_run_batch(self._executor, batch))
- def _numerical_admission_refusals(self, req: RunBatchRequest) -> set[str]:
- """Return the work items that this process's live numerical admission does not cover."""
- refused = {
- item.work_item_id: reason
- for item, reason in zip(req.items, self._numerical_admission_reasons(req), strict=True)
- if reason is not None
- }
+ async def _run_unrefused(
+ self,
+ req: RunBatchRequest | ProcessEncodeBatchRequest | ProcessScoreBatchRequest,
+ refused: Mapping[str, str],
+ run: Callable[[Any], Awaitable[BatchOutcome]],
+ ) -> BatchOutcome:
+ """Run the items that are not refused and refuse the others before the upstream sees them.
+
+ An admitted item that the backend leaves unanswered is refused too, so
+ its bridged caller gets its local refusal back at once.
+ """
+ if not refused and all(_named_admission(item) is None for item in req.items):
+ return await run(req)
+ kept = [item for item in req.items if item.work_item_id not in refused]
+ served: dict[str, ItemOutcome] = {}
+ batched: list[BatchedF16MultivectorOutput] = []
+ if kept:
+ subset = msgspec.structs.replace(req, items=kept)
+ if isinstance(subset, RunBatchRequest):
+ subset = msgspec.structs.replace(subset, total_cost=sum(map(_run_batch_item_cost, subset.items)))
+ result = await run(subset)
+ served = {outcome.work_item_id: outcome for outcome in result.outcomes}
+ batched = result.batched_f16_multivectors
+ outcomes: list[ItemOutcome] = []
+ for item in req.items:
+ if item.work_item_id in refused:
+ outcomes.append(self._numerical_admission_refusal(item, refused[item.work_item_id]))
+ elif item.work_item_id in served:
+ outcomes.append(served[item.work_item_id])
+ elif _named_admission(item) is not None:
+ outcomes.append(self._numerical_admission_refusal(item, _ADMITTED_ITEM_UNANSWERED))
+ return BatchOutcome(outcomes=outcomes, batched_f16_multivectors=batched)
+
+ @staticmethod
+ def _unverified_admissions(model_id: str, items: Iterable[Any]) -> dict[str, str]:
+ """Refuse items that name a numerical admission on a method that never verifies one."""
+ refused = {item.work_item_id: _UNVERIFIED_ADMISSION for item in items if _named_admission(item) is not None}
+ if refused:
+ logger.warning("Refused %d items naming a numerical admission for %s", len(refused), model_id)
+ return refused
+
+ def _numerical_admission_refusals(self, req: RunBatchRequest) -> dict[str, str]:
+ """Return the work items that this process's live numerical admission does not cover, with the reason."""
+ try:
+ refused = {
+ item.work_item_id: reason
+ for item, reason in zip(req.items, self._numerical_admission_reasons(req), strict=True)
+ if reason is not None
+ }
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Numerical admission check failed for %s: %s", req.model_id, type(exc).__name__)
+ refused = dict.fromkeys((item.work_item_id for item in req.items), _ADMISSION_CHECK_FAILED)
if refused:
logger.info(
"Numerical admission refused %d of %d items for %s: %s",
@@ -800,7 +871,7 @@ class IpcServer:
req.model_id,
sorted(set(refused.values())),
)
- return set(refused)
+ return refused
def _numerical_admission_reasons(self, req: RunBatchRequest) -> list[str | None]:
base, _, profile = req.model_id.partition(":")
@@ -836,7 +907,7 @@ class IpcServer:
return "operation has no numerical admission"
@staticmethod
- def _numerical_admission_refusal(item: RunBatchItem) -> ItemOutcome:
+ def _numerical_admission_refusal(item: Any, reason: str) -> ItemOutcome:
"""Refuse an item before the upstream sees it; a bridged caller gets its local refusal back."""
return ItemOutcome(
work_item_id=item.work_item_id,
@@ -844,7 +915,7 @@ class IpcServer:
item_index=item.item_index,
disposition="nak_retry",
nak_delay_ms=_NUMERICAL_ADMISSION_RETRY_MS,
- error="numerical admission does not cover this item",
+ error=reason,
error_code=ErrorCode.INFERENCE_ERROR.value,
)
@@ -865,7 +936,11 @@ class IpcServer:
@staticmethod
def _config_retry(items: Iterable[Any]) -> BatchOutcome:
- """Return unsettled work to the sidecar without executing any inputs."""
+ """Return unsettled work to the sidecar without executing any inputs.
+
+ An admitted item is answered at once rather than redelivered, so it
+ names the code of a refused bridge.
+ """
return BatchOutcome(
outcomes=[
ItemOutcome(
@@ -874,6 +949,7 @@ class IpcServer:
item_index=item.item_index,
disposition="nak_retry",
nak_delay_ms=5000,
+ error_code=ErrorCode.INFERENCE_ERROR.value if _named_admission(item) is not None else None,
)
for item in items
]
diff --git a/packages/sie_server/tests/config/test_equivalence.py b/packages/sie_server/tests/config/test_equivalence.py
index 618d753d5..95187dfbd 100644
--- a/packages/sie_server/tests/config/test_equivalence.py
+++ b/packages/sie_server/tests/config/test_equivalence.py
@@ -11,6 +11,7 @@ from datetime import UTC, datetime, timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
+from unittest.mock import MagicMock
import numpy as np
import pytest
@@ -304,7 +305,7 @@ profiles:
max_batch_tokens: 8192
adapter_options:
loadtime: {upstream: upstream, upstream_model: vendor/model}
- runtime: {normalize: false}
+ runtime: {normalize: true}
"""
)
upstream_file = tmp_path / "upstreams.yaml"
@@ -370,6 +371,46 @@ profiles:
assert "1.01" not in serialized
+ ("local", "remote"),
+ [({}, {"normalize": False}), ({"normalize": True}, {"normalize": False}), ({"normalize": True}, {})],
+)
+def test_probe_refuses_a_remote_profile_that_runs_with_other_runtime_options(
+ local: dict[str, Any], remote: dict[str, Any]
+) -> None:
+ config = ModelConfig.model_validate(
+ {
+ "sie_id": "local/model",
+ "hf_id": "weights/model",
+ "hf_revision": "a" * 40,
+ "inputs": {"text": True},
+ "tasks": {"encode": {"dense": {"dim": 2}}},
+ "max_sequence_length": 32,
+ "profiles": {
+ "default": {
+ "adapter_path": "sie_server.adapters.bge_m3:BGEM3Adapter",
+ "max_batch_tokens": 8192,
+ "compute_precision": "float32",
+ "adapter_options": {"runtime": local},
+ },
+ "remote": {
+ "adapter_path": "sie_server.adapters.remote.openai:OpenAIUpstreamAdapter",
+ "max_batch_tokens": 8192,
+ "adapter_options": {
+ "loadtime": {"upstream": "upstream", "upstream_model": "vendor/model"},
+ "runtime": remote,
+ },
+ },
+ },
+ }
+ )
+ local_client, remote_client = MagicMock(), MagicMock()
+ with pytest.raises(ValueError, match="remote profile runtime differs"):
+ probe.run_probe(config, {}, local_client, remote_client, "remote")
+ assert not local_client.mock_calls
+ assert not remote_client.mock_calls
+
+
def test_boundary_counts_include_actual_default_and_empty_instructions() -> None:
tokenizer = _Tokenizer()
cases = probe._cases(tokenizer, 64, default_instruction="profile prefix")
diff --git a/packages/sie_server/tests/config/test_hybrid_admission.py b/packages/sie_server/tests/config/test_hybrid_admission.py
index cccc59998..7f01bf32c 100644
--- a/packages/sie_server/tests/config/test_hybrid_admission.py
+++ b/packages/sie_server/tests/config/test_hybrid_admission.py
@@ -2,6 +2,7 @@
import contextlib
import json
+import logging
import os
import subprocess
import sys
@@ -19,6 +20,7 @@ from fastapi import FastAPI, HTTPException, Request
from fastapi.testclient import TestClient
from opentelemetry import trace
from pydantic import ValidationError
+from sie_server import ipc_server
from sie_server.api.encode import router as encode_router
from sie_server.api.routing import route_request
from sie_server.config import hybrid_admission
@@ -37,11 +39,16 @@ from sie_server.core.loader import expand_profile_variants
from sie_server.core.registry import ModelRegistry
from sie_server.ipc_server import IpcServer
from sie_server.ipc_types import (
+ BatchedF16MultivectorItem,
+ BatchedF16MultivectorOutput,
BatchOutcome,
ItemOutcome,
NumericalProfileSnapshotRequest,
+ ProcessEncodeBatchRequest,
+ ProcessScoreBatchRequest,
ReplaceModelConfigEntry,
ReplaceModelConfigsRequest,
+ RunBatchItem,
RunBatchRequest,
WorkerCapabilitiesRequest,
WorkerCapabilitiesResponse,
@@ -334,11 +341,32 @@ def test_unmeasured_runtime_overrides_cannot_bridge(admission: tuple, options: d
assert hybrid_admission.hybrid_request_refusal(config, {"is_query": True}) is None
-def test_remote_only_defaults_are_not_a_measured_fallback_contract(admission: tuple) -> None:
- config, _, _, _ = admission
- config.profiles["remote"].adapter_options.runtime["normalize"] = False
+ ("local", "remote", "admitted"),
+ [
+ ({}, {"normalize": False}, False),
+ ({"normalize": True}, {"normalize": False}, False),
+ ({"normalize": True}, {}, False),
+ ({"normalize": True}, {"normalize": True}, True),
+ ],
+)
+def test_a_remote_profile_must_run_with_exactly_the_measured_runtime(
+ admission: tuple, local: dict[str, Any], remote: dict[str, Any], admitted: bool
+) -> None:
+ config, upstream, path, data = admission
+ config.profiles["default"].adapter_options.runtime.update(local)
+ config.profiles["remote"].adapter_options.runtime.update(remote)
config._resolved_cache.clear()
- assert refusal(config) == "hybrid remote profile adds unmeasured runtime defaults"
+ rebuilt = {
+ **data,
+ "model_contract_sha256": model_contract_digest(config),
+ "remote_contract_sha256": remote_profile_contract_digest(config, "remote", {"vendor": upstream}),
+ "runtime_options_sha256": canonical_digest(dict(config.resolve_profile("default").runtime)),
+ }
+ path.write_text(json.dumps(rebuilt))
+ assert refusal(config) == (
+ None if admitted else "hybrid remote profile runtime differs from the measured local runtime"
+ )
def test_matching_explicit_defaults_are_allowed_but_numerical_type_aliases_are_not(admission: tuple) -> None:
@@ -896,7 +924,7 @@ async def test_fence_requires_execution_authority_first(
)
inference.assert_not_awaited()
- assert [(value.disposition, value.error_code) for value in stale.outcomes] == [("nak_retry", None)]
+ assert [(value.disposition, value.error_code) for value in stale.outcomes] == [("nak_retry", "INFERENCE_ERROR")]
def test_capability_names_the_numerical_admission_method(admission: tuple, tmp_path: Path) -> None:
@@ -906,3 +934,206 @@ def test_capability_names_the_numerical_admission_method(admission: tuple, tmp_p
assert server._handle_worker_capabilities(WorkerCapabilitiesRequest()).supports_numerical_admission_v1 is True
legacy = msgspec.convert({"supports_execution_authority_v1": True}, type=WorkerCapabilitiesResponse)
assert legacy.supports_numerical_admission_v1 is False
+
+
+def test_evidence_is_parsed_once_per_file_version_and_judged_fresh_on_every_call(
+ admission: tuple, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ config, _, path, data = admission
+ monkeypatch.setattr(hybrid_admission, "_evidence_cache", {})
+ monkeypatch.setattr(hybrid_admission, "_SETTLED_EVIDENCE_NS", -1)
+ read = hybrid_admission.read_equivalence_evidence
+ reads: list[str] = []
+
+ def counted(target: str) -> Any:
+ reads.append(target)
+ return read(target)
+
+ monkeypatch.setattr(hybrid_admission, "read_equivalence_evidence", counted)
+
+ first = hybrid_admission.openai_admission(config, now=NOW)
+ assert isinstance(first, hybrid_admission.NumericalAdmission)
+ assert hybrid_admission.openai_admission(config, now=NOW) == first
+ expired = "hybrid equivalence record failed or is outside its configured age"
+ assert hybrid_admission.openai_admission(config, now=NOW + timedelta(seconds=61)) == expired
+ assert len(reads) == 1
+
+ failed = {
+ **data,
+ "cases": [
+ {**case, "measurements": {"dense": {"noise_floor": 0.0, "remote_error": 0.5, "values": 1024}}}
+ for case in data["cases"]
+ ],
+ }
+ replacement = path.with_name("replacement.json")
+ replacement.write_text(json.dumps(failed))
+ replacement.replace(path)
+ assert hybrid_admission.openai_admission(config, now=NOW) == expired
+ assert len(reads) == 2
+
+
+def test_a_freshly_written_evidence_file_is_read_again(admission: tuple, monkeypatch: pytest.MonkeyPatch) -> None:
+ config, _, _, _ = admission
+ monkeypatch.setattr(hybrid_admission, "_evidence_cache", {})
+ read = hybrid_admission.read_equivalence_evidence
+ reads: list[str] = []
+
+ def counted(target: str) -> Any:
+ reads.append(target)
+ return read(target)
+
+ monkeypatch.setattr(hybrid_admission, "read_equivalence_evidence", counted)
+ for _ in range(2):
+ assert isinstance(hybrid_admission.openai_admission(config, now=NOW), hybrid_admission.NumericalAdmission)
+ assert len(reads) == 2
+
+
[email protected]("require_authority", [False, True])
+async def test_batch_methods_without_the_fence_refuse_items_naming_an_admission(
+ admission: tuple, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, require_authority: bool
+) -> None:
+ config, _, path, data = admission
+ _refresh_record(path, data)
+ server, bundle_hash = _fence_server(config, tmp_path)
+ current = hybrid_admission.openai_admission(config)
+ assert isinstance(current, hybrid_admission.NumericalAdmission)
+ inference = AsyncMock(side_effect=_served)
+ monkeypatch.setattr(server._executor, "process_encode_batch", inference)
+ monkeypatch.setattr(server, "_execution_config", _always_current)
+
+ outcome = await server._handle_run_batch(
+ _bridged_batch(config.sie_id + ":remote", bundle_hash, {"numerical_admission_sha256": current.sha256}, {}),
+ require_authority=require_authority,
+ )
+
+ assert [item.work_item_id for item in inference.await_args.args[0].items] == ["req.1"]
+ _assert_refused_before_the_upstream(outcome.outcomes[0])
+ assert outcome.outcomes[0].error == "this method does not verify numerical admissions"
+ assert outcome.outcomes[1].disposition == "publish_and_ack"
+
+
[email protected]("op", ["encode", "score"])
+async def test_op_scoped_methods_refuse_items_naming_an_admission(
+ admission: tuple, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, op: str
+) -> None:
+ config, _, path, data = admission
+ _refresh_record(path, data)
+ server, bundle_hash = _fence_server(config, tmp_path)
+ inference = AsyncMock(side_effect=_served)
+ monkeypatch.setattr(server._executor, f"process_{op}_batch", inference)
+ monkeypatch.setattr(server, "_execution_config", _always_current)
+ batch = _bridged_batch(
+ config.sie_id + ":remote", bundle_hash, {"op": op, "numerical_admission_sha256": "a" * 64}, {"op": op}
+ )
+ items = [getattr(item, op) for item in batch.items]
+
+ if op == "encode":
+ outcome = await server._handle_process_encode(ProcessEncodeBatchRequest(model_id=batch.model_id, items=items))
+ else:
+ outcome = await server._handle_process_score(ProcessScoreBatchRequest(model_id=batch.model_id, items=items))
+
+ assert [item.work_item_id for item in inference.await_args.args[0].items] == ["req.1"]
+ _assert_refused_before_the_upstream(outcome.outcomes[0])
+ assert outcome.outcomes[1].disposition == "publish_and_ack"
+
+
+async def test_a_failing_admission_check_refuses_every_item_and_logs_only_its_class(
+ admission: tuple, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ config, _, path, data = admission
+ _refresh_record(path, data)
+ server, bundle_hash = _fence_server(config, tmp_path)
+ inference = AsyncMock(side_effect=_served)
+ monkeypatch.setattr(server._executor, "process_encode_batch", inference)
+ monkeypatch.setattr(server, "_execution_config", _always_current)
+
+ def failing(_req: RunBatchRequest) -> list[str | None]:
+ raise RuntimeError("secret-input")
+
+ monkeypatch.setattr(server, "_numerical_admission_reasons", failing)
+ with caplog.at_level(logging.INFO, logger="sie_server.ipc_server"):
+ outcome = await server._handle_run_batch(
+ _bridged_batch(
+ config.sie_id + ":remote",
+ bundle_hash,
+ {"numerical_admission_sha256": "a" * 64},
+ {"numerical_admission_sha256": "a" * 64},
+ ),
+ require_authority=True,
+ require_admission=True,
+ )
+
+ inference.assert_not_awaited()
+ for value in outcome.outcomes:
+ _assert_refused_before_the_upstream(value)
+ assert value.error == "numerical admission check failed"
+ assert "RuntimeError" in caplog.text
+ assert "secret-input" not in caplog.text
+
+
+async def test_the_fence_keeps_shared_outputs_recosts_its_subset_and_names_an_unanswered_item(
+ admission: tuple, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ config, _, path, data = admission
+ _refresh_record(path, data)
+ server, bundle_hash = _fence_server(config, tmp_path)
+ current = hybrid_admission.openai_admission(config)
+ assert isinstance(current, hybrid_admission.NumericalAdmission)
+ monkeypatch.setattr(server, "_execution_config", _always_current)
+ shared = BatchedF16MultivectorOutput(
+ values_f16=b"\x00\x00",
+ items=[BatchedF16MultivectorItem(work_item_id="req.1", byte_offset=0, byte_len=2, num_tokens=1, token_dims=1)],
+ )
+ seen: list[RunBatchRequest] = []
+
+ async def answers_one(_executor: Any, batch: RunBatchRequest) -> BatchOutcome:
+ seen.append(batch)
+ return BatchOutcome(
+ outcomes=[ItemOutcome(work_item_id="req.1", request_id="req", item_index=1, disposition="publish_and_ack")],
+ batched_f16_multivectors=[shared],
+ )
+
+ monkeypatch.setattr(ipc_server, "handle_run_batch", answers_one)
+
+ outcome = await server._handle_run_batch(
+ _bridged_batch(
+ config.sie_id + ":remote",
+ bundle_hash,
+ {"numerical_admission_sha256": "0" * 64},
+ {
+ "numerical_admission_sha256": current.sha256,
+ "prepared_tokens": {"input_ids": [[1, 2, 3], [4, 5]], "tokenizer_id": "t"},
+ },
+ {"numerical_admission_sha256": current.sha256},
+ ),
+ require_authority=True,
+ require_admission=True,
+ )
+
+ assert [item.work_item_id for item in seen[0].items] == ["req.1", "req.2"]
+ assert seen[0].total_cost == 6
+ assert outcome.batched_f16_multivectors == [shared]
+ assert [value.work_item_id for value in outcome.outcomes] == ["req.0", "req.1", "req.2"]
+ assert outcome.outcomes[1].disposition == "publish_and_ack"
+ _assert_refused_before_the_upstream(outcome.outcomes[0])
+ assert outcome.outcomes[0].error == "bridged item names a different numerical admission"
+ _assert_refused_before_the_upstream(outcome.outcomes[2])
+ assert outcome.outcomes[2].error == "the backend returned no outcome for this admitted item"
+
+
+def test_a_subset_is_costed_as_the_sidecar_scheduler_costs_its_items() -> None:
+ def item(op: str, **payload: Any) -> RunBatchItem:
+ base = {"work_item_id": "w", "request_id": "r", "item_index": 0, "total_items": 1, "timestamp": 1.0}
+ return msgspec.convert({"op": op, op: {**base, **payload}}, type=RunBatchItem)
+
+ tokens = {"input_ids": [[1, 2, 3], [4, 5]], "tokenizer_id": "t"}
+ query = {"text": "query"}
+ documents = [{"text": "doc"}, {"content": "abcd"}, {"text": None, "content": "zz"}, {"images": [b"a", b"b"]}]
+ assert ipc_server._run_batch_item_cost(item("encode", item={"text": "x" * 40})) == 1
+ assert ipc_server._run_batch_item_cost(item("encode", item={"text": "x"}, prepared_tokens=tokens)) == 5
+ empty = {"input_ids": [[]], "tokenizer_id": "t"}
+ assert ipc_server._run_batch_item_cost(item("encode", item={"text": "x"}, prepared_tokens=empty)) == 1
+ assert ipc_server._run_batch_item_cost(item("score", query_item=query, score_items=documents)) == 2075
+ scored = item("score", query_item=query, score_items=documents, prepared_tokens=tokens)
+ assert ipc_server._run_batch_item_cost(scored) == 5
+ assert ipc_server._run_batch_item_cost(item("score", query_item={"text": ""}, score_items=[{"text": ""}])) == 1
diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.md
index 72c00c1e6..cc904c63e 100644
--- a/packages/sie_server_sidecar/docs/architecture-guide.md
+++ b/packages/sie_server_sidecar/docs/architecture-guide.md
@@ -415,30 +415,59 @@ gateway's queue-only ownership and worker-owned inference.
A remote attempt for an `encode` or `score` item may carry
`numerical_admission_sha256`, the digest of the remote process's `admission`
-that the producer relied on. The sidecar accepts such an item only on the
-`execution-authority-v1` subject and only for `encode` or `score`; anything
-else, or an item that arrives before every backend child supports the method,
-is refused before readiness or offloaded input retrieval, like other
-authority work. The local-ingest lane rejects the field.
+that the producer relied on. Such admitted work uses the worker-direct subject
+with the eighth token `numerical-admission-v1`. Only a sidecar with this fence
+creates `WORK_ADMISSION_V1_<worker>` and `admission-v1-<worker>`, with the same
+bounds as the authority stream. No consumer of a sidecar without the fence
+matches that subject, including its authority consumer. A rollback therefore
+cannot hand such a sidecar admitted work that is already queued, and until a
+fenced sidecar has created the stream, admitted work cannot be published at
+all. The contract comes from the subject, never from the payload field, which
+an older sidecar would ignore.
+
+Admitted work also runs under execution authority. Before readiness or
+offloaded input retrieval, the sidecar answers an item with `INFERENCE_ERROR`
+and ACKs it when the item and its subject disagree: the field on any other
+subject, an item without the field on the admission subject, an operation other
+than `encode` or `score`, or a payload model other than the subject's. It does
+the same for an `encode` or `score` item that carries `fallback_reason` without
+the field, because every numerical remote attempt that stands in for a local
+refusal is admitted work. Such an item can never become valid, and a NAK could
+hand an item on a pool subject to a worker without the fence. An item that
+arrives before every backend child supports the method is NAKed on the
+worker's own admission stream, like other authority work. The local-ingest
+lane rejects the field, and `fallback_reason` on `encode` or `score`.
Admitted items keep their own scheduler partition and run only through
-`RunBatchWithNumericalAdmissionV1`, which an older backend rejects. Under the
-same execution lease as the authority checks, the Python backend derives its
-own current admission for the bare model whose fallback profile the batch
-targets, without contacting an SIE upstream. It runs an item only when the item
-names that digest, requests only admitted outputs and keeps the measured
-runtime options. Any other item gets `nak_retry` with `INFERENCE_ERROR` before
-the upstream is called. Redelivery to the pinned worker cannot restore an
-admission, so the sidecar publishes a `nak_retry` for an admitted item as its
-refusal at once and ACKs it, as it does for a fallback attempt. A bridged caller
-then receives its local refusal with `X-SIE-Fallback-Error: INFERENCE_ERROR`. A
-replaced, expired or removed record therefore stops execution at once, without
-waiting for the next heartbeat.
+`RunBatchWithNumericalAdmissionV1`, which an older backend rejects. A sidecar
+without the scheduler answers them instead of sending them through
+`ProcessEncodeBatch` or `ProcessScoreBatch`, and the Python backend refuses the
+field on every method other than the admission method. Under the same
+execution lease as the authority checks, the Python backend derives its own
+current admission for the bare model whose fallback profile the batch targets,
+without contacting an SIE upstream. It runs an item only when the item names
+that digest, requests only admitted outputs and keeps the measured runtime
+options. Any other item gets `nak_retry` with `INFERENCE_ERROR` before the
+upstream is called, as does every item when the check itself fails or when the
+configuration barrier refuses an admitted batch. Redelivery to the pinned
+worker cannot restore an admission, so the sidecar publishes a `nak_retry` for
+an admitted item as its refusal at once and ACKs it, as it does for a fallback
+attempt. A bridged caller then receives its local refusal with
+`X-SIE-Fallback-Error: INFERENCE_ERROR`.
+
+The check covers batches that start after a change. A replaced, expired or
+removed record refuses every later batch without waiting for the next
+heartbeat, while a batch that has already passed the check completes its
+upstream calls. An SIE upstream's identity comes from a cache that is trusted
+for up to 30 seconds.
The backend capability `supports_numerical_admission_v1` defaults to false. The
heartbeat reports `supports_numerical_admission_v1` only when it reports
-`supports_execution_authority_v1` and every backend child supports the method.
-No gateway produces these items yet.
+`supports_execution_authority_v1`, every backend child supports the method and
+the admission pull consumer runs. After a rollback below this version, admitted
+work still queued for that worker never runs and its callers time out. The
+gateway stops selecting the worker once its heartbeat no longer reports the
+capability. No gateway produces these items yet.
Non-streaming backend responses use one physical frame while the serialized
response is at most 32 MiB. For a larger response, the sidecar explicitly sets
diff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rs
index 2472c6b10..a8edc790c 100644
--- a/packages/sie_server_sidecar/src/config.rs
+++ b/packages/sie_server_sidecar/src/config.rs
@@ -386,6 +386,28 @@ impl WorkerConfig {
crate::subject::EXECUTION_AUTHORITY_V1_TOKEN
)
}
+
+ pub fn admission_stream_name(&self) -> String {
+ format!(
+ "WORK_ADMISSION_V1_{}",
+ crate::subject::normalize_model_id(&self.worker_id)
+ )
+ }
+
+ pub fn admission_consumer_name(&self) -> String {
+ format!(
+ "admission-v1-{}",
+ crate::subject::normalize_model_id(&self.worker_id)
+ )
+ }
+
+ pub fn admission_subject_filter(&self) -> String {
+ format!(
+ "{}.{}",
+ self.worker_subject_filter(),
+ crate::subject::NUMERICAL_ADMISSION_V1_TOKEN
+ )
+ }
}
#[cfg(test)]
@@ -503,6 +525,18 @@ mod tests {
c.worker_subject_filter(),
"sie.work.l4.l4.default.*.worker-test"
);
+ assert_eq!(c.authority_stream_name(), "WORK_AUTHORITY_V1_worker-test");
+ assert_eq!(c.authority_consumer_name(), "authority-v1-worker-test");
+ assert_eq!(
+ c.authority_subject_filter(),
+ "sie.work.l4.l4.default.*.worker-test.execution-authority-v1"
+ );
+ assert_eq!(c.admission_stream_name(), "WORK_ADMISSION_V1_worker-test");
+ assert_eq!(c.admission_consumer_name(), "admission-v1-worker-test");
+ assert_eq!(
+ c.admission_subject_filter(),
+ "sie.work.l4.l4.default.*.worker-test.numerical-admission-v1"
+ );
}
#[test]
diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rs
index 814e39c5a..3b0c8420f 100644
--- a/packages/sie_server_sidecar/src/dispatcher.rs
+++ b/packages/sie_server_sidecar/src/dispatcher.rs
@@ -55,7 +55,7 @@ use crate::scheduler::{
use crate::shutdown::Shutdown;
use crate::subject::{
execution_authority_model_matches, extract_model_id, is_worker_direct_work_subject,
- requires_execution_authority_v1,
+ requires_execution_authority_v1, requires_numerical_admission_v1,
};
use crate::tokenize::TokenizerRegistry;
use crate::work_deadline::{
@@ -80,6 +80,10 @@ const INVALID_INPUT_ERROR_CODE: &str = "INVALID_INPUT";
/// A remote profile's upstream cannot serve now; retryable, like the single
/// server's `QUEUE_FULL` for a busy or unreachable upstream.
const QUEUE_FULL_ERROR_CODE: &str = "QUEUE_FULL";
+/// The code of a numerical admission refusal, as the backend's fence and the
+/// single server's bridge refusal report it.
+const INFERENCE_ERROR_CODE: &str = "INFERENCE_ERROR";
+const NUMERICAL_ADMISSION_RETRY_AFTER_S: u32 = 1;
const FALLBACK_REFUSAL_MESSAGE: &str = "The remote profile cannot serve this request now";
/// Operation of a work item that only asks the worker to load its model.
const LOAD_OPERATION: &str = "load";
@@ -1288,16 +1292,17 @@ impl Dispatcher {
};
match rmp_serde::from_slice::<WorkItem>(&msg.payload) {
Ok(mut wi) => {
- // This contract is derived from the consumer's versioned
- // subject, never an additive payload field an old worker
- // could ignore. Refuse before readiness or payload fetch.
- if !numerical_admission_contract_holds(&msg.subject, &wi)
- || (requires_execution_authority_v1(&msg.subject)
- && (!execution_authority_model_matches(&msg.subject, &wi.model_id)
- || !self.execution_authority_is_available(
- &wi,
- wi.operation != "generate",
- )))
+ // These contracts are derived from the consumer's
+ // versioned subject. Admitted work travels only on a
+ // subject no sidecar without the admission fence
+ // consumes, and its payload field must agree with that
+ // subject. Refuse before readiness or payload fetch.
+ let admission_violation = numerical_admission_violation(&msg.subject, &wi);
+ if admission_violation.is_none()
+ && requires_execution_authority_v1(&msg.subject)
+ && (!execution_authority_model_matches(&msg.subject, &wi.model_id)
+ || !self
+ .execution_authority_is_available(&wi, wi.operation != "generate"))
{
nak_one_with_reason(
&Delivery::Nats(msg, admission_permit, None),
@@ -1330,6 +1335,24 @@ impl Dispatcher {
continue;
}
let mut delivery = Delivery::Nats(msg, admission_permit, None);
+ if let Some(violation) = admission_violation {
+ // Such an item can never become valid, and a NAK
+ // could hand it to a consumer without the fence.
+ warn!(
+ work_item_id = %wi.work_item_id,
+ model = %wi.model_id,
+ violation,
+ "work breaks the numerical admission contract — answering and ACKing",
+ );
+ self.refuse_fallback_attempt(
+ &wi,
+ &delivery,
+ INFERENCE_ERROR_CODE,
+ NUMERICAL_ADMISSION_RETRY_AFTER_S,
+ )
+ .await;
+ continue;
+ }
self.observe_deadline_clock(&wi, &delivery);
if self.settle_if_cancelled(&wi, &delivery, "intake").await {
continue;
@@ -2569,6 +2592,29 @@ impl Dispatcher {
Ok(())
}
+ /// Answer admitted items instead of sending them through a method that
+ /// never re-verifies a numerical admission.
+ async fn refuse_admitted_items(
+ &self,
+ items: Vec<(WorkItem, Delivery)>,
+ ) -> Vec<(WorkItem, Delivery)> {
+ let mut kept = Vec::with_capacity(items.len());
+ for (wi, delivery) in items {
+ if wi.numerical_admission_sha256.is_none() {
+ kept.push((wi, delivery));
+ continue;
+ }
+ self.refuse_fallback_attempt(
+ &wi,
+ &delivery,
+ INFERENCE_ERROR_CODE,
+ NUMERICAL_ADMISSION_RETRY_AFTER_S,
+ )
+ .await;
+ }
+ kept
+ }
+
// -- encode -----------------------------------------------------------
async fn handle_encode(
@@ -2576,6 +2622,7 @@ impl Dispatcher {
model_id: &str,
items: Vec<(WorkItem, Delivery)>,
) -> Result<(), DispatchError> {
+ let items = self.refuse_admitted_items(items).await;
let mut resolved: Vec<(WorkItem, Delivery, MsgValue, f64, Option<String>)> =
Vec::with_capacity(items.len());
for (wi, delivery) in items {
@@ -2698,7 +2745,7 @@ impl Dispatcher {
options: wi.options.clone(),
profile_id: opt_non_empty(&wi.profile_id),
bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
- numerical_admission_sha256: wi.numerical_admission_sha256.clone(),
+ numerical_admission_sha256: None,
payload_fetch_ms: *fm,
prepared_tokens,
}
@@ -2751,6 +2798,7 @@ impl Dispatcher {
model_id: &str,
items: Vec<(WorkItem, Delivery)>,
) -> Result<(), DispatchError> {
+ let items = self.refuse_admitted_items(items).await;
let mut prepared: Vec<(WorkItem, Delivery, MsgValue, Vec<MsgValue>, f64)> =
Vec::with_capacity(items.len());
for (wi, delivery) in items {
@@ -2873,7 +2921,7 @@ impl Dispatcher {
options: wi.options.clone(),
profile_id: opt_non_empty(&wi.profile_id),
bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
- numerical_admission_sha256: wi.numerical_admission_sha256.clone(),
+ numerical_admission_sha256: None,
payload_fetch_ms: *fm,
prepared_tokens: None,
})
@@ -4862,13 +4910,28 @@ async fn nak_one(
nak_one_with_reason(delivery, delay_ms, telemetry, "retry").await;
}
-/// An item that names a numerical admission arrives only on a verified
-/// worker-direct subject and only as encode or score, the operations whose
-/// backend method re-verifies the admission before execution.
-fn numerical_admission_contract_holds(subject: &str, wi: &WorkItem) -> bool {
- wi.numerical_admission_sha256.is_none()
- || (requires_execution_authority_v1(subject)
- && matches!(wi.operation.as_str(), "encode" | "score"))
+/// Why an item breaks the numerical admission contract, if it does. Admitted
+/// work names a numerical admission, travels only on the admission subject
+/// for its own model, and is encode or score: the operations whose backend
+/// method re-verifies the admission before execution. A numerical remote
+/// attempt that stands in for a local refusal is always admitted work.
+fn numerical_admission_violation(subject: &str, wi: &WorkItem) -> Option<&'static str> {
+ let numerical = matches!(wi.operation.as_str(), "encode" | "score");
+ match (
+ wi.numerical_admission_sha256.is_some(),
+ requires_numerical_admission_v1(subject),
+ ) {
+ (true, false) => Some("admitted_work_off_the_admission_subject"),
+ (false, true) => Some("unadmitted_work_on_the_admission_subject"),
+ (true, true) if !numerical => Some("admitted_work_is_not_encode_or_score"),
+ (true, true) if !execution_authority_model_matches(subject, &wi.model_id) => {
+ Some("admitted_work_names_another_model")
+ }
+ (false, false) if numerical && wi.fallback_reason.is_some() => {
+ Some("numerical_fallback_without_admission")
+ }
+ _ => None,
+ }
}
async fn nak_one_with_reason(
@@ -6690,27 +6753,68 @@ mod tests {
#[tokio::test]
async fn an_admitted_item_is_answered_at_once_even_without_a_held_refusal() {
- let dispatcher =
- dispatcher_with_backend(naking_backend(Some("INFERENCE_ERROR"), None, Some(1_000)));
+ let dispatcher = dispatcher_with_backend(naking_backend(None, None, None));
+ let admitted = WorkItem {
+ numerical_admission_sha256: Some("a".repeat(64)),
+ ..wi("admitted", 0, "acme/model:remote", "encode")
+ };
+ let refusal = ItemOutcome {
+ nak_delay_ms: Some(1_000),
+ error_code: Some(INFERENCE_ERROR_CODE.to_string()),
+ ..outcome("admitted", 0, Disposition::NakRetry, None, None)
+ };
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
- let admitted = settle_one(
- &dispatcher,
- WorkItem {
- numerical_admission_sha256: Some("a".repeat(64)),
- ..wi("admitted", 0, "acme/model:remote", "encode")
- },
- )
- .await;
+ dispatcher
+ .apply_outcome(
+ &admitted,
+ &Delivery::Local(LocalDelivery::new(0, 0, tx)),
+ &refusal,
+ 0.0,
+ None,
+ )
+ .await;
- let [crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }] = admitted.as_slice()
+ let Ok(crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }) = rx.try_recv()
else {
- panic!("an admitted item must settle with a result: {admitted:?}");
+ panic!("an admitted item must settle with a result");
};
assert!(!result.success);
- assert_eq!(result.error_code.as_deref(), Some("INFERENCE_ERROR"));
+ assert_eq!(result.error_code.as_deref(), Some(INFERENCE_ERROR_CODE));
assert_eq!(result.retry_after_s, Some(1));
}
+ #[tokio::test]
+ async fn the_scheduler_less_path_answers_admitted_items_without_the_backend() {
+ for op in ["encode", "score"] {
+ let backend = naking_backend(None, None, Some(2_500));
+ let dispatcher = dispatcher_with_backend(backend.clone());
+
+ let events = settle_one(
+ &dispatcher,
+ WorkItem {
+ numerical_admission_sha256: Some("a".repeat(64)),
+ ..wi("admitted", 0, "acme/model:remote", op)
+ },
+ )
+ .await;
+
+ let [crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }] =
+ events.as_slice()
+ else {
+ panic!("{op}: an admitted item must settle with a result: {events:?}");
+ };
+ assert!(!result.success, "{op}");
+ assert_eq!(
+ result.error_code.as_deref(),
+ Some(INFERENCE_ERROR_CODE),
+ "{op}"
+ );
+ assert_eq!(result.retry_after_s, Some(1), "{op}");
+ assert_eq!(backend.encoded.load(Ordering::SeqCst), 0, "{op}");
+ }
+ }
+
#[tokio::test]
async fn a_fallback_refusal_keeps_the_engines_code_and_retry_hint() {
let dispatcher =
@@ -6989,6 +7093,15 @@ mod tests {
delivery
}
+ async fn admission_test_delivery() -> Delivery {
+ let mut delivery = unacknowledgeable_nats_delivery().await;
+ if let Delivery::Nats(message, ..) = &mut delivery {
+ message.message.subject =
+ "sie.work.test.machine.bundle.cold.worker.numerical-admission-v1".into();
+ }
+ delivery
+ }
+
#[tokio::test]
async fn stale_authority_generation_refuses_before_readiness_or_payload_fetch() {
let backend = LoadingModelBackend::new("cold");
@@ -7063,45 +7176,89 @@ mod tests {
}
#[test]
- fn an_admitted_item_must_be_verified_encode_or_score_work() {
- let verified = "sie.work.p.m.b.model.worker.execution-authority-v1";
+ fn the_admission_subject_carries_exactly_the_admitted_numerical_work() {
+ let admission = "sie.work.p.m.b.model.worker.numerical-admission-v1";
+ let authority = "sie.work.p.m.b.model.worker.execution-authority-v1";
+ let direct = "sie.work.p.m.b.model.worker";
let pooled = "sie.work.p.m.b.model";
- for (subject, op, token, holds) in [
- (verified, "encode", true, true),
- (verified, "score", true, true),
- (verified, "extract", true, false),
- (verified, "generate", true, false),
- (pooled, "encode", true, false),
- (pooled, "encode", false, true),
- (verified, "generate", false, true),
+ let off = Some("admitted_work_off_the_admission_subject");
+ let unadmitted = Some("unadmitted_work_on_the_admission_subject");
+ let not_numerical = Some("admitted_work_is_not_encode_or_score");
+ let bridge = Some("numerical_fallback_without_admission");
+ for (subject, model, op, token, fallback, violation) in [
+ (admission, "model", "encode", true, true, None),
+ (admission, "model", "score", true, false, None),
+ (admission, "model", "extract", true, false, not_numerical),
+ (admission, "model", "generate", true, true, not_numerical),
+ (
+ admission,
+ "other",
+ "encode",
+ true,
+ false,
+ Some("admitted_work_names_another_model"),
+ ),
+ (admission, "model", "encode", false, false, unadmitted),
+ (admission, "model", "generate", false, false, unadmitted),
+ (authority, "model", "encode", true, true, off),
+ (direct, "model", "score", true, false, off),
+ (pooled, "model", "encode", true, false, off),
+ (pooled, "model", "encode", false, true, bridge),
+ (authority, "model", "score", false, true, bridge),
+ (pooled, "model", "generate", false, true, None),
+ (authority, "model", "encode", false, false, None),
+ (pooled, "model", "extract", false, true, None),
] {
- let mut work = wi("req", 0, "model", op);
+ let mut work = wi("req", 0, model, op);
work.numerical_admission_sha256 = token.then(|| "a".repeat(64));
+ work.fallback_reason = fallback.then(|| "provisioning".to_string());
assert_eq!(
- numerical_admission_contract_holds(subject, &work),
- holds,
- "{subject} {op} {token}"
+ numerical_admission_violation(subject, &work),
+ violation,
+ "{subject} {model} {op} {token} {fallback}"
);
}
}
#[tokio::test]
- async fn admitted_work_on_a_pool_subject_is_refused_at_receipt() {
- let backend = LoadingModelBackend::new("cold");
- let dispatcher = dispatcher_with_backend(backend.clone());
- let mut work = wi("pooled", 0, "cold", "encode");
- work.numerical_admission_sha256 = Some("a".repeat(64));
- let Delivery::Nats(mut message, permit, _) = unacknowledgeable_nats_delivery().await else {
- unreachable!()
- };
- message.message.subject = "sie.work.pool.machine.bundle.cold".into();
- message.message.payload = rmp_serde::to_vec_named(&work).unwrap().into();
- dispatcher
- .handle_batch(vec![QueuedMessage::new(message, permit)])
- .await;
- dispatcher.join_parked_groups(Duration::from_secs(1)).await;
- assert_eq!(backend.probes.load(Ordering::SeqCst), 0);
- assert!(backend.encoded_models().is_empty());
+ async fn work_breaking_the_admission_contract_never_reaches_the_backend() {
+ let admitted = Some("a".repeat(64));
+ for (subject, token, fallback_reason) in [
+ ("sie.work.pool.machine.bundle.cold", admitted.clone(), None),
+ (
+ "sie.work.pool.machine.bundle.cold.worker.execution-authority-v1",
+ admitted.clone(),
+ None,
+ ),
+ (
+ "sie.work.pool.machine.bundle.cold.worker.numerical-admission-v1",
+ None,
+ None,
+ ),
+ (
+ "sie.work.pool.machine.bundle.cold",
+ None,
+ Some("provisioning".to_string()),
+ ),
+ ] {
+ let backend = LoadingModelBackend::new("cold");
+ let dispatcher = dispatcher_with_backend(backend.clone());
+ let mut work = wi("refused", 0, "cold", "encode");
+ work.numerical_admission_sha256 = token;
+ work.fallback_reason = fallback_reason;
+ let Delivery::Nats(mut message, permit, _) = unacknowledgeable_nats_delivery().await
+ else {
+ unreachable!()
+ };
+ message.message.subject = subject.into();
+ message.message.payload = rmp_serde::to_vec_named(&work).unwrap().into();
+ dispatcher
+ .handle_batch(vec![QueuedMessage::new(message, permit)])
+ .await;
+ dispatcher.join_parked_groups(Duration::from_secs(1)).await;
+ assert_eq!(backend.probes.load(Ordering::SeqCst), 0, "{subject}");
+ assert!(backend.encoded_models().is_empty(), "{subject}");
+ }
}
#[tokio::test]
@@ -7124,7 +7281,7 @@ mod tests {
assert!(!dispatcher.execution_authority_is_available(&work, true));
dispatcher
.dispatch_decoded(
- vec![(work.clone(), authority_test_delivery().await)],
+ vec![(work.clone(), admission_test_delivery().await)],
1,
Instant::now(),
)
@@ -7151,7 +7308,7 @@ mod tests {
legacy,
Delivery::Local(LocalDelivery::new(0, 0, tx.clone())),
),
- (admitted, authority_test_delivery().await),
+ (admitted, admission_test_delivery().await),
(verified, authority_test_delivery().await),
];
let mut batch = crate::scheduler::FormattedBatch {
diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rs
index 52b249f4f..2cde987e9 100644
--- a/packages/sie_server_sidecar/src/health_publisher.rs
+++ b/packages/sie_server_sidecar/src/health_publisher.rs
@@ -213,6 +213,8 @@ pub struct HealthPublisherConfig {
pub numerical_admission_v1: Arc<AtomicBool>,
/// The versioned pull consumer must also be running.
pub authority_consumer_ready: Arc<AtomicBool>,
+ /// The admitted-work pull consumer must also be running.
+ pub admission_consumer_ready: Arc<AtomicBool>,
/// Runtime pressure/capacity gauges mirrored into the heartbeat payload.
pub runtime_state: Arc<RuntimeState>,
/// How often to publish. Defaults to [`DEFAULT_PUBLISH_INTERVAL`].
@@ -345,7 +347,8 @@ fn encode_payload(
terminated,
supports_execution_authority_v1,
supports_numerical_admission_v1: supports_execution_authority_v1
- && config.numerical_admission_v1.load(Ordering::Acquire),
+ && config.numerical_admission_v1.load(Ordering::Acquire)
+ && config.admission_consumer_ready.load(Ordering::Acquire),
gpu_count: config.gpu_count,
total_gpu_slots,
ready_gpu_slots,
@@ -550,6 +553,7 @@ mod tests {
execution_authority_v1: Arc::new(AtomicBool::new(false)),
numerical_admission_v1: Arc::new(AtomicBool::new(false)),
authority_consumer_ready: Arc::new(AtomicBool::new(false)),
+ admission_consumer_ready: Arc::new(AtomicBool::new(false)),
runtime_state: Arc::new(RuntimeState::new()),
interval: DEFAULT_PUBLISH_INTERVAL,
}
@@ -740,18 +744,25 @@ mod tests {
}
#[test]
- fn numerical_admission_health_requires_authority_and_the_backend_method() {
- for (authority, backend) in [(true, true), (true, false), (false, true)] {
+ fn numerical_admission_health_requires_authority_the_backend_method_and_its_consumer() {
+ for (authority, backend, consumer) in [
+ (true, true, true),
+ (true, false, true),
+ (false, true, true),
+ (true, true, false),
+ ] {
let c = cfg();
c.execution_authority_v1.store(authority, Ordering::Release);
c.authority_consumer_ready.store(true, Ordering::Release);
c.numerical_admission_v1.store(backend, Ordering::Release);
+ c.admission_consumer_ready
+ .store(consumer, Ordering::Release);
let payload: serde_json::Value =
serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();
assert_eq!(
payload["supports_numerical_admission_v1"],
- authority && backend,
- "{authority} {backend}"
+ authority && backend && consumer,
+ "{authority} {backend} {consumer}"
);
}
}
diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rs
index a2736bf4d..5c1c939f5 100644
--- a/packages/sie_server_sidecar/src/lib.rs
+++ b/packages/sie_server_sidecar/src/lib.rs
@@ -63,9 +63,9 @@ use crate::dispatcher::{Dispatcher, QueuedMessage};
use crate::latency::{FetchExpiryController, LatencyTracker};
use crate::log_util::ErrChain;
use crate::nats_consumer::{
- connect, ensure_authority_stream_and_consumer, ensure_stream_and_consumer,
- ensure_worker_stream_and_consumer, reconcile_stream_and_consumer,
- reconcile_worker_stream_and_consumer, work_cancel_tombstone_ttl, NatsConsumer,
+ connect, ensure_admission_stream_and_consumer, ensure_authority_stream_and_consumer,
+ ensure_stream_and_consumer, ensure_worker_stream_and_consumer, reconcile_stream_and_consumer,
+ reconcile_worker_stream_and_consumer, work_cancel_tombstone_ttl, NatsConsumer, NatsSetupError,
};
use crate::payload_store::{create_payload_store, with_telemetry as payload_store_with_telemetry};
use crate::pool_admission::PoolAdmissionGate;
@@ -574,6 +574,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
execution_authority_v1: worker_pool.execution_authority_v1(),
numerical_admission_v1: worker_pool.numerical_admission_v1(),
authority_consumer_ready: Arc::clone(&generation_direct_dispatch.authority_active),
+ admission_consumer_ready: Arc::clone(&generation_direct_dispatch.admission_active),
runtime_state: Arc::clone(&runtime_state),
interval: Duration::from_millis(config.health_publish_interval_ms),
})
@@ -973,6 +974,7 @@ pub async fn run_local(config: WorkerConfig) -> anyhow::Result<()> {
struct GenerationDirectHandles {
pull: Option<JoinHandle<()>>,
authority_pull: Option<JoinHandle<()>>,
+ admission_pull: Option<JoinHandle<()>>,
generation_cancel: Option<JoinHandle<()>>,
batch_cancel: Option<JoinHandle<()>>,
work_cancel: Option<JoinHandle<()>>,
@@ -995,11 +997,42 @@ struct GenerationDirectDispatch {
worker_pool: Arc<AdapterWorkerPool>,
active: Arc<AtomicBool>,
authority_active: Arc<AtomicBool>,
+ admission_active: Arc<AtomicBool>,
batch_cancel_state: BatchCancelState,
request_cancel_state: RequestCancelState,
handles: Mutex<GenerationDirectHandles>,
}
+#[derive(Clone, Copy)]
+enum VersionedConsumer {
+ ExecutionAuthorityV1,
+ NumericalAdmissionV1,
+}
+
+impl VersionedConsumer {
+ fn label(self) -> &'static str {
+ match self {
+ Self::ExecutionAuthorityV1 => "execution authority",
+ Self::NumericalAdmissionV1 => "numerical admission",
+ }
+ }
+
+ async fn ensure(
+ self,
+ jetstream: &async_nats::jetstream::Context,
+ config: &WorkerConfig,
+ ) -> Result<async_nats::jetstream::consumer::PullConsumer, NatsSetupError> {
+ match self {
+ Self::ExecutionAuthorityV1 => {
+ ensure_authority_stream_and_consumer(jetstream, config).await
+ }
+ Self::NumericalAdmissionV1 => {
+ ensure_admission_stream_and_consumer(jetstream, config).await
+ }
+ }
+ }
+}
+
impl GenerationDirectDispatch {
#[allow(clippy::too_many_arguments)]
fn new(
@@ -1028,6 +1061,7 @@ impl GenerationDirectDispatch {
worker_pool,
active,
authority_active: Arc::new(AtomicBool::new(false)),
+ admission_active: Arc::new(AtomicBool::new(false)),
batch_cancel_state,
request_cancel_state,
handles: Mutex::new(GenerationDirectHandles::default()),
@@ -1110,54 +1144,69 @@ impl GenerationDirectDispatch {
Arc::clone(&self.shutdown),
);
- let authority_dispatcher = Arc::clone(&self.dispatcher);
- let authority_shutdown = Arc::clone(&self.shutdown);
- let authority_fetch_ctrl = self.fetch_ctrl.clone();
- let authority_latency_tracker = Arc::clone(&self.latency_tracker);
- let authority_pool_admission = self.pool_admission.clone();
- let authority_active = Arc::clone(&self.authority_active);
- let authority_jetstream = self.jetstream.clone();
- let authority_config = self.config.clone();
- let authority_pull = tokio::spawn(async move {
- // Authority setup is independent of the ordinary pull loops. Keep
+ let authority_pull = self.spawn_versioned_pull(
+ VersionedConsumer::ExecutionAuthorityV1,
+ Arc::clone(&self.authority_active),
+ );
+ let admission_pull = self.spawn_versioned_pull(
+ VersionedConsumer::NumericalAdmissionV1,
+ Arc::clone(&self.admission_active),
+ );
+
+ let mut handles = self.handles.lock().await;
+ handles.pull = Some(pull);
+ handles.authority_pull = Some(authority_pull);
+ handles.admission_pull = Some(admission_pull);
+ handles.generation_cancel = Some(generation_cancel);
+ handles.batch_cancel = Some(batch_cancel);
+ handles.work_cancel = Some(work_cancel);
+ info!(reason, "worker direct-dispatch activated");
+ Ok(true)
+ }
+
+ fn spawn_versioned_pull(
+ &self,
+ contract: VersionedConsumer,
+ active: Arc<AtomicBool>,
+ ) -> JoinHandle<()> {
+ let dispatcher = Arc::clone(&self.dispatcher);
+ let shutdown = Arc::clone(&self.shutdown);
+ let fetch_ctrl = self.fetch_ctrl.clone();
+ let latency_tracker = Arc::clone(&self.latency_tracker);
+ let pool_admission = self.pool_admission.clone();
+ let jetstream = self.jetstream.clone();
+ let config = self.config.clone();
+ tokio::spawn(async move {
+ // Versioned setup is independent of the ordinary pull loops. Keep
// its capability closed and retry boundedly while legacy work runs.
- let authority_consumer = loop {
+ let consumer = loop {
let result = tokio::select! {
- _ = authority_shutdown.wait() => return,
- result = ensure_authority_stream_and_consumer(&authority_jetstream, &authority_config) => result,
+ _ = shutdown.wait() => return,
+ result = contract.ensure(&jetstream, &config) => result,
};
match result {
Ok(consumer) => break consumer,
Err(error) => {
- warn!(%error, "authority consumer setup failed; retrying without blocking ordinary dispatch")
+ warn!(%error, contract = contract.label(), "versioned consumer setup failed; retrying without blocking ordinary dispatch")
}
}
tokio::select! {
- _ = authority_shutdown.wait() => return,
+ _ = shutdown.wait() => return,
_ = tokio::time::sleep(Duration::from_secs(5)) => {},
}
};
- let _ready = AuthorityConsumerReady(Arc::clone(&authority_active));
- authority_active.store(true, Ordering::Release);
+ let _ready = AuthorityConsumerReady(Arc::clone(&active));
+ active.store(true, Ordering::Release);
run_pull_loop(
- &NatsConsumer::new(authority_consumer),
- authority_dispatcher,
- authority_shutdown,
- &authority_fetch_ctrl,
- authority_latency_tracker,
- authority_pool_admission,
+ &NatsConsumer::new(consumer),
+ dispatcher,
+ shutdown,
+ &fetch_ctrl,
+ latency_tracker,
+ pool_admission,
)
.await;
- });
-
- let mut handles = self.handles.lock().await;
- handles.pull = Some(pull);
- handles.authority_pull = Some(authority_pull);
- handles.generation_cancel = Some(generation_cancel);
- handles.batch_cancel = Some(batch_cancel);
- handles.work_cancel = Some(work_cancel);
- info!(reason, "worker direct-dispatch activated");
- Ok(true)
+ })
}
async fn abort_and_join(&self) {
@@ -1166,19 +1215,17 @@ impl GenerationDirectDispatch {
GenerationDirectHandles {
pull: guard.pull.take(),
authority_pull: guard.authority_pull.take(),
+ admission_pull: guard.admission_pull.take(),
generation_cancel: guard.generation_cancel.take(),
batch_cancel: guard.batch_cancel.take(),
work_cancel: guard.work_cancel.take(),
}
};
- if let Some(h) = handles.pull {
- if !h.is_finished() {
- h.abort();
- }
- let _ = h.await;
- }
- if let Some(h) = handles.authority_pull {
+ for h in [handles.pull, handles.authority_pull, handles.admission_pull]
+ .into_iter()
+ .flatten()
+ {
if !h.is_finished() {
h.abort();
}
@@ -1244,6 +1291,9 @@ fn spawn_nats_consumer_reconciler(
if let Err(e) = ensure_authority_stream_and_consumer(&jetstream, &config).await {
warn!(error = %e, "nats-consumer: execution authority stream/durable reconcile failed");
}
+ if let Err(e) = ensure_admission_stream_and_consumer(&jetstream, &config).await {
+ warn!(error = %e, "nats-consumer: numerical admission stream/durable reconcile failed");
+ }
}
}
}))
diff --git a/packages/sie_server_sidecar/src/local_ingest.rs b/packages/sie_server_sidecar/src/local_ingest.rs
index 37cc83d71..b97caff19 100644
--- a/packages/sie_server_sidecar/src/local_ingest.rs
+++ b/packages/sie_server_sidecar/src/local_ingest.rs
@@ -1561,7 +1561,9 @@ fn validate_work_items_with_limit(
.to_string(),
);
}
- if wi.numerical_admission_sha256.is_some() {
+ if wi.numerical_admission_sha256.is_some()
+ || (wi.fallback_reason.is_some() && matches!(wi.operation.as_str(), "encode" | "score"))
+ {
return Err(
"InvalidTransportBinding: numerical admission is not supported on the local-ingest lane"
.to_string(),
@@ -2071,12 +2073,19 @@ mod tests {
.unwrap_err()
.contains("bundle_config_hash"));
- let mut admitted = item;
+ let mut admitted = item.clone();
admitted.numerical_admission_sha256 = Some("a".repeat(64));
assert_eq!(
validate_work_items(&body, &[admitted]).unwrap_err(),
"InvalidTransportBinding: numerical admission is not supported on the local-ingest lane"
);
+
+ let mut bridged = item;
+ bridged.fallback_reason = Some("provisioning".into());
+ assert_eq!(
+ validate_work_items(&body, &[bridged]).unwrap_err(),
+ "InvalidTransportBinding: numerical admission is not supported on the local-ingest lane"
+ );
}
#[test]
diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rs
index 5598b2a13..fb17696ab 100644
--- a/packages/sie_server_sidecar/src/nats_consumer.rs
+++ b/packages/sie_server_sidecar/src/nats_consumer.rs
@@ -601,7 +601,7 @@ pub async fn ensure_worker_stream_and_consumer(
js: &JsContext,
config: &WorkerConfig,
) -> Result<PullConsumer, NatsSetupError> {
- ensure_direct_stream_and_consumer(js, config, false).await
+ ensure_direct_stream_and_consumer(js, config, DirectContract::Worker).await
}
/// Separate, bounded durable authority stream; older worker reconciliation
@@ -610,26 +610,47 @@ pub async fn ensure_authority_stream_and_consumer(
js: &JsContext,
config: &WorkerConfig,
) -> Result<PullConsumer, NatsSetupError> {
- ensure_direct_stream_and_consumer(js, config, true).await
+ ensure_direct_stream_and_consumer(js, config, DirectContract::ExecutionAuthorityV1).await
+}
+
+/// Admitted numerical work has its own stream and durable, which only a
+/// sidecar with the admission fence creates. A sidecar without the fence,
+/// including one that consumes the authority stream, never receives it.
+pub async fn ensure_admission_stream_and_consumer(
+ js: &JsContext,
+ config: &WorkerConfig,
+) -> Result<PullConsumer, NatsSetupError> {
+ ensure_direct_stream_and_consumer(js, config, DirectContract::NumericalAdmissionV1).await
+}
+
+#[derive(Clone, Copy)]
+enum DirectContract {
+ Worker,
+ ExecutionAuthorityV1,
+ NumericalAdmissionV1,
}
async fn ensure_direct_stream_and_consumer(
js: &JsContext,
config: &WorkerConfig,
- authority_v1: bool,
+ contract: DirectContract,
) -> Result<PullConsumer, NatsSetupError> {
- let (stream_name, subject, consumer_name) = if authority_v1 {
- (
- config.authority_stream_name(),
- config.authority_subject_filter(),
- config.authority_consumer_name(),
- )
- } else {
- (
+ let (stream_name, subject, consumer_name) = match contract {
+ DirectContract::Worker => (
config.worker_stream_name(),
config.worker_subject_filter(),
config.worker_consumer_name(),
- )
+ ),
+ DirectContract::ExecutionAuthorityV1 => (
+ config.authority_stream_name(),
+ config.authority_subject_filter(),
+ config.authority_consumer_name(),
+ ),
+ DirectContract::NumericalAdmissionV1 => (
+ config.admission_stream_name(),
+ config.admission_subject_filter(),
+ config.admission_consumer_name(),
+ ),
};
let desired_max_age = Duration::from_secs(generation_stream_max_age_secs());
diff --git a/packages/sie_server_sidecar/src/subject.rs b/packages/sie_server_sidecar/src/subject.rs
index 1245c80fa..c9a177674 100644
--- a/packages/sie_server_sidecar/src/subject.rs
+++ b/packages/sie_server_sidecar/src/subject.rs
@@ -18,12 +18,28 @@ const DIRECT_WORK_SUBJECT_PARTS: usize = 7;
/// Incompatible execution contract: older pool/direct filters have fewer tokens.
pub const EXECUTION_AUTHORITY_V1_TOKEN: &str = "execution-authority-v1";
-pub fn requires_execution_authority_v1(subject: &str) -> bool {
+/// Admitted numerical work. No consumer filter of a sidecar without the
+/// admission fence matches this token, including its authority filter.
+pub const NUMERICAL_ADMISSION_V1_TOKEN: &str = "numerical-admission-v1";
+
+fn versioned_direct_token(subject: &str) -> Option<&str> {
let parts: Vec<&str> = subject.split('.').collect();
- parts.len() == DIRECT_WORK_SUBJECT_PARTS + 1
+ (parts.len() == DIRECT_WORK_SUBJECT_PARTS + 1
&& parts.first() == Some(&"sie")
- && parts.get(1) == Some(&"work")
- && parts.last() == Some(&EXECUTION_AUTHORITY_V1_TOKEN)
+ && parts.get(1) == Some(&"work"))
+ .then(|| parts[DIRECT_WORK_SUBJECT_PARTS])
+}
+
+/// Both versioned worker subjects run under execution authority.
+pub fn requires_execution_authority_v1(subject: &str) -> bool {
+ matches!(
+ versioned_direct_token(subject),
+ Some(EXECUTION_AUTHORITY_V1_TOKEN | NUMERICAL_ADMISSION_V1_TOKEN)
+ )
+}
+
+pub fn requires_numerical_admission_v1(subject: &str) -> bool {
+ versioned_direct_token(subject) == Some(NUMERICAL_ADMISSION_V1_TOKEN)
}
/// Verified subjects may not silently retarget a lossy-normalized model id.
@@ -141,6 +157,37 @@ mod tests {
] {
assert!(!requires_execution_authority_v1(invalid));
}
+ assert!(!requires_numerical_admission_v1(subject));
+ }
+
+ #[test]
+ fn admitted_work_subject_matches_no_filter_of_an_unfenced_sidecar() {
+ let subject = "sie.work.pool.machine.bundle.model.worker.numerical-admission-v1";
+ assert!(requires_numerical_admission_v1(subject));
+ assert!(requires_execution_authority_v1(subject));
+ assert!(is_worker_direct_work_subject(subject));
+ assert!(execution_authority_model_matches(subject, "model"));
+ assert!(!execution_authority_model_matches(subject, "other"));
+ for older in [
+ "sie.work.pool.*.*.*",
+ "sie.work.pool.machine.bundle.*",
+ "sie.work.pool.machine.bundle.*.worker",
+ "sie.work.pool.machine.bundle.*.worker.execution-authority-v1",
+ ] {
+ assert!(!subjects_overlap(older, subject), "{older}");
+ }
+ assert!(!subjects_overlap(
+ "sie.work.pool.machine.bundle.*.worker.numerical-admission-v1",
+ "sie.work.pool.machine.bundle.model.worker.execution-authority-v1"
+ ));
+ for invalid in [
+ "sie.work.pool.machine.bundle.model.worker",
+ "sie.work.pool.machine.bundle.model.worker.numerical-admission-v2",
+ "sie.work.pool.machine.bundle.model.worker.extra.numerical-admission-v1",
+ "other.work.pool.machine.bundle.model.worker.numerical-admission-v1",
+ ] {
+ assert!(!requires_numerical_admission_v1(invalid), "{invalid}");
+ }
}
#[test]
diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rs
index d138ab00a..7c126d0e4 100644
--- a/packages/sie_server_sidecar/tests/integration_smoke.rs
+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs
@@ -1886,6 +1886,26 @@ async fn publish_encode_work_item(
reply_subject: &str,
timing: Option<(f64, f64)>,
) -> (String, u64) {
+ let work_item = encode_work_item(
+ request_id,
+ model_id,
+ pool,
+ admission_pool,
+ reply_subject,
+ timing,
+ );
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode WorkItem");
+ publish_jetstream_with_retry(js, subject, payload).await
+}
+
+fn encode_work_item(
+ request_id: &str,
+ model_id: &str,
+ pool: &str,
+ admission_pool: &str,
+ reply_subject: &str,
+ timing: Option<(f64, f64)>,
+) -> WorkItem {
let now_s = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
@@ -1893,7 +1913,7 @@ async fn publish_encode_work_item(
let (timestamp, deadline) = timing.map_or((now_s, None), |(timestamp, deadline)| {
(timestamp, Some(deadline))
});
- let work_item = WorkItem {
+ WorkItem {
work_item_id: format!("{request_id}.0"),
request_id: request_id.into(),
item_index: 0,
@@ -1929,9 +1949,7 @@ async fn publish_encode_work_item(
deadline,
fallback_reason: None,
numerical_admission_sha256: None,
- };
- let payload = rmp_serde::to_vec_named(&work_item).expect("encode WorkItem");
- publish_jetstream_with_retry(js, subject, payload).await
+ }
}
/// WorkQueue retention removes an item only after its consumer ACKs it, so
@@ -3297,36 +3315,17 @@ async fn smoke_scheduler_coalesces_concurrent_encodes() {
sleep(Duration::from_millis(200)).await;
}
-/// Stream discard-policy reconcile (architecture-review finding B3).
-///
-/// A `WORK_POOL_{pool}` / `WORK_WORKER_{worker_id}` stream created by a
-/// pre-fix gateway carries the async-nats default `DiscardPolicy::Old`,
-/// which silently discards the OLDEST queued work at the `max_messages`
-/// cap. Both sidecar ensure paths must repair such streams to `New` so a
-/// full work queue rejects the new publish loudly instead.
-///
-/// Only needs `nats-server` (no Python harness / worker binary), so the
-/// skip gate is intentionally narrower than `skip_unless_tools_available`.
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn ensure_paths_reconcile_stream_discard_policy_to_new() {
- if which("nats-server").is_none() {
- eprintln!("integration_smoke: skipping — missing tools on $PATH: nats-server");
- return;
- }
- let _guard = smoke_test_guard().await;
-
- let nats = NatsHarness::start().await;
- eprintln!("nats: {} (port {})", nats.url, nats.port);
-
- let (_client, js) = sie_server_sidecar::nats_consumer::connect(&nats.url, None)
- .await
- .expect("connect JetStream");
-
- let config = sie_server_sidecar::config::WorkerConfig {
- nats_url: Some(nats.url.clone()),
+/// A worker config for tests that only exercise the JetStream ensure paths.
+fn jetstream_worker_config(
+ nats_url: &str,
+ pool: &str,
+ worker_id: &str,
+) -> sie_server_sidecar::config::WorkerConfig {
+ sie_server_sidecar::config::WorkerConfig {
+ nats_url: Some(nats_url.to_string()),
nats_credentials: None,
local_socket_path: None,
- pool: "discardsmoke".into(),
+ pool: pool.into(),
bundle: "default".into(),
ipc_socket_path: PathBuf::from("/tmp/discard-smoke.sock"),
ipc_socket_paths: vec![PathBuf::from("/tmp/discard-smoke.sock")],
@@ -3341,7 +3340,7 @@ async fn ensure_paths_reconcile_stream_discard_policy_to_new() {
pool_admission_pause_ms: 1_000,
pool_admission_stale_after_ms: 30_000,
probe_port: 9095,
- worker_id: "discard-worker".into(),
+ worker_id: worker_id.into(),
ping_interval_ms: 2000,
ready_stale_mult: 3,
machine_profile: "l4".into(),
@@ -3353,7 +3352,35 @@ async fn ensure_paths_reconcile_stream_discard_policy_to_new() {
config_full_export_interval_ms: 300_000,
nats_config_trusted_producers: vec!["sie-config".into()],
health_publish_interval_ms: 5_000,
- };
+ }
+}
+
+/// Stream discard-policy reconcile (architecture-review finding B3).
+///
+/// A `WORK_POOL_{pool}` / `WORK_WORKER_{worker_id}` stream created by a
+/// pre-fix gateway carries the async-nats default `DiscardPolicy::Old`,
+/// which silently discards the OLDEST queued work at the `max_messages`
+/// cap. Both sidecar ensure paths must repair such streams to `New` so a
+/// full work queue rejects the new publish loudly instead.
+///
+/// Only needs `nats-server` (no Python harness / worker binary), so the
+/// skip gate is intentionally narrower than `skip_unless_tools_available`.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn ensure_paths_reconcile_stream_discard_policy_to_new() {
+ if which("nats-server").is_none() {
+ eprintln!("integration_smoke: skipping — missing tools on $PATH: nats-server");
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ let nats = NatsHarness::start().await;
+ eprintln!("nats: {} (port {})", nats.url, nats.port);
+
+ let (_client, js) = sie_server_sidecar::nats_consumer::connect(&nats.url, None)
+ .await
+ .expect("connect JetStream");
+
+ let config = jetstream_worker_config(&nats.url, "discardsmoke", "discard-worker");
// Pre-create both streams exactly as a pre-fix gateway did: no
// `discard` field, so the async-nats default (`Old`) sticks.
@@ -3478,3 +3505,200 @@ async fn ensure_paths_reconcile_stream_discard_policy_to_new() {
drop(nats);
}
+
+/// Admitted numerical work has its own versioned stream and durable, which
+/// only a sidecar with the admission fence creates. A sidecar without the
+/// fence creates and reconciles only its pool, worker and authority streams:
+/// before a fenced sidecar exists admitted work cannot be published at all,
+/// and afterwards none of the older durables can fetch it.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn admitted_work_is_invisible_to_a_sidecar_without_the_admission_fence() {
+ if which("nats-server").is_none() {
+ eprintln!("integration_smoke: skipping — missing tools on $PATH: nats-server");
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ let nats = NatsHarness::start().await;
+ let (_client, js) = sie_server_sidecar::nats_consumer::connect(&nats.url, None)
+ .await
+ .expect("connect JetStream");
+ let config = jetstream_worker_config(&nats.url, "admissionsmoke", "admission-worker");
+
+ let older = [
+ sie_server_sidecar::nats_consumer::ensure_stream_and_consumer(&js, &config)
+ .await
+ .expect("pool stream and consumer"),
+ sie_server_sidecar::nats_consumer::ensure_worker_stream_and_consumer(&js, &config)
+ .await
+ .expect("worker stream and consumer"),
+ sie_server_sidecar::nats_consumer::ensure_authority_stream_and_consumer(&js, &config)
+ .await
+ .expect("authority stream and consumer"),
+ ];
+ let subject = config.admission_subject_filter().replace('*', "model");
+ let unrouted = js
+ .publish(subject.clone(), "admitted-work".into())
+ .await
+ .expect("publish")
+ .await;
+ assert!(
+ unrouted.is_err(),
+ "no stream of a sidecar without the fence may capture admitted work"
+ );
+
+ let admission =
+ sie_server_sidecar::nats_consumer::ensure_admission_stream_and_consumer(&js, &config)
+ .await
+ .expect("admission stream and consumer");
+ js.publish(subject.clone(), "admitted-work".into())
+ .await
+ .unwrap()
+ .await
+ .unwrap();
+
+ // Rolling the worker back reconciles only the older streams and durables.
+ sie_server_sidecar::nats_consumer::ensure_stream_and_consumer(&js, &config)
+ .await
+ .unwrap();
+ sie_server_sidecar::nats_consumer::ensure_worker_stream_and_consumer(&js, &config)
+ .await
+ .unwrap();
+ sie_server_sidecar::nats_consumer::ensure_authority_stream_and_consumer(&js, &config)
+ .await
+ .unwrap();
+ for consumer in &older {
+ let mut messages = consumer
+ .batch()
+ .max_messages(1)
+ .expires(Duration::from_millis(300))
+ .messages()
+ .await
+ .expect("fetch from an older durable");
+ assert!(timeout(Duration::from_secs(3), messages.next())
+ .await
+ .expect("the fetch expires")
+ .is_none());
+ }
+ for name in [
+ config.stream_name(),
+ config.worker_stream_name(),
+ config.authority_stream_name(),
+ ] {
+ let mut stream = js.get_stream(&name).await.unwrap();
+ assert_eq!(stream.info().await.unwrap().state.messages, 0, "{name}");
+ }
+ let mut stream = js.get_stream(config.admission_stream_name()).await.unwrap();
+ let info = stream.info().await.unwrap();
+ assert_eq!(info.config.subjects, [config.admission_subject_filter()]);
+ assert_eq!(info.state.messages, 1);
+ let mut messages = admission
+ .batch()
+ .max_messages(1)
+ .expires(Duration::from_secs(1))
+ .messages()
+ .await
+ .unwrap();
+ let delivery = timeout(Duration::from_secs(3), messages.next())
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ assert_eq!(delivery.subject.as_str(), subject);
+ delivery.double_ack().await.unwrap();
+
+ drop(nats);
+}
+
+/// Work that breaks the numerical admission contract never runs and is never
+/// handed to another consumer: the worker answers it once with
+/// `INFERENCE_ERROR` and ACKs it.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn work_breaking_the_numerical_admission_contract_is_answered_and_acked() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ let nats = NatsHarness::start().await;
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start(sock.path.clone()).await;
+ let pool = "smoke-admission";
+ let bundle = "default";
+ let probe_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, probe_port, None);
+ wait_for_tcp(probe_port, Duration::from_secs(30))
+ .await
+ .expect("worker probe port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let js = async_nats::jetstream::new(client.clone());
+ let reply_subject = format!("_INBOX.smoke-admission.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ let model = "BAAI/bge-m3";
+ let pooled = pool_work_subject(pool, pool, bundle, model);
+ let direct = worker_work_subject(pool, pool, bundle, model, "smoke-worker");
+ let token = Some("a".repeat(64));
+ let bridged = Some("provisioning".to_string());
+ for (request_id, subject, admission, fallback_reason) in [
+ ("admitted-on-the-pool", pooled.clone(), token.clone(), None),
+ (
+ "admitted-on-the-worker",
+ direct.clone(),
+ token.clone(),
+ None,
+ ),
+ (
+ "admitted-on-the-authority-subject",
+ format!("{direct}.execution-authority-v1"),
+ token.clone(),
+ None,
+ ),
+ (
+ "unadmitted-on-the-admission-subject",
+ format!("{direct}.numerical-admission-v1"),
+ None,
+ None,
+ ),
+ ("bridge-without-an-admission", pooled, None, bridged),
+ ] {
+ let mut work = encode_work_item(request_id, model, pool, "", &reply_subject, None);
+ work.numerical_admission_sha256 = admission;
+ work.fallback_reason = fallback_reason;
+ let payload = rmp_serde::to_vec_named(&work).expect("encode WorkItem");
+ let (stream_name, sequence) = publish_jetstream_with_retry(&js, &subject, payload).await;
+
+ let reply = timeout(Duration::from_secs(10), sub.next())
+ .await
+ .unwrap_or_else(|_| panic!("{request_id}: no answer"))
+ .expect("reply stream closed");
+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");
+ assert_eq!(result.request_id, request_id);
+ assert!(!result.success, "{request_id}");
+ assert_eq!(
+ result.error_code.as_deref(),
+ Some("INFERENCE_ERROR"),
+ "{request_id}"
+ );
+ assert_eq!(result.retry_after_s, Some(1), "{request_id}");
+ let stream = js.get_stream(&stream_name).await.expect("get work stream");
+ let ack_deadline = Instant::now() + Duration::from_secs(2);
+ while stream.get_raw_message(sequence).await.is_ok() {
+ assert!(Instant::now() < ack_deadline, "{request_id} was not ACKed");
+ sleep(Duration::from_millis(25)).await;
+ }
+ }
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
diff --git a/tools/remote_equivalence.py b/tools/remote_equivalence.py
index 0b6813277..ef0f32f0a 100755
--- a/tools/remote_equivalence.py
+++ b/tools/remote_equivalence.py
@@ -255,7 +255,7 @@ def _wake_lanes(
items: list[Item] = [{"id": "probe-wake", "text": "wake"}]
for client, selected in ((local, "default"), (remote, profile)):
common: dict[str, Any] = {
- "options": {**config.resolve_profile("default").runtime, "profile": selected},
+ "options": {**config.resolve_profile(selected).runtime, "profile": selected},
"wait_for_capacity": True,
"max_oom_retries": 0,
}
@@ -345,7 +345,7 @@ def _request(
machine_profile: str | None = None,
) -> tuple[str, Any]:
common: dict[str, Any] = {
- "options": {**config.resolve_profile("default").runtime, "profile": profile},
+ "options": {**config.resolve_profile(profile).runtime, "profile": profile},
"instruction": case.instruction,
"wait_for_capacity": local_instance is None,
"provision_timeout_s": None if local_instance is None else 60.0,
@@ -408,8 +408,8 @@ def run_probe(
resolved = config.resolve_profile(profile)
if profile == "default" or not is_remote_adapter_path(resolved.adapter_path):
raise ValueError("probe requires an explicit remote profile")
- if resolved.runtime.keys() - config.resolve_profile("default").runtime.keys():
- raise ValueError("remote profile adds runtime defaults absent from the fallback contract")
+ if canonical_digest(dict(resolved.runtime)) != canonical_digest(dict(config.resolve_profile("default").runtime)):
+ raise ValueError("remote profile runtime differs from the local runtime it is measured against")
default_runtime = config.resolve_profile("default").runtime
if default_runtime.get("output_dtype", DEFAULT_OUTPUT_DTYPE) != DEFAULT_OUTPUT_DTYPE:
raise ValueError("probe requires the default float32 output dtype")