413 lines
22 KiB
Python
413 lines
22 KiB
Python
"""Bounded multi-rate perception, navigation and live-odometry control.
|
|
|
|
One latest camera slot, one latest range slot, one latest pose slot. Slow image
|
|
inference/evidence cannot serialize the controller. All epochs fence pause and
|
|
resume, and each stage records the original observation identity and age.
|
|
"""
|
|
|
|
import json
|
|
import http.client
|
|
import math
|
|
import threading
|
|
import time
|
|
import traceback
|
|
from pathlib import Path
|
|
|
|
from navigation_client import NavigationClient
|
|
from realtime_ai import EvidenceWriter
|
|
from k1link.simulation.ai_polygon.perception_evidence import archive_perception
|
|
|
|
|
|
class ContinuousPipeline:
|
|
def __init__(self, factory, directory, clock=time.monotonic):
|
|
self.factory, self.directory, self.clock = factory, Path(directory), clock
|
|
self.condition = threading.Condition()
|
|
self.enabled = self.closed = self.ready = self.ever_ready = False
|
|
self.epoch = self.count = self.dropped = 0
|
|
self.result = self.error = self.sensor = self.perception = self.pose = self.control = None
|
|
self.failure = None
|
|
self.intent_revision = 0
|
|
self.intent_key = None
|
|
self.perception_revision = 0
|
|
self.model = None
|
|
self.route_guard = None
|
|
self.writer_closed = False
|
|
self.threads = []
|
|
self.model_ready = threading.Event()
|
|
self.mission_lock = threading.Lock()
|
|
|
|
def start(self):
|
|
self.directory.mkdir(parents=True, exist_ok=True)
|
|
self.writer = EvidenceWriter(self.fail)
|
|
for name, run in (("perception", self.perceive), ("navigation", self.navigate),
|
|
("control", self.control_loop)):
|
|
def guarded(run=run, name=name):
|
|
try:
|
|
run()
|
|
except Exception as exc:
|
|
self.fail(name, exc)
|
|
thread = threading.Thread(target=guarded, name="continuous-"+name, daemon=True)
|
|
thread.start()
|
|
self.threads.append(thread)
|
|
|
|
def fail(self, frame, exc):
|
|
with self.condition:
|
|
if self.failure is None:
|
|
self.failure = dict(stage=frame if isinstance(frame, str) else "evidence",
|
|
frame_id=frame if isinstance(frame, int) else None,
|
|
type=type(exc).__name__, message=str(exc), monotonic=self.clock())
|
|
self.error = self.failure["type"]
|
|
self.ready = False
|
|
self.control = None
|
|
self.condition.notify_all()
|
|
try:
|
|
with (self.directory / "errors.jsonl").open("a") as stream:
|
|
stream.write(json.dumps(dict(frame=frame, error=str(exc),
|
|
traceback=traceback.format_exc(), monotonic=self.clock()))+"\n")
|
|
except OSError:
|
|
pass
|
|
|
|
def terminal_failure(self):
|
|
with self.condition:
|
|
return None if self.failure is None else dict(self.failure)
|
|
|
|
def enable(self, enabled, *, epoch=None):
|
|
with self.condition:
|
|
if epoch is not None and (type(epoch) is not int or epoch < self.epoch):
|
|
raise ValueError("Invalid pipeline epoch")
|
|
if enabled != self.enabled or (epoch is not None and epoch != self.epoch):
|
|
self.enabled = enabled
|
|
self.epoch = self.epoch + 1 if epoch is None else epoch
|
|
self.sensor = self.perception = self.result = self.control = None
|
|
self.ready = False
|
|
self.intent_key = None
|
|
self.intent_revision += 1
|
|
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 or self.error:
|
|
return
|
|
self.sensor = (self.epoch, frame_id, {**observation, "captured_at": captured_at,
|
|
"simulation_time_ns": simulation_time_ns})
|
|
self.condition.notify_all()
|
|
|
|
def observe_pose(self, pose, speed, captured_at, *, measured_twist=None):
|
|
# Called from the physics callback: only an in-memory bounded publish.
|
|
if measured_twist is not None and (len(measured_twist) != 3 or
|
|
not all(math.isfinite(value) for value in measured_twist)):
|
|
raise ValueError('Invalid measured planar twist')
|
|
with self.condition:
|
|
self.pose = (list(pose), float(speed), captured_at)
|
|
self.pose_twist = None if measured_twist is None else (tuple(measured_twist), captured_at)
|
|
|
|
def current(self, epoch):
|
|
return not self.closed and self.enabled and self.epoch == epoch and not self.error
|
|
|
|
@staticmethod
|
|
def mission_intent_key(record):
|
|
"""Fence task changes without treating each sensor refresh as a new task."""
|
|
mission = record.get("mission") or {}
|
|
recovery = mission.get("recovery") or {}
|
|
selected = recovery.get("selected") or {}
|
|
request = recovery.get("request") or {}
|
|
key = {name: mission.get(name) for name in (
|
|
"global_route_sha256", "active_route_sha256", "route_revision",
|
|
"route_segment", "waypoint", "recovery_attempt", "state")}
|
|
key["recovery"] = dict(phase=recovery.get("phase"), option=recovery.get("option"),
|
|
request_key=request.get("key"),
|
|
selected={name: selected.get(name) for name in ("goal", "reverse", "kind")})
|
|
key["motion_enabled"] = record["decision"]["reason"] in {"road", "replanning"}
|
|
return json.dumps(key, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
|
|
|
def publish_navigation(self, epoch, record, guard):
|
|
key = self.mission_intent_key(record)
|
|
with self.condition:
|
|
if not self.current(epoch):
|
|
return None
|
|
if key != self.intent_key:
|
|
self.intent_key = key
|
|
self.intent_revision += 1
|
|
self.control = None
|
|
record = {**record, "intent_revision": self.intent_revision}
|
|
self.result, self.route_guard = record, guard
|
|
self.count += 1
|
|
self.ready = self.ever_ready = True
|
|
self.condition.notify_all()
|
|
return record
|
|
|
|
def wait_sensor(self, previous):
|
|
with self.condition:
|
|
self.condition.wait_for(lambda: self.closed or self.error or
|
|
(self.enabled and self.sensor is not None and self.sensor[:2] != previous))
|
|
return None if self.closed or self.error else self.sensor
|
|
|
|
def wait_navigation(self, previous):
|
|
"""A completed neural result can update an unchanged range sample."""
|
|
with self.condition:
|
|
def available():
|
|
return (self.enabled and self.sensor is not None and self.perception is not None
|
|
and self.sensor[0] == self.perception[0] == self.epoch
|
|
and (*self.sensor[:2], self.perception_revision) != previous)
|
|
self.condition.wait_for(lambda: self.closed or self.error or available())
|
|
if self.closed or self.error:
|
|
return None
|
|
return ((*self.sensor[:2], self.perception_revision), self.sensor, self.perception)
|
|
|
|
def perceive(self):
|
|
# The first sensor packet is admitted only after the worker's complete
|
|
# model-stack readiness barrier. Do not race startup on a partial stack.
|
|
if self.wait_sensor(None) is None:
|
|
return
|
|
self.model = self.factory()
|
|
self.model.ready()
|
|
self.model_ready.set()
|
|
previous = None
|
|
with (self.directory / "perception.jsonl").open("a") as journal:
|
|
while (packet := self.wait_sensor(previous)) is not None:
|
|
epoch, frame, observation = packet
|
|
if previous and previous[0] == epoch:
|
|
self.dropped += max(0, frame-previous[1]-1)
|
|
previous = packet[:2]
|
|
started = self.clock()
|
|
result = self.model.perceive(observation, frame)
|
|
with self.condition:
|
|
if not self.current(epoch):
|
|
continue
|
|
self.perception = (epoch, result)
|
|
self.perception_revision += 1
|
|
self.condition.notify_all()
|
|
|
|
def archive(result=result, observation=observation, frame=frame, started=started):
|
|
now = self.clock()
|
|
self.model.archive_observation((result["rgb"], result["values"],
|
|
result["observation"], frame))
|
|
from PIL import Image
|
|
Image.fromarray(result["rgb"]).save(self.directory/f"{frame:08d}.jpg", quality=90)
|
|
extra = result.get("supplement")
|
|
if extra is not None:
|
|
Image.fromarray(extra["rgb"]).save(
|
|
self.directory/f"{frame:08d}.supplement.jpg", quality=90)
|
|
exact_evidence = archive_perception(self.directory, result)
|
|
journal.write(json.dumps(dict(frame_id=frame, captured_at=observation["captured_at"],
|
|
completed_at=result["completed_at"], started_at=started,
|
|
module_ms=result["module_ms"], semantic_observations=result["semantic_observations"],
|
|
detection_views=[dict(captured_at=view["observation"]["captured_at"],
|
|
frame_id=view["samples"]["frame_id"],
|
|
objects=view["values"].get("detection.objects", []))
|
|
for view in result.get("detection_views", [])],
|
|
sensor_timing_ms=observation.get("sensor_timing_ms"),
|
|
acquisition_age_ms=(started-observation["captured_at"])*1000,
|
|
archive_ms=(self.clock()-now)*1000, view="body-forward",
|
|
exact_evidence=exact_evidence))+"\n")
|
|
journal.flush()
|
|
self.writer.submit(frame, archive)
|
|
# The writer owns this stream until the final outstanding packet.
|
|
self.writer.close()
|
|
self.writer_closed = True
|
|
|
|
def await_model(self):
|
|
while not self.closed and not self.error:
|
|
if self.model_ready.wait(0.1):
|
|
return True
|
|
return False
|
|
|
|
def navigate(self):
|
|
if not self.await_model():
|
|
return
|
|
previous = None
|
|
active_epoch = None
|
|
with (self.directory / "decisions.jsonl").open("a") as journal:
|
|
while (snapshot := self.wait_navigation(previous)) is not None:
|
|
signature, packet, perception = snapshot
|
|
epoch, frame, observation = packet
|
|
previous = signature
|
|
with self.mission_lock:
|
|
if active_epoch is not None and active_epoch != epoch:
|
|
self.model.reset()
|
|
active_epoch = epoch
|
|
started = self.clock()
|
|
identifier = f"{epoch}:{frame}:{signature[2]}"
|
|
decision, evidence = self.model.navigate_latest(observation, perception[1], identifier)
|
|
guard = None
|
|
if hasattr(self.model.mission, "motion_corridors"):
|
|
from k1link.simulation.ai_polygon.corridor_control import CorridorControl
|
|
guard = CorridorControl(self.model.mission.motion_corridors(),
|
|
self.model.mission.global_route["no_go"])
|
|
completed = self.clock()
|
|
record = dict(frame_id=frame, observation_id=identifier, captured_at=observation["captured_at"],
|
|
completed_at=completed, started_at=started, simulation_time_ns=observation["simulation_time_ns"],
|
|
inference_ms=perception[1].get("processing_ms", 0.0),
|
|
navigation_ms=(completed-started)*1000, decision=decision, **evidence)
|
|
record = self.publish_navigation(epoch, record, guard)
|
|
if record is None:
|
|
continue
|
|
journal.write(json.dumps(record, allow_nan=False)+"\n")
|
|
journal.flush()
|
|
|
|
def control_loop(self):
|
|
if not self.await_model():
|
|
return
|
|
connection = NavigationClient()
|
|
connection_epoch = None
|
|
delivered_range = None
|
|
try:
|
|
with (self.directory / "controller.jsonl").open("a") as journal:
|
|
while not self.closed and not self.error:
|
|
started = self.clock()
|
|
with self.condition:
|
|
epoch, pose, result, perception = self.epoch, self.pose, self.result, self.perception
|
|
guard = self.route_guard
|
|
sensor = self.sensor
|
|
measured_twist = getattr(self, 'pose_twist', None)
|
|
enabled = self.enabled and self.ready
|
|
intent_revision = self.intent_revision
|
|
if connection_epoch != epoch:
|
|
connection.close()
|
|
connection = NavigationClient()
|
|
connection_epoch = epoch
|
|
delivered_range = None
|
|
if pose is not None and result is not None and perception is not None and enabled:
|
|
payload = dict(execution_inputs_sha256=self.model.inputs["sha256"],
|
|
pose=pose[0], speed_mps=pose[1], pose_age_seconds=max(0, started-pose[2]),
|
|
perception_age_seconds=max(0, started-perception[1]["observation"]["captured_at"]),
|
|
observation_id=result["observation_id"],
|
|
enabled=result["decision"]["reason"] in {"road", "replanning"})
|
|
if measured_twist is not None and measured_twist[1] == pose[2]:
|
|
payload['measured_twist'] = list(measured_twist[0])
|
|
range_identity = sensor[:2] if sensor is not None else None
|
|
if sensor is not None and sensor[0] == epoch and range_identity != delivered_range:
|
|
payload["range_observation"] = {
|
|
"range_sequence": list(range_identity),
|
|
"geometry_age_seconds": max(0, started-sensor[2]["captured_at"]),
|
|
"points": sensor[2]["points"].tolist(),
|
|
}
|
|
try:
|
|
response = connection.request("/control", payload)
|
|
if "range_observation" in payload:
|
|
delivered_range = range_identity
|
|
except (OSError, http.client.HTTPException) as exc:
|
|
# A reset replaces the native service and closes
|
|
# keep-alive sockets. Drop authority before reconnect;
|
|
# never replay a command or renew its observation age.
|
|
with self.condition:
|
|
self.control = None
|
|
connection.close()
|
|
connection = NavigationClient()
|
|
delivered_range = None
|
|
journal.write(json.dumps(dict(started_at=started,
|
|
completed_at=self.clock(), reason="control-transport-error",
|
|
error=type(exc).__name__, speed_mps=0, yaw_rate_rps=0))+"\n")
|
|
journal.flush()
|
|
with self.condition:
|
|
self.condition.wait(timeout=.05)
|
|
continue
|
|
# Corridor policy still owns its full-body veto at the
|
|
# live pose. A route revision cannot reuse old authority.
|
|
if guard is not None and response["reason"] == "none":
|
|
v, w, scale = guard.regulate_command(pose[0],
|
|
self.model.route_monitor, response["speed_mps"], response["yaw_rate_rps"])
|
|
response.update(speed_mps=v, yaw_rate_rps=w)
|
|
if scale == 0:
|
|
response["reason"] = "route-corridor"
|
|
completed = self.clock()
|
|
if response["reason"] == "none" and (
|
|
response.get("observation_id") != result["observation_id"]
|
|
or not all(math.isfinite(response[key])
|
|
for key in ("speed_mps", "yaw_rate_rps"))):
|
|
raise ValueError("Controller reply does not match its observation")
|
|
# All deadlines stay in the capture host's monotonic
|
|
# clock. Transport/server work consumes the original
|
|
# budget; receiving a reply never renews old evidence.
|
|
expires_at = min(started + .25, pose[2] + .5,
|
|
perception[1]["observation"]["captured_at"] + 2.,
|
|
sensor[2]["captured_at"] + .8 if sensor else started,
|
|
result["captured_at"] + .8)
|
|
with self.condition:
|
|
if self.current(epoch) and self.intent_revision == intent_revision:
|
|
self.control = (completed, pose[2], response, expires_at,
|
|
intent_revision)
|
|
self.condition.notify_all()
|
|
journal.write(json.dumps({"started_at":started, "completed_at":completed,
|
|
"observation_id":result["observation_id"],
|
|
"expires_at":expires_at,
|
|
"freshness_deadlines":dict(command=started+.25, pose=pose[2]+.5,
|
|
perception=perception[1]["observation"]["captured_at"]+2.,
|
|
range=sensor[2]["captured_at"]+.8 if sensor else started,
|
|
plan=result["captured_at"]+.8),
|
|
**response})+"\n")
|
|
journal.flush()
|
|
with self.condition:
|
|
self.condition.wait(timeout=max(0.001, 0.05-(self.clock()-started)))
|
|
finally:
|
|
connection.close()
|
|
|
|
def command(self, now, **_):
|
|
with self.condition:
|
|
result, command = self.result, self.control
|
|
if self.closed or not self.enabled:
|
|
return 0.0, 0.0, "paused", result
|
|
if self.error:
|
|
return 0.0, 0.0, "inference-error", result
|
|
if result is not None and result["decision"]["reason"] not in {"road", "replanning"}:
|
|
return 0.0, 0.0, "control-blocked", result
|
|
if command is None or now-command[0] > 0.25:
|
|
return 0.0, 0.0, "stale-command", result
|
|
_, pose_at, response, expires_at, intent_revision = command
|
|
if intent_revision != self.intent_revision or now >= expires_at:
|
|
return 0.0, 0.0, "stale-command", result
|
|
if result is not None:
|
|
result = {**result, "control_completed_at": command[0]}
|
|
if now-pose_at > 0.5:
|
|
return 0.0, 0.0, "stale-pose", result
|
|
reason = response["reason"]
|
|
if reason != "none":
|
|
reason = reason if reason in {"stale-range", "stale-pose", "stale-perception"} else "control-blocked"
|
|
return 0.0, 0.0, reason, result
|
|
return response["speed_mps"], response["yaw_rate_rps"], "none", result
|
|
|
|
def apply_command(self, apply_target, *, shape=None, stop=False):
|
|
"""Consume the current command and set the actuator under one intent lock.
|
|
|
|
The callbacks are bounded local arithmetic / target assignment only.
|
|
Physics integration and I/O stay outside. Record only successful writes;
|
|
the record is an applied target, not measured motion or certification.
|
|
"""
|
|
with self.condition:
|
|
checked_at = self.clock()
|
|
source = self.control
|
|
command = self.command(checked_at)
|
|
velocity, angular, reason, decision = command
|
|
if stop:
|
|
velocity = angular = 0.0
|
|
reason = "control-blocked" if reason == "none" else reason
|
|
if shape is not None:
|
|
velocity, angular = shape(velocity, angular, reason)
|
|
# Shaping and lock wait consume the original lease as well.
|
|
if reason == "none" and self.command(self.clock())[:3] != command[:3]:
|
|
velocity = angular = 0.0
|
|
reason = "stale-command"
|
|
if shape is not None:
|
|
velocity, angular = shape(0.0, 0.0, reason)
|
|
apply_target(velocity, angular)
|
|
self.applied_target = dict(intent_revision=self.intent_revision,
|
|
applied_at=self.clock(), speed_mps=velocity, yaw_rate_rps=angular,
|
|
reason=reason, checked_at=checked_at,
|
|
control_completed_at=source[0] if source is not None else None,
|
|
expires_at=source[3] if source is not None else None,
|
|
observation_id=source[2].get('observation_id') if source is not None else None)
|
|
return velocity, angular, reason, decision
|
|
|
|
def close(self):
|
|
with self.condition:
|
|
self.closed = True
|
|
self.condition.notify_all()
|
|
for thread in self.threads:
|
|
thread.join(timeout=15)
|
|
if any(thread.is_alive() for thread in self.threads):
|
|
raise RuntimeError("Continuous stage did not stop")
|
|
if not self.writer_closed:
|
|
self.writer.close()
|
|
if self.model is not None:
|
|
self.model.close()
|