feat(perception): preserve resident runtime across recoverable input gaps
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
"""One controller-supplied IPC socket feeding the common streaming lifecycle.
|
||||
|
||||
No listener, acquisition, archive reader, model RPC, network authentication or
|
||||
automatic reconnect. Reconnect needs a new StreamStart/lease and decoder state.
|
||||
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;
|
||||
@@ -16,15 +18,22 @@ 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,
|
||||
@@ -37,6 +46,7 @@ class StreamingIngress:
|
||||
*,
|
||||
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")
|
||||
@@ -49,7 +59,8 @@ class StreamingIngress:
|
||||
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.binding = wire.binding(runtime.start)
|
||||
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
|
||||
@@ -60,10 +71,10 @@ class StreamingIngress:
|
||||
self.thread = threading.Thread(
|
||||
target=self._serve, name="perception-binary-ingress", daemon=True
|
||||
)
|
||||
runtime.track_thread(self.thread)
|
||||
runtime.register_ingress(self.thread, self.input_epoch)
|
||||
|
||||
def start(self) -> None:
|
||||
self.runtime.check_current(self.runtime.start)
|
||||
self.runtime.check_input(self.input_epoch, synchronizing=True)
|
||||
self.thread.start()
|
||||
|
||||
def join(self, timeout: float = 1.0) -> bool:
|
||||
@@ -71,9 +82,9 @@ class StreamingIngress:
|
||||
return not self.thread.is_alive()
|
||||
|
||||
def _check(self, deadline: float) -> None:
|
||||
self.runtime.check_current(self.runtime.start)
|
||||
self.runtime.check_input(self.input_epoch, synchronizing=True)
|
||||
if time.monotonic() >= deadline:
|
||||
raise wire.StreamWireError("ingress deadline exceeded")
|
||||
raise InputInterrupted("ingress deadline exceeded")
|
||||
|
||||
def _read_into(self, target: memoryview, deadline: float) -> None:
|
||||
offset = 0
|
||||
@@ -87,8 +98,10 @@ class StreamingIngress:
|
||||
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 wire.StreamWireError("unexpected EOF without explicit End")
|
||||
raise InputInterrupted("unexpected EOF without explicit End")
|
||||
self.counts["wire_bytes"] += read
|
||||
offset += read
|
||||
self._check(deadline)
|
||||
@@ -109,8 +122,10 @@ class StreamingIngress:
|
||||
|
||||
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_current(self.runtime.start)
|
||||
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) != {
|
||||
@@ -157,6 +172,8 @@ class StreamingIngress:
|
||||
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)
|
||||
@@ -191,6 +208,10 @@ class StreamingIngress:
|
||||
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)
|
||||
@@ -224,8 +245,10 @@ class StreamingIngress:
|
||||
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_current(self.runtime.start)
|
||||
self.runtime.check_input(self.input_epoch, synchronizing=True)
|
||||
self.counts["gap_notices"] += 1
|
||||
|
||||
def _serve(self) -> None:
|
||||
@@ -240,7 +263,7 @@ class StreamingIngress:
|
||||
expected = wire.parse_header(
|
||||
bytearray(
|
||||
wire.open_packet(
|
||||
self.runtime.start,
|
||||
self.input_epoch,
|
||||
self.session_id,
|
||||
self.session_generation,
|
||||
)[wire.PREFIX.size :]
|
||||
@@ -269,8 +292,21 @@ class StreamingIngress:
|
||||
self.error = str(exc)
|
||||
self.terminal = "failed"
|
||||
if self.opened:
|
||||
self.runtime.mailbox.finish(self.error)
|
||||
self.runtime.request_stop("failed")
|
||||
if self.runtime.continuity is not None and isinstance(
|
||||
exc, (InputInterrupted, StreamSuspended)
|
||||
):
|
||||
self.terminal = "paused"
|
||||
# A late old socket cannot pause a replacement connection.
|
||||
with suppress(RuntimeError): # Already replaced, stopping, or fenced.
|
||||
self.runtime.pause_input(
|
||||
self.input_epoch,
|
||||
"input-disconnected"
|
||||
if isinstance(exc, InputInterrupted)
|
||||
else "source-gap",
|
||||
)
|
||||
else:
|
||||
self.runtime.mailbox.finish(self.error)
|
||||
self.runtime.request_stop("failed")
|
||||
finally:
|
||||
self.connection.close()
|
||||
if reservation is not None:
|
||||
|
||||
Reference in New Issue
Block a user