Skip to content

armgit / sie

Public Imported from GitHub
0

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

refactor(server): expose the numerical profile snapshot as a library function (#613)

Krisztian Gajdar2f54c01d5e5a
diff --git a/packages/sie_server/src/sie_server/core/numerical_snapshot.py b/packages/sie_server/src/sie_server/core/numerical_snapshot.py
new file mode 100644
index 000000000..a281c57ca
--- /dev/null
+++ b/packages/sie_server/src/sie_server/core/numerical_snapshot.py
@@ -0,0 +1,106 @@
+"""The numerical profile snapshot a server process reports for numerical admission.
+
+For every model config the registry holds, the snapshot reports the local
+execution identity of the ``default`` profile and the model contract. For a
+model whose remote profile this process serves, it also reports that profile's
+contract and its current numerical admission.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import TYPE_CHECKING
+
+from sie_server.config.equivalence import model_contract_digest, remote_profile_contract_digest
+from sie_server.config.hybrid_admission import remote_admission
+from sie_server.config.model import ModelConfig
+from sie_server.config.upstreams import installed_upstreams
+from sie_server.core.profile_identity import local_profile_identity, runtime_instance_id, serving_code_digest
+from sie_server.ipc_types import (
+ NumericalAdmissionObservation,
+ NumericalProfileObservation,
+ NumericalProfileSnapshotResponse,
+)
+
+if TYPE_CHECKING:
+ from sie_server.core.registry import ModelRegistry
+
+logger = logging.getLogger(__name__)
+
+_MAX_NUMERICAL_PROFILES = 1024
+_MAX_ADMITTED_IDENTITIES = 8
+_MAX_NUMERICAL_MODEL_ID_BYTES = 1024
+
+
+async def numerical_profile_snapshot(registry: ModelRegistry) -> NumericalProfileSnapshotResponse:
+ """The registry's numerical profile snapshot, taken under its execution lease.
+
+ A failure answers an incomplete snapshot with no profiles, and the log names
+ only the class of the error.
+ """
+ try:
+ async with registry.execution_lease():
+ return await asyncio.to_thread(_snapshot, registry)
+ except Exception as exc: # noqa: BLE001
+ error_class = (
+ "io" if isinstance(exc, OSError) else "invalid" if isinstance(exc, TypeError | ValueError) else "internal"
+ )
+ logger.debug("Could not collect numerical profile snapshot (error_class=%s)", error_class)
+ return NumericalProfileSnapshotResponse(runtime_instance_id=runtime_instance_id())
+
+
+def _snapshot(registry: ModelRegistry) -> NumericalProfileSnapshotResponse:
+ configs = registry.get_configs_snapshot()
+ complete = len(configs) <= _MAX_NUMERICAL_PROFILES
+ observations = []
+ for name in sorted(configs)[:_MAX_NUMERICAL_PROFILES]:
+ if not name or len(name.encode()) > _MAX_NUMERICAL_MODEL_ID_BYTES:
+ complete = False
+ continue
+ config = configs[name]
+ identity = None
+ contract = None
+ if isinstance(config, ModelConfig):
+ identity = local_profile_identity(
+ config,
+ "default",
+ device=registry.profile_execution_device(name) or "",
+ engine_config=registry.engine_config,
+ )
+ contract = model_contract_digest(config)
+ else:
+ complete = False
+ observation = NumericalProfileObservation(name, identity, contract)
+ if isinstance(config, ModelConfig) and config.synthetic_profile_variant_source is None:
+ _observe_remote_profile(observation, config)
+ observations.append(observation)
+ return NumericalProfileSnapshotResponse(runtime_instance_id(), observations, complete)
+
+
+def _observe_remote_profile(observation: NumericalProfileObservation, config: ModelConfig) -> None:
+ """Report this process's contract and admission for a model's remote profile, if it serves one."""
+ routing = config.routing
+ profile = routing.fallback_profile if routing is not None and routing.fallback_profile else "default"
+ remote_contract = remote_profile_contract_digest(config, profile, installed_upstreams())
+ if remote_contract is None:
+ return
+ observation.remote_contract_sha256 = remote_contract
+ observation.remote_execution_sha256 = serving_code_digest()
+ if config.tasks.encode is None and config.tasks.score is None:
+ return
+ admission = remote_admission(config, wait=False)
+ if (
+ isinstance(admission, str)
+ or not admission.outputs
+ or len(admission.local_identities) > _MAX_ADMITTED_IDENTITIES
+ ):
+ return
+ observation.admission = NumericalAdmissionObservation(
+ sha256=admission.sha256,
+ kind=admission.kind,
+ local_identities=sorted(admission.local_identities),
+ model_contract_sha256=admission.model_contract_sha256,
+ outputs=sorted(admission.outputs),
+ expires_at_unix_ms=int(admission.expires_at.timestamp() * 1000),
+ )
diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.py
index dcad88f87..ac80ff28f 100644
--- a/packages/sie_server/src/sie_server/ipc_server.py
+++ b/packages/sie_server/src/sie_server/ipc_server.py
@@ -19,13 +19,11 @@ import msgspec
from sie_server.adapter_call_loop import handle_run_batch
from sie_server.adapters._generation_base import GenerationUnsupportedFieldError
-from sie_server.config.equivalence import model_contract_digest, remote_profile_contract_digest
from sie_server.config.hybrid_admission import NumericalAdmission, bridged_item_refusal, remote_admission
from sie_server.config.model import ModelConfig
-from sie_server.config.upstreams import installed_upstreams
from sie_server.core.gpu_health import gpu_is_healthy_async
from sie_server.core.grammar_routing import resolve_grammar_serving_model
-from sie_server.core.profile_identity import local_profile_identity, runtime_instance_id, serving_code_digest
+from sie_server.core.numerical_snapshot import numerical_profile_snapshot
from sie_server.core.readiness import is_ready
from sie_server.ipc_types import (
IPC_VERSION,
@@ -56,8 +54,6 @@ from sie_server.ipc_types import (
GenerateEvent,
IpcResponseChunkV1,
ItemOutcome,
- NumericalAdmissionObservation,
- NumericalProfileObservation,
NumericalProfileSnapshotRequest,
NumericalProfileSnapshotResponse,
PingRequest,
@@ -94,9 +90,6 @@ _LEN_BYTES = _LEN_STRUCT.size
# any decoded WorkItem batch we would send in-band — large payloads arrive
# via the payload store, not via IPC.
_MAX_FRAME_BYTES = 32 * 1024 * 1024
-_MAX_NUMERICAL_PROFILES = 1024
-_MAX_ADMITTED_IDENTITIES = 8
-_MAX_NUMERICAL_MODEL_ID_BYTES = 1024
_NUMERICAL_ADMISSION_RETRY_MS = 1000
_UNVERIFIED_ADMISSION = "this method does not verify numerical admissions"
_ADMISSION_CHECK_FAILED = "numerical admission check failed"
@@ -202,34 +195,6 @@ class _IpcGenerateMessage:
await self._sink.send(GenerateEvent(kind="in_progress"))
-def _observe_remote_profile(observation: NumericalProfileObservation, config: ModelConfig) -> None:
- """Report this process's contract and admission for a model's remote profile, if it serves one."""
- routing = config.routing
- profile = routing.fallback_profile if routing is not None and routing.fallback_profile else "default"
- remote_contract = remote_profile_contract_digest(config, profile, installed_upstreams())
- if remote_contract is None:
- return
- observation.remote_contract_sha256 = remote_contract
- observation.remote_execution_sha256 = serving_code_digest()
- if config.tasks.encode is None and config.tasks.score is None:
- return
- admission = remote_admission(config, wait=False)
- if (
- isinstance(admission, str)
- or not admission.outputs
- or len(admission.local_identities) > _MAX_ADMITTED_IDENTITIES
- ):
- return
- observation.admission = NumericalAdmissionObservation(
- sha256=admission.sha256,
- kind=admission.kind,
- local_identities=sorted(admission.local_identities),
- model_contract_sha256=admission.model_contract_sha256,
- outputs=sorted(admission.outputs),
- expires_at_unix_ms=int(admission.expires_at.timestamp() * 1000),
- )
-
-
def _named_admission(item: Any) -> str | None:
"""The numerical admission digest that a batch item names, if any."""
payloads = (item.encode, item.score) if isinstance(item, RunBatchItem) else (item,)
@@ -948,47 +913,7 @@ class IpcServer:
async def _handle_numerical_profile_snapshot(
self, _req: NumericalProfileSnapshotRequest
) -> NumericalProfileSnapshotResponse:
- try:
- async with self._executor.registry.execution_lease():
- return await asyncio.to_thread(self._numerical_profile_snapshot)
- except Exception as exc: # noqa: BLE001
- error_class = (
- "io"
- if isinstance(exc, OSError)
- else "invalid"
- if isinstance(exc, TypeError | ValueError)
- else "internal"
- )
- logger.debug("Could not collect numerical profile snapshot (error_class=%s)", error_class)
- return NumericalProfileSnapshotResponse(runtime_instance_id=runtime_instance_id())
-
- def _numerical_profile_snapshot(self) -> NumericalProfileSnapshotResponse:
- registry = self._executor.registry
- configs = registry.get_configs_snapshot()
- complete = len(configs) <= _MAX_NUMERICAL_PROFILES
- observations = []
- for name in sorted(configs)[:_MAX_NUMERICAL_PROFILES]:
- if not name or len(name.encode()) > _MAX_NUMERICAL_MODEL_ID_BYTES:
- complete = False
- continue
- config = configs[name]
- identity = None
- contract = None
- if isinstance(config, ModelConfig):
- identity = local_profile_identity(
- config,
- "default",
- device=registry.profile_execution_device(name) or "",
- engine_config=registry.engine_config,
- )
- contract = model_contract_digest(config)
- else:
- complete = False
- observation = NumericalProfileObservation(name, identity, contract)
- if isinstance(config, ModelConfig) and config.synthetic_profile_variant_source is None:
- _observe_remote_profile(observation, config)
- observations.append(observation)
- return NumericalProfileSnapshotResponse(runtime_instance_id(), observations, complete)
+ return await numerical_profile_snapshot(self._executor.registry)
def _handle_worker_capabilities(self, _req: WorkerCapabilitiesRequest) -> WorkerCapabilitiesResponse:
generation_models: list[str] = []
diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.py
index 0f6746e95..78f7ee8a9 100644
--- a/packages/sie_server/tests/test_ipc_server.py
+++ b/packages/sie_server/tests/test_ipc_server.py
@@ -19,6 +19,7 @@ import msgspec
import numpy as np
import pytest
import sie_server.api.ws as ws_module
+import sie_server.core.numerical_snapshot as numerical_snapshot_module
import sie_server.ipc_server as ipc_server_module
import yaml
from sie_config.model_registry import ModelRegistry as ConfigModelRegistry
@@ -2748,7 +2749,7 @@ class TestGenerationSidecarIpc:
observed.append((config.sie_id, profile, kwargs))
return "v1:sha256:" + "a" * 64
- monkeypatch.setattr(ipc_server_module, "local_profile_identity", identity)
+ monkeypatch.setattr(numerical_snapshot_module, "local_profile_identity", identity)
config = registry.get_config("Qwen/Qwen3.6-27B")
response = await server._handle_numerical_profile_snapshot(NumericalProfileSnapshotRequest())
assert response.runtime_instance_id == runtime_instance_id()
@@ -2772,11 +2773,22 @@ class TestGenerationSidecarIpc:
]
assert not registry.loaded_model_names
+ @pytest.mark.asyncio
+ async def test_numerical_profile_snapshot_is_the_ipc_answer(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ server, registry, _ = _pinned_execution_server(monkeypatch)
+
+ direct = await numerical_snapshot_module.numerical_profile_snapshot(registry)
+ answered = await server._handle_numerical_profile_snapshot(NumericalProfileSnapshotRequest())
+
+ assert msgspec.to_builtins(direct) == msgspec.to_builtins(answered)
+ assert direct.complete
+ assert [profile.model_id for profile in direct.profiles] == ["Qwen/Qwen3.6-27B"]
+
@pytest.mark.asyncio
async def test_numerical_snapshot_failure_is_incomplete_and_exposes_no_exception(
self, caplog: pytest.LogCaptureFixture
) -> None:
- caplog.set_level("DEBUG", logger="sie_server.ipc_server")
+ caplog.set_level("DEBUG", logger="sie_server.core.numerical_snapshot")
executor, registry = _make_executor()
registry.get_configs_snapshot.side_effect = RuntimeError("private upstream credential")
async with IpcServer(_short_sock_path(), executor, worker_id="w") as server:
@@ -2806,7 +2818,7 @@ class TestGenerationSidecarIpc:
started.set()
assert finish.wait(2)
- monkeypatch.setattr(ipc_server_module, "local_profile_identity", identity)
+ monkeypatch.setattr(numerical_snapshot_module, "local_profile_identity", identity)
snapshot = asyncio.create_task(server._handle_numerical_profile_snapshot(NumericalProfileSnapshotRequest()))
try:
assert await asyncio.to_thread(started.wait, 1)
@@ -2822,7 +2834,7 @@ class TestGenerationSidecarIpc:
current = await server._handle_numerical_profile_snapshot(NumericalProfileSnapshotRequest())
assert current.profiles[0].model_contract_sha256 == model_contract_digest(after)
assert current.profiles[0].model_contract_sha256 != response.profiles[0].model_contract_sha256
- monkeypatch.setattr(ipc_server_module, "_MAX_NUMERICAL_PROFILES", 0)
+ monkeypatch.setattr(numerical_snapshot_module, "_MAX_NUMERICAL_PROFILES", 0)
bounded = await server._handle_numerical_profile_snapshot(NumericalProfileSnapshotRequest())
assert not bounded.complete
assert bounded.profiles == []