From 8abd4acbcb79af7d56e000537f3fcbdd4b07fc11 Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Wed, 4 Nov 2026 21:55:33 +0100 Subject: [PATCH 01/16] feat(placement): add versioned planner input and plan schemas Add sie-placement, a standard-library workspace package with strict, versioned documents for a measured-only placement planner: - service levels per served identity (comeAliveP95S, warmP99Ms or the ttftP99Ms and itlP99Ms pair for generation, queueWaitP99Ms), with optional named tiers that identities inherit and override - receipt v1, keyed by machine profile and realized GPU product, with container shape, concurrency, request shape, throughput, latency percentiles and a source reference - boot evidence v1 for cold boots, snapshot restores and resident loads - price list v1 with per-profile accelerator, core and memory rates and a region multiplier per placement - hourly demand per identity and operation over a UTC window - the plan: lanes with cell, shape, concurrency, ceiling and envelope (floorMin, floorMax and optional buffer and scale-down window ranges), and each identity's lane and warmth Every type parses from JSON-compatible dicts with path-qualified errors and serializes back without loss. The package joins the workspace, pytest, lint, typecheck and coverage lists. It stays out of the PyPI distribution list and the release contract. --- .coveragerc | 1 + CONTRIBUTING.md | 1 + packages/sie_placement/README.md | 79 ++ packages/sie_placement/pyproject.toml | 19 + .../src/sie_placement/__init__.py | 0 .../sie_placement/src/sie_placement/schema.py | 1054 +++++++++++++++++ .../tests/fixtures/boot-evidence.json | 21 + .../sie_placement/tests/fixtures/demand.json | 34 + .../sie_placement/tests/fixtures/plan.json | 68 ++ .../tests/fixtures/price-list.json | 31 + .../tests/fixtures/receipt-encode.json | 32 + .../tests/fixtures/receipt-generate.json | 37 + .../tests/fixtures/service-levels.json | 40 + packages/sie_placement/tests/test_schema.py | 528 +++++++++ pyproject.toml | 3 + tools/mise_tasks/lint.bash | 1 + tools/mise_tasks/typecheck.bash | 1 + uv.lock | 16 + 18 files changed, 1966 insertions(+) create mode 100644 packages/sie_placement/README.md create mode 100644 packages/sie_placement/pyproject.toml create mode 100644 packages/sie_placement/src/sie_placement/__init__.py create mode 100644 packages/sie_placement/src/sie_placement/schema.py create mode 100644 packages/sie_placement/tests/fixtures/boot-evidence.json create mode 100644 packages/sie_placement/tests/fixtures/demand.json create mode 100644 packages/sie_placement/tests/fixtures/plan.json create mode 100644 packages/sie_placement/tests/fixtures/price-list.json create mode 100644 packages/sie_placement/tests/fixtures/receipt-encode.json create mode 100644 packages/sie_placement/tests/fixtures/receipt-generate.json create mode 100644 packages/sie_placement/tests/fixtures/service-levels.json create mode 100644 packages/sie_placement/tests/test_schema.py diff --git a/.coveragerc b/.coveragerc index 23e4ec855..3eb71ea6c 100644 --- a/.coveragerc +++ b/.coveragerc @@ -9,6 +9,7 @@ source_pkgs = sie_config sie_mcp + sie_placement sie_sdk sie_server relative_files = True diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7f713626a..a73b5b105 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -67,6 +67,7 @@ git switch -c upstream/main | [`packages/sie_sdk`](packages/sie_sdk/README.md) | Python client SDK and public request and response types | | `packages/sie_config` | Python configuration service | | [`packages/sie_mcp`](packages/sie_mcp/README.md) | Python MCP edge service, plugin, and agent skill | +| [`packages/sie_placement`](packages/sie_placement/README.md) | Standard-library Python schemas for placement planner inputs and plans; a workspace package that is not published | | [`packages/sie_audio_prep`](packages/sie_audio_prep/README.md) | Native audio preparation extension with Python bindings | | [`packages/sie_ts_sdk`](packages/sie_ts_sdk/README.md) | TypeScript client SDK | | [`packages/sie_gateway`](packages/sie_gateway/README.md) | Rust gateway for routing, queuing, API compatibility, and cluster state | diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md new file mode 100644 index 000000000..cf72c6183 --- /dev/null +++ b/packages/sie_placement/README.md @@ -0,0 +1,79 @@ +# sie-placement + +Versioned documents for a measured-only placement planner: the service level +each served identity must meet, the measurements a placement may be chosen +from, the prices those placements cost, the demand they serve, and the plan +that results. The package uses only the Python standard library. It is a +workspace package and is not published to PyPI. + +A served identity is a model id or a `model:profile` pair, the routing key a +request resolves to. A measurement cell is a machine profile together with the +GPU product the measurement actually ran on, such as the +`nvidia.com/gpu.product` node label value `NVIDIA-L4`. Recording the realized +product rather than the requested one keeps a measurement taken on different +silicon from standing in for the profile it was requested on. + +## Documents + +Every document is a JSON object with a `kind` and a `schemaVersion`. Readers +reject another kind, any version other than `1`, unknown fields, `null` +values, booleans where numbers are expected and non-finite numbers. Errors +name the offending field by its JSON path, for example +`$.lanes[1].envelope.floorMax: must not exceed maxContainers (2), got 3`. + +| Kind | Type | Contents | +| --- | --- | --- | +| `placement-service-levels` | `ServiceLevels` | Optional named `tiers` and the `identities` that declare or inherit service levels | +| `placement-receipt` | `Receipt` | One throughput and latency measurement of one identity on one cell, container shape, concurrency and request shape | +| `placement-boot-evidence` | `BootEvidence` | One measured boot, snapshot restore or resident load of one identity on one cell and container shape | +| `placement-price-list` | `PriceList` | Accelerator, core and memory rates per machine profile, and the region multiplier per placement | +| `placement-demand` | `Demand` | Hourly request counts per identity and operation over a UTC window | +| `placement-plan` | `Plan` | Lanes with their cell, container shape, concurrency, ceiling and envelope, and the lane and warmth of every identity | + +Each type parses with `from_dict(data)` and serializes with `to_dict()`. +Constructing a type in code applies the same rules as parsing it: + +```python +import json + +from sie_placement.schema import Plan + +with open("plan.json", encoding="utf-8") as handle: + plan = Plan.from_dict(json.load(handle)) +assert Plan.from_dict(plan.to_dict()) == plan +``` + +## Service levels + +An identity declares up to three numbers, or inherits them from the tier it +names. Fields it declares override the tier's. + +| Field | Meaning | +| --- | --- | +| `comeAliveP95S` | Seconds from a request for an idle identity to its first result, at the 95th percentile. `0` means never cold | +| `warmP99Ms` | Warm latency at the 99th percentile, at the receipt's request shape | +| `ttftP99Ms`, `itlP99Ms` | Time to first token and inter-token latency at the 99th percentile. A generation identity declares both instead of `warmP99Ms` | +| `queueWaitP99Ms` | Time a request may wait for capacity under load, at the 99th percentile | + +## Warmth + +A plan gives every identity one warmth: `pinned`, `cold-with-bound`, +`bridged`, `snapshot-cold`, `scheduled-warm` or `lazy-resident`. A `pinned` or +`lazy-resident` identity sits on a lane whose envelope keeps `floorMin` at 1 +or more; every other warmth sits on a lane whose `floorMin` is 0. Boot +evidence records `cold-with-bound` boots, `snapshot-cold` restores and +`lazy-resident` loads, with outcome `succeeded`, `failed` or `timed-out`. + +## Envelope + +A plan lane's envelope bounds what an online tuner may change without a new +plan. `floorMin` and `floorMax` are required, with `floorMax` at most the +lane's `maxContainers`. `bufferMin` with `bufferMax`, and +`scaledownWindowMinS` with `scaledownWindowMaxS`, are optional pairs for +platforms that can move a warm buffer or a scale-down window per lane. + +## Tests + +```bash +mise run test -- packages/sie_placement/tests +``` diff --git a/packages/sie_placement/pyproject.toml b/packages/sie_placement/pyproject.toml new file mode 100644 index 000000000..91b0c19d6 --- /dev/null +++ b/packages/sie_placement/pyproject.toml @@ -0,0 +1,19 @@ +[project] +name = "sie-placement" +version = "0.0.0" +description = "SIE placement planner - versioned input and plan documents for measured-only placement" +requires-python = ">=3.12,<3.13" +license = { text = "Apache-2.0" } +dependencies = [] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/sie_placement"] + +[dependency-groups] +dev = [ + "pytest>=9.0.3", +] diff --git a/packages/sie_placement/src/sie_placement/__init__.py b/packages/sie_placement/src/sie_placement/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/packages/sie_placement/src/sie_placement/schema.py b/packages/sie_placement/src/sie_placement/schema.py new file mode 100644 index 000000000..3171da492 --- /dev/null +++ b/packages/sie_placement/src/sie_placement/schema.py @@ -0,0 +1,1054 @@ +"""Versioned input and plan documents of the measured-only placement planner.""" + +from __future__ import annotations + +import math +import re +from collections.abc import Callable, Hashable, Iterable, Mapping +from dataclasses import dataclass +from datetime import UTC, datetime +from enum import StrEnum +from typing import Self + +SCHEMA_VERSION = 1 + +SERVICE_LEVELS_KIND = "placement-service-levels" +RECEIPT_KIND = "placement-receipt" +BOOT_EVIDENCE_KIND = "placement-boot-evidence" +PRICE_LIST_KIND = "placement-price-list" +DEMAND_KIND = "placement-demand" +PLAN_KIND = "placement-plan" + +ROOT_PATH = "$" + +_SHA256 = re.compile(r"[0-9a-f]{64}") +_CURRENCY = re.compile(r"[A-Z]{3}") +_HOUR = re.compile(r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):00:00Z") +_HOUR_FORMAT = "%Y-%m-%dT%H:00:00Z" + + +class SchemaError(ValueError): + def __init__(self, path: str, message: str) -> None: + super().__init__(f"{path}: {message}" if path else message) + self.path = path + self.message = message + + +class Operation(StrEnum): + ENCODE = "encode" + SCORE = "score" + EXTRACT = "extract" + GENERATE = "generate" + + +class Warmth(StrEnum): + PINNED = "pinned" + COLD_WITH_BOUND = "cold-with-bound" + BRIDGED = "bridged" + SNAPSHOT_COLD = "snapshot-cold" + SCHEDULED_WARM = "scheduled-warm" + LAZY_RESIDENT = "lazy-resident" + + +BOOT_WARMTHS = frozenset({Warmth.COLD_WITH_BOUND, Warmth.SNAPSHOT_COLD, Warmth.LAZY_RESIDENT}) +WARM_FLOOR_WARMTHS = frozenset({Warmth.PINNED, Warmth.LAZY_RESIDENT}) + + +class BootOutcome(StrEnum): + SUCCEEDED = "succeeded" + FAILED = "failed" + TIMED_OUT = "timed-out" + + +def _join(path: str, key: str) -> str: + if not key: + return path + if not path: + return key + if key.startswith("["): + return f"{path}{key}" + return f"{path}.{key}" + + +def _within(path: str, error: SchemaError) -> SchemaError: + return SchemaError(_join(path, error.path), error.message) + + +def _describe(value: object) -> str: + if value is None: + return "null" + if isinstance(value, bool): + return f"boolean {str(value).lower()}" + if isinstance(value, int | float): + return f"number {value!r}" + if isinstance(value, str): + return f"string {value!r}" + if isinstance(value, Mapping): + return "an object" + if isinstance(value, list | tuple): + return "an array" + return type(value).__name__ + + +def _format_hour(value: datetime) -> str: + return value.strftime(_HOUR_FORMAT) + + +def _compact(fields: dict[str, object | None]) -> dict[str, object]: + return {key: value for key, value in fields.items() if value is not None} + + +class _Reader: + def __init__(self, data: object, path: str) -> None: + if not isinstance(data, Mapping): + raise SchemaError(path, f"expected an object, got {_describe(data)}") + self._data: dict[str, object] = {} + for key, value in data.items(): + if not isinstance(key, str): + raise SchemaError(path, f"expected string keys, got {_describe(key)}") + self._data[key] = value + self._path = path + self._read: set[str] = set() + + def _at(self, key: str) -> str: + return _join(self._path, key) + + def _required(self, key: str) -> object: + self._read.add(key) + if key not in self._data: + raise SchemaError(self._at(key), "is required") + value = self._data[key] + if value is None: + raise SchemaError(self._at(key), "must not be null") + return value + + def _optional(self, key: str) -> object | None: + self._read.add(key) + if key not in self._data: + return None + value = self._data[key] + if value is None: + raise SchemaError(self._at(key), "must be omitted rather than null") + return value + + def _string(self, key: str, value: object) -> str: + if not isinstance(value, str): + raise SchemaError(self._at(key), f"expected a string, got {_describe(value)}") + return value + + def _integer(self, key: str, value: object) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise SchemaError(self._at(key), f"expected an integer, got {_describe(value)}") + return value + + def _number(self, key: str, value: object) -> float: + if isinstance(value, bool) or not isinstance(value, int | float): + raise SchemaError(self._at(key), f"expected a number, got {_describe(value)}") + if not math.isfinite(value): + raise SchemaError(self._at(key), f"expected a finite number, got {value!r}") + return value + + def header(self, kind: str) -> None: + found = self._string("kind", self._required("kind")) + if found != kind: + raise SchemaError(self._at("kind"), f"expected {kind!r}, got {found!r}") + version = self._integer("schemaVersion", self._required("schemaVersion")) + if version != SCHEMA_VERSION: + raise SchemaError( + self._at("schemaVersion"), + f"unsupported version {version}; this reader supports version {SCHEMA_VERSION}", + ) + + def string(self, key: str) -> str: + return self._string(key, self._required(key)) + + def optional_string(self, key: str) -> str | None: + value = self._optional(key) + return None if value is None else self._string(key, value) + + def integer(self, key: str) -> int: + return self._integer(key, self._required(key)) + + def optional_integer(self, key: str) -> int | None: + value = self._optional(key) + return None if value is None else self._integer(key, value) + + def number(self, key: str) -> float: + return self._number(key, self._required(key)) + + def optional_number(self, key: str) -> float | None: + value = self._optional(key) + return None if value is None else self._number(key, value) + + def enum[E: StrEnum](self, key: str, kind: type[E]) -> E: + value = self.string(key) + try: + return kind(value) + except ValueError: + choices = ", ".join(repr(member.value) for member in kind) + raise SchemaError(self._at(key), f"expected one of {choices}, got {value!r}") from None + + def hour(self, key: str) -> datetime: + value = self.string(key) + match = _HOUR.fullmatch(value) + if match is None: + raise SchemaError(self._at(key), f"expected a UTC hour such as '2026-01-01T00:00:00Z', got {value!r}") + year, month, day, hour = (int(part) for part in match.groups()) + try: + return datetime(year, month, day, hour, tzinfo=UTC) + except ValueError as error: + raise SchemaError(self._at(key), f"is not a valid time: {error}") from None + + def child[T](self, key: str, parse: Callable[[object, str], T]) -> T: + return parse(self._required(key), self._at(key)) + + def optional_child[T](self, key: str, parse: Callable[[object, str], T]) -> T | None: + value = self._optional(key) + return None if value is None else parse(value, self._at(key)) + + def children[T](self, key: str, parse: Callable[[object, str], T], *, required: bool = True) -> tuple[T, ...]: + value = self._required(key) if required else self._optional(key) + if value is None: + return () + if not isinstance(value, list | tuple): + raise SchemaError(self._at(key), f"expected an array, got {_describe(value)}") + return tuple(parse(item, f"{self._at(key)}[{index}]") for index, item in enumerate(value)) + + def service_level(self) -> ServiceLevel: + return self.construct( + ServiceLevel, + come_alive_p95_s=self.optional_integer("comeAliveP95S"), + warm_p99_ms=self.optional_integer("warmP99Ms"), + ttft_p99_ms=self.optional_integer("ttftP99Ms"), + itl_p99_ms=self.optional_integer("itlP99Ms"), + queue_wait_p99_ms=self.optional_integer("queueWaitP99Ms"), + ) + + def construct[**P, T](self, factory: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: + try: + return factory(*args, **kwargs) + except SchemaError as error: + raise _within(self._path, error) from None + + def build[**P, T](self, factory: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: + unknown = sorted(set(self._data) - self._read) + if unknown: + raise SchemaError(self._at(unknown[0]), "is not a field of this object") + return self.construct(factory, *args, **kwargs) + + +def _require_identifier(name: str, value: str) -> None: + if not value or any(character.isspace() for character in value): + raise SchemaError(name, f"must be a non-empty string without whitespace, got {value!r}") + + +def _require_at_least(name: str, value: float | None, minimum: int) -> None: + if value is not None and value < minimum: + raise SchemaError(name, f"must be at least {minimum}, got {value!r}") + + +def _require_positive(name: str, value: float | None) -> None: + if value is not None and value <= 0: + raise SchemaError(name, f"must be greater than 0, got {value!r}") + + +def _require_ordered(lower_name: str, lower: float | None, upper_name: str, upper: float | None) -> None: + if lower is not None and upper is not None and lower > upper: + raise SchemaError(upper_name, f"must be at least {lower_name} ({lower!r}), got {upper!r}") + + +def _require_pair(first_name: str, first: object | None, second_name: str, second: object | None) -> None: + if (first is None) != (second is None): + missing = first_name if first is None else second_name + raise SchemaError(missing, f"{first_name} and {second_name} are declared together") + + +def _require_absent(name: str, value: object | None, reason: str) -> None: + if value is not None: + raise SchemaError(name, f"must be omitted {reason}") + + +def _require_unique(collection: str, field: str, keys: Iterable[Hashable]) -> None: + seen: set[Hashable] = set() + for index, key in enumerate(keys): + if key in seen: + raise SchemaError(f"{collection}[{index}].{field}", f"duplicates {key!r}") + seen.add(key) + + +def _require_hour(name: str, value: datetime) -> None: + offset = value.utcoffset() + if offset is None or offset.total_seconds() != 0 or value.minute or value.second or value.microsecond: + raise SchemaError(name, f"must be a UTC hour boundary, got {value.isoformat()}") + + +def _prefer(override: int | None, inherited: int | None) -> int | None: + return inherited if override is None else override + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ServiceLevel: + come_alive_p95_s: int | None = None + warm_p99_ms: int | None = None + ttft_p99_ms: int | None = None + itl_p99_ms: int | None = None + queue_wait_p99_ms: int | None = None + + def __post_init__(self) -> None: + for name, value in self._fields(): + _require_at_least(name, value, 0) + if self.warm_p99_ms is not None and (self.ttft_p99_ms is not None or self.itl_p99_ms is not None): + raise SchemaError("warmP99Ms", "must be omitted when ttftP99Ms and itlP99Ms declare a generation identity") + + def _fields(self) -> tuple[tuple[str, int | None], ...]: + return ( + ("comeAliveP95S", self.come_alive_p95_s), + ("warmP99Ms", self.warm_p99_ms), + ("ttftP99Ms", self.ttft_p99_ms), + ("itlP99Ms", self.itl_p99_ms), + ("queueWaitP99Ms", self.queue_wait_p99_ms), + ) + + @property + def is_generation(self) -> bool: + return self.ttft_p99_ms is not None or self.itl_p99_ms is not None + + def require_complete(self) -> None: + _require_pair("ttftP99Ms", self.ttft_p99_ms, "itlP99Ms", self.itl_p99_ms) + + def overlay(self, override: ServiceLevel) -> ServiceLevel: + return ServiceLevel( + come_alive_p95_s=_prefer(override.come_alive_p95_s, self.come_alive_p95_s), + warm_p99_ms=_prefer(override.warm_p99_ms, self.warm_p99_ms), + ttft_p99_ms=_prefer(override.ttft_p99_ms, self.ttft_p99_ms), + itl_p99_ms=_prefer(override.itl_p99_ms, self.itl_p99_ms), + queue_wait_p99_ms=_prefer(override.queue_wait_p99_ms, self.queue_wait_p99_ms), + ) + + def to_dict(self) -> dict[str, object]: + return _compact(dict(self._fields())) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ServiceLevelTier: + name: str + level: ServiceLevel + + def __post_init__(self) -> None: + _require_identifier("name", self.name) + self.level.require_complete() + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build(cls, name=reader.string("name"), level=reader.service_level()) + + def to_dict(self) -> dict[str, object]: + return {"name": self.name, **self.level.to_dict()} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class IdentityServiceLevel: + identity: str + level: ServiceLevel + tier: str | None = None + + def __post_init__(self) -> None: + _require_identifier("identity", self.identity) + if self.tier is not None: + _require_identifier("tier", self.tier) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + identity=reader.string("identity"), + tier=reader.optional_string("tier"), + level=reader.service_level(), + ) + + def to_dict(self) -> dict[str, object]: + return _compact({"identity": self.identity, "tier": self.tier}) | self.level.to_dict() + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ServiceLevels: + identities: tuple[IdentityServiceLevel, ...] + tiers: tuple[ServiceLevelTier, ...] = () + + def __post_init__(self) -> None: + _require_unique("tiers", "name", (tier.name for tier in self.tiers)) + _require_unique("identities", "identity", (entry.identity for entry in self.identities)) + tiers = {tier.name: tier.level for tier in self.tiers} + for index, entry in enumerate(self.identities): + if entry.tier is not None and entry.tier not in tiers: + raise SchemaError(f"identities[{index}].tier", f"names no declared tier: {entry.tier!r}") + try: + self._resolve(entry, tiers).require_complete() + except SchemaError as error: + raise _within(f"identities[{index}]", error) from None + + @staticmethod + def _resolve(entry: IdentityServiceLevel, tiers: Mapping[str, ServiceLevel]) -> ServiceLevel: + if entry.tier is None: + return entry.level + return tiers[entry.tier].overlay(entry.level) + + def effective(self, identity: str) -> ServiceLevel: + tiers = {tier.name: tier.level for tier in self.tiers} + for entry in self.identities: + if entry.identity == identity: + return self._resolve(entry, tiers) + raise KeyError(identity) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + reader.header(SERVICE_LEVELS_KIND) + return reader.build( + cls, + tiers=reader.children("tiers", ServiceLevelTier.from_dict, required=False), + identities=reader.children("identities", IdentityServiceLevel.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + document: dict[str, object] = {"kind": SERVICE_LEVELS_KIND, "schemaVersion": SCHEMA_VERSION} + if self.tiers: + document["tiers"] = [tier.to_dict() for tier in self.tiers] + document["identities"] = [entry.to_dict() for entry in self.identities] + return document + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Cell: + machine_profile: str + gpu_product: str + + def __post_init__(self) -> None: + _require_identifier("machineProfile", self.machine_profile) + _require_identifier("gpuProduct", self.gpu_product) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + machine_profile=reader.string("machineProfile"), + gpu_product=reader.string("gpuProduct"), + ) + + def to_dict(self) -> dict[str, object]: + return {"machineProfile": self.machine_profile, "gpuProduct": self.gpu_product} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ContainerShape: + gpu_count: int + cpu_cores: float + memory_mib: int + + def __post_init__(self) -> None: + _require_at_least("gpuCount", self.gpu_count, 1) + _require_positive("cpuCores", self.cpu_cores) + _require_at_least("memoryMiB", self.memory_mib, 1) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + gpu_count=reader.integer("gpuCount"), + cpu_cores=reader.number("cpuCores"), + memory_mib=reader.integer("memoryMiB"), + ) + + def to_dict(self) -> dict[str, object]: + return {"gpuCount": self.gpu_count, "cpuCores": self.cpu_cores, "memoryMiB": self.memory_mib} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class RequestShape: + operation: Operation + items_per_request: int + input_tokens_per_item: int | None = None + output_tokens: int | None = None + + def __post_init__(self) -> None: + _require_at_least("itemsPerRequest", self.items_per_request, 1) + _require_at_least("inputTokensPerItem", self.input_tokens_per_item, 0) + if self.operation is Operation.GENERATE: + if self.output_tokens is None: + raise SchemaError("outputTokens", "is required for the generate operation") + _require_at_least("outputTokens", self.output_tokens, 1) + else: + _require_absent("outputTokens", self.output_tokens, "for an operation other than generate") + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + operation=reader.enum("operation", Operation), + items_per_request=reader.integer("itemsPerRequest"), + input_tokens_per_item=reader.optional_integer("inputTokensPerItem"), + output_tokens=reader.optional_integer("outputTokens"), + ) + + def to_dict(self) -> dict[str, object]: + return _compact( + { + "operation": self.operation.value, + "itemsPerRequest": self.items_per_request, + "inputTokensPerItem": self.input_tokens_per_item, + "outputTokens": self.output_tokens, + } + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Throughput: + requests_per_second: float + output_tokens_per_second: float | None = None + + def __post_init__(self) -> None: + _require_positive("requestsPerSecond", self.requests_per_second) + _require_positive("outputTokensPerSecond", self.output_tokens_per_second) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + requests_per_second=reader.number("requestsPerSecond"), + output_tokens_per_second=reader.optional_number("outputTokensPerSecond"), + ) + + def to_dict(self) -> dict[str, object]: + return _compact( + {"requestsPerSecond": self.requests_per_second, "outputTokensPerSecond": self.output_tokens_per_second} + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Percentiles: + p99_ms: float + p50_ms: float | None = None + p95_ms: float | None = None + + def __post_init__(self) -> None: + _require_at_least("p50Ms", self.p50_ms, 0) + _require_at_least("p95Ms", self.p95_ms, 0) + _require_at_least("p99Ms", self.p99_ms, 0) + _require_ordered("p50Ms", self.p50_ms, "p95Ms", self.p95_ms) + _require_ordered("p95Ms", self.p95_ms, "p99Ms", self.p99_ms) + _require_ordered("p50Ms", self.p50_ms, "p99Ms", self.p99_ms) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + p50_ms=reader.optional_number("p50Ms"), + p95_ms=reader.optional_number("p95Ms"), + p99_ms=reader.number("p99Ms"), + ) + + def to_dict(self) -> dict[str, object]: + return _compact({"p50Ms": self.p50_ms, "p95Ms": self.p95_ms, "p99Ms": self.p99_ms}) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class SourceRef: + uri: str + sha256: str | None = None + + def __post_init__(self) -> None: + _require_identifier("uri", self.uri) + if self.sha256 is not None and _SHA256.fullmatch(self.sha256) is None: + raise SchemaError("sha256", f"must be 64 lowercase hexadecimal characters, got {self.sha256!r}") + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build(cls, uri=reader.string("uri"), sha256=reader.optional_string("sha256")) + + def to_dict(self) -> dict[str, object]: + return _compact({"uri": self.uri, "sha256": self.sha256}) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Receipt: + identity: str + cell: Cell + container_shape: ContainerShape + concurrency: int + request_shape: RequestShape + throughput: Throughput + source: SourceRef + latency: Percentiles | None = None + ttft: Percentiles | None = None + itl: Percentiles | None = None + + def __post_init__(self) -> None: + _require_identifier("identity", self.identity) + _require_at_least("concurrency", self.concurrency, 1) + if self.request_shape.operation is Operation.GENERATE: + _require_absent("latency", self.latency, "for the generate operation, which reports ttft and itl") + if self.ttft is None: + raise SchemaError("ttft", "is required for the generate operation") + if self.itl is None: + raise SchemaError("itl", "is required for the generate operation") + else: + if self.latency is None: + raise SchemaError("latency", "is required for an operation other than generate") + _require_absent("ttft", self.ttft, "for an operation other than generate") + _require_absent("itl", self.itl, "for an operation other than generate") + _require_absent( + "throughput.outputTokensPerSecond", + self.throughput.output_tokens_per_second, + "for an operation other than generate", + ) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + reader.header(RECEIPT_KIND) + return reader.build( + cls, + identity=reader.string("identity"), + cell=reader.child("cell", Cell.from_dict), + container_shape=reader.child("containerShape", ContainerShape.from_dict), + concurrency=reader.integer("concurrency"), + request_shape=reader.child("requestShape", RequestShape.from_dict), + throughput=reader.child("throughput", Throughput.from_dict), + latency=reader.optional_child("latency", Percentiles.from_dict), + ttft=reader.optional_child("ttft", Percentiles.from_dict), + itl=reader.optional_child("itl", Percentiles.from_dict), + source=reader.child("source", SourceRef.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + return _compact( + { + "kind": RECEIPT_KIND, + "schemaVersion": SCHEMA_VERSION, + "identity": self.identity, + "cell": self.cell.to_dict(), + "containerShape": self.container_shape.to_dict(), + "concurrency": self.concurrency, + "requestShape": self.request_shape.to_dict(), + "throughput": self.throughput.to_dict(), + "latency": None if self.latency is None else self.latency.to_dict(), + "ttft": None if self.ttft is None else self.ttft.to_dict(), + "itl": None if self.itl is None else self.itl.to_dict(), + "source": self.source.to_dict(), + } + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class BootEvidence: + identity: str + cell: Cell + container_shape: ContainerShape + warmth: Warmth + boot_seconds: float + outcome: BootOutcome + source: SourceRef + + def __post_init__(self) -> None: + _require_identifier("identity", self.identity) + if self.warmth not in BOOT_WARMTHS: + choices = ", ".join(repr(warmth.value) for warmth in Warmth if warmth in BOOT_WARMTHS) + raise SchemaError("warmth", f"boot evidence records one of {choices}, got {self.warmth.value!r}") + _require_at_least("bootSeconds", self.boot_seconds, 0) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + reader.header(BOOT_EVIDENCE_KIND) + return reader.build( + cls, + identity=reader.string("identity"), + cell=reader.child("cell", Cell.from_dict), + container_shape=reader.child("containerShape", ContainerShape.from_dict), + warmth=reader.enum("warmth", Warmth), + boot_seconds=reader.number("bootSeconds"), + outcome=reader.enum("outcome", BootOutcome), + source=reader.child("source", SourceRef.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + return { + "kind": BOOT_EVIDENCE_KIND, + "schemaVersion": SCHEMA_VERSION, + "identity": self.identity, + "cell": self.cell.to_dict(), + "containerShape": self.container_shape.to_dict(), + "warmth": self.warmth.value, + "bootSeconds": self.boot_seconds, + "outcome": self.outcome.value, + "source": self.source.to_dict(), + } + + +@dataclass(frozen=True, slots=True, kw_only=True) +class MachineProfilePrice: + name: str + gpu_product: str + accelerator_per_hour: float + core_per_hour: float + memory_gib_per_hour: float + + def __post_init__(self) -> None: + _require_identifier("name", self.name) + _require_identifier("gpuProduct", self.gpu_product) + _require_at_least("acceleratorPerHour", self.accelerator_per_hour, 0) + _require_at_least("corePerHour", self.core_per_hour, 0) + _require_at_least("memoryGiBPerHour", self.memory_gib_per_hour, 0) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + name=reader.string("name"), + gpu_product=reader.string("gpuProduct"), + accelerator_per_hour=reader.number("acceleratorPerHour"), + core_per_hour=reader.number("corePerHour"), + memory_gib_per_hour=reader.number("memoryGiBPerHour"), + ) + + def to_dict(self) -> dict[str, object]: + return { + "name": self.name, + "gpuProduct": self.gpu_product, + "acceleratorPerHour": self.accelerator_per_hour, + "corePerHour": self.core_per_hour, + "memoryGiBPerHour": self.memory_gib_per_hour, + } + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Placement: + name: str + region_multiplier: float + + def __post_init__(self) -> None: + _require_identifier("name", self.name) + _require_positive("regionMultiplier", self.region_multiplier) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build(cls, name=reader.string("name"), region_multiplier=reader.number("regionMultiplier")) + + def to_dict(self) -> dict[str, object]: + return {"name": self.name, "regionMultiplier": self.region_multiplier} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class PriceList: + currency: str + machine_profiles: tuple[MachineProfilePrice, ...] + placements: tuple[Placement, ...] + + def __post_init__(self) -> None: + if _CURRENCY.fullmatch(self.currency) is None: + raise SchemaError("currency", f"must be a three-letter upper-case currency code, got {self.currency!r}") + if not self.machine_profiles: + raise SchemaError("machineProfiles", "must list at least one machine profile") + if not self.placements: + raise SchemaError("placements", "must list at least one placement") + _require_unique("machineProfiles", "name", (profile.name for profile in self.machine_profiles)) + _require_unique("placements", "name", (placement.name for placement in self.placements)) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + reader.header(PRICE_LIST_KIND) + return reader.build( + cls, + currency=reader.string("currency"), + machine_profiles=reader.children("machineProfiles", MachineProfilePrice.from_dict), + placements=reader.children("placements", Placement.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + return { + "kind": PRICE_LIST_KIND, + "schemaVersion": SCHEMA_VERSION, + "currency": self.currency, + "machineProfiles": [profile.to_dict() for profile in self.machine_profiles], + "placements": [placement.to_dict() for placement in self.placements], + } + + +@dataclass(frozen=True, slots=True, kw_only=True) +class DemandHour: + start: datetime + requests: int + units: int | None = None + + def __post_init__(self) -> None: + _require_hour("start", self.start) + _require_at_least("requests", self.requests, 0) + _require_at_least("units", self.units, 0) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + start=reader.hour("start"), + requests=reader.integer("requests"), + units=reader.optional_integer("units"), + ) + + def to_dict(self) -> dict[str, object]: + return _compact({"start": _format_hour(self.start), "requests": self.requests, "units": self.units}) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class DemandSeries: + identity: str + operation: Operation + hours: tuple[DemandHour, ...] + + def __post_init__(self) -> None: + _require_identifier("identity", self.identity) + for index in range(1, len(self.hours)): + if self.hours[index].start <= self.hours[index - 1].start: + raise SchemaError(f"hours[{index}].start", "must be later than the previous hour") + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + identity=reader.string("identity"), + operation=reader.enum("operation", Operation), + hours=reader.children("hours", DemandHour.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + return { + "identity": self.identity, + "operation": self.operation.value, + "hours": [hour.to_dict() for hour in self.hours], + } + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Demand: + start: datetime + end: datetime + series: tuple[DemandSeries, ...] + + def __post_init__(self) -> None: + _require_hour("start", self.start) + _require_hour("end", self.end) + if self.end <= self.start: + raise SchemaError("end", "must be later than start") + _require_unique("series", "identity", (f"{entry.identity} {entry.operation.value}" for entry in self.series)) + for series_index, entry in enumerate(self.series): + for hour_index, hour in enumerate(entry.hours): + if not self.start <= hour.start < self.end: + raise SchemaError( + f"series[{series_index}].hours[{hour_index}].start", + f"must fall inside the window [{_format_hour(self.start)}, {_format_hour(self.end)})", + ) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + reader.header(DEMAND_KIND) + return reader.build( + cls, + start=reader.hour("start"), + end=reader.hour("end"), + series=reader.children("series", DemandSeries.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + return { + "kind": DEMAND_KIND, + "schemaVersion": SCHEMA_VERSION, + "start": _format_hour(self.start), + "end": _format_hour(self.end), + "series": [entry.to_dict() for entry in self.series], + } + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Envelope: + floor_min: int + floor_max: int + buffer_min: int | None = None + buffer_max: int | None = None + scaledown_window_min_s: int | None = None + scaledown_window_max_s: int | None = None + + def __post_init__(self) -> None: + for name, value in self._fields(): + _require_at_least(name, value, 0) + _require_ordered("floorMin", self.floor_min, "floorMax", self.floor_max) + _require_pair("bufferMin", self.buffer_min, "bufferMax", self.buffer_max) + _require_ordered("bufferMin", self.buffer_min, "bufferMax", self.buffer_max) + _require_pair( + "scaledownWindowMinS", self.scaledown_window_min_s, "scaledownWindowMaxS", self.scaledown_window_max_s + ) + _require_ordered( + "scaledownWindowMinS", self.scaledown_window_min_s, "scaledownWindowMaxS", self.scaledown_window_max_s + ) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + floor_min=reader.integer("floorMin"), + floor_max=reader.integer("floorMax"), + buffer_min=reader.optional_integer("bufferMin"), + buffer_max=reader.optional_integer("bufferMax"), + scaledown_window_min_s=reader.optional_integer("scaledownWindowMinS"), + scaledown_window_max_s=reader.optional_integer("scaledownWindowMaxS"), + ) + + def _fields(self) -> tuple[tuple[str, int | None], ...]: + return ( + ("floorMin", self.floor_min), + ("floorMax", self.floor_max), + ("bufferMin", self.buffer_min), + ("bufferMax", self.buffer_max), + ("scaledownWindowMinS", self.scaledown_window_min_s), + ("scaledownWindowMaxS", self.scaledown_window_max_s), + ) + + def to_dict(self) -> dict[str, object]: + return _compact(dict(self._fields())) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class PlanLane: + name: str + pool: str + bundle: str + cell: Cell + container_shape: ContainerShape + concurrency: int + max_containers: int + envelope: Envelope + + def __post_init__(self) -> None: + _require_identifier("name", self.name) + _require_identifier("pool", self.pool) + _require_identifier("bundle", self.bundle) + _require_at_least("concurrency", self.concurrency, 1) + _require_at_least("maxContainers", self.max_containers, 1) + if self.envelope.floor_max > self.max_containers: + raise SchemaError( + "envelope.floorMax", + f"must not exceed maxContainers ({self.max_containers}), got {self.envelope.floor_max}", + ) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + name=reader.string("name"), + pool=reader.string("pool"), + bundle=reader.string("bundle"), + cell=reader.child("cell", Cell.from_dict), + container_shape=reader.child("containerShape", ContainerShape.from_dict), + concurrency=reader.integer("concurrency"), + max_containers=reader.integer("maxContainers"), + envelope=reader.child("envelope", Envelope.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + return { + "name": self.name, + "pool": self.pool, + "bundle": self.bundle, + "cell": self.cell.to_dict(), + "containerShape": self.container_shape.to_dict(), + "concurrency": self.concurrency, + "maxContainers": self.max_containers, + "envelope": self.envelope.to_dict(), + } + + +@dataclass(frozen=True, slots=True, kw_only=True) +class PlanIdentity: + identity: str + lane: str + warmth: Warmth + + def __post_init__(self) -> None: + _require_identifier("identity", self.identity) + _require_identifier("lane", self.lane) + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + return reader.build( + cls, + identity=reader.string("identity"), + lane=reader.string("lane"), + warmth=reader.enum("warmth", Warmth), + ) + + def to_dict(self) -> dict[str, object]: + return {"identity": self.identity, "lane": self.lane, "warmth": self.warmth.value} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Plan: + placement: str + lanes: tuple[PlanLane, ...] + identities: tuple[PlanIdentity, ...] + + def __post_init__(self) -> None: + _require_identifier("placement", self.placement) + _require_unique("lanes", "name", (lane.name for lane in self.lanes)) + _require_unique("identities", "identity", (entry.identity for entry in self.identities)) + lanes = {lane.name: lane for lane in self.lanes} + for index, entry in enumerate(self.identities): + lane = lanes.get(entry.lane) + if lane is None: + raise SchemaError(f"identities[{index}].lane", f"names no lane of this plan: {entry.lane!r}") + warm_floor = lane.envelope.floor_min >= 1 + if (entry.warmth in WARM_FLOOR_WARMTHS) != warm_floor: + expectation = "at least 1" if entry.warmth in WARM_FLOOR_WARMTHS else "0" + raise SchemaError( + f"identities[{index}].warmth", + f"{entry.warmth.value} needs lane {lane.name!r} to have floorMin {expectation}, " + f"got {lane.envelope.floor_min}", + ) + hosted = {entry.lane for entry in self.identities} + for index, lane in enumerate(self.lanes): + if lane.name not in hosted: + raise SchemaError(f"lanes[{index}].name", f"lane {lane.name!r} hosts no identity") + + @classmethod + def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: + reader = _Reader(data, path) + reader.header(PLAN_KIND) + return reader.build( + cls, + placement=reader.string("placement"), + lanes=reader.children("lanes", PlanLane.from_dict), + identities=reader.children("identities", PlanIdentity.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + return { + "kind": PLAN_KIND, + "schemaVersion": SCHEMA_VERSION, + "placement": self.placement, + "lanes": [lane.to_dict() for lane in self.lanes], + "identities": [entry.to_dict() for entry in self.identities], + } diff --git a/packages/sie_placement/tests/fixtures/boot-evidence.json b/packages/sie_placement/tests/fixtures/boot-evidence.json new file mode 100644 index 000000000..be9e58814 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/boot-evidence.json @@ -0,0 +1,21 @@ +{ + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-8B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 12, + "memoryMiB": 87040 + }, + "warmth": "cold-with-bound", + "bootSeconds": 187.4, + "outcome": "succeeded", + "source": { + "uri": "https://example.com/boots/qwen3-8b-a100-80gb-0001.json", + "sha256": "0a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f9" + } +} diff --git a/packages/sie_placement/tests/fixtures/demand.json b/packages/sie_placement/tests/fixtures/demand.json new file mode 100644 index 000000000..9facb2166 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/demand.json @@ -0,0 +1,34 @@ +{ + "kind": "placement-demand", + "schemaVersion": 1, + "start": "2026-11-02T00:00:00Z", + "end": "2026-11-03T00:00:00Z", + "series": [ + { + "identity": "BAAI/bge-m3", + "operation": "encode", + "hours": [ + { + "start": "2026-11-02T09:00:00Z", + "requests": 1840, + "units": 14720 + }, + { + "start": "2026-11-02T10:00:00Z", + "requests": 2210, + "units": 17680 + } + ] + }, + { + "identity": "Qwen/Qwen3-8B", + "operation": "generate", + "hours": [ + { + "start": "2026-11-02T14:00:00Z", + "requests": 12 + } + ] + } + ] +} diff --git a/packages/sie_placement/tests/fixtures/plan.json b/packages/sie_placement/tests/fixtures/plan.json new file mode 100644 index 000000000..cc601e491 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/plan.json @@ -0,0 +1,68 @@ +{ + "kind": "placement-plan", + "schemaVersion": 1, + "placement": "us-central1", + "lanes": [ + { + "name": "default-l4-default", + "pool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 7.5, + "memoryMiB": 30720 + }, + "concurrency": 16, + "maxContainers": 6, + "envelope": { + "floorMin": 1, + "floorMax": 3, + "bufferMin": 0, + "bufferMax": 1, + "scaledownWindowMinS": 60, + "scaledownWindowMaxS": 900 + } + }, + { + "name": "default-a100-80gb-generation", + "pool": "default", + "bundle": "generation", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 12, + "memoryMiB": 87040 + }, + "concurrency": 32, + "maxContainers": 2, + "envelope": { + "floorMin": 0, + "floorMax": 1 + } + } + ], + "identities": [ + { + "identity": "BAAI/bge-m3", + "lane": "default-l4-default", + "warmth": "pinned" + }, + { + "identity": "BAAI/bge-m3:sparse", + "lane": "default-l4-default", + "warmth": "lazy-resident" + }, + { + "identity": "Qwen/Qwen3-8B", + "lane": "default-a100-80gb-generation", + "warmth": "cold-with-bound" + } + ] +} diff --git a/packages/sie_placement/tests/fixtures/price-list.json b/packages/sie_placement/tests/fixtures/price-list.json new file mode 100644 index 000000000..328ef3d0f --- /dev/null +++ b/packages/sie_placement/tests/fixtures/price-list.json @@ -0,0 +1,31 @@ +{ + "kind": "placement-price-list", + "schemaVersion": 1, + "currency": "USD", + "machineProfiles": [ + { + "name": "l4", + "gpuProduct": "NVIDIA-L4", + "acceleratorPerHour": 0.56, + "corePerHour": 0.031, + "memoryGiBPerHour": 0.0042 + }, + { + "name": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB", + "acceleratorPerHour": 3.4, + "corePerHour": 0.031, + "memoryGiBPerHour": 0.0042 + } + ], + "placements": [ + { + "name": "us-central1", + "regionMultiplier": 1 + }, + { + "name": "europe-west4", + "regionMultiplier": 1.15 + } + ] +} diff --git a/packages/sie_placement/tests/fixtures/receipt-encode.json b/packages/sie_placement/tests/fixtures/receipt-encode.json new file mode 100644 index 000000000..d77d41895 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/receipt-encode.json @@ -0,0 +1,32 @@ +{ + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "BAAI/bge-m3", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 7.5, + "memoryMiB": 30720 + }, + "concurrency": 16, + "requestShape": { + "operation": "encode", + "itemsPerRequest": 8, + "inputTokensPerItem": 256 + }, + "throughput": { + "requestsPerSecond": 42.5 + }, + "latency": { + "p50Ms": 110.2, + "p95Ms": 171.9, + "p99Ms": 214 + }, + "source": { + "uri": "benchmarks/bge-m3/l4/encode-8x256.json", + "sha256": "4f2d8c1e9b7a6053d2e1f0c9b8a7d6e5f4c3b2a1908f7e6d5c4b3a2918f7e6d5" + } +} diff --git a/packages/sie_placement/tests/fixtures/receipt-generate.json b/packages/sie_placement/tests/fixtures/receipt-generate.json new file mode 100644 index 000000000..9b39c905a --- /dev/null +++ b/packages/sie_placement/tests/fixtures/receipt-generate.json @@ -0,0 +1,37 @@ +{ + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-8B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 12, + "memoryMiB": 87040 + }, + "concurrency": 32, + "requestShape": { + "operation": "generate", + "itemsPerRequest": 1, + "inputTokensPerItem": 1024, + "outputTokens": 256 + }, + "throughput": { + "requestsPerSecond": 3.1, + "outputTokensPerSecond": 793.6 + }, + "ttft": { + "p50Ms": 310, + "p99Ms": 1480 + }, + "itl": { + "p50Ms": 24.5, + "p95Ms": 31, + "p99Ms": 44.8 + }, + "source": { + "uri": "https://example.com/receipts/qwen3-8b-a100-80gb.json" + } +} diff --git a/packages/sie_placement/tests/fixtures/service-levels.json b/packages/sie_placement/tests/fixtures/service-levels.json new file mode 100644 index 000000000..49c6e59b4 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/service-levels.json @@ -0,0 +1,40 @@ +{ + "kind": "placement-service-levels", + "schemaVersion": 1, + "tiers": [ + { + "name": "interactive-retrieval", + "comeAliveP95S": 0, + "warmP99Ms": 250, + "queueWaitP99Ms": 500 + }, + { + "name": "batch-generation", + "comeAliveP95S": 600, + "ttftP99Ms": 4000, + "itlP99Ms": 120, + "queueWaitP99Ms": 30000 + } + ], + "identities": [ + { + "identity": "BAAI/bge-m3", + "tier": "interactive-retrieval" + }, + { + "identity": "BAAI/bge-m3:sparse", + "tier": "interactive-retrieval", + "comeAliveP95S": 120 + }, + { + "identity": "Qwen/Qwen3-8B", + "tier": "batch-generation", + "itlP99Ms": 80 + }, + { + "identity": "Qwen/Qwen3-Reranker-0.6B", + "comeAliveP95S": 90, + "warmP99Ms": 400 + } + ] +} diff --git a/packages/sie_placement/tests/test_schema.py b/packages/sie_placement/tests/test_schema.py new file mode 100644 index 000000000..609455835 --- /dev/null +++ b/packages/sie_placement/tests/test_schema.py @@ -0,0 +1,528 @@ +from __future__ import annotations + +import copy +import json +import math +from collections.abc import Callable +from datetime import UTC, datetime, timedelta, timezone +from pathlib import Path + +import pytest +from sie_placement.schema import ( + BootEvidence, + Cell, + ContainerShape, + Demand, + DemandHour, + DemandSeries, + Envelope, + IdentityServiceLevel, + Operation, + Percentiles, + Plan, + PlanIdentity, + PlanLane, + PriceList, + Receipt, + SchemaError, + ServiceLevel, + ServiceLevels, + Warmth, +) + +FIXTURES = Path(__file__).parent / "fixtures" + +DOCUMENTS: list[tuple[str, Callable[..., object]]] = [ + ("service-levels.json", ServiceLevels.from_dict), + ("receipt-encode.json", Receipt.from_dict), + ("receipt-generate.json", Receipt.from_dict), + ("boot-evidence.json", BootEvidence.from_dict), + ("price-list.json", PriceList.from_dict), + ("demand.json", Demand.from_dict), + ("plan.json", Plan.from_dict), +] + + +def load(name: str) -> dict: + return json.loads((FIXTURES / name).read_text(encoding="utf-8")) + + +def schema_error(parse: Callable[[dict], object], data: dict) -> SchemaError: + with pytest.raises(SchemaError) as caught: + parse(data) + return caught.value + + +@pytest.mark.parametrize(("name", "parse"), DOCUMENTS) +def test_canonical_documents_round_trip(name, parse): + data = load(name) + document = parse(data) + assert document.to_dict() == data + assert json.dumps(document.to_dict()) == json.dumps(data) + assert parse(json.loads(json.dumps(document.to_dict()))) == document + + +@pytest.mark.parametrize(("name", "parse"), DOCUMENTS) +def test_documents_reject_another_kind(name, parse): + data = load(name) + data["kind"] = "placement-other" + error = schema_error(parse, data) + assert error.path == "$.kind" + assert "expected 'placement-" in error.message + + +@pytest.mark.parametrize(("name", "parse"), DOCUMENTS) +def test_documents_reject_unsupported_versions(name, parse): + data = load(name) + data["schemaVersion"] = 2 + error = schema_error(parse, data) + assert str(error) == "$.schemaVersion: unsupported version 2; this reader supports version 1" + + +@pytest.mark.parametrize(("name", "parse"), DOCUMENTS) +def test_documents_require_a_version(name, parse): + data = load(name) + del data["schemaVersion"] + assert str(schema_error(parse, data)) == "$.schemaVersion: is required" + + +@pytest.mark.parametrize(("name", "parse"), DOCUMENTS) +def test_documents_reject_unknown_top_level_fields(name, parse): + data = load(name) + data["notes"] = "free text" + assert str(schema_error(parse, data)) == "$.notes: is not a field of this object" + + +@pytest.mark.parametrize("value", [[], "receipt", 1, None]) +def test_documents_must_be_objects(value): + error = schema_error(Receipt.from_dict, value) + assert error.path == "$" + assert error.message.startswith("expected an object, got ") + + +def test_nested_unknown_fields_are_reported_at_their_path(): + data = load("receipt-encode.json") + data["cell"]["gpuType"] = "nvidia-l4" + assert str(schema_error(Receipt.from_dict, data)) == "$.cell.gpuType: is not a field of this object" + + +def test_missing_nested_fields_are_reported_at_their_path(): + data = load("plan.json") + del data["lanes"][1]["containerShape"]["memoryMiB"] + assert str(schema_error(Plan.from_dict, data)) == "$.lanes[1].containerShape.memoryMiB: is required" + + +def test_null_is_never_a_value(): + data = load("receipt-encode.json") + data["latency"]["p50Ms"] = None + assert str(schema_error(Receipt.from_dict, data)) == "$.latency.p50Ms: must be omitted rather than null" + data = load("receipt-encode.json") + data["concurrency"] = None + assert str(schema_error(Receipt.from_dict, data)) == "$.concurrency: must not be null" + + +@pytest.mark.parametrize(("value", "described"), [(True, "boolean true"), (16.0, "number 16.0"), ("16", "string '16'")]) +def test_integers_are_strict(value, described): + data = load("receipt-encode.json") + data["concurrency"] = value + assert str(schema_error(Receipt.from_dict, data)) == f"$.concurrency: expected an integer, got {described}" + + +@pytest.mark.parametrize("value", [math.nan, math.inf]) +def test_numbers_must_be_finite(value): + data = load("receipt-encode.json") + data["throughput"]["requestsPerSecond"] = value + error = schema_error(Receipt.from_dict, data) + assert error.path == "$.throughput.requestsPerSecond" + assert error.message.startswith("expected a finite number") + + +def test_numbers_reject_booleans(): + data = load("price-list.json") + data["placements"][0]["regionMultiplier"] = False + assert ( + str(schema_error(PriceList.from_dict, data)) + == "$.placements[0].regionMultiplier: expected a number, got boolean false" + ) + + +def test_enumerations_list_their_choices(): + data = load("plan.json") + data["identities"][0]["warmth"] = "warm" + error = schema_error(Plan.from_dict, data) + assert error.path == "$.identities[0].warmth" + assert error.message == ( + "expected one of 'pinned', 'cold-with-bound', 'bridged', 'snapshot-cold', 'scheduled-warm', " + "'lazy-resident', got 'warm'" + ) + + +def test_arrays_are_required_where_declared(): + data = load("plan.json") + data["lanes"] = {"default-l4-default": {}} + assert str(schema_error(Plan.from_dict, data)) == "$.lanes: expected an array, got an object" + + +@pytest.mark.parametrize("value", ["", "two words", "trailing\n"]) +def test_identifiers_reject_empty_and_whitespace(value): + data = load("receipt-encode.json") + data["identity"] = value + error = schema_error(Receipt.from_dict, data) + assert error.path == "$.identity" + assert error.message.startswith("must be a non-empty string without whitespace") + + +def test_service_levels_resolve_tier_defaults_and_overrides(): + levels = ServiceLevels.from_dict(load("service-levels.json")) + assert levels.effective("BAAI/bge-m3") == ServiceLevel(come_alive_p95_s=0, warm_p99_ms=250, queue_wait_p99_ms=500) + assert levels.effective("BAAI/bge-m3:sparse").come_alive_p95_s == 120 + generation = levels.effective("Qwen/Qwen3-8B") + assert generation.is_generation + assert (generation.ttft_p99_ms, generation.itl_p99_ms) == (4000, 80) + assert levels.effective("Qwen/Qwen3-Reranker-0.6B") == ServiceLevel(come_alive_p95_s=90, warm_p99_ms=400) + with pytest.raises(KeyError): + levels.effective("unknown/model") + + +def test_service_levels_omit_an_empty_tier_list(): + data = load("service-levels.json") + data["tiers"] = [] + data["identities"] = [{"identity": "BAAI/bge-m3", "warmP99Ms": 200}] + assert ServiceLevels.from_dict(data).to_dict() == { + "kind": "placement-service-levels", + "schemaVersion": 1, + "identities": [{"identity": "BAAI/bge-m3", "warmP99Ms": 200}], + } + + +def test_generation_identities_do_not_declare_a_warm_latency(): + data = load("service-levels.json") + data["identities"][3] = {"identity": "Qwen/Qwen3-8B-Chat", "warmP99Ms": 300, "ttftP99Ms": 900, "itlP99Ms": 60} + error = schema_error(ServiceLevels.from_dict, data) + assert error.path == "$.identities[3].warmP99Ms" + assert "generation identity" in error.message + + +def test_a_generation_override_cannot_join_a_warm_latency_tier(): + data = load("service-levels.json") + data["identities"][0]["ttftP99Ms"] = 900 + data["identities"][0]["itlP99Ms"] = 60 + error = schema_error(ServiceLevels.from_dict, data) + assert error.path == "$.identities[0].warmP99Ms" + + +def test_generation_latencies_are_declared_together(): + data = load("service-levels.json") + data["identities"][3] = {"identity": "Qwen/Qwen3-8B-Chat", "ttftP99Ms": 900} + assert ( + str(schema_error(ServiceLevels.from_dict, data)) + == "$.identities[3].itlP99Ms: ttftP99Ms and itlP99Ms are declared together" + ) + data = load("service-levels.json") + del data["tiers"][1]["itlP99Ms"] + assert ( + str(schema_error(ServiceLevels.from_dict, data)) + == "$.tiers[1].itlP99Ms: ttftP99Ms and itlP99Ms are declared together" + ) + + +def test_service_level_tiers_must_exist_and_names_must_be_unique(): + data = load("service-levels.json") + data["identities"][0]["tier"] = "realtime" + assert ( + str(schema_error(ServiceLevels.from_dict, data)) == "$.identities[0].tier: names no declared tier: 'realtime'" + ) + data = load("service-levels.json") + data["identities"][2]["identity"] = "BAAI/bge-m3" + assert str(schema_error(ServiceLevels.from_dict, data)) == "$.identities[2].identity: duplicates 'BAAI/bge-m3'" + data = load("service-levels.json") + data["tiers"][1]["name"] = "interactive-retrieval" + assert str(schema_error(ServiceLevels.from_dict, data)) == "$.tiers[1].name: duplicates 'interactive-retrieval'" + + +def test_service_level_bounds_are_non_negative(): + data = load("service-levels.json") + data["identities"][3]["comeAliveP95S"] = -1 + assert ( + str(schema_error(ServiceLevels.from_dict, data)) == "$.identities[3].comeAliveP95S: must be at least 0, got -1" + ) + + +def test_generate_receipts_report_ttft_and_itl(): + data = load("receipt-generate.json") + data["latency"] = data.pop("ttft") + error = schema_error(Receipt.from_dict, data) + assert error.path == "$.latency" + assert error.message.startswith("must be omitted for the generate operation") + data = load("receipt-generate.json") + del data["itl"] + assert str(schema_error(Receipt.from_dict, data)) == "$.itl: is required for the generate operation" + + +def test_other_receipts_report_one_latency(): + data = load("receipt-encode.json") + data["ttft"] = data.pop("latency") + assert str(schema_error(Receipt.from_dict, data)) == "$.latency: is required for an operation other than generate" + data = load("receipt-encode.json") + data["throughput"]["outputTokensPerSecond"] = 10 + error = schema_error(Receipt.from_dict, data) + assert error.path == "$.throughput.outputTokensPerSecond" + + +def test_request_shapes_tie_output_tokens_to_generation(): + data = load("receipt-generate.json") + del data["requestShape"]["outputTokens"] + assert ( + str(schema_error(Receipt.from_dict, data)) + == "$.requestShape.outputTokens: is required for the generate operation" + ) + data = load("receipt-encode.json") + data["requestShape"]["outputTokens"] = 32 + error = schema_error(Receipt.from_dict, data) + assert error.path == "$.requestShape.outputTokens" + assert error.message.startswith("must be omitted") + + +def test_receipt_shapes_and_rates_are_bounded(): + data = load("receipt-encode.json") + data["containerShape"]["gpuCount"] = 0 + assert str(schema_error(Receipt.from_dict, data)) == "$.containerShape.gpuCount: must be at least 1, got 0" + data = load("receipt-encode.json") + data["throughput"]["requestsPerSecond"] = 0 + assert str(schema_error(Receipt.from_dict, data)) == "$.throughput.requestsPerSecond: must be greater than 0, got 0" + data = load("receipt-encode.json") + data["concurrency"] = 0 + assert str(schema_error(Receipt.from_dict, data)) == "$.concurrency: must be at least 1, got 0" + + +def test_percentiles_are_ordered(): + data = load("receipt-encode.json") + data["latency"]["p95Ms"] = 300 + assert str(schema_error(Receipt.from_dict, data)) == "$.latency.p99Ms: must be at least p95Ms (300), got 214" + data = load("receipt-generate.json") + data["ttft"]["p50Ms"] = 2000 + assert str(schema_error(Receipt.from_dict, data)) == "$.ttft.p99Ms: must be at least p50Ms (2000), got 1480" + + +def test_source_digests_are_sha256_hex(): + data = load("receipt-encode.json") + data["source"]["sha256"] = data["source"]["sha256"].upper() + error = schema_error(Receipt.from_dict, data) + assert error.path == "$.source.sha256" + + +def test_boot_evidence_records_only_booting_warmths(): + data = load("boot-evidence.json") + data["warmth"] = "pinned" + assert str(schema_error(BootEvidence.from_dict, data)) == ( + "$.warmth: boot evidence records one of 'cold-with-bound', 'snapshot-cold', 'lazy-resident', got 'pinned'" + ) + + +def test_boot_evidence_keeps_failed_outcomes(): + data = load("boot-evidence.json") + data["outcome"] = "timed-out" + data["bootSeconds"] = 900 + evidence = BootEvidence.from_dict(data) + assert evidence.outcome.value == "timed-out" + assert evidence.to_dict() == data + data["bootSeconds"] = -0.5 + assert str(schema_error(BootEvidence.from_dict, data)) == "$.bootSeconds: must be at least 0, got -0.5" + + +def test_price_lists_validate_currency_rates_and_names(): + data = load("price-list.json") + data["currency"] = "usd" + assert schema_error(PriceList.from_dict, data).path == "$.currency" + data = load("price-list.json") + data["machineProfiles"][1]["name"] = "l4" + assert str(schema_error(PriceList.from_dict, data)) == "$.machineProfiles[1].name: duplicates 'l4'" + data = load("price-list.json") + data["machineProfiles"][0]["corePerHour"] = -0.01 + assert ( + str(schema_error(PriceList.from_dict, data)) + == "$.machineProfiles[0].corePerHour: must be at least 0, got -0.01" + ) + data = load("price-list.json") + data["placements"][1]["regionMultiplier"] = 0 + assert ( + str(schema_error(PriceList.from_dict, data)) + == "$.placements[1].regionMultiplier: must be greater than 0, got 0" + ) + data = load("price-list.json") + data["placements"] = [] + assert str(schema_error(PriceList.from_dict, data)) == "$.placements: must list at least one placement" + + +@pytest.mark.parametrize( + "value", ["2026-11-02T09:30:00Z", "2026-11-02T09:00:00+00:00", "2026-11-02 09:00:00Z", "2026-02-30T09:00:00Z"] +) +def test_demand_hours_are_utc_hour_boundaries(value): + data = load("demand.json") + data["series"][0]["hours"][0]["start"] = value + error = schema_error(Demand.from_dict, data) + assert error.path == "$.series[0].hours[0].start" + + +def test_demand_hours_are_ordered_and_inside_the_window(): + data = load("demand.json") + data["series"][0]["hours"].reverse() + assert ( + str(schema_error(Demand.from_dict, data)) == "$.series[0].hours[1].start: must be later than the previous hour" + ) + data = load("demand.json") + data["series"][1]["hours"][0]["start"] = "2026-11-03T00:00:00Z" + assert str(schema_error(Demand.from_dict, data)) == ( + "$.series[1].hours[0].start: must fall inside the window [2026-11-02T00:00:00Z, 2026-11-03T00:00:00Z)" + ) + data = load("demand.json") + data["end"] = data["start"] + assert str(schema_error(Demand.from_dict, data)) == "$.end: must be later than start" + + +def test_demand_series_are_unique_per_identity_and_operation(): + data = load("demand.json") + data["series"].append(copy.deepcopy(data["series"][0])) + assert str(schema_error(Demand.from_dict, data)) == "$.series[2].identity: duplicates 'BAAI/bge-m3 encode'" + data["series"][2]["operation"] = "score" + assert len(Demand.from_dict(data).series) == 3 + + +def test_demand_hours_built_in_code_must_be_utc_boundaries(): + with pytest.raises(SchemaError, match="UTC hour boundary"): + DemandHour(start=datetime(2026, 11, 2, 9, 30, tzinfo=UTC), requests=1) + with pytest.raises(SchemaError, match="UTC hour boundary"): + DemandHour(start=datetime(2026, 11, 2, 9, tzinfo=timezone(timedelta(hours=1))), requests=1) + with pytest.raises(SchemaError, match="UTC hour boundary"): + DemandHour(start=datetime(2026, 11, 2, 9), requests=1) # noqa: DTZ001 + hour = DemandHour(start=datetime(2026, 11, 2, 9, tzinfo=UTC), requests=4) + series = DemandSeries(identity="BAAI/bge-m3", operation=Operation.ENCODE, hours=(hour,)) + demand = Demand(start=hour.start, end=hour.start + timedelta(hours=1), series=(series,)) + assert Demand.from_dict(demand.to_dict()) == demand + + +@pytest.mark.parametrize( + ("envelope", "path", "message"), + [ + ({"floorMin": 2, "floorMax": 1}, "floorMax", "must be at least floorMin (2), got 1"), + ({"floorMin": -1, "floorMax": 1}, "floorMin", "must be at least 0, got -1"), + ({"floorMin": 0, "floorMax": 1, "bufferMin": 0}, "bufferMax", "bufferMin and bufferMax are declared together"), + ( + {"floorMin": 0, "floorMax": 1, "bufferMin": 2, "bufferMax": 1}, + "bufferMax", + "must be at least bufferMin (2), got 1", + ), + ( + {"floorMin": 0, "floorMax": 1, "scaledownWindowMaxS": 60}, + "scaledownWindowMinS", + "scaledownWindowMinS and scaledownWindowMaxS are declared together", + ), + ( + {"floorMin": 0, "floorMax": 1, "scaledownWindowMinS": 600, "scaledownWindowMaxS": 60}, + "scaledownWindowMaxS", + "must be at least scaledownWindowMinS (600), got 60", + ), + ], +) +def test_envelopes_are_ordered_ranges(envelope, path, message): + error = schema_error(Envelope.from_dict, envelope) + assert error.path == f"$.{path}" + assert error.message == message + + +def test_envelope_ranges_are_optional_for_floor_only_appliers(): + envelope = Envelope.from_dict({"floorMin": 0, "floorMax": 2}) + assert envelope.buffer_min is None + assert envelope.scaledown_window_max_s is None + assert envelope.to_dict() == {"floorMin": 0, "floorMax": 2} + + +def test_plan_envelopes_stay_under_the_lane_ceiling(): + data = load("plan.json") + data["lanes"][0]["maxContainers"] = 2 + assert str(schema_error(Plan.from_dict, data)) == ( + "$.lanes[0].envelope.floorMax: must not exceed maxContainers (2), got 3" + ) + + +def test_plan_identities_name_a_lane_of_the_plan(): + data = load("plan.json") + data["identities"][2]["lane"] = "default-h100-generation" + assert str(schema_error(Plan.from_dict, data)) == ( + "$.identities[2].lane: names no lane of this plan: 'default-h100-generation'" + ) + + +def test_plan_lanes_host_an_identity(): + data = load("plan.json") + del data["identities"][2] + assert str(schema_error(Plan.from_dict, data)) == ( + "$.lanes[1].name: lane 'default-a100-80gb-generation' hosts no identity" + ) + + +@pytest.mark.parametrize( + ("index", "warmth", "expectation"), + [ + (0, "cold-with-bound", "floorMin 0, got 1"), + (1, "snapshot-cold", "floorMin 0, got 1"), + (2, "pinned", "floorMin at least 1, got 0"), + (2, "lazy-resident", "floorMin at least 1, got 0"), + ], +) +def test_plan_warmth_matches_the_lane_floor(index, warmth, expectation): + data = load("plan.json") + data["identities"][index]["warmth"] = warmth + error = schema_error(Plan.from_dict, data) + assert error.path == f"$.identities[{index}].warmth" + assert error.message.startswith(f"{warmth} needs lane ") + assert error.message.endswith(expectation) + + +@pytest.mark.parametrize("warmth", ["bridged", "scheduled-warm", "snapshot-cold"]) +def test_plan_accepts_every_zero_floor_warmth(warmth): + data = load("plan.json") + data["identities"][2]["warmth"] = warmth + assert Plan.from_dict(data).identities[2].warmth.value == warmth + + +def test_plan_lane_names_and_identities_are_unique(): + data = load("plan.json") + data["lanes"][1]["name"] = "default-l4-default" + assert str(schema_error(Plan.from_dict, data)) == "$.lanes[1].name: duplicates 'default-l4-default'" + data = load("plan.json") + data["identities"][1]["identity"] = "BAAI/bge-m3" + assert str(schema_error(Plan.from_dict, data)) == "$.identities[1].identity: duplicates 'BAAI/bge-m3'" + + +def test_documents_built_in_code_report_relative_paths(): + with pytest.raises(SchemaError) as caught: + Envelope(floor_min=3, floor_max=1) + assert caught.value.path == "floorMax" + with pytest.raises(SchemaError) as caught: + IdentityServiceLevel(identity="model", level=ServiceLevel(ttft_p99_ms=1, warm_p99_ms=1)) + assert caught.value.path == "warmP99Ms" + with pytest.raises(SchemaError) as caught: + Percentiles(p50_ms=5, p99_ms=1) + assert str(caught.value) == "p99Ms: must be at least p50Ms (5), got 1" + + +def test_plans_built_in_code_round_trip(): + cell = Cell(machine_profile="l4", gpu_product="NVIDIA-L4") + shape = ContainerShape(gpu_count=1, cpu_cores=4, memory_mib=16384) + lane = PlanLane( + name="default-l4-default", + pool="default", + bundle="default", + cell=cell, + container_shape=shape, + concurrency=8, + max_containers=4, + envelope=Envelope(floor_min=1, floor_max=2), + ) + plan = Plan( + placement="us-central1", + lanes=(lane,), + identities=(PlanIdentity(identity="BAAI/bge-m3", lane=lane.name, warmth=Warmth.PINNED),), + ) + assert Plan.from_dict(json.loads(json.dumps(plan.to_dict()))) == plan diff --git a/pyproject.toml b/pyproject.toml index 0d4371428..7dab46203 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,6 +53,7 @@ torchvision = [ sie-audio-prep = { workspace = true } sie-config = { workspace = true } sie-mcp = { workspace = true } +sie-placement = { workspace = true } sie-sdk = { workspace = true } sie-server = { workspace = true } @@ -63,6 +64,7 @@ members = [ "packages/sie_audio_prep", "packages/sie_config", "packages/sie_mcp", + "packages/sie_placement", "packages/sie_sdk", "packages/sie_server", "integrations/sie_chroma", @@ -83,6 +85,7 @@ testpaths = [ "packages/sie_audio_prep/tests", "packages/sie_config/tests", "packages/sie_mcp/tests", + "packages/sie_placement/tests", "packages/sie_sdk/tests", "packages/sie_server/tests", ] diff --git a/tools/mise_tasks/lint.bash b/tools/mise_tasks/lint.bash index fa8531aac..f3d5fb421 100755 --- a/tools/mise_tasks/lint.bash +++ b/tools/mise_tasks/lint.bash @@ -8,6 +8,7 @@ PUBLIC_PATHS=( packages/sie_audio_prep packages/sie_config packages/sie_mcp + packages/sie_placement packages/sie_sdk packages/sie_server integrations diff --git a/tools/mise_tasks/typecheck.bash b/tools/mise_tasks/typecheck.bash index ec09e0fa4..6f397d0ab 100755 --- a/tools/mise_tasks/typecheck.bash +++ b/tools/mise_tasks/typecheck.bash @@ -10,6 +10,7 @@ else PATHS_TO_CHECK=( packages/sie_config packages/sie_mcp + packages/sie_placement packages/sie_sdk packages/sie_server ) diff --git a/uv.lock b/uv.lock index 78041689d..d07c8964a 100644 --- a/uv.lock +++ b/uv.lock @@ -21,6 +21,7 @@ members = [ "sie-langchain", "sie-llamaindex", "sie-mcp", + "sie-placement", "sie-qdrant", "sie-sdk", "sie-server", @@ -4760,6 +4761,21 @@ dev = [ { name = "pytest-asyncio", specifier = ">=1.0" }, ] +[[package]] +name = "sie-placement" +version = "0.0.0" +source = { editable = "packages/sie_placement" } + +[package.dev-dependencies] +dev = [ + { name = "pytest" }, +] + +[package.metadata] + +[package.metadata.requires-dev] +dev = [{ name = "pytest", specifier = ">=9.0.3" }] + [[package]] name = "sie-qdrant" version = "0.11.0" From ac80e65a24fead645b687a225881de6e6b021e13 Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Wed, 4 Nov 2026 22:09:41 +0100 Subject: [PATCH 02/16] fix(placement): keep number and hour parsing inside the schema contract An integer beyond the float range in a number field raised OverflowError from math.isfinite instead of a path-qualified SchemaError. Report it as a non-finite number at its JSON path. UTC hours matched any Unicode digit, so an hour written in non-ASCII digits parsed and then serialized differently. Match ASCII digits only, and format the hour explicitly so a year below 1000 keeps four digits on every platform's strftime. --- .../sie_placement/src/sie_placement/schema.py | 11 ++++++---- packages/sie_placement/tests/test_schema.py | 21 +++++++++++++++++-- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/packages/sie_placement/src/sie_placement/schema.py b/packages/sie_placement/src/sie_placement/schema.py index 3171da492..533b0b3bd 100644 --- a/packages/sie_placement/src/sie_placement/schema.py +++ b/packages/sie_placement/src/sie_placement/schema.py @@ -23,8 +23,7 @@ _SHA256 = re.compile(r"[0-9a-f]{64}") _CURRENCY = re.compile(r"[A-Z]{3}") -_HOUR = re.compile(r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):00:00Z") -_HOUR_FORMAT = "%Y-%m-%dT%H:00:00Z" +_HOUR = re.compile(r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):00:00Z", re.ASCII) class SchemaError(ValueError): @@ -91,7 +90,7 @@ def _describe(value: object) -> str: def _format_hour(value: datetime) -> str: - return value.strftime(_HOUR_FORMAT) + return f"{value.year:04d}-{value.month:02d}-{value.day:02d}T{value.hour:02d}:00:00Z" def _compact(fields: dict[str, object | None]) -> dict[str, object]: @@ -144,7 +143,11 @@ def _integer(self, key: str, value: object) -> int: def _number(self, key: str, value: object) -> float: if isinstance(value, bool) or not isinstance(value, int | float): raise SchemaError(self._at(key), f"expected a number, got {_describe(value)}") - if not math.isfinite(value): + try: + finite = math.isfinite(value) + except OverflowError: + raise SchemaError(self._at(key), "expected a finite number, got an integer beyond the float range") from None + if not finite: raise SchemaError(self._at(key), f"expected a finite number, got {value!r}") return value diff --git a/packages/sie_placement/tests/test_schema.py b/packages/sie_placement/tests/test_schema.py index 609455835..39833b128 100644 --- a/packages/sie_placement/tests/test_schema.py +++ b/packages/sie_placement/tests/test_schema.py @@ -128,7 +128,11 @@ def test_integers_are_strict(value, described): assert str(schema_error(Receipt.from_dict, data)) == f"$.concurrency: expected an integer, got {described}" -@pytest.mark.parametrize("value", [math.nan, math.inf]) +@pytest.mark.parametrize( + "value", + [math.nan, math.inf, json.loads("1" + "0" * 400), -(10**400)], + ids=["nan", "infinity", "integer-above-float-range", "integer-below-float-range"], +) def test_numbers_must_be_finite(value): data = load("receipt-encode.json") data["throughput"]["requestsPerSecond"] = value @@ -355,7 +359,14 @@ def test_price_lists_validate_currency_rates_and_names(): @pytest.mark.parametrize( - "value", ["2026-11-02T09:30:00Z", "2026-11-02T09:00:00+00:00", "2026-11-02 09:00:00Z", "2026-02-30T09:00:00Z"] + "value", + [ + "2026-11-02T09:30:00Z", + "2026-11-02T09:00:00+00:00", + "2026-11-02 09:00:00Z", + "2026-02-30T09:00:00Z", + "٢٠٢٦-11-02T09:00:00Z", + ], ) def test_demand_hours_are_utc_hour_boundaries(value): data = load("demand.json") @@ -401,6 +412,12 @@ def test_demand_hours_built_in_code_must_be_utc_boundaries(): assert Demand.from_dict(demand.to_dict()) == demand +def test_demand_hours_serialize_four_digit_years(): + hour = DemandHour(start=datetime(999, 1, 1, 7, tzinfo=UTC), requests=1) + assert hour.to_dict()["start"] == "0999-01-01T07:00:00Z" + assert DemandHour.from_dict(hour.to_dict()) == hour + + @pytest.mark.parametrize( ("envelope", "path", "message"), [ From a3f9193a1608d7c36525d49f0f9a7c57ace450ff Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Wed, 4 Nov 2026 22:10:43 +0100 Subject: [PATCH 03/16] fix(placement): name the plan lane's queue pool queuePool The plan lane's `pool` field was ambiguous: in the sie-cluster chart a pool is a worker group (`workers.pools.`), while a lane is named by its queuePool, machineProfile and bundle tokens. Rename the wire key to `queuePool`, the chart's lane token, and document the three tokens and how they differ from the worker group key and an SDK logical pool. --- packages/sie_placement/README.md | 11 +++++++++++ packages/sie_placement/src/sie_placement/schema.py | 8 ++++---- packages/sie_placement/tests/fixtures/plan.json | 4 ++-- packages/sie_placement/tests/test_schema.py | 2 +- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index cf72c6183..8915201cd 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -64,6 +64,17 @@ or more; every other warmth sits on a lane whose `floorMin` is 0. Boot evidence records `cold-with-bound` boots, `snapshot-cold` restores and `lazy-resident` loads, with outcome `succeeded`, `failed` or `timed-out`. +## Lanes + +A plan lane carries the three tokens that name a lane of the `sie-cluster` +Helm chart: `queuePool`, the `machineProfile` of its `cell`, and `bundle`. +`queuePool` is the physical queue pool the lane's workers consume: +`workers.common.queuePool` (`default`), or a worker group's `queuePool` +override. It is neither the `workers.pools` map key, which names a worker +group, nor an SDK logical pool. `bundle` is a key of that worker group's `bundles` map. `name` +is the lane's handle inside the plan, and each identity refers to its lane by +that name. + ## Envelope A plan lane's envelope bounds what an online tuner may change without a new diff --git a/packages/sie_placement/src/sie_placement/schema.py b/packages/sie_placement/src/sie_placement/schema.py index 533b0b3bd..2acffb7c5 100644 --- a/packages/sie_placement/src/sie_placement/schema.py +++ b/packages/sie_placement/src/sie_placement/schema.py @@ -936,7 +936,7 @@ def to_dict(self) -> dict[str, object]: @dataclass(frozen=True, slots=True, kw_only=True) class PlanLane: name: str - pool: str + queue_pool: str bundle: str cell: Cell container_shape: ContainerShape @@ -946,7 +946,7 @@ class PlanLane: def __post_init__(self) -> None: _require_identifier("name", self.name) - _require_identifier("pool", self.pool) + _require_identifier("queuePool", self.queue_pool) _require_identifier("bundle", self.bundle) _require_at_least("concurrency", self.concurrency, 1) _require_at_least("maxContainers", self.max_containers, 1) @@ -962,7 +962,7 @@ def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: return reader.build( cls, name=reader.string("name"), - pool=reader.string("pool"), + queue_pool=reader.string("queuePool"), bundle=reader.string("bundle"), cell=reader.child("cell", Cell.from_dict), container_shape=reader.child("containerShape", ContainerShape.from_dict), @@ -974,7 +974,7 @@ def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: def to_dict(self) -> dict[str, object]: return { "name": self.name, - "pool": self.pool, + "queuePool": self.queue_pool, "bundle": self.bundle, "cell": self.cell.to_dict(), "containerShape": self.container_shape.to_dict(), diff --git a/packages/sie_placement/tests/fixtures/plan.json b/packages/sie_placement/tests/fixtures/plan.json index cc601e491..ed9a2f5fa 100644 --- a/packages/sie_placement/tests/fixtures/plan.json +++ b/packages/sie_placement/tests/fixtures/plan.json @@ -5,7 +5,7 @@ "lanes": [ { "name": "default-l4-default", - "pool": "default", + "queuePool": "default", "bundle": "default", "cell": { "machineProfile": "l4", @@ -29,7 +29,7 @@ }, { "name": "default-a100-80gb-generation", - "pool": "default", + "queuePool": "default", "bundle": "generation", "cell": { "machineProfile": "a100-80gb", diff --git a/packages/sie_placement/tests/test_schema.py b/packages/sie_placement/tests/test_schema.py index 39833b128..2ca86915c 100644 --- a/packages/sie_placement/tests/test_schema.py +++ b/packages/sie_placement/tests/test_schema.py @@ -529,7 +529,7 @@ def test_plans_built_in_code_round_trip(): shape = ContainerShape(gpu_count=1, cpu_cores=4, memory_mib=16384) lane = PlanLane( name="default-l4-default", - pool="default", + queue_pool="default", bundle="default", cell=cell, container_shape=shape, From 2ccf70dcb6d577394b462f33add040c43f9d249a Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Wed, 4 Nov 2026 22:10:47 +0100 Subject: [PATCH 04/16] docs(placement): state how telemetry route labels fold into operations Receipts and demand name the work primitive a lane runs, while gateway telemetry labels requests by route. Document the fold an adapter applies: `embeddings` is rewritten into an encode request and counts as `encode`, `moderations` answers 501 without serving a model and carries no demand, and `other` names no primitive. Also describe the service level fields without a fixed count, since a generation identity declares four. --- packages/sie_placement/README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index 8915201cd..38c5a069c 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -43,9 +43,20 @@ with open("plan.json", encoding="utf-8") as handle: assert Plan.from_dict(plan.to_dict()) == plan ``` +## Operations + +Receipts and demand name the primitive a lane runs: `encode`, `score`, +`extract` or `generate`. Gateway telemetry labels requests by route and +already reports the generation and transcription routes as `generate` and +`extract`. An adapter folds the remaining route labels the same way: +`embeddings`, the OpenAI-compatible route that the gateway rewrites into an +encode request, counts as `encode`; `moderations` answers 501 without serving +a model, so it carries no demand to place; `other` names no primitive and is +not assigned to one. + ## Service levels -An identity declares up to three numbers, or inherits them from the tier it +An identity declares the fields below, or inherits them from the tier it names. Fields it declares override the tier's. | Field | Meaning | From a516e71c516f7285b68462014d7f648b52a42b7c Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Wed, 4 Nov 2026 22:11:13 +0100 Subject: [PATCH 05/16] style(placement): format the float-range number check --- packages/sie_placement/src/sie_placement/schema.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/sie_placement/src/sie_placement/schema.py b/packages/sie_placement/src/sie_placement/schema.py index 2acffb7c5..410d6cf7e 100644 --- a/packages/sie_placement/src/sie_placement/schema.py +++ b/packages/sie_placement/src/sie_placement/schema.py @@ -146,7 +146,9 @@ def _number(self, key: str, value: object) -> float: try: finite = math.isfinite(value) except OverflowError: - raise SchemaError(self._at(key), "expected a finite number, got an integer beyond the float range") from None + raise SchemaError( + self._at(key), "expected a finite number, got an integer beyond the float range" + ) from None if not finite: raise SchemaError(self._at(key), f"expected a finite number, got {value!r}") return value From c7c9aff697e47a728e036b5c586a5032e7a9cf5e Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Wed, 4 Nov 2026 22:12:09 +0100 Subject: [PATCH 06/16] docs(placement): rewrap the lanes paragraph --- packages/sie_placement/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index 38c5a069c..2e434f900 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -82,9 +82,9 @@ Helm chart: `queuePool`, the `machineProfile` of its `cell`, and `bundle`. `queuePool` is the physical queue pool the lane's workers consume: `workers.common.queuePool` (`default`), or a worker group's `queuePool` override. It is neither the `workers.pools` map key, which names a worker -group, nor an SDK logical pool. `bundle` is a key of that worker group's `bundles` map. `name` -is the lane's handle inside the plan, and each identity refers to its lane by -that name. +group, nor an SDK logical pool. `bundle` is a key of that worker group's +`bundles` map. `name` is the lane's handle inside the plan, and each identity +refers to its lane by that name. ## Envelope From 2800e5232e633d672c328e3d9ebbe6e1ea0d22aa Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Thu, 5 Nov 2026 01:15:27 +0100 Subject: [PATCH 07/16] feat(placement): add the measured-only planner core and its cost report Add sie_placement.planner.plan, a pure function from service levels, receipts, boot evidence, a price list, demand, the current plan and planner parameters to a plan and a report: - refuse receipts and boot evidence whose realized GPU product differs from the product their machine profile requests or whose profile has no price, and receipts whose latency cannot answer the identity's service level - block cells that miss the warm bounds; offer pinned, and cold-with-bound or snapshot-cold where boot evidence exists, with the slowest successful boot standing for the come-alive percentile, the environment's own evidence replacing borrowed evidence, and a comeAliveP95S of 0 admitting pinned only - price at list times the region multiplier: one warm container plus the above-floor hours demand needs, or the work plus a burst tail held at the active floor for the cooldown; the fallback floor, cooldown, ceiling and buffer are parameters - set the envelope floorMax to floorMin plus the declared buffer while queue wait is unmeasured, at realizable floors and capped by the reviewed ceiling - report per identity the chosen cell, warmth, monthly cost and come-alive basis, and the nearest cheaper blocked option with the bounds that block it; per lane the floor and envelope-maximum cost; measurement requests ranked by their price-bounded saving; come-alive levers priced under the identity's bound and at the bound their measured come-alive permits; unattained queue-wait bounds; refusals; and the changes against the current plan Boot evidence gains an optional borrowed flag. The rendered plan and report are byte-stable under input reordering, and replanning over the plan the planner wrote reports no change. Each identity gets its own lane; co-packing is not part of this change. --- packages/sie_placement/README.md | 116 ++- .../src/sie_placement/planner.py | 763 +++++++++++++++ .../sie_placement/src/sie_placement/report.py | 318 +++++++ .../sie_placement/src/sie_placement/schema.py | 36 +- .../tests/fixtures/planner/boot-evidence.json | 213 +++++ .../tests/fixtures/planner/current-plan.json | 64 ++ .../tests/fixtures/planner/demand.json | 114 +++ .../tests/fixtures/planner/expected-plan.json | 134 +++ .../fixtures/planner/expected-report.json | 698 ++++++++++++++ .../tests/fixtures/planner/price-list.json | 45 + .../tests/fixtures/planner/receipts.json | 295 ++++++ .../fixtures/planner/service-levels.json | 48 + packages/sie_placement/tests/test_levers.py | 215 +++++ packages/sie_placement/tests/test_planner.py | 893 ++++++++++++++++++ packages/sie_placement/tests/test_schema.py | 20 + 15 files changed, 3960 insertions(+), 12 deletions(-) create mode 100644 packages/sie_placement/src/sie_placement/planner.py create mode 100644 packages/sie_placement/src/sie_placement/report.py create mode 100644 packages/sie_placement/tests/fixtures/planner/boot-evidence.json create mode 100644 packages/sie_placement/tests/fixtures/planner/current-plan.json create mode 100644 packages/sie_placement/tests/fixtures/planner/demand.json create mode 100644 packages/sie_placement/tests/fixtures/planner/expected-plan.json create mode 100644 packages/sie_placement/tests/fixtures/planner/expected-report.json create mode 100644 packages/sie_placement/tests/fixtures/planner/price-list.json create mode 100644 packages/sie_placement/tests/fixtures/planner/receipts.json create mode 100644 packages/sie_placement/tests/fixtures/planner/service-levels.json create mode 100644 packages/sie_placement/tests/test_levers.py create mode 100644 packages/sie_placement/tests/test_planner.py diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index 2e434f900..643684cc7 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -3,7 +3,8 @@ Versioned documents for a measured-only placement planner: the service level each served identity must meet, the measurements a placement may be chosen from, the prices those placements cost, the demand they serve, and the plan -that results. The package uses only the Python standard library. It is a +that results, together with the planner that turns them into a plan and a cost +report. The package uses only the Python standard library. It is a workspace package and is not published to PyPI. A served identity is a model id or a `model:profile` pair, the routing key a @@ -74,6 +75,10 @@ A plan gives every identity one warmth: `pinned`, `cold-with-bound`, or more; every other warmth sits on a lane whose `floorMin` is 0. Boot evidence records `cold-with-bound` boots, `snapshot-cold` restores and `lazy-resident` loads, with outcome `succeeded`, `failed` or `timed-out`. +`borrowed: true` marks a boot measured in another environment whose +boot-shaping inputs match: the identity and its model revision, the image, the +realized GPU product and count, the container shape, the warmth and the +placement class. Whoever supplies the evidence decides the match. ## Lanes @@ -94,6 +99,115 @@ lane's `maxContainers`. `bufferMin` with `bufferMax`, and `scaledownWindowMinS` with `scaledownWindowMaxS`, are optional pairs for platforms that can move a warm buffer or a scale-down window per lane. +## Planner + +```python +from sie_placement.planner import PlannerParameters, plan +from sie_placement.report import render + +result = plan( + service_levels, + receipts, + boot_evidence, + price_list, + demand, + current_plan, + PlannerParameters(placement="us-central1", max_containers=4, fallback_floor=2, cooldown_s=900), +) +print(render(result.plan.to_dict()), render(result.report.to_dict())) +``` + +`plan` is a pure function of its documents. The same inputs render to the +same bytes in whatever order the receipts, boot evidence, identities and demand +series arrive, and a run whose `current_plan` is its own previous plan reports +no change. + +| Parameter | Meaning | +| --- | --- | +| `placement` | The price-list placement whose region multiplier applies | +| `max_containers` | The reviewed ceiling of every lane, its `maxContainers` | +| `fallback_floor` | The least containers an active zero-floor lane holds, the `sie-cluster` chart's `autoscaling.fallbackReplicas` | +| `cooldown_s` | How long an active lane keeps its containers after its last request, the chart's `autoscaling.cooldownPeriod` | +| `buffer_containers` | The declared warm buffer above a lane's floor, `0` by default | +| `hours_per_month` | The hours a monthly figure covers, `730` by default | +| `queue_pool`, `bundle`, `bundles` | Every lane's queue pool, and each identity's bundle: its `bundles` entry, otherwise `bundle` | + +### Selection + +The planner places each identity of the service-level document on its own +lane: + +1. It refuses a receipt or boot record whose machine profile has no price, or + whose realized GPU product differs from the product the price list gives + that profile, and a receipt whose latency cannot answer the identity's + service level. The report lists every refusal. +2. Every other receipt is a cell. A cell whose p99 misses `warmP99Ms`, or + `ttftP99Ms` or `itlP99Ms`, is blocked. +3. A cell offers `pinned`, and `cold-with-bound` or `snapshot-cold` where boot + evidence for the identity, cell and container shape exists. The slowest + successful boot stands for the come-alive percentile, a boot that did not + succeed withdraws the warmth, and the environment's own evidence replaces + borrowed evidence. A `comeAliveP95S` of `0` admits `pinned` only. +4. The cheapest unblocked option wins. Ties go to the current plan's + placement, then to the faster come-alive. + +The planner does not select `lazy-resident`, `bridged` or `scheduled-warm`, +and does not put two identities on one lane. An identity with no unblocked +option keeps its current lane, or stays out of the plan when it has none. + +### Pricing + +A container costs `(acceleratorPerHour * gpuCount + corePerHour * cpuCores + +memoryGiBPerHour * memoryMiB / 1024) * regionMultiplier` an hour. An identity's +demand is its hourly requests summed over operations. A container serves +`requestsPerSecond * 3600` requests an hour at the receipt's concurrency, and +no hour runs more containers than the ceiling. Monthly figures scale the +demand window to `hours_per_month`. + +- `pinned` pays one container all month, plus each container an hour needs + above it, for that hour. +- A cold warmth pays, in each hour with requests, the work plus a tail after + every request: the active floor for `cooldown_s`, at most the whole hour. + The active floor is `fallback_floor` capped by the ceiling, and at least one. + +### Envelope + +`floorMin` is 1 for `pinned` and 0 otherwise. No source measures queue wait +yet, so `floorMax` is `floorMin` plus `buffer_containers`, capped by the +ceiling. A floor raised on a zero-floor lane realizes as at least +`fallback_floor`, so a zero-floor lane's nonzero `floorMax` is at least +`fallback_floor` capped by the ceiling. The envelope carries the floor range +only. + +### Report + +The report renders as a `placement-report` document: + +- `identities`: each identity's status (`placed`, `kept` or `unplaced`), + effective service level and demand, the chosen cell, warmth, monthly cost and + come-alive with its basis (`warm-floor`, `boot-evidence` or + `borrowed-boot-evidence`), the peak containers its demand needs, and + `nextCheaper`: the nearest cheaper option a service level blocks, its saving + and the bounds that block it. +- `lanes`: each lane's hourly cost, its floor's monthly cost and the monthly + cost of its `floorMax`, which a floor budget prices. +- `measurementRequests`: options that lack evidence, ranked by the saving they + could unlock. A profile without a receipt is bounded by price alone: one + accelerator at its rate, kept warm or, where the come-alive bound allows, + paying burst tails only. A cell whose receipt has no successful boot asks for + boot evidence and is bounded by its cold cost. A request that cannot save is + dropped, and the requests of an identity without a placement carry no bound + and rank first. +- `comeAliveLevers`: cold warmths whose measured come-alive misses the bound + on a cell that meets the warm bounds for less than the choice. Each is priced + under the identity's bound, where a bound of 0 admits no lever, and at + `permittedBoundS`, the bound its measured come-alive would permit. Levers rank + by the first saving, then by the second. +- `queueWaitUnattained`: every identity that declares `queueWaitP99Ms`. No + plan claims that bound as met. +- `refusals`, and `changes`: the identities and lanes that differ from + `current_plan`. + ## Tests ```bash diff --git a/packages/sie_placement/src/sie_placement/planner.py b/packages/sie_placement/src/sie_placement/planner.py new file mode 100644 index 000000000..29b23f997 --- /dev/null +++ b/packages/sie_placement/src/sie_placement/planner.py @@ -0,0 +1,763 @@ +"""Measured-only placement: the cheapest measured cell and warmth that meet each identity's service level.""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +from collections import Counter, defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field, replace +from datetime import datetime + +from sie_placement.report import ( + Blocker, + ComeAliveBasis, + IdentityChange, + IdentityReport, + IdentityStatus, + LaneChange, + LaneReport, + Lever, + Measurement, + MeasurementRequest, + Option, + Refusal, + RefusedRecord, + Report, + RequestReason, + UnplacedReason, +) +from sie_placement.schema import ( + WARM_FLOOR_WARMTHS, + BootEvidence, + BootOutcome, + Cell, + ContainerShape, + Demand, + Envelope, + MachineProfilePrice, + Operation, + Plan, + PlanIdentity, + PlanLane, + PriceList, + Receipt, + SchemaError, + ServiceLevel, + ServiceLevels, + SourceRef, + Warmth, +) + +SECONDS_PER_HOUR = 3600 +HOURS_PER_MONTH = 730.0 +PINNED_FLOOR = 1 +COLD_WARMTHS = (Warmth.COLD_WITH_BOUND, Warmth.SNAPSHOT_COLD) + +_SLUG = re.compile(r"[^a-z0-9]+") + + +class PlannerInputError(ValueError): + pass + + +def _require_name(name: str, value: str) -> None: + if not value or any(character.isspace() for character in value): + raise SchemaError(name, f"must be a non-empty string without whitespace, got {value!r}") + + +def _require_minimum(name: str, value: float, minimum: int) -> None: + if value < minimum: + raise SchemaError(name, f"must be at least {minimum}, got {value!r}") + + +@dataclass(frozen=True, slots=True, kw_only=True) +class PlannerParameters: + placement: str + max_containers: int + fallback_floor: int + cooldown_s: int + buffer_containers: int = 0 + hours_per_month: float = HOURS_PER_MONTH + queue_pool: str = "default" + bundle: str = "default" + bundles: Mapping[str, str] = field(default_factory=dict) + + def __post_init__(self) -> None: + _require_name("placement", self.placement) + _require_minimum("maxContainers", self.max_containers, 1) + _require_minimum("fallbackFloor", self.fallback_floor, 0) + _require_minimum("cooldownS", self.cooldown_s, 0) + _require_minimum("bufferContainers", self.buffer_containers, 0) + if not (math.isfinite(self.hours_per_month) and self.hours_per_month > 0): + raise SchemaError("hoursPerMonth", f"must be greater than 0, got {self.hours_per_month!r}") + _require_name("queuePool", self.queue_pool) + _require_name("bundle", self.bundle) + for identity, bundle in self.bundles.items(): + _require_name("bundles", identity) + _require_name(f"bundles[{identity!r}]", bundle) + + @property + def active_floor(self) -> int: + return max(1, min(self.fallback_floor, self.max_containers)) + + def bundle_of(self, identity: str) -> str: + return self.bundles.get(identity, self.bundle) + + def to_dict(self) -> dict[str, object]: + document: dict[str, object] = { + "placement": self.placement, + "maxContainers": self.max_containers, + "fallbackFloor": self.fallback_floor, + "cooldownS": self.cooldown_s, + "bufferContainers": self.buffer_containers, + "hoursPerMonth": self.hours_per_month, + "queuePool": self.queue_pool, + "bundle": self.bundle, + } + if self.bundles: + document["bundles"] = dict(sorted(self.bundles.items())) + return document + + +@dataclass(frozen=True, slots=True, kw_only=True) +class PlannerResult: + plan: Plan + report: Report + + +def container_hourly_cost(price: MachineProfilePrice, shape: ContainerShape, region_multiplier: float) -> float: + return region_multiplier * ( + price.accelerator_per_hour * shape.gpu_count + + price.core_per_hour * shape.cpu_cores + + price.memory_gib_per_hour * shape.memory_mib / 1024 + ) + + +def envelope_for(warmth: Warmth, parameters: PlannerParameters) -> Envelope: + floor_min = PINNED_FLOOR if warmth in WARM_FLOOR_WARMTHS else 0 + raised = floor_min + parameters.buffer_containers + if raised and not floor_min: + raised = max(raised, parameters.fallback_floor) + return Envelope(floor_min=floor_min, floor_max=min(parameters.max_containers, raised)) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class _Window: + hours: int + hours_per_month: float + ceiling: int + active_floor: int + cooldown_s: int + + @property + def scale(self) -> float: + return self.hours_per_month / self.hours + + @staticmethod + def needed(requests: int, requests_per_second: float) -> int: + return math.ceil(requests / (requests_per_second * SECONDS_PER_HOUR)) + + def warm_container_hours(self, requests: Sequence[int], requests_per_second: float) -> float: + above = sum( + max(0, min(self.ceiling, self.needed(count, requests_per_second)) - PINNED_FLOOR) for count in requests + ) + return PINNED_FLOOR * self.hours_per_month + above * self.scale + + def cold_container_hours(self, requests: Sequence[int], requests_per_second: float | None) -> float: + seconds = 0.0 + for count in requests: + tail = count * self.active_floor * self.cooldown_s + if requests_per_second is None: + seconds += min(self.active_floor * SECONDS_PER_HOUR, tail) + continue + containers = max(self.active_floor, min(self.ceiling, self.needed(count, requests_per_second))) + seconds += min(containers * SECONDS_PER_HOUR, count / requests_per_second + tail) + return seconds / SECONDS_PER_HOUR * self.scale + + +@dataclass(frozen=True, slots=True) +class _Boot: + seconds: float | None + borrowed: bool + + @property + def basis(self) -> ComeAliveBasis: + return ComeAliveBasis.BORROWED_BOOT_EVIDENCE if self.borrowed else ComeAliveBasis.BOOT_EVIDENCE + + +type _BootKey = tuple[str, Cell, ContainerShape, Warmth] + + +@dataclass(frozen=True, slots=True, kw_only=True) +class _Option: + receipt: Receipt + order: str + warmth: Warmth + cost: float + come_alive_s: float + basis: ComeAliveBasis + blockers: tuple[Blocker, ...] + current: bool + + @property + def feasible(self) -> bool: + return not self.blockers + + @property + def rank(self) -> tuple[float, bool, float, str, str]: + return (self.cost, not self.current, self.come_alive_s, self.order, self.warmth.value) + + def summary(self, saving: float | None = None) -> Option: + return Option( + cell=self.receipt.cell, + container_shape=self.receipt.container_shape, + concurrency=self.receipt.concurrency, + warmth=self.warmth, + monthly_cost=self.cost, + come_alive_s=self.come_alive_s, + come_alive_basis=self.basis, + receipt=self.receipt.source, + blocked_by=self.blockers, + saving=saving, + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class _Choice: + identity: str + level: ServiceLevel + requests: tuple[int, ...] + options: tuple[_Option, ...] + chosen: _Option | None + boot_requests: tuple[MeasurementRequest, ...] + has_valid_receipt: bool + + +def _canonical(document: Mapping[str, object]) -> str: + return json.dumps(document, sort_keys=True) + + +def _slug(value: str) -> str: + return _SLUG.sub("-", value.lower()).strip("-") + + +def _digest(value: str) -> str: + return hashlib.sha256(value.encode()).hexdigest()[:8] + + +def _refusal_reason(cell: Cell, prices: Mapping[str, MachineProfilePrice]) -> str | None: + price = prices.get(cell.machine_profile) + if price is None: + return f"machine profile {cell.machine_profile!r} has no price" + if price.gpu_product != cell.gpu_product: + return ( + f"realized GPU product {cell.gpu_product!r} differs from {price.gpu_product!r}, " + f"the product machine profile {cell.machine_profile!r} requests" + ) + return None + + +def _incomparable_reason(level: ServiceLevel, receipt: Receipt) -> str | None: + generate = receipt.request_shape.operation is Operation.GENERATE + if level.is_generation and not generate: + return "the receipt reports one latency and the service level declares ttftP99Ms and itlP99Ms" + if level.warm_p99_ms is not None and generate: + return "the receipt reports ttft and itl and the service level declares warmP99Ms" + return None + + +def _warm_blockers(level: ServiceLevel, receipt: Receipt) -> tuple[Blocker, ...]: + checks: list[tuple[str, int | None, float]] = [] + if receipt.latency is not None: + checks.append(("warmP99Ms", level.warm_p99_ms, receipt.latency.p99_ms)) + if receipt.ttft is not None: + checks.append(("ttftP99Ms", level.ttft_p99_ms, receipt.ttft.p99_ms)) + if receipt.itl is not None: + checks.append(("itlP99Ms", level.itl_p99_ms, receipt.itl.p99_ms)) + return tuple( + Blocker(field=name, bound=bound, measured=measured) + for name, bound, measured in checks + if bound is not None and measured > bound + ) + + +def _come_alive_blocker(level: ServiceLevel, seconds: float) -> Blocker | None: + bound = level.come_alive_p95_s + if bound is None or (bound > 0 and seconds <= bound): + return None + return Blocker(field="comeAliveP95S", bound=bound, measured=seconds) + + +def _boot_index(records: Iterable[BootEvidence]) -> dict[_BootKey, _Boot]: + grouped: defaultdict[_BootKey, list[BootEvidence]] = defaultdict(list) + for record in records: + grouped[(record.identity, record.cell, record.container_shape, record.warmth)].append(record) + index: dict[_BootKey, _Boot] = {} + for key, group in grouped.items(): + own = [record for record in group if not record.borrowed] + used = own or group + if any(record.outcome is not BootOutcome.SUCCEEDED for record in used): + index[key] = _Boot(seconds=None, borrowed=not own) + else: + index[key] = _Boot(seconds=max(record.boot_seconds for record in used), borrowed=not own) + return index + + +def _hourly_requests(demand: Demand) -> dict[str, tuple[int, ...]]: + hours: defaultdict[str, Counter[datetime]] = defaultdict(Counter) + for series in demand.series: + for hour in series.hours: + hours[series.identity][hour.start] += hour.requests + return { + identity: tuple(count for _, count in sorted(counts.items()) if count) for identity, counts in hours.items() + } + + +def _matches_current(receipt: Receipt, warmth: Warmth, current: tuple[PlanIdentity, PlanLane] | None) -> bool: + if current is None: + return False + entry, lane = current + return ( + entry.warmth is warmth + and lane.cell == receipt.cell + and lane.container_shape == receipt.container_shape + and lane.concurrency == receipt.concurrency + ) + + +class _Planner: + def __init__( + self, + service_levels: ServiceLevels, + receipts: Iterable[Receipt], + boot_evidence: Iterable[BootEvidence], + price_list: PriceList, + demand: Demand, + current_plan: Plan | None, + parameters: PlannerParameters, + ) -> None: + placements = {placement.name: placement for placement in price_list.placements} + placement = placements.get(parameters.placement) + if placement is None: + raise PlannerInputError(f"placement {parameters.placement!r} is not in the price list") + if current_plan is not None and current_plan.placement != parameters.placement: + raise PlannerInputError( + f"the current plan is for placement {current_plan.placement!r}, not {parameters.placement!r}" + ) + self.parameters = parameters + self.price_list = price_list + self.multiplier = placement.region_multiplier + self.prices = {profile.name: profile for profile in price_list.machine_profiles} + self.levels = {entry.identity: service_levels.effective(entry.identity) for entry in service_levels.identities} + self.window = _Window( + hours=int((demand.end - demand.start).total_seconds()) // SECONDS_PER_HOUR, + hours_per_month=parameters.hours_per_month, + ceiling=parameters.max_containers, + active_floor=parameters.active_floor, + cooldown_s=parameters.cooldown_s, + ) + self.requests = _hourly_requests(demand) + self.current_plan = current_plan + self.current: dict[str, tuple[PlanIdentity, PlanLane]] = {} + if current_plan is not None: + lanes = {lane.name: lane for lane in current_plan.lanes} + self.current = {entry.identity: (entry, lanes[entry.lane]) for entry in current_plan.identities} + self.refusals: list[Refusal] = [] + self.refused_profiles: set[tuple[str, str]] = set() + self.receipts = self._accept_receipts(receipts) + self.boots = _boot_index(self._accept_boot_evidence(boot_evidence)) + + def _accept_receipts(self, receipts: Iterable[Receipt]) -> dict[str, list[tuple[str, Receipt]]]: + accepted: defaultdict[str, list[tuple[str, Receipt]]] = defaultdict(list) + for receipt in receipts: + level = self.levels.get(receipt.identity) + if level is None: + continue + reason = _refusal_reason(receipt.cell, self.prices) or _incomparable_reason(level, receipt) + if reason is not None: + self._refuse(RefusedRecord.RECEIPT, receipt.identity, receipt.cell, receipt.source, reason) + self.refused_profiles.add((receipt.identity, receipt.cell.machine_profile)) + continue + accepted[receipt.identity].append((_canonical(receipt.to_dict()), receipt)) + return accepted + + def _accept_boot_evidence(self, records: Iterable[BootEvidence]) -> list[BootEvidence]: + accepted = [] + for record in records: + if record.identity not in self.levels: + continue + reason = _refusal_reason(record.cell, self.prices) + if reason is not None: + self._refuse(RefusedRecord.BOOT_EVIDENCE, record.identity, record.cell, record.source, reason) + continue + accepted.append(record) + return accepted + + def _refuse(self, record: RefusedRecord, identity: str, cell: Cell, source: SourceRef, reason: str) -> None: + self.refusals.append(Refusal(record=record, identity=identity, cell=cell, source=source, reason=reason)) + + def hourly_cost(self, cell: Cell, shape: ContainerShape) -> float | None: + if _refusal_reason(cell, self.prices) is not None: + return None + return container_hourly_cost(self.prices[cell.machine_profile], shape, self.multiplier) + + def choose(self, identity: str) -> _Choice: + level = self.levels[identity] + requests = self.requests.get(identity, ()) + current = self.current.get(identity) + options: list[_Option] = [] + boot_requests: dict[tuple[Cell, ContainerShape], MeasurementRequest] = {} + receipts = self.receipts.get(identity, []) + for order, receipt in receipts: + hourly = container_hourly_cost( + self.prices[receipt.cell.machine_profile], receipt.container_shape, self.multiplier + ) + rate = receipt.throughput.requests_per_second + warm = _warm_blockers(level, receipt) + options.append( + _Option( + receipt=receipt, + order=order, + warmth=Warmth.PINNED, + cost=hourly * self.window.warm_container_hours(requests, rate), + come_alive_s=0.0, + basis=ComeAliveBasis.WARM_FLOOR, + blockers=warm, + current=_matches_current(receipt, Warmth.PINNED, current), + ) + ) + cold_cost = hourly * self.window.cold_container_hours(requests, rate) + for warmth in COLD_WARMTHS: + boot = self.boots.get((identity, receipt.cell, receipt.container_shape, warmth)) + if boot is None or boot.seconds is None: + if warmth is Warmth.COLD_WITH_BOUND and not warm and level.come_alive_p95_s != 0: + key = (receipt.cell, receipt.container_shape) + known = boot_requests.get(key) + if known is None or cold_cost < known.cost_bound: + boot_requests[key] = MeasurementRequest( + identity=identity, + cell=receipt.cell, + container_shape=receipt.container_shape, + measure=(Measurement.BOOT_EVIDENCE,), + warmth=warmth, + reason=RequestReason.UNMEASURED if boot is None else RequestReason.FAILED, + cost_bound=cold_cost, + saving_bound=None, + ) + continue + blocker = _come_alive_blocker(level, boot.seconds) + options.append( + _Option( + receipt=receipt, + order=order, + warmth=warmth, + cost=cold_cost, + come_alive_s=boot.seconds, + basis=boot.basis, + blockers=warm if blocker is None else (*warm, blocker), + current=_matches_current(receipt, warmth, current), + ) + ) + feasible = [option for option in options if option.feasible] + chosen = min(feasible, key=lambda option: option.rank) if feasible else None + return _Choice( + identity=identity, + level=level, + requests=requests, + options=tuple(options), + chosen=chosen, + boot_requests=tuple(boot_requests.values()), + has_valid_receipt=bool(receipts), + ) + + def receipt_requests(self, choice: _Choice) -> list[MeasurementRequest]: + measured = {receipt.cell.machine_profile for _, receipt in self.receipts.get(choice.identity, [])} + bound = choice.level.come_alive_p95_s + requests = [] + for profile in sorted(self.price_list.machine_profiles, key=lambda price: price.name): + if profile.name in measured: + continue + accelerator = profile.accelerator_per_hour * self.multiplier + candidates = [(accelerator * self.window.warm_container_hours((), 1.0), Warmth.PINNED)] + if bound != 0: + cold = accelerator * self.window.cold_container_hours(choice.requests, None) + candidates.append((cold, Warmth.COLD_WITH_BOUND)) + cost, warmth = min(candidates, key=lambda candidate: (candidate[0], candidate[1] is not Warmth.PINNED)) + saving = None if choice.chosen is None else choice.chosen.cost - cost + if saving is not None and saving <= 0: + continue + requests.append( + MeasurementRequest( + identity=choice.identity, + cell=Cell(machine_profile=profile.name, gpu_product=profile.gpu_product), + measure=( + (Measurement.RECEIPT,) + if warmth is Warmth.PINNED + else (Measurement.RECEIPT, Measurement.BOOT_EVIDENCE) + ), + warmth=warmth, + reason=( + RequestReason.REFUSED + if (choice.identity, profile.name) in self.refused_profiles + else RequestReason.UNMEASURED + ), + cost_bound=cost, + saving_bound=saving, + ) + ) + return requests + + def boot_requests(self, choice: _Choice) -> list[MeasurementRequest]: + if choice.chosen is None: + return [] + chosen = choice.chosen + return [ + replace(request, saving_bound=chosen.cost - request.cost_bound) + for request in choice.boot_requests + if chosen.cost - request.cost_bound > 0 + ] + + @staticmethod + def levers(choice: _Choice) -> list[Lever]: + chosen = choice.chosen + bound = choice.level.come_alive_p95_s + if chosen is None or bound is None: + return [] + best: dict[tuple[Cell, ContainerShape, Warmth], _Option] = {} + for option in choice.options: + if option.warmth not in COLD_WARMTHS or option.cost >= chosen.cost: + continue + if [blocker.field for blocker in option.blockers] != ["comeAliveP95S"]: + continue + key = (option.receipt.cell, option.receipt.container_shape, option.warmth) + known = best.get(key) + if known is None or option.rank < known.rank: + best[key] = option + levers = [] + for option in best.values(): + saving = chosen.cost - option.cost + levers.append( + Lever( + identity=choice.identity, + cell=option.receipt.cell, + container_shape=option.receipt.container_shape, + warmth=option.warmth, + come_alive_s=option.come_alive_s, + come_alive_basis=option.basis, + bound_s=bound, + monthly_cost=option.cost, + saving_under_bound=saving if bound > 0 else 0.0, + permitted_bound_s=max(1, math.ceil(option.come_alive_s)), + saving_at_permitted_bound=saving, + ) + ) + return levers + + @staticmethod + def next_cheaper(choice: _Choice) -> _Option | None: + chosen = choice.chosen + if chosen is None: + return None + cheaper = [option for option in choice.options if not option.feasible and option.cost < chosen.cost] + if not cheaper: + return None + nearest = max(option.cost for option in cheaper) + return min((option for option in cheaper if option.cost == nearest), key=lambda option: option.rank) + + def lane_names(self, choices: Sequence[_Choice], reserved: set[str]) -> dict[str, str]: + bases: dict[str, str] = {} + for choice in choices: + if choice.chosen is not None: + profile = choice.chosen.receipt.cell.machine_profile + bases[choice.identity] = _slug(f"{choice.identity}-{profile}") or "lane" + counts = Counter(bases.values()) + return { + identity: base if counts[base] == 1 and base not in reserved else f"{base}-{_digest(identity)}" + for identity, base in bases.items() + } + + def run(self) -> PlannerResult: + choices = [self.choose(identity) for identity in sorted(self.levels)] + kept = { + choice.identity: self.current[choice.identity] + for choice in choices + if choice.chosen is None and choice.identity in self.current + } + kept_lanes = {lane.name: lane for _, lane in kept.values()} + names = self.lane_names(choices, set(kept_lanes)) + lanes: dict[str, PlanLane] = dict(kept_lanes) + identities: list[PlanIdentity] = [entry for entry, _ in kept.values()] + reports: list[IdentityReport] = [] + requests: list[MeasurementRequest] = [] + levers: list[Lever] = [] + monthly_cost = 0.0 + for choice in choices: + requests.extend(self.receipt_requests(choice)) + requests.extend(self.boot_requests(choice)) + levers.extend(self.levers(choice)) + reports.append(self._identity_report(choice, names, kept)) + if choice.chosen is None: + continue + monthly_cost += choice.chosen.cost + receipt = choice.chosen.receipt + name = names[choice.identity] + lanes[name] = PlanLane( + name=name, + queue_pool=self.parameters.queue_pool, + bundle=self.parameters.bundle_of(choice.identity), + cell=receipt.cell, + container_shape=receipt.container_shape, + concurrency=receipt.concurrency, + max_containers=self.parameters.max_containers, + envelope=envelope_for(choice.chosen.warmth, self.parameters), + ) + identities.append(PlanIdentity(identity=choice.identity, lane=name, warmth=choice.chosen.warmth)) + new_plan = Plan( + placement=self.parameters.placement, + lanes=tuple(lanes[name] for name in sorted(lanes)), + identities=tuple(sorted(identities, key=lambda entry: entry.identity)), + ) + lane_reports = self._lane_reports(new_plan) + identity_changes, lane_changes = _changes(self.current_plan, new_plan) + report = Report( + placement=self.parameters.placement, + currency=self.price_list.currency, + parameters=self.parameters.to_dict(), + monthly_cost=monthly_cost, + envelope_max_monthly_cost=sum( + lane.envelope_max_monthly_cost for lane in lane_reports if lane.envelope_max_monthly_cost is not None + ), + identities=tuple(reports), + lanes=lane_reports, + measurement_requests=tuple(sorted(requests, key=_request_rank)), + come_alive_levers=tuple(sorted(levers, key=_lever_rank)), + queue_wait_unattained=tuple( + identity for identity in sorted(self.levels) if self.levels[identity].queue_wait_p99_ms is not None + ), + refusals=tuple(sorted(self.refusals, key=_refusal_rank)), + identity_changes=identity_changes, + lane_changes=lane_changes, + ) + return PlannerResult(plan=new_plan, report=report) + + def _identity_report( + self, choice: _Choice, names: Mapping[str, str], kept: Mapping[str, tuple[PlanIdentity, PlanLane]] + ) -> IdentityReport: + current = self.current.get(choice.identity) + report = IdentityReport( + identity=choice.identity, + status=IdentityStatus.UNPLACED, + service_level=choice.level, + demand_requests=sum(choice.requests), + current=None if current is None else current[0], + ) + chosen = choice.chosen + if chosen is None: + reason = UnplacedReason.WARM_BOUND_MISSED if choice.has_valid_receipt else UnplacedReason.NO_RECEIPT + if choice.identity in kept: + return replace( + report, status=IdentityStatus.KEPT, lane=kept[choice.identity][0].lane, unplaced_reason=reason + ) + return replace(report, unplaced_reason=reason) + nearest = self.next_cheaper(choice) + rate = chosen.receipt.throughput.requests_per_second + return replace( + report, + status=IdentityStatus.PLACED, + lane=names[choice.identity], + chosen=chosen.summary(), + peak_containers=max((_Window.needed(count, rate) for count in choice.requests), default=0), + next_cheaper=None if nearest is None else nearest.summary(saving=chosen.cost - nearest.cost), + ) + + def _lane_reports(self, plan: Plan) -> tuple[LaneReport, ...]: + residents: defaultdict[str, list[str]] = defaultdict(list) + for entry in plan.identities: + residents[entry.lane].append(entry.identity) + reports = [] + for lane in plan.lanes: + hourly = self.hourly_cost(lane.cell, lane.container_shape) + hours = self.parameters.hours_per_month + reports.append( + LaneReport( + name=lane.name, + identities=tuple(sorted(residents[lane.name])), + hourly_cost=hourly, + floor_monthly_cost=None if hourly is None else hourly * lane.envelope.floor_min * hours, + envelope_max_monthly_cost=None if hourly is None else hourly * lane.envelope.floor_max * hours, + ) + ) + return tuple(reports) + + +def _changes(current: Plan | None, new: Plan) -> tuple[tuple[IdentityChange, ...], tuple[LaneChange, ...]]: + before_identities = {} if current is None else {entry.identity: entry for entry in current.identities} + after_identities = {entry.identity: entry for entry in new.identities} + before_lanes = {} if current is None else {lane.name: lane for lane in current.lanes} + after_lanes = {lane.name: lane for lane in new.lanes} + identity_changes = tuple( + IdentityChange(identity=identity, before=before_identities.get(identity), after=after_identities.get(identity)) + for identity in sorted(before_identities.keys() | after_identities.keys()) + if before_identities.get(identity) != after_identities.get(identity) + ) + lane_changes = tuple( + LaneChange(name=name, before=before_lanes.get(name), after=after_lanes.get(name)) + for name in sorted(before_lanes.keys() | after_lanes.keys()) + if before_lanes.get(name) != after_lanes.get(name) + ) + return identity_changes, lane_changes + + +def _shape_key(shape: ContainerShape | None) -> tuple[int, float, int]: + return (0, 0.0, 0) if shape is None else (shape.gpu_count, shape.cpu_cores, shape.memory_mib) + + +def _request_rank(request: MeasurementRequest) -> tuple[object, ...]: + return ( + request.saving_bound is not None, + -(request.saving_bound or 0.0), + request.identity, + request.cell.machine_profile, + request.cell.gpu_product, + _shape_key(request.container_shape), + tuple(measurement.value for measurement in request.measure), + ) + + +def _lever_rank(lever: Lever) -> tuple[object, ...]: + return ( + -lever.saving_under_bound, + -lever.saving_at_permitted_bound, + lever.identity, + lever.cell.machine_profile, + lever.cell.gpu_product, + _shape_key(lever.container_shape), + lever.warmth.value, + ) + + +def _refusal_rank(refusal: Refusal) -> tuple[str, ...]: + return ( + refusal.record.value, + refusal.identity, + refusal.cell.machine_profile, + refusal.cell.gpu_product, + refusal.source.uri, + refusal.source.sha256 or "", + refusal.reason, + ) + + +def plan( + service_levels: ServiceLevels, + receipts: Iterable[Receipt], + boot_evidence: Iterable[BootEvidence], + price_list: PriceList, + demand: Demand, + current_plan: Plan | None, + parameters: PlannerParameters, +) -> PlannerResult: + return _Planner(service_levels, receipts, boot_evidence, price_list, demand, current_plan, parameters).run() diff --git a/packages/sie_placement/src/sie_placement/report.py b/packages/sie_placement/src/sie_placement/report.py new file mode 100644 index 000000000..462bbe3ed --- /dev/null +++ b/packages/sie_placement/src/sie_placement/report.py @@ -0,0 +1,318 @@ +"""The planner's report: what each placement costs and what would make it cheaper.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from dataclasses import dataclass +from enum import StrEnum + +from sie_placement.schema import ( + SCHEMA_VERSION, + Cell, + ContainerShape, + PlanIdentity, + PlanLane, + ServiceLevel, + SourceRef, + Warmth, +) + +REPORT_KIND = "placement-report" + + +class IdentityStatus(StrEnum): + PLACED = "placed" + KEPT = "kept" + UNPLACED = "unplaced" + + +class UnplacedReason(StrEnum): + NO_RECEIPT = "no-receipt" + WARM_BOUND_MISSED = "warm-bound-missed" + + +class ComeAliveBasis(StrEnum): + WARM_FLOOR = "warm-floor" + BOOT_EVIDENCE = "boot-evidence" + BORROWED_BOOT_EVIDENCE = "borrowed-boot-evidence" + + +class Measurement(StrEnum): + RECEIPT = "receipt" + BOOT_EVIDENCE = "boot-evidence" + + +class RequestReason(StrEnum): + UNMEASURED = "unmeasured" + REFUSED = "refused" + FAILED = "failed" + + +class RefusedRecord(StrEnum): + RECEIPT = "receipt" + BOOT_EVIDENCE = "boot-evidence" + + +def _money(value: float) -> float: + return round(value, 2) + 0.0 + + +def _rate(value: float) -> float: + return round(value, 4) + 0.0 + + +def _compact(fields: dict[str, object | None]) -> dict[str, object]: + return {key: value for key, value in fields.items() if value is not None} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Blocker: + field: str + bound: int + measured: float + + def to_dict(self) -> dict[str, object]: + return {"field": self.field, "bound": self.bound, "measured": self.measured} + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Option: + cell: Cell + container_shape: ContainerShape + concurrency: int + warmth: Warmth + monthly_cost: float + come_alive_s: float + come_alive_basis: ComeAliveBasis + receipt: SourceRef + blocked_by: tuple[Blocker, ...] = () + saving: float | None = None + + def to_dict(self) -> dict[str, object]: + return _compact( + { + "cell": self.cell.to_dict(), + "containerShape": self.container_shape.to_dict(), + "concurrency": self.concurrency, + "warmth": self.warmth.value, + "monthlyCost": _money(self.monthly_cost), + "saving": None if self.saving is None else _money(self.saving), + "comeAliveS": self.come_alive_s, + "comeAliveBasis": self.come_alive_basis.value, + "blockedBy": [blocker.to_dict() for blocker in self.blocked_by] or None, + "receipt": self.receipt.to_dict(), + } + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class IdentityReport: + identity: str + status: IdentityStatus + service_level: ServiceLevel + demand_requests: int + lane: str | None = None + chosen: Option | None = None + peak_containers: int | None = None + next_cheaper: Option | None = None + current: PlanIdentity | None = None + unplaced_reason: UnplacedReason | None = None + + def to_dict(self) -> dict[str, object]: + return _compact( + { + "identity": self.identity, + "status": self.status.value, + "serviceLevel": self.service_level.to_dict(), + "demandRequests": self.demand_requests, + "lane": self.lane, + "chosen": None if self.chosen is None else self.chosen.to_dict(), + "peakContainers": self.peak_containers, + "nextCheaper": None if self.next_cheaper is None else self.next_cheaper.to_dict(), + "unplacedReason": None if self.unplaced_reason is None else self.unplaced_reason.value, + "current": None if self.current is None else self.current.to_dict(), + } + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class LaneReport: + name: str + identities: tuple[str, ...] + hourly_cost: float | None + floor_monthly_cost: float | None + envelope_max_monthly_cost: float | None + + def to_dict(self) -> dict[str, object]: + return _compact( + { + "name": self.name, + "identities": list(self.identities), + "hourlyCost": None if self.hourly_cost is None else _rate(self.hourly_cost), + "floorMonthlyCost": None if self.floor_monthly_cost is None else _money(self.floor_monthly_cost), + "envelopeMaxMonthlyCost": ( + None if self.envelope_max_monthly_cost is None else _money(self.envelope_max_monthly_cost) + ), + } + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class MeasurementRequest: + identity: str + cell: Cell + measure: tuple[Measurement, ...] + warmth: Warmth + reason: RequestReason + cost_bound: float + saving_bound: float | None + container_shape: ContainerShape | None = None + + def to_dict(self) -> dict[str, object]: + return _compact( + { + "identity": self.identity, + "cell": self.cell.to_dict(), + "containerShape": None if self.container_shape is None else self.container_shape.to_dict(), + "measure": [measurement.value for measurement in self.measure], + "warmth": self.warmth.value, + "reason": self.reason.value, + "costBound": _money(self.cost_bound), + "savingBound": None if self.saving_bound is None else _money(self.saving_bound), + } + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Lever: + identity: str + cell: Cell + container_shape: ContainerShape + warmth: Warmth + come_alive_s: float + come_alive_basis: ComeAliveBasis + bound_s: int + monthly_cost: float + saving_under_bound: float + permitted_bound_s: int + saving_at_permitted_bound: float + + def to_dict(self) -> dict[str, object]: + return { + "identity": self.identity, + "cell": self.cell.to_dict(), + "containerShape": self.container_shape.to_dict(), + "warmth": self.warmth.value, + "comeAliveS": self.come_alive_s, + "comeAliveBasis": self.come_alive_basis.value, + "comeAliveBoundS": self.bound_s, + "monthlyCost": _money(self.monthly_cost), + "savingUnderBound": _money(self.saving_under_bound), + "permittedBoundS": self.permitted_bound_s, + "savingAtPermittedBound": _money(self.saving_at_permitted_bound), + } + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Refusal: + record: RefusedRecord + identity: str + cell: Cell + source: SourceRef + reason: str + + def to_dict(self) -> dict[str, object]: + return { + "record": self.record.value, + "identity": self.identity, + "cell": self.cell.to_dict(), + "source": self.source.to_dict(), + "reason": self.reason, + } + + +@dataclass(frozen=True, slots=True, kw_only=True) +class IdentityChange: + identity: str + before: PlanIdentity | None + after: PlanIdentity | None + + def to_dict(self) -> dict[str, object]: + return _compact( + { + "identity": self.identity, + "before": None if self.before is None else self.before.to_dict(), + "after": None if self.after is None else self.after.to_dict(), + } + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class LaneChange: + name: str + before: PlanLane | None + after: PlanLane | None + + def to_dict(self) -> dict[str, object]: + return _compact( + { + "name": self.name, + "before": None if self.before is None else self.before.to_dict(), + "after": None if self.after is None else self.after.to_dict(), + } + ) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Report: + placement: str + currency: str + parameters: Mapping[str, object] + monthly_cost: float + envelope_max_monthly_cost: float + identities: tuple[IdentityReport, ...] + lanes: tuple[LaneReport, ...] + measurement_requests: tuple[MeasurementRequest, ...] + come_alive_levers: tuple[Lever, ...] + queue_wait_unattained: tuple[str, ...] + refusals: tuple[Refusal, ...] + identity_changes: tuple[IdentityChange, ...] + lane_changes: tuple[LaneChange, ...] + + @property + def unchanged(self) -> bool: + return not self.identity_changes and not self.lane_changes + + def identity(self, identity: str) -> IdentityReport: + for entry in self.identities: + if entry.identity == identity: + return entry + raise KeyError(identity) + + def to_dict(self) -> dict[str, object]: + return { + "kind": REPORT_KIND, + "schemaVersion": SCHEMA_VERSION, + "placement": self.placement, + "currency": self.currency, + "parameters": dict(self.parameters), + "totals": { + "monthlyCost": _money(self.monthly_cost), + "envelopeMaxMonthlyCost": _money(self.envelope_max_monthly_cost), + }, + "identities": [entry.to_dict() for entry in self.identities], + "lanes": [lane.to_dict() for lane in self.lanes], + "measurementRequests": [request.to_dict() for request in self.measurement_requests], + "comeAliveLevers": [lever.to_dict() for lever in self.come_alive_levers], + "queueWaitUnattained": list(self.queue_wait_unattained), + "refusals": [refusal.to_dict() for refusal in self.refusals], + "changes": { + "identities": [change.to_dict() for change in self.identity_changes], + "lanes": [change.to_dict() for change in self.lane_changes], + }, + } + + +def render(document: Mapping[str, object]) -> str: + return json.dumps(document, indent=2, ensure_ascii=False) + "\n" diff --git a/packages/sie_placement/src/sie_placement/schema.py b/packages/sie_placement/src/sie_placement/schema.py index 410d6cf7e..ba9e691ba 100644 --- a/packages/sie_placement/src/sie_placement/schema.py +++ b/packages/sie_placement/src/sie_placement/schema.py @@ -135,6 +135,11 @@ def _string(self, key: str, value: object) -> str: raise SchemaError(self._at(key), f"expected a string, got {_describe(value)}") return value + def _boolean(self, key: str, value: object) -> bool: + if not isinstance(value, bool): + raise SchemaError(self._at(key), f"expected a boolean, got {_describe(value)}") + return value + def _integer(self, key: str, value: object) -> int: if isinstance(value, bool) or not isinstance(value, int): raise SchemaError(self._at(key), f"expected an integer, got {_describe(value)}") @@ -171,6 +176,10 @@ def optional_string(self, key: str) -> str | None: value = self._optional(key) return None if value is None else self._string(key, value) + def optional_boolean(self, key: str) -> bool | None: + value = self._optional(key) + return None if value is None else self._boolean(key, value) + def integer(self, key: str) -> int: return self._integer(key, self._required(key)) @@ -661,6 +670,7 @@ class BootEvidence: boot_seconds: float outcome: BootOutcome source: SourceRef + borrowed: bool = False def __post_init__(self) -> None: _require_identifier("identity", self.identity) @@ -681,21 +691,25 @@ def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: warmth=reader.enum("warmth", Warmth), boot_seconds=reader.number("bootSeconds"), outcome=reader.enum("outcome", BootOutcome), + borrowed=reader.optional_boolean("borrowed") is True, source=reader.child("source", SourceRef.from_dict), ) def to_dict(self) -> dict[str, object]: - return { - "kind": BOOT_EVIDENCE_KIND, - "schemaVersion": SCHEMA_VERSION, - "identity": self.identity, - "cell": self.cell.to_dict(), - "containerShape": self.container_shape.to_dict(), - "warmth": self.warmth.value, - "bootSeconds": self.boot_seconds, - "outcome": self.outcome.value, - "source": self.source.to_dict(), - } + return _compact( + { + "kind": BOOT_EVIDENCE_KIND, + "schemaVersion": SCHEMA_VERSION, + "identity": self.identity, + "cell": self.cell.to_dict(), + "containerShape": self.container_shape.to_dict(), + "warmth": self.warmth.value, + "bootSeconds": self.boot_seconds, + "outcome": self.outcome.value, + "borrowed": True if self.borrowed else None, + "source": self.source.to_dict(), + } + ) @dataclass(frozen=True, slots=True, kw_only=True) diff --git a/packages/sie_placement/tests/fixtures/planner/boot-evidence.json b/packages/sie_placement/tests/fixtures/planner/boot-evidence.json new file mode 100644 index 000000000..4667e5138 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/boot-evidence.json @@ -0,0 +1,213 @@ +[ + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "BAAI/bge-m3", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "cold-with-bound", + "bootSeconds": 95.0, + "outcome": "succeeded", + "borrowed": true, + "source": { + "uri": "boots/baai-bge-m3/l4-cold-with-bound-1.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000065" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "BAAI/bge-m3", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "snapshot-cold", + "bootSeconds": 8.5, + "outcome": "succeeded", + "source": { + "uri": "boots/baai-bge-m3/l4-snapshot-cold-2.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000066" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "BAAI/bge-m3:sparse", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "cold-with-bound", + "bootSeconds": 88.1, + "outcome": "succeeded", + "source": { + "uri": "boots/baai-bge-m3-sparse/l4-cold-with-bound-3.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000067" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "BAAI/bge-m3:sparse", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "cold-with-bound", + "bootSeconds": 95.0, + "outcome": "succeeded", + "source": { + "uri": "boots/baai-bge-m3-sparse/l4-cold-with-bound-4.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000068" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-8B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "warmth": "cold-with-bound", + "bootSeconds": 187.4, + "outcome": "succeeded", + "source": { + "uri": "boots/qwen-qwen3-8b/a100-80gb-cold-with-bound-5.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000069" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-8B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "cold-with-bound", + "bootSeconds": 240.0, + "outcome": "succeeded", + "source": { + "uri": "boots/qwen-qwen3-8b/l4-cold-with-bound-6.json", + "sha256": "000000000000000000000000000000000000000000000000000000000000006a" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "cold-with-bound", + "bootSeconds": 240.0, + "outcome": "succeeded", + "source": { + "uri": "boots/qwen-qwen3-embedding-4b/l4-cold-with-bound-7.json", + "sha256": "000000000000000000000000000000000000000000000000000000000000006b" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "snapshot-cold", + "bootSeconds": 45.0, + "outcome": "succeeded", + "source": { + "uri": "boots/qwen-qwen3-embedding-4b/l4-snapshot-cold-8.json", + "sha256": "000000000000000000000000000000000000000000000000000000000000006c" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "warmth": "cold-with-bound", + "bootSeconds": 900.0, + "outcome": "timed-out", + "source": { + "uri": "boots/qwen-qwen3-embedding-4b/a100-80gb-cold-with-bound-9.json", + "sha256": "000000000000000000000000000000000000000000000000000000000000006d" + } + }, + { + "kind": "placement-boot-evidence", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-Reranker-0.6B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-40GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "warmth": "cold-with-bound", + "bootSeconds": 70.0, + "outcome": "succeeded", + "source": { + "uri": "boots/qwen-qwen3-reranker-0.6b/a100-80gb-cold-with-bound-10.json", + "sha256": "000000000000000000000000000000000000000000000000000000000000006e" + } + } +] diff --git a/packages/sie_placement/tests/fixtures/planner/current-plan.json b/packages/sie_placement/tests/fixtures/planner/current-plan.json new file mode 100644 index 000000000..b51a64d28 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/current-plan.json @@ -0,0 +1,64 @@ +{ + "kind": "placement-plan", + "schemaVersion": 1, + "placement": "us-central1", + "lanes": [ + { + "name": "default-l4-default", + "queuePool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "maxContainers": 4, + "envelope": { + "floorMin": 1, + "floorMax": 2 + } + }, + { + "name": "qwen-qwen3-8b-a100-80gb", + "queuePool": "default", + "bundle": "sglang", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "concurrency": 32, + "maxContainers": 4, + "envelope": { + "floorMin": 0, + "floorMax": 2 + } + } + ], + "identities": [ + { + "identity": "BAAI/bge-m3", + "lane": "default-l4-default", + "warmth": "pinned" + }, + { + "identity": "Qwen/Qwen3-8B", + "lane": "qwen-qwen3-8b-a100-80gb", + "warmth": "cold-with-bound" + }, + { + "identity": "intfloat/e5-base-v2", + "lane": "default-l4-default", + "warmth": "pinned" + } + ] +} diff --git a/packages/sie_placement/tests/fixtures/planner/demand.json b/packages/sie_placement/tests/fixtures/planner/demand.json new file mode 100644 index 000000000..b00b366ee --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/demand.json @@ -0,0 +1,114 @@ +{ + "kind": "placement-demand", + "schemaVersion": 1, + "start": "2026-11-02T00:00:00Z", + "end": "2026-11-03T00:00:00Z", + "series": [ + { + "identity": "BAAI/bge-m3", + "operation": "encode", + "hours": [ + { + "start": "2026-11-02T09:00:00Z", + "requests": 20000 + }, + { + "start": "2026-11-02T10:00:00Z", + "requests": 20000 + }, + { + "start": "2026-11-02T11:00:00Z", + "requests": 20000 + }, + { + "start": "2026-11-02T12:00:00Z", + "requests": 20000 + }, + { + "start": "2026-11-02T13:00:00Z", + "requests": 20000 + }, + { + "start": "2026-11-02T14:00:00Z", + "requests": 20000 + }, + { + "start": "2026-11-02T15:00:00Z", + "requests": 20000 + }, + { + "start": "2026-11-02T16:00:00Z", + "requests": 20000 + }, + { + "start": "2026-11-02T17:00:00Z", + "requests": 20000 + } + ] + }, + { + "identity": "BAAI/bge-m3:sparse", + "operation": "encode", + "hours": [ + { + "start": "2026-11-02T11:00:00Z", + "requests": 3 + } + ] + }, + { + "identity": "Qwen/Qwen3-8B", + "operation": "generate", + "hours": [ + { + "start": "2026-11-02T14:00:00Z", + "requests": 12 + }, + { + "start": "2026-11-02T15:00:00Z", + "requests": 30 + } + ] + }, + { + "identity": "Qwen/Qwen3-Embedding-4B", + "operation": "encode", + "hours": [ + { + "start": "2026-11-02T08:00:00Z", + "requests": 600 + }, + { + "start": "2026-11-02T09:00:00Z", + "requests": 600 + }, + { + "start": "2026-11-02T10:00:00Z", + "requests": 600 + }, + { + "start": "2026-11-02T11:00:00Z", + "requests": 600 + }, + { + "start": "2026-11-02T12:00:00Z", + "requests": 600 + }, + { + "start": "2026-11-02T13:00:00Z", + "requests": 600 + } + ] + }, + { + "identity": "intfloat/e5-base-v2", + "operation": "encode", + "hours": [ + { + "start": "2026-11-02T10:00:00Z", + "requests": 40 + } + ] + } + ] +} diff --git a/packages/sie_placement/tests/fixtures/planner/expected-plan.json b/packages/sie_placement/tests/fixtures/planner/expected-plan.json new file mode 100644 index 000000000..1edfd3444 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/expected-plan.json @@ -0,0 +1,134 @@ +{ + "kind": "placement-plan", + "schemaVersion": 1, + "placement": "us-central1", + "lanes": [ + { + "name": "baai-bge-m3-l4", + "queuePool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "maxContainers": 4, + "envelope": { + "floorMin": 1, + "floorMax": 2 + } + }, + { + "name": "baai-bge-m3-sparse-l4", + "queuePool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "maxContainers": 4, + "envelope": { + "floorMin": 0, + "floorMax": 2 + } + }, + { + "name": "default-l4-default", + "queuePool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "maxContainers": 4, + "envelope": { + "floorMin": 1, + "floorMax": 2 + } + }, + { + "name": "qwen-qwen3-8b-a100-80gb", + "queuePool": "default", + "bundle": "sglang", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "concurrency": 32, + "maxContainers": 4, + "envelope": { + "floorMin": 0, + "floorMax": 2 + } + }, + { + "name": "qwen-qwen3-embedding-4b-l4", + "queuePool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 8, + "maxContainers": 4, + "envelope": { + "floorMin": 1, + "floorMax": 2 + } + } + ], + "identities": [ + { + "identity": "BAAI/bge-m3", + "lane": "baai-bge-m3-l4", + "warmth": "pinned" + }, + { + "identity": "BAAI/bge-m3:sparse", + "lane": "baai-bge-m3-sparse-l4", + "warmth": "cold-with-bound" + }, + { + "identity": "Qwen/Qwen3-8B", + "lane": "qwen-qwen3-8b-a100-80gb", + "warmth": "cold-with-bound" + }, + { + "identity": "Qwen/Qwen3-Embedding-4B", + "lane": "qwen-qwen3-embedding-4b-l4", + "warmth": "pinned" + }, + { + "identity": "intfloat/e5-base-v2", + "lane": "default-l4-default", + "warmth": "pinned" + } + ] +} diff --git a/packages/sie_placement/tests/fixtures/planner/expected-report.json b/packages/sie_placement/tests/fixtures/planner/expected-report.json new file mode 100644 index 000000000..ee6424bc9 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/expected-report.json @@ -0,0 +1,698 @@ +{ + "kind": "placement-report", + "schemaVersion": 1, + "placement": "us-central1", + "currency": "USD", + "parameters": { + "placement": "us-central1", + "maxContainers": 4, + "fallbackFloor": 2, + "cooldownS": 900, + "bufferContainers": 1, + "hoursPerMonth": 730.0, + "queuePool": "default", + "bundle": "default", + "bundles": { + "Qwen/Qwen3-8B": "sglang" + } + }, + "totals": { + "monthlyCost": 1947.88, + "envelopeMaxMonthlyCost": 10658.0 + }, + "identities": [ + { + "identity": "BAAI/bge-m3", + "status": "placed", + "serviceLevel": { + "comeAliveP95S": 0, + "warmP99Ms": 250, + "queueWaitP99Ms": 500 + }, + "demandRequests": 180000, + "lane": "baai-bge-m3-l4", + "chosen": { + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "warmth": "pinned", + "monthlyCost": 759.2, + "comeAliveS": 0.0, + "comeAliveBasis": "warm-floor", + "receipt": { + "uri": "receipts/baai-bge-m3/l4-c16-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000001" + } + }, + "peakContainers": 1, + "nextCheaper": { + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "warmth": "snapshot-cold", + "monthlyCost": 569.4, + "saving": 189.8, + "comeAliveS": 8.5, + "comeAliveBasis": "boot-evidence", + "blockedBy": [ + { + "field": "comeAliveP95S", + "bound": 0, + "measured": 8.5 + } + ], + "receipt": { + "uri": "receipts/baai-bge-m3/l4-c16-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000001" + } + }, + "current": { + "identity": "BAAI/bge-m3", + "lane": "default-l4-default", + "warmth": "pinned" + } + }, + { + "identity": "BAAI/bge-m3:sparse", + "status": "placed", + "serviceLevel": { + "comeAliveP95S": 120, + "warmP99Ms": 250, + "queueWaitP99Ms": 500 + }, + "demandRequests": 3, + "lane": "baai-bge-m3-sparse-l4", + "chosen": { + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "warmth": "cold-with-bound", + "monthlyCost": 47.45, + "comeAliveS": 95.0, + "comeAliveBasis": "boot-evidence", + "receipt": { + "uri": "receipts/baai-bge-m3-sparse/l4-c16-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000003" + } + }, + "peakContainers": 1 + }, + { + "identity": "Qwen/Qwen3-8B", + "status": "placed", + "serviceLevel": { + "comeAliveP95S": 600, + "ttftP99Ms": 4000, + "itlP99Ms": 80 + }, + "demandRequests": 42, + "lane": "qwen-qwen3-8b-a100-80gb", + "chosen": { + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "concurrency": 32, + "warmth": "cold-with-bound", + "monthlyCost": 382.03, + "comeAliveS": 187.4, + "comeAliveBasis": "boot-evidence", + "receipt": { + "uri": "receipts/qwen-qwen3-8b/a100-80gb-c32-65536.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000004" + } + }, + "peakContainers": 1, + "nextCheaper": { + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 8, + "warmth": "cold-with-bound", + "monthlyCost": 126.53, + "saving": 255.5, + "comeAliveS": 240.0, + "comeAliveBasis": "boot-evidence", + "blockedBy": [ + { + "field": "itlP99Ms", + "bound": 80, + "measured": 118 + } + ], + "receipt": { + "uri": "receipts/qwen-qwen3-8b/l4-c8-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000005" + } + }, + "current": { + "identity": "Qwen/Qwen3-8B", + "lane": "qwen-qwen3-8b-a100-80gb", + "warmth": "cold-with-bound" + } + }, + { + "identity": "Qwen/Qwen3-Embedding-4B", + "status": "placed", + "serviceLevel": { + "comeAliveP95S": 30, + "warmP99Ms": 300 + }, + "demandRequests": 3600, + "lane": "qwen-qwen3-embedding-4b-l4", + "chosen": { + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 8, + "warmth": "pinned", + "monthlyCost": 759.2, + "comeAliveS": 0.0, + "comeAliveBasis": "warm-floor", + "receipt": { + "uri": "receipts/qwen-qwen3-embedding-4b/l4-c8-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000007" + } + }, + "peakContainers": 1, + "nextCheaper": { + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 8, + "warmth": "snapshot-cold", + "monthlyCost": 379.6, + "saving": 379.6, + "comeAliveS": 45.0, + "comeAliveBasis": "boot-evidence", + "blockedBy": [ + { + "field": "comeAliveP95S", + "bound": 30, + "measured": 45.0 + } + ], + "receipt": { + "uri": "receipts/qwen-qwen3-embedding-4b/l4-c8-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000007" + } + } + }, + { + "identity": "Qwen/Qwen3-Reranker-0.6B", + "status": "unplaced", + "serviceLevel": { + "comeAliveP95S": 90, + "warmP99Ms": 400 + }, + "demandRequests": 0, + "unplacedReason": "no-receipt" + }, + { + "identity": "intfloat/e5-base-v2", + "status": "kept", + "serviceLevel": { + "comeAliveP95S": 0, + "warmP99Ms": 250, + "queueWaitP99Ms": 500 + }, + "demandRequests": 40, + "lane": "default-l4-default", + "unplacedReason": "no-receipt", + "current": { + "identity": "intfloat/e5-base-v2", + "lane": "default-l4-default", + "warmth": "pinned" + } + } + ], + "lanes": [ + { + "name": "baai-bge-m3-l4", + "identities": [ + "BAAI/bge-m3" + ], + "hourlyCost": 1.04, + "floorMonthlyCost": 759.2, + "envelopeMaxMonthlyCost": 1518.4 + }, + { + "name": "baai-bge-m3-sparse-l4", + "identities": [ + "BAAI/bge-m3:sparse" + ], + "hourlyCost": 1.04, + "floorMonthlyCost": 0.0, + "envelopeMaxMonthlyCost": 1518.4 + }, + { + "name": "default-l4-default", + "identities": [ + "intfloat/e5-base-v2" + ], + "hourlyCost": 1.04, + "floorMonthlyCost": 759.2, + "envelopeMaxMonthlyCost": 1518.4 + }, + { + "name": "qwen-qwen3-8b-a100-80gb", + "identities": [ + "Qwen/Qwen3-8B" + ], + "hourlyCost": 3.14, + "floorMonthlyCost": 0.0, + "envelopeMaxMonthlyCost": 4584.4 + }, + { + "name": "qwen-qwen3-embedding-4b-l4", + "identities": [ + "Qwen/Qwen3-Embedding-4B" + ], + "hourlyCost": 1.04, + "floorMonthlyCost": 759.2, + "envelopeMaxMonthlyCost": 1518.4 + } + ], + "measurementRequests": [ + { + "identity": "Qwen/Qwen3-Reranker-0.6B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "measure": [ + "receipt", + "boot-evidence" + ], + "warmth": "cold-with-bound", + "reason": "unmeasured", + "costBound": 0.0 + }, + { + "identity": "Qwen/Qwen3-Reranker-0.6B", + "cell": { + "machineProfile": "h100", + "gpuProduct": "NVIDIA-H100-80GB-HBM3" + }, + "measure": [ + "receipt", + "boot-evidence" + ], + "warmth": "cold-with-bound", + "reason": "unmeasured", + "costBound": 0.0 + }, + { + "identity": "Qwen/Qwen3-Reranker-0.6B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "measure": [ + "receipt", + "boot-evidence" + ], + "warmth": "cold-with-bound", + "reason": "refused", + "costBound": 0.0 + }, + { + "identity": "Qwen/Qwen3-Reranker-0.6B", + "cell": { + "machineProfile": "l40s", + "gpuProduct": "NVIDIA-L40S" + }, + "measure": [ + "receipt", + "boot-evidence" + ], + "warmth": "cold-with-bound", + "reason": "unmeasured", + "costBound": 0.0 + }, + { + "identity": "intfloat/e5-base-v2", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "measure": [ + "receipt" + ], + "warmth": "pinned", + "reason": "unmeasured", + "costBound": 1825.0 + }, + { + "identity": "intfloat/e5-base-v2", + "cell": { + "machineProfile": "h100", + "gpuProduct": "NVIDIA-H100-80GB-HBM3" + }, + "measure": [ + "receipt" + ], + "warmth": "pinned", + "reason": "unmeasured", + "costBound": 2920.0 + }, + { + "identity": "intfloat/e5-base-v2", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "measure": [ + "receipt" + ], + "warmth": "pinned", + "reason": "unmeasured", + "costBound": 584.0 + }, + { + "identity": "intfloat/e5-base-v2", + "cell": { + "machineProfile": "l40s", + "gpuProduct": "NVIDIA-L40S" + }, + "measure": [ + "receipt" + ], + "warmth": "pinned", + "reason": "unmeasured", + "costBound": 876.0 + }, + { + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "l40s", + "gpuProduct": "NVIDIA-L40S" + }, + "measure": [ + "receipt", + "boot-evidence" + ], + "warmth": "cold-with-bound", + "reason": "unmeasured", + "costBound": 438.0, + "savingBound": 321.2 + }, + { + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 32768 + }, + "measure": [ + "boot-evidence" + ], + "warmth": "cold-with-bound", + "reason": "unmeasured", + "costBound": 467.2, + "savingBound": 292.0 + }, + { + "identity": "Qwen/Qwen3-8B", + "cell": { + "machineProfile": "l40s", + "gpuProduct": "NVIDIA-L40S" + }, + "measure": [ + "receipt", + "boot-evidence" + ], + "warmth": "cold-with-bound", + "reason": "unmeasured", + "costBound": 146.0, + "savingBound": 236.03 + } + ], + "comeAliveLevers": [ + { + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "cold-with-bound", + "comeAliveS": 240.0, + "comeAliveBasis": "boot-evidence", + "comeAliveBoundS": 30, + "monthlyCost": 379.6, + "savingUnderBound": 379.6, + "permittedBoundS": 240, + "savingAtPermittedBound": 379.6 + }, + { + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "snapshot-cold", + "comeAliveS": 45.0, + "comeAliveBasis": "boot-evidence", + "comeAliveBoundS": 30, + "monthlyCost": 379.6, + "savingUnderBound": 379.6, + "permittedBoundS": 45, + "savingAtPermittedBound": 379.6 + }, + { + "identity": "BAAI/bge-m3", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "cold-with-bound", + "comeAliveS": 95.0, + "comeAliveBasis": "borrowed-boot-evidence", + "comeAliveBoundS": 0, + "monthlyCost": 569.4, + "savingUnderBound": 0.0, + "permittedBoundS": 95, + "savingAtPermittedBound": 189.8 + }, + { + "identity": "BAAI/bge-m3", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "warmth": "snapshot-cold", + "comeAliveS": 8.5, + "comeAliveBasis": "boot-evidence", + "comeAliveBoundS": 0, + "monthlyCost": 569.4, + "savingUnderBound": 0.0, + "permittedBoundS": 9, + "savingAtPermittedBound": 189.8 + } + ], + "queueWaitUnattained": [ + "BAAI/bge-m3", + "BAAI/bge-m3:sparse", + "intfloat/e5-base-v2" + ], + "refusals": [ + { + "record": "boot-evidence", + "identity": "Qwen/Qwen3-Reranker-0.6B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-40GB" + }, + "source": { + "uri": "boots/qwen-qwen3-reranker-0.6b/a100-80gb-cold-with-bound-10.json", + "sha256": "000000000000000000000000000000000000000000000000000000000000006e" + }, + "reason": "realized GPU product 'NVIDIA-A100-SXM4-40GB' differs from 'NVIDIA-A100-SXM4-80GB', the product machine profile 'a100-80gb' requests" + }, + { + "record": "receipt", + "identity": "Qwen/Qwen3-Reranker-0.6B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-A10G" + }, + "source": { + "uri": "receipts/qwen-qwen3-reranker-0.6b/l4-c16-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000006" + }, + "reason": "realized GPU product 'NVIDIA-A10G' differs from 'NVIDIA-L4', the product machine profile 'l4' requests" + } + ], + "changes": { + "identities": [ + { + "identity": "BAAI/bge-m3", + "before": { + "identity": "BAAI/bge-m3", + "lane": "default-l4-default", + "warmth": "pinned" + }, + "after": { + "identity": "BAAI/bge-m3", + "lane": "baai-bge-m3-l4", + "warmth": "pinned" + } + }, + { + "identity": "BAAI/bge-m3:sparse", + "after": { + "identity": "BAAI/bge-m3:sparse", + "lane": "baai-bge-m3-sparse-l4", + "warmth": "cold-with-bound" + } + }, + { + "identity": "Qwen/Qwen3-Embedding-4B", + "after": { + "identity": "Qwen/Qwen3-Embedding-4B", + "lane": "qwen-qwen3-embedding-4b-l4", + "warmth": "pinned" + } + } + ], + "lanes": [ + { + "name": "baai-bge-m3-l4", + "after": { + "name": "baai-bge-m3-l4", + "queuePool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "maxContainers": 4, + "envelope": { + "floorMin": 1, + "floorMax": 2 + } + } + }, + { + "name": "baai-bge-m3-sparse-l4", + "after": { + "name": "baai-bge-m3-sparse-l4", + "queuePool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "maxContainers": 4, + "envelope": { + "floorMin": 0, + "floorMax": 2 + } + } + }, + { + "name": "qwen-qwen3-embedding-4b-l4", + "after": { + "name": "qwen-qwen3-embedding-4b-l4", + "queuePool": "default", + "bundle": "default", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 8, + "maxContainers": 4, + "envelope": { + "floorMin": 1, + "floorMax": 2 + } + } + } + ] + } +} diff --git a/packages/sie_placement/tests/fixtures/planner/price-list.json b/packages/sie_placement/tests/fixtures/planner/price-list.json new file mode 100644 index 000000000..08d835d8a --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/price-list.json @@ -0,0 +1,45 @@ +{ + "kind": "placement-price-list", + "schemaVersion": 1, + "currency": "USD", + "machineProfiles": [ + { + "name": "l4", + "gpuProduct": "NVIDIA-L4", + "acceleratorPerHour": 0.8, + "corePerHour": 0.04, + "memoryGiBPerHour": 0.005 + }, + { + "name": "l40s", + "gpuProduct": "NVIDIA-L40S", + "acceleratorPerHour": 1.2, + "corePerHour": 0.04, + "memoryGiBPerHour": 0.005 + }, + { + "name": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB", + "acceleratorPerHour": 2.5, + "corePerHour": 0.04, + "memoryGiBPerHour": 0.005 + }, + { + "name": "h100", + "gpuProduct": "NVIDIA-H100-80GB-HBM3", + "acceleratorPerHour": 4.0, + "corePerHour": 0.04, + "memoryGiBPerHour": 0.005 + } + ], + "placements": [ + { + "name": "us-central1", + "regionMultiplier": 1 + }, + { + "name": "europe-west4", + "regionMultiplier": 1.25 + } + ] +} diff --git a/packages/sie_placement/tests/fixtures/planner/receipts.json b/packages/sie_placement/tests/fixtures/planner/receipts.json new file mode 100644 index 000000000..c29fe2621 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/receipts.json @@ -0,0 +1,295 @@ +[ + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "BAAI/bge-m3", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "requestShape": { + "operation": "encode", + "itemsPerRequest": 8, + "inputTokensPerItem": 256 + }, + "throughput": { + "requestsPerSecond": 40 + }, + "latency": { + "p50Ms": 110.2, + "p95Ms": 171.9, + "p99Ms": 214 + }, + "source": { + "uri": "receipts/baai-bge-m3/l4-c16-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000001" + } + }, + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "BAAI/bge-m3", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "concurrency": 32, + "requestShape": { + "operation": "encode", + "itemsPerRequest": 8, + "inputTokensPerItem": 256 + }, + "throughput": { + "requestsPerSecond": 120 + }, + "latency": { + "p50Ms": 61, + "p95Ms": 98, + "p99Ms": 120 + }, + "source": { + "uri": "receipts/baai-bge-m3/a100-80gb-c32-65536.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000002" + } + }, + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "BAAI/bge-m3:sparse", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "requestShape": { + "operation": "encode", + "itemsPerRequest": 8, + "inputTokensPerItem": 256 + }, + "throughput": { + "requestsPerSecond": 40 + }, + "latency": { + "p50Ms": 101, + "p99Ms": 190 + }, + "source": { + "uri": "receipts/baai-bge-m3-sparse/l4-c16-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000003" + } + }, + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-8B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "concurrency": 32, + "requestShape": { + "operation": "generate", + "itemsPerRequest": 1, + "inputTokensPerItem": 1024, + "outputTokens": 256 + }, + "throughput": { + "requestsPerSecond": 3.1, + "outputTokensPerSecond": 793.6 + }, + "ttft": { + "p50Ms": 310, + "p99Ms": 1480 + }, + "itl": { + "p50Ms": 24.5, + "p95Ms": 31, + "p99Ms": 44.8 + }, + "source": { + "uri": "receipts/qwen-qwen3-8b/a100-80gb-c32-65536.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000004" + } + }, + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-8B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 8, + "requestShape": { + "operation": "generate", + "itemsPerRequest": 1, + "inputTokensPerItem": 1024, + "outputTokens": 256 + }, + "throughput": { + "requestsPerSecond": 0.9, + "outputTokensPerSecond": 230.4 + }, + "ttft": { + "p50Ms": 820, + "p99Ms": 3900 + }, + "itl": { + "p50Ms": 61, + "p99Ms": 118 + }, + "source": { + "uri": "receipts/qwen-qwen3-8b/l4-c8-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000005" + } + }, + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-Reranker-0.6B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-A10G" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "requestShape": { + "operation": "score", + "itemsPerRequest": 8, + "inputTokensPerItem": 256 + }, + "throughput": { + "requestsPerSecond": 55 + }, + "latency": { + "p99Ms": 180 + }, + "source": { + "uri": "receipts/qwen-qwen3-reranker-0.6b/l4-c16-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000006" + } + }, + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 8, + "requestShape": { + "operation": "encode", + "itemsPerRequest": 8, + "inputTokensPerItem": 256 + }, + "throughput": { + "requestsPerSecond": 12 + }, + "latency": { + "p50Ms": 140, + "p99Ms": 280 + }, + "source": { + "uri": "receipts/qwen-qwen3-embedding-4b/l4-c8-16384.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000007" + } + }, + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 32768 + }, + "concurrency": 8, + "requestShape": { + "operation": "encode", + "itemsPerRequest": 8, + "inputTokensPerItem": 256 + }, + "throughput": { + "requestsPerSecond": 14 + }, + "latency": { + "p50Ms": 131, + "p99Ms": 262 + }, + "source": { + "uri": "receipts/qwen-qwen3-embedding-4b/l4-c8-32768.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000008" + } + }, + { + "kind": "placement-receipt", + "schemaVersion": 1, + "identity": "Qwen/Qwen3-Embedding-4B", + "cell": { + "machineProfile": "a100-80gb", + "gpuProduct": "NVIDIA-A100-SXM4-80GB" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 8, + "memoryMiB": 65536 + }, + "concurrency": 16, + "requestShape": { + "operation": "encode", + "itemsPerRequest": 8, + "inputTokensPerItem": 256 + }, + "throughput": { + "requestsPerSecond": 40 + }, + "latency": { + "p50Ms": 70, + "p99Ms": 150 + }, + "source": { + "uri": "receipts/qwen-qwen3-embedding-4b/a100-80gb-c16-65536.json", + "sha256": "0000000000000000000000000000000000000000000000000000000000000009" + } + } +] diff --git a/packages/sie_placement/tests/fixtures/planner/service-levels.json b/packages/sie_placement/tests/fixtures/planner/service-levels.json new file mode 100644 index 000000000..7a0da5891 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/service-levels.json @@ -0,0 +1,48 @@ +{ + "kind": "placement-service-levels", + "schemaVersion": 1, + "tiers": [ + { + "name": "interactive-retrieval", + "comeAliveP95S": 0, + "warmP99Ms": 250, + "queueWaitP99Ms": 500 + }, + { + "name": "batch-generation", + "comeAliveP95S": 600, + "ttftP99Ms": 4000, + "itlP99Ms": 120 + } + ], + "identities": [ + { + "identity": "BAAI/bge-m3", + "tier": "interactive-retrieval" + }, + { + "identity": "BAAI/bge-m3:sparse", + "tier": "interactive-retrieval", + "comeAliveP95S": 120 + }, + { + "identity": "Qwen/Qwen3-8B", + "tier": "batch-generation", + "itlP99Ms": 80 + }, + { + "identity": "Qwen/Qwen3-Reranker-0.6B", + "comeAliveP95S": 90, + "warmP99Ms": 400 + }, + { + "identity": "intfloat/e5-base-v2", + "tier": "interactive-retrieval" + }, + { + "identity": "Qwen/Qwen3-Embedding-4B", + "comeAliveP95S": 30, + "warmP99Ms": 300 + } + ] +} diff --git a/packages/sie_placement/tests/test_levers.py b/packages/sie_placement/tests/test_levers.py new file mode 100644 index 000000000..27e8a02df --- /dev/null +++ b/packages/sie_placement/tests/test_levers.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +import pytest +from sie_placement.planner import PlannerParameters, plan +from sie_placement.report import ComeAliveBasis +from sie_placement.schema import ( + BootEvidence, + BootOutcome, + Cell, + ContainerShape, + Demand, + DemandHour, + DemandSeries, + IdentityServiceLevel, + MachineProfilePrice, + Operation, + Percentiles, + Placement, + PriceList, + Receipt, + RequestShape, + ServiceLevel, + ServiceLevels, + SourceRef, + Throughput, + Warmth, +) + +START = datetime(2026, 11, 2, tzinfo=UTC) +MONTH = 730.0 +SCALE = MONTH / 24 +L4 = Cell(machine_profile="l4", gpu_product="NVIDIA-L4") +A100 = Cell(machine_profile="a100-80gb", gpu_product="NVIDIA-A100-SXM4-80GB") +SHAPE = ContainerShape(gpu_count=1, cpu_cores=4, memory_mib=16384) +WIDE = ContainerShape(gpu_count=1, cpu_cores=8, memory_mib=32768) +PRICES = PriceList( + currency="USD", + machine_profiles=( + MachineProfilePrice( + name="l4", gpu_product="NVIDIA-L4", accelerator_per_hour=1.0, core_per_hour=0.1, memory_gib_per_hour=0.0 + ), + MachineProfilePrice( + name="a100-80gb", + gpu_product="NVIDIA-A100-SXM4-80GB", + accelerator_per_hour=3.0, + core_per_hour=0.1, + memory_gib_per_hour=0.0, + ), + ), + placements=(Placement(name="test", region_multiplier=1),), +) +PARAMETERS = PlannerParameters(placement="test", max_containers=4, fallback_floor=2, cooldown_s=900) +L4_HOURLY = 1.0 + 4 * 0.1 + + +def receipt(identity, cell=L4, *, shape=SHAPE, p99=100.0, concurrency=8): + return Receipt( + identity=identity, + cell=cell, + container_shape=shape, + concurrency=concurrency, + request_shape=RequestShape(operation=Operation.ENCODE, items_per_request=1), + throughput=Throughput(requests_per_second=10.0), + latency=Percentiles(p99_ms=p99), + source=SourceRef(uri=f"receipts/{identity}/{cell.machine_profile}/{shape.memory_mib}/{concurrency}"), + ) + + +def boot(identity, seconds, warmth=Warmth.COLD_WITH_BOUND, cell=L4, *, shape=SHAPE, borrowed=False): + return BootEvidence( + identity=identity, + cell=cell, + container_shape=shape, + warmth=warmth, + boot_seconds=seconds, + outcome=BootOutcome.SUCCEEDED, + borrowed=borrowed, + source=SourceRef(uri=f"boots/{identity}/{cell.machine_profile}/{warmth.value}"), + ) + + +def busy(*identities, hours=6): + return Demand( + start=START, + end=START + timedelta(hours=24), + series=tuple( + DemandSeries( + identity=identity, + operation=Operation.ENCODE, + hours=tuple(DemandHour(start=START + timedelta(hours=hour), requests=10) for hour in range(hours)), + ) + for identity in identities + ), + ) + + +def run(bounds, receipts, boots, demand=None): + service_levels = ServiceLevels( + identities=tuple( + IdentityServiceLevel(identity=identity, level=ServiceLevel(come_alive_p95_s=bound, warm_p99_ms=250)) + for identity, bound in bounds.items() + ) + ) + return plan(service_levels, receipts, boots, PRICES, demand or busy(*bounds), None, PARAMETERS).report + + +def cold_cost(hours=6): + return L4_HOURLY * hours * 2 * SCALE + + +def test_a_zero_bound_lever_saves_nothing_under_its_bound_and_is_priced_at_the_bound_it_permits(): + report = run({"org/warm": 0}, [receipt("org/warm")], [boot("org/warm", 95.2, borrowed=True)]) + (lever,) = report.come_alive_levers + assert (lever.identity, lever.cell, lever.container_shape, lever.warmth) == ( + "org/warm", + L4, + SHAPE, + Warmth.COLD_WITH_BOUND, + ) + assert (lever.bound_s, lever.come_alive_s, lever.permitted_bound_s) == (0, 95.2, 96) + assert lever.come_alive_basis is ComeAliveBasis.BORROWED_BOOT_EVIDENCE + assert lever.saving_under_bound == 0 + assert lever.monthly_cost == pytest.approx(cold_cost()) + assert lever.saving_at_permitted_bound == pytest.approx(L4_HOURLY * MONTH - cold_cost()) + + +def test_a_finite_bound_lever_saves_the_same_under_its_bound_and_at_the_bound_it_permits(): + report = run({"org/slow": 60}, [receipt("org/slow")], [boot("org/slow", 240.0)]) + (lever,) = report.come_alive_levers + assert (lever.bound_s, lever.permitted_bound_s) == (60, 240) + assert lever.saving_under_bound == pytest.approx(L4_HOURLY * MONTH - cold_cost()) + assert lever.saving_at_permitted_bound == lever.saving_under_bound + + +@pytest.mark.parametrize("seconds", [0.0, 0.4]) +def test_a_sub_second_restore_permits_a_one_second_bound(seconds): + report = run({"org/warm": 0}, [receipt("org/warm")], [boot("org/warm", seconds, Warmth.SNAPSHOT_COLD)]) + assert report.come_alive_levers[0].permitted_bound_s == 1 + + +def test_levers_rank_by_the_saving_under_the_bound_then_at_the_permitted_bound(): + bounds = {"org/always-warm": 0, "org/small-saving": 60, "org/big-saving": 60, "org/zero-quiet": 0} + receipts = [receipt(identity) for identity in bounds] + boots = [boot(identity, 120.0) for identity in bounds] + demand = Demand( + start=START, + end=START + timedelta(hours=24), + series=( + *busy("org/small-saving", hours=8).series, + *busy("org/big-saving", hours=2).series, + *busy("org/always-warm", hours=1).series, + *busy("org/zero-quiet", hours=4).series, + ), + ) + report = run(bounds, receipts, boots, demand) + ranked = [(lever.identity, lever.saving_under_bound > 0) for lever in report.come_alive_levers] + assert ranked == [ + ("org/big-saving", True), + ("org/small-saving", True), + ("org/always-warm", False), + ("org/zero-quiet", False), + ] + savings = [lever.saving_at_permitted_bound for lever in report.come_alive_levers] + assert savings[2] > savings[3] + + +def test_a_cell_that_misses_its_warm_bound_offers_no_lever(): + report = run( + {"org/model": 60}, [receipt("org/model", p99=400.0), receipt("org/model", A100)], [boot("org/model", 240.0)] + ) + assert report.come_alive_levers == () + assert report.identity("org/model").chosen.cell == A100 + + +def test_a_cold_posture_that_is_not_cheaper_offers_no_lever(): + report = run({"org/model": 60}, [receipt("org/model")], [boot("org/model", 240.0)], busy("org/model", hours=24)) + assert report.identity("org/model").chosen.warmth is Warmth.PINNED + assert report.come_alive_levers == () + + +def test_an_undeclared_bound_offers_no_lever(): + report = run({"org/model": None}, [receipt("org/model")], [boot("org/model", 240.0)]) + assert report.identity("org/model").chosen.warmth is Warmth.COLD_WITH_BOUND + assert report.come_alive_levers == () + + +def test_a_measured_come_alive_under_the_bound_is_a_choice_and_not_a_lever(): + report = run({"org/model": 60}, [receipt("org/model")], [boot("org/model", 30.0)]) + assert report.identity("org/model").chosen.warmth is Warmth.COLD_WITH_BOUND + assert report.come_alive_levers == () + + +def test_each_cell_shape_and_warmth_is_one_lever_at_its_cheapest_receipt(): + receipts = [ + receipt("org/model", concurrency=8), + receipt("org/model", concurrency=16), + receipt("org/model", shape=WIDE), + ] + boots = [ + boot("org/model", 240.0), + boot("org/model", 30.0 + 60.0, Warmth.SNAPSHOT_COLD), + boot("org/model", 300.0, shape=WIDE), + ] + report = run({"org/model": 60}, receipts, boots) + keys = [(lever.container_shape, lever.warmth) for lever in report.come_alive_levers] + assert sorted(keys, key=str) == sorted( + [(SHAPE, Warmth.COLD_WITH_BOUND), (SHAPE, Warmth.SNAPSHOT_COLD), (WIDE, Warmth.COLD_WITH_BOUND)], key=str + ) + assert len(keys) == len(set(keys)) + by_key = {(lever.container_shape, lever.warmth): lever for lever in report.come_alive_levers} + assert by_key[(SHAPE, Warmth.COLD_WITH_BOUND)].monthly_cost == pytest.approx(cold_cost()) + assert by_key[(WIDE, Warmth.COLD_WITH_BOUND)].monthly_cost == pytest.approx((1.0 + 8 * 0.1) * 6 * 2 * SCALE) + assert by_key[(SHAPE, Warmth.SNAPSHOT_COLD)].permitted_bound_s == 90 diff --git a/packages/sie_placement/tests/test_planner.py b/packages/sie_placement/tests/test_planner.py new file mode 100644 index 000000000..90776c2bd --- /dev/null +++ b/packages/sie_placement/tests/test_planner.py @@ -0,0 +1,893 @@ +from __future__ import annotations + +import hashlib +import json +import math +import random +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest +from sie_placement.planner import ( + PlannerInputError, + PlannerParameters, + container_hourly_cost, + envelope_for, + plan, +) +from sie_placement.report import ( + Blocker, + ComeAliveBasis, + IdentityStatus, + Measurement, + RefusedRecord, + RequestReason, + UnplacedReason, + render, +) +from sie_placement.schema import ( + BootEvidence, + BootOutcome, + Cell, + ContainerShape, + Demand, + DemandHour, + DemandSeries, + Envelope, + IdentityServiceLevel, + MachineProfilePrice, + Operation, + Percentiles, + Placement, + Plan, + PlanIdentity, + PlanLane, + PriceList, + Receipt, + RequestShape, + SchemaError, + ServiceLevel, + ServiceLevels, + SourceRef, + Throughput, + Warmth, +) + +FIXTURES = Path(__file__).parent / "fixtures" / "planner" +START = datetime(2026, 11, 2, tzinfo=UTC) +WINDOW_HOURS = 24 +MONTH = 730.0 +SCALE = MONTH / WINDOW_HOURS + +L4 = Cell(machine_profile="l4", gpu_product="NVIDIA-L4") +L40S = Cell(machine_profile="l40s", gpu_product="NVIDIA-L40S") +A100 = Cell(machine_profile="a100-80gb", gpu_product="NVIDIA-A100-SXM4-80GB") +SHAPE = ContainerShape(gpu_count=1, cpu_cores=4, memory_mib=16384) +WIDE = ContainerShape(gpu_count=1, cpu_cores=8, memory_mib=32768) +IDENTITY = "org/model" + +ESTATE_PARAMETERS = PlannerParameters( + placement="us-central1", + max_containers=4, + fallback_floor=2, + cooldown_s=900, + buffer_containers=1, + bundles={"Qwen/Qwen3-8B": "sglang"}, +) + + +def profile(cell: Cell, accelerator: float, core: float = 0.0) -> MachineProfilePrice: + return MachineProfilePrice( + name=cell.machine_profile, + gpu_product=cell.gpu_product, + accelerator_per_hour=accelerator, + core_per_hour=core, + memory_gib_per_hour=0.0, + ) + + +def price_list(*, l4=1.0, a100=3.0, core=0.0, multiplier=1.0, extra=()) -> PriceList: + profiles = [profile(cell, rate, core) for cell, rate in ((L4, l4), (A100, a100)) if rate is not None] + return PriceList( + currency="USD", + machine_profiles=(*profiles, *extra), + placements=(Placement(name="test", region_multiplier=multiplier),), + ) + + +L4_ONLY = price_list(a100=None) + + +def receipt(identity=IDENTITY, cell=L4, *, shape=SHAPE, concurrency=8, rps=10.0, p99=100.0, uri=None) -> Receipt: + return Receipt( + identity=identity, + cell=cell, + container_shape=shape, + concurrency=concurrency, + request_shape=RequestShape(operation=Operation.ENCODE, items_per_request=1), + throughput=Throughput(requests_per_second=rps), + latency=Percentiles(p99_ms=p99), + source=SourceRef(uri=uri or f"receipts/{identity}/{cell.machine_profile}-{concurrency}-{shape.memory_mib}"), + ) + + +def generation_receipt(identity=IDENTITY, cell=A100, *, ttft=1000.0, itl=40.0, rps=2.0) -> Receipt: + return Receipt( + identity=identity, + cell=cell, + container_shape=SHAPE, + concurrency=16, + request_shape=RequestShape(operation=Operation.GENERATE, items_per_request=1, output_tokens=256), + throughput=Throughput(requests_per_second=rps, output_tokens_per_second=rps * 256), + ttft=Percentiles(p99_ms=ttft), + itl=Percentiles(p99_ms=itl), + source=SourceRef(uri=f"receipts/{identity}/{cell.machine_profile}-generate"), + ) + + +def boot( + identity=IDENTITY, + cell=L4, + warmth=Warmth.COLD_WITH_BOUND, + seconds=60.0, + *, + outcome=BootOutcome.SUCCEEDED, + borrowed=False, + shape=SHAPE, + uri="boots/example.json", +) -> BootEvidence: + return BootEvidence( + identity=identity, + cell=cell, + container_shape=shape, + warmth=warmth, + boot_seconds=seconds, + outcome=outcome, + borrowed=borrowed, + source=SourceRef(uri=uri), + ) + + +def levels(*entries: tuple[str, ServiceLevel]) -> ServiceLevels: + return ServiceLevels(identities=tuple(IdentityServiceLevel(identity=name, level=lvl) for name, lvl in entries)) + + +def level(**fields) -> ServiceLevels: + return levels((IDENTITY, ServiceLevel(**fields))) + + +def demand(hourly=None) -> Demand: + return Demand( + start=START, + end=START + timedelta(hours=WINDOW_HOURS), + series=tuple( + DemandSeries( + identity=identity, + operation=Operation.ENCODE, + hours=tuple( + DemandHour(start=START + timedelta(hours=hour), requests=requests) + for hour, requests in sorted(counts.items()) + ), + ) + for identity, counts in sorted((hourly or {}).items()) + ), + ) + + +def parameters(**overrides) -> PlannerParameters: + values = {"placement": "test", "max_containers": 4, "fallback_floor": 2, "cooldown_s": 900} | overrides + return PlannerParameters(**values) + + +def run(service_levels, receipts=(), boots=(), *, prices=None, hourly=None, current=None, **overrides): + return plan( + service_levels, + receipts, + boots, + prices or price_list(), + demand(hourly), + current, + parameters(**overrides), + ) + + +def single_lane_plan(name="shared", warmth=Warmth.PINNED, cell=L4, identity=IDENTITY) -> Plan: + floor = 1 if warmth is Warmth.PINNED else 0 + return Plan( + placement="test", + lanes=( + PlanLane( + name=name, + queue_pool="default", + bundle="default", + cell=cell, + container_shape=SHAPE, + concurrency=8, + max_containers=2, + envelope=Envelope(floor_min=floor, floor_max=max(floor, 1)), + ), + ), + identities=(PlanIdentity(identity=identity, lane=name, warmth=warmth),), + ) + + +def load(name: str): + return json.loads((FIXTURES / name).read_text(encoding="utf-8")) + + +def estate() -> dict: + return { + "service_levels": ServiceLevels.from_dict(load("service-levels.json")), + "receipts": [Receipt.from_dict(document) for document in load("receipts.json")], + "boot_evidence": [BootEvidence.from_dict(document) for document in load("boot-evidence.json")], + "price_list": PriceList.from_dict(load("price-list.json")), + "demand": Demand.from_dict(load("demand.json")), + "current_plan": Plan.from_dict(load("current-plan.json")), + "parameters": ESTATE_PARAMETERS, + } + + +def rendered(result) -> tuple[str, str]: + return render(result.plan.to_dict()), render(result.report.to_dict()) + + +def test_container_hourly_cost_prices_accelerators_cores_and_memory(): + price = MachineProfilePrice( + name="l4", gpu_product="NVIDIA-L4", accelerator_per_hour=2.0, core_per_hour=0.05, memory_gib_per_hour=0.01 + ) + shape = ContainerShape(gpu_count=2, cpu_cores=8, memory_mib=20480) + assert container_hourly_cost(price, shape, 1.5) == pytest.approx(1.5 * (2 * 2.0 + 8 * 0.05 + 20 * 0.01)) + + +def test_a_pinned_cell_costs_its_floor_plus_the_hours_demand_needs_above_it(): + result = run(level(come_alive_p95_s=0), [receipt(rps=1.0)], prices=L4_ONLY, hourly={IDENTITY: {3: 9000, 4: 100}}) + report = result.report.identity(IDENTITY) + assert report.status is IdentityStatus.PLACED + assert report.chosen.warmth is Warmth.PINNED + assert report.chosen.come_alive_basis is ComeAliveBasis.WARM_FLOOR + assert report.chosen.monthly_cost == pytest.approx(MONTH + (3 - 1) * SCALE) + assert report.peak_containers == 3 + assert report.demand_requests == 9100 + + +def test_needed_containers_stop_at_the_reviewed_ceiling(): + result = run( + level(come_alive_p95_s=0), [receipt(rps=1.0)], prices=L4_ONLY, hourly={IDENTITY: {0: 36000}}, max_containers=2 + ) + report = result.report.identity(IDENTITY) + assert report.chosen.monthly_cost == pytest.approx(MONTH + (2 - 1) * SCALE) + assert report.peak_containers == 10 + + +def test_a_cold_cell_costs_its_work_and_the_tail_each_burst_holds(): + result = run( + level(come_alive_p95_s=120), [receipt(rps=10.0)], [boot()], prices=L4_ONLY, hourly={IDENTITY: {0: 1, 5: 10}} + ) + chosen = result.report.identity(IDENTITY).chosen + assert chosen.warmth is Warmth.COLD_WITH_BOUND + assert chosen.come_alive_s == 60.0 + one_burst = 1 / 10.0 + 1 * 2 * 900 + capped_hour = 2 * 3600 + assert chosen.monthly_cost == pytest.approx((one_burst + capped_hour) / 3600 * SCALE) + + +def test_an_active_lane_without_a_fallback_floor_holds_one_container(): + result = run( + level(come_alive_p95_s=120), + [receipt(rps=10.0)], + [boot()], + prices=L4_ONLY, + hourly={IDENTITY: {0: 2}}, + fallback_floor=0, + cooldown_s=60, + ) + chosen = result.report.identity(IDENTITY).chosen + assert chosen.monthly_cost == pytest.approx((2 / 10.0 + 2 * 1 * 60) / 3600 * SCALE) + + +def test_the_active_floor_never_exceeds_the_ceiling(): + result = run( + level(come_alive_p95_s=120), + [receipt(rps=10.0)], + [boot()], + prices=L4_ONLY, + hourly={IDENTITY: {0: 1}}, + fallback_floor=3, + max_containers=1, + ) + chosen = result.report.identity(IDENTITY).chosen + assert chosen.monthly_cost == pytest.approx((1 / 10.0 + 1 * 1 * 900) / 3600 * SCALE) + + +def test_an_idle_cold_cell_costs_nothing_and_its_lane_keeps_no_floor(): + result = run(level(come_alive_p95_s=120), [receipt()], [boot()], prices=L4_ONLY) + chosen = result.report.identity(IDENTITY).chosen + assert chosen.warmth is Warmth.COLD_WITH_BOUND + assert chosen.monthly_cost == 0 + (lane,) = result.plan.lanes + assert lane.envelope == Envelope(floor_min=0, floor_max=0) + assert result.plan.identities == (PlanIdentity(identity=IDENTITY, lane=lane.name, warmth=Warmth.COLD_WITH_BOUND),) + + +def test_a_cold_posture_without_boot_evidence_is_a_measurement_request(): + result = run(level(come_alive_p95_s=120), [receipt()], prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.PINNED + (request,) = result.report.measurement_requests + assert request.measure == (Measurement.BOOT_EVIDENCE,) + assert request.warmth is Warmth.COLD_WITH_BOUND + assert request.reason is RequestReason.UNMEASURED + assert (request.cell, request.container_shape) == (L4, SHAPE) + assert request.cost_bound == 0 + assert request.saving_bound == pytest.approx(MONTH) + + +def test_a_failed_boot_is_not_selectable_and_asks_for_a_new_measurement(): + boots = [boot(seconds=900.0, outcome=BootOutcome.TIMED_OUT)] + result = run(level(come_alive_p95_s=600), [receipt()], boots, prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.PINNED + (request,) = result.report.measurement_requests + assert request.reason is RequestReason.FAILED + assert result.report.come_alive_levers == () + + +def test_a_failed_boot_disqualifies_the_successful_ones_beside_it(): + boots = [boot(seconds=40.0, uri="boots/1.json"), boot(seconds=0.0, outcome=BootOutcome.FAILED, uri="boots/2.json")] + result = run(level(come_alive_p95_s=600), [receipt()], boots, prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.PINNED + + +def test_the_slowest_successful_boot_stands_for_the_percentile(): + boots = [boot(seconds=80.0, uri="boots/1.json"), boot(seconds=130.0, uri="boots/2.json")] + result = run(level(come_alive_p95_s=120), [receipt()], boots, prices=L4_ONLY) + report = result.report.identity(IDENTITY) + assert report.chosen.warmth is Warmth.PINNED + assert report.next_cheaper.blocked_by == (Blocker(field="comeAliveP95S", bound=120, measured=130.0),) + + +def test_own_boot_evidence_replaces_borrowed_evidence(): + borrowed = boot(seconds=150.0, borrowed=True, uri="boots/borrowed.json") + own = boot(seconds=60.0, uri="boots/own.json") + result = run(level(come_alive_p95_s=120), [receipt()], [borrowed, own], prices=L4_ONLY) + chosen = result.report.identity(IDENTITY).chosen + assert (chosen.warmth, chosen.come_alive_s) == (Warmth.COLD_WITH_BOUND, 60.0) + assert chosen.come_alive_basis is ComeAliveBasis.BOOT_EVIDENCE + failed = boot(seconds=0.0, outcome=BootOutcome.FAILED, uri="boots/own-failed.json") + result = run(level(come_alive_p95_s=200), [receipt()], [boot(seconds=60.0, borrowed=True), failed], prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.PINNED + + +def test_borrowed_boot_evidence_stands_in_and_is_labelled(): + result = run(level(come_alive_p95_s=120), [receipt()], [boot(seconds=60.0, borrowed=True)], prices=L4_ONLY) + chosen = result.report.identity(IDENTITY).chosen + assert (chosen.warmth, chosen.come_alive_s) == (Warmth.COLD_WITH_BOUND, 60.0) + assert chosen.come_alive_basis is ComeAliveBasis.BORROWED_BOOT_EVIDENCE + assert chosen.to_dict()["comeAliveBasis"] == "borrowed-boot-evidence" + + +def test_a_zero_come_alive_bound_never_selects_a_cold_posture(): + boots = [boot(seconds=0.0), boot(warmth=Warmth.SNAPSHOT_COLD, seconds=0.0, uri="boots/snapshot.json")] + result = run(level(come_alive_p95_s=0), [receipt()], boots, prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.PINNED + assert result.report.measurement_requests == () + + +def test_an_undeclared_come_alive_bound_admits_any_measured_boot(): + result = run(level(warm_p99_ms=250), [receipt()], [boot(seconds=5000.0)], prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.COLD_WITH_BOUND + + +def test_a_snapshot_restore_under_the_bound_beats_a_slow_boot(): + boots = [boot(seconds=300.0), boot(warmth=Warmth.SNAPSHOT_COLD, seconds=20.0, uri="boots/snapshot.json")] + result = run(level(come_alive_p95_s=60), [receipt()], boots, prices=L4_ONLY) + chosen = result.report.identity(IDENTITY).chosen + assert chosen.warmth is Warmth.SNAPSHOT_COLD + assert chosen.come_alive_s == 20.0 + assert result.plan.identities[0].warmth is Warmth.SNAPSHOT_COLD + + +def test_equal_costs_prefer_the_faster_come_alive(): + boots = [boot(seconds=50.0), boot(warmth=Warmth.SNAPSHOT_COLD, seconds=20.0, uri="boots/snapshot.json")] + result = run(level(come_alive_p95_s=60), [receipt()], boots, prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.SNAPSHOT_COLD + + +def test_a_cell_whose_receipt_misses_the_warm_bound_is_never_chosen(): + receipts = [receipt(cell=L4, p99=300.0), receipt(cell=A100, p99=120.0)] + result = run(level(come_alive_p95_s=0, warm_p99_ms=250), receipts) + report = result.report.identity(IDENTITY) + assert report.chosen.cell == A100 + assert report.chosen.monthly_cost == pytest.approx(3 * MONTH) + assert report.next_cheaper.cell == L4 + assert report.next_cheaper.blocked_by == (Blocker(field="warmP99Ms", bound=250, measured=300.0),) + assert report.next_cheaper.saving == pytest.approx(2 * MONTH) + assert result.plan.lanes[0].cell == A100 + + +def test_generation_cells_meet_both_the_first_token_and_the_per_token_bound(): + receipts = [generation_receipt(cell=L4, ttft=2000.0, itl=95.0), generation_receipt(cell=A100, ttft=1200.0)] + result = run(level(come_alive_p95_s=0, ttft_p99_ms=1500, itl_p99_ms=80), receipts) + report = result.report.identity(IDENTITY) + assert report.chosen.cell == A100 + assert report.next_cheaper.blocked_by == ( + Blocker(field="ttftP99Ms", bound=1500, measured=2000.0), + Blocker(field="itlP99Ms", bound=80, measured=95.0), + ) + + +def test_a_receipt_whose_realized_product_differs_from_its_profile_is_refused(): + faster = Cell(machine_profile="l4", gpu_product="NVIDIA-L40S") + result = run(level(come_alive_p95_s=0), [receipt(cell=faster), receipt(cell=A100)]) + report = result.report.identity(IDENTITY) + assert report.chosen.cell == A100 + (refusal,) = result.report.refusals + assert refusal.record is RefusedRecord.RECEIPT + assert refusal.cell == faster + assert refusal.reason == ( + "realized GPU product 'NVIDIA-L40S' differs from 'NVIDIA-L4', the product machine profile 'l4' requests" + ) + (request,) = result.report.measurement_requests + assert (request.cell, request.reason, request.measure) == (L4, RequestReason.REFUSED, (Measurement.RECEIPT,)) + assert request.saving_bound == pytest.approx(2 * MONTH) + assert all(lane.cell != faster for lane in result.plan.lanes) + + +def test_boot_evidence_whose_realized_product_differs_from_its_profile_is_refused(): + other = Cell(machine_profile="l4", gpu_product="NVIDIA-A10G") + result = run(level(come_alive_p95_s=120), [receipt()], [boot(cell=other)], prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.PINNED + (refusal,) = result.report.refusals + assert refusal.record is RefusedRecord.BOOT_EVIDENCE + (request,) = result.report.measurement_requests + assert (request.measure, request.reason) == ((Measurement.BOOT_EVIDENCE,), RequestReason.UNMEASURED) + + +def test_a_receipt_on_an_unpriced_profile_is_refused(): + unpriced = Cell(machine_profile="t4", gpu_product="NVIDIA-T4") + result = run(level(come_alive_p95_s=0), [receipt(cell=unpriced)], prices=L4_ONLY) + report = result.report.identity(IDENTITY) + assert report.status is IdentityStatus.UNPLACED + assert report.unplaced_reason is UnplacedReason.NO_RECEIPT + assert result.report.refusals[0].reason == "machine profile 't4' has no price" + (request,) = result.report.measurement_requests + assert (request.cell, request.reason, request.saving_bound) == (L4, RequestReason.UNMEASURED, None) + + +@pytest.mark.parametrize( + ("service_level", "candidate", "reason"), + [ + ( + ServiceLevel(ttft_p99_ms=1000, itl_p99_ms=50), + receipt(), + "the receipt reports one latency and the service level declares ttftP99Ms and itlP99Ms", + ), + ( + ServiceLevel(warm_p99_ms=250), + generation_receipt(cell=L4), + "the receipt reports ttft and itl and the service level declares warmP99Ms", + ), + ], +) +def test_a_receipt_that_cannot_answer_the_service_level_is_refused(service_level, candidate, reason): + result = run(levels((IDENTITY, service_level)), [candidate], prices=L4_ONLY) + assert result.report.identity(IDENTITY).status is IdentityStatus.UNPLACED + assert [refusal.reason for refusal in result.report.refusals] == [reason] + + +def test_records_of_identities_without_a_service_level_are_ignored(): + stranger = Cell(machine_profile="l4", gpu_product="NVIDIA-A10G") + result = run( + level(come_alive_p95_s=0), + [receipt(), receipt(identity="org/other", cell=stranger)], + [boot(identity="org/other", cell=stranger)], + prices=L4_ONLY, + ) + assert result.report.refusals == () + assert [entry.identity for entry in result.plan.identities] == [IDENTITY] + assert [entry.identity for entry in result.report.identities] == [IDENTITY] + + +def test_an_unmeasured_cell_is_bounded_by_its_accelerator_price_alone(): + result = run(level(come_alive_p95_s=0), [receipt(cell=A100)], prices=price_list(core=0.5)) + chosen = result.report.identity(IDENTITY).chosen + assert chosen.monthly_cost == pytest.approx((3.0 + 4 * 0.5) * MONTH) + (request,) = result.report.measurement_requests + assert (request.cell, request.measure, request.warmth) == (L4, (Measurement.RECEIPT,), Warmth.PINNED) + assert request.cost_bound == pytest.approx(1.0 * MONTH) + assert request.saving_bound == pytest.approx((5.0 - 1.0) * MONTH) + + +def test_an_unmeasured_cell_under_a_finite_bound_is_bounded_by_its_burst_tails(): + result = run(level(come_alive_p95_s=300), [receipt(cell=A100)], hourly={IDENTITY: {0: 1}}) + requests = {request.cell: request for request in result.report.measurement_requests} + request = requests[L4] + assert request.measure == (Measurement.RECEIPT, Measurement.BOOT_EVIDENCE) + assert request.warmth is Warmth.COLD_WITH_BOUND + assert request.cost_bound == pytest.approx(1.0 * (1 * 2 * 900) / 3600 * SCALE) + assert requests[A100].measure == (Measurement.BOOT_EVIDENCE,) + + +def test_a_cell_that_cannot_save_is_not_requested(): + result = run(level(come_alive_p95_s=0), [receipt(cell=L4)]) + assert result.report.measurement_requests == () + + +def test_measurement_requests_rank_unplaced_identities_first_then_by_saving(): + service_levels = levels( + ("org/big", ServiceLevel(come_alive_p95_s=0)), + ("org/small", ServiceLevel(come_alive_p95_s=120)), + ("org/unplaced", ServiceLevel(come_alive_p95_s=0)), + ) + receipts = [receipt(identity="org/big", cell=A100), receipt(identity="org/small", cell=L4)] + result = run(service_levels, receipts) + ranked = [ + (request.identity, request.cell.machine_profile, request.measure, request.saving_bound) + for request in result.report.measurement_requests + ] + assert ranked == [ + ("org/unplaced", "a100-80gb", (Measurement.RECEIPT,), None), + ("org/unplaced", "l4", (Measurement.RECEIPT,), None), + ("org/big", "l4", (Measurement.RECEIPT,), pytest.approx(2 * MONTH)), + ("org/small", "a100-80gb", (Measurement.RECEIPT, Measurement.BOOT_EVIDENCE), pytest.approx(MONTH)), + ("org/small", "l4", (Measurement.BOOT_EVIDENCE,), pytest.approx(MONTH)), + ] + + +def test_the_next_cheaper_option_is_the_nearest_cheaper_one_and_names_its_bound(): + prices = price_list(extra=(profile(L40S, 2.0),)) + receipts = [receipt(cell=L4, p99=400.0), receipt(cell=L40S, p99=300.0), receipt(cell=A100, p99=100.0)] + result = run(level(come_alive_p95_s=0, warm_p99_ms=250), receipts, prices=prices) + report = result.report.identity(IDENTITY) + assert report.chosen.cell == A100 + assert report.next_cheaper.cell == L40S + assert report.next_cheaper.saving == pytest.approx(MONTH) + assert report.next_cheaper.blocked_by == (Blocker(field="warmP99Ms", bound=250, measured=300.0),) + + +def test_a_placement_with_nothing_cheaper_names_no_next_option(): + result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY) + assert result.report.identity(IDENTITY).next_cheaper is None + + +@pytest.mark.parametrize( + ("warmth", "buffer", "fallback", "ceiling", "expected"), + [ + (Warmth.PINNED, 0, 2, 4, (1, 1)), + (Warmth.PINNED, 2, 2, 4, (1, 3)), + (Warmth.PINNED, 5, 2, 4, (1, 4)), + (Warmth.COLD_WITH_BOUND, 0, 2, 4, (0, 0)), + (Warmth.COLD_WITH_BOUND, 1, 2, 4, (0, 2)), + (Warmth.COLD_WITH_BOUND, 3, 2, 4, (0, 3)), + (Warmth.COLD_WITH_BOUND, 1, 0, 4, (0, 1)), + (Warmth.COLD_WITH_BOUND, 1, 3, 2, (0, 2)), + (Warmth.SNAPSHOT_COLD, 1, 2, 4, (0, 2)), + ], +) +def test_envelopes_add_the_declared_buffer_at_realizable_floors(warmth, buffer, fallback, ceiling, expected): + envelope = envelope_for( + warmth, parameters(buffer_containers=buffer, fallback_floor=fallback, max_containers=ceiling) + ) + assert (envelope.floor_min, envelope.floor_max) == expected + assert (envelope.buffer_min, envelope.scaledown_window_min_s) == (None, None) + + +def test_the_plan_carries_the_envelope_and_the_report_prices_its_maximum(): + result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY, buffer_containers=2) + (lane,) = result.plan.lanes + assert lane.envelope == Envelope(floor_min=1, floor_max=3) + assert (lane.max_containers, lane.concurrency, lane.container_shape) == (4, 8, SHAPE) + (lane_report,) = result.report.lanes + assert lane_report.hourly_cost == pytest.approx(1.0) + assert lane_report.floor_monthly_cost == pytest.approx(MONTH) + assert lane_report.envelope_max_monthly_cost == pytest.approx(3 * MONTH) + assert result.report.envelope_max_monthly_cost == pytest.approx(3 * MONTH) + assert result.report.monthly_cost == pytest.approx(MONTH) + + +def test_every_declared_queue_wait_bound_is_reported_unattained(): + service_levels = levels( + ("org/a", ServiceLevel(come_alive_p95_s=0, queue_wait_p99_ms=500)), + ("org/b", ServiceLevel(come_alive_p95_s=0)), + ("org/c", ServiceLevel(queue_wait_p99_ms=30000)), + ) + result = run(service_levels, [receipt(identity="org/a")], prices=L4_ONLY) + assert result.report.queue_wait_unattained == ("org/a", "org/c") + + +def test_an_identity_without_a_feasible_cell_keeps_its_current_lane(): + current = single_lane_plan() + result = run(level(come_alive_p95_s=0, warm_p99_ms=50), [receipt(p99=100.0)], prices=L4_ONLY, current=current) + assert result.plan == current + report = result.report.identity(IDENTITY) + assert report.status is IdentityStatus.KEPT + assert report.unplaced_reason is UnplacedReason.WARM_BOUND_MISSED + assert report.lane == "shared" + assert report.current == current.identities[0] + assert result.report.unchanged + assert result.report.lanes[0].floor_monthly_cost == pytest.approx(MONTH) + + +def test_an_identity_without_a_feasible_cell_or_a_current_lane_is_left_out(): + result = run(level(come_alive_p95_s=0), [], prices=L4_ONLY) + assert (result.plan.lanes, result.plan.identities) == ((), ()) + report = result.report.identity(IDENTITY) + assert (report.status, report.unplaced_reason) == (IdentityStatus.UNPLACED, UnplacedReason.NO_RECEIPT) + assert result.report.monthly_cost == 0 + + +def test_lane_names_derive_from_the_identity_and_its_machine_profile(): + result = run(levels(("BAAI/bge-m3:sparse", ServiceLevel())), [receipt(identity="BAAI/bge-m3:sparse")]) + assert result.plan.lanes[0].name == "baai-bge-m3-sparse-l4" + + +def test_colliding_lane_names_take_an_identity_digest(): + service_levels = levels(("org/model", ServiceLevel()), ("org-model", ServiceLevel())) + receipts = [receipt(identity="org/model"), receipt(identity="org-model")] + result = run(service_levels, receipts, prices=L4_ONLY) + names = {entry.identity: entry.lane for entry in result.plan.identities} + assert names == { + identity: f"org-model-l4-{hashlib.sha256(identity.encode()).hexdigest()[:8]}" for identity in names + } + assert len(set(names.values())) == 2 + + +def test_a_derived_lane_name_never_takes_a_kept_lane_name(): + current = single_lane_plan(name="org-model-l4", identity="org/kept") + service_levels = levels(("org/kept", ServiceLevel(come_alive_p95_s=0)), (IDENTITY, ServiceLevel())) + result = run(service_levels, [receipt()], prices=L4_ONLY, current=current) + names = {entry.identity: entry.lane for entry in result.plan.identities} + assert names["org/kept"] == "org-model-l4" + assert names[IDENTITY] == f"org-model-l4-{hashlib.sha256(IDENTITY.encode()).hexdigest()[:8]}" + + +def test_bundles_and_the_queue_pool_come_from_the_parameters(): + service_levels = levels(("org/embed", ServiceLevel()), ("org/generate", ServiceLevel())) + result = run( + service_levels, + [receipt(identity="org/embed"), receipt(identity="org/generate")], + prices=L4_ONLY, + queue_pool="batch", + bundle="default", + bundles={"org/generate": "sglang"}, + ) + lanes = {lane.name: (lane.queue_pool, lane.bundle) for lane in result.plan.lanes} + assert lanes == {"org-embed-l4": ("batch", "default"), "org-generate-l4": ("batch", "sglang")} + + +def test_equal_costs_prefer_the_current_placement(): + twin = Cell(machine_profile="l4-b", gpu_product="NVIDIA-L4") + prices = price_list(a100=None, extra=(profile(twin, 1.0),)) + receipts = [receipt(cell=L4), receipt(cell=twin)] + first = run(level(come_alive_p95_s=0), receipts, prices=prices) + assert first.plan.lanes[0].cell == L4 + current = single_lane_plan(name="org-model-l4-b", cell=twin) + second = run(level(come_alive_p95_s=0), receipts, prices=prices, current=current) + assert second.plan.lanes[0].cell == twin + assert second.report.identity(IDENTITY).current == current.identities[0] + + +def test_the_region_multiplier_scales_every_price(): + result = run(level(come_alive_p95_s=0), [receipt()], prices=price_list(a100=None, multiplier=1.25)) + assert result.report.identity(IDENTITY).chosen.monthly_cost == pytest.approx(1.25 * MONTH) + assert result.report.lanes[0].hourly_cost == pytest.approx(1.25) + + +@pytest.mark.parametrize( + ("overrides", "path"), + [ + ({"placement": ""}, "placement"), + ({"max_containers": 0}, "maxContainers"), + ({"fallback_floor": -1}, "fallbackFloor"), + ({"cooldown_s": -1}, "cooldownS"), + ({"buffer_containers": -1}, "bufferContainers"), + ({"hours_per_month": 0}, "hoursPerMonth"), + ({"hours_per_month": math.inf}, "hoursPerMonth"), + ({"queue_pool": "two words"}, "queuePool"), + ({"bundle": ""}, "bundle"), + ({"bundles": {"": "sglang"}}, "bundles"), + ({"bundles": {IDENTITY: ""}}, "bundles['org/model']"), + ], +) +def test_parameters_are_validated(overrides, path): + with pytest.raises(SchemaError) as caught: + parameters(**overrides) + assert caught.value.path == path + + +def test_parameters_echo_into_the_report(): + echoed = parameters(bundles={"org/b": "sglang", "org/a": "default"}).to_dict() + assert echoed == { + "placement": "test", + "maxContainers": 4, + "fallbackFloor": 2, + "cooldownS": 900, + "bufferContainers": 0, + "hoursPerMonth": 730.0, + "queuePool": "default", + "bundle": "default", + "bundles": {"org/a": "default", "org/b": "sglang"}, + } + assert list(echoed["bundles"]) == ["org/a", "org/b"] + + +def test_the_placement_must_be_in_the_price_list(): + with pytest.raises(PlannerInputError, match="placement 'elsewhere' is not in the price list"): + run(level(), [receipt()], placement="elsewhere") + + +def test_the_current_plan_must_be_for_the_same_placement(): + current = Plan(placement="other", lanes=(), identities=()) + with pytest.raises(PlannerInputError, match="the current plan is for placement 'other'"): + run(level(), [receipt()], current=current) + + +def test_the_estate_plan_and_report_are_byte_stable(): + plan_text, report_text = rendered(plan(**estate())) + assert plan_text == (FIXTURES / "expected-plan.json").read_text(encoding="utf-8") + assert report_text == (FIXTURES / "expected-report.json").read_text(encoding="utf-8") + assert rendered(plan(**estate())) == (plan_text, report_text) + + +def test_input_order_does_not_change_the_output(): + baseline = rendered(plan(**estate())) + shuffler = random.Random(11) # noqa: S311 -- reproducible test data + for _ in range(5): + inputs = estate() + shuffler.shuffle(inputs["receipts"]) + shuffler.shuffle(inputs["boot_evidence"]) + service_levels = inputs["service_levels"] + inputs["service_levels"] = ServiceLevels( + identities=tuple(reversed(service_levels.identities)), tiers=tuple(reversed(service_levels.tiers)) + ) + source = inputs["demand"] + inputs["demand"] = Demand(start=source.start, end=source.end, series=tuple(reversed(source.series))) + assert rendered(plan(**inputs)) == baseline + + +def test_replanning_the_plan_it_wrote_changes_nothing(): + first = plan(**estate()) + second = plan(**{**estate(), "current_plan": first.plan}) + assert second.plan == first.plan + assert render(second.plan.to_dict()) == render(first.plan.to_dict()) + assert second.report.unchanged + assert second.report.to_dict()["changes"] == {"identities": [], "lanes": []} + + +def test_the_estate_plan_parses_as_a_plan_document(): + result = plan(**estate()) + assert Plan.from_dict(json.loads(render(result.plan.to_dict()))) == result.plan + + +def test_the_estate_places_every_identity_on_a_measured_feasible_cell(): + inputs = estate() + result = plan(**inputs) + receipts = {document.source.uri: document for document in inputs["receipts"]} + for entry in result.report.identities: + if entry.status is not IdentityStatus.PLACED: + continue + chosen = entry.chosen + assert chosen.blocked_by == () + measured = receipts[chosen.receipt.uri] + assert measured.cell == chosen.cell + if measured.latency is not None and entry.service_level.warm_p99_ms is not None: + assert measured.latency.p99_ms <= entry.service_level.warm_p99_ms + if measured.itl is not None: + assert measured.ttft.p99_ms <= entry.service_level.ttft_p99_ms + assert measured.itl.p99_ms <= entry.service_level.itl_p99_ms + if chosen.warmth is not Warmth.PINNED: + assert entry.service_level.come_alive_p95_s > 0 + assert chosen.come_alive_s <= entry.service_level.come_alive_p95_s + + +def test_the_estate_report_states_its_findings(): + report = plan(**estate()).report + dense = report.identity("BAAI/bge-m3") + assert (dense.chosen.cell, dense.chosen.warmth) == (L4, Warmth.PINNED) + assert dense.chosen.monthly_cost == pytest.approx(1.04 * MONTH) + assert dense.next_cheaper.warmth is Warmth.SNAPSHOT_COLD + assert dense.next_cheaper.blocked_by == (Blocker(field="comeAliveP95S", bound=0, measured=8.5),) + sparse = report.identity("BAAI/bge-m3:sparse") + assert (sparse.chosen.warmth, sparse.chosen.come_alive_s) == (Warmth.COLD_WITH_BOUND, 95.0) + assert sparse.chosen.monthly_cost == pytest.approx(1.04 * (3 / 40 + 3 * 2 * 900) / 3600 * SCALE) + generation = report.identity("Qwen/Qwen3-8B") + assert (generation.chosen.cell, generation.chosen.warmth) == (A100, Warmth.COLD_WITH_BOUND) + assert generation.chosen.monthly_cost == pytest.approx(3.14 * 2 * 2 * SCALE) + assert generation.next_cheaper.blocked_by == (Blocker(field="itlP99Ms", bound=80, measured=118.0),) + assert report.identity("Qwen/Qwen3-Reranker-0.6B").status is IdentityStatus.UNPLACED + assert report.identity("intfloat/e5-base-v2").status is IdentityStatus.KEPT + assert [refusal.record for refusal in report.refusals] == [RefusedRecord.BOOT_EVIDENCE, RefusedRecord.RECEIPT] + assert report.queue_wait_unattained == ("BAAI/bge-m3", "BAAI/bge-m3:sparse", "intfloat/e5-base-v2") + assert [change.identity for change in report.identity_changes] == [ + "BAAI/bge-m3", + "BAAI/bge-m3:sparse", + "Qwen/Qwen3-Embedding-4B", + ] + assert report.monthly_cost == pytest.approx( + sum(entry.chosen.monthly_cost for entry in report.identities if entry.chosen is not None) + ) + + +@pytest.mark.parametrize("seed", range(25)) +def test_random_estates_choose_only_feasible_cells_and_replan_to_themselves(seed): + rng = random.Random(seed) # noqa: S311 -- reproducible test data + identities = [f"org/model-{index}" for index in range(rng.randint(1, 5))] + service_levels = levels( + *( + ( + identity, + ServiceLevel( + come_alive_p95_s=rng.choice([None, 0, 30, 120, 600]), + warm_p99_ms=rng.choice([None, 150, 250, 400]), + ), + ) + for identity in identities + ) + ) + receipts = [ + receipt( + identity=identity, + cell=cell, + concurrency=rng.choice([4, 8]), + rps=rng.choice([0.5, 5.0, 50.0]), + p99=rng.choice([100.0, 200.0, 300.0, 500.0]), + uri=f"receipts/{identity}/{cell.machine_profile}/{index}", + ) + for identity in identities + for index, cell in enumerate([L4, A100, L4]) + if rng.random() < 0.7 + ] + boots = [ + boot( + identity=identity, + cell=cell, + warmth=warmth, + seconds=rng.choice([5.0, 60.0, 200.0]), + outcome=rng.choice([BootOutcome.SUCCEEDED, BootOutcome.SUCCEEDED, BootOutcome.FAILED]), + borrowed=rng.random() < 0.3, + uri=f"boots/{identity}/{cell.machine_profile}/{warmth.value}/{index}", + ) + for identity in identities + for cell in (L4, A100) + for warmth in (Warmth.COLD_WITH_BOUND, Warmth.SNAPSHOT_COLD) + for index in range(2) + if rng.random() < 0.4 + ] + hourly = { + identity: {hour: rng.choice([0, 1, 50, 20000]) for hour in rng.sample(range(WINDOW_HOURS), rng.randint(0, 6))} + for identity in identities + } + prices = price_list(l4=rng.choice([0.5, 1.0]), a100=rng.choice([2.0, 3.0]), core=0.1) + overrides = { + "buffer_containers": rng.randint(0, 2), + "fallback_floor": rng.randint(0, 3), + "cooldown_s": rng.choice([0, 60, 900]), + } + result = run(service_levels, receipts, boots, prices=prices, hourly=hourly, **overrides) + assert Plan.from_dict(result.plan.to_dict()) == result.plan + by_uri = {document.source.uri: document for document in receipts} + for entry in result.report.identities: + if entry.chosen is None: + continue + chosen = entry.chosen + assert chosen.blocked_by == () + bound = entry.service_level.warm_p99_ms + assert bound is None or by_uri[chosen.receipt.uri].latency.p99_ms <= bound + come_alive = entry.service_level.come_alive_p95_s + if chosen.warmth is not Warmth.PINNED: + assert come_alive is None or come_alive > 0 + assert come_alive is None or chosen.come_alive_s <= come_alive + if entry.next_cheaper is not None: + assert entry.next_cheaper.blocked_by + assert entry.next_cheaper.monthly_cost < chosen.monthly_cost + costs = {entry.identity: entry.chosen.monthly_cost for entry in result.report.identities if entry.chosen} + for lever in result.report.come_alive_levers: + assert lever.monthly_cost < costs[lever.identity] + assert lever.saving_at_permitted_bound >= lever.saving_under_bound >= 0 + for request in result.report.measurement_requests: + assert request.saving_bound is None or request.saving_bound > 0 + again = run(service_levels, receipts, boots, prices=prices, hourly=hourly, current=result.plan, **overrides) + assert again.plan == result.plan + assert again.report.unchanged + shuffled = list(receipts) + rng.shuffle(shuffled) + reordered = run(service_levels, shuffled, list(reversed(boots)), prices=prices, hourly=hourly, **overrides) + assert rendered(reordered) == rendered(result) diff --git a/packages/sie_placement/tests/test_schema.py b/packages/sie_placement/tests/test_schema.py index 2ca86915c..c05a873c3 100644 --- a/packages/sie_placement/tests/test_schema.py +++ b/packages/sie_placement/tests/test_schema.py @@ -334,6 +334,26 @@ def test_boot_evidence_keeps_failed_outcomes(): assert str(schema_error(BootEvidence.from_dict, data)) == "$.bootSeconds: must be at least 0, got -0.5" +def test_boot_evidence_marks_evidence_borrowed_from_another_environment(): + data = load("boot-evidence.json") + assert BootEvidence.from_dict(data).borrowed is False + data["borrowed"] = True + evidence = BootEvidence.from_dict(data) + assert evidence.borrowed is True + assert evidence.to_dict() == data + data["borrowed"] = False + evidence = BootEvidence.from_dict(data) + assert evidence.borrowed is False + assert "borrowed" not in evidence.to_dict() + + +@pytest.mark.parametrize(("value", "described"), [(1, "number 1"), ("true", "string 'true'")]) +def test_boot_evidence_borrowed_is_a_strict_boolean(value, described): + data = load("boot-evidence.json") + data["borrowed"] = value + assert str(schema_error(BootEvidence.from_dict, data)) == f"$.borrowed: expected a boolean, got {described}" + + def test_price_lists_validate_currency_rates_and_names(): data = load("price-list.json") data["currency"] = "usd" From 46d5f3340e7c177adac6bb9b225f627567c8b04f Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Thu, 5 Nov 2026 01:41:26 +0100 Subject: [PATCH 08/16] fix(placement): keep current lanes and price every lane of the plan An identity whose choice is its current placement now stays on its current lane under its current name, beside whoever else that lane hosts. The current placement also has to match the queue pool and the bundle the parameters give the identity. Before this, the planner renamed an unchanged lane and split a shared current lane into new pinned floors, so an unchanged input could still produce a diff. Only lanes for new or moved placements get minted names, and a minted name widens its digest when a kept lane already holds it. Kept lanes stay within the reviewed ceiling. Costs are now per lane: each lane pays its floor once, plus its residents' demand above the floor. A kept identity's demand is priced at its slowest receipt for its lane's cell, shape and concurrency, under that lane's ceiling. The totals cover every lane. totals.unpricedLanes lists each lane whose cell has no price (with an unpricedReason) or that has a resident whose demand no receipt can price. Each identity reports its monthly cost on its lane. A kept identity's blockedBy names the bounds its kept placement is known to miss. The report also lists sharedChartLanes: every chart lane, by queue pool, machine profile and bundle, that more than one plan lane names. Boot seconds normalize to float, so an int and a float record of the same boot render the same bytes in either order. New tests cover demand summed over operations, saturated cold hours, the cheapest receipt for levers and boot requests under shuffled input, the concurrency match of the current placement, and snapshot restores, which are never requested. --- packages/sie_placement/README.md | 63 +++- .../src/sie_placement/planner.py | 245 ++++++++---- .../sie_placement/src/sie_placement/report.py | 57 ++- .../tests/fixtures/planner/expected-plan.json | 22 +- .../fixtures/planner/expected-report.json | 78 ++-- packages/sie_placement/tests/test_levers.py | 24 +- packages/sie_placement/tests/test_planner.py | 353 +++++++++++++++++- 7 files changed, 661 insertions(+), 181 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index 643684cc7..cfeb962ed 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -89,7 +89,9 @@ Helm chart: `queuePool`, the `machineProfile` of its `cell`, and `bundle`. override. It is neither the `workers.pools` map key, which names a worker group, nor an SDK logical pool. `bundle` is a key of that worker group's `bundles` map. `name` is the lane's handle inside the plan, and each identity -refers to its lane by that name. +refers to its lane by that name. Two plan lanes may carry the same three +tokens, and so name one chart lane, which cannot give them separate envelopes +or concurrency; the planner's report lists every such chart lane. ## Envelope @@ -119,8 +121,9 @@ print(render(result.plan.to_dict()), render(result.report.to_dict())) `plan` is a pure function of its documents. The same inputs render to the same bytes in whatever order the receipts, boot evidence, identities and demand -series arrive, and a run whose `current_plan` is its own previous plan reports -no change. +series arrive. An identity whose choice is its current placement keeps its +current lane and that lane's name, so a run whose `current_plan` already holds +every choice, such as its own previous plan, reports no change. | Parameter | Meaning | | --- | --- | @@ -134,8 +137,8 @@ no change. ### Selection -The planner places each identity of the service-level document on its own -lane: +The planner chooses a cell and warmth for each identity of the service-level +document: 1. It refuses a receipt or boot record whose machine profile has no price, or whose realized GPU product differs from the product the price list gives @@ -148,12 +151,21 @@ lane: successful boot stands for the come-alive percentile, a boot that did not succeed withdraws the warmth, and the environment's own evidence replaces borrowed evidence. A `comeAliveP95S` of `0` admits `pinned` only. -4. The cheapest unblocked option wins. Ties go to the current plan's - placement, then to the faster come-alive. - -The planner does not select `lazy-resident`, `bridged` or `scheduled-warm`, -and does not put two identities on one lane. An identity with no unblocked -option keeps its current lane, or stays out of the plan when it has none. +4. The cheapest unblocked option wins. Ties go to the current placement, + then to the faster come-alive. + +The current placement is the identity's current lane when that lane has the +option's cell, container shape and concurrency, the identity's warmth is the +option's, and the lane's `queuePool` and `bundle` are the ones the parameters +give the identity. An identity whose choice is its current placement stays on +that lane under its name, beside whoever else the lane hosts, and the lane +takes the ceiling and envelope of the choice. Every other placed identity gets +a new lane of its own, named from the identity and its machine profile, with a +digest of the identity added when that name is taken. The planner does not +select `lazy-resident`, `bridged` or `scheduled-warm`, and does not move an +identity onto another identity's lane. An identity with no unblocked option +keeps its current lane, capped by the reviewed ceiling, or stays out of the +plan when it has none. ### Pricing @@ -170,6 +182,13 @@ demand window to `hours_per_month`. every request: the active floor for `cooldown_s`, at most the whole hour. The active floor is `fallback_floor` capped by the ceiling, and at least one. +A lane costs its floor all month once, whoever it hosts, plus what each +resident's demand needs beyond the floor: on a lane with a floor, the +containers an hour needs above it, and on a zero-floor lane, the work and the +tails a cold warmth pays. A placed identity's demand is priced at its chosen +receipt, and a kept identity's at the slowest receipt it has for its lane's +cell, container shape and concurrency, under that lane's own ceiling. + ### Envelope `floorMin` is 1 for `pinned` and 0 otherwise. No source measures queue wait @@ -183,14 +202,26 @@ only. The report renders as a `placement-report` document: +- `totals`: the monthly cost of every lane of the plan, the monthly cost of + their `floorMax`, and `unpricedLanes`, the lanes whose cost the totals leave + out in whole or in part. - `identities`: each identity's status (`placed`, `kept` or `unplaced`), - effective service level and demand, the chosen cell, warmth, monthly cost and - come-alive with its basis (`warm-floor`, `boot-evidence` or + effective service level and demand, its lane and `monthlyCost`, what its + demand costs there with the lane's floor, the chosen cell, warmth, monthly + cost and come-alive with its basis (`warm-floor`, `boot-evidence` or `borrowed-boot-evidence`), the peak containers its demand needs, and `nextCheaper`: the nearest cheaper option a service level blocks, its saving - and the bounds that block it. -- `lanes`: each lane's hourly cost, its floor's monthly cost and the monthly - cost of its `floorMax`, which a floor budget prices. + and the bounds that block it. A kept identity's `blockedBy` names the bounds + its kept placement is known to miss: its receipt's warm latencies, a measured + come-alive over the bound, or a cold warmth under a bound of `0`, which needs + no measurement. +- `lanes`: each lane's hourly cost, its monthly cost, its floor's monthly cost + and the monthly cost of its `floorMax`, which a floor budget prices. A lane + on a cell the price list cannot price carries `unpricedReason` and no cost, + and `unpricedIdentities` lists residents whose demand has no receipt to price + it on the lane. +- `sharedChartLanes`: every chart lane, by `queuePool`, `machineProfile` and + `bundle`, that more than one plan lane names. - `measurementRequests`: options that lack evidence, ranked by the saving they could unlock. A profile without a receipt is bounded by price alone: one accelerator at its rate, kept warm or, where the come-alive bound allows, diff --git a/packages/sie_placement/src/sie_placement/planner.py b/packages/sie_placement/src/sie_placement/planner.py index 29b23f997..df445c623 100644 --- a/packages/sie_placement/src/sie_placement/planner.py +++ b/packages/sie_placement/src/sie_placement/planner.py @@ -27,6 +27,7 @@ RefusedRecord, Report, RequestReason, + SharedChartLane, UnplacedReason, ) from sie_placement.schema import ( @@ -160,11 +161,12 @@ def scale(self) -> float: def needed(requests: int, requests_per_second: float) -> int: return math.ceil(requests / (requests_per_second * SECONDS_PER_HOUR)) + def above_floor_hours(self, requests: Sequence[int], requests_per_second: float, floor: int) -> float: + above = sum(max(0, min(self.ceiling, self.needed(count, requests_per_second)) - floor) for count in requests) + return above * self.scale + def warm_container_hours(self, requests: Sequence[int], requests_per_second: float) -> float: - above = sum( - max(0, min(self.ceiling, self.needed(count, requests_per_second)) - PINNED_FLOOR) for count in requests - ) - return PINNED_FLOOR * self.hours_per_month + above * self.scale + return PINNED_FLOOR * self.hours_per_month + self.above_floor_hours(requests, requests_per_second, PINNED_FLOOR) def cold_container_hours(self, requests: Sequence[int], requests_per_second: float | None) -> float: seconds = 0.0 @@ -244,8 +246,8 @@ def _slug(value: str) -> str: return _SLUG.sub("-", value.lower()).strip("-") -def _digest(value: str) -> str: - return hashlib.sha256(value.encode()).hexdigest()[:8] +def _digest(value: str, width: int = 8) -> str: + return hashlib.sha256(value.encode()).hexdigest()[:width] def _refusal_reason(cell: Cell, prices: Mapping[str, MachineProfilePrice]) -> str | None: @@ -302,7 +304,7 @@ def _boot_index(records: Iterable[BootEvidence]) -> dict[_BootKey, _Boot]: if any(record.outcome is not BootOutcome.SUCCEEDED for record in used): index[key] = _Boot(seconds=None, borrowed=not own) else: - index[key] = _Boot(seconds=max(record.boot_seconds for record in used), borrowed=not own) + index[key] = _Boot(seconds=float(max(record.boot_seconds for record in used)), borrowed=not own) return index @@ -316,13 +318,9 @@ def _hourly_requests(demand: Demand) -> dict[str, tuple[int, ...]]: } -def _matches_current(receipt: Receipt, warmth: Warmth, current: tuple[PlanIdentity, PlanLane] | None) -> bool: - if current is None: - return False - entry, lane = current +def _runs_on(receipt: Receipt, lane: PlanLane) -> bool: return ( - entry.warmth is warmth - and lane.cell == receipt.cell + lane.cell == receipt.cell and lane.container_shape == receipt.container_shape and lane.concurrency == receipt.concurrency ) @@ -399,15 +397,21 @@ def _accept_boot_evidence(self, records: Iterable[BootEvidence]) -> list[BootEvi def _refuse(self, record: RefusedRecord, identity: str, cell: Cell, source: SourceRef, reason: str) -> None: self.refusals.append(Refusal(record=record, identity=identity, cell=cell, source=source, reason=reason)) - def hourly_cost(self, cell: Cell, shape: ContainerShape) -> float | None: - if _refusal_reason(cell, self.prices) is not None: - return None - return container_hourly_cost(self.prices[cell.machine_profile], shape, self.multiplier) + def is_current(self, identity: str, receipt: Receipt, warmth: Warmth) -> bool: + current = self.current.get(identity) + if current is None: + return False + entry, lane = current + return ( + entry.warmth is warmth + and lane.queue_pool == self.parameters.queue_pool + and lane.bundle == self.parameters.bundle_of(identity) + and _runs_on(receipt, lane) + ) def choose(self, identity: str) -> _Choice: level = self.levels[identity] requests = self.requests.get(identity, ()) - current = self.current.get(identity) options: list[_Option] = [] boot_requests: dict[tuple[Cell, ContainerShape], MeasurementRequest] = {} receipts = self.receipts.get(identity, []) @@ -426,7 +430,7 @@ def choose(self, identity: str) -> _Choice: come_alive_s=0.0, basis=ComeAliveBasis.WARM_FLOOR, blockers=warm, - current=_matches_current(receipt, Warmth.PINNED, current), + current=self.is_current(identity, receipt, Warmth.PINNED), ) ) cold_cost = hourly * self.window.cold_container_hours(requests, rate) @@ -458,7 +462,7 @@ def choose(self, identity: str) -> _Choice: come_alive_s=boot.seconds, basis=boot.basis, blockers=warm if blocker is None else (*warm, blocker), - current=_matches_current(receipt, warmth, current), + current=self.is_current(identity, receipt, warmth), ) ) feasible = [option for option in options if option.feasible] @@ -567,71 +571,131 @@ def next_cheaper(choice: _Choice) -> _Option | None: nearest = max(option.cost for option in cheaper) return min((option for option in cheaper if option.cost == nearest), key=lambda option: option.rank) - def lane_names(self, choices: Sequence[_Choice], reserved: set[str]) -> dict[str, str]: - bases: dict[str, str] = {} - for choice in choices: - if choice.chosen is not None: - profile = choice.chosen.receipt.cell.machine_profile - bases[choice.identity] = _slug(f"{choice.identity}-{profile}") or "lane" - counts = Counter(bases.values()) - return { - identity: base if counts[base] == 1 and base not in reserved else f"{base}-{_digest(identity)}" - for identity, base in bases.items() + @staticmethod + def lane_names(placed: Mapping[str, _Option], reserved: set[str]) -> dict[str, str]: + bases = { + identity: _slug(f"{identity}-{option.receipt.cell.machine_profile}") or "lane" + for identity, option in placed.items() } + counts = Counter(bases.values()) + taken = set(reserved) + names: dict[str, str] = {} + for identity, base in bases.items(): + name = base if counts[base] == 1 and base not in reserved else f"{base}-{_digest(identity)}" + if name in taken: + name = f"{base}-{_digest(identity, width=64)}" + if name in taken: + raise PlannerInputError(f"lane name {name!r} for {identity!r} is already taken") + taken.add(name) + names[identity] = name + return names + + def placed_lane(self, name: str, identity: str, option: _Option) -> PlanLane: + receipt = option.receipt + return PlanLane( + name=name, + queue_pool=self.parameters.queue_pool, + bundle=self.parameters.bundle_of(identity), + cell=receipt.cell, + container_shape=receipt.container_shape, + concurrency=receipt.concurrency, + max_containers=self.parameters.max_containers, + envelope=envelope_for(option.warmth, self.parameters), + ) + + def within_ceiling(self, lane: PlanLane) -> PlanLane: + ceiling = self.parameters.max_containers + if lane.max_containers <= ceiling: + return lane + envelope = replace( + lane.envelope, + floor_min=min(lane.envelope.floor_min, ceiling), + floor_max=min(lane.envelope.floor_max, ceiling), + ) + return replace(lane, max_containers=ceiling, envelope=envelope) + + def slowest_receipt(self, identity: str, lane: PlanLane) -> Receipt | None: + matching = [(order, receipt) for order, receipt in self.receipts.get(identity, []) if _runs_on(receipt, lane)] + if not matching: + return None + return min(matching, key=lambda pair: (pair[1].throughput.requests_per_second, pair[0]))[1] + + def kept_blockers( + self, identity: str, entry: PlanIdentity, lane: PlanLane, receipt: Receipt | None + ) -> tuple[Blocker, ...]: + level = self.levels[identity] + blockers = [] if receipt is None else list(_warm_blockers(level, receipt)) + if entry.warmth in COLD_WARMTHS and level.come_alive_p95_s is not None: + boot = self.boots.get((identity, lane.cell, lane.container_shape, entry.warmth)) + if boot is not None and boot.seconds is not None: + blocker = _come_alive_blocker(level, boot.seconds) + blockers.extend(() if blocker is None else (blocker,)) + elif level.come_alive_p95_s == 0: + blockers.append(Blocker(field="comeAliveP95S", bound=0, measured=None)) + return tuple(blockers) + + def demand_hours(self, lane: PlanLane, identity: str, receipt: Receipt | None) -> float | None: + requests = self.requests.get(identity, ()) + if not requests: + return 0.0 + if receipt is None: + return None + window = replace( + self.window, + ceiling=lane.max_containers, + active_floor=max(1, min(self.parameters.fallback_floor, lane.max_containers)), + ) + rate = receipt.throughput.requests_per_second + if lane.envelope.floor_min: + return window.above_floor_hours(requests, rate, lane.envelope.floor_min) + return window.cold_container_hours(requests, rate) def run(self) -> PlannerResult: choices = [self.choose(identity) for identity in sorted(self.levels)] + placed = {choice.identity: choice.chosen for choice in choices if choice.chosen is not None} kept = { choice.identity: self.current[choice.identity] for choice in choices if choice.chosen is None and choice.identity in self.current } - kept_lanes = {lane.name: lane for _, lane in kept.values()} - names = self.lane_names(choices, set(kept_lanes)) - lanes: dict[str, PlanLane] = dict(kept_lanes) - identities: list[PlanIdentity] = [entry for entry, _ in kept.values()] + staying = {identity: self.current[identity][1].name for identity, option in placed.items() if option.current} + reserved = {lane.name for _, lane in kept.values()} | set(staying.values()) + moving = {identity: option for identity, option in placed.items() if identity not in staying} + names = staying | self.lane_names(moving, reserved) + lanes = {lane.name: self.within_ceiling(lane) for _, lane in kept.values()} + for identity, option in placed.items(): + lanes[names[identity]] = self.placed_lane(names[identity], identity, option) + identities = [entry for entry, _ in kept.values()] + identities.extend( + PlanIdentity(identity=identity, lane=names[identity], warmth=option.warmth) + for identity, option in placed.items() + ) + new_plan = Plan( + placement=self.parameters.placement, + lanes=tuple(lanes[name] for name in sorted(lanes)), + identities=tuple(sorted(identities, key=lambda entry: entry.identity)), + ) + receipts: dict[str, Receipt | None] = {identity: option.receipt for identity, option in placed.items()} + receipts.update({identity: self.slowest_receipt(identity, lane) for identity, (_, lane) in kept.items()}) + lane_reports, costs = self._pricing(new_plan, receipts) reports: list[IdentityReport] = [] requests: list[MeasurementRequest] = [] levers: list[Lever] = [] - monthly_cost = 0.0 for choice in choices: requests.extend(self.receipt_requests(choice)) requests.extend(self.boot_requests(choice)) levers.extend(self.levers(choice)) - reports.append(self._identity_report(choice, names, kept)) - if choice.chosen is None: - continue - monthly_cost += choice.chosen.cost - receipt = choice.chosen.receipt - name = names[choice.identity] - lanes[name] = PlanLane( - name=name, - queue_pool=self.parameters.queue_pool, - bundle=self.parameters.bundle_of(choice.identity), - cell=receipt.cell, - container_shape=receipt.container_shape, - concurrency=receipt.concurrency, - max_containers=self.parameters.max_containers, - envelope=envelope_for(choice.chosen.warmth, self.parameters), + reports.append( + self._identity_report(choice, names, kept, costs.get(choice.identity), receipts.get(choice.identity)) ) - identities.append(PlanIdentity(identity=choice.identity, lane=name, warmth=choice.chosen.warmth)) - new_plan = Plan( - placement=self.parameters.placement, - lanes=tuple(lanes[name] for name in sorted(lanes)), - identities=tuple(sorted(identities, key=lambda entry: entry.identity)), - ) - lane_reports = self._lane_reports(new_plan) identity_changes, lane_changes = _changes(self.current_plan, new_plan) report = Report( placement=self.parameters.placement, currency=self.price_list.currency, parameters=self.parameters.to_dict(), - monthly_cost=monthly_cost, - envelope_max_monthly_cost=sum( - lane.envelope_max_monthly_cost for lane in lane_reports if lane.envelope_max_monthly_cost is not None - ), identities=tuple(reports), lanes=lane_reports, + shared_chart_lanes=_shared_chart_lanes(new_plan), measurement_requests=tuple(sorted(requests, key=_request_rank)), come_alive_levers=tuple(sorted(levers, key=_lever_rank)), queue_wait_unattained=tuple( @@ -644,7 +708,12 @@ def run(self) -> PlannerResult: return PlannerResult(plan=new_plan, report=report) def _identity_report( - self, choice: _Choice, names: Mapping[str, str], kept: Mapping[str, tuple[PlanIdentity, PlanLane]] + self, + choice: _Choice, + names: Mapping[str, str], + kept: Mapping[str, tuple[PlanIdentity, PlanLane]], + cost: float | None, + receipt: Receipt | None, ) -> IdentityReport: current = self.current.get(choice.identity) report = IdentityReport( @@ -658,8 +727,14 @@ def _identity_report( if chosen is None: reason = UnplacedReason.WARM_BOUND_MISSED if choice.has_valid_receipt else UnplacedReason.NO_RECEIPT if choice.identity in kept: + entry, lane = kept[choice.identity] return replace( - report, status=IdentityStatus.KEPT, lane=kept[choice.identity][0].lane, unplaced_reason=reason + report, + status=IdentityStatus.KEPT, + lane=entry.lane, + monthly_cost=cost, + unplaced_reason=reason, + blocked_by=self.kept_blockers(choice.identity, entry, lane, receipt), ) return replace(report, unplaced_reason=reason) nearest = self.next_cheaper(choice) @@ -668,29 +743,57 @@ def _identity_report( report, status=IdentityStatus.PLACED, lane=names[choice.identity], + monthly_cost=cost, chosen=chosen.summary(), peak_containers=max((_Window.needed(count, rate) for count in choice.requests), default=0), next_cheaper=None if nearest is None else nearest.summary(saving=chosen.cost - nearest.cost), ) - def _lane_reports(self, plan: Plan) -> tuple[LaneReport, ...]: + def _pricing( + self, plan: Plan, receipts: Mapping[str, Receipt | None] + ) -> tuple[tuple[LaneReport, ...], dict[str, float]]: residents: defaultdict[str, list[str]] = defaultdict(list) for entry in plan.identities: residents[entry.lane].append(entry.identity) - reports = [] + hours = self.parameters.hours_per_month + reports: list[LaneReport] = [] + costs: dict[str, float] = {} for lane in plan.lanes: - hourly = self.hourly_cost(lane.cell, lane.container_shape) - hours = self.parameters.hours_per_month + hosted = tuple(sorted(residents[lane.name])) + reason = _refusal_reason(lane.cell, self.prices) + if reason is not None: + reports.append(LaneReport(name=lane.name, identities=hosted, unpriced_reason=reason)) + continue + hourly = container_hourly_cost( + self.prices[lane.cell.machine_profile], lane.container_shape, self.multiplier + ) + floor = lane.envelope.floor_min * hours + demand = {identity: self.demand_hours(lane, identity, receipts.get(identity)) for identity in hosted} + priced = {identity: value for identity, value in demand.items() if value is not None} + costs.update((identity, hourly * (floor + value)) for identity, value in priced.items()) reports.append( LaneReport( name=lane.name, - identities=tuple(sorted(residents[lane.name])), + identities=hosted, hourly_cost=hourly, - floor_monthly_cost=None if hourly is None else hourly * lane.envelope.floor_min * hours, - envelope_max_monthly_cost=None if hourly is None else hourly * lane.envelope.floor_max * hours, + monthly_cost=hourly * (floor + sum(priced.values())), + floor_monthly_cost=hourly * lane.envelope.floor_min * hours, + envelope_max_monthly_cost=hourly * lane.envelope.floor_max * hours, + unpriced_identities=tuple(identity for identity in hosted if identity not in priced), ) ) - return tuple(reports) + return tuple(reports), costs + + +def _shared_chart_lanes(plan: Plan) -> tuple[SharedChartLane, ...]: + grouped: defaultdict[tuple[str, str, str], list[str]] = defaultdict(list) + for lane in plan.lanes: + grouped[(lane.queue_pool, lane.cell.machine_profile, lane.bundle)].append(lane.name) + return tuple( + SharedChartLane(queue_pool=pool, machine_profile=profile, bundle=bundle, lanes=tuple(sorted(names))) + for (pool, profile, bundle), names in sorted(grouped.items()) + if len(names) > 1 + ) def _changes(current: Plan | None, new: Plan) -> tuple[tuple[IdentityChange, ...], tuple[LaneChange, ...]]: diff --git a/packages/sie_placement/src/sie_placement/report.py b/packages/sie_placement/src/sie_placement/report.py index 462bbe3ed..f285f71bc 100644 --- a/packages/sie_placement/src/sie_placement/report.py +++ b/packages/sie_placement/src/sie_placement/report.py @@ -70,10 +70,10 @@ def _compact(fields: dict[str, object | None]) -> dict[str, object]: class Blocker: field: str bound: int - measured: float + measured: float | None def to_dict(self) -> dict[str, object]: - return {"field": self.field, "bound": self.bound, "measured": self.measured} + return _compact({"field": self.field, "bound": self.bound, "measured": self.measured}) @dataclass(frozen=True, slots=True, kw_only=True) @@ -113,11 +113,13 @@ class IdentityReport: service_level: ServiceLevel demand_requests: int lane: str | None = None + monthly_cost: float | None = None chosen: Option | None = None peak_containers: int | None = None next_cheaper: Option | None = None current: PlanIdentity | None = None unplaced_reason: UnplacedReason | None = None + blocked_by: tuple[Blocker, ...] = () def to_dict(self) -> dict[str, object]: return _compact( @@ -127,6 +129,8 @@ def to_dict(self) -> dict[str, object]: "serviceLevel": self.service_level.to_dict(), "demandRequests": self.demand_requests, "lane": self.lane, + "monthlyCost": None if self.monthly_cost is None else _money(self.monthly_cost), + "blockedBy": [blocker.to_dict() for blocker in self.blocked_by] or None, "chosen": None if self.chosen is None else self.chosen.to_dict(), "peakContainers": self.peak_containers, "nextCheaper": None if self.next_cheaper is None else self.next_cheaper.to_dict(), @@ -140,9 +144,16 @@ def to_dict(self) -> dict[str, object]: class LaneReport: name: str identities: tuple[str, ...] - hourly_cost: float | None - floor_monthly_cost: float | None - envelope_max_monthly_cost: float | None + hourly_cost: float | None = None + monthly_cost: float | None = None + floor_monthly_cost: float | None = None + envelope_max_monthly_cost: float | None = None + unpriced_reason: str | None = None + unpriced_identities: tuple[str, ...] = () + + @property + def unpriced(self) -> bool: + return self.unpriced_reason is not None or bool(self.unpriced_identities) def to_dict(self) -> dict[str, object]: return _compact( @@ -150,14 +161,33 @@ def to_dict(self) -> dict[str, object]: "name": self.name, "identities": list(self.identities), "hourlyCost": None if self.hourly_cost is None else _rate(self.hourly_cost), + "monthlyCost": None if self.monthly_cost is None else _money(self.monthly_cost), "floorMonthlyCost": None if self.floor_monthly_cost is None else _money(self.floor_monthly_cost), "envelopeMaxMonthlyCost": ( None if self.envelope_max_monthly_cost is None else _money(self.envelope_max_monthly_cost) ), + "unpricedReason": self.unpriced_reason, + "unpricedIdentities": list(self.unpriced_identities) or None, } ) +@dataclass(frozen=True, slots=True, kw_only=True) +class SharedChartLane: + queue_pool: str + machine_profile: str + bundle: str + lanes: tuple[str, ...] + + def to_dict(self) -> dict[str, object]: + return { + "queuePool": self.queue_pool, + "machineProfile": self.machine_profile, + "bundle": self.bundle, + "lanes": list(self.lanes), + } + + @dataclass(frozen=True, slots=True, kw_only=True) class MeasurementRequest: identity: str @@ -269,10 +299,9 @@ class Report: placement: str currency: str parameters: Mapping[str, object] - monthly_cost: float - envelope_max_monthly_cost: float identities: tuple[IdentityReport, ...] lanes: tuple[LaneReport, ...] + shared_chart_lanes: tuple[SharedChartLane, ...] measurement_requests: tuple[MeasurementRequest, ...] come_alive_levers: tuple[Lever, ...] queue_wait_unattained: tuple[str, ...] @@ -280,6 +309,18 @@ class Report: identity_changes: tuple[IdentityChange, ...] lane_changes: tuple[LaneChange, ...] + @property + def monthly_cost(self) -> float: + return sum(lane.monthly_cost for lane in self.lanes if lane.monthly_cost is not None) + + @property + def envelope_max_monthly_cost(self) -> float: + return sum(lane.envelope_max_monthly_cost for lane in self.lanes if lane.envelope_max_monthly_cost is not None) + + @property + def unpriced_lanes(self) -> tuple[str, ...]: + return tuple(lane.name for lane in self.lanes if lane.unpriced) + @property def unchanged(self) -> bool: return not self.identity_changes and not self.lane_changes @@ -300,9 +341,11 @@ def to_dict(self) -> dict[str, object]: "totals": { "monthlyCost": _money(self.monthly_cost), "envelopeMaxMonthlyCost": _money(self.envelope_max_monthly_cost), + "unpricedLanes": list(self.unpriced_lanes), }, "identities": [entry.to_dict() for entry in self.identities], "lanes": [lane.to_dict() for lane in self.lanes], + "sharedChartLanes": [shared.to_dict() for shared in self.shared_chart_lanes], "measurementRequests": [request.to_dict() for request in self.measurement_requests], "comeAliveLevers": [lever.to_dict() for lever in self.come_alive_levers], "queueWaitUnattained": list(self.queue_wait_unattained), diff --git a/packages/sie_placement/tests/fixtures/planner/expected-plan.json b/packages/sie_placement/tests/fixtures/planner/expected-plan.json index 1edfd3444..303a4ed79 100644 --- a/packages/sie_placement/tests/fixtures/planner/expected-plan.json +++ b/packages/sie_placement/tests/fixtures/planner/expected-plan.json @@ -3,26 +3,6 @@ "schemaVersion": 1, "placement": "us-central1", "lanes": [ - { - "name": "baai-bge-m3-l4", - "queuePool": "default", - "bundle": "default", - "cell": { - "machineProfile": "l4", - "gpuProduct": "NVIDIA-L4" - }, - "containerShape": { - "gpuCount": 1, - "cpuCores": 4, - "memoryMiB": 16384 - }, - "concurrency": 16, - "maxContainers": 4, - "envelope": { - "floorMin": 1, - "floorMax": 2 - } - }, { "name": "baai-bge-m3-sparse-l4", "queuePool": "default", @@ -107,7 +87,7 @@ "identities": [ { "identity": "BAAI/bge-m3", - "lane": "baai-bge-m3-l4", + "lane": "default-l4-default", "warmth": "pinned" }, { diff --git a/packages/sie_placement/tests/fixtures/planner/expected-report.json b/packages/sie_placement/tests/fixtures/planner/expected-report.json index ee6424bc9..7de1fe3db 100644 --- a/packages/sie_placement/tests/fixtures/planner/expected-report.json +++ b/packages/sie_placement/tests/fixtures/planner/expected-report.json @@ -18,7 +18,10 @@ }, "totals": { "monthlyCost": 1947.88, - "envelopeMaxMonthlyCost": 10658.0 + "envelopeMaxMonthlyCost": 9139.6, + "unpricedLanes": [ + "default-l4-default" + ] }, "identities": [ { @@ -30,7 +33,8 @@ "queueWaitP99Ms": 500 }, "demandRequests": 180000, - "lane": "baai-bge-m3-l4", + "lane": "default-l4-default", + "monthlyCost": 759.2, "chosen": { "cell": { "machineProfile": "l4", @@ -96,6 +100,7 @@ }, "demandRequests": 3, "lane": "baai-bge-m3-sparse-l4", + "monthlyCost": 47.45, "chosen": { "cell": { "machineProfile": "l4", @@ -128,6 +133,7 @@ }, "demandRequests": 42, "lane": "qwen-qwen3-8b-a100-80gb", + "monthlyCost": 382.03, "chosen": { "cell": { "machineProfile": "a100-80gb", @@ -192,6 +198,7 @@ }, "demandRequests": 3600, "lane": "qwen-qwen3-embedding-4b-l4", + "monthlyCost": 759.2, "chosen": { "cell": { "machineProfile": "l4", @@ -271,32 +278,29 @@ } ], "lanes": [ - { - "name": "baai-bge-m3-l4", - "identities": [ - "BAAI/bge-m3" - ], - "hourlyCost": 1.04, - "floorMonthlyCost": 759.2, - "envelopeMaxMonthlyCost": 1518.4 - }, { "name": "baai-bge-m3-sparse-l4", "identities": [ "BAAI/bge-m3:sparse" ], "hourlyCost": 1.04, + "monthlyCost": 47.45, "floorMonthlyCost": 0.0, "envelopeMaxMonthlyCost": 1518.4 }, { "name": "default-l4-default", "identities": [ + "BAAI/bge-m3", "intfloat/e5-base-v2" ], "hourlyCost": 1.04, + "monthlyCost": 759.2, "floorMonthlyCost": 759.2, - "envelopeMaxMonthlyCost": 1518.4 + "envelopeMaxMonthlyCost": 1518.4, + "unpricedIdentities": [ + "intfloat/e5-base-v2" + ] }, { "name": "qwen-qwen3-8b-a100-80gb", @@ -304,6 +308,7 @@ "Qwen/Qwen3-8B" ], "hourlyCost": 3.14, + "monthlyCost": 382.03, "floorMonthlyCost": 0.0, "envelopeMaxMonthlyCost": 4584.4 }, @@ -313,10 +318,23 @@ "Qwen/Qwen3-Embedding-4B" ], "hourlyCost": 1.04, + "monthlyCost": 759.2, "floorMonthlyCost": 759.2, "envelopeMaxMonthlyCost": 1518.4 } ], + "sharedChartLanes": [ + { + "queuePool": "default", + "machineProfile": "l4", + "bundle": "default", + "lanes": [ + "baai-bge-m3-sparse-l4", + "default-l4-default", + "qwen-qwen3-embedding-4b-l4" + ] + } + ], "measurementRequests": [ { "identity": "Qwen/Qwen3-Reranker-0.6B", @@ -593,19 +611,6 @@ ], "changes": { "identities": [ - { - "identity": "BAAI/bge-m3", - "before": { - "identity": "BAAI/bge-m3", - "lane": "default-l4-default", - "warmth": "pinned" - }, - "after": { - "identity": "BAAI/bge-m3", - "lane": "baai-bge-m3-l4", - "warmth": "pinned" - } - }, { "identity": "BAAI/bge-m3:sparse", "after": { @@ -624,29 +629,6 @@ } ], "lanes": [ - { - "name": "baai-bge-m3-l4", - "after": { - "name": "baai-bge-m3-l4", - "queuePool": "default", - "bundle": "default", - "cell": { - "machineProfile": "l4", - "gpuProduct": "NVIDIA-L4" - }, - "containerShape": { - "gpuCount": 1, - "cpuCores": 4, - "memoryMiB": 16384 - }, - "concurrency": 16, - "maxContainers": 4, - "envelope": { - "floorMin": 1, - "floorMax": 2 - } - } - }, { "name": "baai-bge-m3-sparse-l4", "after": { diff --git a/packages/sie_placement/tests/test_levers.py b/packages/sie_placement/tests/test_levers.py index 27e8a02df..9d762a98d 100644 --- a/packages/sie_placement/tests/test_levers.py +++ b/packages/sie_placement/tests/test_levers.py @@ -55,14 +55,14 @@ L4_HOURLY = 1.0 + 4 * 0.1 -def receipt(identity, cell=L4, *, shape=SHAPE, p99=100.0, concurrency=8): +def receipt(identity, cell=L4, *, shape=SHAPE, p99=100.0, concurrency=8, rps=10.0): return Receipt( identity=identity, cell=cell, container_shape=shape, concurrency=concurrency, request_shape=RequestShape(operation=Operation.ENCODE, items_per_request=1), - throughput=Throughput(requests_per_second=10.0), + throughput=Throughput(requests_per_second=rps), latency=Percentiles(p99_ms=p99), source=SourceRef(uri=f"receipts/{identity}/{cell.machine_profile}/{shape.memory_mib}/{concurrency}"), ) @@ -81,7 +81,7 @@ def boot(identity, seconds, warmth=Warmth.COLD_WITH_BOUND, cell=L4, *, shape=SHA ) -def busy(*identities, hours=6): +def busy(*identities, hours=6, requests=10): return Demand( start=START, end=START + timedelta(hours=24), @@ -89,7 +89,9 @@ def busy(*identities, hours=6): DemandSeries( identity=identity, operation=Operation.ENCODE, - hours=tuple(DemandHour(start=START + timedelta(hours=hour), requests=10) for hour in range(hours)), + hours=tuple( + DemandHour(start=START + timedelta(hours=hour), requests=requests) for hour in range(hours) + ), ) for identity in identities ), @@ -213,3 +215,17 @@ def test_each_cell_shape_and_warmth_is_one_lever_at_its_cheapest_receipt(): assert by_key[(SHAPE, Warmth.COLD_WITH_BOUND)].monthly_cost == pytest.approx(cold_cost()) assert by_key[(WIDE, Warmth.COLD_WITH_BOUND)].monthly_cost == pytest.approx((1.0 + 8 * 0.1) * 6 * 2 * SCALE) assert by_key[(SHAPE, Warmth.SNAPSHOT_COLD)].permitted_bound_s == 90 + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_a_lever_is_priced_at_the_cheapest_receipt_of_its_cell_and_shape(reverse): + receipts = [receipt("org/model", rps=0.01), receipt("org/model", concurrency=16, rps=0.02)] + report = run( + {"org/model": 60}, + receipts[::-1] if reverse else receipts, + [boot("org/model", 240.0)], + busy("org/model", requests=1), + ) + (lever,) = report.come_alive_levers + assert lever.monthly_cost == pytest.approx(L4_HOURLY * 6 * (1 / 0.02 + 1 * 2 * 900) / 3600 * SCALE) + assert lever.saving_under_bound == pytest.approx(L4_HOURLY * MONTH - lever.monthly_cost) diff --git a/packages/sie_placement/tests/test_planner.py b/packages/sie_placement/tests/test_planner.py index 90776c2bd..c039599a0 100644 --- a/packages/sie_placement/tests/test_planner.py +++ b/packages/sie_placement/tests/test_planner.py @@ -191,7 +191,17 @@ def run(service_levels, receipts=(), boots=(), *, prices=None, hourly=None, curr ) -def single_lane_plan(name="shared", warmth=Warmth.PINNED, cell=L4, identity=IDENTITY) -> Plan: +def single_lane_plan( + name="shared", + warmth=Warmth.PINNED, + cell=L4, + identity=IDENTITY, + *, + others=(), + concurrency=8, + max_containers=2, + envelope=None, +) -> Plan: floor = 1 if warmth is Warmth.PINNED else 0 return Plan( placement="test", @@ -202,12 +212,14 @@ def single_lane_plan(name="shared", warmth=Warmth.PINNED, cell=L4, identity=IDEN bundle="default", cell=cell, container_shape=SHAPE, - concurrency=8, - max_containers=2, - envelope=Envelope(floor_min=floor, floor_max=max(floor, 1)), + concurrency=concurrency, + max_containers=max_containers, + envelope=envelope or Envelope(floor_min=floor, floor_max=max(floor, 1)), ), ), - identities=(PlanIdentity(identity=identity, lane=name, warmth=warmth),), + identities=tuple( + PlanIdentity(identity=resident, lane=name, warmth=warmth) for resident in sorted((identity, *others)) + ), ) @@ -250,6 +262,23 @@ def test_a_pinned_cell_costs_its_floor_plus_the_hours_demand_needs_above_it(): assert report.demand_requests == 9100 +def test_demand_sums_its_operations_in_each_hour(): + hour = START + timedelta(hours=3) + mixed = Demand( + start=START, + end=START + timedelta(hours=WINDOW_HOURS), + series=tuple( + DemandSeries(identity=IDENTITY, operation=operation, hours=(DemandHour(start=hour, requests=requests),)) + for operation, requests in ((Operation.ENCODE, 5000), (Operation.SCORE, 4000)) + ), + ) + result = plan(level(come_alive_p95_s=0), [receipt(rps=1.0)], (), L4_ONLY, mixed, None, parameters()) + report = result.report.identity(IDENTITY) + assert report.demand_requests == 9000 + assert report.peak_containers == 3 + assert report.chosen.monthly_cost == pytest.approx(MONTH + (3 - 1) * SCALE) + + def test_needed_containers_stop_at_the_reviewed_ceiling(): result = run( level(come_alive_p95_s=0), [receipt(rps=1.0)], prices=L4_ONLY, hourly={IDENTITY: {0: 36000}}, max_containers=2 @@ -271,6 +300,20 @@ def test_a_cold_cell_costs_its_work_and_the_tail_each_burst_holds(): assert chosen.monthly_cost == pytest.approx((one_burst + capped_hour) / 3600 * SCALE) +def test_a_saturated_cold_hour_runs_at_most_the_ceiling(): + result = run( + level(come_alive_p95_s=120), + [receipt(rps=1.0)], + [boot()], + prices=L4_ONLY, + hourly={IDENTITY: {0: 36000}}, + max_containers=2, + ) + chosen = result.report.identity(IDENTITY).chosen + assert chosen.warmth is Warmth.COLD_WITH_BOUND + assert chosen.monthly_cost == pytest.approx(2 * SCALE) + + def test_an_active_lane_without_a_fallback_floor_holds_one_container(): result = run( level(come_alive_p95_s=120), @@ -321,6 +364,28 @@ def test_a_cold_posture_without_boot_evidence_is_a_measurement_request(): assert request.saving_bound == pytest.approx(MONTH) +@pytest.mark.parametrize("reverse", [False, True]) +def test_a_cell_without_boot_evidence_asks_once_at_its_cheapest_receipt(reverse): + receipts = [receipt(rps=0.01), receipt(concurrency=16, rps=0.02)] + result = run( + level(come_alive_p95_s=120), + receipts[::-1] if reverse else receipts, + prices=L4_ONLY, + hourly={IDENTITY: {0: 1}}, + ) + (request,) = result.report.measurement_requests + assert request.measure == (Measurement.BOOT_EVIDENCE,) + assert request.cost_bound == pytest.approx((1 / 0.02 + 1 * 2 * 900) / 3600 * SCALE) + + +def test_snapshot_restores_are_never_requested(): + result = run(level(come_alive_p95_s=120), [receipt()], [boot(seconds=300.0)], prices=L4_ONLY) + report = result.report + assert report.identity(IDENTITY).chosen.warmth is Warmth.PINNED + assert report.measurement_requests == () + assert [lever.warmth for lever in report.come_alive_levers] == [Warmth.COLD_WITH_BOUND] + + def test_a_failed_boot_is_not_selectable_and_asks_for_a_new_measurement(): boots = [boot(seconds=900.0, outcome=BootOutcome.TIMED_OUT)] result = run(level(come_alive_p95_s=600), [receipt()], boots, prices=L4_ONLY) @@ -344,6 +409,14 @@ def test_the_slowest_successful_boot_stands_for_the_percentile(): assert report.next_cheaper.blocked_by == (Blocker(field="comeAliveP95S", bound=120, measured=130.0),) +def test_boot_seconds_render_the_same_whatever_their_number_type(): + boots = [boot(seconds=60, uri="boots/1.json"), boot(seconds=60.0, uri="boots/2.json")] + first = run(level(come_alive_p95_s=120), [receipt()], boots, prices=L4_ONLY) + second = run(level(come_alive_p95_s=120), [receipt()], boots[::-1], prices=L4_ONLY) + assert rendered(first) == rendered(second) + assert first.report.to_dict()["identities"][0]["chosen"]["comeAliveS"] == 60.0 + + def test_own_boot_evidence_replaces_borrowed_evidence(): borrowed = boot(seconds=150.0, borrowed=True, uri="boots/borrowed.json") own = boot(seconds=60.0, uri="boots/own.json") @@ -581,6 +654,9 @@ def test_the_plan_carries_the_envelope_and_the_report_prices_its_maximum(): assert lane_report.envelope_max_monthly_cost == pytest.approx(3 * MONTH) assert result.report.envelope_max_monthly_cost == pytest.approx(3 * MONTH) assert result.report.monthly_cost == pytest.approx(MONTH) + assert lane_report.monthly_cost == pytest.approx(MONTH) + assert result.report.identity(IDENTITY).monthly_cost == pytest.approx(MONTH) + assert result.report.unpriced_lanes == () def test_every_declared_queue_wait_bound_is_reported_unattained(): @@ -604,6 +680,114 @@ def test_an_identity_without_a_feasible_cell_keeps_its_current_lane(): assert report.current == current.identities[0] assert result.report.unchanged assert result.report.lanes[0].floor_monthly_cost == pytest.approx(MONTH) + assert report.monthly_cost == pytest.approx(MONTH) + assert report.blocked_by == (Blocker(field="warmP99Ms", bound=50, measured=100.0),) + assert result.report.monthly_cost == pytest.approx(MONTH) + assert result.report.to_dict()["totals"] == { + "monthlyCost": MONTH, + "envelopeMaxMonthlyCost": MONTH, + "unpricedLanes": [], + } + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_a_kept_lane_prices_its_demand_at_the_slowest_receipt_for_its_cell(reverse): + current = single_lane_plan(max_containers=4, envelope=Envelope(floor_min=1, floor_max=2)) + receipts = [receipt(rps=1.0, p99=100.0, uri="receipts/slow"), receipt(rps=2.0, p99=100.0, uri="receipts/fast")] + result = run( + level(come_alive_p95_s=0, warm_p99_ms=50), + receipts[::-1] if reverse else receipts, + prices=L4_ONLY, + hourly={IDENTITY: {3: 9000}}, + current=current, + ) + assert result.plan == current + report = result.report.identity(IDENTITY) + assert report.status is IdentityStatus.KEPT + assert report.monthly_cost == pytest.approx(MONTH + (3 - 1) * SCALE) + (lane,) = result.report.lanes + assert lane.monthly_cost == pytest.approx(MONTH + (3 - 1) * SCALE) + assert result.report.monthly_cost == pytest.approx(MONTH + (3 - 1) * SCALE) + assert result.report.envelope_max_monthly_cost == pytest.approx(2 * MONTH) + + +@pytest.mark.parametrize( + ("warmth", "ceiling", "hourly", "hours"), + [ + (Warmth.PINNED, 2, {3: 9000}, MONTH + (2 - 1) * SCALE), + (Warmth.COLD_WITH_BOUND, 1, {0: 1}, (1 / 1.0 + 1 * 1 * 900) / 3600 * SCALE), + ], +) +def test_a_kept_lane_prices_its_demand_under_its_own_ceiling(warmth, ceiling, hourly, hours): + current = single_lane_plan(warmth=warmth, max_containers=ceiling) + result = run( + level(come_alive_p95_s=600, warm_p99_ms=50), + [receipt(rps=1.0, p99=100.0)], + prices=L4_ONLY, + hourly={IDENTITY: hourly}, + current=current, + ) + assert result.plan == current + assert result.report.identity(IDENTITY).monthly_cost == pytest.approx(hours) + + +def test_a_kept_lane_without_a_receipt_for_its_demand_lists_it_unpriced(): + current = single_lane_plan() + result = run(level(come_alive_p95_s=0), [], prices=L4_ONLY, hourly={IDENTITY: {0: 10}}, current=current) + report = result.report.identity(IDENTITY) + assert (report.status, report.monthly_cost) == (IdentityStatus.KEPT, None) + (lane,) = result.report.lanes + assert lane.unpriced_identities == (IDENTITY,) + assert lane.monthly_cost == pytest.approx(MONTH) + assert result.report.unpriced_lanes == ("shared",) + assert result.report.monthly_cost == pytest.approx(MONTH) + + +def test_a_kept_lane_on_a_refused_cell_is_kept_and_reported_unpriced(): + other = Cell(machine_profile="l4", gpu_product="NVIDIA-A10G") + current = single_lane_plan(cell=other) + result = run(level(come_alive_p95_s=0), [], prices=L4_ONLY, current=current) + assert result.plan == current + (lane,) = result.report.lanes + assert lane.unpriced_reason == ( + "realized GPU product 'NVIDIA-A10G' differs from 'NVIDIA-L4', the product machine profile 'l4' requests" + ) + assert (lane.hourly_cost, lane.monthly_cost, lane.envelope_max_monthly_cost) == (None, None, None) + assert result.report.identity(IDENTITY).monthly_cost is None + assert result.report.to_dict()["totals"] == { + "monthlyCost": 0.0, + "envelopeMaxMonthlyCost": 0.0, + "unpricedLanes": ["shared"], + } + + +def test_a_kept_lane_never_exceeds_the_reviewed_ceiling(): + current = single_lane_plan(max_containers=4, envelope=Envelope(floor_min=2, floor_max=3)) + result = run(level(come_alive_p95_s=0), [], prices=L4_ONLY, current=current, max_containers=1) + (lane,) = result.plan.lanes + assert (lane.max_containers, lane.envelope) == (1, Envelope(floor_min=1, floor_max=1)) + (change,) = result.report.lane_changes + assert (change.name, change.before, change.after) == ("shared", current.lanes[0], lane) + + +@pytest.mark.parametrize( + ("bound", "boots", "expected"), + [ + (0, (), (Blocker(field="comeAliveP95S", bound=0, measured=None),)), + (120, (), ()), + (120, (boot(seconds=200.0),), (Blocker(field="comeAliveP95S", bound=120, measured=200.0),)), + (300, (boot(seconds=200.0),), ()), + ], +) +def test_a_kept_cold_placement_names_the_come_alive_bound_it_is_known_to_miss(bound, boots, expected): + current = single_lane_plan(warmth=Warmth.COLD_WITH_BOUND) + result = run(level(come_alive_p95_s=bound), [], boots, prices=L4_ONLY, current=current) + report = result.report.identity(IDENTITY) + assert report.status is IdentityStatus.KEPT + assert report.blocked_by == expected + assert report.monthly_cost == 0 + if expected and expected[0].measured is None: + assert report.to_dict()["blockedBy"] == [{"field": "comeAliveP95S", "bound": 0}] def test_an_identity_without_a_feasible_cell_or_a_current_lane_is_left_out(): @@ -639,6 +823,141 @@ def test_a_derived_lane_name_never_takes_a_kept_lane_name(): assert names[IDENTITY] == f"org-model-l4-{hashlib.sha256(IDENTITY.encode()).hexdigest()[:8]}" +def test_a_current_placement_keeps_its_lane_name(): + current = single_lane_plan(name="legacy") + result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY, current=current, max_containers=2) + assert result.plan == current + assert result.report.identity(IDENTITY).lane == "legacy" + assert result.report.unchanged + + +def test_a_current_placement_that_differs_only_in_its_envelope_keeps_its_lane_name(): + current = single_lane_plan(name="legacy", max_containers=8, envelope=Envelope(floor_min=2, floor_max=5)) + result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY, current=current) + (lane,) = result.plan.lanes + assert (lane.name, lane.max_containers, lane.envelope) == ("legacy", 4, Envelope(floor_min=1, floor_max=1)) + assert result.report.identity_changes == () + assert [change.name for change in result.report.lane_changes] == ["legacy"] + + +def test_a_current_lane_that_differs_in_concurrency_is_not_the_current_placement(): + current = single_lane_plan(name="legacy", max_containers=4) + receipts = [receipt(concurrency=16), receipt(concurrency=8)] + result = run(level(come_alive_p95_s=0), receipts, prices=L4_ONLY, current=current) + (lane,) = result.plan.lanes + assert (lane.name, lane.concurrency) == ("legacy", 8) + assert result.report.unchanged + moved = run(level(come_alive_p95_s=0), [receipts[0]], prices=L4_ONLY, current=current) + (lane,) = moved.plan.lanes + assert (lane.name, lane.concurrency) == ("org-model-l4", 16) + assert [(change.name, change.before is None) for change in moved.report.lane_changes] == [ + ("legacy", False), + ("org-model-l4", True), + ] + + +def test_a_current_placement_on_a_shared_lane_stays_beside_its_kept_neighbour(): + current = single_lane_plan(others=("org/kept",), max_containers=4) + service_levels = levels( + (IDENTITY, ServiceLevel(come_alive_p95_s=0)), ("org/kept", ServiceLevel(come_alive_p95_s=0)) + ) + result = run(service_levels, [receipt()], prices=L4_ONLY, current=current, hourly={IDENTITY: {3: 300000}}) + assert result.plan == current + assert result.report.unchanged + (lane,) = result.report.lanes + assert lane.identities == ("org/kept", IDENTITY) + above = (min(4, math.ceil(300000 / 36000)) - 1) * SCALE + assert lane.monthly_cost == pytest.approx(MONTH + above) + assert result.report.identity(IDENTITY).monthly_cost == pytest.approx(MONTH + above) + assert result.report.identity("org/kept").monthly_cost == pytest.approx(MONTH) + assert result.report.monthly_cost == pytest.approx(MONTH + above) + + +def test_current_placements_that_share_a_lane_keep_sharing_it(): + current = single_lane_plan(others=("org/other",), max_containers=4) + service_levels = levels((IDENTITY, ServiceLevel()), ("org/other", ServiceLevel())) + result = run(service_levels, [receipt(), receipt(identity="org/other")], prices=L4_ONLY, current=current) + assert result.plan == current + assert result.report.unchanged + assert result.report.monthly_cost == pytest.approx(MONTH) + assert result.report.shared_chart_lanes == () + + +def test_a_placement_that_moves_leaves_its_shared_lane_to_the_kept_neighbour(): + current = single_lane_plan(others=("org/kept",), max_containers=4) + service_levels = levels( + (IDENTITY, ServiceLevel(come_alive_p95_s=0, warm_p99_ms=250)), ("org/kept", ServiceLevel(come_alive_p95_s=0)) + ) + receipts = [receipt(p99=300.0), receipt(cell=A100)] + result = run(service_levels, receipts, current=current) + names = {entry.identity: entry.lane for entry in result.plan.identities} + assert names == {IDENTITY: "org-model-a100-80gb", "org/kept": "shared"} + assert result.report.identity(IDENTITY).current == current.identities[1] + + +@pytest.mark.parametrize( + ("overrides", "moved"), + [({"bundles": {IDENTITY: "sglang"}}, ("default", "sglang")), ({"queue_pool": "batch"}, ("batch", "default"))], +) +def test_a_new_queue_pool_or_bundle_moves_the_identity_off_its_current_lane(overrides, moved): + current = single_lane_plan(others=("org/kept",), max_containers=4) + service_levels = levels( + (IDENTITY, ServiceLevel(come_alive_p95_s=0)), ("org/kept", ServiceLevel(come_alive_p95_s=0)) + ) + result = run(service_levels, [receipt()], prices=L4_ONLY, current=current, **overrides) + lanes = {lane.name: (lane.queue_pool, lane.bundle) for lane in result.plan.lanes} + assert lanes == {"org-model-l4": moved, "shared": ("default", "default")} + + +def test_removing_one_of_two_colliding_identities_keeps_the_other_lane_name(): + service_levels = levels(("org/model", ServiceLevel()), ("org-model", ServiceLevel())) + receipts = [receipt(identity="org/model"), receipt(identity="org-model")] + first = run(service_levels, receipts, prices=L4_ONLY) + second = run(levels(("org/model", ServiceLevel())), receipts, prices=L4_ONLY, current=first.plan) + digest = hashlib.sha256(b"org-model").hexdigest()[:8] + kept_name = f"org-model-l4-{hashlib.sha256(b'org/model').hexdigest()[:8]}" + assert [entry.lane for entry in second.plan.identities] == [kept_name] + assert [(change.identity, change.after) for change in second.report.identity_changes] == [("org-model", None)] + assert [(change.name, change.after) for change in second.report.lane_changes] == [(f"org-model-l4-{digest}", None)] + + +def test_plan_lanes_that_name_one_chart_lane_are_reported(): + service_levels = levels(("org/a", ServiceLevel()), ("org/b", ServiceLevel()), ("org/c", ServiceLevel())) + receipts = [receipt(identity=identity) for identity in ("org/a", "org/b", "org/c")] + result = run(service_levels, receipts, prices=L4_ONLY, bundles={"org/c": "sglang"}) + (shared,) = result.report.shared_chart_lanes + assert shared.to_dict() == { + "queuePool": "default", + "machineProfile": "l4", + "bundle": "default", + "lanes": ["org-a-l4", "org-b-l4"], + } + apart = run(service_levels, receipts, prices=L4_ONLY, bundles={"org/a": "a", "org/b": "b"}) + assert apart.report.shared_chart_lanes == () + + +def test_a_derived_lane_name_never_takes_a_kept_lane_named_with_its_digest(): + digest = hashlib.sha256(IDENTITY.encode()).hexdigest() + first = single_lane_plan(name="org-model-l4", identity="org/kept") + second = single_lane_plan(name=f"org-model-l4-{digest[:8]}", identity="org/kept-too") + current = Plan( + placement="test", lanes=(*first.lanes, *second.lanes), identities=(*first.identities, *second.identities) + ) + service_levels = levels( + (IDENTITY, ServiceLevel()), + ("org/kept", ServiceLevel(come_alive_p95_s=0)), + ("org/kept-too", ServiceLevel(come_alive_p95_s=0)), + ) + result = run(service_levels, [receipt()], prices=L4_ONLY, current=current) + names = {entry.identity: entry.lane for entry in result.plan.identities} + assert names == { + IDENTITY: f"org-model-l4-{digest}", + "org/kept": "org-model-l4", + "org/kept-too": f"org-model-l4-{digest[:8]}", + } + assert {lane.name: lane for lane in result.plan.lanes}[f"org-model-l4-{digest[:8]}"] == second.lanes[0] + + def test_bundles_and_the_queue_pool_come_from_the_parameters(): service_levels = levels(("org/embed", ServiceLevel()), ("org/generate", ServiceLevel())) result = run( @@ -781,7 +1100,7 @@ def test_the_estate_places_every_identity_on_a_measured_feasible_cell(): def test_the_estate_report_states_its_findings(): report = plan(**estate()).report dense = report.identity("BAAI/bge-m3") - assert (dense.chosen.cell, dense.chosen.warmth) == (L4, Warmth.PINNED) + assert (dense.chosen.cell, dense.chosen.warmth, dense.lane) == (L4, Warmth.PINNED, "default-l4-default") assert dense.chosen.monthly_cost == pytest.approx(1.04 * MONTH) assert dense.next_cheaper.warmth is Warmth.SNAPSHOT_COLD assert dense.next_cheaper.blocked_by == (Blocker(field="comeAliveP95S", bound=0, measured=8.5),) @@ -793,16 +1112,22 @@ def test_the_estate_report_states_its_findings(): assert generation.chosen.monthly_cost == pytest.approx(3.14 * 2 * 2 * SCALE) assert generation.next_cheaper.blocked_by == (Blocker(field="itlP99Ms", bound=80, measured=118.0),) assert report.identity("Qwen/Qwen3-Reranker-0.6B").status is IdentityStatus.UNPLACED - assert report.identity("intfloat/e5-base-v2").status is IdentityStatus.KEPT + kept = report.identity("intfloat/e5-base-v2") + assert (kept.status, kept.lane, kept.monthly_cost) == (IdentityStatus.KEPT, "default-l4-default", None) assert [refusal.record for refusal in report.refusals] == [RefusedRecord.BOOT_EVIDENCE, RefusedRecord.RECEIPT] assert report.queue_wait_unattained == ("BAAI/bge-m3", "BAAI/bge-m3:sparse", "intfloat/e5-base-v2") - assert [change.identity for change in report.identity_changes] == [ - "BAAI/bge-m3", - "BAAI/bge-m3:sparse", - "Qwen/Qwen3-Embedding-4B", - ] - assert report.monthly_cost == pytest.approx( - sum(entry.chosen.monthly_cost for entry in report.identities if entry.chosen is not None) + assert [change.identity for change in report.identity_changes] == ["BAAI/bge-m3:sparse", "Qwen/Qwen3-Embedding-4B"] + assert report.monthly_cost == pytest.approx(sum(lane.monthly_cost for lane in report.lanes)) + shared = {lane.name: lane for lane in report.lanes}["default-l4-default"] + assert shared.identities == ("BAAI/bge-m3", "intfloat/e5-base-v2") + assert shared.monthly_cost == pytest.approx(dense.monthly_cost) + assert shared.unpriced_identities == ("intfloat/e5-base-v2",) + assert report.unpriced_lanes == ("default-l4-default",) + (chart_lane,) = report.shared_chart_lanes + assert chart_lane.lanes == ("baai-bge-m3-sparse-l4", "default-l4-default", "qwen-qwen3-embedding-4b-l4") + current = estate()["current_plan"] + assert sum(lane.envelope.floor_min for lane in plan(**estate()).plan.lanes) == 1 + sum( + lane.envelope.floor_min for lane in current.lanes ) From e6820804f1839e1c490adc637a5057c21c6eb4ce Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Thu, 5 Nov 2026 05:18:11 +0100 Subject: [PATCH 09/16] fix(placement): price come-alive levers by planning again A come-alive lever's savings are now the fall in the plan total found by planning again from the plan the run wrote: savingAtPermittedBound with the identity's come-alive bound loosened to permittedBoundS, and savingUnderBound with the warmth's boot measured at the identity's bound. A lever is listed only when loosening its bound lowers the plan total. An identity that stays beside another resident of its current lane no longer claims the lane's floor as a saving: leaving the lane leaves that floor paid by the other residents, so loosening its bound raises the plan total and the planner offers no lever for it. --- packages/sie_placement/README.md | 14 +++- .../src/sie_placement/planner.py | 77 ++++++++++++++++-- .../fixtures/planner/expected-report.json | 40 ---------- packages/sie_placement/tests/test_levers.py | 79 ++++++++++++++++++- packages/sie_placement/tests/test_planner.py | 57 +++++++++++++ 5 files changed, 214 insertions(+), 53 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index cfeb962ed..72a4f4196 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -230,10 +230,16 @@ The report renders as a `placement-report` document: dropped, and the requests of an identity without a placement carry no bound and rank first. - `comeAliveLevers`: cold warmths whose measured come-alive misses the bound - on a cell that meets the warm bounds for less than the choice. Each is priced - under the identity's bound, where a bound of 0 admits no lever, and at - `permittedBoundS`, the bound its measured come-alive would permit. Levers rank - by the first saving, then by the second. + on a cell that meets the warm bounds for less than the choice, listed only + when loosening the identity's bound to `permittedBoundS`, the bound the + measured come-alive would permit, lowers the plan total. Both savings are + found by planning again from this plan and taking the fall in its total: + `savingAtPermittedBound` with the bound loosened, and `savingUnderBound` with + the warmth's boot measured at the identity's bound, which is 0 under a bound + of 0, since no boot comes under it, and when the total would not fall. An + identity that shares its lane saves nothing of the lane's floor by leaving, + since the other residents keep it. Levers rank by the saving under the bound, + then by the saving at the permitted bound. - `queueWaitUnattained`: every identity that declares `queueWaitP99Ms`. No plan claims that bound as met. - `refusals`, and `changes`: the identities and lanes that differ from diff --git a/packages/sie_placement/src/sie_placement/planner.py b/packages/sie_placement/src/sie_placement/planner.py index df445c623..2ca4306bd 100644 --- a/packages/sie_placement/src/sie_placement/planner.py +++ b/packages/sie_placement/src/sie_placement/planner.py @@ -337,6 +337,8 @@ def __init__( current_plan: Plan | None, parameters: PlannerParameters, ) -> None: + receipts = tuple(receipts) + boot_evidence = tuple(boot_evidence) placements = {placement.name: placement for placement in price_list.placements} placement = placements.get(parameters.placement) if placement is None: @@ -346,6 +348,10 @@ def __init__( f"the current plan is for placement {current_plan.placement!r}, not {parameters.placement!r}" ) self.parameters = parameters + self.service_levels = service_levels + self.receipt_records = receipts + self.boot_records = boot_evidence + self.demand = demand self.price_list = price_list self.multiplier = placement.region_multiplier self.prices = {profile.name: profile for profile in price_list.machine_profiles} @@ -524,8 +530,45 @@ def boot_requests(self, choice: _Choice) -> list[MeasurementRequest]: if chosen.cost - request.cost_bound > 0 ] - @staticmethod - def levers(choice: _Choice) -> list[Lever]: + def replanned_total( + self, + current: Plan, + *, + service_levels: ServiceLevels | None = None, + boot_evidence: Iterable[BootEvidence] | None = None, + ) -> float: + planner = _Planner( + self.service_levels if service_levels is None else service_levels, + self.receipt_records, + self.boot_records if boot_evidence is None else boot_evidence, + self.price_list, + self.demand, + current, + self.parameters, + ) + return planner.run(price_levers=False).report.monthly_cost + + def loosened(self, identity: str, bound: int) -> ServiceLevels: + return replace( + self.service_levels, + identities=tuple( + replace(entry, level=replace(entry.level, come_alive_p95_s=bound)) + if entry.identity == identity + else entry + for entry in self.service_levels.identities + ), + ) + + def booted_within(self, identity: str, option: _Option, bound: int) -> tuple[BootEvidence, ...]: + key = (identity, option.receipt.cell, option.receipt.container_shape, option.warmth) + return tuple( + replace(record, boot_seconds=min(record.boot_seconds, bound)) + if (record.identity, record.cell, record.container_shape, record.warmth) == key + else record + for record in self.boot_records + ) + + def levers(self, choice: _Choice, written: Plan, total: float) -> list[Lever]: chosen = choice.chosen bound = choice.level.come_alive_p95_s if chosen is None or bound is None: @@ -540,9 +583,22 @@ def levers(choice: _Choice) -> list[Lever]: known = best.get(key) if known is None or option.rank < known.rank: best[key] = option + savings: dict[int, float] = {} levers = [] for option in best.values(): - saving = chosen.cost - option.cost + permitted = max(1, math.ceil(option.come_alive_s)) + if permitted not in savings: + replanned = self.replanned_total(written, service_levels=self.loosened(choice.identity, permitted)) + savings[permitted] = _saving(total, replanned) + saving = savings[permitted] + if not saving: + continue + under = 0.0 + if bound > 0: + replanned = self.replanned_total( + written, boot_evidence=self.booted_within(choice.identity, option, bound) + ) + under = _saving(total, replanned) levers.append( Lever( identity=choice.identity, @@ -553,8 +609,8 @@ def levers(choice: _Choice) -> list[Lever]: come_alive_basis=option.basis, bound_s=bound, monthly_cost=option.cost, - saving_under_bound=saving if bound > 0 else 0.0, - permitted_bound_s=max(1, math.ceil(option.come_alive_s)), + saving_under_bound=under, + permitted_bound_s=permitted, saving_at_permitted_bound=saving, ) ) @@ -650,7 +706,7 @@ def demand_hours(self, lane: PlanLane, identity: str, receipt: Receipt | None) - return window.above_floor_hours(requests, rate, lane.envelope.floor_min) return window.cold_container_hours(requests, rate) - def run(self) -> PlannerResult: + def run(self, *, price_levers: bool = True) -> PlannerResult: choices = [self.choose(identity) for identity in sorted(self.levels)] placed = {choice.identity: choice.chosen for choice in choices if choice.chosen is not None} kept = { @@ -678,13 +734,15 @@ def run(self) -> PlannerResult: receipts: dict[str, Receipt | None] = {identity: option.receipt for identity, option in placed.items()} receipts.update({identity: self.slowest_receipt(identity, lane) for identity, (_, lane) in kept.items()}) lane_reports, costs = self._pricing(new_plan, receipts) + total = sum(lane.monthly_cost for lane in lane_reports if lane.monthly_cost is not None) reports: list[IdentityReport] = [] requests: list[MeasurementRequest] = [] levers: list[Lever] = [] for choice in choices: requests.extend(self.receipt_requests(choice)) requests.extend(self.boot_requests(choice)) - levers.extend(self.levers(choice)) + if price_levers: + levers.extend(self.levers(choice, new_plan, total)) reports.append( self._identity_report(choice, names, kept, costs.get(choice.identity), receipts.get(choice.identity)) ) @@ -785,6 +843,11 @@ def _pricing( return tuple(reports), costs +def _saving(total: float, replanned: float) -> float: + saving = total - replanned + return saving if round(saving, 2) > 0 else 0.0 + + def _shared_chart_lanes(plan: Plan) -> tuple[SharedChartLane, ...]: grouped: defaultdict[tuple[str, str, str], list[str]] = defaultdict(list) for lane in plan.lanes: diff --git a/packages/sie_placement/tests/fixtures/planner/expected-report.json b/packages/sie_placement/tests/fixtures/planner/expected-report.json index 7de1fe3db..e231c560c 100644 --- a/packages/sie_placement/tests/fixtures/planner/expected-report.json +++ b/packages/sie_placement/tests/fixtures/planner/expected-report.json @@ -534,46 +534,6 @@ "savingUnderBound": 379.6, "permittedBoundS": 45, "savingAtPermittedBound": 379.6 - }, - { - "identity": "BAAI/bge-m3", - "cell": { - "machineProfile": "l4", - "gpuProduct": "NVIDIA-L4" - }, - "containerShape": { - "gpuCount": 1, - "cpuCores": 4, - "memoryMiB": 16384 - }, - "warmth": "cold-with-bound", - "comeAliveS": 95.0, - "comeAliveBasis": "borrowed-boot-evidence", - "comeAliveBoundS": 0, - "monthlyCost": 569.4, - "savingUnderBound": 0.0, - "permittedBoundS": 95, - "savingAtPermittedBound": 189.8 - }, - { - "identity": "BAAI/bge-m3", - "cell": { - "machineProfile": "l4", - "gpuProduct": "NVIDIA-L4" - }, - "containerShape": { - "gpuCount": 1, - "cpuCores": 4, - "memoryMiB": 16384 - }, - "warmth": "snapshot-cold", - "comeAliveS": 8.5, - "comeAliveBasis": "boot-evidence", - "comeAliveBoundS": 0, - "monthlyCost": 569.4, - "savingUnderBound": 0.0, - "permittedBoundS": 9, - "savingAtPermittedBound": 189.8 } ], "queueWaitUnattained": [ diff --git a/packages/sie_placement/tests/test_levers.py b/packages/sie_placement/tests/test_levers.py index 9d762a98d..feed8adf7 100644 --- a/packages/sie_placement/tests/test_levers.py +++ b/packages/sie_placement/tests/test_levers.py @@ -13,11 +13,15 @@ Demand, DemandHour, DemandSeries, + Envelope, IdentityServiceLevel, MachineProfilePrice, Operation, Percentiles, Placement, + Plan, + PlanIdentity, + PlanLane, PriceList, Receipt, RequestShape, @@ -98,14 +102,39 @@ def busy(*identities, hours=6, requests=10): ) -def run(bounds, receipts, boots, demand=None): +def planned(bounds, receipts, boots, demand=None, current=None): service_levels = ServiceLevels( identities=tuple( IdentityServiceLevel(identity=identity, level=ServiceLevel(come_alive_p95_s=bound, warm_p99_ms=250)) for identity, bound in bounds.items() ) ) - return plan(service_levels, receipts, boots, PRICES, demand or busy(*bounds), None, PARAMETERS).report + return plan(service_levels, receipts, boots, PRICES, demand or busy(*bounds), current, PARAMETERS) + + +def run(bounds, receipts, boots, demand=None): + return planned(bounds, receipts, boots, demand).report + + +def shared_lane(*identities): + return Plan( + placement="test", + lanes=( + PlanLane( + name="shared", + queue_pool="default", + bundle="default", + cell=L4, + container_shape=SHAPE, + concurrency=8, + max_containers=4, + envelope=Envelope(floor_min=1, floor_max=1), + ), + ), + identities=tuple( + PlanIdentity(identity=identity, lane="shared", warmth=Warmth.PINNED) for identity in identities + ), + ) def cold_cost(hours=6): @@ -229,3 +258,49 @@ def test_a_lever_is_priced_at_the_cheapest_receipt_of_its_cell_and_shape(reverse (lever,) = report.come_alive_levers assert lever.monthly_cost == pytest.approx(L4_HOURLY * 6 * (1 / 0.02 + 1 * 2 * 900) / 3600 * SCALE) assert lever.saving_under_bound == pytest.approx(L4_HOURLY * MONTH - lever.monthly_cost) + + +@pytest.mark.parametrize(("bound", "seconds", "permitted"), [(0, 95.2, 96), (60, 240.0, 240)]) +def test_an_identity_staying_beside_a_neighbour_offers_no_lever_that_loosening_its_bound_would_not_pay( + bound, seconds, permitted +): + bounds = {"org/a": bound, "org/b": 0} + receipts = [receipt("org/a"), receipt("org/b")] + boots = [boot("org/a", seconds)] + result = planned(bounds, receipts, boots, current=shared_lane("org/a", "org/b")) + assert result.plan == shared_lane("org/a", "org/b") + assert result.report.identity("org/a").chosen.monthly_cost == pytest.approx(L4_HOURLY * MONTH) + assert result.report.come_alive_levers == () + loosened = planned({**bounds, "org/a": permitted}, receipts, boots, current=result.plan) + assert loosened.report.identity("org/a").chosen.warmth is Warmth.COLD_WITH_BOUND + assert loosened.report.monthly_cost - result.report.monthly_cost == pytest.approx(cold_cost()) + + +@pytest.mark.parametrize(("bound", "seconds", "permitted"), [(0, 95.2, 96), (60, 240.0, 240)]) +def test_an_identity_alone_on_its_current_lane_offers_the_lever_that_loosening_its_bound_pays( + bound, seconds, permitted +): + bounds = {"org/a": bound, "org/b": 0} + receipts = [receipt("org/a"), receipt("org/b")] + boots = [boot("org/a", seconds)] + result = planned(bounds, receipts, boots, current=shared_lane("org/a")) + assert result.report.identity("org/a").lane == "shared" + (lever,) = result.report.come_alive_levers + assert (lever.identity, lever.permitted_bound_s) == ("org/a", permitted) + loosened = planned({**bounds, "org/a": permitted}, receipts, boots, current=result.plan) + saving = result.report.monthly_cost - loosened.report.monthly_cost + assert saving == pytest.approx(L4_HOURLY * MONTH - cold_cost()) + assert lever.saving_at_permitted_bound == pytest.approx(saving) + assert lever.saving_under_bound == (0 if bound == 0 else pytest.approx(saving)) + + +def test_a_lever_saves_under_its_bound_what_its_own_boot_unlocks_and_at_its_permitted_bound_all_that_bound_unlocks(): + receipts = [receipt("org/model"), receipt("org/model", shape=WIDE)] + boots = [boot("org/model", 240.0), boot("org/model", 300.0, shape=WIDE)] + report = run({"org/model": 60}, receipts, boots) + by_shape = {lever.container_shape: lever for lever in report.come_alive_levers} + assert by_shape[WIDE].monthly_cost == pytest.approx((1.0 + 8 * 0.1) * 6 * 2 * SCALE) + assert by_shape[WIDE].saving_under_bound == pytest.approx(L4_HOURLY * MONTH - by_shape[WIDE].monthly_cost) + assert by_shape[WIDE].saving_at_permitted_bound == pytest.approx(L4_HOURLY * MONTH - cold_cost()) + assert by_shape[SHAPE].saving_under_bound == pytest.approx(L4_HOURLY * MONTH - cold_cost()) + assert [lever.container_shape for lever in report.come_alive_levers] == [SHAPE, WIDE] diff --git a/packages/sie_placement/tests/test_planner.py b/packages/sie_placement/tests/test_planner.py index c039599a0..d1065bbd1 100644 --- a/packages/sie_placement/tests/test_planner.py +++ b/packages/sie_placement/tests/test_planner.py @@ -4,6 +4,7 @@ import json import math import random +from dataclasses import replace from datetime import UTC, datetime, timedelta from pathlib import Path @@ -243,6 +244,16 @@ def rendered(result) -> tuple[str, str]: return render(result.plan.to_dict()), render(result.report.to_dict()) +def loosened(service_levels: ServiceLevels, identity: str, bound: int) -> ServiceLevels: + return replace( + service_levels, + identities=tuple( + replace(entry, level=replace(entry.level, come_alive_p95_s=bound)) if entry.identity == identity else entry + for entry in service_levels.identities + ), + ) + + def test_container_hourly_cost_prices_accelerators_cores_and_memory(): price = MachineProfilePrice( name="l4", gpu_product="NVIDIA-L4", accelerator_per_hour=2.0, core_per_hour=0.05, memory_gib_per_hour=0.01 @@ -1131,6 +1142,35 @@ def test_the_estate_report_states_its_findings(): ) +def test_an_estate_lever_saves_what_planning_again_at_its_permitted_bound_saves(): + inputs = estate() + result = plan(**inputs) + report = result.report + assert [(lever.identity, lever.warmth) for lever in report.come_alive_levers] == [ + ("Qwen/Qwen3-Embedding-4B", Warmth.COLD_WITH_BOUND), + ("Qwen/Qwen3-Embedding-4B", Warmth.SNAPSHOT_COLD), + ] + for lever in report.come_alive_levers: + service_levels = loosened(inputs["service_levels"], lever.identity, lever.permitted_bound_s) + again = plan(**{**inputs, "service_levels": service_levels, "current_plan": result.plan}) + assert report.monthly_cost - again.report.monthly_cost == pytest.approx(lever.saving_at_permitted_bound) + assert lever.saving_at_permitted_bound > 0 + + +def test_an_estate_identity_beside_a_kept_neighbour_offers_no_lever(): + inputs = estate() + result = plan(**inputs) + dense = result.report.identity("BAAI/bge-m3") + assert (dense.lane, dense.chosen.warmth) == ("default-l4-default", Warmth.PINNED) + assert dense.next_cheaper.come_alive_s == 8.5 + assert not [lever for lever in result.report.come_alive_levers if lever.identity == "BAAI/bge-m3"] + for bound in (9, 95): + service_levels = loosened(inputs["service_levels"], "BAAI/bge-m3", bound) + again = plan(**{**inputs, "service_levels": service_levels, "current_plan": result.plan}) + assert again.report.identity("BAAI/bge-m3").chosen.warmth in (Warmth.COLD_WITH_BOUND, Warmth.SNAPSHOT_COLD) + assert again.report.monthly_cost > result.report.monthly_cost + + @pytest.mark.parametrize("seed", range(25)) def test_random_estates_choose_only_feasible_cells_and_replan_to_themselves(seed): rng = random.Random(seed) # noqa: S311 -- reproducible test data @@ -1207,6 +1247,23 @@ def test_random_estates_choose_only_feasible_cells_and_replan_to_themselves(seed for lever in result.report.come_alive_levers: assert lever.monthly_cost < costs[lever.identity] assert lever.saving_at_permitted_bound >= lever.saving_under_bound >= 0 + assert lever.saving_at_permitted_bound > 0 + looser = loosened(service_levels, lever.identity, lever.permitted_bound_s) + again = run(looser, receipts, boots, prices=prices, hourly=hourly, current=result.plan, **overrides) + assert result.report.monthly_cost - again.report.monthly_cost == pytest.approx(lever.saving_at_permitted_bound) + if lever.bound_s == 0: + assert lever.saving_under_bound == 0 + continue + key = (lever.identity, lever.cell, lever.container_shape, lever.warmth) + within = [ + replace(record, boot_seconds=min(record.boot_seconds, lever.bound_s)) + if (record.identity, record.cell, record.container_shape, record.warmth) == key + else record + for record in boots + ] + booted = run(service_levels, receipts, within, prices=prices, hourly=hourly, current=result.plan, **overrides) + fall = result.report.monthly_cost - booted.report.monthly_cost + assert lever.saving_under_bound == pytest.approx(max(0.0, fall), abs=0.01) for request in result.report.measurement_requests: assert request.saving_bound is None or request.saving_bound > 0 again = run(service_levels, receipts, boots, prices=prices, hourly=hourly, current=result.plan, **overrides) From f819b72b691afde492122380a46bbefb40c14c46 Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Thu, 5 Nov 2026 05:43:03 +0100 Subject: [PATCH 10/16] fix(placement): price the next cheaper option by planning again nextCheaper.saving is now the fall in the plan total found by planning again from the plan the run wrote, with each bound that blocks the option loosened to what the option measured, rounded up and never below 1. It is 0 when the total would not fall. The loosened bounds may admit a cheaper option still, and the saving counts it, as savingAtPermittedBound does for a come-alive lever. An identity that stays beside another resident of its current lane no longer claims the lane's floor as a nextCheaper saving: leaving the lane leaves that floor paid by the other residents. Levers and nextCheaper share one cached replan per loosened bound set. --- packages/sie_placement/README.md | 15 +++-- .../src/sie_placement/planner.py | 60 ++++++++++++------- .../fixtures/planner/expected-report.json | 2 +- packages/sie_placement/tests/test_planner.py | 57 +++++++++++++++++- 4 files changed, 107 insertions(+), 27 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index 72a4f4196..8f8322222 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -210,11 +210,16 @@ The report renders as a `placement-report` document: demand costs there with the lane's floor, the chosen cell, warmth, monthly cost and come-alive with its basis (`warm-floor`, `boot-evidence` or `borrowed-boot-evidence`), the peak containers its demand needs, and - `nextCheaper`: the nearest cheaper option a service level blocks, its saving - and the bounds that block it. A kept identity's `blockedBy` names the bounds - its kept placement is known to miss: its receipt's warm latencies, a measured - come-alive over the bound, or a cold warmth under a bound of `0`, which needs - no measurement. + `nextCheaper`: the nearest cheaper option a service level blocks, the bounds + that block it, and `saving`, the fall in the plan total found by planning + again from this plan with each of those bounds loosened to what the option + measured, rounded up to a whole second or millisecond and never below 1. The + loosened bounds may admit a cheaper option still, and the saving counts it. + The saving is 0 when the total would not fall, as for an identity whose lane + keeps its floor for its other residents. A kept identity's `blockedBy` names + the bounds its kept placement is known to miss: its receipt's warm + latencies, a measured come-alive over the bound, or a cold warmth under a + bound of `0`, which needs no measurement. - `lanes`: each lane's hourly cost, its monthly cost, its floor's monthly cost and the monthly cost of its `floorMax`, which a floor budget prices. A lane on a cell the price list cannot price carries `unpricedReason` and no cost, diff --git a/packages/sie_placement/src/sie_placement/planner.py b/packages/sie_placement/src/sie_placement/planner.py index 2ca4306bd..63c55ccb4 100644 --- a/packages/sie_placement/src/sie_placement/planner.py +++ b/packages/sie_placement/src/sie_placement/planner.py @@ -58,6 +58,12 @@ COLD_WARMTHS = (Warmth.COLD_WITH_BOUND, Warmth.SNAPSHOT_COLD) _SLUG = re.compile(r"[^a-z0-9]+") +_LEVEL_FIELDS = { + "comeAliveP95S": "come_alive_p95_s", + "warmP99Ms": "warm_p99_ms", + "ttftP99Ms": "ttft_p99_ms", + "itlP99Ms": "itl_p99_ms", +} class PlannerInputError(ValueError): @@ -371,6 +377,7 @@ def __init__( self.current = {entry.identity: (entry, lanes[entry.lane]) for entry in current_plan.identities} self.refusals: list[Refusal] = [] self.refused_profiles: set[tuple[str, str]] = set() + self.savings: dict[tuple[str, tuple[tuple[str, int], ...]], float] = {} self.receipts = self._accept_receipts(receipts) self.boots = _boot_index(self._accept_boot_evidence(boot_evidence)) @@ -546,19 +553,25 @@ def replanned_total( current, self.parameters, ) - return planner.run(price_levers=False).report.monthly_cost + return planner.run(price_savings=False).report.monthly_cost - def loosened(self, identity: str, bound: int) -> ServiceLevels: + def loosened(self, identity: str, bounds: Mapping[str, int]) -> ServiceLevels: + fields = {_LEVEL_FIELDS[name]: bound for name, bound in bounds.items()} return replace( self.service_levels, identities=tuple( - replace(entry, level=replace(entry.level, come_alive_p95_s=bound)) - if entry.identity == identity - else entry + replace(entry, level=replace(entry.level, **fields)) if entry.identity == identity else entry for entry in self.service_levels.identities ), ) + def saving_when_loosened(self, identity: str, bounds: Mapping[str, int], written: Plan, total: float) -> float: + key = (identity, tuple(sorted(bounds.items()))) + if key not in self.savings: + replanned = self.replanned_total(written, service_levels=self.loosened(identity, bounds)) + self.savings[key] = _saving(total, replanned) + return self.savings[key] + def booted_within(self, identity: str, option: _Option, bound: int) -> tuple[BootEvidence, ...]: key = (identity, option.receipt.cell, option.receipt.container_shape, option.warmth) return tuple( @@ -583,14 +596,10 @@ def levers(self, choice: _Choice, written: Plan, total: float) -> list[Lever]: known = best.get(key) if known is None or option.rank < known.rank: best[key] = option - savings: dict[int, float] = {} levers = [] for option in best.values(): - permitted = max(1, math.ceil(option.come_alive_s)) - if permitted not in savings: - replanned = self.replanned_total(written, service_levels=self.loosened(choice.identity, permitted)) - savings[permitted] = _saving(total, replanned) - saving = savings[permitted] + permitted = _permitted(option.come_alive_s) + saving = self.saving_when_loosened(choice.identity, {"comeAliveP95S": permitted}, written, total) if not saving: continue under = 0.0 @@ -616,16 +625,19 @@ def levers(self, choice: _Choice, written: Plan, total: float) -> list[Lever]: ) return levers - @staticmethod - def next_cheaper(choice: _Choice) -> _Option | None: + def next_cheaper(self, choice: _Choice, written: Plan, total: float) -> Option | None: chosen = choice.chosen if chosen is None: return None cheaper = [option for option in choice.options if not option.feasible and option.cost < chosen.cost] if not cheaper: return None - nearest = max(option.cost for option in cheaper) - return min((option for option in cheaper if option.cost == nearest), key=lambda option: option.rank) + cost = max(option.cost for option in cheaper) + nearest = min((option for option in cheaper if option.cost == cost), key=lambda option: option.rank) + bounds = { + blocker.field: _permitted(blocker.measured) for blocker in nearest.blockers if blocker.measured is not None + } + return nearest.summary(saving=self.saving_when_loosened(choice.identity, bounds, written, total)) @staticmethod def lane_names(placed: Mapping[str, _Option], reserved: set[str]) -> dict[str, str]: @@ -706,7 +718,7 @@ def demand_hours(self, lane: PlanLane, identity: str, receipt: Receipt | None) - return window.above_floor_hours(requests, rate, lane.envelope.floor_min) return window.cold_container_hours(requests, rate) - def run(self, *, price_levers: bool = True) -> PlannerResult: + def run(self, *, price_savings: bool = True) -> PlannerResult: choices = [self.choose(identity) for identity in sorted(self.levels)] placed = {choice.identity: choice.chosen for choice in choices if choice.chosen is not None} kept = { @@ -741,10 +753,14 @@ def run(self, *, price_levers: bool = True) -> PlannerResult: for choice in choices: requests.extend(self.receipt_requests(choice)) requests.extend(self.boot_requests(choice)) - if price_levers: + nearest = None + if price_savings: levers.extend(self.levers(choice, new_plan, total)) + nearest = self.next_cheaper(choice, new_plan, total) reports.append( - self._identity_report(choice, names, kept, costs.get(choice.identity), receipts.get(choice.identity)) + self._identity_report( + choice, names, kept, costs.get(choice.identity), receipts.get(choice.identity), nearest + ) ) identity_changes, lane_changes = _changes(self.current_plan, new_plan) report = Report( @@ -772,6 +788,7 @@ def _identity_report( kept: Mapping[str, tuple[PlanIdentity, PlanLane]], cost: float | None, receipt: Receipt | None, + next_cheaper: Option | None, ) -> IdentityReport: current = self.current.get(choice.identity) report = IdentityReport( @@ -795,7 +812,6 @@ def _identity_report( blocked_by=self.kept_blockers(choice.identity, entry, lane, receipt), ) return replace(report, unplaced_reason=reason) - nearest = self.next_cheaper(choice) rate = chosen.receipt.throughput.requests_per_second return replace( report, @@ -804,7 +820,7 @@ def _identity_report( monthly_cost=cost, chosen=chosen.summary(), peak_containers=max((_Window.needed(count, rate) for count in choice.requests), default=0), - next_cheaper=None if nearest is None else nearest.summary(saving=chosen.cost - nearest.cost), + next_cheaper=next_cheaper, ) def _pricing( @@ -848,6 +864,10 @@ def _saving(total: float, replanned: float) -> float: return saving if round(saving, 2) > 0 else 0.0 +def _permitted(measured: float) -> int: + return max(1, math.ceil(measured)) + + def _shared_chart_lanes(plan: Plan) -> tuple[SharedChartLane, ...]: grouped: defaultdict[tuple[str, str, str], list[str]] = defaultdict(list) for lane in plan.lanes: diff --git a/packages/sie_placement/tests/fixtures/planner/expected-report.json b/packages/sie_placement/tests/fixtures/planner/expected-report.json index e231c560c..5d4325782 100644 --- a/packages/sie_placement/tests/fixtures/planner/expected-report.json +++ b/packages/sie_placement/tests/fixtures/planner/expected-report.json @@ -69,7 +69,7 @@ "concurrency": 16, "warmth": "snapshot-cold", "monthlyCost": 569.4, - "saving": 189.8, + "saving": 0.0, "comeAliveS": 8.5, "comeAliveBasis": "boot-evidence", "blockedBy": [ diff --git a/packages/sie_placement/tests/test_planner.py b/packages/sie_placement/tests/test_planner.py index d1065bbd1..de33e77a4 100644 --- a/packages/sie_placement/tests/test_planner.py +++ b/packages/sie_placement/tests/test_planner.py @@ -254,6 +254,25 @@ def loosened(service_levels: ServiceLevels, identity: str, bound: int) -> Servic ) +LEVEL_FIELDS = { + "comeAliveP95S": "come_alive_p95_s", + "warmP99Ms": "warm_p99_ms", + "ttftP99Ms": "ttft_p99_ms", + "itlP99Ms": "itl_p99_ms", +} + + +def relaxed(service_levels: ServiceLevels, identity: str, blockers) -> ServiceLevels: + fields = {LEVEL_FIELDS[blocker.field]: max(1, math.ceil(blocker.measured)) for blocker in blockers} + return replace( + service_levels, + identities=tuple( + replace(entry, level=replace(entry.level, **fields)) if entry.identity == identity else entry + for entry in service_levels.identities + ), + ) + + def test_container_hourly_cost_prices_accelerators_cores_and_memory(): price = MachineProfilePrice( name="l4", gpu_product="NVIDIA-L4", accelerator_per_hour=2.0, core_per_hour=0.05, memory_gib_per_hour=0.01 @@ -496,6 +515,7 @@ def test_generation_cells_meet_both_the_first_token_and_the_per_token_bound(): Blocker(field="ttftP99Ms", bound=1500, measured=2000.0), Blocker(field="itlP99Ms", bound=80, measured=95.0), ) + assert report.next_cheaper.saving == pytest.approx(2 * MONTH) def test_a_receipt_whose_realized_product_differs_from_its_profile_is_refused(): @@ -627,6 +647,23 @@ def test_the_next_cheaper_option_is_the_nearest_cheaper_one_and_names_its_bound( assert report.next_cheaper.blocked_by == (Blocker(field="warmP99Ms", bound=250, measured=300.0),) +@pytest.mark.parametrize(("others", "saving"), [((), MONTH), (("org/kept",), 0.0)]) +def test_a_next_cheaper_saving_is_what_loosening_its_bounds_saves_the_plan(others, saving): + service_levels = levels(*((name, ServiceLevel(come_alive_p95_s=0)) for name in (IDENTITY, *others))) + current = single_lane_plan(others=others) + result = run(service_levels, [receipt()], [boot(seconds=30.0)], prices=L4_ONLY, current=current) + report = result.report.identity(IDENTITY) + assert (report.lane, report.chosen.warmth) == ("shared", Warmth.PINNED) + assert (report.next_cheaper.warmth, report.next_cheaper.monthly_cost) == (Warmth.COLD_WITH_BOUND, 0.0) + assert report.chosen.monthly_cost - report.next_cheaper.monthly_cost == pytest.approx(MONTH) + assert report.next_cheaper.saving == pytest.approx(saving) + again = run( + loosened(service_levels, IDENTITY, 30), [receipt()], [boot(seconds=30.0)], prices=L4_ONLY, current=result.plan + ) + assert again.report.identity(IDENTITY).chosen.warmth is Warmth.COLD_WITH_BOUND + assert result.report.monthly_cost - again.report.monthly_cost == pytest.approx(saving) + + def test_a_placement_with_nothing_cheaper_names_no_next_option(): result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY) assert result.report.identity(IDENTITY).next_cheaper is None @@ -1157,12 +1194,14 @@ def test_an_estate_lever_saves_what_planning_again_at_its_permitted_bound_saves( assert lever.saving_at_permitted_bound > 0 -def test_an_estate_identity_beside_a_kept_neighbour_offers_no_lever(): +def test_an_estate_identity_beside_a_kept_neighbour_offers_no_lever_and_no_saving(): inputs = estate() result = plan(**inputs) dense = result.report.identity("BAAI/bge-m3") assert (dense.lane, dense.chosen.warmth) == ("default-l4-default", Warmth.PINNED) assert dense.next_cheaper.come_alive_s == 8.5 + assert dense.chosen.monthly_cost > dense.next_cheaper.monthly_cost + assert dense.next_cheaper.saving == 0 assert not [lever for lever in result.report.come_alive_levers if lever.identity == "BAAI/bge-m3"] for bound in (9, 95): service_levels = loosened(inputs["service_levels"], "BAAI/bge-m3", bound) @@ -1171,6 +1210,18 @@ def test_an_estate_identity_beside_a_kept_neighbour_offers_no_lever(): assert again.report.monthly_cost > result.report.monthly_cost +def test_an_estate_next_cheaper_saving_is_what_planning_again_with_its_bounds_loosened_saves(): + inputs = estate() + result = plan(**inputs) + offered = [entry for entry in result.report.identities if entry.next_cheaper is not None] + assert [entry.identity for entry in offered] == ["BAAI/bge-m3", "Qwen/Qwen3-8B", "Qwen/Qwen3-Embedding-4B"] + for entry in offered: + service_levels = relaxed(inputs["service_levels"], entry.identity, entry.next_cheaper.blocked_by) + again = plan(**{**inputs, "service_levels": service_levels, "current_plan": result.plan}) + fall = result.report.monthly_cost - again.report.monthly_cost + assert entry.next_cheaper.saving == pytest.approx(max(0.0, fall), abs=0.01) + + @pytest.mark.parametrize("seed", range(25)) def test_random_estates_choose_only_feasible_cells_and_replan_to_themselves(seed): rng = random.Random(seed) # noqa: S311 -- reproducible test data @@ -1243,6 +1294,10 @@ def test_random_estates_choose_only_feasible_cells_and_replan_to_themselves(seed if entry.next_cheaper is not None: assert entry.next_cheaper.blocked_by assert entry.next_cheaper.monthly_cost < chosen.monthly_cost + looser = relaxed(service_levels, entry.identity, entry.next_cheaper.blocked_by) + again = run(looser, receipts, boots, prices=prices, hourly=hourly, current=result.plan, **overrides) + fall = result.report.monthly_cost - again.report.monthly_cost + assert entry.next_cheaper.saving == pytest.approx(max(0.0, fall), abs=0.01) costs = {entry.identity: entry.chosen.monthly_cost for entry in result.report.identities if entry.chosen} for lever in result.report.come_alive_levers: assert lever.monthly_cost < costs[lever.identity] From 884584bb64c20da9ad6e54dafdc004ce8120d7f9 Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Thu, 5 Nov 2026 13:23:52 +0100 Subject: [PATCH 11/16] feat(placement): keep unmeasured current placements and select lazy residents A first plan over a running deployment should change nothing it has no measured reason to change. Four selection rules make that hold: - An identity whose current placement no option matches, because its lane has no receipt at its cell, container shape and concurrency, a cold lane has no successful boot, or a lazy resident has no load, keeps that placement unless it is known to miss a bound. It leaves only for an unblocked option at least a cent cheaper than the placement, priced at the lane's fastest receipt or, without one, at its floor alone. What the placement lacks is a measurement request at its lane, with the lane's name and concurrency. An identity that stays keeps its lane as it is, envelope included, capped by the reviewed ceiling. - An identity that declares no warm bound has no bound to choose a class by: cells outside its current class are blocked by the undeclared bound, which the report lists, and an identity without a current lane is not placed. - lazy-resident is selectable on a warm lane of the current plan, on the identity's queue pool and bundle, that a never-cold identity pins, when the identity has a receipt at that lane and a load onto its cell and container shape. Its come-alive is the load and its cost the demand above the host's floor. A missing load is a measurement request on that lane. - A warmth's come-alive is the 95th percentile by nearest rank of its successful boots from 20 boots, and their slowest below that. Kept identities now report the nearest cheaper option and price their measurement requests against the current placement, and come-alive levers include lazy-resident. --- packages/sie_placement/README.md | 122 +++-- .../src/sie_placement/planner.py | 289 ++++++++-- .../sie_placement/src/sie_placement/report.py | 12 +- .../fixtures/planner/expected-report.json | 68 +-- packages/sie_placement/tests/test_planner.py | 508 +++++++++++++++++- 5 files changed, 870 insertions(+), 129 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index 8f8322222..bc24b2f6c 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -121,9 +121,11 @@ print(render(result.plan.to_dict()), render(result.report.to_dict())) `plan` is a pure function of its documents. The same inputs render to the same bytes in whatever order the receipts, boot evidence, identities and demand -series arrive. An identity whose choice is its current placement keeps its -current lane and that lane's name, so a run whose `current_plan` already holds -every choice, such as its own previous plan, reports no change. +series arrive. An identity that stays on its current placement keeps its +current lane as it is, so a run whose `current_plan` already holds every +choice, such as its own previous plan, reports no change. The one exception is +a lane that the previous run created for an identity whose `comeAliveP95S` is +`0`: it hosts lazy residents only from the run after it. | Parameter | Meaning | | --- | --- | @@ -145,27 +147,54 @@ document: that profile, and a receipt whose latency cannot answer the identity's service level. The report lists every refusal. 2. Every other receipt is a cell. A cell whose p99 misses `warmP99Ms`, or - `ttftP99Ms` or `itlP99Ms`, is blocked. + `ttftP99Ms` or `itlP99Ms`, is blocked. An identity that declares none of + them has no bound to choose a class by: every cell outside its current + class, the cell of its current lane, is blocked by the undeclared bound, and + an identity without a current lane has no unblocked cell. 3. A cell offers `pinned`, and `cold-with-bound` or `snapshot-cold` where boot - evidence for the identity, cell and container shape exists. The slowest - successful boot stands for the come-alive percentile, a boot that did not - succeed withdraws the warmth, and the environment's own evidence replaces - borrowed evidence. A `comeAliveP95S` of `0` admits `pinned` only. -4. The cheapest unblocked option wins. Ties go to the current placement, + evidence for the identity, cell and container shape exists. Below 20 + successful boots the slowest stands for the come-alive percentile; from 20, + their 95th percentile by nearest rank does, so one slow boot stops deciding + once enough boots exist. A boot that did not succeed withdraws the warmth, + and the environment's own evidence replaces borrowed evidence. A + `comeAliveP95S` of `0` admits `pinned` only. +4. A cell also offers `lazy-resident` on each host lane with its cell, + container shape and concurrency. A host lane is a lane of the current plan + with a `floorMin` of at least 1, on the parameters' queue pool and the + identity's bundle, on which another identity whose `comeAliveP95S` is `0` is + pinned. The identity's own current lane is a host only when it is a lazy + resident there, since its floor is paid either way. + The come-alive is the identity's `lazy-resident` boot evidence, its measured + load onto that cell and container shape, under the same statistic. The + option costs what the identity's demand needs above the host lane's floor. +5. The cheapest unblocked option wins. Ties go to the current placement, then to the faster come-alive. The current placement is the identity's current lane when that lane has the option's cell, container shape and concurrency, the identity's warmth is the option's, and the lane's `queuePool` and `bundle` are the ones the parameters -give the identity. An identity whose choice is its current placement stays on -that lane under its name, beside whoever else the lane hosts, and the lane -takes the ceiling and envelope of the choice. Every other placed identity gets -a new lane of its own, named from the identity and its machine profile, with a -digest of the identity added when that name is taken. The planner does not -select `lazy-resident`, `bridged` or `scheduled-warm`, and does not move an -identity onto another identity's lane. An identity with no unblocked option -keeps its current lane, capped by the reviewed ceiling, or stays out of the -plan when it has none. +give the identity; a `lazy-resident` option must also be hosted by that lane. +A current placement that no option matches lacks evidence: a receipt at its +lane's cell, container shape and concurrency, a successful boot for a cold +warmth, or a load for a lazy resident. Unless it is known to miss a bound, +through a receipt at the lane that misses a warm bound, a measured come-alive +over the bound, or a cold or `lazy-resident` warmth under a bound of `0`, the +identity keeps that placement and leaves it only for an unblocked option at +least a cent cheaper than the placement. The placement is priced as an option +of its warmth at the lane's fastest receipt, or without one at its floor alone: +one container all month for `pinned`, nothing beyond the host lane's floor for +`lazy-resident`, and the burst tails for a cold warmth. What the placement +lacks becomes a measurement request. + +An identity that stays on its current placement keeps that lane exactly as it +is, beside whoever else the lane hosts: its cell, container shape, +concurrency and envelope, capped by the reviewed ceiling. A lazy resident +joins its host lane the same way. Every other placed identity gets a new lane +of its own, named from the identity and its machine profile, with a digest of +the identity added when that name is taken. The planner does not select +`bridged` or `scheduled-warm`. An identity with no unblocked option keeps its +current lane, capped by the reviewed ceiling, or stays out of the plan when it +has none. ### Pricing @@ -191,12 +220,13 @@ cell, container shape and concurrency, under that lane's own ceiling. ### Envelope -`floorMin` is 1 for `pinned` and 0 otherwise. No source measures queue wait -yet, so `floorMax` is `floorMin` plus `buffer_containers`, capped by the -ceiling. A floor raised on a zero-floor lane realizes as at least +A new lane's `floorMin` is 1 for `pinned` and 0 otherwise. No source measures +queue wait yet, so `floorMax` is `floorMin` plus `buffer_containers`, capped by +the ceiling. A floor raised on a zero-floor lane realizes as at least `fallback_floor`, so a zero-floor lane's nonzero `floorMax` is at least `fallback_floor` capped by the ceiling. The envelope carries the floor range -only. +only. A lane carried from the current plan keeps its envelope, capped by the +ceiling. ### Report @@ -209,17 +239,24 @@ The report renders as a `placement-report` document: effective service level and demand, its lane and `monthlyCost`, what its demand costs there with the lane's floor, the chosen cell, warmth, monthly cost and come-alive with its basis (`warm-floor`, `boot-evidence` or - `borrowed-boot-evidence`), the peak containers its demand needs, and - `nextCheaper`: the nearest cheaper option a service level blocks, the bounds - that block it, and `saving`, the fall in the plan total found by planning - again from this plan with each of those bounds loosened to what the option - measured, rounded up to a whole second or millisecond and never below 1. The - loosened bounds may admit a cheaper option still, and the saving counts it. - The saving is 0 when the total would not fall, as for an identity whose lane - keeps its floor for its other residents. A kept identity's `blockedBy` names - the bounds its kept placement is known to miss: its receipt's warm - latencies, a measured come-alive over the bound, or a cold warmth under a - bound of `0`, which needs no measurement. + `borrowed-boot-evidence`) and, for a lazy resident, its host `lane`, the peak + containers its demand needs, and `nextCheaper`: the nearest option cheaper + than the choice, or than a kept identity's current placement, that a + service level blocks, the bounds that block it, and `saving`, the fall in + the plan total found by planning again from this plan with each of those + bounds loosened to what the option measured, rounded up to a whole second or + millisecond and never below 1. A bound the identity does not declare blocks + with no `bound`, and loosening it declares it. The loosened bounds may admit + a cheaper option still, and the saving counts it. The saving is 0 when the + total would not fall, as for an identity whose lane keeps its floor for its + other residents. An identity without a placement names its + `unplacedReason`: `no-receipt`, `warm-bound-missed`, + `warm-bound-undeclared` when no cell is on its current class, or + `current-unmeasured` when it keeps a current placement that lacks evidence + and no unblocked option is cheaper. A kept identity's `blockedBy` names the + bounds its kept placement is known to miss: its receipt's warm latencies, a + measured come-alive over the bound, or a cold or `lazy-resident` warmth under + a bound of `0`, which needs no measurement. - `lanes`: each lane's hourly cost, its monthly cost, its floor's monthly cost and the monthly cost of its `floorMax`, which a floor budget prices. A lane on a cell the price list cannot price carries `unpricedReason` and no cost, @@ -231,11 +268,18 @@ The report renders as a `placement-report` document: could unlock. A profile without a receipt is bounded by price alone: one accelerator at its rate, kept warm or, where the come-alive bound allows, paying burst tails only. A cell whose receipt has no successful boot asks for - boot evidence and is bounded by its cold cost. A request that cannot save is - dropped, and the requests of an identity without a placement carry no bound - and rank first. -- `comeAliveLevers`: cold warmths whose measured come-alive misses the bound - on a cell that meets the warm bounds for less than the choice, listed only + boot evidence and is bounded by its cold cost, and a host lane without the + identity's load asks for `lazy-resident` boot evidence on it, bounded by the + demand above the host's floor. Savings are measured against the choice, or + against a kept identity's current placement. A request that cannot save is + dropped, and the requests of an identity without a placement or a current + one carry no bound and rank first. The evidence a kept current placement + lacks is requested at its lane, named in `lane` with its `concurrency`, and + also ranks first without a bound; a profile it asks for there is not asked + for again. +- `comeAliveLevers`: cold and `lazy-resident` warmths whose measured + come-alive misses the bound on a cell that meets the warm bounds for less + than the choice, or than a kept identity's current placement, listed only when loosening the identity's bound to `permittedBoundS`, the bound the measured come-alive would permit, lowers the plan total. Both savings are found by planning again from this plan and taking the fall in its total: @@ -247,6 +291,8 @@ The report renders as a `placement-report` document: then by the saving at the permitted bound. - `queueWaitUnattained`: every identity that declares `queueWaitP99Ms`. No plan claims that bound as met. +- `warmBoundUndeclared`: every identity that has a cell and declares neither + `warmP99Ms` nor `ttftP99Ms` and `itlP99Ms`, so keeps its current class. - `refusals`, and `changes`: the identities and lanes that differ from `current_plan`. diff --git a/packages/sie_placement/src/sie_placement/planner.py b/packages/sie_placement/src/sie_placement/planner.py index 63c55ccb4..88ed83bcb 100644 --- a/packages/sie_placement/src/sie_placement/planner.py +++ b/packages/sie_placement/src/sie_placement/planner.py @@ -31,6 +31,7 @@ UnplacedReason, ) from sie_placement.schema import ( + BOOT_WARMTHS, WARM_FLOOR_WARMTHS, BootEvidence, BootOutcome, @@ -55,6 +56,8 @@ SECONDS_PER_HOUR = 3600 HOURS_PER_MONTH = 730.0 PINNED_FLOOR = 1 +BOOT_PERCENTILE = 95 +BOOT_PERCENTILE_MIN_ROWS = 20 COLD_WARMTHS = (Warmth.COLD_WITH_BOUND, Warmth.SNAPSHOT_COLD) _SLUG = re.compile(r"[^a-z0-9]+") @@ -209,14 +212,15 @@ class _Option: basis: ComeAliveBasis blockers: tuple[Blocker, ...] current: bool + host: str | None = None @property def feasible(self) -> bool: return not self.blockers @property - def rank(self) -> tuple[float, bool, float, str, str]: - return (self.cost, not self.current, self.come_alive_s, self.order, self.warmth.value) + def rank(self) -> tuple[float, bool, float, str, str, str]: + return (self.cost, not self.current, self.come_alive_s, self.order, self.warmth.value, self.host or "") def summary(self, saving: float | None = None) -> Option: return Option( @@ -230,6 +234,7 @@ def summary(self, saving: float | None = None) -> Option: receipt=self.receipt.source, blocked_by=self.blockers, saving=saving, + lane=self.host, ) @@ -242,6 +247,22 @@ class _Choice: chosen: _Option | None boot_requests: tuple[MeasurementRequest, ...] has_valid_receipt: bool + held: float | None = None + gaps: tuple[MeasurementRequest, ...] = () + + @property + def baseline(self) -> float | None: + return self.held if self.chosen is None else self.chosen.cost + + @property + def unplaced_reason(self) -> UnplacedReason: + if any(option.feasible for option in self.options): + return UnplacedReason.CURRENT_UNMEASURED + if not self.has_valid_receipt: + return UnplacedReason.NO_RECEIPT + if not _declares_warm_bound(self.level): + return UnplacedReason.WARM_BOUND_UNDECLARED + return UnplacedReason.WARM_BOUND_MISSED def _canonical(document: Mapping[str, object]) -> str: @@ -292,6 +313,19 @@ def _warm_blockers(level: ServiceLevel, receipt: Receipt) -> tuple[Blocker, ...] ) +def _declares_warm_bound(level: ServiceLevel) -> bool: + return level.warm_p99_ms is not None or level.is_generation + + +def _undeclared_blockers(level: ServiceLevel, receipt: Receipt) -> tuple[Blocker, ...]: + if _declares_warm_bound(level): + return () + measured = (("warmP99Ms", receipt.latency), ("ttftP99Ms", receipt.ttft), ("itlP99Ms", receipt.itl)) + return tuple( + Blocker(field=name, bound=None, measured=values.p99_ms) for name, values in measured if values is not None + ) + + def _come_alive_blocker(level: ServiceLevel, seconds: float) -> Blocker | None: bound = level.come_alive_p95_s if bound is None or (bound > 0 and seconds <= bound): @@ -299,6 +333,13 @@ def _come_alive_blocker(level: ServiceLevel, seconds: float) -> Blocker | None: return Blocker(field="comeAliveP95S", bound=bound, measured=seconds) +def _come_alive(seconds: Iterable[float]) -> float: + ordered = sorted(float(value) for value in seconds) + if len(ordered) < BOOT_PERCENTILE_MIN_ROWS: + return ordered[-1] + return ordered[(len(ordered) * BOOT_PERCENTILE + 99) // 100 - 1] + + def _boot_index(records: Iterable[BootEvidence]) -> dict[_BootKey, _Boot]: grouped: defaultdict[_BootKey, list[BootEvidence]] = defaultdict(list) for record in records: @@ -310,7 +351,7 @@ def _boot_index(records: Iterable[BootEvidence]) -> dict[_BootKey, _Boot]: if any(record.outcome is not BootOutcome.SUCCEEDED for record in used): index[key] = _Boot(seconds=None, borrowed=not own) else: - index[key] = _Boot(seconds=float(max(record.boot_seconds for record in used)), borrowed=not own) + index[key] = _Boot(seconds=_come_alive(record.boot_seconds for record in used), borrowed=not own) return index @@ -372,9 +413,15 @@ def __init__( self.requests = _hourly_requests(demand) self.current_plan = current_plan self.current: dict[str, tuple[PlanIdentity, PlanLane]] = {} + self.current_lanes: dict[str, PlanLane] = {} + self.residents: defaultdict[str, list[PlanIdentity]] = defaultdict(list) if current_plan is not None: - lanes = {lane.name: lane for lane in current_plan.lanes} - self.current = {entry.identity: (entry, lanes[entry.lane]) for entry in current_plan.identities} + self.current_lanes = {lane.name: lane for lane in current_plan.lanes} + self.current = { + entry.identity: (entry, self.current_lanes[entry.lane]) for entry in current_plan.identities + } + for entry in current_plan.identities: + self.residents[entry.lane].append(entry) self.refusals: list[Refusal] = [] self.refused_profiles: set[tuple[str, str]] = set() self.savings: dict[tuple[str, tuple[tuple[str, int], ...]], float] = {} @@ -422,18 +469,118 @@ def is_current(self, identity: str, receipt: Receipt, warmth: Warmth) -> bool: and _runs_on(receipt, lane) ) + def current_class(self, identity: str) -> Cell | None: + current = self.current.get(identity) + return None if current is None else current[1].cell + + def keepable(self, identity: str) -> tuple[PlanIdentity, PlanLane] | None: + current = self.current.get(identity) + if current is None: + return None + lane = current[1] + if lane.queue_pool != self.parameters.queue_pool or lane.bundle != self.parameters.bundle_of(identity): + return None + return current + + def anchors(self, entry: PlanIdentity) -> bool: + level = self.levels.get(entry.identity) + return entry.warmth is Warmth.PINNED and level is not None and level.come_alive_p95_s == 0 + + def lazy_hosts(self, identity: str) -> tuple[PlanLane, ...]: + current = self.current.get(identity) + home = None if current is None else current[1].name + lazy = current is not None and current[0].warmth is Warmth.LAZY_RESIDENT + bundle = self.parameters.bundle_of(identity) + return tuple( + lane + for name, lane in sorted(self.current_lanes.items()) + if lane.envelope.floor_min >= PINNED_FLOOR + and lane.queue_pool == self.parameters.queue_pool + and lane.bundle == bundle + and ( + lazy + if name == home + else any(self.anchors(entry) for entry in self.residents[name] if entry.identity != identity) + ) + ) + + def resident_hours(self, lane: PlanLane, requests: Sequence[int], rate: float) -> float: + capped = self.within_ceiling(lane) + window = replace(self.window, ceiling=capped.max_containers) + return window.above_floor_hours(requests, rate, capped.envelope.floor_min) + + def current_cost(self, identity: str, entry: PlanIdentity, lane: PlanLane) -> float | None: + if _refusal_reason(lane.cell, self.prices) is not None: + return None + hourly = container_hourly_cost(self.prices[lane.cell.machine_profile], lane.container_shape, self.multiplier) + requests = self.requests.get(identity, ()) + rate = max( + ( + receipt.throughput.requests_per_second + for _, receipt in self.receipts.get(identity, []) + if _runs_on(receipt, lane) + ), + default=None, + ) + if entry.warmth is Warmth.PINNED: + hours = ( + PINNED_FLOOR * self.parameters.hours_per_month + if rate is None + else self.window.warm_container_hours(requests, rate) + ) + elif entry.warmth is Warmth.LAZY_RESIDENT: + hours = 0.0 if rate is None else self.resident_hours(lane, requests, rate) + else: + hours = self.window.cold_container_hours(requests, rate) + return hourly * hours + + def current_gaps( + self, identity: str, entry: PlanIdentity, lane: PlanLane, cost: float | None + ) -> tuple[MeasurementRequest, ...]: + if cost is None: + return () + missing: list[tuple[Measurement, RequestReason]] = [] + if self.slowest_receipt(identity, lane) is None: + refused = (identity, lane.cell.machine_profile) in self.refused_profiles + missing.append((Measurement.RECEIPT, RequestReason.REFUSED if refused else RequestReason.UNMEASURED)) + if entry.warmth in BOOT_WARMTHS: + boot = self.boots.get((identity, lane.cell, lane.container_shape, entry.warmth)) + if boot is None or boot.seconds is None: + reason = RequestReason.UNMEASURED if boot is None else RequestReason.FAILED + missing.append((Measurement.BOOT_EVIDENCE, reason)) + return tuple( + MeasurementRequest( + identity=identity, + cell=lane.cell, + container_shape=lane.container_shape, + concurrency=lane.concurrency, + lane=lane.name, + measure=(measurement,), + warmth=entry.warmth, + reason=reason, + cost_bound=cost, + saving_bound=None, + ) + for measurement, reason in missing + ) + def choose(self, identity: str) -> _Choice: level = self.levels[identity] requests = self.requests.get(identity, ()) options: list[_Option] = [] boot_requests: dict[tuple[Cell, ContainerShape], MeasurementRequest] = {} + load_requests: dict[str, MeasurementRequest] = {} receipts = self.receipts.get(identity, []) + current_class = self.current_class(identity) + hosts = self.lazy_hosts(identity) for order, receipt in receipts: hourly = container_hourly_cost( self.prices[receipt.cell.machine_profile], receipt.container_shape, self.multiplier ) rate = receipt.throughput.requests_per_second warm = _warm_blockers(level, receipt) + if receipt.cell != current_class: + warm = (*warm, *_undeclared_blockers(level, receipt)) options.append( _Option( receipt=receipt, @@ -478,20 +625,82 @@ def choose(self, identity: str) -> _Choice: current=self.is_current(identity, receipt, warmth), ) ) + for host in hosts: + if not _runs_on(receipt, host): + continue + lazy_cost = hourly * self.resident_hours(host, requests, rate) + load = self.boots.get((identity, host.cell, host.container_shape, Warmth.LAZY_RESIDENT)) + if load is None or load.seconds is None: + known = load_requests.get(host.name) + if not warm and level.come_alive_p95_s != 0 and (known is None or lazy_cost < known.cost_bound): + load_requests[host.name] = MeasurementRequest( + identity=identity, + cell=host.cell, + container_shape=host.container_shape, + concurrency=host.concurrency, + lane=host.name, + measure=(Measurement.BOOT_EVIDENCE,), + warmth=Warmth.LAZY_RESIDENT, + reason=RequestReason.UNMEASURED if load is None else RequestReason.FAILED, + cost_bound=lazy_cost, + saving_bound=None, + ) + continue + blocker = _come_alive_blocker(level, load.seconds) + options.append( + _Option( + receipt=receipt, + order=order, + warmth=Warmth.LAZY_RESIDENT, + cost=lazy_cost, + come_alive_s=load.seconds, + basis=load.basis, + blockers=warm if blocker is None else (*warm, blocker), + current=self.is_current(identity, receipt, Warmth.LAZY_RESIDENT) + and self.current[identity][1].name == host.name, + host=host.name, + ) + ) feasible = [option for option in options if option.feasible] chosen = min(feasible, key=lambda option: option.rank) if feasible else None + held = None + gaps: tuple[MeasurementRequest, ...] = () + current = self.keepable(identity) + if current is not None and not any(option.current for option in options): + entry, lane = current + if not self.kept_blockers(identity, entry, lane, self.slowest_receipt(identity, lane)): + cost = self.current_cost(identity, entry, lane) + cheaper = [option for option in feasible if cost is not None and round(cost - option.cost, 2) > 0] + chosen = min(cheaper, key=lambda option: option.rank) if cheaper else None + if chosen is None: + held = cost + gaps = self.current_gaps(identity, entry, lane, cost) + gapped = { + (request.cell, request.container_shape, request.warmth) + for request in gaps + if Measurement.BOOT_EVIDENCE in request.measure + } return _Choice( identity=identity, level=level, requests=requests, options=tuple(options), chosen=chosen, - boot_requests=tuple(boot_requests.values()), + boot_requests=tuple( + request + for request in (*boot_requests.values(), *load_requests.values()) + if (request.cell, request.container_shape, request.warmth) not in gapped + ), has_valid_receipt=bool(receipts), + held=held, + gaps=gaps, ) - def receipt_requests(self, choice: _Choice) -> list[MeasurementRequest]: + def receipt_requests(self, choice: _Choice, baseline: float | None) -> list[MeasurementRequest]: measured = {receipt.cell.machine_profile for _, receipt in self.receipts.get(choice.identity, [])} + measured.update( + request.cell.machine_profile for request in choice.gaps if Measurement.RECEIPT in request.measure + ) bound = choice.level.come_alive_p95_s requests = [] for profile in sorted(self.price_list.machine_profiles, key=lambda price: price.name): @@ -503,7 +712,7 @@ def receipt_requests(self, choice: _Choice) -> list[MeasurementRequest]: cold = accelerator * self.window.cold_container_hours(choice.requests, None) candidates.append((cold, Warmth.COLD_WITH_BOUND)) cost, warmth = min(candidates, key=lambda candidate: (candidate[0], candidate[1] is not Warmth.PINNED)) - saving = None if choice.chosen is None else choice.chosen.cost - cost + saving = None if baseline is None else baseline - cost if saving is not None and saving <= 0: continue requests.append( @@ -527,14 +736,14 @@ def receipt_requests(self, choice: _Choice) -> list[MeasurementRequest]: ) return requests - def boot_requests(self, choice: _Choice) -> list[MeasurementRequest]: - if choice.chosen is None: + @staticmethod + def boot_requests(choice: _Choice, baseline: float | None) -> list[MeasurementRequest]: + if baseline is None: return [] - chosen = choice.chosen return [ - replace(request, saving_bound=chosen.cost - request.cost_bound) + replace(request, saving_bound=baseline - request.cost_bound) for request in choice.boot_requests - if chosen.cost - request.cost_bound > 0 + if baseline - request.cost_bound > 0 ] def replanned_total( @@ -582,13 +791,13 @@ def booted_within(self, identity: str, option: _Option, bound: int) -> tuple[Boo ) def levers(self, choice: _Choice, written: Plan, total: float) -> list[Lever]: - chosen = choice.chosen + baseline = choice.baseline bound = choice.level.come_alive_p95_s - if chosen is None or bound is None: + if baseline is None or bound is None: return [] best: dict[tuple[Cell, ContainerShape, Warmth], _Option] = {} for option in choice.options: - if option.warmth not in COLD_WARMTHS or option.cost >= chosen.cost: + if option.warmth is Warmth.PINNED or option.cost >= baseline: continue if [blocker.field for blocker in option.blockers] != ["comeAliveP95S"]: continue @@ -625,11 +834,10 @@ def levers(self, choice: _Choice, written: Plan, total: float) -> list[Lever]: ) return levers - def next_cheaper(self, choice: _Choice, written: Plan, total: float) -> Option | None: - chosen = choice.chosen - if chosen is None: + def next_cheaper(self, choice: _Choice, baseline: float | None, written: Plan, total: float) -> Option | None: + if baseline is None: return None - cheaper = [option for option in choice.options if not option.feasible and option.cost < chosen.cost] + cheaper = [option for option in choice.options if not option.feasible and option.cost < baseline] if not cheaper: return None cost = max(option.cost for option in cheaper) @@ -693,7 +901,7 @@ def kept_blockers( ) -> tuple[Blocker, ...]: level = self.levels[identity] blockers = [] if receipt is None else list(_warm_blockers(level, receipt)) - if entry.warmth in COLD_WARMTHS and level.come_alive_p95_s is not None: + if entry.warmth in BOOT_WARMTHS and level.come_alive_p95_s is not None: boot = self.boots.get((identity, lane.cell, lane.container_shape, entry.warmth)) if boot is not None and boot.seconds is not None: blocker = _come_alive_blocker(level, boot.seconds) @@ -727,11 +935,22 @@ def run(self, *, price_savings: bool = True) -> PlannerResult: if choice.chosen is None and choice.identity in self.current } staying = {identity: self.current[identity][1].name for identity, option in placed.items() if option.current} - reserved = {lane.name for _, lane in kept.values()} | set(staying.values()) - moving = {identity: option for identity, option in placed.items() if identity not in staying} - names = staying | self.lane_names(moving, reserved) - lanes = {lane.name: self.within_ceiling(lane) for _, lane in kept.values()} - for identity, option in placed.items(): + joining = { + identity: host + for identity, option in placed.items() + if (host := option.host) is not None and identity not in staying + } + reserved = {lane.name for _, lane in kept.values()} | set(staying.values()) | set(joining.values()) + moving = { + identity: option + for identity, option in placed.items() + if identity not in staying and identity not in joining + } + names = staying | joining | self.lane_names(moving, reserved) + carried = [lane for _, lane in kept.values()] + carried.extend(self.current_lanes[name] for name in (*staying.values(), *joining.values())) + lanes = {lane.name: self.within_ceiling(lane) for lane in carried} + for identity, option in moving.items(): lanes[names[identity]] = self.placed_lane(names[identity], identity, option) identities = [entry for entry, _ in kept.values()] identities.extend( @@ -751,12 +970,14 @@ def run(self, *, price_savings: bool = True) -> PlannerResult: requests: list[MeasurementRequest] = [] levers: list[Lever] = [] for choice in choices: - requests.extend(self.receipt_requests(choice)) - requests.extend(self.boot_requests(choice)) + baseline = choice.baseline + requests.extend(choice.gaps) + requests.extend(self.receipt_requests(choice, baseline)) + requests.extend(self.boot_requests(choice, baseline)) nearest = None if price_savings: levers.extend(self.levers(choice, new_plan, total)) - nearest = self.next_cheaper(choice, new_plan, total) + nearest = self.next_cheaper(choice, baseline, new_plan, total) reports.append( self._identity_report( choice, names, kept, costs.get(choice.identity), receipts.get(choice.identity), nearest @@ -778,6 +999,11 @@ def run(self, *, price_savings: bool = True) -> PlannerResult: refusals=tuple(sorted(self.refusals, key=_refusal_rank)), identity_changes=identity_changes, lane_changes=lane_changes, + warm_bound_undeclared=tuple( + identity + for identity in sorted(self.levels) + if not _declares_warm_bound(self.levels[identity]) and self.receipts.get(identity) + ), ) return PlannerResult(plan=new_plan, report=report) @@ -800,7 +1026,7 @@ def _identity_report( ) chosen = choice.chosen if chosen is None: - reason = UnplacedReason.WARM_BOUND_MISSED if choice.has_valid_receipt else UnplacedReason.NO_RECEIPT + reason = choice.unplaced_reason if choice.identity in kept: entry, lane = kept[choice.identity] return replace( @@ -810,6 +1036,7 @@ def _identity_report( monthly_cost=cost, unplaced_reason=reason, blocked_by=self.kept_blockers(choice.identity, entry, lane, receipt), + next_cheaper=next_cheaper, ) return replace(report, unplaced_reason=reason) rate = chosen.receipt.throughput.requests_per_second @@ -910,6 +1137,8 @@ def _request_rank(request: MeasurementRequest) -> tuple[object, ...]: request.cell.gpu_product, _shape_key(request.container_shape), tuple(measurement.value for measurement in request.measure), + request.lane or "", + request.concurrency or 0, ) diff --git a/packages/sie_placement/src/sie_placement/report.py b/packages/sie_placement/src/sie_placement/report.py index f285f71bc..42eea8e31 100644 --- a/packages/sie_placement/src/sie_placement/report.py +++ b/packages/sie_placement/src/sie_placement/report.py @@ -30,6 +30,8 @@ class IdentityStatus(StrEnum): class UnplacedReason(StrEnum): NO_RECEIPT = "no-receipt" WARM_BOUND_MISSED = "warm-bound-missed" + WARM_BOUND_UNDECLARED = "warm-bound-undeclared" + CURRENT_UNMEASURED = "current-unmeasured" class ComeAliveBasis(StrEnum): @@ -69,7 +71,7 @@ def _compact(fields: dict[str, object | None]) -> dict[str, object]: @dataclass(frozen=True, slots=True, kw_only=True) class Blocker: field: str - bound: int + bound: int | None measured: float | None def to_dict(self) -> dict[str, object]: @@ -88,6 +90,7 @@ class Option: receipt: SourceRef blocked_by: tuple[Blocker, ...] = () saving: float | None = None + lane: str | None = None def to_dict(self) -> dict[str, object]: return _compact( @@ -95,6 +98,7 @@ def to_dict(self) -> dict[str, object]: "cell": self.cell.to_dict(), "containerShape": self.container_shape.to_dict(), "concurrency": self.concurrency, + "lane": self.lane, "warmth": self.warmth.value, "monthlyCost": _money(self.monthly_cost), "saving": None if self.saving is None else _money(self.saving), @@ -198,6 +202,8 @@ class MeasurementRequest: cost_bound: float saving_bound: float | None container_shape: ContainerShape | None = None + concurrency: int | None = None + lane: str | None = None def to_dict(self) -> dict[str, object]: return _compact( @@ -205,6 +211,8 @@ def to_dict(self) -> dict[str, object]: "identity": self.identity, "cell": self.cell.to_dict(), "containerShape": None if self.container_shape is None else self.container_shape.to_dict(), + "concurrency": self.concurrency, + "lane": self.lane, "measure": [measurement.value for measurement in self.measure], "warmth": self.warmth.value, "reason": self.reason.value, @@ -308,6 +316,7 @@ class Report: refusals: tuple[Refusal, ...] identity_changes: tuple[IdentityChange, ...] lane_changes: tuple[LaneChange, ...] + warm_bound_undeclared: tuple[str, ...] = () @property def monthly_cost(self) -> float: @@ -349,6 +358,7 @@ def to_dict(self) -> dict[str, object]: "measurementRequests": [request.to_dict() for request in self.measurement_requests], "comeAliveLevers": [lever.to_dict() for lever in self.come_alive_levers], "queueWaitUnattained": list(self.queue_wait_unattained), + "warmBoundUndeclared": list(self.warm_bound_undeclared), "refusals": [refusal.to_dict() for refusal in self.refusals], "changes": { "identities": [change.to_dict() for change in self.identity_changes], diff --git a/packages/sie_placement/tests/fixtures/planner/expected-report.json b/packages/sie_placement/tests/fixtures/planner/expected-report.json index 5d4325782..076b55a12 100644 --- a/packages/sie_placement/tests/fixtures/planner/expected-report.json +++ b/packages/sie_placement/tests/fixtures/planner/expected-report.json @@ -392,57 +392,25 @@ "reason": "unmeasured", "costBound": 0.0 }, - { - "identity": "intfloat/e5-base-v2", - "cell": { - "machineProfile": "a100-80gb", - "gpuProduct": "NVIDIA-A100-SXM4-80GB" - }, - "measure": [ - "receipt" - ], - "warmth": "pinned", - "reason": "unmeasured", - "costBound": 1825.0 - }, - { - "identity": "intfloat/e5-base-v2", - "cell": { - "machineProfile": "h100", - "gpuProduct": "NVIDIA-H100-80GB-HBM3" - }, - "measure": [ - "receipt" - ], - "warmth": "pinned", - "reason": "unmeasured", - "costBound": 2920.0 - }, { "identity": "intfloat/e5-base-v2", "cell": { "machineProfile": "l4", "gpuProduct": "NVIDIA-L4" }, - "measure": [ - "receipt" - ], - "warmth": "pinned", - "reason": "unmeasured", - "costBound": 584.0 - }, - { - "identity": "intfloat/e5-base-v2", - "cell": { - "machineProfile": "l40s", - "gpuProduct": "NVIDIA-L40S" + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 }, + "concurrency": 16, + "lane": "default-l4-default", "measure": [ "receipt" ], "warmth": "pinned", "reason": "unmeasured", - "costBound": 876.0 + "costBound": 759.2 }, { "identity": "Qwen/Qwen3-Embedding-4B", @@ -492,6 +460,27 @@ "reason": "unmeasured", "costBound": 146.0, "savingBound": 236.03 + }, + { + "identity": "BAAI/bge-m3:sparse", + "cell": { + "machineProfile": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "lane": "default-l4-default", + "measure": [ + "boot-evidence" + ], + "warmth": "lazy-resident", + "reason": "unmeasured", + "costBound": 0.0, + "savingBound": 47.45 } ], "comeAliveLevers": [ @@ -541,6 +530,7 @@ "BAAI/bge-m3:sparse", "intfloat/e5-base-v2" ], + "warmBoundUndeclared": [], "refusals": [ { "record": "boot-evidence", diff --git a/packages/sie_placement/tests/test_planner.py b/packages/sie_placement/tests/test_planner.py index de33e77a4..463ad80a8 100644 --- a/packages/sie_placement/tests/test_planner.py +++ b/packages/sie_placement/tests/test_planner.py @@ -66,6 +66,8 @@ SHAPE = ContainerShape(gpu_count=1, cpu_cores=4, memory_mib=16384) WIDE = ContainerShape(gpu_count=1, cpu_cores=8, memory_mib=32768) IDENTITY = "org/model" +ANY_P99_MS = 1000 +WARM = ServiceLevel(warm_p99_ms=ANY_P99_MS) ESTATE_PARAMETERS = PlannerParameters( placement="us-central1", @@ -154,6 +156,8 @@ def levels(*entries: tuple[str, ServiceLevel]) -> ServiceLevels: def level(**fields) -> ServiceLevels: + if not fields.keys() & {"warm_p99_ms", "ttft_p99_ms", "itl_p99_ms"}: + fields["warm_p99_ms"] = ANY_P99_MS return levels((IDENTITY, ServiceLevel(**fields))) @@ -224,6 +228,51 @@ def single_lane_plan( ) +ANCHOR = "org/anchor" + + +def plan_lane(name, *, cell=L4, floor=1, bundle="default", queue_pool="default") -> PlanLane: + return PlanLane( + name=name, + queue_pool=queue_pool, + bundle=bundle, + cell=cell, + container_shape=SHAPE, + concurrency=8, + max_containers=4, + envelope=Envelope(floor_min=floor, floor_max=max(floor, 1)), + ) + + +def plan_of(lanes, residents) -> Plan: + return Plan( + placement="test", + lanes=tuple(lanes), + identities=tuple( + PlanIdentity(identity=identity, lane=name, warmth=warmth) + for identity, (name, warmth) in sorted(residents.items()) + ), + ) + + +def resident_levels(bound=60, anchor_bound=0) -> ServiceLevels: + return levels( + (ANCHOR, ServiceLevel(come_alive_p95_s=anchor_bound, warm_p99_ms=ANY_P99_MS)), + (IDENTITY, ServiceLevel(come_alive_p95_s=bound, warm_p99_ms=ANY_P99_MS)), + ) + + +def resident_estate() -> Plan: + return plan_of( + [plan_lane("own"), plan_lane("shared")], + {ANCHOR: ("shared", Warmth.PINNED), IDENTITY: ("own", Warmth.PINNED)}, + ) + + +RESIDENT_RECEIPTS = [receipt(identity=ANCHOR), receipt()] +LOADS = [boot(warmth=Warmth.LAZY_RESIDENT, seconds=20.0, uri="loads/example.json")] + + def load(name: str): return json.loads((FIXTURES / name).read_text(encoding="utf-8")) @@ -431,7 +480,7 @@ def test_a_failed_boot_disqualifies_the_successful_ones_beside_it(): assert result.report.identity(IDENTITY).chosen.warmth is Warmth.PINNED -def test_the_slowest_successful_boot_stands_for_the_percentile(): +def test_fewer_than_twenty_boots_stand_for_the_come_alive_at_their_slowest(): boots = [boot(seconds=80.0, uri="boots/1.json"), boot(seconds=130.0, uri="boots/2.json")] result = run(level(come_alive_p95_s=120), [receipt()], boots, prices=L4_ONLY) report = result.report.identity(IDENTITY) @@ -439,6 +488,30 @@ def test_the_slowest_successful_boot_stands_for_the_percentile(): assert report.next_cheaper.blocked_by == (Blocker(field="comeAliveP95S", bound=120, measured=130.0),) +@pytest.mark.parametrize( + ("seconds", "come_alive"), + [ + ([50.0] * 18 + [130.0], 130.0), + ([50.0] * 19 + [130.0], 50.0), + ([50.0] * 37 + [130.0] * 3, 130.0), + ([50.0] * 38 + [130.0] * 2, 50.0), + ], +) +def test_twenty_or_more_boots_stand_for_the_come_alive_at_their_95th_percentile(seconds, come_alive): + boots = [boot(seconds=value, uri=f"boots/{index}.json") for index, value in enumerate(seconds)] + result = run(level(come_alive_p95_s=600), [receipt()], boots, prices=L4_ONLY) + chosen = result.report.identity(IDENTITY).chosen + assert (chosen.warmth, chosen.come_alive_s) == (Warmth.COLD_WITH_BOUND, come_alive) + assert rendered(run(level(come_alive_p95_s=600), [receipt()], boots[::-1], prices=L4_ONLY)) == rendered(result) + + +def test_a_failed_boot_withdraws_the_warmth_however_many_boots_succeeded(): + boots = [boot(seconds=50.0, uri=f"boots/{index}.json") for index in range(30)] + boots.append(boot(seconds=0.0, outcome=BootOutcome.FAILED, uri="boots/failed.json")) + result = run(level(come_alive_p95_s=600), [receipt()], boots, prices=L4_ONLY) + assert result.report.identity(IDENTITY).chosen.warmth is Warmth.PINNED + + def test_boot_seconds_render_the_same_whatever_their_number_type(): boots = [boot(seconds=60, uri="boots/1.json"), boot(seconds=60.0, uri="boots/2.json")] first = run(level(come_alive_p95_s=120), [receipt()], boots, prices=L4_ONLY) @@ -617,8 +690,8 @@ def test_a_cell_that_cannot_save_is_not_requested(): def test_measurement_requests_rank_unplaced_identities_first_then_by_saving(): service_levels = levels( - ("org/big", ServiceLevel(come_alive_p95_s=0)), - ("org/small", ServiceLevel(come_alive_p95_s=120)), + ("org/big", ServiceLevel(come_alive_p95_s=0, warm_p99_ms=ANY_P99_MS)), + ("org/small", ServiceLevel(come_alive_p95_s=120, warm_p99_ms=ANY_P99_MS)), ("org/unplaced", ServiceLevel(come_alive_p95_s=0)), ) receipts = [receipt(identity="org/big", cell=A100), receipt(identity="org/small", cell=L4)] @@ -847,12 +920,12 @@ def test_an_identity_without_a_feasible_cell_or_a_current_lane_is_left_out(): def test_lane_names_derive_from_the_identity_and_its_machine_profile(): - result = run(levels(("BAAI/bge-m3:sparse", ServiceLevel())), [receipt(identity="BAAI/bge-m3:sparse")]) + result = run(levels(("BAAI/bge-m3:sparse", WARM)), [receipt(identity="BAAI/bge-m3:sparse")]) assert result.plan.lanes[0].name == "baai-bge-m3-sparse-l4" def test_colliding_lane_names_take_an_identity_digest(): - service_levels = levels(("org/model", ServiceLevel()), ("org-model", ServiceLevel())) + service_levels = levels(("org/model", WARM), ("org-model", WARM)) receipts = [receipt(identity="org/model"), receipt(identity="org-model")] result = run(service_levels, receipts, prices=L4_ONLY) names = {entry.identity: entry.lane for entry in result.plan.identities} @@ -864,7 +937,7 @@ def test_colliding_lane_names_take_an_identity_digest(): def test_a_derived_lane_name_never_takes_a_kept_lane_name(): current = single_lane_plan(name="org-model-l4", identity="org/kept") - service_levels = levels(("org/kept", ServiceLevel(come_alive_p95_s=0)), (IDENTITY, ServiceLevel())) + service_levels = levels(("org/kept", ServiceLevel(come_alive_p95_s=0)), (IDENTITY, WARM)) result = run(service_levels, [receipt()], prices=L4_ONLY, current=current) names = {entry.identity: entry.lane for entry in result.plan.identities} assert names["org/kept"] == "org-model-l4" @@ -879,31 +952,263 @@ def test_a_current_placement_keeps_its_lane_name(): assert result.report.unchanged -def test_a_current_placement_that_differs_only_in_its_envelope_keeps_its_lane_name(): +def test_a_current_placement_keeps_its_lane_as_it_is_under_the_reviewed_ceiling(): current = single_lane_plan(name="legacy", max_containers=8, envelope=Envelope(floor_min=2, floor_max=5)) - result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY, current=current) + result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY, current=current, buffer_containers=2) (lane,) = result.plan.lanes - assert (lane.name, lane.max_containers, lane.envelope) == ("legacy", 4, Envelope(floor_min=1, floor_max=1)) + assert (lane.name, lane.max_containers, lane.envelope) == ("legacy", 4, Envelope(floor_min=2, floor_max=4)) + assert (lane.cell, lane.container_shape, lane.concurrency) == (L4, SHAPE, 8) + assert result.report.identity(IDENTITY).status is IdentityStatus.PLACED assert result.report.identity_changes == () assert [change.name for change in result.report.lane_changes] == ["legacy"] + within = single_lane_plan(name="legacy", max_containers=4, envelope=Envelope(floor_min=1, floor_max=3)) + assert run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY, current=within).plan == within -def test_a_current_lane_that_differs_in_concurrency_is_not_the_current_placement(): +def test_a_receipt_at_the_current_concurrency_keeps_the_current_lane(): current = single_lane_plan(name="legacy", max_containers=4) receipts = [receipt(concurrency=16), receipt(concurrency=8)] result = run(level(come_alive_p95_s=0), receipts, prices=L4_ONLY, current=current) (lane,) = result.plan.lanes assert (lane.name, lane.concurrency) == ("legacy", 8) assert result.report.unchanged - moved = run(level(come_alive_p95_s=0), [receipts[0]], prices=L4_ONLY, current=current) - (lane,) = moved.plan.lanes - assert (lane.name, lane.concurrency) == ("org-model-l4", 16) - assert [(change.name, change.before is None) for change in moved.report.lane_changes] == [ - ("legacy", False), - ("org-model-l4", True), + + +def test_a_current_lane_without_a_receipt_at_its_concurrency_is_kept_and_asks_for_one(): + current = single_lane_plan(name="legacy", max_containers=4) + result = run(level(come_alive_p95_s=0), [receipt(concurrency=16)], prices=L4_ONLY, current=current) + assert result.plan == current + assert result.report.unchanged + report = result.report.identity(IDENTITY) + assert (report.status, report.unplaced_reason) == (IdentityStatus.KEPT, UnplacedReason.CURRENT_UNMEASURED) + (request,) = result.report.measurement_requests + assert (request.cell, request.container_shape, request.concurrency, request.lane) == (L4, SHAPE, 8, "legacy") + assert (request.measure, request.warmth, request.reason) == ( + (Measurement.RECEIPT,), + Warmth.PINNED, + RequestReason.UNMEASURED, + ) + assert (request.cost_bound, request.saving_bound) == (pytest.approx(MONTH), None) + assert request.to_dict()["lane"] == "legacy" + assert request.to_dict()["concurrency"] == 8 + + +def test_a_cold_lane_without_boot_evidence_is_kept_and_asks_for_it(): + current = single_lane_plan(name="cold", warmth=Warmth.COLD_WITH_BOUND) + result = run(level(come_alive_p95_s=120), [receipt()], prices=L4_ONLY, hourly={IDENTITY: {0: 1}}, current=current) + assert result.plan == current + report = result.report.identity(IDENTITY) + assert (report.status, report.unplaced_reason) == (IdentityStatus.KEPT, UnplacedReason.CURRENT_UNMEASURED) + (request,) = result.report.measurement_requests + assert (request.measure, request.warmth, request.lane, request.concurrency, request.reason) == ( + (Measurement.BOOT_EVIDENCE,), + Warmth.COLD_WITH_BOUND, + "cold", + 8, + RequestReason.UNMEASURED, + ) + assert request.cost_bound == pytest.approx((1 / 10.0 + 1 * 2 * 900) / 3600 * SCALE) + + +def test_an_unmeasured_current_lane_moves_to_a_measured_option_that_is_cheaper(): + current = single_lane_plan(name="cold", warmth=Warmth.COLD_WITH_BOUND, cell=A100) + result = run( + level(come_alive_p95_s=120), + [receipt(cell=A100), receipt()], + [boot()], + hourly={IDENTITY: {0: 1}}, + current=current, + ) + report = result.report.identity(IDENTITY) + assert (report.status, report.chosen.cell, report.chosen.warmth) == ( + IdentityStatus.PLACED, + L4, + Warmth.COLD_WITH_BOUND, + ) + assert [entry.lane for entry in result.plan.identities] == ["org-model-l4"] + + +def test_a_cold_current_lane_under_a_zero_bound_moves_to_a_warm_floor_without_evidence(): + current = single_lane_plan(name="cold", warmth=Warmth.COLD_WITH_BOUND) + result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY, current=current) + assert [(entry.lane, entry.warmth) for entry in result.plan.identities] == [("org-model-l4", Warmth.PINNED)] + assert result.report.measurement_requests == () + + +def test_an_undeclared_warm_bound_keeps_the_current_class_and_is_reported(): + current = single_lane_plan(cell=A100) + receipts = [receipt(cell=A100), receipt(p99=300.0)] + result = run(levels((IDENTITY, ServiceLevel(come_alive_p95_s=0))), receipts, current=current) + assert result.plan == current + report = result.report.identity(IDENTITY) + assert (report.status, report.chosen.cell) == (IdentityStatus.PLACED, A100) + assert report.next_cheaper.cell == L4 + assert report.next_cheaper.blocked_by == (Blocker(field="warmP99Ms", bound=None, measured=300.0),) + assert report.next_cheaper.to_dict()["blockedBy"] == [{"field": "warmP99Ms", "measured": 300.0}] + assert report.next_cheaper.saving == pytest.approx(2 * MONTH) + assert result.report.warm_bound_undeclared == (IDENTITY,) + assert result.report.to_dict()["warmBoundUndeclared"] == [IDENTITY] + + +def test_an_undeclared_generation_bound_blocks_both_token_latencies_off_the_current_class(): + current = single_lane_plan(cell=A100, concurrency=16) + receipts = [generation_receipt(cell=A100), generation_receipt(cell=L4, ttft=2000.0, itl=95.0)] + result = run(levels((IDENTITY, ServiceLevel(come_alive_p95_s=0))), receipts, current=current) + report = result.report.identity(IDENTITY) + assert report.chosen.cell == A100 + assert report.next_cheaper.blocked_by == ( + Blocker(field="ttftP99Ms", bound=None, measured=2000.0), + Blocker(field="itlP99Ms", bound=None, measured=95.0), + ) + assert report.next_cheaper.saving == pytest.approx(2 * MONTH) + + +def test_an_undeclared_warm_bound_without_a_current_class_places_nothing(): + result = run(levels((IDENTITY, ServiceLevel(come_alive_p95_s=0))), [receipt()], prices=L4_ONLY) + report = result.report.identity(IDENTITY) + assert (report.status, report.unplaced_reason) == (IdentityStatus.UNPLACED, UnplacedReason.WARM_BOUND_UNDECLARED) + assert result.plan.identities == () + assert result.report.warm_bound_undeclared == (IDENTITY,) + + +def test_an_undeclared_warm_bound_without_a_receipt_on_the_current_class_keeps_it(): + current = single_lane_plan(cell=A100) + result = run(levels((IDENTITY, ServiceLevel(come_alive_p95_s=0))), [receipt()], current=current) + assert result.plan == current + report = result.report.identity(IDENTITY) + assert (report.status, report.unplaced_reason) == (IdentityStatus.KEPT, UnplacedReason.WARM_BOUND_UNDECLARED) + assert [(request.cell, request.measure, request.lane) for request in result.report.measurement_requests] == [ + (A100, (Measurement.RECEIPT,), "shared") + ] + assert report.next_cheaper.saving == pytest.approx(2 * MONTH) + + +def test_an_identity_without_any_bound_has_no_undeclared_warm_bound_until_it_has_a_cell(): + result = run(levels((IDENTITY, ServiceLevel())), [], prices=L4_ONLY) + assert result.report.warm_bound_undeclared == () + + +def test_a_lazy_resident_without_evidence_keeps_its_place_and_asks_for_it(): + current = plan_of( + [plan_lane("shared")], {ANCHOR: ("shared", Warmth.PINNED), IDENTITY: ("shared", Warmth.LAZY_RESIDENT)} + ) + receipts = [receipt(identity=ANCHOR), receipt(concurrency=16)] + result = run( + resident_levels(), receipts, [boot(seconds=30.0)], prices=L4_ONLY, hourly={IDENTITY: {0: 10}}, current=current + ) + assert result.plan == current + assert result.report.unchanged + report = result.report.identity(IDENTITY) + assert (report.status, report.unplaced_reason, report.lane) == ( + IdentityStatus.KEPT, + UnplacedReason.CURRENT_UNMEASURED, + "shared", + ) + requests = [ + (request.measure, request.warmth, request.lane, request.concurrency, request.saving_bound) + for request in result.report.measurement_requests + if request.identity == IDENTITY + ] + assert requests == [ + ((Measurement.BOOT_EVIDENCE,), Warmth.LAZY_RESIDENT, "shared", 8, None), + ((Measurement.RECEIPT,), Warmth.LAZY_RESIDENT, "shared", 8, None), ] +def test_a_measured_load_onto_a_lane_a_never_cold_neighbour_pins_makes_a_lazy_resident(): + current = resident_estate() + hourly = {IDENTITY: {3: 90000}} + result = run(resident_levels(), RESIDENT_RECEIPTS, LOADS, prices=L4_ONLY, hourly=hourly, current=current) + report = result.report.identity(IDENTITY) + assert (report.status, report.lane, report.chosen.warmth, report.chosen.lane) == ( + IdentityStatus.PLACED, + "shared", + Warmth.LAZY_RESIDENT, + "shared", + ) + assert (report.chosen.come_alive_s, report.chosen.come_alive_basis) == (20.0, ComeAliveBasis.BOOT_EVIDENCE) + assert report.chosen.monthly_cost == pytest.approx(2 * SCALE) + assert report.chosen.to_dict()["lane"] == "shared" + assert result.plan.lanes == (current.lanes[1],) + assert [(entry.identity, entry.lane, entry.warmth) for entry in result.plan.identities] == [ + (ANCHOR, "shared", Warmth.PINNED), + (IDENTITY, "shared", Warmth.LAZY_RESIDENT), + ] + assert result.report.monthly_cost == pytest.approx(MONTH + 2 * SCALE) + again = run(resident_levels(), RESIDENT_RECEIPTS, LOADS, prices=L4_ONLY, hourly=hourly, current=result.plan) + assert again.plan == result.plan + assert again.report.unchanged + + +def test_an_identity_pinned_beside_a_never_cold_neighbour_stays_pinned_there(): + current = plan_of([plan_lane("shared")], {ANCHOR: ("shared", Warmth.PINNED), IDENTITY: ("shared", Warmth.PINNED)}) + result = run(resident_levels(), RESIDENT_RECEIPTS, LOADS, prices=L4_ONLY, current=current) + assert result.plan == current + assert result.report.unchanged + assert result.report.come_alive_levers == () + + +def test_a_load_over_the_bound_is_a_come_alive_lever(): + result = run(resident_levels(bound=10), RESIDENT_RECEIPTS, LOADS, prices=L4_ONLY, current=resident_estate()) + report = result.report.identity(IDENTITY) + assert (report.lane, report.chosen.warmth) == ("own", Warmth.PINNED) + assert report.next_cheaper.blocked_by == (Blocker(field="comeAliveP95S", bound=10, measured=20.0),) + (lever,) = result.report.come_alive_levers + assert (lever.identity, lever.warmth, lever.permitted_bound_s) == (IDENTITY, Warmth.LAZY_RESIDENT, 20) + assert lever.saving_at_permitted_bound == pytest.approx(MONTH) + assert lever.saving_under_bound == pytest.approx(MONTH) + + +def test_a_lane_a_run_creates_for_a_never_cold_identity_hosts_lazy_residents_from_the_next_run(): + current = plan_of([plan_lane("own")], {IDENTITY: ("own", Warmth.PINNED)}) + first = run(resident_levels(), RESIDENT_RECEIPTS, LOADS, prices=L4_ONLY, current=current) + assert [(entry.identity, entry.lane, entry.warmth) for entry in first.plan.identities] == [ + (ANCHOR, "org-anchor-l4", Warmth.PINNED), + (IDENTITY, "own", Warmth.PINNED), + ] + second = run(resident_levels(), RESIDENT_RECEIPTS, LOADS, prices=L4_ONLY, current=first.plan) + assert [(entry.identity, entry.lane, entry.warmth) for entry in second.plan.identities] == [ + (ANCHOR, "org-anchor-l4", Warmth.PINNED), + (IDENTITY, "org-anchor-l4", Warmth.LAZY_RESIDENT), + ] + assert first.report.monthly_cost - second.report.monthly_cost == pytest.approx(MONTH) + third = run(resident_levels(), RESIDENT_RECEIPTS, LOADS, prices=L4_ONLY, current=second.plan) + assert third.report.unchanged + + +@pytest.mark.parametrize( + ("shared", "anchor_bound"), + [ + (plan_lane("shared"), 30), + (plan_lane("shared", bundle="sglang"), 0), + (plan_lane("shared", queue_pool="batch"), 0), + ], +) +def test_a_lazy_resident_needs_a_never_cold_neighbour_on_a_lane_of_its_pool_and_bundle(shared, anchor_bound): + current = plan_of([plan_lane("own"), shared], {ANCHOR: ("shared", Warmth.PINNED), IDENTITY: ("own", Warmth.PINNED)}) + result = run(resident_levels(anchor_bound=anchor_bound), RESIDENT_RECEIPTS, LOADS, prices=L4_ONLY, current=current) + report = result.report.identity(IDENTITY) + assert (report.lane, report.chosen.warmth) == ("own", Warmth.PINNED) + assert all(lever.warmth is not Warmth.LAZY_RESIDENT for lever in result.report.come_alive_levers) + assert all(request.warmth is not Warmth.LAZY_RESIDENT for request in result.report.measurement_requests) + + +@pytest.mark.parametrize( + ("bound", "expected"), [(60, [(Warmth.COLD_WITH_BOUND, None), (Warmth.LAZY_RESIDENT, "shared")]), (0, [])] +) +def test_a_warm_lane_without_a_load_row_asks_for_one_at_the_saving_it_unlocks(bound, expected): + result = run(resident_levels(bound=bound), RESIDENT_RECEIPTS, prices=L4_ONLY, current=resident_estate()) + requests = [request for request in result.report.measurement_requests if request.identity == IDENTITY] + assert [(request.warmth, request.lane) for request in requests] == expected + for request in requests: + assert (request.measure, request.reason, request.cost_bound) == ( + (Measurement.BOOT_EVIDENCE,), + RequestReason.UNMEASURED, + 0, + ) + assert request.saving_bound == pytest.approx(MONTH) + + def test_a_current_placement_on_a_shared_lane_stays_beside_its_kept_neighbour(): current = single_lane_plan(others=("org/kept",), max_containers=4) service_levels = levels( @@ -958,10 +1263,10 @@ def test_a_new_queue_pool_or_bundle_moves_the_identity_off_its_current_lane(over def test_removing_one_of_two_colliding_identities_keeps_the_other_lane_name(): - service_levels = levels(("org/model", ServiceLevel()), ("org-model", ServiceLevel())) + service_levels = levels(("org/model", WARM), ("org-model", WARM)) receipts = [receipt(identity="org/model"), receipt(identity="org-model")] first = run(service_levels, receipts, prices=L4_ONLY) - second = run(levels(("org/model", ServiceLevel())), receipts, prices=L4_ONLY, current=first.plan) + second = run(levels(("org/model", WARM)), receipts, prices=L4_ONLY, current=first.plan) digest = hashlib.sha256(b"org-model").hexdigest()[:8] kept_name = f"org-model-l4-{hashlib.sha256(b'org/model').hexdigest()[:8]}" assert [entry.lane for entry in second.plan.identities] == [kept_name] @@ -970,7 +1275,7 @@ def test_removing_one_of_two_colliding_identities_keeps_the_other_lane_name(): def test_plan_lanes_that_name_one_chart_lane_are_reported(): - service_levels = levels(("org/a", ServiceLevel()), ("org/b", ServiceLevel()), ("org/c", ServiceLevel())) + service_levels = levels(("org/a", WARM), ("org/b", WARM), ("org/c", WARM)) receipts = [receipt(identity=identity) for identity in ("org/a", "org/b", "org/c")] result = run(service_levels, receipts, prices=L4_ONLY, bundles={"org/c": "sglang"}) (shared,) = result.report.shared_chart_lanes @@ -992,7 +1297,7 @@ def test_a_derived_lane_name_never_takes_a_kept_lane_named_with_its_digest(): placement="test", lanes=(*first.lanes, *second.lanes), identities=(*first.identities, *second.identities) ) service_levels = levels( - (IDENTITY, ServiceLevel()), + (IDENTITY, WARM), ("org/kept", ServiceLevel(come_alive_p95_s=0)), ("org/kept-too", ServiceLevel(come_alive_p95_s=0)), ) @@ -1007,7 +1312,7 @@ def test_a_derived_lane_name_never_takes_a_kept_lane_named_with_its_digest(): def test_bundles_and_the_queue_pool_come_from_the_parameters(): - service_levels = levels(("org/embed", ServiceLevel()), ("org/generate", ServiceLevel())) + service_levels = levels(("org/embed", WARM), ("org/generate", WARM)) result = run( service_levels, [receipt(identity="org/embed"), receipt(identity="org/generate")], @@ -1164,6 +1469,22 @@ def test_the_estate_report_states_its_findings(): assert (kept.status, kept.lane, kept.monthly_cost) == (IdentityStatus.KEPT, "default-l4-default", None) assert [refusal.record for refusal in report.refusals] == [RefusedRecord.BOOT_EVIDENCE, RefusedRecord.RECEIPT] assert report.queue_wait_unattained == ("BAAI/bge-m3", "BAAI/bge-m3:sparse", "intfloat/e5-base-v2") + assert report.warm_bound_undeclared == () + on_lanes = [ + (request.identity, request.measure, request.warmth, request.lane, request.saving_bound) + for request in report.measurement_requests + if request.lane is not None + ] + assert on_lanes == [ + ("intfloat/e5-base-v2", (Measurement.RECEIPT,), Warmth.PINNED, "default-l4-default", None), + ( + "BAAI/bge-m3:sparse", + (Measurement.BOOT_EVIDENCE,), + Warmth.LAZY_RESIDENT, + "default-l4-default", + pytest.approx(sparse.chosen.monthly_cost), + ), + ] assert [change.identity for change in report.identity_changes] == ["BAAI/bge-m3:sparse", "Qwen/Qwen3-Embedding-4B"] assert report.monthly_cost == pytest.approx(sum(lane.monthly_cost for lane in report.lanes)) shared = {lane.name: lane for lane in report.lanes}["default-l4-default"] @@ -1328,3 +1649,148 @@ def test_random_estates_choose_only_feasible_cells_and_replan_to_themselves(seed rng.shuffle(shuffled) reordered = run(service_levels, shuffled, list(reversed(boots)), prices=prices, hourly=hourly, **overrides) assert rendered(reordered) == rendered(result) + + +def capped(lane: PlanLane, ceiling: int) -> PlanLane: + if lane.max_containers <= ceiling: + return lane + envelope = replace( + lane.envelope, + floor_min=min(lane.envelope.floor_min, ceiling), + floor_max=min(lane.envelope.floor_max, ceiling), + ) + return replace(lane, max_containers=ceiling, envelope=envelope) + + +@pytest.mark.parametrize("seed", range(40)) +def test_random_current_estates_keep_what_no_measured_option_beats(seed): + rng = random.Random(seed) # noqa: S311 -- reproducible test data + identities = [f"org/model-{index}" for index in range(rng.randint(2, 6))] + lanes = [] + for index in range(rng.randint(1, 3)): + floor = 1 if index == 0 or rng.random() < 0.6 else 0 + ceiling = rng.choice([2, 4, 6]) + lanes.append( + PlanLane( + name=f"lane-{index}", + queue_pool="default", + bundle="default", + cell=rng.choice([L4, A100]), + container_shape=rng.choice([SHAPE, WIDE]), + concurrency=rng.choice([4, 8]), + max_containers=ceiling, + envelope=Envelope(floor_min=floor, floor_max=min(ceiling, floor + rng.randint(0, 2))), + ) + ) + anchor_lane = lanes[0] + residents = {identities[0]: (anchor_lane.name, Warmth.PINNED)} + for identity in identities[1:]: + if rng.random() < 0.8: + host = rng.choice(lanes) + if host.envelope.floor_min: + warmth = rng.choice([Warmth.PINNED, Warmth.PINNED, Warmth.LAZY_RESIDENT]) + else: + warmth = rng.choice([Warmth.COLD_WITH_BOUND, Warmth.SNAPSHOT_COLD]) + residents[identity] = (host.name, warmth) + hosted = {name for name, _ in residents.values()} + current = plan_of([lane for lane in lanes if lane.name in hosted], residents) + service_levels = levels( + *( + ( + identity, + ServiceLevel( + come_alive_p95_s=0 if identity == identities[0] else rng.choice([None, 0, 30, 120, 600]), + warm_p99_ms=rng.choice([None, 150, 250, 400]), + ), + ) + for identity in identities + ) + ) + on_anchor = (anchor_lane.cell, anchor_lane.container_shape, anchor_lane.concurrency) + receipts = [ + receipt( + identity=identity, + cell=cell, + shape=shape, + concurrency=concurrency, + rps=rng.choice([0.5, 5.0, 50.0]), + p99=rng.choice([100.0, 200.0, 300.0, 500.0]), + uri=f"receipts/{identity}/{cell.machine_profile}/{shape.memory_mib}/{concurrency}", + ) + for identity in identities + for cell in (L4, A100) + for shape in (SHAPE, WIDE) + for concurrency in (4, 8) + if rng.random() < (0.6 if (cell, shape, concurrency) == on_anchor else 0.3) + ] + boots = [ + boot( + identity=identity, + cell=cell, + warmth=warmth, + seconds=rng.choice([5.0, 60.0, 200.0]), + outcome=rng.choice([BootOutcome.SUCCEEDED, BootOutcome.SUCCEEDED, BootOutcome.FAILED]), + shape=shape, + uri=f"boots/{identity}/{cell.machine_profile}/{shape.memory_mib}/{warmth.value}", + ) + for identity in identities + for cell in (L4, A100) + for shape in (SHAPE, WIDE) + for warmth in (Warmth.COLD_WITH_BOUND, Warmth.SNAPSHOT_COLD, Warmth.LAZY_RESIDENT) + if rng.random() < (0.6 if (cell, shape, warmth) == (*on_anchor[:2], Warmth.LAZY_RESIDENT) else 0.3) + ] + hourly = { + identity: {hour: rng.choice([1, 50, 20000]) for hour in rng.sample(range(WINDOW_HOURS), rng.randint(0, 4))} + for identity in identities + } + prices = price_list(l4=rng.choice([0.5, 1.0]), a100=rng.choice([2.0, 3.0]), core=0.1) + overrides = {"buffer_containers": rng.randint(0, 2), "fallback_floor": rng.randint(0, 3)} + result = run(service_levels, receipts, boots, prices=prices, hourly=hourly, current=current, **overrides) + assert Plan.from_dict(result.plan.to_dict()) == result.plan + before = {lane.name: lane for lane in current.lanes} + after = {lane.name: lane for lane in result.plan.lanes} + for name, lane in after.items(): + if name in before: + assert lane == capped(before[name], 4) + placements = {entry.identity: entry for entry in result.plan.identities} + for entry in result.report.identities: + level = entry.service_level + was = residents.get(entry.identity) + if entry.status is IdentityStatus.KEPT: + assert (placements[entry.identity].lane, placements[entry.identity].warmth) == was + continue + declared = level.warm_p99_ms is not None + if entry.chosen is None: + assert entry.identity not in placements + continue + chosen = entry.chosen + assert chosen.blocked_by == () + if not declared: + assert was is not None + assert chosen.cell == before[was[0]].cell + if chosen.warmth is not Warmth.PINNED: + assert level.come_alive_p95_s != 0 + assert level.come_alive_p95_s is None or chosen.come_alive_s <= level.come_alive_p95_s + if chosen.warmth is Warmth.LAZY_RESIDENT: + assert chosen.lane in before + assert before[chosen.lane].envelope.floor_min >= 1 + if entry.next_cheaper is not None: + looser = relaxed(service_levels, entry.identity, entry.next_cheaper.blocked_by) + again = run(looser, receipts, boots, prices=prices, hourly=hourly, current=result.plan, **overrides) + fall = result.report.monthly_cost - again.report.monthly_cost + assert entry.next_cheaper.saving == pytest.approx(max(0.0, fall), abs=0.01) + shuffled = list(receipts) + rng.shuffle(shuffled) + reordered = run( + ServiceLevels(identities=tuple(reversed(service_levels.identities))), + shuffled, + list(reversed(boots)), + prices=prices, + hourly=hourly, + current=current, + **overrides, + ) + assert rendered(reordered) == rendered(result) + again = run(service_levels, receipts, boots, prices=prices, hourly=hourly, current=result.plan, **overrides) + assert again.plan == result.plan + assert again.report.unchanged From c469b250b423d6e28b170a5720ab5272d2cb950a Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Thu, 5 Nov 2026 13:27:01 +0100 Subject: [PATCH 12/16] docs(placement): rewrap the lazy-resident selection step --- packages/sie_placement/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index bc24b2f6c..d0cf747c3 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -163,10 +163,10 @@ document: with a `floorMin` of at least 1, on the parameters' queue pool and the identity's bundle, on which another identity whose `comeAliveP95S` is `0` is pinned. The identity's own current lane is a host only when it is a lazy - resident there, since its floor is paid either way. - The come-alive is the identity's `lazy-resident` boot evidence, its measured - load onto that cell and container shape, under the same statistic. The - option costs what the identity's demand needs above the host lane's floor. + resident there, since its floor is paid either way. The come-alive is the + identity's `lazy-resident` boot evidence, its measured load onto that cell + and container shape, under the same statistic. The option costs what the + identity's demand needs above the host lane's floor. 5. The cheapest unblocked option wins. Ties go to the current placement, then to the faster come-alive. From 195cd2ef0d593106ec97b893b1b4f4efab1ec406 Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Thu, 5 Nov 2026 14:08:28 +0100 Subject: [PATCH 13/16] fix(placement): decide lazy hosts against the plan being written A lazy resident's option was hosted by any lane of the current plan on which a never-cold identity was pinned, even when that identity moved in the same run. The resident then sat alone on a warm-floor lane while its option claimed to cost nothing beyond a floor nobody else paid. Identities whose comeAliveP95S is 0 are now placed first, since no cold or lazy option can meet that bound, and a lane hosts lazy residents only when one of them stays pinned on it in this run. A resident's own lazy lane without such a neighbour stays an option, priced at the lane's floor as well. A boot or load at the current lane that did not succeed now blocks the current placement instead of holding it as unmeasured, and a current placement kept on a lane the price list cannot price reports current-unpriced rather than current-unmeasured. --- packages/sie_placement/README.md | 59 ++++---- .../src/sie_placement/planner.py | 61 ++++---- .../sie_placement/src/sie_placement/report.py | 1 + packages/sie_placement/tests/test_planner.py | 133 +++++++++++++++++- 4 files changed, 201 insertions(+), 53 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index d0cf747c3..7a8be6e86 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -123,9 +123,11 @@ print(render(result.plan.to_dict()), render(result.report.to_dict())) same bytes in whatever order the receipts, boot evidence, identities and demand series arrive. An identity that stays on its current placement keeps its current lane as it is, so a run whose `current_plan` already holds every -choice, such as its own previous plan, reports no change. The one exception is -a lane that the previous run created for an identity whose `comeAliveP95S` is -`0`: it hosts lazy residents only from the run after it. +choice, such as its own previous plan, reports no change. The exceptions are +lazy residents that join a host lane one run later: a lane the previous run +created for an identity whose `comeAliveP95S` is `0` hosts lazy residents only +from the run after it, and an identity that left a host lane it was pinned on +may rejoin that lane as a lazy resident on the next run. | Parameter | Meaning | | --- | --- | @@ -161,12 +163,16 @@ document: 4. A cell also offers `lazy-resident` on each host lane with its cell, container shape and concurrency. A host lane is a lane of the current plan with a `floorMin` of at least 1, on the parameters' queue pool and the - identity's bundle, on which another identity whose `comeAliveP95S` is `0` is - pinned. The identity's own current lane is a host only when it is a lazy - resident there, since its floor is paid either way. The come-alive is the + identity's bundle, on which another identity whose `comeAliveP95S` is `0` + stays pinned in this run, on its current placement or kept there. Those + identities are placed first: a bound of `0` admits no cold or lazy option, + so no other choice moves them. The identity's own current lane is also a + host when it is a lazy resident there already. The come-alive is the identity's `lazy-resident` boot evidence, its measured load onto that cell and container shape, under the same statistic. The option costs what the - identity's demand needs above the host lane's floor. + identity's demand needs above the host lane's floor, plus the floor itself + on a lane where no such identity stays pinned, since no other identity pays + it. 5. The cheapest unblocked option wins. Ties go to the current placement, then to the faster come-alive. @@ -175,16 +181,19 @@ option's cell, container shape and concurrency, the identity's warmth is the option's, and the lane's `queuePool` and `bundle` are the ones the parameters give the identity; a `lazy-resident` option must also be hosted by that lane. A current placement that no option matches lacks evidence: a receipt at its -lane's cell, container shape and concurrency, a successful boot for a cold -warmth, or a load for a lazy resident. Unless it is known to miss a bound, -through a receipt at the lane that misses a warm bound, a measured come-alive -over the bound, or a cold or `lazy-resident` warmth under a bound of `0`, the -identity keeps that placement and leaves it only for an unblocked option at -least a cent cheaper than the placement. The placement is priced as an option -of its warmth at the lane's fastest receipt, or without one at its floor alone: -one container all month for `pinned`, nothing beyond the host lane's floor for -`lazy-resident`, and the burst tails for a cold warmth. What the placement -lacks becomes a measurement request. +lane's cell, container shape and concurrency, a boot for a cold warmth, or a +load for a lazy resident. Unless it is known to miss a bound, through a receipt +at the lane that misses a warm bound, a measured come-alive over the bound, a +boot or load at the lane that did not succeed, or a cold or `lazy-resident` +warmth under a bound of `0`, the identity keeps that placement and leaves it +only for an unblocked option at least a cent cheaper than the placement. The +placement is priced as an option of its warmth at the lane's fastest receipt, +or without one at its floor alone: one container all month for `pinned`, for +`lazy-resident` nothing beyond the lane's floor, or the floor itself where no +identity whose `comeAliveP95S` is `0` stays pinned on the lane, and the burst +tails for a cold warmth. What the placement lacks becomes a measurement +request. Such a placement on a lane the price list cannot price has no cost to +compare, so the identity keeps it. An identity that stays on its current placement keeps that lane exactly as it is, beside whoever else the lane hosts: its cell, container shape, @@ -251,12 +260,14 @@ The report renders as a `placement-report` document: total would not fall, as for an identity whose lane keeps its floor for its other residents. An identity without a placement names its `unplacedReason`: `no-receipt`, `warm-bound-missed`, - `warm-bound-undeclared` when no cell is on its current class, or + `warm-bound-undeclared` when no cell is on its current class, `current-unmeasured` when it keeps a current placement that lacks evidence - and no unblocked option is cheaper. A kept identity's `blockedBy` names the - bounds its kept placement is known to miss: its receipt's warm latencies, a - measured come-alive over the bound, or a cold or `lazy-resident` warmth under - a bound of `0`, which needs no measurement. + and no unblocked option is cheaper, or `current-unpriced` when it keeps a + current placement on a lane the price list cannot price. A kept identity's + `blockedBy` names the bounds its kept placement is known to miss: its + receipt's warm latencies, a measured come-alive over the bound, and with no + `measured` value a boot or load at its lane that did not succeed, or a cold + or `lazy-resident` warmth under a bound of `0`, which needs no measurement. - `lanes`: each lane's hourly cost, its monthly cost, its floor's monthly cost and the monthly cost of its `floorMax`, which a floor budget prices. A lane on a cell the price list cannot price carries `unpricedReason` and no cost, @@ -269,8 +280,8 @@ The report renders as a `placement-report` document: accelerator at its rate, kept warm or, where the come-alive bound allows, paying burst tails only. A cell whose receipt has no successful boot asks for boot evidence and is bounded by its cold cost, and a host lane without the - identity's load asks for `lazy-resident` boot evidence on it, bounded by the - demand above the host's floor. Savings are measured against the choice, or + identity's load asks for `lazy-resident` boot evidence on it, bounded by + what that option would cost. Savings are measured against the choice, or against a kept identity's current placement. A request that cannot save is dropped, and the requests of an identity without a placement or a current one carry no bound and rank first. The evidence a kept current placement diff --git a/packages/sie_placement/src/sie_placement/planner.py b/packages/sie_placement/src/sie_placement/planner.py index 88ed83bcb..b3e82d23b 100644 --- a/packages/sie_placement/src/sie_placement/planner.py +++ b/packages/sie_placement/src/sie_placement/planner.py @@ -249,6 +249,7 @@ class _Choice: has_valid_receipt: bool held: float | None = None gaps: tuple[MeasurementRequest, ...] = () + unpriced: bool = False @property def baseline(self) -> float | None: @@ -257,7 +258,7 @@ def baseline(self) -> float | None: @property def unplaced_reason(self) -> UnplacedReason: if any(option.feasible for option in self.options): - return UnplacedReason.CURRENT_UNMEASURED + return UnplacedReason.CURRENT_UNPRICED if self.unpriced else UnplacedReason.CURRENT_UNMEASURED if not self.has_valid_receipt: return UnplacedReason.NO_RECEIPT if not _declares_warm_bound(self.level): @@ -414,14 +415,12 @@ def __init__( self.current_plan = current_plan self.current: dict[str, tuple[PlanIdentity, PlanLane]] = {} self.current_lanes: dict[str, PlanLane] = {} - self.residents: defaultdict[str, list[PlanIdentity]] = defaultdict(list) + self.anchors: dict[str, frozenset[str]] = {} if current_plan is not None: self.current_lanes = {lane.name: lane for lane in current_plan.lanes} self.current = { entry.identity: (entry, self.current_lanes[entry.lane]) for entry in current_plan.identities } - for entry in current_plan.identities: - self.residents[entry.lane].append(entry) self.refusals: list[Refusal] = [] self.refused_profiles: set[tuple[str, str]] = set() self.savings: dict[tuple[str, tuple[tuple[str, int], ...]], float] = {} @@ -482,9 +481,18 @@ def keepable(self, identity: str) -> tuple[PlanIdentity, PlanLane] | None: return None return current - def anchors(self, entry: PlanIdentity) -> bool: - level = self.levels.get(entry.identity) - return entry.warmth is Warmth.PINNED and level is not None and level.come_alive_p95_s == 0 + def staying_anchors(self, choices: Iterable[_Choice]) -> dict[str, frozenset[str]]: + anchors: defaultdict[str, set[str]] = defaultdict(set) + for choice in choices: + current = self.current.get(choice.identity) + if current is None or current[0].warmth is not Warmth.PINNED: + continue + if choice.chosen is None or choice.chosen.current: + anchors[current[1].name].add(choice.identity) + return {lane: frozenset(identities) for lane, identities in anchors.items()} + + def floor_paid(self, lane: str, identity: str) -> bool: + return bool(self.anchors.get(lane, frozenset()) - {identity}) def lazy_hosts(self, identity: str) -> tuple[PlanLane, ...]: current = self.current.get(identity) @@ -494,20 +502,21 @@ def lazy_hosts(self, identity: str) -> tuple[PlanLane, ...]: return tuple( lane for name, lane in sorted(self.current_lanes.items()) - if lane.envelope.floor_min >= PINNED_FLOOR + if (lazy if name == home else self.floor_paid(name, identity)) + and lane.envelope.floor_min >= PINNED_FLOOR and lane.queue_pool == self.parameters.queue_pool and lane.bundle == bundle - and ( - lazy - if name == home - else any(self.anchors(entry) for entry in self.residents[name] if entry.identity != identity) - ) ) - def resident_hours(self, lane: PlanLane, requests: Sequence[int], rate: float) -> float: + def resident_hours(self, lane: PlanLane, identity: str, requests: Sequence[int], rate: float | None) -> float: capped = self.within_ceiling(lane) + floor = ( + 0.0 if self.floor_paid(lane.name, identity) else capped.envelope.floor_min * self.parameters.hours_per_month + ) + if rate is None: + return floor window = replace(self.window, ceiling=capped.max_containers) - return window.above_floor_hours(requests, rate, capped.envelope.floor_min) + return floor + window.above_floor_hours(requests, rate, capped.envelope.floor_min) def current_cost(self, identity: str, entry: PlanIdentity, lane: PlanLane) -> float | None: if _refusal_reason(lane.cell, self.prices) is not None: @@ -529,7 +538,7 @@ def current_cost(self, identity: str, entry: PlanIdentity, lane: PlanLane) -> fl else self.window.warm_container_hours(requests, rate) ) elif entry.warmth is Warmth.LAZY_RESIDENT: - hours = 0.0 if rate is None else self.resident_hours(lane, requests, rate) + hours = self.resident_hours(lane, identity, requests, rate) else: hours = self.window.cold_container_hours(requests, rate) return hourly * hours @@ -543,11 +552,8 @@ def current_gaps( if self.slowest_receipt(identity, lane) is None: refused = (identity, lane.cell.machine_profile) in self.refused_profiles missing.append((Measurement.RECEIPT, RequestReason.REFUSED if refused else RequestReason.UNMEASURED)) - if entry.warmth in BOOT_WARMTHS: - boot = self.boots.get((identity, lane.cell, lane.container_shape, entry.warmth)) - if boot is None or boot.seconds is None: - reason = RequestReason.UNMEASURED if boot is None else RequestReason.FAILED - missing.append((Measurement.BOOT_EVIDENCE, reason)) + if entry.warmth in BOOT_WARMTHS and (identity, lane.cell, lane.container_shape, entry.warmth) not in self.boots: + missing.append((Measurement.BOOT_EVIDENCE, RequestReason.UNMEASURED)) return tuple( MeasurementRequest( identity=identity, @@ -628,7 +634,7 @@ def choose(self, identity: str) -> _Choice: for host in hosts: if not _runs_on(receipt, host): continue - lazy_cost = hourly * self.resident_hours(host, requests, rate) + lazy_cost = hourly * self.resident_hours(host, identity, requests, rate) load = self.boots.get((identity, host.cell, host.container_shape, Warmth.LAZY_RESIDENT)) if load is None or load.seconds is None: known = load_requests.get(host.name) @@ -664,6 +670,7 @@ def choose(self, identity: str) -> _Choice: feasible = [option for option in options if option.feasible] chosen = min(feasible, key=lambda option: option.rank) if feasible else None held = None + unpriced = False gaps: tuple[MeasurementRequest, ...] = () current = self.keepable(identity) if current is not None and not any(option.current for option in options): @@ -674,6 +681,7 @@ def choose(self, identity: str) -> _Choice: chosen = min(cheaper, key=lambda option: option.rank) if cheaper else None if chosen is None: held = cost + unpriced = cost is None gaps = self.current_gaps(identity, entry, lane, cost) gapped = { (request.cell, request.container_shape, request.warmth) @@ -694,6 +702,7 @@ def choose(self, identity: str) -> _Choice: has_valid_receipt=bool(receipts), held=held, gaps=gaps, + unpriced=unpriced, ) def receipt_requests(self, choice: _Choice, baseline: float | None) -> list[MeasurementRequest]: @@ -901,13 +910,13 @@ def kept_blockers( ) -> tuple[Blocker, ...]: level = self.levels[identity] blockers = [] if receipt is None else list(_warm_blockers(level, receipt)) - if entry.warmth in BOOT_WARMTHS and level.come_alive_p95_s is not None: + if entry.warmth in BOOT_WARMTHS: boot = self.boots.get((identity, lane.cell, lane.container_shape, entry.warmth)) if boot is not None and boot.seconds is not None: blocker = _come_alive_blocker(level, boot.seconds) blockers.extend(() if blocker is None else (blocker,)) - elif level.come_alive_p95_s == 0: - blockers.append(Blocker(field="comeAliveP95S", bound=0, measured=None)) + elif boot is not None or level.come_alive_p95_s == 0: + blockers.append(Blocker(field="comeAliveP95S", bound=level.come_alive_p95_s, measured=None)) return tuple(blockers) def demand_hours(self, lane: PlanLane, identity: str, receipt: Receipt | None) -> float | None: @@ -927,6 +936,8 @@ def demand_hours(self, lane: PlanLane, identity: str, receipt: Receipt | None) - return window.cold_container_hours(requests, rate) def run(self, *, price_savings: bool = True) -> PlannerResult: + never_cold = [identity for identity in sorted(self.levels) if self.levels[identity].come_alive_p95_s == 0] + self.anchors = self.staying_anchors(self.choose(identity) for identity in never_cold) choices = [self.choose(identity) for identity in sorted(self.levels)] placed = {choice.identity: choice.chosen for choice in choices if choice.chosen is not None} kept = { diff --git a/packages/sie_placement/src/sie_placement/report.py b/packages/sie_placement/src/sie_placement/report.py index 42eea8e31..585f5f8d0 100644 --- a/packages/sie_placement/src/sie_placement/report.py +++ b/packages/sie_placement/src/sie_placement/report.py @@ -32,6 +32,7 @@ class UnplacedReason(StrEnum): WARM_BOUND_MISSED = "warm-bound-missed" WARM_BOUND_UNDECLARED = "warm-bound-undeclared" CURRENT_UNMEASURED = "current-unmeasured" + CURRENT_UNPRICED = "current-unpriced" class ComeAliveBasis(StrEnum): diff --git a/packages/sie_placement/tests/test_planner.py b/packages/sie_placement/tests/test_planner.py index 463ad80a8..0141707b1 100644 --- a/packages/sie_placement/tests/test_planner.py +++ b/packages/sie_placement/tests/test_planner.py @@ -882,6 +882,21 @@ def test_a_kept_lane_on_a_refused_cell_is_kept_and_reported_unpriced(): } +@pytest.mark.parametrize( + "cell", + [Cell(machine_profile="l4", gpu_product="NVIDIA-A10G"), Cell(machine_profile="h100", gpu_product="NVIDIA-H100")], +) +def test_a_current_lane_on_a_refused_cell_is_kept_beside_a_measured_priced_option(cell): + current = single_lane_plan(cell=cell) + result = run(level(come_alive_p95_s=0), [receipt()], prices=L4_ONLY, current=current) + assert result.plan == current + report = result.report.identity(IDENTITY) + assert (report.status, report.unplaced_reason) == (IdentityStatus.KEPT, UnplacedReason.CURRENT_UNPRICED) + assert report.to_dict()["unplacedReason"] == "current-unpriced" + assert result.report.unpriced_lanes == ("shared",) + assert result.report.measurement_requests == () + + def test_a_kept_lane_never_exceeds_the_reviewed_ceiling(): current = single_lane_plan(max_containers=4, envelope=Envelope(floor_min=2, floor_max=3)) result = run(level(come_alive_p95_s=0), [], prices=L4_ONLY, current=current, max_containers=1) @@ -898,6 +913,8 @@ def test_a_kept_lane_never_exceeds_the_reviewed_ceiling(): (120, (), ()), (120, (boot(seconds=200.0),), (Blocker(field="comeAliveP95S", bound=120, measured=200.0),)), (300, (boot(seconds=200.0),), ()), + (120, (boot(outcome=BootOutcome.FAILED),), (Blocker(field="comeAliveP95S", bound=120, measured=None),)), + (None, (boot(outcome=BootOutcome.TIMED_OUT),), (Blocker(field="comeAliveP95S", bound=None, measured=None),)), ], ) def test_a_kept_cold_placement_names_the_come_alive_bound_it_is_known_to_miss(bound, boots, expected): @@ -908,7 +925,8 @@ def test_a_kept_cold_placement_names_the_come_alive_bound_it_is_known_to_miss(bo assert report.blocked_by == expected assert report.monthly_cost == 0 if expected and expected[0].measured is None: - assert report.to_dict()["blockedBy"] == [{"field": "comeAliveP95S", "bound": 0}] + bounded = {} if bound is None else {"bound": bound} + assert report.to_dict()["blockedBy"] == [{"field": "comeAliveP95S", **bounded}] def test_an_identity_without_a_feasible_cell_or_a_current_lane_is_left_out(): @@ -1010,6 +1028,37 @@ def test_a_cold_lane_without_boot_evidence_is_kept_and_asks_for_it(): assert request.cost_bound == pytest.approx((1 / 10.0 + 1 * 2 * 900) / 3600 * SCALE) +@pytest.mark.parametrize("outcome", [BootOutcome.FAILED, BootOutcome.TIMED_OUT]) +def test_a_cold_lane_whose_boot_did_not_succeed_moves_to_a_measured_option(outcome): + current = single_lane_plan(name="cold", warmth=Warmth.COLD_WITH_BOUND) + boots = [boot(seconds=0.0, outcome=outcome)] + result = run( + level(come_alive_p95_s=120), [receipt()], boots, prices=L4_ONLY, hourly={IDENTITY: {0: 1}}, current=current + ) + report = result.report.identity(IDENTITY) + assert (report.status, report.chosen.warmth) == (IdentityStatus.PLACED, Warmth.PINNED) + assert [(entry.lane, entry.warmth) for entry in result.plan.identities] == [("org-model-l4", Warmth.PINNED)] + (request,) = result.report.measurement_requests + assert (request.measure, request.warmth, request.reason) == ( + (Measurement.BOOT_EVIDENCE,), + Warmth.COLD_WITH_BOUND, + RequestReason.FAILED, + ) + assert request.saving_bound == pytest.approx(MONTH - (1 / 10.0 + 1 * 2 * 900) / 3600 * SCALE) + + +def test_a_lazy_resident_whose_load_failed_moves_to_a_measured_option(): + current = plan_of( + [plan_lane("shared")], {ANCHOR: ("shared", Warmth.PINNED), IDENTITY: ("shared", Warmth.LAZY_RESIDENT)} + ) + loads = [boot(warmth=Warmth.LAZY_RESIDENT, outcome=BootOutcome.FAILED, uri="loads/failed.json")] + result = run(resident_levels(), RESIDENT_RECEIPTS, loads, prices=L4_ONLY, current=current) + report = result.report.identity(IDENTITY) + assert (report.status, report.lane, report.chosen.warmth) == (IdentityStatus.PLACED, "org-model-l4", Warmth.PINNED) + requests = [(request.warmth, request.lane, request.reason) for request in result.report.measurement_requests] + assert (Warmth.LAZY_RESIDENT, "shared", RequestReason.FAILED) in requests + + def test_an_unmeasured_current_lane_moves_to_a_measured_option_that_is_cheaper(): current = single_lane_plan(name="cold", warmth=Warmth.COLD_WITH_BOUND, cell=A100) result = run( @@ -1176,6 +1225,62 @@ def test_a_lane_a_run_creates_for_a_never_cold_identity_hosts_lazy_residents_fro assert third.report.unchanged +def test_a_lazy_resident_never_joins_a_lane_its_never_cold_neighbour_leaves(): + current = plan_of( + [plan_lane("own"), plan_lane("shared", cell=A100)], + {ANCHOR: ("shared", Warmth.PINNED), IDENTITY: ("own", Warmth.PINNED)}, + ) + receipts = [receipt(identity=ANCHOR, cell=A100), receipt(identity=ANCHOR), receipt(cell=A100), receipt()] + loads = [boot(cell=A100, warmth=Warmth.LAZY_RESIDENT, seconds=20.0, uri="loads/a100.json")] + result = run(resident_levels(), receipts, loads, current=current) + assert [(entry.identity, entry.lane, entry.warmth) for entry in result.plan.identities] == [ + (ANCHOR, "org-anchor-l4", Warmth.PINNED), + (IDENTITY, "own", Warmth.PINNED), + ] + assert result.report.monthly_cost == pytest.approx(2 * MONTH) + assert all(request.warmth is not Warmth.LAZY_RESIDENT for request in result.report.measurement_requests) + again = run(resident_levels(), receipts, loads, current=result.plan) + assert again.report.unchanged + + +def test_a_lazy_resident_whose_lane_keeps_no_never_cold_neighbour_pays_the_lane_floor(): + current = plan_of( + [plan_lane("shared")], {"org/warm": ("shared", Warmth.PINNED), IDENTITY: ("shared", Warmth.LAZY_RESIDENT)} + ) + service_levels = levels( + ("org/warm", ServiceLevel(come_alive_p95_s=120, warm_p99_ms=ANY_P99_MS)), + (IDENTITY, ServiceLevel(come_alive_p95_s=60, warm_p99_ms=ANY_P99_MS)), + ) + receipts = [receipt(identity="org/warm"), receipt()] + boots = [boot(identity="org/warm"), *LOADS, boot(seconds=30.0)] + hourly = {"org/warm": {0: 1}, IDENTITY: {0: 1}} + result = run(service_levels, receipts, boots, prices=L4_ONLY, hourly=hourly, current=current) + cold = (1 / 10.0 + 1 * 2 * 900) / 3600 * SCALE + assert [(entry.identity, entry.lane, entry.warmth) for entry in result.plan.identities] == [ + (IDENTITY, "org-model-l4", Warmth.COLD_WITH_BOUND), + ("org/warm", "org-warm-l4", Warmth.COLD_WITH_BOUND), + ] + assert result.report.monthly_cost == pytest.approx(2 * cold) + report = result.report.identity(IDENTITY) + assert report.chosen.monthly_cost == pytest.approx(cold) + assert report.next_cheaper is None + + +def test_a_lazy_resident_left_alone_on_its_lane_stays_when_nothing_is_cheaper_than_the_lane_floor(): + current = plan_of([plan_lane("shared")], {IDENTITY: ("shared", Warmth.LAZY_RESIDENT)}) + result = run(level(come_alive_p95_s=60), [receipt()], LOADS, prices=L4_ONLY, current=current) + assert result.plan == current + assert result.report.unchanged + report = result.report.identity(IDENTITY) + assert (report.status, report.chosen.warmth, report.chosen.lane) == ( + IdentityStatus.PLACED, + Warmth.LAZY_RESIDENT, + "shared", + ) + assert report.chosen.monthly_cost == pytest.approx(MONTH) + assert result.report.monthly_cost == pytest.approx(MONTH) + + @pytest.mark.parametrize( ("shared", "anchor_bound"), [ @@ -1662,7 +1767,7 @@ def capped(lane: PlanLane, ceiling: int) -> PlanLane: return replace(lane, max_containers=ceiling, envelope=envelope) -@pytest.mark.parametrize("seed", range(40)) +@pytest.mark.parametrize("seed", range(200)) def test_random_current_estates_keep_what_no_measured_option_beats(seed): rng = random.Random(seed) # noqa: S311 -- reproducible test data identities = [f"org/model-{index}" for index in range(rng.randint(2, 6))] @@ -1753,6 +1858,13 @@ def test_random_current_estates_keep_what_no_measured_option_beats(seed): if name in before: assert lane == capped(before[name], 4) placements = {entry.identity: entry for entry in result.plan.identities} + never_cold = {entry.identity for entry in service_levels.identities if entry.level.come_alive_p95_s == 0} + anchored = { + entry.lane + for entry in result.plan.identities + if entry.identity in never_cold and residents.get(entry.identity) == (entry.lane, Warmth.PINNED) + } + rates = {price.name: price for price in prices.machine_profiles} for entry in result.report.identities: level = entry.service_level was = residents.get(entry.identity) @@ -1774,6 +1886,11 @@ def test_random_current_estates_keep_what_no_measured_option_beats(seed): if chosen.warmth is Warmth.LAZY_RESIDENT: assert chosen.lane in before assert before[chosen.lane].envelope.floor_min >= 1 + if chosen.lane not in anchored: + lane = after[chosen.lane] + hourly_cost = container_hourly_cost(rates[lane.cell.machine_profile], lane.container_shape, 1.0) + assert was == (chosen.lane, Warmth.LAZY_RESIDENT) + assert chosen.monthly_cost >= hourly_cost * lane.envelope.floor_min * MONTH - 0.01 if entry.next_cheaper is not None: looser = relaxed(service_levels, entry.identity, entry.next_cheaper.blocked_by) again = run(looser, receipts, boots, prices=prices, hourly=hourly, current=result.plan, **overrides) @@ -1791,6 +1908,14 @@ def test_random_current_estates_keep_what_no_measured_option_beats(seed): **overrides, ) assert rendered(reordered) == rendered(result) - again = run(service_levels, receipts, boots, prices=prices, hourly=hourly, current=result.plan, **overrides) - assert again.plan == result.plan + replanned = result + for _ in range(3): + again = run(service_levels, receipts, boots, prices=prices, hourly=hourly, current=replanned.plan, **overrides) + if again.report.unchanged: + break + lanes = {lane.name for lane in replanned.plan.lanes} + for change in again.report.identity_changes: + assert (change.after.lane in lanes, change.after.warmth) == (True, Warmth.LAZY_RESIDENT) + assert all(change.after is None for change in again.report.lane_changes) + replanned = again assert again.report.unchanged From 89a5790bae2c313694b14f45c3ca2ddfe077b9c7 Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Fri, 6 Nov 2026 10:16:49 +0100 Subject: [PATCH 14/16] fix(placement): refuse non-finite numbers in documents built in code - The minimum and positivity checks that every number field passes through now refuse NaN, infinities and integers beyond the float range, as parsing does, so a document built in code serializes to one that parses again. --- .../sie_placement/src/sie_placement/schema.py | 19 +++++++++++-- packages/sie_placement/tests/test_schema.py | 28 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/packages/sie_placement/src/sie_placement/schema.py b/packages/sie_placement/src/sie_placement/schema.py index 410d6cf7e..9c7a1317f 100644 --- a/packages/sie_placement/src/sie_placement/schema.py +++ b/packages/sie_placement/src/sie_placement/schema.py @@ -247,13 +247,28 @@ def _require_identifier(name: str, value: str) -> None: raise SchemaError(name, f"must be a non-empty string without whitespace, got {value!r}") +def _require_finite(name: str, value: float) -> None: + try: + finite = math.isfinite(value) + except OverflowError: + raise SchemaError(name, "must be a finite number, got an integer beyond the float range") from None + if not finite: + raise SchemaError(name, f"must be a finite number, got {value!r}") + + def _require_at_least(name: str, value: float | None, minimum: int) -> None: - if value is not None and value < minimum: + if value is None: + return + _require_finite(name, value) + if value < minimum: raise SchemaError(name, f"must be at least {minimum}, got {value!r}") def _require_positive(name: str, value: float | None) -> None: - if value is not None and value <= 0: + if value is None: + return + _require_finite(name, value) + if value <= 0: raise SchemaError(name, f"must be greater than 0, got {value!r}") diff --git a/packages/sie_placement/tests/test_schema.py b/packages/sie_placement/tests/test_schema.py index 2ca86915c..eb729e56d 100644 --- a/packages/sie_placement/tests/test_schema.py +++ b/packages/sie_placement/tests/test_schema.py @@ -17,8 +17,10 @@ DemandSeries, Envelope, IdentityServiceLevel, + MachineProfilePrice, Operation, Percentiles, + Placement, Plan, PlanIdentity, PlanLane, @@ -27,6 +29,7 @@ SchemaError, ServiceLevel, ServiceLevels, + Throughput, Warmth, ) @@ -141,6 +144,31 @@ def test_numbers_must_be_finite(value): assert error.message.startswith("expected a finite number") +@pytest.mark.parametrize( + ("build", "field"), + [ + (lambda value: Throughput(requests_per_second=value), "requestsPerSecond"), + (lambda value: Percentiles(p99_ms=value), "p99Ms"), + (lambda value: ContainerShape(gpu_count=1, cpu_cores=value, memory_mib=1024), "cpuCores"), + (lambda value: Placement(name="default", region_multiplier=value), "regionMultiplier"), + ( + lambda value: MachineProfilePrice( + name="l4", gpu_product="NVIDIA-L4", accelerator_per_hour=value, core_per_hour=0, memory_gib_per_hour=0 + ), + "acceleratorPerHour", + ), + ], +) +@pytest.mark.parametrize( + "value", [math.nan, math.inf, -math.inf, 10**400], ids=["nan", "infinity", "negative-infinity", "integer"] +) +def test_numbers_built_in_code_must_be_finite(build, field, value): + with pytest.raises(SchemaError) as caught: + build(value) + assert caught.value.path == field + assert caught.value.message.startswith("must be a finite number") + + def test_numbers_reject_booleans(): data = load("price-list.json") data["placements"][0]["regionMultiplier"] = False From 557696f65962600e5c9e2e480af470ce698b4ce2 Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Fri, 6 Nov 2026 10:28:15 +0100 Subject: [PATCH 15/16] fix(placement): refuse booleans and non-integers in documents built in code - Number fields refuse booleans and values that are not numbers, as the parser does, and integer fields refuse booleans and floats through a dedicated integer check, so a document built in code serializes to one that parses again. --- .../sie_placement/src/sie_placement/schema.py | 41 ++++++++++++------- packages/sie_placement/tests/test_schema.py | 23 +++++++++++ 2 files changed, 49 insertions(+), 15 deletions(-) diff --git a/packages/sie_placement/src/sie_placement/schema.py b/packages/sie_placement/src/sie_placement/schema.py index 9c7a1317f..1e319f28d 100644 --- a/packages/sie_placement/src/sie_placement/schema.py +++ b/packages/sie_placement/src/sie_placement/schema.py @@ -247,7 +247,9 @@ def _require_identifier(name: str, value: str) -> None: raise SchemaError(name, f"must be a non-empty string without whitespace, got {value!r}") -def _require_finite(name: str, value: float) -> None: +def _require_number(name: str, value: float) -> None: + if isinstance(value, bool) or not isinstance(value, int | float): + raise SchemaError(name, f"must be a number, got {_describe(value)}") try: finite = math.isfinite(value) except OverflowError: @@ -256,10 +258,19 @@ def _require_finite(name: str, value: float) -> None: raise SchemaError(name, f"must be a finite number, got {value!r}") +def _require_count(name: str, value: int | None, minimum: int) -> None: + if value is None: + return + if isinstance(value, bool) or not isinstance(value, int): + raise SchemaError(name, f"must be an integer, got {_describe(value)}") + if value < minimum: + raise SchemaError(name, f"must be at least {minimum}, got {value!r}") + + def _require_at_least(name: str, value: float | None, minimum: int) -> None: if value is None: return - _require_finite(name, value) + _require_number(name, value) if value < minimum: raise SchemaError(name, f"must be at least {minimum}, got {value!r}") @@ -267,7 +278,7 @@ def _require_at_least(name: str, value: float | None, minimum: int) -> None: def _require_positive(name: str, value: float | None) -> None: if value is None: return - _require_finite(name, value) + _require_number(name, value) if value <= 0: raise SchemaError(name, f"must be greater than 0, got {value!r}") @@ -316,7 +327,7 @@ class ServiceLevel: def __post_init__(self) -> None: for name, value in self._fields(): - _require_at_least(name, value, 0) + _require_count(name, value, 0) if self.warm_p99_ms is not None and (self.ttft_p99_ms is not None or self.itl_p99_ms is not None): raise SchemaError("warmP99Ms", "must be omitted when ttftP99Ms and itlP99Ms declare a generation identity") @@ -469,9 +480,9 @@ class ContainerShape: memory_mib: int def __post_init__(self) -> None: - _require_at_least("gpuCount", self.gpu_count, 1) + _require_count("gpuCount", self.gpu_count, 1) _require_positive("cpuCores", self.cpu_cores) - _require_at_least("memoryMiB", self.memory_mib, 1) + _require_count("memoryMiB", self.memory_mib, 1) @classmethod def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: @@ -495,12 +506,12 @@ class RequestShape: output_tokens: int | None = None def __post_init__(self) -> None: - _require_at_least("itemsPerRequest", self.items_per_request, 1) - _require_at_least("inputTokensPerItem", self.input_tokens_per_item, 0) + _require_count("itemsPerRequest", self.items_per_request, 1) + _require_count("inputTokensPerItem", self.input_tokens_per_item, 0) if self.operation is Operation.GENERATE: if self.output_tokens is None: raise SchemaError("outputTokens", "is required for the generate operation") - _require_at_least("outputTokens", self.output_tokens, 1) + _require_count("outputTokens", self.output_tokens, 1) else: _require_absent("outputTokens", self.output_tokens, "for an operation other than generate") @@ -612,7 +623,7 @@ class Receipt: def __post_init__(self) -> None: _require_identifier("identity", self.identity) - _require_at_least("concurrency", self.concurrency, 1) + _require_count("concurrency", self.concurrency, 1) if self.request_shape.operation is Operation.GENERATE: _require_absent("latency", self.latency, "for the generate operation, which reports ttft and itl") if self.ttft is None: @@ -813,8 +824,8 @@ class DemandHour: def __post_init__(self) -> None: _require_hour("start", self.start) - _require_at_least("requests", self.requests, 0) - _require_at_least("units", self.units, 0) + _require_count("requests", self.requests, 0) + _require_count("units", self.units, 0) @classmethod def from_dict(cls, data: object, path: str = ROOT_PATH) -> Self: @@ -912,7 +923,7 @@ class Envelope: def __post_init__(self) -> None: for name, value in self._fields(): - _require_at_least(name, value, 0) + _require_count(name, value, 0) _require_ordered("floorMin", self.floor_min, "floorMax", self.floor_max) _require_pair("bufferMin", self.buffer_min, "bufferMax", self.buffer_max) _require_ordered("bufferMin", self.buffer_min, "bufferMax", self.buffer_max) @@ -965,8 +976,8 @@ def __post_init__(self) -> None: _require_identifier("name", self.name) _require_identifier("queuePool", self.queue_pool) _require_identifier("bundle", self.bundle) - _require_at_least("concurrency", self.concurrency, 1) - _require_at_least("maxContainers", self.max_containers, 1) + _require_count("concurrency", self.concurrency, 1) + _require_count("maxContainers", self.max_containers, 1) if self.envelope.floor_max > self.max_containers: raise SchemaError( "envelope.floorMax", diff --git a/packages/sie_placement/tests/test_schema.py b/packages/sie_placement/tests/test_schema.py index eb729e56d..f1dfb3c34 100644 --- a/packages/sie_placement/tests/test_schema.py +++ b/packages/sie_placement/tests/test_schema.py @@ -169,6 +169,29 @@ def test_numbers_built_in_code_must_be_finite(build, field, value): assert caught.value.message.startswith("must be a finite number") +@pytest.mark.parametrize(("value", "described"), [(True, "boolean true"), ("1", "string '1'")]) +def test_numbers_built_in_code_must_be_numbers(value, described): + with pytest.raises(SchemaError) as caught: + Throughput(requests_per_second=value) + assert str(caught.value) == f"requestsPerSecond: must be a number, got {described}" + + +@pytest.mark.parametrize( + ("build", "field"), + [ + (lambda value: ContainerShape(gpu_count=value, cpu_cores=1.0, memory_mib=1024), "gpuCount"), + (lambda value: ServiceLevel(come_alive_p95_s=value), "comeAliveP95S"), + (lambda value: Envelope(floor_min=0, floor_max=value), "floorMax"), + (lambda value: DemandHour(start=datetime(2026, 1, 1, tzinfo=UTC), requests=value), "requests"), + ], +) +@pytest.mark.parametrize(("value", "described"), [(1.5, "number 1.5"), (2.0, "number 2.0"), (True, "boolean true")]) +def test_integers_built_in_code_must_be_integers(build, field, value, described): + with pytest.raises(SchemaError) as caught: + build(value) + assert str(caught.value) == f"{field}: must be an integer, got {described}" + + def test_numbers_reject_booleans(): data = load("price-list.json") data["placements"][0]["regionMultiplier"] = False From 1e781a014bc36b51467090571faf1012e7125e88 Mon Sep 17 00:00:00 2001 From: krisztian-gajdar Date: Fri, 6 Nov 2026 10:43:29 +0100 Subject: [PATCH 16/16] fix(placement): group plan lanes into chart lanes without regard to case - sharedChartLanes compares queuePool, machineProfile and bundle in lowercase, as the chart canonicalizes lane tokens, so two plan lanes whose tokens differ only in case are reported as one chart lane. --- packages/sie_placement/README.md | 9 +++++---- .../sie_placement/src/sie_placement/planner.py | 2 +- packages/sie_placement/tests/test_planner.py | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/sie_placement/README.md b/packages/sie_placement/README.md index 7a8be6e86..768503b2a 100644 --- a/packages/sie_placement/README.md +++ b/packages/sie_placement/README.md @@ -89,9 +89,10 @@ Helm chart: `queuePool`, the `machineProfile` of its `cell`, and `bundle`. override. It is neither the `workers.pools` map key, which names a worker group, nor an SDK logical pool. `bundle` is a key of that worker group's `bundles` map. `name` is the lane's handle inside the plan, and each identity -refers to its lane by that name. Two plan lanes may carry the same three -tokens, and so name one chart lane, which cannot give them separate envelopes -or concurrency; the planner's report lists every such chart lane. +refers to its lane by that name. The chart compares the three tokens without +regard to case. Two plan lanes may carry the same three tokens, and so name one +chart lane, which cannot give them separate envelopes or concurrency; the +planner's report lists every such chart lane. ## Envelope @@ -274,7 +275,7 @@ The report renders as a `placement-report` document: and `unpricedIdentities` lists residents whose demand has no receipt to price it on the lane. - `sharedChartLanes`: every chart lane, by `queuePool`, `machineProfile` and - `bundle`, that more than one plan lane names. + `bundle` in lowercase, that more than one plan lane names. - `measurementRequests`: options that lack evidence, ranked by the saving they could unlock. A profile without a receipt is bounded by price alone: one accelerator at its rate, kept warm or, where the come-alive bound allows, diff --git a/packages/sie_placement/src/sie_placement/planner.py b/packages/sie_placement/src/sie_placement/planner.py index b3e82d23b..8dfa39d35 100644 --- a/packages/sie_placement/src/sie_placement/planner.py +++ b/packages/sie_placement/src/sie_placement/planner.py @@ -1109,7 +1109,7 @@ def _permitted(measured: float) -> int: def _shared_chart_lanes(plan: Plan) -> tuple[SharedChartLane, ...]: grouped: defaultdict[tuple[str, str, str], list[str]] = defaultdict(list) for lane in plan.lanes: - grouped[(lane.queue_pool, lane.cell.machine_profile, lane.bundle)].append(lane.name) + grouped[(lane.queue_pool.lower(), lane.cell.machine_profile.lower(), lane.bundle.lower())].append(lane.name) return tuple( SharedChartLane(queue_pool=pool, machine_profile=profile, bundle=bundle, lanes=tuple(sorted(names))) for (pool, profile, bundle), names in sorted(grouped.items()) diff --git a/packages/sie_placement/tests/test_planner.py b/packages/sie_placement/tests/test_planner.py index 0141707b1..00104fa88 100644 --- a/packages/sie_placement/tests/test_planner.py +++ b/packages/sie_placement/tests/test_planner.py @@ -1394,6 +1394,20 @@ def test_plan_lanes_that_name_one_chart_lane_are_reported(): assert apart.report.shared_chart_lanes == () +def test_plan_lanes_whose_tokens_differ_only_in_case_name_one_chart_lane(): + service_levels = levels(("org/a", WARM), ("org/b", WARM)) + receipts = [receipt(identity=identity) for identity in ("org/a", "org/b")] + result = run(service_levels, receipts, prices=L4_ONLY, bundles={"org/a": "Default"}) + assert {lane.name: lane.bundle for lane in result.plan.lanes} == {"org-a-l4": "Default", "org-b-l4": "default"} + (shared,) = result.report.shared_chart_lanes + assert shared.to_dict() == { + "queuePool": "default", + "machineProfile": "l4", + "bundle": "default", + "lanes": ["org-a-l4", "org-b-l4"], + } + + def test_a_derived_lane_name_never_takes_a_kept_lane_named_with_its_digest(): digest = hashlib.sha256(IDENTITY.encode()).hexdigest() first = single_lane_plan(name="org-model-l4", identity="org/kept")