Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions src/inferrsi/box/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,7 @@ def receipt(command, current, code, *, phase="rejected", details=None) -> dict:
}


def validate_receipt(
command: Command,
data: bytes,
patches: Mapping[str, PatchHistory | tuple[str, ...]],
known_modules: Mapping[str, tuple[str, dict]],
expected_reset: tuple[str, ...],
) -> tuple[dict, Identity]:
def validate_receipt_header(command: Command, data: bytes) -> tuple[dict, Identity]:
value = decode(data)
expected = command.expected
baseline = receipt(command, expected, "ok")
Expand Down Expand Up @@ -225,10 +219,21 @@ def validate_receipt(
or (current.activation_id != expected.activation_id) != advances
):
raise BoxError("conflict", "receipt has an invalid phase or activation transition")
if code in {"ok", "rolled_back"}:
return value, current


def validate_receipt(
command: Command,
data: bytes,
patches: Mapping[str, PatchHistory | tuple[str, ...]],
known_modules: Mapping[str, tuple[str, dict]],
expected_reset: tuple[str, ...],
) -> tuple[dict, Identity]:
value, current = validate_receipt_header(command, data)
if value["code"] in {"ok", "rolled_back"}:
_validate_proof(
command,
code,
value["code"],
value["details"],
patches,
known_modules,
Expand All @@ -242,14 +247,17 @@ def _require(verified: bool) -> None:
raise BoxError("conflict", "receipt does not prove the requested result")


def _hash(value: object) -> bool:
def is_sha256(value: object) -> bool:
return (
isinstance(value, str)
and len(value) == 64
and all(character in "0123456789abcdef" for character in value)
)


_hash = is_sha256


def _valid_bindings(value: object) -> bool:
return isinstance(value, dict) and all(
isinstance(name, str)
Expand Down
132 changes: 101 additions & 31 deletions src/inferrsi/box/serving.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from typing import Protocol
from uuid import uuid4

from .patch import PatchSpec, install_specs
from .protocol import (
MAX_MESSAGE_BYTES,
MUTATIONS,
Expand All @@ -24,6 +25,9 @@
encode,
fields,
identifier,
is_sha256,
source_hash,
validate_receipt_header,
)


Expand Down Expand Up @@ -98,8 +102,10 @@ def __init__(
"loaded_root": str(loaded_root),
"loaded_revision": loaded_revision,
}
self._parent_hash = parent_hash
self._candidate = {"revision": loaded_revision, "artifact_id": "sha256:" + parent_hash}
self._baseline = {"revision": loaded_revision, "artifact_id": "sha256:" + parent_hash}
self._candidate = dict(self._baseline)
self._stack: list[str] = []
self._candidates: dict[str, dict[str, str]] = {}
self._condition = Condition()
self._blocked = False
self._isolated = False
Expand Down Expand Up @@ -161,50 +167,114 @@ def _wait(self, active, deadline):
self._isolated = self._blocked = True
raise BoxError("in_doubt", "serving admission has been isolated")

@staticmethod
def _validate_install(payload: dict) -> PatchSpec:
_, edits = install_specs(payload)
if "edits" in payload or len(edits) != 1 or edits[0].role != "worker":
raise BoxError("invalid_request", "serving install requires a single worker patch")
if edits[0].candidate_revision is None:
raise BoxError("invalid_request", "serving install requires candidate provenance")
return edits[0]

def _fail_in_doubt(self, reason: str) -> None:
self._isolated = self._blocked = True
raise BoxError("in_doubt", reason)

def _transaction(self, wire):
command = Command.parse(wire)
install_patch = None
with self._condition:
if self._blocked or self._stage is not None:
raise BoxError("in_doubt", "cannot control an unverified serving activation")
if command.expected != self.endpoint.identity:
raise BoxError("stale_instance", "Box control did not bind the live activation")
if command.operation == "install":
install_patch = self._validate_install(command.payload)
self._blocked = True
# An engine check must witness only its own request, even on a busy frontend.
self._wait(lambda: self._active, command.deadline)
result = decode(self.endpoint.handle(wire))
try:
raw = self.endpoint.handle(wire)
except BaseException:
with self._condition:
self._isolated = self._blocked = True
raise
with self._condition:
identity = Identity.parse(result.get("identity"))
try:
result, identity = validate_receipt_header(command, raw)
except BoxError as error:
self._isolated = self._blocked = True
raise BoxError("in_doubt", str(error)) from error
if identity != self.endpoint.identity:
raise BoxError("in_doubt", "Box reply and worker identity disagree")
if result["phase"] in ("committed", "rolled_back"):
prior = command.expected
if (
command.operation not in MUTATIONS
or identity.instance_id != prior.instance_id
or identity.lease_id != prior.lease_id
or identity.participant != prior.participant
or identity.generation != prior.generation + 1
or identity.activation_id == prior.activation_id
):
raise BoxError("in_doubt", "Box mutation did not prove the next activation")
elif result["code"] != "in_doubt" and identity != command.expected:
raise BoxError("in_doubt", "Box observation changed the worker activation")
details = result["details"]
if command.operation in MUTATIONS and result["code"] == "ok":
self._fail_in_doubt("Box reply and worker identity disagree")
code, details = result["code"], result["details"]
if code == "in_doubt":
self._fail_in_doubt("Box command outcome is in doubt")
if command.operation in MUTATIONS and code == "rolled_back":
if details.get("patch_stack") != self._stack:
self._fail_in_doubt("Box rollback did not preserve the patch stack")
elif command.operation in ("install", "uninstall") and code == "ok":
stack = details.get("patch_stack")
if not isinstance(stack, list) or not all(isinstance(item, str) for item in stack):
self._fail_in_doubt("Box mutation did not prove its patch stack")
if command.operation == "install":
revision = identifier(details["candidate_revision"])
sha256 = details["source_hashes"][details["module"]]
self._candidate = {"revision": revision, "artifact_id": "sha256:" + sha256}
elif command.operation == "uninstall" and not details["patch_stack"]:
self._candidate = {
"revision": self.loaded["loaded_revision"],
"artifact_id": "sha256:" + self._parent_hash,
sources = details.get("source_hashes")
expected_sha = source_hash(install_patch.source)
if (
install_patch.patch_id in self._stack
or details.get("patch_id") != install_patch.patch_id
or details.get("candidate_revision") != install_patch.candidate_revision
or details.get("module") != install_patch.module
or not isinstance(sources, dict)
or not all(
isinstance(name, str) and is_sha256(digest)
for name, digest in sources.items()
)
or sources.get(install_patch.module) != expected_sha
or stack != [*self._stack, install_patch.patch_id]
):
self._fail_in_doubt("Box install did not prove candidate provenance")
candidate = {
"revision": install_patch.candidate_revision,
"artifact_id": "sha256:" + expected_sha,
}
if (
not self._isolated and result["code"] != "in_doubt"
and monotonic() < command.deadline
):
self._stack = list(stack)
self._candidates[install_patch.patch_id] = candidate
self._candidate = dict(candidate)
else:
if set(command.payload) != {"patch_id"}:
self._fail_in_doubt("Box uninstall did not carry a valid patch target")
requested = command.payload["patch_id"]
if requested is None:
if not self._stack:
self._fail_in_doubt("Box uninstall succeeded on an empty patch stack")
expected_stack = self._stack[:-1]
elif isinstance(requested, str) and requested in self._stack:
expected_stack = self._stack[: self._stack.index(requested)]
else:
self._fail_in_doubt("Box uninstall did not match an installed patch")
if stack != expected_stack:
self._fail_in_doubt("Box uninstall left an unexpected patch stack")
sources = details.get("source_hashes")
if sources is not None and (
not isinstance(sources, dict)
or not all(
isinstance(name, str) and is_sha256(digest)
for name, digest in sources.items()
)
):
self._fail_in_doubt("Box uninstall did not prove valid source hashes")
self._stack = list(stack)
self._candidates = {pid: self._candidates[pid] for pid in self._stack}
self._candidate = (
dict(self._baseline)
if not self._stack
else dict(self._candidates[self._stack[-1]])
)
if not self._isolated and monotonic() < command.deadline:
self._blocked = False
else:
self._isolated = True
return result

def _begin(self, message):
Expand Down
Loading
Loading