feat(planning): consolidate recorded-route localization and spatial scene

Preserve the completed teach-and-repeat laboratory stage: reference preparation, cascaded acquisition, local tracking and recovery, recording lifecycle, replay qualification, and persistent Rerun scene controls. Document the open grid-picking regression and Rerun upgrade contract. No autonomous driving or loop-closure optimization is claimed.
This commit is contained in:
DCCONSTRUCTIONS
2026-09-21 08:47:19 +03:00
parent be58d589e2
commit e515ab1b8c
189 changed files with 19074 additions and 758 deletions
@@ -6,6 +6,7 @@ from missioncore_plugin_sdk.v0alpha2 import RuntimePluginDescriptor
from k1link.web.plugin_runtime import DevicePluginRuntimeContribution, InProcessDevicePluginRuntime
from .planning_live import K1PlanningLiveSource
from .camera import build_xgrids_k1_camera_router
from .facade import (
XGRIDS_K1_PLUGIN_ID,
@@ -57,5 +58,5 @@ def build_xgrids_k1_plugin(repository_root: Path) -> DevicePluginRuntimeContribu
),
),
),
observation=build_xgrids_k1_observation(repository_root),
observation=build_xgrids_k1_observation(repository_root, K1PlanningLiveSource(service.live_perception_ingress)),
)
@@ -22641,6 +22641,7 @@ class XgridsK1CompatibilityService:
def dispatch_admission_deadline_reached() -> bool:
return self._operations.deadline_reached(operation.operation_id)
stop_ingress = self.live_perception_ingress.snapshot()
try:
self._application_control_session.request_stop(
confirmation=request.physical_acceptance.confirmation(),
@@ -22663,6 +22664,14 @@ class XgridsK1CompatibilityService:
expected_session_generation=(request.expected_control_session_generation),
expected_state_revision=request.expected_control_state_revision,
)
# End derived localisation after admission, not after the
# potentially long raw-recording/READY finalisation. A
# rejected synchronous request never reaches this edge.
if prepared_stop_lineage.evidence_session_id is not None:
self.live_perception_ingress.request_spatial_stop(
prepared_stop_lineage.evidence_session_id,
stop_ingress["session_generation"],
)
with self._lock:
# The fresh S1 now owns the durable edge. The retained
# S0 classification owner must not race or survive it.
@@ -0,0 +1,82 @@
"""Extract a bounded, provenance-carrying K1 submap from a saved interval."""
from __future__ import annotations
import bisect
import time
import numpy as np
from .protocol.streams import decode_lio_pcl
from .viewer.replay import iter_replay_messages
EXTRACTION = {'version': 'k1-submap/v1', 'max_frames': 120, 'max_raw_points': 2_000_000,
'max_retained_points': 1_000_000, 'voxel_m': .25,
'radius_m': 20., 'height_relative_m': [-3., 6.]}
def extract_submap(source, planning, start, end):
return _extract(source, planning, start, end, presentation=False)
def extract_scene_submap(source, planning, start, end):
"""Presentation geometry is never an input to numerical localisation."""
return _extract(source, planning, start, end, presentation=True)
def _extract(source, planning, start, end, *, presentation):
profile = ({**EXTRACTION, "version": "k1-scene-submap/v1",
"radius_m": 80.0, "height_relative_m": None} if presentation else EXTRACTION)
poses = planning['poses']
if not 0 <= start < end < len(poses):
raise ValueError('Некорректный интервал записи.')
if poses[end]['distance_m'] - poses[start]['distance_m'] > 40:
raise ValueError('Для первой проверки выберите участок не длиннее 40 м.')
lower, upper = poses[start]['message_index'], poses[end]['message_index']
started = time.monotonic()
def messages():
for ordinal, msg in enumerate(iter_replay_messages(source)):
if ordinal > 2_000_000 or time.monotonic() - started > 90:
raise ValueError('Превышен предел подготовки участка записи.')
if ordinal > upper:
break
if ordinal >= lower and msg.topic.endswith('/lio_pcl'):
yield ordinal, msg
eligible = [ordinal for ordinal, _ in messages()]
if not eligible:
raise ValueError('На выбранном участке нет кадров облака.')
selected = {eligible[int(i)] for i in np.linspace(0, len(eligible)-1, min(120, len(eligible)))}
pose_ordinals = [p['message_index'] for p in poses]
chunks, provenance = [], []
raw_count = retained_count = 0
for ordinal, msg in messages():
if ordinal not in selected:
continue
frame = decode_lio_pcl(msg.payload) # Fail closed on any selected corrupt frame.
xyz = np.array([p.scaled_xyz(frame.header.scaler) for p in frame.points], dtype=np.float64)
if not len(xyz):
continue
if not np.isfinite(xyz).all():
raise ValueError('В облаке обнаружены некорректные координаты.')
pose = poses[bisect.bisect_right(pose_ordinals, ordinal)-1]
delta = xyz - np.asarray(pose['position'])
keep = np.linalg.norm(delta, axis=1) <= profile["radius_m"]
if profile["height_relative_m"] is not None:
low, high = profile["height_relative_m"]
keep &= (delta[:, 2] >= low) & (delta[:, 2] <= high)
raw_count += len(xyz); retained_count += int(keep.sum())
if raw_count > EXTRACTION['max_raw_points'] or retained_count > EXTRACTION['max_retained_points']:
raise ValueError('Облако превышает предел размера проверочного участка.')
chunks.append(xyz[keep]) # K1 publishes map-space points: no second pose transform.
timing_available = pose['elapsed_s'] is not None
provenance.append({'message_index': ordinal, 'sequence': msg.sequence,
'received_monotonic_ns': msg.received_monotonic_ns if timing_available else None,
'received_at_epoch_ns': msg.received_at_epoch_ns if timing_available else None,
'pose_index': pose['index']})
points = np.concatenate(chunks) if chunks else np.empty((0, 3))
_, indices = np.unique(np.floor(points / .25).astype(np.int64), axis=0, return_index=True)
points = points[np.sort(indices)]
if presentation and len(points) > 100_000:
# Display LOD spans the entire extracted volume, never a height slice.
points = points[np.linspace(0, len(points)-1, 100_000, dtype=int)]
return points, {'extraction': profile, 'start_index': start, 'end_index': end,
'message_interval': [lower, upper], 'available_frames': len(eligible),
'frames': provenance, 'raw_points': raw_count, 'retained_points': retained_count,
'voxel_points': len(points), 'extraction_seconds': time.monotonic() - started}
@@ -39,7 +39,7 @@ from k1link.web.camera_archive import recover_incomplete_camera_archives
XGRIDS_K1_PLUGIN_ID = "nodedc.device.xgrids-lixelkity-k1"
def build_xgrids_k1_observation(repository_root: Path) -> ObservationRuntimeContribution:
def build_xgrids_k1_observation(repository_root: Path, live_planning_source=None) -> ObservationRuntimeContribution:
"""Compose every K1 evidence root behind the generic observation ABI."""
configured_legacy_root = os.environ.get(
@@ -58,6 +58,9 @@ def build_xgrids_k1_observation(repository_root: Path) -> ObservationRuntimeCont
),
)
point_colors = RecordedPointColorOverlayStore()
from .session_overview import export_session_overview
from .planning_source import export_planning_source
from .localization_source import extract_submap, extract_scene_submap
return ObservationRuntimeContribution(
archives=tuple(
ObservationArchiveSource(
@@ -71,6 +74,11 @@ def build_xgrids_k1_observation(repository_root: Path) -> ObservationRuntimeCont
),
recording_exporter=_export_recording,
point_color_renderer=point_colors.render,
overview_exporter=export_session_overview,
planning_exporter=export_planning_source,
submap_extractor=extract_submap,
scene_submap_extractor=extract_scene_submap,
live_planning_source=live_planning_source,
)
@@ -0,0 +1,74 @@
"""Planning profile uses the existing exclusive derived-data lease, never MQTT."""
import json
import numpy as np
from k1link.sessions.live_planning import PlanningLiveEvent
from .protocol.streams import (
decode_legacy_pointcloud,
decode_legacy_pose,
decode_lio_pcl,
decode_lio_pose,
)
def decode_planning_event(identity, source_id, modality, payload):
"""One decoder for committed live ingress and receipt-paced archive replay."""
if modality == "pose":
frame = (
decode_legacy_pose(payload) if source_id == "RealtimePath" else decode_lio_pose(payload)
)
return PlanningLiveEvent(
**identity,
kind="pose",
position=frame.position_xyz,
orientation_xyzw=frame.orientation_xyzw,
)
if modality == "lidar":
if source_id == "RealtimePointcloud":
frame = decode_legacy_pointcloud(payload, max_points=100_000)
points = np.array([[p.x, p.y, p.z] for p in frame.points], dtype=float).reshape(-1, 3)
else:
frame = decode_lio_pcl(payload)
# Published points already occupy the K1 map frame.
points = np.array(
[p.scaled_xyz(frame.header.scaler) for p in frame.points], dtype=float
).reshape(-1, 3)
if len(points) > 100_000 or not np.isfinite(points).all():
raise ValueError("Некорректный кадр облака.")
return PlanningLiveEvent(**identity, kind="points", points=points)
if modality == "control":
return PlanningLiveEvent(**identity, kind=json.loads(payload)["event"])
return None
class K1PlanningLiveSource:
def __init__(self, ingress):
self.ingress = ingress
def snapshot(self):
return self.ingress.snapshot()
def open(self, consumer_id):
self.ingress.open_consumer(consumer_id)
def close(self, consumer_id):
self.ingress.close_consumer(consumer_id)
def take(self, consumer_id):
event = self.ingress.take_next(consumer_id, timeout=0.25)
if event is None:
return None
identity = dict(
session_id=event.session_id,
generation=event.session_generation,
sequence=event.ingress_sequence,
monotonic_ns=event.received_monotonic_ns,
epoch_ns=event.captured_at_epoch_ns,
)
decoded = decode_planning_event(identity, event.source_id, event.modality, event.payload)
# Preserve one receipt per turn, including modalities planning ignores.
# None means no receipt: bootstrap may use it to finish a queued prefix.
return decoded if decoded is not None else PlanningLiveEvent(**identity, kind="ignored")
@@ -0,0 +1,39 @@
"""Read-only planning events with original, mandatory host receipt clocks."""
from .planning_live import decode_planning_event
from .viewer.replay import detect_replay_format, iter_replay_messages
def iter_planning_events(source, session_id):
if (
detect_replay_format(source) != "k1mqtt"
or not source.with_name("mqtt.metadata.jsonl").is_file()
):
raise ValueError("Causal replay requires native receipt metadata.")
previous = -1
for message in iter_replay_messages(source):
stamp = message.received_monotonic_ns
if stamp is None or stamp < previous:
raise ValueError("Missing or non-monotonic receipt clock.")
previous = stamp
modality = (
"pose"
if message.topic.endswith("/lio_pose")
else "lidar"
if message.topic.endswith("/lio_pcl")
else None
)
if modality is None:
continue
yield decode_planning_event(
dict(
session_id=session_id,
generation=1,
sequence=message.sequence,
monotonic_ns=stamp,
epoch_ns=message.received_at_epoch_ns,
),
message.topic,
modality,
message.payload,
)
@@ -0,0 +1,58 @@
"""Read the complete recorded scanner trajectory; never reapply K1 poses to its map."""
from __future__ import annotations
import json
import math
import time
from pathlib import Path
from .protocol.streams import decode_lio_pcl, decode_lio_pose
from .viewer.replay import detect_replay_format, iter_replay_messages
def export_planning_source(source: Path, destination: Path, *, cancel_event=None, activity_callback=None) -> dict:
poses = []
distance = 0.0
first_time = None
point_frames = errors = 0
started = time.monotonic()
timing = detect_replay_format(source) != 'k1mqtt' or source.with_name('mqtt.metadata.jsonl').is_file()
for ordinal, message in enumerate(iter_replay_messages(source)):
if ordinal % 100 == 0:
if time.monotonic() - started > 90 or (cancel_event is not None and cancel_event.is_set()):
raise ValueError('Превышено время подготовки траектории.')
if activity_callback:
activity_callback()
if ordinal > 2_000_000:
raise ValueError('Запись превышает размер поддерживаемой зоны.')
try:
if message.topic.endswith('/lio_pcl'):
# Prove a spatial payload once. Route extraction does not decode the
# entire cloud a second time; full cloud diagnostics belong to Overview.
if point_frames:
point_frames += 1
elif decode_lio_pcl(message.payload).points:
point_frames = 1
continue
if not message.topic.endswith('/lio_pose'):
continue
frame = decode_lio_pose(message.payload)
except ValueError:
errors += 1
continue
xyz = list(frame.position_xyz)
if not all(math.isfinite(v) for v in xyz):
raise ValueError('Траектория содержит некорректные координаты.')
if len(poses) >= 100_000:
raise ValueError('Траектория превышает 100 000 положений.')
if poses:
distance += math.dist(poses[-1]['position'], xyz)
timestamp = (message.received_monotonic_ns if message.received_monotonic_ns is not None else message.received_at_epoch_ns) if timing else None
if first_time is None:
first_time = timestamp
poses.append({'index': len(poses), 'message_index': ordinal, 'position': xyz,
'elapsed_s': (timestamp - first_time) / 1e9 if timestamp is not None else None,
'distance_m': distance})
if len(poses) < 2 or not point_frames:
raise ValueError('Для зоны необходимы облако точек и траектория.')
result = {'poses': poses, 'path_m': distance, 'point_frames': point_frames, 'decode_errors': errors}
destination.write_text(json.dumps(result, allow_nan=False))
return {'pose_count': len(poses)}
@@ -0,0 +1,159 @@
"""Bounded display overview of a K1 archive, independent of live preview drops."""
from __future__ import annotations
import math
import threading
from pathlib import Path
from typing import Callable
import numpy as np
import rerun as rr
from rerun import blueprint as rrb
from .protocol.streams import decode_lio_pcl, decode_lio_pose
from .viewer.replay import detect_replay_format, iter_replay_messages
from .protocol.normalizer import normalize_k1_message
from k1link.data_plane import DecodedPointCloudView, DecodedPoseView
MAX_SAMPLE = 180_000
MAX_SERIES = 200_000
def export_session_overview(source: Path, destination: Path, *,
cancel_event: threading.Event | None = None,
activity_callback: Callable[[], None] | None = None) -> dict:
point_frames = pose_frames = points_total = errors = 0
samples: list[np.ndarray] = []
sample_count = 0
stride = 64
poses: list[tuple[float, float, float]] = []
pose_stride = 1
intervals: list[float] = []
path_length = 0.0
first_pose = last_pose = None
last_cloud_time = first_cloud_time = None
timing_available = detect_replay_format(source) != 'k1mqtt' or source.with_name('mqtt.metadata.jsonl').is_file()
sequence_previous: dict[str, int] = {}
sequence_gaps = sequence_backwards = 0
arrival_backwards = 0
max_gap = 0.0
gaps_over_second = 0
chart: dict[int, tuple[float, float]] = {}
chart_bucket_seconds = 1
messages = 0
for message in iter_replay_messages(source):
if cancel_event is not None and cancel_event.is_set():
raise RuntimeError('overview cancelled')
messages += 1
if messages % 100 == 0 and activity_callback:
activity_callback()
xyz = pose = None
try:
if message.topic.endswith('/lio_pcl'):
frame = decode_lio_pcl(message.payload)
xyz = np.array(frame.points, dtype=np.float64).reshape(-1, 4)[:, :3] / frame.header.scaler
seq = frame.header.seq
elif message.topic.endswith('/lio_pose'):
frame = decode_lio_pose(message.payload)
pose = frame.position_xyz
seq = frame.header.seq
else:
view = normalize_k1_message(message, processing_started_monotonic_ns=0)
if isinstance(view, DecodedPointCloudView):
xyz = np.asarray(view.positions_xyz, dtype=np.float64).reshape(-1, 3)
elif isinstance(view, DecodedPoseView):
pose = view.position_xyz
else:
continue
seq = None
if seq is not None:
previous = sequence_previous.get(message.topic)
if previous is not None:
sequence_gaps += max(0, seq - previous - 1)
sequence_backwards += int(seq <= previous)
sequence_previous[message.topic] = seq
except (ValueError, OverflowError):
errors += 1
continue
if xyz is not None:
point_frames += 1
points_total += len(xyz)
if len(xyz):
samples.append(xyz[(point_frames % min(stride, len(xyz)))::stride].astype(np.float32))
sample_count += len(samples[-1])
if sample_count > MAX_SAMPLE:
samples = [np.concatenate(samples)[::2]]
sample_count = len(samples[0])
stride *= 2
if timing_available:
t = (message.received_monotonic_ns if message.received_monotonic_ns is not None else message.received_at_epoch_ns) / 1e9
if first_cloud_time is None:
first_cloud_time = t
if last_cloud_time is not None:
gap = t - last_cloud_time
arrival_backwards += int(gap < 0)
if gap >= 0:
max_gap = max(max_gap, gap)
gaps_over_second += int(gap > 1)
if len(intervals) < MAX_SERIES:
intervals.append(gap)
elapsed = t - first_cloud_time
bucket = int(elapsed // chart_bucket_seconds)
if bucket not in chart or gap > chart[bucket][1]:
chart[bucket] = (elapsed, gap)
if len(chart) > 1600:
chart_bucket_seconds *= 2
merged: dict[int, tuple[float, float]] = {}
for item in chart.values():
b = int(item[0] // chart_bucket_seconds)
if b not in merged or item[1] > merged[b][1]:
merged[b] = item
chart = merged
last_cloud_time = t
if pose is not None:
if not all(math.isfinite(v) for v in pose):
errors += 1
continue
pose_frames += 1
if first_pose is None:
first_pose = pose
if last_pose is not None:
path_length += math.dist(pose, last_pose)
last_pose = pose
if pose_frames % pose_stride == 0:
poses.append(pose)
if len(poses) > 20_000:
poses = poses[::2]
pose_stride *= 2
cloud = np.concatenate(samples) if samples else np.empty((0, 3), dtype=np.float32)
recording = rr.RecordingStream('missioncore_session_overview')
recording.save(str(destination))
recording.log('world', rr.ViewCoordinates.RIGHT_HAND_Z_UP, static=True)
if len(cloud):
# Fixed renderer colors encode geometry, not product control states.
height = cloud[:, 2]
low, high = np.quantile(height, [.05, .95])
normalized = np.clip((height-low) / max(high-low, .01), 0, 1)
colors = np.column_stack([70+100*normalized, 135+80*normalized, 220-90*normalized]).astype(np.uint8)
recording.log('world/cloud', rr.Points3D(cloud, colors=colors, radii=rr.Radius.ui_points(1.5)), static=True)
if len(poses) > 1:
recording.log('world/route', rr.LineStrips3D([poses], colors=[180, 240, 90], radii=rr.Radius.ui_points(2)), static=True)
recording.log('world/endpoints', rr.Points3D([first_pose, last_pose], labels=['Старт', 'Финиш'], colors=[245, 248, 240], radii=rr.Radius.ui_points(5)), static=True)
recording.send_blueprint(rrb.Blueprint(rrb.Spatial3DView(name='Облако и траектория', origin='/world', background=[9, 10, 12, 255]), collapse_panels=True), make_active=True)
recording.flush()
recording.disconnect()
span = last_cloud_time-first_cloud_time if first_cloud_time is not None and last_cloud_time is not None else None
return {
'point_frames': point_frames, 'pose_frames': pose_frames, 'point_count': points_total,
'sample_points': len(cloud), 'decode_errors': errors,
'sequence_gaps': sequence_gaps, 'sequence_nonincreasing': sequence_backwards,
'path_m': path_length if pose_frames > 1 else None,
'start_end_m': math.dist(first_pose, last_pose) if pose_frames > 1 else None,
'stream_seconds': span, 'mean_hz': (point_frames-1)/span if span and span > 0 else None,
'interval_p95_s': float(np.quantile(intervals, .95)) if intervals else None,
'interval_statistics_complete': point_frames-1 <= MAX_SERIES,
'interval_max_s': max_gap if intervals else None, 'gaps_over_second': gaps_over_second if intervals else None,
'arrival_backwards': arrival_backwards, 'chart': sorted(chart.values()),
'chart_bucket_seconds': chart_bucket_seconds,
'spatial_available': bool(len(cloud) or poses),
}