Skip to content

armgit / sie

Public Imported from GitHub
0

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

feat(server): measure remote equivalence against local noise (#531)

Krisztian Gajdare5cc5c6504ea
diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.py
index cdbf125ec..ace6b9a39 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -311,6 +311,7 @@ class ProfileInfo(TypedDict, total=False):
is_default: bool
identity: str | None
+ remote_contract_sha256: 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.md
index 912f4ecc6..d4726b89e 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -192,3 +192,52 @@ BGE-M3 cannot identify its effective revision; flash/LoRA and other engines need
additional runtime evidence. An identity is a descriptor, not a numerical
measurement. Hybrid routing remains refused until upstream comparison and
measured equivalence gates are delivered; this field alone does not activate it.
+
+
+## Measuring remote equivalence
+
+An encode/score comparison runs through the Python SDK against one SIE server
+that has both the local default profile and an explicit remote profile. Keep
+hybrid routing disabled while measuring. The server must expose a non-null
+local identity and `profiles.<remote>.remote_contract_sha256`; the latter binds
+its 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.
+
+From the locked public workspace, run:
+
+```bash
+mise exec -- uv run --frozen --project . python tools/remote_equivalence.py \
+ --model-file /path/to/model.yaml \
+ --upstreams-file /path/to/upstreams.yaml \
+ --local-url https://sie.example.com \
+ --api-key-env SIE_PROBE_API_KEY \
+ --remote-profile remote \
+ --output /path/to/new-evidence.json
+```
+
+The API key argument names an environment variable; omit it for a server that
+does not require authentication. The output path must be new. Each case makes
+two local calls with remote serving forbidden, followed by one explicit remote
+call. Cases cover short and long inputs, both sides of the pinned tokenizer's
+truncation boundary, query and document instruction prefixes, and score scale
+when scoring is declared. All declared encode/score outputs must be measured.
+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.
+
+A pass requires matching layouts and finite values whose maximum absolute
+error against both local runs does not exceed the difference measured between
+those local runs. Identical local runs require identical remote values. Matching
+boundary input refusals are recorded; a suite of refusals cannot establish
+numerical equivalence. Endpoint/model contracts and local identity must remain
+unchanged throughout the probe.
+
+Exit status is `0` for passing evidence, `1` for a measured failure, or `2` when
+valid evidence could not be produced. Records contain input hashes, token
+counts, serving identities, contract hashes and measured errors; they contain
+no inputs, vectors or credential values. They carry a measurement timestamp so
+an admission gate can reject stale or future evidence. Remeasure after changes
+to weights, serving settings, software, endpoint or request transforms.
+This delivery produces evidence; hybrid routing still requires its runtime
+admission gate and does not become enabled by writing a record.
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 832647595..fabbcf391 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -2428,6 +2428,17 @@
}
],
"title": "Identity"
+ },
+ "remote_contract_sha256": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Remote Contract Sha256"
}
},
"type": "object",
diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.py
index 17dde6f07..bb1d47004 100644
--- a/packages/sie_server/src/sie_server/api/models.py
+++ b/packages/sie_server/src/sie_server/api/models.py
@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING, Any, Literal
from fastapi import APIRouter, HTTPException, Request, status
from pydantic import BaseModel, Field
+from sie_server.config.equivalence import remote_profile_contract_digest
from sie_server.config.model import ModelConfig, RoutingPolicy, is_remote_adapter_path
from sie_server.config.upstreams import installed_upstreams
from sie_server.core.model_suggestions import suggestion_suffix
@@ -26,6 +27,8 @@ class ProfileInfo(BaseModel):
is_default: bool = False
identity: str | None = None
"""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."""
class ModelLoadError(BaseModel):
@@ -224,6 +227,7 @@ async def list_models(http_request: Request) -> ModelsListResponse:
identity=local_profile_identity(
config, pname, device=registry.device, engine_config=registry.engine_config
),
+ remote_contract_sha256=remote_profile_contract_digest(config, pname, installed_upstreams()),
)
for pname in config.profiles
}
@@ -283,6 +287,7 @@ async def get_model(model: str, http_request: Request) -> ModelInfo:
identity=local_profile_identity(
config, pname, device=registry.device, engine_config=registry.engine_config
),
+ remote_contract_sha256=remote_profile_contract_digest(config, pname, installed_upstreams()),
)
for pname in config.profiles
}
diff --git a/packages/sie_server/src/sie_server/config/equivalence.py b/packages/sie_server/src/sie_server/config/equivalence.py
new file mode 100644
index 000000000..f5b73dc46
--- /dev/null
+++ b/packages/sie_server/src/sie_server/config/equivalence.py
@@ -0,0 +1,198 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from collections.abc import Mapping
+from datetime import UTC, datetime, timedelta
+from typing import Any, Literal
+
+import numpy as np
+from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator
+
+from sie_server.config.model import ModelConfig
+from sie_server.config.upstreams import Upstream, UpstreamKind
+
+ProbeCategory = Literal[
+ "short", "long", "boundary_before", "boundary_after", "query_prefix", "document_prefix", "score_scale"
+]
+ProbeOperation = Literal["encode", "score"]
+ProbeOutput = Literal["dense", "sparse", "multivector", "score"]
+ProbeOutcome = Literal["ok", "invalid_input", "input_too_long", "shape_mismatch"]
+_HASH_PATTERN = r"^[0-9a-f]{64}$"
+_MAX_VALUES = 100_000_000
+_MAX_TOKENS = 100_000
+_CATEGORIES = frozenset({"short", "long", "boundary_before", "boundary_after", "query_prefix", "document_prefix"})
+
+
+def canonical_digest(value: Any) -> str:
+ encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
+ return hashlib.sha256(encoded).hexdigest()
+
+
+def model_contract_digest(config: ModelConfig) -> str:
+ """Bind serving settings, independent of the policy enabled after measurement."""
+ # A probe runs before hybrid admission. Changing only the dispatch policy
+ # must not invalidate the very evidence needed to enable that policy.
+ return canonical_digest(config.model_dump(mode="json", exclude={"routing"}))
+
+
+def upstream_contract_digest(upstream: Upstream) -> str:
+ """Bind endpoint, tenant credential reference and operator request transforms."""
+ return canonical_digest(upstream.model_dump(mode="json", exclude={"rate_cap", "breaker"}))
+
+
+def remote_profile_contract_digest(
+ config: ModelConfig, profile_name: str, upstreams: Mapping[str, Upstream]
+) -> str | None:
+ """Report the server's actual operator-bound endpoint/model contract, never credentials."""
+ kinds = {
+ "sie_server.adapters.remote.sie:SieUpstreamAdapter": UpstreamKind.SIE,
+ "sie_server.adapters.remote.openai:OpenAIUpstreamAdapter": UpstreamKind.OPENAI,
+ }
+ try:
+ profile = config.resolve_profile(profile_name)
+ name = profile.loadtime.get("upstream")
+ upstream = upstreams.get(name) if isinstance(name, str) else None
+ if upstream is None or kinds.get(profile.adapter_path) != upstream.kind:
+ return None
+ return canonical_digest(
+ {
+ "version": 1,
+ "model_contract": model_contract_digest(config),
+ "profile": profile_name,
+ "upstream_contract": upstream_contract_digest(upstream),
+ }
+ )
+ except (TypeError, ValueError, RecursionError):
+ return None
+
+
+class ErrorMeasurement(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ noise_floor: float = Field(ge=0, allow_inf_nan=False)
+ remote_error: float = Field(ge=0, allow_inf_nan=False)
+ values: int = Field(gt=0, le=_MAX_VALUES)
+
+ @property
+ def passed(self) -> bool:
+ return self.remote_error <= self.noise_floor
+
+
+def measure_values(first: np.ndarray, second: np.ndarray, remote: np.ndarray) -> ErrorMeasurement:
+ """Compare absolute error to the actual two-run local noise floor.
+
+ There is no caller-selected tolerance. The remote run must be within the
+ measured floor of both local observations. Layout changes fail separately.
+ """
+ if first.shape != second.shape or first.shape != remote.shape or first.size == 0 or first.size > _MAX_VALUES:
+ raise ValueError("probe output layout differs or exceeds the limit")
+ if any(
+ value.dtype not in (np.dtype("float16"), np.dtype("float32"), np.dtype("float64"))
+ for value in (first, second, remote)
+ ):
+ raise ValueError("probe output must use a supported floating precision")
+ arrays = [np.asarray(value, dtype=np.float64) for value in (first, second, remote)]
+ if any(not np.isfinite(value).all() for value in arrays):
+ raise ValueError("probe output is not finite")
+ a, b, r = arrays
+ return ErrorMeasurement(
+ noise_floor=float(np.max(np.abs(a - b))),
+ remote_error=float(max(np.max(np.abs(a - r)), np.max(np.abs(b - r)))),
+ values=int(a.size),
+ )
+
+
+class ProbeCase(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ operation: ProbeOperation
+ category: ProbeCategory
+ input_sha256: str = Field(pattern=_HASH_PATTERN)
+ token_counts: tuple[int, ...] = Field(min_length=1, max_length=32)
+ outcomes: tuple[ProbeOutcome, ProbeOutcome, ProbeOutcome]
+ measurements: dict[ProbeOutput, ErrorMeasurement] = Field(max_length=4)
+
+ @model_validator(mode="after")
+ def coherent(self) -> ProbeCase:
+ if any(value < 0 or value > _MAX_TOKENS for value in self.token_counts):
+ raise ValueError("probe token count is out of range")
+ if self.outcomes == ("ok", "ok", "ok") and not self.measurements:
+ raise ValueError("successful runs require measured evidence")
+ if self.outcomes != ("ok", "ok", "ok") and self.measurements:
+ raise ValueError("refused or incompatible outputs cannot report measured errors")
+ return self
+
+ @property
+ def passed(self) -> bool:
+ if self.outcomes == ("ok", "ok", "ok"):
+ return all(value.passed for value in self.measurements.values())
+ return len(set(self.outcomes)) == 1 and self.outcomes[0] in ("invalid_input", "input_too_long")
+
+
+class EquivalenceRecord(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ version: Literal[1] = 1
+ measured_at: AwareDatetime
+ upstream_name: str = Field(min_length=1, max_length=128)
+ upstream_model: str = Field(min_length=1, max_length=256)
+ upstream_contract_sha256: str = Field(pattern=_HASH_PATTERN)
+ model_contract_sha256: str = Field(pattern=_HASH_PATTERN)
+ probe_sources_sha256: str = Field(pattern=_HASH_PATTERN)
+ remote_contract_sha256: str = Field(pattern=_HASH_PATTERN)
+ local_observation_sha256: 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"
+ remote_profile: str = Field(min_length=1, max_length=128)
+ context_length: int = Field(gt=1, le=100_000)
+ outputs: frozenset[ProbeOutput] = Field(min_length=1, max_length=4)
+ cases: tuple[ProbeCase, ...] = Field(min_length=6, max_length=16)
+
+ @model_validator(mode="after")
+ def complete_suite(self) -> EquivalenceRecord:
+ if self.local_profile != "default" or self.remote_profile == "default":
+ raise ValueError("probe must compare the local default to an explicit remote profile")
+ if len({(case.operation, case.category) for case in self.cases}) != len(self.cases):
+ raise ValueError("probe cases must not repeat")
+ operations = {"score" if output == "score" else "encode" for output in self.outputs}
+ if {case.operation for case in self.cases} != operations:
+ raise ValueError("probe operations do not cover the declared outputs")
+ for operation in operations:
+ selected = [case for case in self.cases if case.operation == operation]
+ required = _CATEGORIES | ({"score_scale"} if operation == "score" else set())
+ if {case.category for case in selected} != required:
+ raise ValueError("probe suite must cover lengths, truncation and both instruction prefixes")
+ expected = {output for output in self.outputs if (output == "score") == (operation == "score")}
+ for case in selected:
+ if case.outcomes == ("ok", "ok", "ok") and set(case.measurements) != expected:
+ raise ValueError("every successful probe must measure every declared output")
+ if case.category == "boundary_before" and max(case.token_counts) > self.context_length:
+ raise ValueError("before-boundary probe must fit the context")
+ if case.category == "boundary_after" and max(case.token_counts) <= self.context_length:
+ raise ValueError("after-boundary probe must cross the context")
+ return self
+
+ @property
+ def passed(self) -> bool:
+ # A set of matching refusals does not establish numerical equivalence.
+ return all(case.passed for case in self.cases) and all(
+ case.outcomes == ("ok", "ok", "ok")
+ for case in self.cases
+ if case.category in ("short", "long", "score_scale")
+ )
+
+ def is_fresh(self, *, max_age_s: int, now: datetime | None = None) -> bool:
+ observed = now or datetime.now(UTC)
+ if observed.tzinfo is None or observed.utcoffset() is None:
+ return False
+ age = observed - self.measured_at
+ return max_age_s > 0 and timedelta(0) <= age <= timedelta(seconds=max_age_s)
diff --git a/packages/sie_server/tests/api/test_models.py b/packages/sie_server/tests/api/test_models.py
index 2ef03e326..b4716ee52 100644
--- a/packages/sie_server/tests/api/test_models.py
+++ b/packages/sie_server/tests/api/test_models.py
@@ -4,7 +4,9 @@ from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from sie_server.api import models as models_api
from sie_server.api.models import router as models_router
+from sie_server.config.equivalence import remote_profile_contract_digest
from sie_server.config.model import (
EmbeddingDim,
EncodeTask,
@@ -14,6 +16,7 @@ from sie_server.config.model import (
ProfileConfig,
Tasks,
)
+from sie_server.config.upstreams import Upstream
from sie_server.core.load_errors import LoadErrorClass, LoadFailure
from sie_server.core.registry import ModelRegistry
@@ -416,3 +419,37 @@ def test_pinned_builtin_profile_exposes_same_identity_in_list_and_detail(
def test_unpinned_profile_reports_no_identity(client: TestClient) -> None:
assert client.get("/v1/models/model-a").json()["profiles"]["default"]["identity"] is None
+
+
[email protected]("base_url", ["https://first.example/v1", "https://second.example/v1"])
+def test_remote_contract_metadata_binds_the_installed_upstream(
+ client: TestClient, mock_registry: MagicMock, monkeypatch: pytest.MonkeyPatch, base_url: str
+) -> None:
+ config = mock_registry.get_config("model-a")
+ config.profiles["remote"] = ProfileConfig(
+ adapter_path="sie_server.adapters.remote.openai:OpenAIUpstreamAdapter",
+ max_batch_tokens=8192,
+ adapter_options={"loadtime": {"upstream": "vendor", "upstream_model": "vendor/model"}},
+ )
+ upstream = Upstream.model_validate(
+ {
+ "kind": "openai",
+ "base_url": base_url,
+ "endpoints": ["embeddings"],
+ "api_key_secret": "SECRET_ENV_REFERENCE",
+ "rate_cap": {"requests_per_minute": 600, "max_concurrency": 32},
+ }
+ )
+ monkeypatch.setattr(models_api, "installed_upstreams", lambda: {"vendor": upstream})
+ expected = remote_profile_contract_digest(config, "remote", {"vendor": upstream})
+ assert expected is not None
+ detail = client.get("/v1/models/model-a").json()
+ listed = client.get("/v1/models").json()["models"][0]
+ for value in (detail, listed):
+ assert value["profiles"]["remote"]["remote_contract_sha256"] == expected
+ assert value["profiles"]["default"]["remote_contract_sha256"] is None
+ assert 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"})
+ assert remote_profile_contract_digest(config, "remote", {"vendor": different}) != expected
+ assert remote_profile_contract_digest(config, "remote", {}) is None
diff --git a/packages/sie_server/tests/config/test_equivalence.py b/packages/sie_server/tests/config/test_equivalence.py
new file mode 100644
index 000000000..1d7d093ca
--- /dev/null
+++ b/packages/sie_server/tests/config/test_equivalence.py
@@ -0,0 +1,367 @@
+"""Evidence admits only complete, fresh suites bounded by measured local noise."""
+
+import importlib.util
+import json
+import sys
+import threading
+from datetime import UTC, datetime, timedelta
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pytest
+import yaml
+from pydantic import ValidationError
+from sie_sdk._msgpack import packb, unpackb
+from sie_server.config.equivalence import (
+ EquivalenceRecord,
+ ErrorMeasurement,
+ ProbeCase,
+ measure_values,
+ remote_profile_contract_digest,
+)
+from sie_server.config.model import ModelConfig
+from sie_server.config.upstreams import load_upstreams
+
+NOW = datetime(2026, 10, 3, tzinfo=UTC)
+_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
+assert _PROBE_SPEC.loader is not None
+probe = importlib.util.module_from_spec(_PROBE_SPEC)
+sys.modules[_PROBE_SPEC.name] = probe
+_PROBE_SPEC.loader.exec_module(probe)
+
+
+def record(*, outputs: frozenset[str] = frozenset({"dense"})) -> EquivalenceRecord:
+ cases = []
+ for operation in ("encode", "score"):
+ selected = {value for value in outputs if (value == "score") == (operation == "score")}
+ if not selected:
+ continue
+ categories = ["short", "long", "boundary_before", "boundary_after", "query_prefix", "document_prefix"]
+ if operation == "score":
+ categories.append("score_scale")
+ for category in categories:
+ cases.append(
+ {
+ "operation": operation,
+ "category": category,
+ "input_sha256": "a" * 64,
+ "token_counts": [513 if category == "boundary_after" else 512],
+ "outcomes": ["ok"] * 3,
+ "measurements": {
+ output: {"noise_floor": 0.0, "remote_error": 0.0, "values": 384} for output in selected
+ },
+ }
+ )
+ return EquivalenceRecord.model_validate_json(
+ json.dumps(
+ {
+ "version": 1,
+ "measured_at": NOW.isoformat(),
+ "upstream_name": "upstream",
+ "upstream_model": "vendor/model",
+ "upstream_contract_sha256": "b" * 64,
+ "model_contract_sha256": "c" * 64,
+ "probe_sources_sha256": "d" * 64,
+ "remote_contract_sha256": "d" * 64,
+ "local_observation_sha256": "e" * 64,
+ "local_identity": "v1:sha256:" + "f" * 64,
+ "model": "local/model",
+ "remote_profile": "remote",
+ "context_length": 512,
+ "outputs": list(outputs),
+ "cases": cases,
+ }
+ )
+ )
+
+
+def test_noise_floor_is_measured_and_remote_must_match_both_local_runs() -> None:
+ result = measure_values(np.array([1.0, 2.0]), np.array([1.25, 2.0]), np.array([1.125, 2.0]))
+ assert result.noise_floor == 0.25
+ assert result.remote_error == 0.125
+ assert result.passed
+ assert not measure_values(np.array([1.0]), np.array([1.25]), np.array([1.5])).passed
+
+
+def test_deterministic_local_runs_require_identical_remote_values() -> None:
+ assert measure_values(np.array([1.0]), np.array([1.0]), np.array([1.0])).passed
+ assert not measure_values(np.array([1.0]), np.array([1.0]), np.array([1.000001])).passed
+
+
[email protected]("remote", [np.array([np.nan]), np.array([np.inf]), np.array([1 + 1j]), np.array(["1"])])
+def test_invalid_output_cannot_be_measured(remote: np.ndarray) -> None:
+ with pytest.raises(ValueError, match="probe output"):
+ measure_values(np.array([1.0]), np.array([1.0]), remote)
+
+
+def test_output_shape_changes_and_empty_values_are_refused() -> None:
+ for remote in (np.array([[1.0]]), np.array([])):
+ with pytest.raises(ValueError, match="probe output layout"):
+ measure_values(np.array([1.0]), np.array([1.0]), remote)
+
+
[email protected]("value", [-1.0, float("inf"), float("nan")])
+def test_record_cannot_assert_nonfinite_or_negative_tolerances(value: float) -> None:
+ with pytest.raises(ValidationError):
+ ErrorMeasurement(noise_floor=value, remote_error=0.0, values=1)
+
+
+def test_all_declared_outputs_and_operations_are_measured() -> None:
+ assert record(outputs=frozenset({"dense", "sparse", "multivector", "score"})).passed
+
+
+def test_missing_or_duplicate_categories_cannot_make_a_complete_suite() -> None:
+ data = record().model_dump(mode="json")
+ data["cases"][-1] = data["cases"][0]
+ with pytest.raises(ValidationError):
+ EquivalenceRecord.model_validate_json(json.dumps(data))
+
+
+def test_success_requires_every_declared_output() -> None:
+ data = record(outputs=frozenset({"dense", "sparse"})).model_dump(mode="json")
+ del data["cases"][0]["measurements"]["sparse"]
+ with pytest.raises(ValidationError):
+ EquivalenceRecord.model_validate_json(json.dumps(data))
+
+
+def test_matching_refusals_are_not_a_numerical_proof() -> None:
+ data = record().model_dump(mode="json")
+ for case in data["cases"]:
+ case["outcomes"] = ["invalid_input"] * 3
+ case["measurements"] = {}
+ assert not EquivalenceRecord.model_validate_json(json.dumps(data)).passed
+
+
+def test_matching_boundary_refusal_can_preserve_truncation_contract() -> None:
+ data = record().model_dump(mode="json")
+ after = next(case for case in data["cases"] if case["category"] == "boundary_after")
+ after["outcomes"] = ["input_too_long"] * 3
+ after["measurements"] = {}
+ assert EquivalenceRecord.model_validate_json(json.dumps(data)).passed
+ after["outcomes"][2] = "invalid_input"
+ assert not EquivalenceRecord.model_validate_json(json.dumps(data)).passed
+
+
+def test_boundary_labels_require_observed_token_counts() -> None:
+ data = record().model_dump(mode="json")
+ data["cases"][3]["token_counts"] = [512]
+ with pytest.raises(ValidationError):
+ EquivalenceRecord.model_validate_json(json.dumps(data))
+
+
+def test_freshness_rejects_expired_future_naive_and_disabled_records() -> None:
+ evidence = record()
+ assert evidence.is_fresh(max_age_s=60, now=NOW + timedelta(seconds=60))
+ assert not evidence.is_fresh(max_age_s=60, now=NOW + timedelta(seconds=61))
+ assert not evidence.is_fresh(max_age_s=60, now=NOW - timedelta(seconds=1))
+ assert not evidence.is_fresh(max_age_s=60, now=NOW.replace(tzinfo=None))
+ assert not evidence.is_fresh(max_age_s=0, now=NOW)
+
+
+def test_rejected_or_malformed_outputs_cannot_claim_measurements() -> None:
+ with pytest.raises(ValidationError):
+ ProbeCase(
+ operation="encode",
+ category="short",
+ input_sha256="a" * 64,
+ token_counts=(5,),
+ outcomes=("shape_mismatch",) * 3,
+ measurements={"dense": ErrorMeasurement(noise_floor=0.0, remote_error=0.0, values=384)},
+ )
+
+
+class _Tokenizer:
+ def encode(self, text: str, *, add_special_tokens: bool) -> list[int]:
+ return [1] * (len(text.split()) + (2 if add_special_tokens else 0))
+
+
[email protected](("remote_offset", "contract_mismatch"), [(0.0, False), (0.01, False), (0.0, True)])
+def test_full_cli_runs_real_sdk_transport_and_only_writes_evidence(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, remote_offset: float, contract_mismatch: bool
+) -> None:
+ requests: list[tuple[dict[str, Any], bool]] = []
+ remote_contract: str | None = None
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self) -> None:
+ self.reply(
+ json.dumps(
+ {
+ "name": "local/model",
+ "revision": "a" * 40,
+ "max_sequence_length": 32,
+ "profiles": {
+ "default": {"identity": "v1:sha256:" + "f" * 64},
+ "remote": {"remote_contract_sha256": remote_contract},
+ },
+ }
+ ).encode(),
+ "application/json",
+ )
+
+ def do_POST(self) -> None:
+ body = unpackb(self.rfile.read(int(self.headers["Content-Length"])), numeric_arrays=False)
+ forbid = self.headers.get("X-SIE-Remote") == "forbid"
+ requests.append((body, forbid))
+ offset = 0.0 if forbid else remote_offset
+ rows = [
+ {"id": item["id"], "dense": {"dims": 2, "values": np.asarray([1.0 + offset, 2.0], dtype=np.float32)}}
+ for item in body["items"]
+ ]
+ self.reply(packb({"model": "local/model", "items": rows}), "application/msgpack", remote=not forbid)
+
+ def reply(self, body: bytes, content_type: str, *, remote: bool = False) -> None:
+ self.send_response(200)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("X-SIE-Served-By", "remote" if remote else "local")
+ if remote:
+ self.send_header("X-SIE-Upstream", "upstream")
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, format: str, *args: Any) -> None:
+ return None
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server.daemon_threads = True
+ thread = threading.Thread(target=server.serve_forever, args=(0.01,), daemon=True)
+ thread.start()
+ config_file = tmp_path / "model.yaml"
+ config_file.write_text(
+ """sie_id: local/model
+hf_id: weights/model
+hf_revision: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+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
+ remote:
+ adapter_path: sie_server.adapters.remote.openai:OpenAIUpstreamAdapter
+ max_batch_tokens: 8192
+ adapter_options:
+ loadtime: {upstream: upstream, upstream_model: vendor/model}
+"""
+ )
+ upstream_file = tmp_path / "upstreams.yaml"
+ upstream_file.write_text(
+ """upstreams:
+ upstream:
+ kind: openai
+ base_url: https://vendor.example/v1
+ endpoints: [embeddings]
+ rate_cap: {requests_per_minute: 600, max_concurrency: 32}
+"""
+ )
+ monkeypatch.setattr(probe, "load_tokenizer", lambda *args, **kwargs: _Tokenizer())
+ monkeypatch.setattr(probe, "_execution_code", lambda: {"sources": "e" * 64})
+ config = ModelConfig.model_validate(yaml.safe_load(config_file.read_bytes()))
+ remote_contract = remote_profile_contract_digest(config, "remote", load_upstreams(upstream_file))
+ if contract_mismatch:
+ remote_contract = "0" * 64
+ output = tmp_path / "evidence.json"
+ try:
+ result = probe.main(
+ [
+ "--model-file",
+ str(config_file),
+ "--upstreams-file",
+ str(upstream_file),
+ "--local-url",
+ f"http://127.0.0.1:{server.server_port}",
+ "--output",
+ str(output),
+ ]
+ )
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+ if contract_mismatch:
+ assert result == 2
+ assert not requests
+ assert not output.exists()
+ return
+ assert result == (0 if remote_offset == 0 else 1)
+ evidence = EquivalenceRecord.model_validate_json(output.read_bytes())
+ assert evidence.passed == (remote_offset == 0)
+ assert len(requests) == 18
+ assert [forbid for _, forbid in requests] == [True, True, False] * 6
+ assert [body["params"]["options"]["profile"] for body, _ in requests] == ["default", "default", "remote"] * 6
+ serialized = output.read_text()
+ assert "retrieval " not in serialized
+ assert "Represent this text" not in serialized
+ assert 'values"' in serialized # Measurement count, never vector contents.
+ assert "1.01" not in serialized
+
+
+def test_sparse_layout_and_score_order_are_compared_by_identity() -> None:
+ sparse = probe._values(
+ [
+ [{"sparse": {"indices": [1, 2], "values": [0.1, 0.2]}}],
+ [{"sparse": {"indices": [2, 1], "values": [0.2, 0.1]}}],
+ [{"sparse": {"indices": [1, 3], "values": [0.1, 0.2]}}],
+ ],
+ "sparse",
+ dimension=4,
+ )
+ assert not measure_values(*sparse).passed
+ scores = probe._values(
+ [
+ {"scores": [{"item_id": "b", "score": 0.2}, {"item_id": "a", "score": 0.1}]},
+ {"scores": [{"item_id": "a", "score": 0.1}, {"item_id": "b", "score": 0.2}]},
+ {"scores": [{"item_id": "b", "score": 0.2}, {"item_id": "a", "score": 0.1}]},
+ ],
+ "score",
+ )
+ assert measure_values(*scores).passed
+
+
[email protected]("index", [-1, 1.5, True, "not-an-index", 4])
+def test_sparse_indices_cannot_claim_invalid_vocabulary_positions(index: Any) -> None:
+ values = [[{"sparse": {"indices": [index], "values": [0.1]}}]] * 3
+ with pytest.raises(ValueError, match="sparse output"):
+ probe._values(values, "sparse", dimension=4)
+
+
+def test_consistently_wrong_dimensions_are_not_equivalence() -> None:
+ values = [[{"dense": np.array([1.0])}]] * 3
+ with pytest.raises(ValueError, match="declared dimensions"):
+ probe._values(values, "dense", dimension=4)
+
+
+def test_integer_conversion_cannot_hide_numerical_differences() -> None:
+ with pytest.raises(ValueError, match="floating precision"):
+ measure_values(np.array([2**53]), np.array([2**53]), np.array([2**53 + 1]))
+
+
[email protected]("shape", [(1, 1), (0, 4), (33, 4), (4,)])
+def test_multivector_dimensions_and_token_bounds_are_required(shape: tuple[int, ...]) -> None:
+ values = [[{"multivector": np.ones(shape)}]] * 3
+ with pytest.raises(ValueError, match="declared dimensions"):
+ probe._values(values, "multivector", dimension=4, context_length=32)
+
+
[email protected]("value", [2**53 + 1, True, "1.0", float("nan")])
+def test_sparse_padding_cannot_coerce_invalid_values_into_equivalence(value: Any) -> None:
+ values = [
+ [{"sparse": {"indices": [0], "values": [float(2**53)]}}],
+ [{"sparse": {"indices": [0, 1], "values": [float(2**53), 0.0]}}],
+ [{"sparse": {"indices": [0, 2], "values": [value, 0.0]}}],
+ ]
+ with pytest.raises(ValueError, match="finite floating"):
+ probe._values(values, "sparse", dimension=4)
+
+
+def test_mixed_integer_scores_cannot_hide_conversion_error() -> None:
+ values = [{"scores": [{"item_id": "a", "score": 2**53 + 1}, {"item_id": "b", "score": 0.0}]}] * 3
+ with pytest.raises(ValueError, match="floating values"):
+ probe._values(values, "score")
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index fc7549bca..72a0d393a 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -266,6 +266,8 @@ export interface ProfileInfo {
is_default?: boolean;
/** Immutable local-profile digest; absent/null when it cannot be identified. */
identity?: string | null;
+ /** Operator-bound upstream/model/profile contract digest. */
+ remote_contract_sha256?: string | null;
}
/**
diff --git a/tools/remote_equivalence.py b/tools/remote_equivalence.py
new file mode 100755
index 000000000..550ce3d57
--- /dev/null
+++ b/tools/remote_equivalence.py
@@ -0,0 +1,347 @@
+#!/usr/bin/env python3
+"""Measure a configured remote profile against two local SIE runs.
+
+Run from the locked public workspace. Credential arguments name environment
+variables; 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.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import os
+import sys
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from http import HTTPStatus
+from numbers import Integral
+from pathlib import Path
+from typing import Any, cast
+
+import numpy as np
+import yaml
+from sie_sdk import SIEClient
+from sie_sdk.client.errors import RequestError, SIEError
+from sie_sdk.types import Item
+from sie_server.config.equivalence import (
+ EquivalenceRecord,
+ ProbeCase,
+ canonical_digest,
+ measure_values,
+ model_contract_digest,
+ remote_profile_contract_digest,
+ upstream_contract_digest,
+)
+from sie_server.config.model import ModelConfig, is_immutable_revision, is_remote_adapter_path
+from sie_server.config.upstreams import load_upstreams, validate_upstream_url
+from sie_server.core.profile_identity import _execution_code
+from sie_server.core.tokenizer import load_tokenizer
+
+_MAX_CONFIG_BYTES = 1 << 20
+_MAX_CONTEXT = 32_768
+_MIN_CONTEXT = 2
+_MATRIX_NDIM = 2
+_PREFIX = "Represent this text for retrieval:"
+_SCORE_QUERY = "relevant documents for search"
+
+
+@dataclass(frozen=True)
+class _Case:
+ category: str
+ texts: tuple[str, ...]
+ token_counts: tuple[int, ...]
+ instruction: str | None = None
+ is_query: bool = False
+
+
+def _cases(tokenizer: Any, context: int) -> list[_Case]:
+ def count(text: str) -> int:
+ return len(tokenizer.encode(text, add_special_tokens=True))
+
+ # Binary-search a deterministic synthetic text. Use the actual pinned
+ # tokenizer so the suite crosses the model's real truncation boundary.
+ def boundary_text(repetitions: int) -> str:
+ return "HEAD astronomy. " + "retrieval medicine law programming history finance " * repetitions + "TAIL ocean."
+
+ low, high = 1, context * 4
+ if count(boundary_text(low)) > context or count(boundary_text(high)) <= context:
+ raise ValueError("could not construct a truncation-boundary probe")
+ while low + 1 < high:
+ middle = (low + high) // 2
+ if count(boundary_text(middle)) <= context:
+ low = middle
+ else:
+ high = middle
+ before, after = boundary_text(low), boundary_text(high)
+ long_text = boundary_text(max(1, low // 2))
+ short = "How does a search engine find relevant documents?"
+ requests = [
+ ("short", (short,), None, False),
+ ("long", (long_text,), None, False),
+ ("boundary_before", (before,), None, False),
+ ("boundary_after", (after,), None, False),
+ ("query_prefix", (short,), _PREFIX, True),
+ ("document_prefix", (f"{_PREFIX} {short}",), None, False),
+ (
+ "score_scale",
+ (
+ "Search retrieves documents related to a query.",
+ "The oven temperature is two hundred degrees.",
+ "Documents are ranked by relevance to a search query.",
+ "A search engine finds relevant documents.",
+ ),
+ None,
+ False,
+ ),
+ ]
+ result = [
+ _Case(category, texts, tuple(count(text) for text in texts), instruction, is_query)
+ for category, texts, instruction, is_query in requests
+ ]
+ if result[2].token_counts[0] > context or result[3].token_counts[0] <= context:
+ raise ValueError("tokenizer cannot establish the truncation boundary")
+ return result
+
+
+def _sparse_values(results: list[Any], dimension: int) -> list[np.ndarray]:
+ maps: list[dict[int, float]] = []
+ for result in results:
+ sparse = result[0]["sparse"]
+ indices, values = sparse["indices"], sparse["values"]
+ if any(not isinstance(value, float | np.floating) or not np.isfinite(value) for value in values):
+ raise ValueError("sparse output must contain finite floating values")
+ if (
+ np.asarray(indices).ndim != 1
+ or np.asarray(values).ndim != 1
+ or len(indices) != len(values)
+ or len(set(indices)) != len(indices)
+ or any(
+ not isinstance(index, Integral) or isinstance(index, bool | np.bool_) or not 0 <= index < dimension
+ for index in indices
+ )
+ ):
+ raise ValueError("sparse output is malformed")
+ maps.append(dict(zip(indices, values, strict=True)))
+ keys = sorted(set().union(*(mapping.keys() for mapping in maps)))
+ # Empty sparse vectors still carry a measurable zero-valued observation.
+ return [np.asarray([mapping.get(key, 0.0) for key in keys] or [0.0]) for mapping in maps]
+
+
+def _values(
+ results: list[Any], output: str, *, dimension: int | None = None, context_length: int = 0
+) -> list[np.ndarray]:
+ if output == "sparse":
+ if dimension is None:
+ raise ValueError("sparse dimension is unidentified")
+ return _sparse_values(results, dimension)
+ if output == "score":
+ observations = []
+ ids: list[str] | None = None
+ for result in results:
+ scores = sorted(result["scores"], key=lambda value: value["item_id"])
+ observed_ids = [value["item_id"] for value in scores]
+ if len(set(observed_ids)) != len(observed_ids) or (ids is not None and observed_ids != ids):
+ raise ValueError("score output identities differ")
+ ids = observed_ids
+ if any(not isinstance(value["score"], float | np.floating) for value in scores):
+ raise ValueError("score output must contain floating values")
+ observations.append(np.asarray([value["score"] for value in scores]))
+ return observations
+ arrays = [np.asarray(result[0][output]) for result in results]
+ if dimension is None or any(
+ (
+ array.shape != (dimension,)
+ if output == "dense"
+ else array.ndim != _MATRIX_NDIM or array.shape[1] != dimension or not 0 < array.shape[0] <= context_length
+ )
+ for array in arrays
+ ):
+ raise ValueError("probe output does not match the declared dimensions")
+ return arrays
+
+
+def _request(
+ client: SIEClient,
+ config: ModelConfig,
+ case: _Case,
+ operation: str,
+ outputs: set[str],
+ *,
+ profile: str,
+ upstream: str,
+) -> tuple[str, Any]:
+ common: dict[str, Any] = {
+ "options": {"profile": profile},
+ "instruction": case.instruction,
+ "wait_for_capacity": False,
+ "provision_timeout_s": 60.0,
+ "max_oom_retries": 0,
+ }
+ try:
+ items: list[Item] = [{"id": f"probe-{index}", "text": text} for index, text in enumerate(case.texts)]
+ if operation == "score":
+ result = client.score(config.sie_id, {"text": _SCORE_QUERY}, items, **common)
+ if {value["item_id"] for value in result["scores"]} != {value["id"] for value in items} or len(
+ result["scores"]
+ ) != len(items):
+ raise ValueError("probe score items are missing or repeated")
+ rows = [result]
+ else:
+ result = client.encode(
+ config.sie_id, items, output_types=cast("Any", sorted(outputs)), is_query=case.is_query, **common
+ )
+ rows = cast("list[Any]", result)
+ if not isinstance(rows, list) or len(rows) != (1 if operation == "score" else len(items)):
+ raise ValueError("probe result count differs")
+ for row in rows:
+ evidence = row.get("request") or {}
+ expected = "local" if profile == "default" else "remote"
+ if evidence.get("served_by") != expected or (expected == "remote" and evidence.get("upstream") != upstream):
+ raise ValueError("probe serving provenance is missing or differs")
+ return "ok", result
+ except RequestError as error:
+ code = (error.code or "").upper()
+ if error.status_code == HTTPStatus.BAD_REQUEST and code in ("INVALID_INPUT", "INPUT_TOO_LONG"):
+ return "input_too_long" if code == "INPUT_TOO_LONG" else "invalid_input", None
+ raise ValueError("probe request failed without a comparable input refusal") from None
+
+
+def run_probe(
+ config: ModelConfig, upstreams: Any, local: SIEClient, remote: SIEClient, profile: str
+) -> EquivalenceRecord:
+ if config.weights_path is not None or not is_immutable_revision(config.hf_revision) or not config.hf_id:
+ raise ValueError("probe requires immutable local Hub weights")
+ if config.max_sequence_length is None or not _MIN_CONTEXT <= config.max_sequence_length <= _MAX_CONTEXT:
+ raise ValueError("probe context is unsupported")
+ 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")
+ upstream_name, upstream_model = resolved.loadtime["upstream"], resolved.loadtime["upstream_model"]
+ upstream = upstreams[upstream_name]
+ before = local.get_model(config.sie_id)
+ identity = (before.get("profiles") or {}).get("default", {}).get("identity")
+ expected_remote = remote_profile_contract_digest(config, profile, upstreams)
+ if (
+ expected_remote is None
+ or (before.get("profiles") or {}).get(profile, {}).get("remote_contract_sha256") != expected_remote
+ ):
+ raise ValueError("serving endpoint/model contract differs from the supplied files")
+ 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:
+ raise ValueError("local model metadata differs from the supplied model contract")
+ outputs = set(config.outputs) & {"dense", "sparse", "multivector", "score"}
+ if not outputs:
+ raise ValueError("probe requires encode or score outputs")
+ tokenizer = load_tokenizer(config.hf_id, revision=config.hf_revision, trust_remote_code=False)
+ cases = []
+ for operation in ("encode", "score"):
+ selected_outputs = {output for output in outputs if (output == "score") == (operation == "score")}
+ if not selected_outputs:
+ continue
+ for case in _cases(tokenizer, config.max_sequence_length):
+ if operation == "encode" and case.category == "score_scale":
+ continue
+ observations = [
+ _request(client, config, case, operation, selected_outputs, profile=selected, upstream=upstream_name)
+ for client, selected in ((local, "default"), (local, "default"), (remote, profile))
+ ]
+ outcomes = tuple(observation[0] for observation in observations)
+ measurements = {}
+ if outcomes == ("ok", "ok", "ok"):
+ results = [observation[1] for observation in observations]
+ try:
+ measurements = {
+ output: measure_values(
+ *_values(
+ results,
+ output,
+ dimension=getattr(getattr(config.tasks.encode, output, None), "dim", None),
+ context_length=config.max_sequence_length,
+ )
+ )
+ for output in sorted(selected_outputs)
+ }
+ except (KeyError, TypeError, ValueError):
+ outcomes = ("shape_mismatch",) * 3
+ cases.append(
+ ProbeCase(
+ operation=cast("Any", operation),
+ category=cast("Any", case.category),
+ input_sha256=canonical_digest(
+ {
+ "texts": case.texts,
+ "instruction": case.instruction,
+ "is_query": case.is_query,
+ "query": _SCORE_QUERY if operation == "score" else None,
+ }
+ ),
+ token_counts=case.token_counts,
+ outcomes=cast("Any", outcomes),
+ measurements=cast("Any", measurements),
+ )
+ )
+ after = local.get_model(config.sie_id)
+ if (after.get("profiles") or {}).get("default", {}).get("identity") != identity or (
+ after.get("profiles") or {}
+ ).get(profile, {}).get("remote_contract_sha256") != expected_remote:
+ raise ValueError("local execution changed during the probe")
+ return EquivalenceRecord(
+ measured_at=datetime.now(UTC),
+ upstream_name=upstream_name,
+ upstream_model=upstream_model,
+ upstream_contract_sha256=upstream_contract_digest(upstream),
+ model_contract_sha256=model_contract_digest(config),
+ probe_sources_sha256=canonical_digest(
+ {"cli": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "library": _execution_code()["sources"]}
+ ),
+ remote_contract_sha256=expected_remote,
+ local_observation_sha256=canonical_digest({"identity": identity, "revision": before.get("revision")}),
+ local_identity=identity,
+ model=config.sie_id,
+ remote_profile=profile,
+ context_length=config.max_sequence_length,
+ outputs=cast("Any", frozenset(outputs)),
+ cases=tuple(cases),
+ )
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model-file", type=Path, required=True)
+ parser.add_argument("--upstreams-file", type=Path, required=True)
+ parser.add_argument("--local-url", required=True)
+ parser.add_argument("--api-key-env")
+ parser.add_argument("--remote-profile", default="remote")
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args(argv)
+ try:
+ if args.output.exists():
+ raise ValueError("evidence output already exists")
+ base_url = validate_upstream_url(args.local_url)
+ data = args.model_file.read_bytes()
+ if len(data) > _MAX_CONFIG_BYTES:
+ raise ValueError("model contract exceeds the byte limit")
+ config = ModelConfig.model_validate(yaml.safe_load(data))
+ upstreams = load_upstreams(args.upstreams_file)
+ key = os.environ[args.api_key_env] if args.api_key_env else None
+ with (
+ SIEClient(base_url, api_key=key, remote="forbid", timeout_s=60) as local,
+ SIEClient(base_url, api_key=key, timeout_s=60) as remote,
+ ):
+ record = run_probe(config, upstreams, local, remote, args.remote_profile)
+ # Refuse to clobber existing evidence; a scheduled run chooses a new path.
+ with args.output.open("x", encoding="utf-8") as output:
+ output.write(record.model_dump_json(indent=2) + "\n")
+ print("PASS" if record.passed else "FAIL")
+ return 0 if record.passed else 1
+ except (OSError, ValueError, KeyError, TypeError, RuntimeError, ImportError, SIEError, yaml.YAMLError):
+ # SDK errors can contain URLs/provider text. Keep failure output fixed.
+ print("Probe could not produce valid equivalence evidence.", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())