Local preservation snapshot, not a new deployment or simulation acceptance.
284 lines
11 KiB
Python
284 lines
11 KiB
Python
"""Worker-local, bounded asynchronous inference. No operator-network dependencies."""
|
|
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import queue
|
|
import threading
|
|
import time
|
|
import traceback
|
|
from contextlib import suppress
|
|
from pathlib import Path
|
|
|
|
|
|
class EvidenceWriter:
|
|
"""One writer, one waiting packet; saturation applies backpressure."""
|
|
|
|
def __init__(self, failed):
|
|
self.failed = failed
|
|
self.queue = queue.Queue(maxsize=1)
|
|
self.error = threading.Event()
|
|
self.thread = threading.Thread(target=self._run, name="polygon-evidence", daemon=True)
|
|
self.thread.start()
|
|
|
|
def _run(self):
|
|
while True:
|
|
work = self.queue.get()
|
|
try:
|
|
if work is None:
|
|
return
|
|
frame_id, save = work
|
|
if not self.error.is_set():
|
|
try:
|
|
save()
|
|
except Exception as exc:
|
|
self.error.set()
|
|
self.failed(frame_id, exc)
|
|
finally:
|
|
self.queue.task_done()
|
|
|
|
def submit(self, frame_id, save):
|
|
while not self.error.is_set():
|
|
try:
|
|
self.queue.put((frame_id, save), timeout=0.05)
|
|
return
|
|
except queue.Full:
|
|
pass
|
|
raise RuntimeError("Evidence writer failed")
|
|
|
|
def close(self):
|
|
# A run cannot be sealed with writes still in flight.
|
|
self.queue.put(None)
|
|
self.thread.join()
|
|
|
|
|
|
class _ClosingWriter:
|
|
def __init__(self, writer):
|
|
self.writer = writer
|
|
|
|
def __enter__(self):
|
|
return self.writer
|
|
|
|
def __exit__(self, *args):
|
|
self.writer.close()
|
|
|
|
|
|
class LatestInference:
|
|
def __init__(self, factory, policy, directory: Path, clock=time.monotonic):
|
|
self.factory, self.policy, self.directory, self.clock = factory, policy, directory, clock
|
|
self.condition = threading.Condition()
|
|
self.enabled = self.closed = self.ready = False
|
|
self.ever_ready = False
|
|
self.epoch = self.count = self.dropped = 0
|
|
self.pending = self.result = None
|
|
self.error = None
|
|
self.archive_error = False
|
|
self.error_lock = threading.Lock()
|
|
self.thread = threading.Thread(target=self._run, name="polygon-inference", daemon=True)
|
|
|
|
def start(self):
|
|
self.thread.start()
|
|
|
|
def enable(self, enabled):
|
|
with self.condition:
|
|
if enabled != self.enabled:
|
|
self.enabled = enabled
|
|
self.epoch += 1
|
|
self.pending = self.result = None
|
|
self.condition.notify_all()
|
|
|
|
def submit(self, rgb, frame_id, captured_at, simulation_time_ns, observation=None):
|
|
with self.condition:
|
|
if not self.enabled or self.closed:
|
|
return
|
|
if self.pending is not None:
|
|
self.dropped += 1
|
|
self.pending = (
|
|
rgb,
|
|
frame_id,
|
|
captured_at,
|
|
simulation_time_ns,
|
|
self.epoch,
|
|
observation,
|
|
self.clock(),
|
|
)
|
|
self.condition.notify_all()
|
|
|
|
def command(self, now, frame_deadline=0.5, command_deadline=0.5):
|
|
with self.condition:
|
|
result = self.result
|
|
if not self.enabled:
|
|
return 0.0, 0.0, "paused", result
|
|
if self.error:
|
|
return 0.0, 0.0, "inference-error", result
|
|
if (
|
|
result is None
|
|
or now
|
|
- min(
|
|
result["captured_at"], result.get("intent_captured_at", result["captured_at"])
|
|
)
|
|
> frame_deadline
|
|
):
|
|
return 0.0, 0.0, "stale-camera", result
|
|
if now - result["completed_at"] > command_deadline:
|
|
return 0.0, 0.0, "stale-command", result
|
|
decision = result["decision"]
|
|
return decision["speed_mps"], decision["yaw_rate_rps"], "none", result
|
|
|
|
def _record_error(self, frame_id, exc, *, archive=False):
|
|
with self.error_lock:
|
|
# Failure must latch even when the same full/broken disk cannot
|
|
# accept its error journal. The episode then remains unsealable.
|
|
with self.condition:
|
|
self.archive_error |= archive
|
|
self.error, self.ready, self.result = type(exc).__name__, False, None
|
|
self.condition.notify_all()
|
|
with (
|
|
suppress(OSError),
|
|
(self.directory / "errors.jsonl").open("a", encoding="utf-8") as errors,
|
|
):
|
|
errors.write(
|
|
json.dumps(
|
|
{
|
|
"frame_id": frame_id,
|
|
"monotonic": self.clock(),
|
|
"error": str(exc),
|
|
"type": type(exc).__name__,
|
|
"traceback": traceback.format_exc(),
|
|
}
|
|
)
|
|
+ "\n"
|
|
)
|
|
|
|
def _run(self):
|
|
model = None
|
|
policy_epoch = None
|
|
self.directory.mkdir(parents=True, exist_ok=True)
|
|
writer = EvidenceWriter(lambda frame, exc: self._record_error(frame, exc, archive=True))
|
|
try:
|
|
with (
|
|
(self.directory / "decisions.jsonl").open("a", encoding="utf-8") as journal,
|
|
_ClosingWriter(writer),
|
|
):
|
|
while True:
|
|
with self.condition:
|
|
self.condition.wait_for(
|
|
lambda: (
|
|
self.closed
|
|
or self.archive_error
|
|
or (self.enabled and self.pending is not None)
|
|
)
|
|
)
|
|
if self.closed or self.archive_error:
|
|
return
|
|
rgb, frame_id, captured_at, sim_ns, epoch, observation, submitted = (
|
|
self.pending
|
|
)
|
|
self.pending = None
|
|
try:
|
|
if model is None:
|
|
model = self.factory()
|
|
model.ready()
|
|
started = self.clock()
|
|
evidence = {}
|
|
if self.policy is None:
|
|
if policy_epoch is not None and policy_epoch != epoch:
|
|
model.reset()
|
|
policy_epoch = epoch
|
|
observation = {**(observation or {}), "captured_at": captured_at}
|
|
decision, boxes, evidence = model.infer_observation(
|
|
rgb, observation, frame_id
|
|
)
|
|
else:
|
|
road, boxes = model.infer(rgb)
|
|
with self.condition:
|
|
if epoch != self.epoch or not self.enabled:
|
|
continue
|
|
if self.policy is not None and policy_epoch != epoch:
|
|
self.policy.reset()
|
|
policy_epoch = epoch
|
|
if self.policy is not None:
|
|
decision = self.policy.decide(road, boxes).model_dump()
|
|
completed = self.clock()
|
|
intent_time = evidence.get("intent_captured_at", captured_at)
|
|
if not math.isfinite(intent_time) or intent_time > captured_at:
|
|
raise ValueError("Invalid task-view intent capture time")
|
|
record = dict(
|
|
frame_id=frame_id,
|
|
captured_at=captured_at,
|
|
intent_captured_at=intent_time,
|
|
simulation_time_ns=sim_ns,
|
|
completed_at=completed,
|
|
submitted_at=submitted,
|
|
started_at=started,
|
|
preparation_ms=(submitted - captured_at) * 1000,
|
|
queue_ms=(started - submitted) * 1000,
|
|
inference_ms=(completed - started) * 1000,
|
|
decision=decision,
|
|
)
|
|
with self.condition:
|
|
if self.archive_error:
|
|
return
|
|
self.ready, self.ever_ready, self.error = True, True, None
|
|
if epoch != self.epoch or not self.enabled:
|
|
continue # A pause/resume fences every earlier in-flight decision.
|
|
self.result = record
|
|
self.count += 1
|
|
archive = None
|
|
detached = self.policy is None and hasattr(model, "take_archive")
|
|
if detached:
|
|
archive = model.take_archive()
|
|
elif self.policy is None and hasattr(model, "archive_observation"):
|
|
archive = model.archive_observation
|
|
|
|
def save(
|
|
record=record,
|
|
rgb=rgb,
|
|
observation=observation,
|
|
frame_id=frame_id,
|
|
boxes=boxes,
|
|
evidence=evidence,
|
|
archive=archive,
|
|
):
|
|
archive_started = self.clock()
|
|
if archive is not None:
|
|
archive()
|
|
from PIL import Image
|
|
|
|
image_path = self.directory / f"{frame_id:08d}.jpg"
|
|
Image.fromarray((observation or {}).get("inference_rgb", rgb)).save(
|
|
image_path, "JPEG", quality=90
|
|
)
|
|
record = {
|
|
**record,
|
|
"image": image_path.name,
|
|
"image_sha256": hashlib.sha256(image_path.read_bytes()).hexdigest(),
|
|
"obstacles": boxes,
|
|
"archive_ms": (self.clock() - archive_started) * 1000,
|
|
"sensor_timing_ms": (observation or {}).get("sensor_timing_ms"),
|
|
**evidence,
|
|
}
|
|
journal.write(json.dumps(record, allow_nan=False) + "\n")
|
|
journal.flush()
|
|
|
|
if detached:
|
|
writer.submit(frame_id, save)
|
|
else:
|
|
save()
|
|
except Exception as exc:
|
|
self._record_error(frame_id, exc)
|
|
if model is not None:
|
|
model.close()
|
|
model = None
|
|
with self.condition:
|
|
self.condition.wait(timeout=0.5)
|
|
finally:
|
|
if model is not None:
|
|
model.close()
|
|
|
|
def close(self):
|
|
with self.condition:
|
|
self.closed = True
|
|
self.condition.notify_all()
|
|
self.thread.join(timeout=12)
|