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..768503b2a --- /dev/null +++ b/packages/sie_placement/README.md @@ -0,0 +1,315 @@ +# 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, 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 +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 +``` + +## 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 the fields below, 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`. +`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 + +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. 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 + +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. + +## 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. 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 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 | +| --- | --- | +| `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 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 + 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. 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. 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` + 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, 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. + +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; 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 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, +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 + +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. + +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 + +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. A lane carried from the current plan keeps its envelope, capped by the +ceiling. + +### Report + +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, 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`) 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, + `current-unmeasured` when it keeps a current placement that lacks evidence + 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, + and `unpricedIdentities` lists residents whose demand has no receipt to price + it on the lane. +- `sharedChartLanes`: every chart lane, by `queuePool`, `machineProfile` and + `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, + 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 + 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 + 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: + `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. +- `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`. + +## 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/planner.py b/packages/sie_placement/src/sie_placement/planner.py new file mode 100644 index 000000000..8dfa39d35 --- /dev/null +++ b/packages/sie_placement/src/sie_placement/planner.py @@ -0,0 +1,1189 @@ +"""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, + SharedChartLane, + UnplacedReason, +) +from sie_placement.schema import ( + BOOT_WARMTHS, + 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 +BOOT_PERCENTILE = 95 +BOOT_PERCENTILE_MIN_ROWS = 20 +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): + 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 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: + 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 + 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 + host: str | None = None + + @property + def feasible(self) -> bool: + return not self.blockers + + @property + 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( + 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, + lane=self.host, + ) + + +@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 + held: float | None = None + gaps: tuple[MeasurementRequest, ...] = () + unpriced: bool = False + + @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_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): + return UnplacedReason.WARM_BOUND_UNDECLARED + return UnplacedReason.WARM_BOUND_MISSED + + +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, width: int = 8) -> str: + return hashlib.sha256(value.encode()).hexdigest()[:width] + + +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 _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): + return 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: + 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=_come_alive(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 _runs_on(receipt: Receipt, lane: PlanLane) -> bool: + return ( + 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: + 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: + 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.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} + 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]] = {} + self.current_lanes: dict[str, PlanLane] = {} + 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 + } + 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)) + + 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 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 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 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) + 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 (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 + ) + + 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 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: + 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 = self.resident_hours(lane, identity, 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 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, + 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, + 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=self.is_current(identity, receipt, Warmth.PINNED), + ) + ) + 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=self.is_current(identity, receipt, warmth), + ) + ) + for host in hosts: + if not _runs_on(receipt, host): + continue + 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) + 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 + unpriced = False + 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 + unpriced = cost is None + 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( + 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, + unpriced=unpriced, + ) + + 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): + 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 baseline is None else baseline - 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 + + @staticmethod + def boot_requests(choice: _Choice, baseline: float | None) -> list[MeasurementRequest]: + if baseline is None: + return [] + return [ + replace(request, saving_bound=baseline - request.cost_bound) + for request in choice.boot_requests + if baseline - request.cost_bound > 0 + ] + + 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_savings=False).report.monthly_cost + + 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, **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( + 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]: + baseline = choice.baseline + bound = choice.level.come_alive_p95_s + if baseline is None or bound is None: + return [] + best: dict[tuple[Cell, ContainerShape, Warmth], _Option] = {} + for option in choice.options: + if option.warmth is Warmth.PINNED or option.cost >= baseline: + 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(): + permitted = _permitted(option.come_alive_s) + saving = self.saving_when_loosened(choice.identity, {"comeAliveP95S": permitted}, written, total) + 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, + 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=under, + permitted_bound_s=permitted, + saving_at_permitted_bound=saving, + ) + ) + return levers + + 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 < baseline] + if not cheaper: + return None + 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]: + 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 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 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: + 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, *, 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 = { + choice.identity: self.current[choice.identity] + for choice in choices + 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} + 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( + 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) + 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: + 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, baseline, new_plan, total) + reports.append( + 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( + placement=self.parameters.placement, + currency=self.price_list.currency, + parameters=self.parameters.to_dict(), + 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( + 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, + 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) + + def _identity_report( + self, + choice: _Choice, + names: Mapping[str, str], + 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( + 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 = choice.unplaced_reason + if choice.identity in kept: + entry, lane = kept[choice.identity] + return replace( + report, + status=IdentityStatus.KEPT, + lane=entry.lane, + 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 + return replace( + 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=next_cheaper, + ) + + 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) + hours = self.parameters.hours_per_month + reports: list[LaneReport] = [] + costs: dict[str, float] = {} + for lane in plan.lanes: + 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=hosted, + hourly_cost=hourly, + 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), costs + + +def _saving(total: float, replanned: float) -> float: + saving = total - replanned + 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: + 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()) + if len(names) > 1 + ) + + +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), + request.lane or "", + request.concurrency or 0, + ) + + +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..585f5f8d0 --- /dev/null +++ b/packages/sie_placement/src/sie_placement/report.py @@ -0,0 +1,372 @@ +"""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" + WARM_BOUND_UNDECLARED = "warm-bound-undeclared" + CURRENT_UNMEASURED = "current-unmeasured" + CURRENT_UNPRICED = "current-unpriced" + + +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 | None + measured: float | None + + def to_dict(self) -> dict[str, object]: + return _compact({"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 + lane: str | 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, + "lane": self.lane, + "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 + 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( + { + "identity": self.identity, + "status": self.status.value, + "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(), + "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 = 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( + { + "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 + cell: Cell + measure: tuple[Measurement, ...] + warmth: Warmth + reason: RequestReason + 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( + { + "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, + "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] + 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, ...] + refusals: tuple[Refusal, ...] + identity_changes: tuple[IdentityChange, ...] + lane_changes: tuple[LaneChange, ...] + warm_bound_undeclared: tuple[str, ...] = () + + @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 + + 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), + "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), + "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], + "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 new file mode 100644 index 000000000..763938533 --- /dev/null +++ b/packages/sie_placement/src/sie_placement/schema.py @@ -0,0 +1,1099 @@ +"""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", re.ASCII) + + +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 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]: + 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 _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)}") + 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)}") + 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 + + 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 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)) + + 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_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: + 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_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_number(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 None: + return + _require_number(name, value) + if 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_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") + + 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_count("gpuCount", self.gpu_count, 1) + _require_positive("cpuCores", self.cpu_cores) + _require_count("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_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_count("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_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: + 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 + borrowed: bool = False + + 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), + borrowed=reader.optional_boolean("borrowed") is True, + source=reader.child("source", SourceRef.from_dict), + ) + + def to_dict(self) -> dict[str, object]: + 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) +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_count("requests", self.requests, 0) + _require_count("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_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) + _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 + queue_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("queuePool", self.queue_pool) + _require_identifier("bundle", self.bundle) + _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", + 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"), + queue_pool=reader.string("queuePool"), + 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, + "queuePool": self.queue_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..ed9a2f5fa --- /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", + "queuePool": "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", + "queuePool": "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/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..303a4ed79 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/expected-plan.json @@ -0,0 +1,114 @@ +{ + "kind": "placement-plan", + "schemaVersion": 1, + "placement": "us-central1", + "lanes": [ + { + "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": "default-l4-default", + "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..076b55a12 --- /dev/null +++ b/packages/sie_placement/tests/fixtures/planner/expected-report.json @@ -0,0 +1,630 @@ +{ + "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": 9139.6, + "unpricedLanes": [ + "default-l4-default" + ] + }, + "identities": [ + { + "identity": "BAAI/bge-m3", + "status": "placed", + "serviceLevel": { + "comeAliveP95S": 0, + "warmP99Ms": 250, + "queueWaitP99Ms": 500 + }, + "demandRequests": 180000, + "lane": "default-l4-default", + "monthlyCost": 759.2, + "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": 0.0, + "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", + "monthlyCost": 47.45, + "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", + "monthlyCost": 382.03, + "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", + "monthlyCost": 759.2, + "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-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, + "unpricedIdentities": [ + "intfloat/e5-base-v2" + ] + }, + { + "name": "qwen-qwen3-8b-a100-80gb", + "identities": [ + "Qwen/Qwen3-8B" + ], + "hourlyCost": 3.14, + "monthlyCost": 382.03, + "floorMonthlyCost": 0.0, + "envelopeMaxMonthlyCost": 4584.4 + }, + { + "name": "qwen-qwen3-embedding-4b-l4", + "identities": [ + "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", + "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": "l4", + "gpuProduct": "NVIDIA-L4" + }, + "containerShape": { + "gpuCount": 1, + "cpuCores": 4, + "memoryMiB": 16384 + }, + "concurrency": 16, + "lane": "default-l4-default", + "measure": [ + "receipt" + ], + "warmth": "pinned", + "reason": "unmeasured", + "costBound": 759.2 + }, + { + "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 + }, + { + "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": [ + { + "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 + } + ], + "queueWaitUnattained": [ + "BAAI/bge-m3", + "BAAI/bge-m3:sparse", + "intfloat/e5-base-v2" + ], + "warmBoundUndeclared": [], + "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: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-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/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_levers.py b/packages/sie_placement/tests/test_levers.py new file mode 100644 index 000000000..feed8adf7 --- /dev/null +++ b/packages/sie_placement/tests/test_levers.py @@ -0,0 +1,306 @@ +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, + Envelope, + IdentityServiceLevel, + MachineProfilePrice, + Operation, + Percentiles, + Placement, + Plan, + PlanIdentity, + PlanLane, + 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, 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=rps), + 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, requests=10): + 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=requests) for hour in range(hours) + ), + ) + for identity in identities + ), + ) + + +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), 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): + 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 + + +@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) + + +@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 new file mode 100644 index 000000000..00104fa88 --- /dev/null +++ b/packages/sie_placement/tests/test_planner.py @@ -0,0 +1,1935 @@ +from __future__ import annotations + +import hashlib +import json +import math +import random +from dataclasses import replace +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" +ANY_P99_MS = 1000 +WARM = ServiceLevel(warm_p99_ms=ANY_P99_MS) + +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: + 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))) + + +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, + *, + others=(), + concurrency=8, + max_containers=2, + envelope=None, +) -> 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=concurrency, + max_containers=max_containers, + envelope=envelope or Envelope(floor_min=floor, floor_max=max(floor, 1)), + ), + ), + identities=tuple( + PlanIdentity(identity=resident, lane=name, warmth=warmth) for resident in sorted((identity, *others)) + ), + ) + + +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")) + + +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 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 + ), + ) + + +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 + ) + 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_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 + ) + 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_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), + [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) + + +@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) + 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_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) + assert report.chosen.warmth is Warmth.PINNED + 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) + 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") + 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), + ) + assert report.next_cheaper.saving == pytest.approx(2 * MONTH) + + +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, 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)] + 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),) + + +@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 + + +@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) + 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(): + 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) + 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"], + } + + +@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) + (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),), ()), + (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): + 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: + 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(): + 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", 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", 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} + 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, 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" + 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_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, buffer_containers=2) + (lane,) = result.plan.lanes + 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_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 + + +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) + + +@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( + 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 + + +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"), + [ + (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( + (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", 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", 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] + 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", 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 + 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_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") + 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, WARM), + ("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", WARM), ("org/generate", WARM)) + 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, 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),) + 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 + 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 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"] + 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 + ) + + +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_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) + 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 + + +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 + 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 + 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] + 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) + 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) + + +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(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))] + 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} + 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) + 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 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) + 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) + 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 diff --git a/packages/sie_placement/tests/test_schema.py b/packages/sie_placement/tests/test_schema.py new file mode 100644 index 000000000..2902e7ff9 --- /dev/null +++ b/packages/sie_placement/tests/test_schema.py @@ -0,0 +1,616 @@ +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, + MachineProfilePrice, + Operation, + Percentiles, + Placement, + Plan, + PlanIdentity, + PlanLane, + PriceList, + Receipt, + SchemaError, + ServiceLevel, + ServiceLevels, + Throughput, + 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, 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 + error = schema_error(Receipt.from_dict, data) + assert error.path == "$.throughput.requestsPerSecond" + 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") + + +@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 + 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_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" + 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", + "٢٠٢٦-11-02T09: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 + + +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"), + [ + ({"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", + queue_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"