Files
NODEDC_MISSION_CORE/src/k1link/perception/streaming_ingress.py
T

329 lines
14 KiB
Python

"""One controller-supplied IPC socket feeding the common streaming lifecycle.
No listener, acquisition, archive reader, model RPC or network authentication.
An explicitly resumable runtime preserves its resident lease on disconnect;
the controller supplies a new input epoch/socket and the adapter resets decoder
and temporal state. The historical non-resumable diagnostic remains supported.
The synchronous consumer is a trusted adapter: raw events are borrowed for that
call only. It must reserve decoder scratch before allocation and retain decoded
work only through the common mailbox. Slow/failed consumers fail this stream;
they do not create another buffering queue.
"""
from __future__ import annotations
import select
import socket
import threading
import time
from collections import Counter
from collections.abc import Callable
from contextlib import suppress
from hashlib import sha256
from typing import Any
from k1link.compute.live_perception import LiveIngressEvent
from . import streaming_wire as wire
from .realtime_contract import StreamStart
from .streaming_continuity import StreamSuspended
from .streaming_lifecycle import StreamingLifecycle
class InputInterrupted(wire.StreamWireError):
"""Transport unavailable, not malformed model data or an ownership loss."""
class StreamingIngress:
def __init__(
self,
connection: socket.socket,
runtime: StreamingLifecycle,
session_id: str,
session_generation: int,
consume: Callable[[LiveIngressEvent], None],
notice: Callable[[dict[str, Any]], None],
*,
fragment_timeout: float = 0.25,
idle_timeout: float = 2.0,
input_epoch: StreamStart | None = None,
) -> None:
if not 0 < fragment_timeout <= 2 or not 0 < idle_timeout <= 30:
raise ValueError("invalid bounded ingress timeouts")
wire.identifier(session_id)
wire.decimal(session_generation)
if session_generation < 1:
raise ValueError("invalid acquisition generation")
self.connection, self.runtime = connection, runtime
connection.setblocking(False)
self.session_id, self.session_generation = session_id, session_generation
self.consume, self.notice = consume, notice
self.fragment_timeout, self.idle_timeout = fragment_timeout, idle_timeout
self.input_epoch = input_epoch or runtime.start
self.binding = wire.binding(self.input_epoch)
self.opened = False
self.error: str | None = None
self.terminal: str | None = None
self.counts: Counter[str] = Counter()
self.last_ingress_sequence = 0
self.channel_sequences: dict[str, tuple[str, int, int]] = {}
self.camera_initialized = False
self.thread = threading.Thread(
target=self._serve, name="perception-binary-ingress", daemon=True
)
runtime.register_ingress(self.thread, self.input_epoch)
def start(self) -> None:
self.runtime.check_input(self.input_epoch, synchronizing=True)
self.thread.start()
def join(self, timeout: float = 1.0) -> bool:
self.thread.join(timeout=timeout)
return not self.thread.is_alive()
def _check(self, deadline: float) -> None:
self.runtime.check_input(self.input_epoch, synchronizing=True)
if time.monotonic() >= deadline:
raise InputInterrupted("ingress deadline exceeded")
def _read_into(self, target: memoryview, deadline: float) -> None:
offset = 0
while offset < len(target):
self._check(deadline)
if not select.select(
[self.connection], [], [], min(0.05, max(0, deadline - time.monotonic()))
)[0]:
continue
try:
read = self.connection.recv_into(target[offset:])
except BlockingIOError:
continue
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError) as exc:
raise InputInterrupted("input connection lost") from exc
if read == 0:
raise InputInterrupted("unexpected EOF without explicit End")
self.counts["wire_bytes"] += read
offset += read
self._check(deadline)
def _header(self, deadline: float) -> tuple[int, dict[str, Any]]:
prefix = bytearray(wire.PREFIX.size)
self._read_into(memoryview(prefix), deadline)
magic, kind, size = wire.PREFIX.unpack(prefix)
if (
magic != wire.MAGIC
or kind not in (wire.OPEN, wire.FRAGMENT, wire.END, wire.CANCEL, wire.GAP)
or not 0 < size <= wire.MAX_HEADER
):
raise wire.StreamWireError("invalid frame prefix or header size")
raw = bytearray(size)
self._read_into(memoryview(raw), deadline)
return kind, wire.parse_header(raw)
def _bound(self, header: dict[str, Any]) -> None:
if header.get("binding") != self.binding:
if self.runtime.continuity is not None:
raise StreamSuspended("obsolete packet from another input epoch")
raise wire.StreamWireError("frame belongs to another StreamStart")
self.runtime.check_input(self.input_epoch, synchronizing=True)
def _fragment(self, header: dict[str, Any]) -> tuple[dict[str, Any], int, int, int]:
if set(header) != {
"binding",
"event",
"total_bytes",
"offset",
"fragment_bytes",
"payload_sha256",
"fragment_sha256",
}:
raise wire.StreamWireError("fragment fields changed")
self._bound(header)
event = wire.validate_event_metadata(header["event"])
if (
event["session_id"] != self.session_id
or event["session_generation"] != self.session_generation
):
raise wire.StreamWireError("event acquisition binding changed")
total, offset, size = (header[x] for x in ("total_bytes", "offset", "fragment_bytes"))
if any(type(x) is not int for x in (total, offset, size)) or not (
0 < total <= wire.PAYLOAD_LIMITS[event["modality"]]
and 0 <= offset < total
and 0 < size <= wire.MAX_FRAGMENT
and size == min(wire.MAX_FRAGMENT, total - offset)
):
raise wire.StreamWireError("invalid fragment length or offset")
wire.digest(header["payload_sha256"])
wire.digest(header["fragment_sha256"])
return event, total, offset, size
def _observation(self, first: dict[str, Any], deadline: float) -> None:
event, total, offset, size = self._fragment(first)
modality = event["modality"]
if offset != 0 or event["ingress_sequence"] <= self.last_ingress_sequence:
raise wire.StreamWireError("duplicate, out-of-order or incomplete observation")
previous = self.channel_sequences.get(modality)
if previous and (
event["source_id"] != previous[0]
or event["source_sequence"] <= previous[1]
or event["received_monotonic_ns"] < previous[2]
):
raise wire.StreamWireError("channel identity, sequence or source clock regressed")
if modality == "camera-frame" and not self.camera_initialized:
raise wire.StreamWireError("camera frame requires new codec initialization")
if modality == "camera-frame" and previous and event["source_sequence"] != previous[1] + 1:
if self.runtime.continuity is not None:
raise StreamSuspended("camera sequence gap requires resynchronization")
raise wire.StreamWireError("camera sequence gap requires new codec initialization")
self.counts["observations_started"] += 1
reservation = self.runtime.mailbox.reserve_ingress(2 * total)
raw = None
admitted = None
try:
raw = bytearray(total)
header = first
while True:
chunk = memoryview(raw)[offset : offset + size]
try:
self._read_into(chunk, deadline)
if sha256(chunk).hexdigest() != header["fragment_sha256"]:
raise wire.StreamWireError("fragment integrity mismatch")
finally:
chunk.release()
self.counts["fragments"] += 1
offset += size
if offset == total:
break
kind, header = self._header(deadline)
if kind != wire.FRAGMENT:
raise wire.StreamWireError("incomplete observation before control event")
next_event, next_total, next_offset, size = self._fragment(header)
if (
next_event != event
or next_total != total
or next_offset != offset
or header["payload_sha256"] != first["payload_sha256"]
):
raise wire.StreamWireError("interleaved or discontinuous fragments")
if sha256(raw).hexdigest() != first["payload_sha256"]:
raise wire.StreamWireError("observation integrity mismatch")
self._check(deadline)
if event["modality"] != "camera-init":
self.runtime.check_input(
self.input_epoch, synchronizing=True, event_ns=event["received_monotonic_ns"]
)
admitted = LiveIngressEvent(**event, payload=bytes(raw))
raw = None # Immutable callback bytes remain fully reserved.
self.consume(admitted)
self._check(deadline)
self.counts["ingress_sequence_gaps"] += (
event["ingress_sequence"] - self.last_ingress_sequence - 1
)
self.last_ingress_sequence = event["ingress_sequence"]
self.channel_sequences[modality] = (
event["source_id"],
event["source_sequence"],
event["received_monotonic_ns"],
)
if modality == "camera-init":
self.camera_initialized = True
self.channel_sequences.pop("camera-frame", None)
self.counts["observations_completed"] += 1
finally:
admitted = raw = None
reservation.release()
def _gap(self, header: dict[str, Any]) -> None:
if set(header) != {"binding", "modality", "reason", "count"}:
raise wire.StreamWireError("gap fields changed")
if header["modality"] not in wire.PAYLOAD_LIMITS or header["reason"] not in (
"unavailable",
"source-gap",
"overload",
):
raise wire.StreamWireError("invalid gap notice")
self.counts["declared_gap_observations"] += wire.uint64(header["count"])
if header["modality"].startswith("camera"):
self.camera_initialized = False
if self.runtime.continuity is not None:
raise StreamSuspended("declared source gap requires resynchronization")
self.notice(dict(header))
self.runtime.check_input(self.input_epoch, synchronizing=True)
self.counts["gap_notices"] += 1
def _serve(self) -> None:
reservation = None
try:
# Covers raw header + JSON decoding copies; Python object overhead
# belongs to the separately measured RSS envelope, not payload bytes.
reservation = self.runtime.mailbox.reserve_ingress(
3 * wire.MAX_HEADER + wire.PREFIX.size
)
kind, header = self._header(time.monotonic() + self.idle_timeout)
expected = wire.parse_header(
bytearray(
wire.open_packet(
self.input_epoch,
self.session_id,
self.session_generation,
)[wire.PREFIX.size :]
)
)
if kind != wire.OPEN or header != expected:
raise wire.StreamWireError("StreamStart or acquisition handshake mismatch")
self.opened = True
while True:
kind, header = self._header(time.monotonic() + self.idle_timeout)
self._bound(header)
if kind == wire.FRAGMENT:
self._observation(header, time.monotonic() + self.fragment_timeout)
elif kind == wire.GAP:
self._gap(header)
elif kind in (wire.END, wire.CANCEL) and set(header) == {"binding"}:
self.terminal = "cancelled" if kind == wire.CANCEL else "end"
if kind == wire.CANCEL:
self.runtime.request_stop("cancelled")
else:
self.runtime.mailbox.finish()
return
else:
raise wire.StreamWireError("unexpected stream control event")
except Exception as exc:
self.error = str(exc)
self.terminal = "failed"
if self.runtime.continuity is not None and isinstance(
exc, (InputInterrupted, StreamSuspended)
):
# Admission already consumed the single-use grant. A transport
# loss before the application OPEN is still WAIT, not an active
# owner stranded forever. A late old socket remains fenced.
self.terminal = "paused"
with suppress(RuntimeError): # Already replaced, stopping, or fenced.
self.runtime.pause_input(
self.input_epoch,
"input-disconnected" if isinstance(exc, InputInterrupted) else "source-gap",
)
elif self.opened:
self.runtime.mailbox.finish(self.error)
self.runtime.request_stop("failed")
finally:
self.connection.close()
if reservation is not None:
reservation.release()
def snapshot(self) -> dict[str, Any]:
return {
"schema_version": wire.SCHEMA,
"opened": self.opened,
"terminal": self.terminal,
"error": self.error,
"counts": dict(self.counts),
"incomplete_observations": self.counts["observations_started"]
- self.counts["observations_completed"],
"source_duration_known": False,
"requires_eof_before_delivery": False,
"transport": "controller-supplied-ipc-socket",
"network_qualified": False,
"actuation_allowed": False,
}