"""Checked JSON messages at the kernel and remote connection boundaries. The `TypedDict` classes below are the wire contract: producers and consumers keep using plain dictionaries. `parse_incoming` and `parse_remote` validate an untrusted dictionary against that contract before it reaches the event loop with the strict checks below, so a JSON number never stands in for a boolean, a boolean never stands in for an integer, and numeric strings are never coerced. Unknown fields are kept: several frames carry fields their `TypedDict` only partly describes (a `done` frame's result, a job view's rows), and dropping them would change the wire. Validation uses only the standard library. Importing this module, as every kernel bootstrap does, and validating its first frame therefore do not pay for Pydantic's import or schema build; Pydantic stays bundled in the kernel environment for cells that import it, not for this wire. Importing this module needs no third-party package, so a bootstrap can import it before the managed environment exists. Validation errors hide their input values: a frame can carry cell source or a token, and neither may appear in an error string. """ from collections.abc import Callable from typing import Literal, NotRequired, TypedDict, cast class Execute(TypedDict): type: Literal["execute"] id: str code: str durable: NotRequired[bool] snapshots: NotRequired[bool] max_edge: NotRequired[int] text_only: NotRequired[bool] media: NotRequired[list[str]] max_fps: NotRequired[float | None] clip_room: NotRequired[int] max_clip_bytes: NotRequired[int] timeout_ms: NotRequired[int] class HostSuccess(TypedDict): ok: Literal[True] value: object class HostFailure(TypedDict): ok: Literal[False] code: str message: str HostReply = HostSuccess | HostFailure class Reply(TypedDict): type: Literal["reply"] id: str value: HostReply class Interrupt(TypedDict): type: Literal["interrupt"] id: str # `memory` is the kernel's own, from its memory guard; the owner sends the others. reason: NotRequired[Literal["deadline", "cancelled", "memory"]] class Shutdown(TypedDict): type: Literal["shutdown"] Invoke = TypedDict( "Invoke", { "type": Literal["invoke"], "id": str, "name": NotRequired[str], "target": NotRequired[dict[str, str]], "args": NotRequired[list[object]], "kwargs": NotRequired[dict[str, object]], "await": NotRequired[bool], # Calls on this call's result, or on an earlier one of these, made # right after it: each an invoke without `type`, targeting a pending id. "then": NotRequired[list["Chained"]], }, ) class Chained(TypedDict): id: str name: str target: dict[str, str] args: NotRequired[list[object]] kwargs: NotRequired[dict[str, object]] class Introspect(TypedDict): type: Literal["introspect"] id: str class Release(TypedDict): type: Literal["release"] handle: str class State(TypedDict): """Save the namespace to disk, or revive it from an earlier save.""" type: Literal["snapshot", "restore"] id: str path: str originals: NotRequired[str] class JobStop(TypedDict): """Stop a background job.""" type: Literal["job_stop"] id: str class JobList(TypedDict): """Ask for every job the kernel knows, finished ones included.""" type: Literal["job_list"] id: str class JobRead(TypedDict): """Read one page of a job's output; without `offset`, the page that ends it.""" type: Literal["job_read"] id: str job: str offset: NotRequired[int] limit: int class CellClaim(TypedDict): """Ask for a cell's result after a restart; a running one is backgrounded.""" type: Literal["cell_claim"] id: str cell: str Incoming = ( Execute | Reply | Interrupt | Shutdown | Invoke | Introspect | Release | State | JobStop | JobList | JobRead | CellClaim ) class SavedCell(TypedDict): id: str source: str started: bool parent: str | None finished: bool class Ready(TypedDict): type: Literal["ready"] pid: int pgid: int | None leader: str | None class StartupError(TypedDict): type: Literal["startup_error"] message: str class RemoteCall(TypedDict): type: Literal["call"] id: str method: str args: dict[str, object] class InvocationError(TypedDict): ename: str evalue: str traceback: list[str] class MirrorState(TypedDict, total=False): job: str | None seen: int tail: str tail_bytes: int exit_code: int | None timed_out: bool duration: float | None class Invoked(TypedDict): type: Literal["invoked"] id: str ok: bool value: NotRequired[object] handle: NotRequired[str] state: NotRequired[MirrorState] error: NotRequired[InvocationError] cancelled: NotRequired[bool] class RemoteHandle(TypedDict): id: str repr: str class Introspected(TypedDict): type: Literal["introspected"] id: str names: list[str] handles: list[RemoteHandle] class Mirror(MirrorState): type: Literal["mirror"] handle: str class RemoteEvent(TypedDict): type: Literal["job_start", "job", "trace", "done"] id: str service: NotRequired[bool] # job_start: nothing waits on the job's end class RemoteCleanup(TypedDict): type: Literal["cleanup"] module: str class JobStopReply(TypedDict): type: Literal["job_stop"] id: str ok: bool error: NotRequired[str] code: NotRequired[str] class JobViewReply(TypedDict): """The answer to a `job_list` or `job_read`: its fields, or `code` and `error`.""" type: Literal["job_list", "job_read"] id: str ok: bool code: NotRequired[str] error: NotRequired[str] class CellClaimReply(TypedDict): """The answer to a `cell_claim`: the cell's done frame, if it knows one.""" type: Literal["cell_claim"] id: str ok: bool done: NotRequired[dict[str, object]] class Blob(TypedDict): """One part of a clip a cell result names by digest; its bytes follow the envelope in a binary packet (albedo_link.send_blob).""" type: Literal["blob"] id: str digest: str part: int parts: int RemoteMessage = ( Ready | StartupError | RemoteCall | Invoked | Introspected | Mirror | RemoteEvent | RemoteCleanup | JobStopReply | JobViewReply | CellClaimReply | Blob ) class _CellsObservation(TypedDict): """A kernel's cell-count observation: counted by its owner, never typed. It has no `RemoteMessage` fields, but a remote kernel publishes it to the same reader, so remote validation accepts and passes it through. """ type: Literal["cells"] # What `parse_remote` accepts: the typed replies plus the count observation. _RemoteWire = RemoteMessage | _CellsObservation # Strict field checks: a bool is not an int, a float is not an int, and no # string is coerced to either. A float field accepts an int, as JSON numbers # do not distinguish them for the one duration on the wire. _FieldCheck = str def _is_int(value: object) -> bool: return isinstance(value, int) and not isinstance(value, bool) def _is_float(value: object) -> bool: return isinstance(value, float) or _is_int(value) def _is_str_dict(value: object) -> bool: return isinstance(value, dict) and all( isinstance(key, str) and isinstance(item, str) for key, item in value.items() ) def _is_str_key_dict(value: object) -> bool: return isinstance(value, dict) and all(isinstance(key, str) for key in value) def _is_str_list(value: object) -> bool: return isinstance(value, list) and all(isinstance(item, str) for item in value) _CHECKS: dict[str, Callable[[object], bool]] = { "str": lambda value: isinstance(value, str), "bool": lambda value: isinstance(value, bool), "int": _is_int, "float": _is_float, "int_or_none": lambda value: value is None or _is_int(value), "str_or_none": lambda value: value is None or isinstance(value, str), "float_or_none": lambda value: value is None or _is_float(value), "list": lambda value: isinstance(value, list), "dict": _is_str_key_dict, "str_dict": _is_str_dict, "str_list": _is_str_list, "any": lambda value: True, } def _object(value: object, context: str) -> dict[str, object]: if not isinstance(value, dict) or not all(isinstance(key, str) for key in value): raise ValueError(f"{context}: expected an object") return cast(dict[str, object], value) def _field( message: dict[str, object], field: str, check: _FieldCheck, context: str, *, optional: bool = False, ) -> None: if field not in message: if optional: return raise ValueError(f"{context}.{field}: required field") if not _CHECKS[check](message[field]): raise ValueError(f"{context}.{field}: invalid field type") def _fields( message: dict[str, object], context: str, required: dict[str, _FieldCheck], optional: dict[str, _FieldCheck] | None = None, ) -> None: for field, check in required.items(): _field(message, field, check, context) for field, check in (optional or {}).items(): _field(message, field, check, context, optional=True) def _envelope(value: object) -> tuple[dict[str, object], str]: message = _object(value, "message") _field(message, "type", "str", "message") return message, cast(str, message["type"]) def _validate_host_reply(value: object) -> None: reply = _object(value, "reply.value") _field(reply, "ok", "bool", "reply.value") if reply["ok"]: _field(reply, "value", "any", "reply.value") else: _fields(reply, "reply.value", {"code": "str", "message": "str"}) def _validate_mirror_state(value: object, context: str) -> None: state = _object(value, context) _fields( state, context, {}, { "job": "str_or_none", "seen": "int", "tail": "str", "tail_bytes": "int", "exit_code": "int_or_none", "timed_out": "bool", "duration": "float_or_none", }, ) def _validate_invocation_error(value: object, context: str) -> None: error = _object(value, context) _fields(error, context, {"ename": "str", "evalue": "str", "traceback": "str_list"}) def parse_incoming(value: object) -> Incoming: """Validate a kernel request before it reaches the event loop.""" message, kind = _envelope(value) if kind == "execute": _fields( message, kind, {"id": "str", "code": "str"}, { "durable": "bool", "snapshots": "bool", "max_edge": "int", "text_only": "bool", "media": "str_list", "max_fps": "float_or_none", "clip_room": "int", "max_clip_bytes": "int", "timeout_ms": "int", }, ) elif kind == "reply": _field(message, "id", "str", kind) _validate_host_reply(message.get("value")) elif kind == "interrupt": _field(message, "id", "str", kind) if "reason" in message and message["reason"] not in ( "deadline", "cancelled", "memory", ): raise ValueError("interrupt.reason: expected deadline, cancelled or memory") elif kind == "shutdown": pass elif kind == "invoke": _fields( message, kind, {"id": "str"}, {"name": "str", "args": "list", "kwargs": "dict", "await": "bool"}, ) if "target" in message: # A target names exactly one live handle or one pending call; the # dictionary shape alone cannot say that. target = message["target"] if not _CHECKS["str_dict"](target): raise ValueError("invoke.target: invalid field type") if set(cast(dict[str, object], target)) not in ( {"handle"}, {"pending"}, ): raise ValueError( "invoke.target: expected exactly one handle or pending" ) if "then" in message: # Each chained call names the call or earlier chained call it # follows, so the receiver can make them in order with no wait. chain = message["then"] if not isinstance(chain, list): raise ValueError("invoke.then: invalid field type") known = {cast(str, message["id"])} for entry in cast(list[object], chain): if not isinstance(entry, dict): raise ValueError("invoke.then: invalid field type") entry = cast(dict[str, object], entry) _fields( entry, "invoke.then", {"id": "str", "name": "str", "target": "str_dict"}, {"args": "list", "kwargs": "dict"}, ) target = cast(dict[str, object], entry["target"]) if set(target) != {"pending"} or target["pending"] not in known: raise ValueError( "invoke.then.target: expected a pending id this frame carries" ) known.add(cast(str, entry["id"])) elif kind == "introspect": _field(message, "id", "str", kind) elif kind == "release": _field(message, "handle", "str", kind) elif kind in {"snapshot", "restore"}: _fields(message, kind, {"id": "str", "path": "str"}, {"originals": "str"}) elif kind in {"job_stop", "job_list"}: _field(message, "id", "str", kind) elif kind == "job_read": _fields( message, kind, {"id": "str", "job": "str", "limit": "int"}, {"offset": "int"}, ) elif kind == "cell_claim": _fields(message, kind, {"id": "str", "cell": "str"}) else: raise ValueError("message.type: unknown message type") return cast(Incoming, message) def parse_remote(value: object) -> RemoteMessage: """Validate remote replies and the event fields the owner consumes.""" message, kind = _envelope(value) if kind == "ready": _fields( message, kind, {"pid": "int", "pgid": "int_or_none", "leader": "str_or_none"}, ) elif kind == "startup_error": _field(message, "message", "str", kind) elif kind == "call": _fields(message, kind, {"id": "str", "method": "str", "args": "dict"}) elif kind == "invoked": _fields( message, kind, {"id": "str", "ok": "bool"}, {"handle": "str", "cancelled": "bool"}, ) if "state" in message: _validate_mirror_state(message["state"], "invoked.state") if "error" in message: _validate_invocation_error(message["error"], "invoked.error") # Two relationships the dictionary shape alone cannot say: a failed # call carries its error, and a successful one carries a value or a # handle for the value it kept. if ("error" in message or not message["ok"]) and not isinstance( message.get("error"), dict ): raise ValueError("invoked.error: expected an object") if message["ok"] and "handle" not in message and "value" not in message: raise ValueError("invoked.value: required without handle") elif kind == "introspected": _fields(message, kind, {"id": "str", "names": "str_list", "handles": "list"}) for item in cast(list[object], message["handles"]): handle = _object(item, "introspected.handles") _fields(handle, "introspected.handles", {"id": "str", "repr": "str"}) elif kind == "mirror": _field(message, "handle", "str", kind) _validate_mirror_state(message, kind) elif kind == "cleanup": _field(message, "module", "str", kind) elif kind == "job_stop": _fields( message, kind, {"id": "str", "ok": "bool"}, {"error": "str", "code": "str"} ) elif kind in {"job_list", "job_read"}: _fields( message, kind, {"id": "str", "ok": "bool"}, {"code": "str", "error": "str"} ) elif kind == "cell_claim": _fields(message, kind, {"id": "str", "ok": "bool"}, {"done": "dict"}) elif kind == "blob": _fields( message, kind, {"id": "str", "digest": "str", "part": "int", "parts": "int"} ) elif kind in {"job_start", "job", "trace", "done"}: _fields(message, kind, {"id": "str"}, {"service": "bool"}) elif kind == "cells": # A remote kernel publishes its cell count for a local owner; over a # remote connection nothing reads it, so it passes through. pass else: raise ValueError("message.type: unknown message type") return cast(RemoteMessage, message)