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:
@@ -0,0 +1,30 @@
|
||||
"""Read-only, vendor-neutral preview input. No capture or device commands."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PlanningLiveEvent:
|
||||
session_id: str
|
||||
generation: int
|
||||
sequence: int
|
||||
monotonic_ns: int
|
||||
epoch_ns: int
|
||||
kind: str
|
||||
points: object = None
|
||||
position: object = None
|
||||
orientation_xyzw: object = None
|
||||
|
||||
|
||||
class PlanningLiveSource(Protocol):
|
||||
"""Return one receipt per take, or None only when no receipt is available.
|
||||
|
||||
Auxiliary modalities use kind='ignored' with identity/timestamps preserved
|
||||
and no payload. They are neither geometry nor an empty-queue signal.
|
||||
"""
|
||||
|
||||
def snapshot(self) -> dict: ...
|
||||
def open(self, consumer_id: str) -> None: ...
|
||||
def take(self, consumer_id: str) -> PlanningLiveEvent | None: ...
|
||||
def close(self, consumer_id: str) -> None: ...
|
||||
@@ -0,0 +1,128 @@
|
||||
"""On-demand, source-bound overview cache. No catalog-wide decoding."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Mapping
|
||||
from uuid import uuid4
|
||||
|
||||
from .store import SessionStore
|
||||
from .plugin_contract import RecordingExporter
|
||||
from .recording import (_validate_source, _validate_source_state,
|
||||
_validated_artifact_digests, _stage_replay_prefix)
|
||||
|
||||
SCHEMA = 'missioncore.session-overview/v1'
|
||||
|
||||
|
||||
class SessionOverviewService:
|
||||
def __init__(self, store: SessionStore, exporters: Mapping[str, RecordingExporter]):
|
||||
self.store = store
|
||||
self.exporters = exporters
|
||||
self.root = store.data_dir / 'session-overviews'
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='session-overview')
|
||||
self.guard = threading.RLock()
|
||||
self.cancel = threading.Event()
|
||||
self.jobs: dict[str, dict] = {}
|
||||
|
||||
def close(self) -> None:
|
||||
self.cancel.set()
|
||||
self.executor.shutdown(wait=True, cancel_futures=True)
|
||||
|
||||
def get(self, session_id: str, *, start: bool = True) -> dict:
|
||||
detail = self.store.get_session(session_id)
|
||||
base = {'schema_version': SCHEMA, 'session': detail.as_dict()}
|
||||
exporter = self.exporters.get(detail.plugin_id)
|
||||
if not detail.summary.replayable or detail.summary.lab is not None or exporter is None:
|
||||
return {**base, 'state': 'ready', 'metrics': None, 'scene_url': None}
|
||||
command = self.store.prepare_replay(session_id)
|
||||
source = _validate_source(command)
|
||||
identity = hashlib.sha256(json.dumps([SCHEMA, session_id, source.identity], default=str).encode()).hexdigest()
|
||||
directory = self.root / identity
|
||||
cached = self._cached(directory)
|
||||
if cached:
|
||||
return {**base, **cached, 'generation': identity, 'scene_url': f'/api/v1/observation-sessions/{session_id}/overview/scene.rrd?generation={identity}'}
|
||||
with self.guard:
|
||||
if identity in self.jobs:
|
||||
return {**base, **self.jobs[identity]}
|
||||
if not start:
|
||||
return {**base, 'state': 'missing'}
|
||||
if sum(j['state'] in {'queued', 'preparing'} for j in self.jobs.values()) >= 8:
|
||||
return {**base, 'state': 'error', 'message': 'Подготовка занята. Повторите позже.'}
|
||||
self.jobs[identity] = {'state': 'queued', 'messages_processed': 0}
|
||||
self.executor.submit(self._build, identity, source, exporter)
|
||||
return {**base, **self.jobs[identity]}
|
||||
|
||||
def retry(self, session_id: str) -> dict:
|
||||
detail = self.store.get_session(session_id)
|
||||
if detail.summary.replayable and detail.summary.lab is None:
|
||||
source = _validate_source(self.store.prepare_replay(session_id))
|
||||
identity = hashlib.sha256(json.dumps([SCHEMA, session_id, source.identity], default=str).encode()).hexdigest()
|
||||
with self.guard:
|
||||
if self.jobs.get(identity, {}).get('state') == 'error':
|
||||
self.jobs.pop(identity, None)
|
||||
return self.get(session_id)
|
||||
|
||||
def scene(self, session_id: str, generation: str) -> Path:
|
||||
current = self.get(session_id, start=False)
|
||||
if current.get('state') != 'ready' or current.get('generation') != generation:
|
||||
raise ValueError('overview generation is unavailable')
|
||||
return self.root / generation / 'scene.rrd'
|
||||
|
||||
def _cached(self, directory: Path) -> dict | None:
|
||||
try:
|
||||
report = directory / 'overview.json'
|
||||
if report.stat().st_size > 2 * 1024 * 1024:
|
||||
return None
|
||||
doc = json.loads(report.read_text())
|
||||
stat = (directory / 'scene.rrd').stat()
|
||||
if doc['schema_version'] != SCHEMA or [stat.st_size, stat.st_mtime_ns] != doc['scene_stat']:
|
||||
return None
|
||||
return {'state': 'ready', 'metrics': doc['metrics'], 'scene_sha256': doc['scene_sha256']}
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
def _build(self, identity: str, source, exporter: RecordingExporter) -> None:
|
||||
directory = self.root / identity
|
||||
directory.mkdir(exist_ok=True)
|
||||
candidate = directory / ('.' + uuid4().hex + '.rrd')
|
||||
staged = None
|
||||
try:
|
||||
with self.guard:
|
||||
self.jobs[identity] = {'state': 'preparing', 'messages_processed': 0}
|
||||
digests = _validated_artifact_digests(source)
|
||||
staged, primary, _ = _stage_replay_prefix(directory, source, cancel_event=self.cancel)
|
||||
def pulse():
|
||||
with self.guard:
|
||||
self.jobs[identity]['messages_processed'] += 100
|
||||
metrics = dict(exporter(primary, candidate, cancel_event=self.cancel, activity_callback=pulse))
|
||||
if self.cancel.is_set() or source.identity != _validate_source_state(source).identity:
|
||||
raise ValueError('overview source changed')
|
||||
if digests != _validated_artifact_digests(source):
|
||||
raise ValueError('overview source changed')
|
||||
if candidate.stat().st_size > 32 * 1024 * 1024:
|
||||
raise ValueError('overview exceeded display budget')
|
||||
digest = hashlib.sha256(candidate.read_bytes()).hexdigest()
|
||||
os.replace(candidate, directory / 'scene.rrd')
|
||||
stat = (directory / 'scene.rrd').stat()
|
||||
document = {'schema_version': SCHEMA, 'metrics': metrics, 'source_digests': digests,
|
||||
'scene_sha256': digest, 'scene_stat': [stat.st_size, stat.st_mtime_ns]}
|
||||
temporary = directory / '.overview.json'
|
||||
temporary.write_text(json.dumps(document, allow_nan=False))
|
||||
os.replace(temporary, directory / 'overview.json')
|
||||
with self.guard:
|
||||
self.jobs.pop(identity, None)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception('Session overview preparation failed')
|
||||
with self.guard:
|
||||
self.jobs[identity] = {'state': 'error', 'message': 'Не удалось подготовить обзор записи.'}
|
||||
finally:
|
||||
candidate.unlink(missing_ok=True)
|
||||
if staged is not None:
|
||||
shutil.rmtree(staged, ignore_errors=True)
|
||||
@@ -0,0 +1,86 @@
|
||||
"""View-only height clipping and camera presets for bounded overview RRDs."""
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
import rerun as rr
|
||||
from rerun import blueprint as rrb
|
||||
from rerun.experimental import RrdReader
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _geometry(path: Path, size: int, modified: int):
|
||||
if size > 32 * 1024 * 1024:
|
||||
raise ValueError('overview exceeds display budget')
|
||||
reader = RrdReader(path)
|
||||
entry = reader.recordings()[0]
|
||||
xyz = np.empty((0, 3), dtype=np.float32)
|
||||
colors = np.empty(0, dtype=np.uint32)
|
||||
for chunk in reader.stream():
|
||||
if chunk.entity_path == '/world/cloud':
|
||||
batch = chunk.to_record_batch()
|
||||
xyz = batch.column('Points3D:positions')[0].values.values.to_numpy().reshape(-1, 3)
|
||||
colors = batch.column('Points3D:colors')[0].values.to_numpy()
|
||||
if len(xyz) > 180_000 or not np.isfinite(xyz).all():
|
||||
raise ValueError('overview geometry is invalid')
|
||||
return entry.application_id, entry.recording_id, xyz, colors
|
||||
|
||||
|
||||
def geometry(path: Path):
|
||||
stat = path.stat()
|
||||
return _geometry(path, stat.st_size, stat.st_mtime_ns)
|
||||
|
||||
|
||||
def spatial_metadata(path: Path) -> dict:
|
||||
_, _, xyz, _ = geometry(path)
|
||||
return {'height_min_m': float(xyz[:, 2].min()) if len(xyz) else None,
|
||||
'height_max_m': float(xyz[:, 2].max()) if len(xyz) else None,
|
||||
'sample_points': len(xyz)}
|
||||
|
||||
|
||||
def _camera_eye(xyz: np.ndarray, mode: Literal['3d', 'top'], aspect: float) -> dict:
|
||||
points = xyz.astype(np.float64) if len(xyz) else np.array([[-1., -1., -1.], [1., 1., 1.]])
|
||||
center = (points.min(axis=0) + points.max(axis=0)) / 2
|
||||
centered = points - center
|
||||
# Align an elongated survey with the width of the viewport, regardless of K1's initial yaw.
|
||||
_, axes = np.linalg.eigh(centered[:, :2].T @ centered[:, :2])
|
||||
along = axes[:, -1]
|
||||
if along[np.argmax(np.abs(along))] < 0:
|
||||
along = -along
|
||||
side = np.array([-along[1], along[0], 0.])
|
||||
direction = np.array([0., 0., 1.]) if mode == 'top' else side * .8 + np.array([0., 0., .75])
|
||||
direction /= np.linalg.norm(direction)
|
||||
up = side if mode == 'top' else np.array([0., 0., 1.])
|
||||
right = np.cross(-direction, up)
|
||||
right /= np.linalg.norm(right)
|
||||
screen_up = np.cross(right, -direction)
|
||||
# Conservative 45-degree vertical field of view, with space around the cloud.
|
||||
tangent = np.tan(np.pi / 8)
|
||||
depth = centered @ direction
|
||||
required = np.maximum(np.abs(centered @ right) / (aspect * tangent),
|
||||
np.abs(centered @ screen_up) / tangent) + depth
|
||||
distance = max(2., float(required.max()) * 1.15)
|
||||
return {'position': (center + direction * distance).tolist(),
|
||||
'lookTarget': center.tolist(), 'eyeUp': up.tolist()}
|
||||
|
||||
|
||||
def render_spatial_update(path: Path, ceiling_m: float | None, mode: Literal['3d', 'top'] | None, aspect: float = 1.5):
|
||||
app_id, recording_id, xyz, colors = geometry(path)
|
||||
selected = xyz[:, 2] <= ceiling_m if ceiling_m is not None else np.ones(len(xyz), dtype=bool)
|
||||
recording = rr.RecordingStream(app_id, recording_id=recording_id, send_properties=False)
|
||||
sink = rr.binary_stream(recording)
|
||||
eye = None
|
||||
try:
|
||||
# Static replacement changes only the display derivative; poses and source metrics are untouched.
|
||||
recording.log('world/cloud', rr.Points3D(xyz[selected], colors=colors[selected], radii=rr.Radius.ui_points(1.5)), static=True)
|
||||
if mode is not None:
|
||||
eye = _camera_eye(xyz, mode, aspect)
|
||||
view = rrb.Spatial3DView(name='Облако и траектория', origin='/world', contents=['/world/**'],
|
||||
background=[9, 10, 12, 255], eye_controls=rrb.EyeControls3D(kind=rrb.Eye3DKind.Orbital,
|
||||
position=eye['position'], look_target=eye['lookTarget'], eye_up=eye['eyeUp']))
|
||||
recording.send_blueprint(rrb.Blueprint(view, auto_layout=False, auto_views=False, collapse_panels=True))
|
||||
data = sink.read(flush=True)
|
||||
return data, int(selected.sum()), eye
|
||||
finally:
|
||||
recording.disconnect()
|
||||
@@ -14,9 +14,11 @@ from pathlib import Path
|
||||
from typing import Literal, Protocol
|
||||
|
||||
from .models import ObservationSessionCandidate, ReplayCommand
|
||||
from .live_planning import PlanningLiveSource
|
||||
|
||||
RecordingProgressPulse = Callable[[], None]
|
||||
RecordingExportResult = Mapping[str, object]
|
||||
SubmapExtractor = Callable[[Path, dict, int, int], tuple[object, dict]]
|
||||
|
||||
|
||||
class PluginRecordingExportError(RuntimeError):
|
||||
@@ -80,3 +82,8 @@ class ObservationRuntimeContribution:
|
||||
archives: tuple[ObservationArchiveSource, ...]
|
||||
recording_exporter: RecordingExporter
|
||||
point_color_renderer: RecordedPointColorRenderer | None = None
|
||||
overview_exporter: RecordingExporter | None = None
|
||||
planning_exporter: RecordingExporter | None = None
|
||||
submap_extractor: SubmapExtractor | None = None
|
||||
live_planning_source: PlanningLiveSource | None = None
|
||||
scene_submap_extractor: SubmapExtractor | None = None
|
||||
|
||||
Reference in New Issue
Block a user