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(remote): bind equivalence evidence to execution identity, not one process (#572)
Krisztian Gajdar21f7c0b7fd50
diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 7522db9bd..43c05ab3b 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -1692,8 +1692,8 @@ Args (dict): url, field, requireTls.{{- end -}}{{- end -}}{{- $age := $policy.max_age_s -}}-{{- if not (and (or (kindIs "int" $age) (kindIs "int64" $age) (kindIs "float64" $age)) (eq (float64 $age) (floor (float64 $age))) (gt (float64 $age) 0.0) (le (float64 $age) 86400.0)) -}}-{{- fail (printf "%s.max_age_s must be an integer from 1 to 86400" $path) -}}+{{- if not (and (or (kindIs "int" $age) (kindIs "int64" $age) (kindIs "float64" $age)) (eq (float64 $age) (floor (float64 $age))) (gt (float64 $age) 0.0) (le (float64 $age) 604800.0)) -}}+{{- fail (printf "%s.max_age_s must be an integer from 1 to 604800" $path) -}}{{- end -}}{{- $records := $policy.record_files -}}{{- if not (and (kindIs "map" $records) (ge (len $records) 1) (le (len $records) 256)) -}}diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex 7545b277f..7e48b5fd2 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -314,6 +314,7 @@ class ProfileInfo(TypedDict, total=False):is_default: boolidentity: str | Noneremote_contract_sha256: str | None+ remote_execution_sha256: str | Noneruntime_instance_id: str | None"""Versioned immutable local-profile digest; absent/null when it cannot be identified."""diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.mdindex e8f764fd2..490920af6 100644--- a/packages/sie_server/REMOTE_BACKENDS.md+++ b/packages/sie_server/REMOTE_BACKENDS.md@@ -227,10 +227,14 @@ Python sources, installed inference-library versions and current Torchprecision/determinism settings. Hardware observations include the kernel,CPU model/features and selected instruction capability, plus the observed CUDAdevice properties and installed NVIDIA driver revision for CUDA execution.-Numerical library builds, observed BLAS kernel/thread selection and environment-settings also participate. Apple Accelerate is bound to the installed OS-version/build. Observed BLAS kernels are limited to OpenBLAS/BLIS; wrapper-backends and libraries without kernel facts report `null`, including MKL.+Numerical library builds, the kernel and thread selection observed for+NumPy's own BLAS and environment settings also participate. Libraries that+other packages load later are not observed, so a server reports the same+identity before and after it loads a model. Apple Accelerate is bound to the+installed OS version/build. Otherwise NumPy's BLAS must be OpenBLAS or BLIS,+loaded from NumPy's own installation with observable kernel facts; wrapper+backends, system libraries and libraries without kernel facts report `null`,+including MKL.Unknown hardware or numerical libraries report `null`;configured device labels are insufficient. Alias names andinheritance do not change a profile with identical resolved settings.@@ -250,11 +254,14 @@ need passing numerical evidence; SIE profiles require the fresh comparison belowAn encode/score comparison runs through the Python SDK against one direct SIE workerthat has both the local default profile and an explicit remote profile. Keephybrid routing disabled while measuring. The server must expose a non-null-local identity, `profiles.default.runtime_instance_id` and-`profiles.<remote>.remote_contract_sha256`; the latter binds+local identity, `profiles.default.runtime_instance_id`,+`profiles.<remote>.remote_contract_sha256` and+`profiles.<remote>.remote_execution_sha256`. The remote contract bindsits installed endpoint, model serving configuration, credential reference and request-transforms to the operator files supplied to the probe. Credential values are-never included. Version 1 local identities currently support native BGE-M3 only.+transforms to the operator files supplied to the probe. The remote execution+digest identifies the serving code and inference libraries that run the remote+profile. Credential values are never included. Version 1 local identities+currently support native BGE-M3 only.From the locked public workspace, run:@@ -277,8 +284,9 @@ instruction prefixes, default query instructions, empty prefixes, and score scalwhen scoring is declared. All declared encode/score outputs must be measured.Generation is outside this numerical probe. The routing policy is excluded fromthe model digest, so evidence can be measured before enabling hybrid routing;-all local and remote profile settings remain bound. Version 2 records bind the-local profile's runtime options and float32 output explicitly. Both measured+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 measuredprofiles receive those same local runtime options; remote-only runtime defaultsare refused because a fallback would not apply them. Older records must be remeasured.@@ -290,6 +298,8 @@ numerical equivalence. Endpoint/model contracts and local identity must remainunchanged throughout the probe. Every local and remote observation, includinginput refusals, must come from the same worker process identified by the initialmetadata. A load balancer mixing workers cannot produce admissible evidence.+The record names the local execution identity it measured, not the process, so+it also covers other processes that report the same identity.Exit status is `0` for passing evidence, `1` for a measured failure, or `2` whenvalid evidence could not be produced. Records contain input hashes, token@@ -356,10 +366,13 @@ upstreams:BAAI/bge-m3: /absolute/path/bge-m3-equivalence.json```-The map keys are local catalog model IDs. The referenced file must contain a-passing version 2 record for that exact model, local identity, worker process,-remote profile, endpoint/model contract and all declared numerical outputs.-The age is a strict integer from 1 to 86400 seconds. Paths and proof authority+The map keys are local catalog model IDs. The referenced file holds one+version 3 record, or a bundle of records for several local identities (see+[Collecting numerical fleet evidence](#collecting-numerical-fleet-evidence)).+A passing record admits only the exact model, remote profile, endpoint/model+contract, remote execution digest and declared numerical outputs it measured,+and only for the local identity it names.+The age is a strict integer from 1 to 604800 seconds. Paths and proof authoritycome only from startup upstream configuration; model API requests cannot supplyor install records. SIE upstreams refuse this policy and require their ownimmutable identity comparison instead.@@ -380,42 +393,45 @@ with unmeasured runtime overrides or non-float32 output also remain local;explicit profiles still serve as requested. Rejection of one exported modelretains its current local configuration without blocking unrelated updates.-Records are bound to the measured worker process. After a worker restart,-disable hybrid routing before startup, re-probe and activate through hot reload-again. Starting directly from a hybrid YAML with an old process-bound record is-refused. This conservative first admission path requires one record per worker-process with one configured concrete device (`cuda:0`, rather than `cuda`,-for a CUDA worker). Multiple devices or a model loaded outside that placement-cannot report an admission identity or use the proof. It does not enable-gateway fallback or a fleet-wide evidence rollout.+A record is bound to the local execution identity it measured, not to the+measured process. A restarted server, or another server with the same software,+inference libraries, hardware and settings, reports the same identity and is+admitted by the same record, also when it starts from a hybrid YAML. A change+to any of them changes the identity and needs a new measurement. Admission+requires one configured concrete device (`cuda:0`, rather than `cuda`, for a+CUDA worker). Multiple devices or a model loaded outside that placement cannot+report an admission identity or use the proof. This does not enable gateway+fallback.## Collecting numerical fleet evidence-Collect one version 2 proof from every reachable Python worker process, including-children behind a sidecar and workers eligible for pool fallback. Each proof-still requires two local runs and one explicit remote run against that process.-The collector accepts repeated `--record` paths, writes a new `--output` file,-and checks a `--max-age-s` window from 1 to 86400 seconds (default 3600):+Servers with different hardware, drivers, inference libraries or settings+report different local identities, and each identity needs its own+measurement: two local runs and one explicit remote run on a server with that+identity. The bundle tool collects one version 3 record per identity into one+evidence file, which an upstream's `record_files` entry can name in place of a+single record. It accepts repeated `--record` paths, writes a new `--output`+file, and checks a `--max-age-s` window from 1 to 604800 seconds (default 3600):```bashmise exec -- uv run --frozen --project . python tools/remote_fleet_equivalence.py \- --record /absolute/path/worker-a.json \- --record /absolute/path/worker-b.json \- --output /absolute/path/fleet.json --max-age-s 3600+ --record /absolute/path/identity-a.json \+ --record /absolute/path/identity-b.json \+ --output /absolute/path/bundle.json --max-age-s 3600```-The version 1 inventory retains the original measurements, including misses.+The version 2 bundle retains the original measurements, including misses.Exit status 0 means all records passed and are fresh, 1 means valid evidencecontains a failure or expired/future measurement, and 2 means collection failed.Existing output files are never overwritten. Inputs are bounded regular files;-the inventory contains at most 256 records and occupies at most 8 MiB.+the bundle contains at most 256 records and occupies at most 8 MiB.-Every member must measure the same model, profiles, endpoint/model contract,-runtime defaults, outputs and probe inputs. Processes may have different local-execution identities, each bound to its own measurement. Canonical digests bind-the entire record, including its process, timestamp and measured errors. Exact-inventory matching rejects missing, additional or replaced processes, even when-a replacement reports the same execution identity.+Every record must measure the same model, profiles, endpoint/model contract,+remote execution digest, runtime defaults, outputs and probe inputs, and no+identity may appear twice. Canonical digests bind the entire record, including+its identity, timestamp and measured errors. A server is admitted only by a+passing, fresh record for its own identity, so a failed or expired record for+one identity leaves the other identities admitted.Sidecars independently poll every adapter child and attach optional`numerical_process_inventory` diagnostics to NATS health messages. Cluster@@ -427,11 +443,10 @@ older than ten seconds do not retain a previous process's inventory. Normalhealth publication does not wait for these probes, and diagnostics use dedicatedIPC connections so they do not occupy serving or readiness connection slots.-These observations and the proof artifact grant no routing authority. An-`observed` child can still lack a local identity. Numerical gateway routing remains-inactive until operator-owned evidence, complete live membership and execution-fencing are connected. Restarts require new proofs; a collector result cannot-authorize a new process or establish scale-to-zero equivalence.+These observations and the evidence file grant no gateway routing authority.+An `observed` child can still lack a local identity. Numerical gateway routing+remains inactive until operator-owned evidence, complete live membership and+execution fencing are connected.## Single-node generation fallbackdiff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 53c545039..47620c1e0 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -2440,6 +2440,17 @@],"title": "Remote Contract Sha256"},+ "remote_execution_sha256": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Remote Execution Sha256"+ },"runtime_instance_id": {"anyOf": [{diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.pyindex 9537e20f2..d6f70f6ec 100644--- a/packages/sie_server/src/sie_server/api/models.py+++ b/packages/sie_server/src/sie_server/api/models.py@@ -7,7 +7,7 @@ from sie_server.config.equivalence import remote_profile_contract_digestfrom sie_server.config.model import ModelConfig, RoutingPolicy, is_remote_adapter_pathfrom sie_server.config.upstreams import installed_upstreamsfrom sie_server.core.model_suggestions import suggestion_suffix-from sie_server.core.profile_identity import local_profile_identity, runtime_instance_id+from sie_server.core.profile_identity import local_profile_identity, runtime_instance_id, serving_code_digestfrom sie_server.types.responses import ErrorCodeif TYPE_CHECKING:@@ -29,8 +29,10 @@ class ProfileInfo(BaseModel):"""Versioned immutable local-profile digest, or None when it cannot be identified."""remote_contract_sha256: str | None = None"""Digest binding the model/profile to this server's operator-defined upstream."""+ remote_execution_sha256: str | None = None+ """Digest of the serving code that runs this remote profile in this process."""runtime_instance_id: str | None = None- """Opaque serving-process identity; numerical probe records cannot cross workers or restarts."""+ """Opaque identity of the serving process, for probe provenance."""class ModelLoadError(BaseModel):@@ -202,6 +204,22 @@ def _resolve_capabilities(config: Any) -> ModelCapabilities | None:)+def _profile_info(registry: "ModelRegistry | Any", name: str, config: ModelConfig, profile: str) -> ProfileInfo:+ remote = is_remote_adapter_path(config.resolve_profile(profile).adapter_path)+ return ProfileInfo(+ is_default=(profile == "default"),+ identity=local_profile_identity(+ config,+ profile,+ device=registry.profile_execution_device(name if profile == "default" else f"{name}:{profile}") or "",+ engine_config=registry.engine_config,+ ),+ remote_contract_sha256=remote_profile_contract_digest(config, profile, installed_upstreams()),+ remote_execution_sha256=serving_code_digest() if remote else None,+ runtime_instance_id=None if remote else runtime_instance_id(),+ )++class ModelsListResponse(BaseModel):"""Response for listing models."""@@ -223,22 +241,7 @@ async def list_models(http_request: Request) -> ModelsListResponse:models = []for name in registry.model_names:config = registry.get_config(name)- profiles = {- pname: ProfileInfo(- is_default=(pname == "default"),- identity=local_profile_identity(- config,- pname,- device=registry.profile_execution_device(name if pname == "default" else f"{name}:{pname}") or "",- engine_config=registry.engine_config,- ),- remote_contract_sha256=remote_profile_contract_digest(config, pname, installed_upstreams()),- runtime_instance_id=runtime_instance_id()- if not is_remote_adapter_path(config.resolve_profile(pname).adapter_path)- else None,- )- for pname in config.profiles- }+ profiles = {pname: _profile_info(registry, name, config, pname) for pname in config.profiles}state, last_error = _resolve_state_and_error(registry, name)models.append(ModelInfo(@@ -289,22 +292,7 @@ async def get_model(model: str, http_request: Request) -> ModelInfo:)config = registry.get_config(model)- profiles = {- pname: ProfileInfo(- is_default=(pname == "default"),- identity=local_profile_identity(- config,- pname,- device=registry.profile_execution_device(model if pname == "default" else f"{model}:{pname}") or "",- engine_config=registry.engine_config,- ),- remote_contract_sha256=remote_profile_contract_digest(config, pname, installed_upstreams()),- runtime_instance_id=runtime_instance_id()- if not is_remote_adapter_path(config.resolve_profile(pname).adapter_path)- else None,- )- for pname in config.profiles- }+ profiles = {pname: _profile_info(registry, model, config, pname) for pname in config.profiles}state, last_error = _resolve_state_and_error(registry, model)return ModelInfo(name=config.sie_id,diff --git a/packages/sie_server/src/sie_server/config/equivalence.py b/packages/sie_server/src/sie_server/config/equivalence.pyindex 6a92cee85..2faf1a76e 100644--- a/packages/sie_server/src/sie_server/config/equivalence.py+++ b/packages/sie_server/src/sie_server/config/equivalence.py@@ -1,8 +1,10 @@"""Bounded, versioned evidence from two local runs and one remote run.Records are operator artifacts, never caller assertions. They contain hashes-and measured errors, not request bodies, vectors or credentials. This module-does not admit hybrid routing; the deployment/runtime gate consumes the record.+and measured errors, not request bodies, vectors or credentials. A record binds+one local execution identity, not the process that was measured, so every+process reporting that identity is covered. This module does not admit hybrid+routing; the deployment/runtime gate consumes the record."""from __future__ import annotations@@ -182,7 +184,7 @@ class ProbeCase(BaseModel):class EquivalenceRecord(BaseModel):model_config = ConfigDict(extra="forbid", frozen=True, strict=True)- version: Literal[2] = 2+ version: Literal[3] = 3measured_at: AwareDatetimeupstream_name: str = Field(min_length=1, max_length=128)upstream_model: str = Field(min_length=1, max_length=256)@@ -190,10 +192,10 @@ class EquivalenceRecord(BaseModel):model_contract_sha256: str = Field(pattern=_HASH_PATTERN)probe_sources_sha256: str = Field(pattern=_HASH_PATTERN)remote_contract_sha256: str = Field(pattern=_HASH_PATTERN)+ remote_execution_sha256: str = Field(pattern=_HASH_PATTERN)local_observation_sha256: str = Field(pattern=_HASH_PATTERN)runtime_options_sha256: str = Field(pattern=_HASH_PATTERN)output_dtype: Literal["float32"]- local_instance_id: str = Field(pattern=_HASH_PATTERN)local_identity: str = Field(pattern=r"^v1:sha256:[0-9a-f]{64}$")model: str = Field(min_length=1, max_length=256)local_profile: str = "default"diff --git a/packages/sie_server/src/sie_server/config/fleet_equivalence.py b/packages/sie_server/src/sie_server/config/fleet_equivalence.pyindex 1bb515554..b5a964aca 100644--- a/packages/sie_server/src/sie_server/config/fleet_equivalence.py+++ b/packages/sie_server/src/sie_server/config/fleet_equivalence.py@@ -1,24 +1,24 @@-"""Process-bound numerical evidence inventory; parsing grants no routing authority.+"""Evidence for one remote profile across local execution identities.-Every reachable Python process needs its own two-local/one-remote measurement.-Failed and expired records remain diagnostic evidence, never admission proof.+A bundle holds one record per local execution identity, all measuring the same+comparison contract. Parsing grants no routing authority. Failed and expired+records remain diagnostic evidence, never admission proof."""from __future__ import annotations-from collections.abc import Mappingfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any, Literal-from pydantic import BaseModel, ConfigDict, Field, model_validator+from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, model_validatorfrom sie_server.config.equivalence import EquivalenceRecord, canonical_digest, read_equivalence_bytesMAX_FLEET_RECORDS = 256MAX_FLEET_BYTES = 8 << 20-MAX_EVIDENCE_AGE_S = 86_400-_PROCESS_FIELDS = {"measured_at", "local_instance_id", "local_identity", "local_observation_sha256", "cases"}+MAX_EVIDENCE_AGE_S = 604_800+_IDENTITY_FIELDS = {"measured_at", "local_identity", "local_observation_sha256", "cases"}def _canonical_record(record: EquivalenceRecord) -> dict[str, Any]:@@ -30,13 +30,13 @@ def _canonical_record(record: EquivalenceRecord) -> dict[str, Any]:def equivalence_record_digest(record: EquivalenceRecord) -> str:- """Bind the entire measurement, including failures, process and timestamp."""+ """Bind the entire measurement, including failures, identity and timestamp."""return canonical_digest(_canonical_record(record))def _comparison_contract(record: EquivalenceRecord) -> dict[str, Any]:data = _canonical_record(record)- contract = {key: value for key, value in data.items() if key not in _PROCESS_FIELDS}+ contract = {key: value for key, value in data.items() if key not in _IDENTITY_FIELDS}contract["cases"] = [{key: case[key] for key in ("operation", "category", "input_sha256", "token_counts")} for case in data["cases"]]@@ -44,17 +44,17 @@ def _comparison_contract(record: EquivalenceRecord) -> dict[str, Any]:class FleetEquivalenceRecord(BaseModel):- """One comparison contract, measured independently on each listed process."""+ """One comparison contract, measured once for each listed execution identity."""model_config = ConfigDict(extra="forbid", frozen=True, strict=True)- version: Literal[1] = 1+ version: Literal[2] = 2records: tuple[EquivalenceRecord, ...] = Field(min_length=1, max_length=MAX_FLEET_RECORDS)@model_validator(mode="after")def coherent(self) -> FleetEquivalenceRecord:- if len({record.local_instance_id for record in self.records}) != len(self.records):- raise ValueError("fleet evidence must not repeat a process")+ if len({record.local_identity for record in self.records}) != len(self.records):+ raise ValueError("fleet evidence must not repeat an execution identity")contract = _comparison_contract(self.records[0])if any(_comparison_contract(record) != contract for record in self.records[1:]):raise ValueError("fleet evidence must measure the same comparison contract")@@ -66,16 +66,12 @@ class FleetEquivalenceRecord(BaseModel):@propertydef record_digests(self) -> dict[str, str]:- return {record.local_instance_id: equivalence_record_digest(record) for record in self.records}+ return {record.local_identity: equivalence_record_digest(record) for record in self.records}@propertydef digest(self) -> str:return canonical_digest({"version": self.version, "records": self.record_digests})- def matches_inventory(self, processes: Mapping[str, str]) -> bool:- """Require the exact nonempty process-to-execution-identity roster."""- return {record.local_instance_id: record.local_identity for record in self.records} == dict(processes)-def is_fresh(self, *, max_age_s: int, now: datetime | None = None) -> bool:if type(max_age_s) is not int or not 1 <= max_age_s <= MAX_EVIDENCE_AGE_S:return False@@ -83,6 +79,15 @@ class FleetEquivalenceRecord(BaseModel):return all(record.is_fresh(max_age_s=max_age_s, now=observed) for record in self.records)+_EVIDENCE = TypeAdapter(FleetEquivalenceRecord | EquivalenceRecord)++def read_fleet_equivalence_record(path: str | Path) -> FleetEquivalenceRecord:"""Read a bounded regular operator artifact, including failed measurements."""return FleetEquivalenceRecord.model_validate_json(read_equivalence_bytes(path, max_bytes=MAX_FLEET_BYTES))+++def read_equivalence_evidence(path: str | Path) -> tuple[EquivalenceRecord, ...]:+ """Read one record, or a bundle of records, from a bounded regular file."""+ evidence = _EVIDENCE.validate_json(read_equivalence_bytes(path, max_bytes=MAX_FLEET_BYTES))+ return evidence.records if isinstance(evidence, FleetEquivalenceRecord) else (evidence,)diff --git a/packages/sie_server/src/sie_server/config/hybrid_admission.py b/packages/sie_server/src/sie_server/config/hybrid_admission.pyindex 8fc5d5d8f..ec4d7eb1a 100644--- a/packages/sie_server/src/sie_server/config/hybrid_admission.py+++ b/packages/sie_server/src/sie_server/config/hybrid_admission.py@@ -1,14 +1,16 @@"""Runtime admission of exact, fresh operator-owned hybrid evidence.Reading a record never makes it authoritative for a different model, endpoint,-profile or local runtime. The check is repeated before each bridged request,-so replacing a record or letting it expire cannot keep an old admission alive.+profile or local execution identity. The check is repeated before each bridged+request, so replacing a record or letting it expire cannot keep an old+admission alive."""from __future__ import annotationsfrom collections.abc import Mapping-from datetime import datetime+from dataclasses import dataclass+from datetime import UTC, datetime, timedeltafrom pydantic import ValidationErrorfrom sie_sdk.types import DEFAULT_OUTPUT_DTYPE@@ -17,25 +19,34 @@ from sie_server.config.engine import EngineConfigfrom sie_server.config.equivalence import (canonical_digest,model_contract_digest,- read_equivalence_record,remote_profile_contract_digest,upstream_contract_digest,)+from sie_server.config.fleet_equivalence import equivalence_record_digest, read_equivalence_evidencefrom sie_server.config.model import ModelConfigfrom sie_server.config.upstreams import UpstreamKind, installed_upstreams-from sie_server.core.profile_identity import local_profile_identity, runtime_instance_id+from sie_server.core.profile_identity import local_profile_identity, serving_code_digest+_NUMERICAL_OUTPUTS = frozenset({"dense", "sparse", "multivector", "score"})-def openai_equivalence_refusal(- config: ModelConfig,- *,- device: str,- engine_config: EngineConfig | None = None,- now: datetime | None = None,-) -> str | None:- """Return a fixed refusal reason, or ``None`` for passing current evidence."""- if device == "cuda" or (device.startswith("cuda:") and not device.partition(":")[2].isdigit()):- return "hybrid execution device is ambiguous"++@dataclass(frozen=True)+class NumericalAdmission:+ """The local execution identities that a remote profile's current evidence covers."""++ sha256: str+ local_identities: frozenset[str]+ model_contract_sha256: str+ outputs: frozenset[str]+ expires_at: datetime+++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.++ The admission depends on the installed evidence, this process's upstream and+ code, and the model configuration. It does not depend on the process asking.+ """routing = config.routingif routing is None or routing.policy not in {"fallback", "threshold"}:return "model does not declare a hybrid policy"@@ -45,44 +56,90 @@ def openai_equivalence_refusal(upstreams = installed_upstreams()profile = config.resolve_profile(profile_name)upstream_name = profile.loadtime.get("upstream")- upstream_model = profile.loadtime.get("upstream_model")upstream = upstreams.get(upstream_name) if isinstance(upstream_name, str) else Noneif upstream is None or upstream.kind is not UpstreamKind.OPENAI:return "hybrid profile requires immutable SIE identity or OpenAI proof"policy = upstream.equivalenceif policy is None or config.sie_id not in policy.record_files:return "hybrid profile has no operator-owned equivalence record"- if profile.runtime.keys() - config.resolve_profile("default").runtime.keys():+ default_runtime = config.resolve_profile("default").runtime+ if profile.runtime.keys() - default_runtime.keys():return "hybrid remote profile adds unmeasured runtime defaults"- if config.resolve_profile("default").runtime.get("output_dtype", DEFAULT_OUTPUT_DTYPE) != DEFAULT_OUTPUT_DTYPE:+ if default_runtime.get("output_dtype", DEFAULT_OUTPUT_DTYPE) != DEFAULT_OUTPUT_DTYPE:return "hybrid output dtype differs from the measured float32 contract"- identity = local_profile_identity(config, "default", device=device, engine_config=engine_config)- if identity is None:- return "hybrid local execution cannot be identified"+ remote_execution = serving_code_digest()+ if remote_execution is None:+ return "hybrid remote execution cannot be identified"try:- record = read_equivalence_record(policy.record_files[config.sie_id])+ records = read_equivalence_evidence(policy.record_files[config.sie_id])except (OSError, ValueError, ValidationError, RecursionError):return "hybrid equivalence record cannot be validated"- if not record.passed or not record.is_fresh(max_age_s=policy.max_age_s, now=now):- return "hybrid equivalence record failed or is outside its configured age"- outputs = frozenset(set(config.outputs) & {"dense", "sparse", "multivector", "score"})- if (- record.model != config.sie_id- or record.local_profile != "default"- or record.remote_profile != profile_name- or record.upstream_name != upstream_name- or record.upstream_model != upstream_model- or record.context_length != config.max_sequence_length- or record.outputs != outputs- or record.local_identity != identity- or record.local_instance_id != runtime_instance_id()- or record.runtime_options_sha256 != canonical_digest(dict(config.resolve_profile("default").runtime))- or record.model_contract_sha256 != model_contract_digest(config)- or record.upstream_contract_sha256 != upstream_contract_digest(upstream)- or record.remote_contract_sha256 != remote_profile_contract_digest(config, profile_name, upstreams)- or record.local_observation_sha256 != canonical_digest({"identity": identity, "revision": config.hf_revision})- ):+ remote_contract = remote_profile_contract_digest(config, profile_name, upstreams)+ contract = {+ "model": config.sie_id,+ "local_profile": "default",+ "remote_profile": profile_name,+ "upstream_name": upstream_name,+ "upstream_model": profile.loadtime.get("upstream_model"),+ "context_length": config.max_sequence_length,+ "outputs": frozenset(set(config.outputs) & _NUMERICAL_OUTPUTS),+ "runtime_options_sha256": canonical_digest(dict(default_runtime)),+ "model_contract_sha256": model_contract_digest(config),+ "upstream_contract_sha256": upstream_contract_digest(upstream),+ "remote_contract_sha256": remote_contract,+ "remote_execution_sha256": remote_execution,+ }+ matching = [+ record+ for record in records+ 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})+ ]+ if not matching: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)+ ]+ if not admitted:+ return "hybrid equivalence record failed or is outside its configured age"+ return NumericalAdmission(+ sha256=canonical_digest(+ {+ "version": 1,+ "kind": UpstreamKind.OPENAI.value,+ "model": config.sie_id,+ "remote_profile": profile_name,+ "remote_contract_sha256": remote_contract,+ "records": sorted(equivalence_record_digest(record) 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),+ )+++def openai_equivalence_refusal(+ config: ModelConfig,+ *,+ device: str,+ engine_config: EngineConfig | None = None,+ now: datetime | None = None,+) -> str | None:+ """Return a fixed refusal reason, or ``None`` when current evidence covers this process."""+ if device == "cuda" or (device.startswith("cuda:") and not device.partition(":")[2].isdigit()):+ return "hybrid execution device is ambiguous"+ admission = openai_admission(config, now=now)+ if isinstance(admission, str):+ return admission+ identity = local_profile_identity(config, "default", device=device, engine_config=engine_config)+ if identity is None:+ return "hybrid local execution cannot be identified"+ if identity not in admission.local_identities:+ return "hybrid equivalence record does not cover this execution identity"return Nonediff --git a/packages/sie_server/src/sie_server/config/upstreams.py b/packages/sie_server/src/sie_server/config/upstreams.pyindex b4dd1839c..c580e8ff5 100644--- a/packages/sie_server/src/sie_server/config/upstreams.py+++ b/packages/sie_server/src/sie_server/config/upstreams.py@@ -254,7 +254,7 @@ class EquivalencePolicy(BaseModel):model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)- max_age_s: int = Field(gt=0, le=86400, strict=True)+ max_age_s: int = Field(gt=0, le=604_800, strict=True)record_files: dict[str, str] = Field(min_length=1, max_length=256)@field_validator("record_files")diff --git a/packages/sie_server/src/sie_server/core/profile_identity.py b/packages/sie_server/src/sie_server/core/profile_identity.pyindex a10b892be..71cdf2ad6 100644--- a/packages/sie_server/src/sie_server/core/profile_identity.py+++ b/packages/sie_server/src/sie_server/core/profile_identity.py@@ -50,7 +50,7 @@ _RUNTIME_NONCE = uuid4().hexdef runtime_instance_id() -> str:- """Opaque process identity; restarts and forks require a fresh local probe."""+ """Opaque identity of this serving process, used for probe provenance."""return hashlib.sha256(f"{os.getpid()}:{_RUNTIME_NONCE}".encode()).hexdigest()@@ -217,6 +217,15 @@ def _execution_code() -> dict[str, Any]:}+def serving_code_digest() -> str | None:+ """Digest of this process's serving sources and inference libraries, or ``None``."""+ try:+ encoded = json.dumps(_execution_code(), sort_keys=True, separators=(",", ":"), allow_nan=False).encode()+ except (OSError, TypeError, ValueError):+ return None+ return hashlib.sha256(encoded).hexdigest()++@lru_cache(maxsize=256)def _adapter_source_available(adapter_path: str) -> bool:"""Refuse custom/unidentifiable adapters without importing provider code."""@@ -240,11 +249,30 @@ def _adapter_source_available(adapter_path: str) -> bool:return any(isinstance(node, ast.ClassDef) and node.name == class_name for node in tree.body)+def _from_numpy_installation(filepath: object) -> bool:+ if not isinstance(filepath, str) or not filepath:+ return False+ package = Path(np.__file__).resolve().parent+ try:+ library = Path(filepath).resolve()+ except (OSError, RuntimeError):+ return False+ return any(library.is_relative_to(root) for root in (package, package.with_name(f"{package.name}.libs")))++def _numerical_libraries() -> dict[str, Any]:- """Observe loaded BLAS kernels and threads without exporting host paths."""+ """Observe the kernels and threads of NumPy's own BLAS without exporting host paths.++ Only libraries loaded from NumPy's installation are observed. A library that+ another package loads later must not change the identity: a process reports+ the same identity before and after it loads a model.+ """keys = ("user_api", "internal_api", "prefix", "version", "num_threads", "threading_layer", "architecture")- libraries = [{key: library.get(key) for key in keys} for library in threadpool_info()]- blas = [library for library in libraries if library["user_api"] == "blas"]+ blas = [+ {key: library.get(key) for key in keys}+ for library in threadpool_info()+ if library.get("user_api") == "blas" and _from_numpy_installation(library.get("filepath"))+ ]if any(library["internal_api"] not in {"openblas", "blis"}or not library["version"]@@ -255,7 +283,6 @@ def _numerical_libraries() -> dict[str, Any]:for library in blas):raise ValueError("numerical execution libraries cannot be identified")- # NumPy's system BLAS remains relevant even alongside another loaded BLAS.build = np.show_config(mode="dicts")numpy_blas = build.get("Build Dependencies", {}).get("blas", {}).get("name")uses_accelerate = numpy_blas == "accelerate"@@ -278,7 +305,7 @@ def _numerical_libraries() -> dict[str, Any]:if required_api is None or not any(library["internal_api"] == required_api for library in blas):raise ValueError("numerical execution libraries cannot be identified")return {- "loaded": sorted(libraries, key=lambda library: json.dumps(library, sort_keys=True)),+ "numpy_blas": sorted(blas, key=lambda library: json.dumps(library, sort_keys=True)),"accelerate_os_version": accelerate,}diff --git a/packages/sie_server/tests/api/test_models.py b/packages/sie_server/tests/api/test_models.pyindex 1a4288176..94b5db8dc 100644--- a/packages/sie_server/tests/api/test_models.py+++ b/packages/sie_server/tests/api/test_models.py@@ -18,6 +18,7 @@ from sie_server.config.model import ()from sie_server.config.upstreams import Upstreamfrom sie_server.core.load_errors import LoadErrorClass, LoadFailure+from sie_server.core.profile_identity import serving_code_digestfrom sie_server.core.registry import ModelRegistry@@ -453,6 +454,9 @@ def test_remote_contract_metadata_binds_the_installed_upstream(for value in (detail, listed):assert value["profiles"]["remote"]["remote_contract_sha256"] == expectedassert value["profiles"]["default"]["remote_contract_sha256"] is None+ assert value["profiles"]["remote"]["remote_execution_sha256"] == serving_code_digest() is not None+ assert value["profiles"]["default"]["remote_execution_sha256"] is None+ assert value["profiles"]["remote"]["runtime_instance_id"] is Noneassert base_url not in str(value)assert "SECRET_ENV_REFERENCE" not in str(value)different = upstream.model_copy(update={"base_url": "https://other.example/v1"})diff --git a/packages/sie_server/tests/config/test_equivalence.py b/packages/sie_server/tests/config/test_equivalence.pyindex af492a9b3..a82ddc6f2 100644--- a/packages/sie_server/tests/config/test_equivalence.py+++ b/packages/sie_server/tests/config/test_equivalence.py@@ -28,12 +28,14 @@ from sie_server.config.fleet_equivalence import (MAX_FLEET_BYTES,FleetEquivalenceRecord,equivalence_record_digest,+ read_equivalence_evidence,read_fleet_equivalence_record,)from sie_server.config.model import ModelConfigfrom sie_server.config.upstreams import load_upstreamsNOW = datetime(2026, 10, 3, tzinfo=UTC)+OTHER_IDENTITY = "v1:sha256:" + "e" * 64_PROBE_PATH = Path(__file__).resolve().parents[4] / "tools" / "remote_equivalence.py"_PROBE_SPEC = importlib.util.spec_from_file_location("remote_equivalence_probe", _PROBE_PATH)assert _PROBE_SPEC is not None@@ -84,7 +86,7 @@ def record(*, outputs: frozenset[str] = frozenset({"dense"})) -> EquivalenceRecoreturn EquivalenceRecord.model_validate_json(json.dumps({- "version": 2,+ "version": 3,"measured_at": NOW.isoformat(),"upstream_name": "upstream","upstream_model": "vendor/model",@@ -92,10 +94,10 @@ def record(*, outputs: frozenset[str] = frozenset({"dense"})) -> EquivalenceReco"model_contract_sha256": "c" * 64,"probe_sources_sha256": "d" * 64,"remote_contract_sha256": "d" * 64,+ "remote_execution_sha256": "9" * 64,"local_observation_sha256": "e" * 64,"runtime_options_sha256": "f" * 64,"output_dtype": "float32",- "local_instance_id": "a" * 64,"local_identity": "v1:sha256:" + "f" * 64,"model": "local/model","remote_profile": "remote",@@ -208,8 +210,15 @@ class _Tokenizer:@pytest.mark.parametrize(- ("remote_offset", "contract_mismatch", "instance_mismatch"),- [(0.0, False, None), (0.01, False, None), (0.0, True, None), (0.0, False, "local"), (0.0, False, "remote")],+ ("remote_offset", "contract_mismatch", "instance_mismatch", "remote_execution"),+ [+ (0.0, False, None, "8" * 64),+ (0.01, False, None, "8" * 64),+ (0.0, True, None, "8" * 64),+ (0.0, False, "local", "8" * 64),+ (0.0, False, "remote", "8" * 64),+ (0.0, False, None, None),+ ],)def test_full_cli_runs_real_sdk_transport_and_only_writes_evidence(tmp_path: Path,@@ -217,6 +226,7 @@ def test_full_cli_runs_real_sdk_transport_and_only_writes_evidence(remote_offset: float,contract_mismatch: bool,instance_mismatch: str | None,+ remote_execution: str | None,) -> None:requests: list[tuple[dict[str, Any], bool]] = []remote_contract: str | None = None@@ -231,7 +241,10 @@ def test_full_cli_runs_real_sdk_transport_and_only_writes_evidence("max_sequence_length": 32,"profiles": {"default": {"identity": "v1:sha256:" + "f" * 64, "runtime_instance_id": "a" * 64},- "remote": {"remote_contract_sha256": remote_contract},+ "remote": {+ "remote_contract_sha256": remote_contract,+ "remote_execution_sha256": remote_execution,+ },},}).encode(),@@ -325,7 +338,7 @@ profiles:server.shutdown()server.server_close()thread.join(timeout=5)- if contract_mismatch:+ if contract_mismatch or remote_execution is None:assert result == 2assert not requestsassert not output.exists()@@ -338,7 +351,9 @@ profiles:assert result == (0 if remote_offset == 0 else 1)evidence = EquivalenceRecord.model_validate_json(output.read_bytes())assert evidence.passed == (remote_offset == 0)- assert evidence.version == 2+ assert evidence.version == 3+ assert evidence.remote_execution_sha256 == remote_execution+ assert "local_instance_id" not in evidence.model_dump()assert evidence.runtime_options_sha256 == canonical_digest({"normalize": True})assert all(body["params"]["options"]["normalize"] is True for body, _ in requests)assert all(body["params"]["output_dtype"] == "float32" for body, _ in requests)@@ -433,17 +448,12 @@ def _fleet_record(**changes: Any) -> EquivalenceRecord:return EquivalenceRecord.model_validate_json(json.dumps(data))-def test_fleet_inventory_requires_every_exact_process_including_replacements() -> None:+def test_bundle_holds_one_record_per_execution_identity() -> None:first = _fleet_record()- second = _fleet_record(local_instance_id="b" * 64, local_identity="v1:sha256:" + "e" * 64)+ second = _fleet_record(local_identity=OTHER_IDENTITY)fleet = FleetEquivalenceRecord(records=(first, second))- roster = {first.local_instance_id: first.local_identity, second.local_instance_id: second.local_identity}- assert fleet.matches_inventory(roster)- assert not fleet.matches_inventory({})- assert not fleet.matches_inventory({first.local_instance_id: first.local_identity})- assert not fleet.matches_inventory({**roster, "c" * 64: first.local_identity})- assert not fleet.matches_inventory({first.local_instance_id: first.local_identity, "c" * 64: second.local_identity})- assert not fleet.matches_inventory({**roster, second.local_instance_id: first.local_identity})+ assert set(fleet.record_digests) == {first.local_identity, OTHER_IDENTITY}+ assert fleet.passed@pytest.mark.parametrize("count", [0, 257])@@ -452,9 +462,12 @@ def test_fleet_inventory_has_bounded_nonempty_membership(count: int) -> None:FleetEquivalenceRecord(records=(record(),) * count)-def test_fleet_inventory_rejects_duplicate_processes() -> None:- with pytest.raises(ValidationError, match="repeat a process"):+def test_fleet_inventory_rejects_a_repeated_execution_identity() -> None:+ with pytest.raises(ValidationError, match="repeat an execution identity"):FleetEquivalenceRecord(records=(record(), record()))+ with pytest.raises(ValidationError, match="repeat an execution identity"):+ remeasured = _fleet_record(measured_at=(NOW + timedelta(seconds=1)).isoformat())+ FleetEquivalenceRecord(records=(_fleet_record(), remeasured))@pytest.mark.parametrize(@@ -467,6 +480,7 @@ def test_fleet_inventory_rejects_duplicate_processes() -> None:{"upstream_contract_sha256": "0" * 64},{"model_contract_sha256": "0" * 64},{"remote_contract_sha256": "0" * 64},+ {"remote_execution_sha256": "0" * 64},{"runtime_options_sha256": "0" * 64},{"probe_sources_sha256": "0" * 64},{"context_length": 513},@@ -481,7 +495,7 @@ def test_fleet_inventory_rejects_mixed_comparison_contracts(changes: dict[str, Acase["token_counts"] = [514]changes = {**changes, "cases": cases}with pytest.raises(ValidationError, match="same comparison contract"):- FleetEquivalenceRecord(records=(_fleet_record(), _fleet_record(local_instance_id="b" * 64, **changes)))+ FleetEquivalenceRecord(records=(_fleet_record(), _fleet_record(local_identity=OTHER_IDENTITY, **changes)))def test_fleet_inventory_cannot_mix_probe_inputs_or_token_counts() -> None:@@ -490,7 +504,7 @@ def test_fleet_inventory_cannot_mix_probe_inputs_or_token_counts() -> None:cases = first.model_dump(mode="json")["cases"]cases[0][field] = valuewith pytest.raises(ValidationError, match="same comparison contract"):- FleetEquivalenceRecord(records=(first, _fleet_record(local_instance_id="b" * 64, cases=cases)))+ FleetEquivalenceRecord(records=(first, _fleet_record(local_identity=OTHER_IDENTITY, cases=cases)))def test_fleet_digests_bind_all_measurements_but_ignore_record_case_and_output_order() -> None:@@ -500,7 +514,7 @@ def test_fleet_digests_bind_all_measurements_but_ignore_record_case_and_output_odata["cases"].reverse()reordered = EquivalenceRecord.model_validate_json(json.dumps(data))assert equivalence_record_digest(first) == equivalence_record_digest(reordered)- second = _fleet_record(local_instance_id="b" * 64)+ second = _fleet_record(local_identity=OTHER_IDENTITY)fleet = FleetEquivalenceRecord(records=(first, second))assert fleet.digest == FleetEquivalenceRecord(records=(second, reordered)).digestdata["cases"][0]["measurements"]["dense"]["remote_error"] = 0.1@@ -515,17 +529,23 @@ def test_one_expired_or_future_process_invalidates_fleet_freshness(offset: int)fleet = FleetEquivalenceRecord(records=(_fleet_record(),- _fleet_record(local_instance_id="b" * 64, measured_at=(NOW + timedelta(seconds=offset)).isoformat()),+ _fleet_record(local_identity=OTHER_IDENTITY, measured_at=(NOW + timedelta(seconds=offset)).isoformat()),))assert not fleet.is_fresh(max_age_s=3600, now=NOW)[email protected]("age", [True, 0, 86401, 1.5])[email protected]("age", [True, 0, 604801, 1.5])def test_fleet_age_is_strict_and_bounded(age: Any) -> None:assert not FleetEquivalenceRecord(records=(record(),)).is_fresh(max_age_s=age, now=NOW)+def test_fleet_age_accepts_a_seven_day_window() -> None:+ fleet = FleetEquivalenceRecord(records=(record(),))+ assert fleet.is_fresh(max_age_s=604800, now=NOW + timedelta(days=7))+ assert not fleet.is_fresh(max_age_s=604800, now=NOW + timedelta(days=7, seconds=1))++def test_fleet_cli_preserves_failed_evidence_and_never_overwrites(tmp_path: Path) -> None:cases = record().model_dump(mode="json")["cases"]cases[0]["measurements"]["dense"]["remote_error"] = 0.1@@ -536,7 +556,7 @@ def test_fleet_cli_preserves_failed_evidence_and_never_overwrites(tmp_path: Pathassert fleet_probe.main(args) == 1inventory = read_fleet_equivalence_record(output)assert not inventory.passed- assert inventory.record_digests == {failed.local_instance_id: equivalence_record_digest(failed)}+ assert inventory.record_digests == {failed.local_identity: equivalence_record_digest(failed)}original = output.read_bytes()assert fleet_probe.main(args) == 2assert output.read_bytes() == original@@ -577,7 +597,12 @@ def test_fleet_cli_never_replaces_a_symlink(tmp_path: Path) -> None:@pytest.mark.parametrize(- ("reader", "limit"), [(read_equivalence_record, 512 << 10), (read_fleet_equivalence_record, MAX_FLEET_BYTES)]+ ("reader", "limit"),+ [+ (read_equivalence_record, 512 << 10),+ (read_fleet_equivalence_record, MAX_FLEET_BYTES),+ (read_equivalence_evidence, MAX_FLEET_BYTES),+ ],)def test_evidence_readers_refuse_oversized_files_and_nonblocking_fifos(tmp_path: Path, reader: Any, limit: int) -> None:source = tmp_path / "evidence.json"@@ -588,3 +613,23 @@ def test_evidence_readers_refuse_oversized_files_and_nonblocking_fifos(tmp_path:os.mkfifo(source)with pytest.raises(ValueError, match="regular file"):reader(source)+++def test_evidence_file_holds_one_record_or_a_bundle(tmp_path: Path) -> None:+ single, bundle = tmp_path / "record.json", tmp_path / "bundle.json"+ first, second = _fleet_record(), _fleet_record(local_identity=OTHER_IDENTITY)+ single.write_text(first.model_dump_json())+ bundle.write_text(FleetEquivalenceRecord(records=(first, second)).model_dump_json())+ assert read_equivalence_evidence(single) == (first,)+ assert read_equivalence_evidence(bundle) == (first, second)+ for invalid in ({"version": 2, "records": []}, {"version": 1, "records": [first.model_dump(mode="json")]}, {}):+ single.write_text(json.dumps(invalid))+ with pytest.raises(ValidationError):+ read_equivalence_evidence(single)+++def test_process_bound_records_are_refused() -> None:+ data = record().model_dump(mode="json")+ data.update(version=2, local_instance_id="a" * 64)+ with pytest.raises(ValidationError):+ EquivalenceRecord.model_validate_json(json.dumps(data))diff --git a/packages/sie_server/tests/config/test_hybrid_admission.py b/packages/sie_server/tests/config/test_hybrid_admission.pyindex 3b0ed3cd6..437d20a66 100644--- a/packages/sie_server/tests/config/test_hybrid_admission.py+++ b/packages/sie_server/tests/config/test_hybrid_admission.py@@ -2,6 +2,8 @@import jsonimport os+import subprocess+import sysfrom collections.abc import Iteratorfrom datetime import UTC, datetime, timedeltafrom pathlib import Path@@ -19,11 +21,13 @@ from sie_server.api.encode import router as encode_routerfrom sie_server.api.routing import route_requestfrom sie_server.config import hybrid_admissionfrom sie_server.config.equivalence import (+ EquivalenceRecord,canonical_digest,model_contract_digest,remote_profile_contract_digest,upstream_contract_digest,)+from sie_server.config.fleet_equivalence import FleetEquivalenceRecord, equivalence_record_digestfrom sie_server.config.model import ModelConfigfrom sie_server.config.routing import validate_model_routingfrom sie_server.config.upstreams import EquivalencePolicy, Upstream, install_upstreams@@ -34,6 +38,7 @@ from sie_server.queue_executor import QueueExecutorNOW = datetime(2026, 10, 3, tzinfo=UTC)IDENTITY = "v1:sha256:" + "a" * 64+OTHER_IDENTITY = "v1:sha256:" + "e" * 64@pytest.fixture@@ -75,7 +80,7 @@ def admission(monkeypatch.setattr(hybrid_admission, "local_profile_identity", lambda *args, **kwargs: IDENTITY)install_upstreams({"vendor": upstream})data = {- "version": 2,+ "version": 3,"measured_at": NOW.isoformat(),"upstream_name": "vendor","upstream_model": "vendor/model",@@ -83,10 +88,10 @@ def admission("model_contract_sha256": model_contract_digest(config),"probe_sources_sha256": "c" * 64,"remote_contract_sha256": remote_profile_contract_digest(config, "remote", {"vendor": upstream}),+ "remote_execution_sha256": hybrid_admission.serving_code_digest(),"local_observation_sha256": canonical_digest({"identity": IDENTITY, "revision": config.hf_revision}),"runtime_options_sha256": canonical_digest(dict(config.resolve_profile("default").runtime)),"output_dtype": "float32",- "local_instance_id": hybrid_admission.runtime_instance_id(),"local_identity": IDENTITY,"model": config.sie_id,"remote_profile": "remote",@@ -141,7 +146,7 @@ def test_matching_passing_evidence_is_admitted(admission: tuple) -> None:("remote_contract_sha256", "f" * 64),("local_observation_sha256", "f" * 64),("runtime_options_sha256", "f" * 64),- ("local_instance_id", "f" * 64),+ ("remote_execution_sha256", "f" * 64),],)def test_evidence_cannot_authorize_a_different_contract(admission: tuple, field: str, value: Any) -> None:@@ -200,10 +205,13 @@ def test_nonregular_record_refuses_without_waiting_for_a_writer(admission: tupleassert refusal(config) == "hybrid equivalence record cannot be validated"[email protected]("max_age", [0, -1, True, 86401])[email protected]("max_age", [0, -1, True, 604801])def test_age_policy_is_bounded_and_strict(tmp_path: Path, max_age: Any) -> None:with pytest.raises(ValidationError):EquivalencePolicy(max_age_s=max_age, record_files={"model": str(tmp_path / "record.json")})+ assert (+ EquivalencePolicy(max_age_s=604800, record_files={"model": str(tmp_path / "record.json")}).max_age_s == 604800+ )def test_record_paths_are_absolute_and_bounded() -> None:@@ -294,13 +302,12 @@ async def test_prebridge_rechecks_freshness_while_preserving_local_warmup(admissregistry.load_now.assert_not_awaited()[email protected]("field", ["runtime_options_sha256", "output_dtype", "local_instance_id"])[email protected]("field", ["runtime_options_sha256", "output_dtype", "remote_execution_sha256"])def test_previous_protocol_or_missing_runtime_binding_cannot_admit(admission: tuple, field: str) -> None:config, _, path, data = admission- data["version"] = 1- path.write_text(json.dumps(data))- assert refusal(config) is not None- data["version"] = 2+ for version in (1, 2):+ path.write_text(json.dumps({**data, "version": version, "local_instance_id": "a" * 64}))+ assert refusal(config) == "hybrid equivalence record cannot be validated"data.pop(field)path.write_text(json.dumps(data))assert refusal(config) is not None@@ -341,11 +348,150 @@ def test_quantized_output_does_not_inherit_float32_equivalence(admission: tuple,assert refusal(config) == "hybrid output dtype differs from the measured float32 contract"-def test_worker_restart_or_replacement_requires_new_evidence(admission: tuple, monkeypatch: pytest.MonkeyPatch) -> None:+def test_a_different_execution_identity_is_not_covered(admission: tuple, monkeypatch: pytest.MonkeyPatch) -> None:config, _, _, _ = admissionassert refusal(config) is None- monkeypatch.setattr(hybrid_admission, "runtime_instance_id", lambda: "f" * 64)+ monkeypatch.setattr(hybrid_admission, "local_profile_identity", lambda *args, **kwargs: OTHER_IDENTITY)+ assert refusal(config) == "hybrid equivalence record does not cover this execution identity"+++def test_a_changed_remote_execution_cannot_reuse_evidence(admission: tuple, monkeypatch: pytest.MonkeyPatch) -> None:+ config, _, _, _ = admission+ monkeypatch.setattr(hybrid_admission, "serving_code_digest", lambda: "f" * 64)assert refusal(config) == "hybrid equivalence record differs from the current serving contract"+ monkeypatch.setattr(hybrid_admission, "serving_code_digest", lambda: None)+ assert refusal(config) == "hybrid remote execution cannot be identified"+++def _identity_record(data: dict[str, Any], identity: str, config: ModelConfig, **changes: Any) -> dict[str, Any]:+ local = canonical_digest({"identity": identity, "revision": config.hf_revision})+ return {**data, "local_identity": identity, "local_observation_sha256": local, **changes}+++def _bundle(*records: dict[str, Any]) -> str:+ parsed = tuple(EquivalenceRecord.model_validate_json(json.dumps(record)) for record in records)+ return FleetEquivalenceRecord(records=parsed).model_dump_json()+++def test_bundle_admits_each_measured_identity_and_names_them(admission: tuple, monkeypatch: pytest.MonkeyPatch) -> None:+ config, _, path, data = admission+ other = _identity_record(data, OTHER_IDENTITY, config, measured_at=(NOW - timedelta(seconds=30)).isoformat())+ path.write_text(_bundle(data, other))+ admitted = hybrid_admission.openai_admission(config, now=NOW)+ assert isinstance(admitted, hybrid_admission.NumericalAdmission)+ assert admitted.local_identities == {IDENTITY, OTHER_IDENTITY}+ assert admitted.outputs == {"dense"}+ assert admitted.model_contract_sha256 == model_contract_digest(config)+ assert admitted.expires_at == NOW + timedelta(seconds=30)+ assert refusal(config) is None+ monkeypatch.setattr(hybrid_admission, "local_profile_identity", lambda *args, **kwargs: OTHER_IDENTITY)+ assert refusal(config) is None+++def test_admission_digest_names_exactly_the_admitted_records(admission: tuple) -> None:+ config, _, path, data = admission+ other = _identity_record(data, OTHER_IDENTITY, config)+ path.write_text(_bundle(data))+ single = hybrid_admission.openai_admission(config, now=NOW)+ path.write_text(_bundle(data, other))+ both = hybrid_admission.openai_admission(config, now=NOW)+ failed_cases = json.loads(json.dumps(other["cases"]))+ failed_cases[0]["measurements"]["dense"]["remote_error"] = 0.1+ path.write_text(_bundle(data, {**other, "cases": failed_cases}))+ with_failure = hybrid_admission.openai_admission(config, now=NOW)+ assert isinstance(single, hybrid_admission.NumericalAdmission)+ assert isinstance(both, hybrid_admission.NumericalAdmission)+ assert isinstance(with_failure, hybrid_admission.NumericalAdmission)+ assert single.sha256 != both.sha256+ assert with_failure.sha256 == single.sha256+ assert with_failure.local_identities == {IDENTITY}+ record = EquivalenceRecord.model_validate_json(json.dumps(data))+ assert single.sha256 == canonical_digest(+ {+ "version": 1,+ "kind": "openai",+ "model": config.sie_id,+ "remote_profile": "remote",+ "remote_contract_sha256": data["remote_contract_sha256"],+ "records": [equivalence_record_digest(record)],+ }+ )+++def test_a_failed_measurement_for_this_identity_is_not_covered_by_another(+ admission: tuple, monkeypatch: pytest.MonkeyPatch+) -> None:+ config, _, path, data = admission+ cases = json.loads(json.dumps(data["cases"]))+ cases[0]["measurements"]["dense"]["remote_error"] = 0.1+ path.write_text(_bundle({**data, "cases": cases}, _identity_record(data, OTHER_IDENTITY, config)))+ assert refusal(config) == "hybrid equivalence record does not cover this execution identity"+ monkeypatch.setattr(hybrid_admission, "local_profile_identity", lambda *args, **kwargs: OTHER_IDENTITY)+ assert refusal(config) is None+++_RESTART_PROBE = """+import importlib, json, sys+from pathlib import Path+from sie_server.config.model import ModelConfig+from sie_server.config.routing import validate_model_routing+from sie_server.config.upstreams import install_upstreams, load_upstreams+from sie_server.core.profile_identity import local_profile_identity, runtime_instance_id, serving_code_digest+config = ModelConfig.model_validate_json(Path(sys.argv[1]).read_text())+install_upstreams(load_upstreams(sys.argv[2]))+if sys.argv[3] == "warm":+ importlib.import_module("transformers.models.xlm_roberta.modeling_xlm_roberta")+try:+ validate_model_routing(config, device="cpu")+ admitted = True+except ValueError:+ admitted = False+print(json.dumps({+ "identity": local_profile_identity(config, "default", device="cpu"),+ "code": serving_code_digest(),+ "instance": runtime_instance_id(),+ "admitted": admitted,+}))+"""+++def _run_server_process(config_file: Path, upstreams_file: Path, state: str) -> dict[str, Any]:+ result = subprocess.run( # noqa: S603 - executes the fixed local interpreter+ [sys.executable, "-c", _RESTART_PROBE, str(config_file), str(upstreams_file), state],+ capture_output=True,+ check=True,+ text=True,+ timeout=300,+ )+ return json.loads(result.stdout.strip().splitlines()[-1])+++def test_evidence_measured_in_one_process_admits_a_new_process_with_the_same_identity(+ admission: tuple, tmp_path: Path+) -> None:+ config, upstream, path, data = admission+ config_file, upstreams_file = tmp_path / "model.json", tmp_path / "upstreams.yaml"+ config_file.write_text(config.model_dump_json())+ upstreams_file.write_text(yaml.safe_dump({"upstreams": {"vendor": upstream.model_dump(mode="json")}}))+ path.unlink()+ measured = _run_server_process(config_file, upstreams_file, "warm")+ assert measured["identity"] is not None+ assert not measured["admitted"]+ path.write_text(+ json.dumps(+ _identity_record(+ data,+ measured["identity"],+ config,+ measured_at=datetime.now(UTC).isoformat(),+ remote_execution_sha256=measured["code"],+ )+ )+ )+ restarted = _run_server_process(config_file, upstreams_file, "cold")+ assert restarted["instance"] != measured["instance"]+ assert restarted["identity"] == measured["identity"]+ assert restarted["admitted"]@pytest.mark.parametrize("expired", [False, True])diff --git a/packages/sie_server/tests/core/test_profile_identity.py b/packages/sie_server/tests/core/test_profile_identity.pyindex dcb025ce7..c29af7ee4 100644--- a/packages/sie_server/tests/core/test_profile_identity.py+++ b/packages/sie_server/tests/core/test_profile_identity.py@@ -1,12 +1,19 @@+import json+import subprocess+import sysfrom copy import deepcopy+from pathlib import Pathfrom types import SimpleNamespace+import numpy as npimport pytestfrom sie_server.config.engine import EngineConfigfrom sie_server.config.model import ModelConfigfrom sie_server.core import profile_identityPIN = "a" * 40+NUMPY_LIBRARY = str(Path(np.__file__).resolve().parent.with_name("numpy.libs") / "libscipy_openblas64_.so")+OTHER_LIBRARY = str(Path(np.__file__).resolve().parent.with_name("scipy.libs") / "libscipy_openblas.so")def config(**changes: object) -> ModelConfig:@@ -355,7 +362,7 @@ def test_cuda_observation_failure_does_not_break_model_metadata(assert identity(config(), device="cuda:99") is None-def test_loaded_blas_kernel_and_threads_change_identity(monkeypatch: pytest.MonkeyPatch) -> None:+def test_numpy_blas_kernel_and_threads_change_identity(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(profile_identity.np, "show_config", lambda **kwargs: {"Build Dependencies": {"blas": {"name": "openblas"}}})@@ -366,6 +373,7 @@ def test_loaded_blas_kernel_and_threads_change_identity(monkeypatch: pytest.Monk"num_threads": 1,"architecture": "Haswell","threading_layer": "pthreads",+ "filepath": NUMPY_LIBRARY,}monkeypatch.setattr(profile_identity, "threadpool_info", lambda: [library])first = identity(config())@@ -385,7 +393,7 @@ def test_library_paths_do_not_enter_identity(monkeypatch: pytest.MonkeyPatch) ->"user_api": "blas","internal_api": "openblas","version": "0.3.30",- "filepath": "/private/env/a/libblas.so",+ "filepath": NUMPY_LIBRARY,"architecture": "Haswell","threading_layer": "pthreads","num_threads": 1,@@ -393,11 +401,14 @@ def test_library_paths_do_not_enter_identity(monkeypatch: pytest.MonkeyPatch) ->monkeypatch.setattr(profile_identity, "threadpool_info", lambda: [library])first = identity(config())assert first is not None- library["filepath"] = "/private/env/b/libblas.so"+ library["filepath"] = str(Path(NUMPY_LIBRARY).with_name("libscipy_openblas64_-other.so"))assert identity(config()) == first[email protected]("libraries", [[], [{"user_api": "blas", "internal_api": "openblas", "version": None}]])+ "libraries",+ [[], [{"user_api": "blas", "internal_api": "openblas", "version": None, "filepath": NUMPY_LIBRARY}]],+)def test_unknown_numerical_libraries_refuse_identity(monkeypatch: pytest.MonkeyPatch, libraries: list[dict]) -> None:monkeypatch.setattr(profile_identity, "threadpool_info", lambda: libraries)monkeypatch.setattr(profile_identity.platform, "system", lambda: "Linux")@@ -444,6 +455,7 @@ def test_unobserved_kernel_dispatch_never_claims_identity(monkeypatch: pytest.Mo"threading_layer": "pthreads","architecture": "Haswell","current_backend": "OPENBLAS",+ "filepath": NUMPY_LIBRARY,}monkeypatch.setattr(profile_identity, "threadpool_info", lambda: [library])assert identity(config()) is None@@ -460,9 +472,71 @@ def test_unrelated_blas_cannot_authorize_numpy_backend(monkeypatch: pytest.Monke"num_threads": 1,"threading_layer": "pthreads","architecture": "Haswell",+ "filepath": NUMPY_LIBRARY,}monkeypatch.setattr(profile_identity, "threadpool_info", lambda: [library])monkeypatch.setattr(profile_identity.np, "show_config", lambda **kwargs: {"Build Dependencies": {"blas": {"name": build}}})assert identity(config()) is None+++def test_numpy_build_requires_its_own_blas(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ profile_identity.np, "show_config", lambda **kwargs: {"Build Dependencies": {"blas": {"name": "openblas"}}}+ )+ library = {+ "user_api": "blas",+ "internal_api": "openblas",+ "version": "0.3.30",+ "num_threads": 1,+ "threading_layer": "pthreads",+ "architecture": "Haswell",+ "filepath": OTHER_LIBRARY,+ }+ monkeypatch.setattr(profile_identity, "threadpool_info", lambda: [library])+ assert identity(config()) is None+++def test_libraries_other_packages_load_do_not_change_identity(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ profile_identity.np, "show_config", lambda **kwargs: {"Build Dependencies": {"blas": {"name": "openblas"}}}+ )+ numpy_blas = {+ "user_api": "blas",+ "internal_api": "openblas",+ "version": "0.3.30",+ "num_threads": 1,+ "threading_layer": "pthreads",+ "architecture": "Haswell",+ "filepath": NUMPY_LIBRARY,+ }+ loaded = [numpy_blas]+ monkeypatch.setattr(profile_identity, "threadpool_info", lambda: list(loaded))+ first = identity(config())+ assert first is not None+ loaded.append({**numpy_blas, "architecture": "SkylakeX", "filepath": OTHER_LIBRARY})+ loaded.append({**numpy_blas, "internal_api": "mkl", "filepath": OTHER_LIBRARY})+ loaded.append({"user_api": "openmp", "internal_api": "openmp", "num_threads": 8, "filepath": OTHER_LIBRARY})+ assert identity(config()) == first+++_LOAD_PROBE = """+import importlib, json+from sie_server.config.model import ModelConfig+from sie_server.core.profile_identity import local_profile_identity+config = ModelConfig.model_validate_json(%r)+before = local_profile_identity(config, "default", device="cpu")+importlib.import_module("transformers.models.xlm_roberta.modeling_xlm_roberta")+print(json.dumps([before, local_profile_identity(config, "default", device="cpu")]))+"""+++def test_identity_is_the_same_before_and_after_the_model_stack_is_imported() -> None:+ script = _LOAD_PROBE % config().model_dump_json()+ result = subprocess.run( # noqa: S603 - executes the fixed local interpreter+ [sys.executable, "-c", script], capture_output=True, check=True, text=True, timeout=300+ )+ before, after = json.loads(result.stdout.strip().splitlines()[-1])+ assert before is not None+ assert before == afterdiff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex 187ad4d40..64fbf4072 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -270,6 +270,8 @@ export interface ProfileInfo {identity?: string | null;/** Operator-bound upstream/model/profile contract digest. */remote_contract_sha256?: string | null;+ /** Digest of the serving code that runs this remote profile. */+ remote_execution_sha256?: string | null;runtime_instance_id?: string | null;}diff --git a/tools/ci/fixtures/helm-upstreams.yaml b/tools/ci/fixtures/helm-upstreams.yamlindex 4fb178f8f..4faeb20da 100644--- a/tools/ci/fixtures/helm-upstreams.yaml+++ b/tools/ci/fixtures/helm-upstreams.yaml@@ -129,7 +129,8 @@ definitions:- {accepted: false, upstream: {kind: openai, endpoints: [embeddings], equivalence: {}}}- {accepted: false, upstream: {kind: openai, endpoints: [embeddings], equivalence: []}}- {accepted: false, upstream: {kind: openai, endpoints: [embeddings], equivalence: {max_age_s: 0, record_files: {local/model: /proof.json}}}}- - {accepted: false, upstream: {kind: openai, endpoints: [embeddings], equivalence: {max_age_s: 86401, record_files: {local/model: /proof.json}}}}+ - {accepted: true, upstream: {kind: openai, endpoints: [embeddings], equivalence: {max_age_s: 604800, record_files: {local/model: /proof.json}}}}+ - {accepted: false, upstream: {kind: openai, endpoints: [embeddings], equivalence: {max_age_s: 604801, record_files: {local/model: /proof.json}}}}- {accepted: false, upstream: {kind: openai, endpoints: [embeddings], equivalence: {max_age_s: true, record_files: {local/model: /proof.json}}}}- {accepted: false, upstream: {kind: openai, endpoints: [embeddings], equivalence: {max_age_s: "60", record_files: {local/model: /proof.json}}}}- {accepted: false, upstream: {kind: openai, endpoints: [embeddings], equivalence: {max_age_s: 1.5, record_files: {local/model: /proof.json}}}}diff --git a/tools/remote_equivalence.py b/tools/remote_equivalence.pyindex ab0cea2b0..330f81588 100755--- a/tools/remote_equivalence.py+++ b/tools/remote_equivalence.py@@ -3,8 +3,9 @@Run from the locked public workspace. Credential arguments name environmentvariables; no credential, request body or vector is written to the evidence.-The local model must expose a verified profile identity. Hybrid routing remains-disabled while the explicit remote profile is evaluated.+The local model must expose a verified profile identity. The record covers+every process that reports that identity. Hybrid routing remains disabled while+the explicit remote profile is evaluated."""from __future__ import annotations@@ -256,6 +257,13 @@ def run_probe(or (before.get("profiles") or {}).get(profile, {}).get("remote_contract_sha256") != expected_remote):raise ValueError("serving endpoint/model contract differs from the supplied files")+ remote_execution = (before.get("profiles") or {}).get(profile, {}).get("remote_execution_sha256")+ if (+ not isinstance(remote_execution, str)+ or len(remote_execution) != _HASH_LENGTH+ or any(char not in "0123456789abcdef" for char in remote_execution)+ ):+ raise ValueError("serving remote execution cannot be identified")if not isinstance(identity, str) or not identity.startswith("v1:sha256:"):raise ValueError("local execution cannot be identified; no equivalence record can authorize it")if before.get("revision") != config.hf_revision or before.get("max_sequence_length") != config.max_sequence_length:@@ -327,6 +335,7 @@ def run_probe((after.get("profiles") or {}).get("default", {}).get("runtime_instance_id") != local_instanceor (after.get("profiles") or {}).get("default", {}).get("identity") != identityor (after.get("profiles") or {}).get(profile, {}).get("remote_contract_sha256") != expected_remote+ or (after.get("profiles") or {}).get(profile, {}).get("remote_execution_sha256") != remote_execution):raise ValueError("local execution changed during the probe")return EquivalenceRecord(@@ -339,10 +348,10 @@ def run_probe({"cli": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "library": _execution_code()["sources"]}),remote_contract_sha256=expected_remote,+ remote_execution_sha256=remote_execution,local_observation_sha256=canonical_digest({"identity": identity, "revision": before.get("revision")}),runtime_options_sha256=canonical_digest(dict(config.resolve_profile("default").runtime)),output_dtype="float32",- local_instance_id=local_instance,local_identity=identity,model=config.sie_id,remote_profile=profile,diff --git a/tools/remote_fleet_equivalence.py b/tools/remote_fleet_equivalence.pyindex c9b4878cd..ea0f0131f 100755--- a/tools/remote_fleet_equivalence.py+++ b/tools/remote_fleet_equivalence.py@@ -1,5 +1,8 @@#!/usr/bin/env python3-"""Collect existing direct-worker proofs; this does not enable fleet routing."""+"""Bundle records for one remote profile, one per local execution identity.++The bundle is evidence only. It admits nothing until an upstream policy names it.+"""from __future__ import annotations@@ -20,12 +23,12 @@ from sie_server.config.fleet_equivalence import (def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--record", type=Path, action="append", required=True, help="direct-worker v2 record; repeat")- parser.add_argument("--output", type=Path, required=True, help="new inventory file (never overwritten)")- parser.add_argument("--max-age-s", type=int, default=3600, help="freshness window, 1..86400 seconds")+ parser.add_argument("--record", type=Path, action="append", required=True, help="version 3 record; repeat")+ parser.add_argument("--output", type=Path, required=True, help="new evidence file (never overwritten)")+ parser.add_argument("--max-age-s", type=int, default=3600, help="freshness window, 1..604800 seconds")args = parser.parse_args(argv)if not 1 <= args.max_age_s <= MAX_EVIDENCE_AGE_S or len(args.record) > MAX_FLEET_RECORDS:- parser.error("max age must be 1..86400 seconds and at most 256 records are allowed")+ parser.error("max age must be 1..604800 seconds and at most 256 records are allowed")try:records = []total = 0