feat: finalize corrected-route planning and Rerun recording review

This commit is contained in:
DCCONSTRUCTIONS
2026-09-22 10:10:03 +03:00
parent c804d89b18
commit 2e5d52521f
132 changed files with 14141 additions and 898 deletions
@@ -15,6 +15,7 @@ from k1link.device_plugins.xgrids_k1.archive import (
from k1link.device_plugins.xgrids_k1.recorded_point_colors import (
RecordedPointColorOverlayStore,
)
from k1link.device_plugins.xgrids_k1.recorded_point_display import render_point_display
from k1link.device_plugins.xgrids_k1.rrd_export import (
RrdExportCancelled,
RrdExportError,
@@ -74,6 +75,7 @@ def build_xgrids_k1_observation(repository_root: Path, live_planning_source=None
),
recording_exporter=_export_recording,
point_color_renderer=point_colors.render,
point_display_renderer=render_point_display,
overview_exporter=export_session_overview,
planning_exporter=export_planning_source,
submap_extractor=extract_submap,
@@ -267,6 +269,8 @@ def _export_recording(
cancel_event: threading.Event | None = None,
activity_callback: object | None = None,
) -> dict[str, object]:
from k1link.reconstruction.recorded_geometry import RecordedMapGeometry
try:
return dict(
export_k1mqtt_to_rrd(
@@ -280,9 +284,14 @@ def _export_recording(
),
cancel_event=cancel_event,
activity_callback=activity_callback if callable(activity_callback) else None,
map_geometry=RecordedMapGeometry.optional(artifacts),
)
)
except RrdExportCancelled as exc:
raise PluginRecordingExportCancelled("K1 recording export was cancelled") from exc
except RrdExportError as exc:
raise PluginRecordingExportError("K1 recording export failed") from exc
# Explicit exporter capability: other plugins must not silently ignore a pinned map.
_export_recording.supports_map_versions = True
@@ -0,0 +1,47 @@
"""Read display rows from the pinned, already verified operator RRD.
The canonical exporter bakes intensity/Turbo colors into this derived file.
Reading Arrow arrays avoids normalizing the complete raw transport again, and
retains the exact corrected geometry and colors already used by the viewer.
"""
from pathlib import Path
import numpy as np
import pyarrow as pa
import rerun_bindings as bindings
def prepared_point_rows(path: Path):
reader = bindings.RrdReaderInternal(str(path))
stores = [entry for entry in reader.store_entries() if entry.kind == "recording"]
if len(stores) != 1:
raise ValueError("display source must contain exactly one recording")
count = 0
for chunk in reader.stream(stores[0]):
if str(chunk.entity_path) != "/world/points":
continue
batch = chunk.to_record_batch()
names = batch.column_names
if "Points3D:positions" not in names:
continue
if not {"session_time", "message_sequence", "Points3D:colors"}.issubset(names):
raise ValueError("prepared points are missing temporal/color ownership")
times = batch.column(names.index("session_time")).cast(pa.int64()).to_numpy()
sequences = batch.column(names.index("message_sequence")).to_numpy()
positions = batch.column(names.index("Points3D:positions"))
colors = batch.column(names.index("Points3D:colors"))
for row, time_ns in enumerate(times):
if not positions[row].is_valid:
continue
xyz = positions[row].values.flatten().to_numpy().reshape(-1, 3)
if not colors[row].is_valid:
raise ValueError("prepared point colors are unavailable")
rgba = colors[row].values.to_numpy()
if len(rgba) == 1:
rgba = np.repeat(rgba, len(xyz))
if len(rgba) != len(xyz):
raise ValueError("prepared color count does not match positions")
count += 1
yield int(sequences[row]), int(time_ns), xyz, rgba
if not count:
raise ValueError("prepared recording has no point frames")
@@ -6,6 +6,7 @@ import hashlib
import json
import os
import threading
from collections.abc import Iterator
from collections import OrderedDict
from contextlib import suppress
from dataclasses import dataclass
@@ -121,6 +122,16 @@ class RecordedPointColorOverlayStore:
capture_clock,
capture_clock_origin,
)
geometry = None
if command.map_version is not None:
from k1link.reconstruction.recorded_geometry import RecordedMapGeometry
paths = {
"map-version-" + name: command.map_version.directory / name
for name in ("manifest.json", "points.f32", "trajectory.npz")
}
geometry = RecordedMapGeometry(paths)
source_identity += (geometry.generation, *_source_identity(*paths.values()))
settings = RerunSceneSettings(
color_mode=color_mode,
palette=palette,
@@ -129,11 +140,7 @@ class RecordedPointColorOverlayStore:
settings_key = (
color_mode,
palette,
(
custom_color.casefold()
if palette == "custom" or color_mode == "class"
else "-"
),
(custom_color.casefold() if palette == "custom" or color_mode == "class" else "-"),
)
payload_key = (*source_identity, application_id, recording_id, *settings_key)
@@ -156,6 +163,7 @@ class RecordedPointColorOverlayStore:
metadata,
capture_clock,
capture_clock_origin,
geometry,
)
payload = _render_color_overlay(
index.frames,
@@ -173,6 +181,7 @@ class RecordedPointColorOverlayStore:
metadata: Path | None,
capture_clock: Path | None,
capture_clock_origin: Path | None,
geometry=None,
) -> _PointColorIndex:
with self._lock:
cached = self._indexes.get(source_identity)
@@ -187,6 +196,7 @@ class RecordedPointColorOverlayStore:
capture_clock,
capture_clock_origin,
source_identity=source_identity,
geometry=geometry,
)
if index.byte_length > self._index_cache_bytes:
return index
@@ -222,7 +232,17 @@ def _build_index(
capture_clock_origin: Path | None,
*,
source_identity: tuple[object, ...],
geometry=None,
) -> _PointColorIndex:
frames = tuple(_iter_point_frames(source, metadata, capture_clock, capture_clock_origin,
geometry=geometry))
return _PointColorIndex(source_identity, frames, sum(frame.byte_length for frame in frames))
def _iter_point_frames(
source: Path, metadata: Path, capture_clock: Path | None,
capture_clock_origin: Path | None, *, geometry=None,
) -> Iterator[_PointColorFrame]:
try:
envelope = None if capture_clock is None else read_capture_clock_envelope(capture_clock)
origin = (
@@ -232,9 +252,13 @@ def _build_index(
)
except CaptureFormatError as exc:
raise RecordedPointColorError("native point-color clock is invalid") from exc
if envelope is not None and origin is not None and (
envelope.started_at_epoch_ns != origin.started_at_epoch_ns
or envelope.started_monotonic_ns != origin.started_monotonic_ns
if (
envelope is not None
and origin is not None
and (
envelope.started_at_epoch_ns != origin.started_at_epoch_ns
or envelope.started_monotonic_ns != origin.started_monotonic_ns
)
):
raise RecordedPointColorError("native point-color clocks do not match")
session_origin_ns = (
@@ -245,11 +269,11 @@ def _build_index(
else None
)
frames: list[_PointColorFrame] = []
total_bytes = 0
frame_count = 0
point_frame_number = 0
previous_sequence = 0
previous_monotonic_ns: int | None = None
first_raw_receipt_s = None
try:
source_size = source.stat().st_size
with source.open("rb") as raw_stream, metadata.open("r", encoding="utf-8") as index_stream:
@@ -274,6 +298,8 @@ def _build_index(
raise RecordedPointColorError("native point-color timeline decreases")
previous_sequence = sequence
previous_monotonic_ns = monotonic_ns
if first_raw_receipt_s is None:
first_raw_receipt_s = monotonic_ns / 1e9
if session_origin_ns is None:
session_origin_ns = monotonic_ns
topic = record.get("topic")
@@ -333,6 +359,12 @@ def _build_index(
if decoded.colors_rgb is None
else np.frombuffer(decoded.colors_rgb, dtype=np.uint8).reshape((-1, 3))
)
if geometry is not None:
positions = geometry.points(
point_frame_number - 1,
monotonic_ns / 1e9 - first_raw_receipt_s,
decoded.point_count,
)
positions, intensities, rgb = _recorded_view_points(
positions,
intensities,
@@ -346,17 +378,12 @@ def _build_index(
intensities=intensities.copy(),
rgb=None if rgb is None else rgb.copy(),
)
frames.append(frame)
total_bytes += frame.byte_length
frame_count += 1
yield frame
except (OSError, json.JSONDecodeError, UnicodeError) as exc:
raise RecordedPointColorError("native point-color index could not be read") from exc
if session_origin_ns is None or not frames:
if session_origin_ns is None or not frame_count:
raise RecordedPointColorError("native point-color index contains no point frames")
return _PointColorIndex(
source_identity=source_identity,
frames=tuple(frames),
byte_length=total_bytes,
)
def _render_color_overlay(
@@ -0,0 +1,119 @@
"""Streaming, display-only point thinning. Never edits raw or mapping evidence."""
from __future__ import annotations
import math
import logging
import re
import struct
import threading
import time
from pathlib import Path
from collections.abc import Iterator
from contextlib import suppress
import numpy as np
import rerun as rr
from k1link.sessions import ReplayCommand
from k1link.viewer.rerun_bridge import RerunSceneSettings, _point_colors
from .recorded_point_colors import _artifact_path, _iter_point_frames
from .rrd_export import APPLICATION_ID, SESSION_TIMELINE
DISPLAY_POINTS_PATH = "/world/display_points"
_render_slot = threading.BoundedSemaphore(1)
_logger = logging.getLogger(__name__)
def retained_indices(count: int, decimation: float, sequence: int) -> np.ndarray:
"""Exact per-frame count; stable ranked samples, not a LiDAR-ring stride."""
if not math.isfinite(decimation) or not 0 <= decimation <= 100:
raise ValueError("invalid point decimation")
keep = int(math.floor(count * (100 - decimation) / 100 + 0.5))
if keep == count:
return np.arange(count)
if keep == 0:
return np.empty(0, dtype=np.int64)
# A bijective integer mix gives a reproducible order and nested samples.
keys = np.arange(count, dtype=np.uint32) ^ np.uint32(sequence & 0xFFFFFFFF)
keys ^= keys >> 16
keys *= np.uint32(0x7FEB352D)
keys ^= keys >> 15
keys *= np.uint32(0x846CA68B)
keys ^= keys >> 16
return np.sort(np.argpartition(keys, keep - 1)[:keep])
def render_point_display(command: ReplayCommand, *, application_id: str, recording_id: str,
color_mode: str, palette: str, custom_color: str,
point_decimation_percent: float, display_bank: str,
prepared_recording_path: Path | None = None) -> Iterator[bytes]:
if application_id != APPLICATION_ID or not 0 < point_decimation_percent < 100 or not re.fullmatch(r"[a-f0-9]{32}", display_bank):
raise ValueError("invalid point display request")
settings = RerunSceneSettings(color_mode=color_mode, palette=palette, custom_color=custom_color)
frames = _display_rows(command, settings, prepared_recording_path)
if not _render_slot.acquire(timeout=30):
raise RuntimeError("point display preparation is busy")
recording = None
started = time.monotonic()
input_points = output_points = frame_count = 0
try:
yield b'NPD1'
batch_points = 0
for index, (sequence, time_ns, positions, colors) in enumerate(frames):
if recording is None:
recording = rr.RecordingStream(application_id, recording_id=recording_id, send_properties=False)
stream = rr.binary_stream(recording)
selected = retained_indices(len(positions), point_decimation_percent, sequence)
input_points += len(positions)
output_points += len(selected)
frame_count += 1
recording.set_time(SESSION_TIMELINE, duration=np.timedelta64(time_ns, "ns"))
recording.log(f"{DISPLAY_POINTS_PATH}/{display_bank}", rr.Points3D(positions[selected], colors=colors[selected]))
batch_points += len(selected)
if index % 64 == 63 or batch_points >= 131072:
payload = stream.read(flush=True, flush_timeout_sec=30.0)
recording.disconnect()
recording = None
batch_points = 0
yield struct.pack('<I', len(payload)) + payload
if recording is not None:
payload = stream.read(flush=True, flush_timeout_sec=30.0)
recording.disconnect()
recording = None
yield struct.pack('<I', len(payload)) + payload
_logger.info("Point display ready: bank=%s frames=%d input_points=%d output_points=%d decimation=%s elapsed_s=%.3f",
display_bank, frame_count, input_points, output_points,
point_decimation_percent, time.monotonic() - started)
yield struct.pack('<I', 0)
finally:
frames.close()
with suppress(Exception):
if recording is not None:
recording.disconnect()
_render_slot.release()
def _display_rows(command, settings, prepared_recording_path):
if prepared_recording_path is not None and settings.color_mode == "intensity" and settings.palette == "turbo":
from .prepared_point_display import prepared_point_rows
yield from prepared_point_rows(prepared_recording_path)
return
metadata = _artifact_path(command, "raw-transport-index")
if metadata is None:
raise ValueError("point index is unavailable")
geometry = None
if command.map_version is not None:
from k1link.reconstruction.recorded_geometry import RecordedMapGeometry
geometry = RecordedMapGeometry({"map-version-" + name: command.map_version.directory / name
for name in ("manifest.json", "points.f32", "trajectory.npz")})
frames = _iter_point_frames(command.primary_artifact.path, metadata,
_artifact_path(command, "raw-transport-clock"),
_artifact_path(command, "raw-transport-clock-origin"), geometry=geometry)
try:
for frame in frames:
# Compute the same palette range on the full frame, then select the
# matching rows; thinning must not shift colors or corrected geometry.
colors = _point_colors(frame.positions, frame.intensities, frame.rgb, settings)
yield frame.sequence, frame.session_time_ns, frame.positions, colors
finally:
frames.close()
@@ -6,7 +6,7 @@ import os
import threading
from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Literal, TypedDict
from uuid import UUID, uuid4
@@ -52,9 +52,6 @@ APPLICATION_ID = "nodedc_mission_core_recorded"
SESSION_TIMELINE = "session_time"
CAPTURE_TIMELINE = "capture_time"
JS_MAX_SAFE_INTEGER = (1 << 53) - 1
RECORDED_VIEW_POINT_DECIMATION_THRESHOLD = 100_000
RECORDED_VIEW_POINT_STRIDE = 4
RECORDED_VIEW_POINT_FRAME_STRIDE = 5
RECORDED_RRD_IDENTITY_VERSION = "missioncore.recorded-rrd/v1"
# Rerun keys viewer state by these IDs. Reusing them for every settings-only
@@ -195,16 +192,17 @@ def export_k1mqtt_to_rrd(
capture_clock_origin_path: Path | None = None,
cancel_event: threading.Event | None = None,
activity_callback: Callable[[], None] | None = None,
map_geometry=None,
) -> RrdExportSummary:
"""Project a bounded-rate view of K1 data into one operator RRD.
"""Project every captured K1 cloud frame into one operator RRD.
The raw capture remains the source of record. The derived RRD uses a
recording-local duration timeline whose zero is the durable capture-clock
origin for v2 recordings (or the first raw message for legacy captures).
It never traverses the bounded live-preview queue. Point-cloud frames and
very dense point batches are deterministically sampled for interactive
rendering while counters, poses, capture boundaries and the native capture
remain complete. AI jobs always read the complete native capture.
It never traverses the bounded live-preview queue or samples away points
and frames. Counters, poses and capture boundaries remain complete, and
an admitted corrected map supplies its exact per-frame positions. AI jobs
still read the complete native capture, independently of this projection.
The destination is replaced only after the temporary RRD has been closed,
flushed and fsynced. Any decode, timing, sink or rename failure therefore
@@ -236,6 +234,8 @@ def export_k1mqtt_to_rrd(
capture_clock,
capture_clock_origin,
)
if map_geometry is not None:
recording_id = map_geometry.recording_id(recording_id)
temporary = destination.with_name(f".{destination.name}.{uuid4()}.tmp")
settings = RerunSceneSettings()
blueprint = _recorded_blueprint(settings)
@@ -264,6 +264,7 @@ def export_k1mqtt_to_rrd(
previous_monotonic_ns: int | None = None
last_source_time_ns: int | None = None
last_source_capture_ns: int | None = None
first_raw_receipt_s: float | None = None
try:
recording = rr.RecordingStream(APPLICATION_ID, recording_id=recording_id)
@@ -297,6 +298,9 @@ def export_k1mqtt_to_rrd(
f"native capture message {message.sequence} is outside its clock envelope"
)
session_time_ns = monotonic_ns - session_origin_ns
if first_raw_receipt_s is None:
first_raw_receipt_s = monotonic_ns / 1e9
map_time_s = monotonic_ns / 1e9 - first_raw_receipt_s
if session_time_ns > JS_MAX_SAFE_INTEGER:
raise RrdExportError(
"session duration exceeds the exact JavaScript nanosecond range"
@@ -345,9 +349,19 @@ def export_k1mqtt_to_rrd(
if isinstance(decoded, DecodedPointCloudView):
counters.point_frames += 1
counters.points += decoded.point_count
positions = (
None
if map_geometry is None
else map_geometry.points(
counters.point_frames - 1, map_time_s, decoded.point_count
)
)
if _should_publish_recorded_point_frame(counters.point_frames):
_log_points(recording, decoded, settings)
_log_points(recording, decoded, settings, positions=positions)
elif isinstance(decoded, DecodedPoseView):
if map_geometry is not None:
xyz, quaternion = map_geometry.pose(counters.pose_frames, map_time_s)
decoded = replace(decoded, position_xyz=xyz, orientation_xyzw=quaternion)
position = (
float(decoded.position_xyz[0]),
float(decoded.position_xyz[1]),
@@ -359,6 +373,8 @@ def export_k1mqtt_to_rrd(
else:
counters.ignored_messages += 1
if map_geometry is not None:
map_geometry.complete(counters.point_frames, counters.pose_frames)
if session_origin_ns is None:
raise RrdExportError("native capture contains no messages")
if counters.decoded_messages == 0:
@@ -471,12 +487,8 @@ def _stable_recording_id(
str(capture_clock.started_monotonic_ns) if capture_clock is not None else "-",
str(capture_clock.completed_at_epoch_ns) if capture_clock is not None else "-",
str(capture_clock.completed_monotonic_ns) if capture_clock is not None else "-",
str(capture_clock_origin.started_at_epoch_ns)
if capture_clock_origin is not None
else "-",
str(capture_clock_origin.started_monotonic_ns)
if capture_clock_origin is not None
else "-",
str(capture_clock_origin.started_at_epoch_ns) if capture_clock_origin is not None else "-",
str(capture_clock_origin.started_monotonic_ns) if capture_clock_origin is not None else "-",
):
identity.update(value.encode("ascii"))
identity.update(b"\0")
@@ -814,8 +826,11 @@ def _log_points(
recording: rr.RecordingStream,
frame: DecodedPointCloudView,
settings: RerunSceneSettings,
*,
positions: np.ndarray | None = None,
) -> None:
positions = np.asarray(frame.positions_xyz, dtype=np.float32).reshape((-1, 3))
if positions is None:
positions = np.asarray(frame.positions_xyz, dtype=np.float32).reshape((-1, 3))
if frame.intensities is None:
intensities = np.full(frame.point_count, 255, dtype=np.uint8)
else:
@@ -841,28 +856,18 @@ def _recorded_view_points(
intensities: np.ndarray,
rgb: np.ndarray | None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]:
# The native K1 capture remains the complete source of record and all AI
# jobs read that source directly. Rerun is the interactive operator
# projection: bound the temporal frame rate, but preserve complete normal
# K1 scans. The AI composition intentionally uses one latest point frame
# so dynamic cuboids do not stack; thinning a normal ~2.4k-point scan here
# made that view visibly bald. Keep spatial decimation only as an emergency
# guard for unusually large (>100k point) frames from future hardware.
if len(positions) <= RECORDED_VIEW_POINT_DECIMATION_THRESHOLD:
return positions, intensities, rgb
return (
positions[::RECORDED_VIEW_POINT_STRIDE],
intensities[::RECORDED_VIEW_POINT_STRIDE],
None if rgb is None else rgb[::RECORDED_VIEW_POINT_STRIDE],
)
# An archive is a faithful projection, not a lossy preview. Keep attributes
# aligned and use the visible time window to control displayed history.
# Resource admission must fail explicitly rather than silently drop points.
return positions, intensities, rgb
def _should_publish_recorded_point_frame(frame_number: int) -> bool:
"""Keep the first point frame and then a stable 2 Hz operator cadence."""
"""Preserve every captured point frame, including its original timestamp."""
if frame_number < 1:
raise ValueError("point frame number must be positive")
return frame_number == 1 or (frame_number - 1) % RECORDED_VIEW_POINT_FRAME_STRIDE == 0
return True
def _log_pose(