feat: finalize corrected-route planning and Rerun recording review
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
"""Mutable per-recording presentation metadata, separate from sealed evidence."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA = "missioncore.session-display-profile/v1"
|
||||
|
||||
|
||||
def load_display_profile(root: Path, session_id: str) -> dict | None:
|
||||
path = root / "display-profile.json"
|
||||
if not path.exists():
|
||||
return None
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size > 64 * 1024:
|
||||
raise ValueError("invalid display profile file")
|
||||
document = json.loads(path.read_text(encoding="utf-8"))
|
||||
if (not isinstance(document, dict) or document.get("schema_version") != SCHEMA
|
||||
or document.get("session_id") != session_id):
|
||||
raise ValueError("invalid display profile identity")
|
||||
return document
|
||||
|
||||
|
||||
def save_display_profile(root: Path, session_id: str, settings: dict) -> dict:
|
||||
destination = root / "display-profile.json"
|
||||
if destination.is_symlink():
|
||||
raise ValueError("invalid display profile file")
|
||||
document = {"schema_version": SCHEMA, "session_id": session_id, "scene_settings": settings}
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=".display-profile-", dir=root)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
json.dump(document, stream, ensure_ascii=False, allow_nan=False)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, destination)
|
||||
finally:
|
||||
Path(temporary).unlink(missing_ok=True)
|
||||
return document
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Validate a pinned geometry projection without widening native source roots."""
|
||||
|
||||
from k1link.reconstruction.map_version import POINTS, TRAJECTORY, MapVersion
|
||||
|
||||
|
||||
class MapReplaySessionStore:
|
||||
"""Operator playback facade. Catalog, media and raw evidence stay in the store.
|
||||
|
||||
Scientific/native consumers receive the original store, not this facade.
|
||||
"""
|
||||
|
||||
def __init__(self, original, versions):
|
||||
self.original, self.versions = original, versions
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self.original, name)
|
||||
|
||||
def prepare_replay(self, *args, **kwargs):
|
||||
from .models import SessionIntegrityError
|
||||
from .recording import RecordingMaterializationError, _validate_source
|
||||
|
||||
try:
|
||||
command = self.versions.resolve_replay(self.original.prepare_replay(*args, **kwargs))
|
||||
if command.map_version is not None:
|
||||
_validate_source(command)
|
||||
return command
|
||||
except (OSError, ValueError, RecordingMaterializationError) as exc:
|
||||
raise SessionIntegrityError(
|
||||
"Исправленная версия записи недоступна или изменилась."
|
||||
) from exc
|
||||
|
||||
|
||||
def map_recording_inputs(command, source):
|
||||
from .recording import (
|
||||
RecordingMaterializationError,
|
||||
_regular_file_stat_nofollow,
|
||||
_sha256_stable,
|
||||
_validated_artifact_digests,
|
||||
_ValidatedArtifact,
|
||||
)
|
||||
|
||||
binding = command.map_version
|
||||
if binding is None:
|
||||
return ()
|
||||
try:
|
||||
if binding.directory.is_symlink() or binding.directory.name != binding.generation:
|
||||
raise ValueError("Unsafe map directory.")
|
||||
version = MapVersion(binding.directory, binding.generation)
|
||||
parent = version.document["source"]
|
||||
if parent["session_id"] != command.session_id or parent[
|
||||
"source_digests"
|
||||
] != _validated_artifact_digests(source):
|
||||
raise ValueError("Map source identity does not match the recording.")
|
||||
artifacts = []
|
||||
names = {
|
||||
"manifest.json": binding.generation,
|
||||
**{
|
||||
name: version.document["artifacts"][name]["sha256"] for name in (POINTS, TRAJECTORY)
|
||||
},
|
||||
}
|
||||
for name, expected in names.items():
|
||||
path = binding.directory / name
|
||||
stat = _regular_file_stat_nofollow(path, "map recording input")
|
||||
if _sha256_stable(path, stat) != expected:
|
||||
raise ValueError("Map recording artifact changed.")
|
||||
artifacts.append(
|
||||
_ValidatedArtifact(
|
||||
"map-version-" + name,
|
||||
path,
|
||||
"application/octet-stream",
|
||||
stat,
|
||||
stat.st_size,
|
||||
expected,
|
||||
)
|
||||
)
|
||||
return tuple(artifacts)
|
||||
except (OSError, ValueError, KeyError) as exc:
|
||||
raise RecordingMaterializationError(
|
||||
"Исправленная версия записи недоступна или изменилась."
|
||||
) from exc
|
||||
@@ -282,6 +282,14 @@ class ReplayArtifact:
|
||||
expected_sha256: str | None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReplayMapVersion:
|
||||
"""Pinned derived geometry; never expands the native capture confinement."""
|
||||
|
||||
directory: Path
|
||||
generation: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReplayCommand:
|
||||
"""Internal replay request containing no vendor format or channel names."""
|
||||
@@ -296,6 +304,7 @@ class ReplayCommand:
|
||||
timeline_origin_monotonic_ns: int
|
||||
speed: float
|
||||
loop: bool
|
||||
map_version: ReplayMapVersion | None = None
|
||||
|
||||
@property
|
||||
def primary_artifact(self) -> ReplayArtifact:
|
||||
|
||||
+111
-40
@@ -1,4 +1,5 @@
|
||||
"""On-demand, source-bound overview cache. No catalog-wide decoding."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
@@ -7,26 +8,34 @@ import logging
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
from collections.abc import Mapping
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Mapping
|
||||
from uuid import uuid4
|
||||
|
||||
from .store import SessionStore
|
||||
from .overview_comparison import load_comparison
|
||||
from .plugin_contract import RecordingExporter
|
||||
from .recording import (_validate_source, _validate_source_state,
|
||||
_validated_artifact_digests, _stage_replay_prefix)
|
||||
from .recording import (
|
||||
_stage_replay_prefix,
|
||||
_validate_source,
|
||||
_validate_source_state,
|
||||
_validated_artifact_digests,
|
||||
)
|
||||
from .store import SessionStore
|
||||
|
||||
SCHEMA = 'missioncore.session-overview/v1'
|
||||
SCHEMA = "missioncore.session-overview/v1"
|
||||
|
||||
|
||||
class SessionOverviewService:
|
||||
def __init__(self, store: SessionStore, exporters: Mapping[str, RecordingExporter]):
|
||||
def __init__(
|
||||
self, store: SessionStore, exporters: Mapping[str, RecordingExporter], *, map_versions=None
|
||||
):
|
||||
self.store = store
|
||||
self.map_versions = map_versions
|
||||
self.exporters = exporters
|
||||
self.root = store.data_dir / 'session-overviews'
|
||||
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.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="session-overview")
|
||||
self.guard = threading.RLock()
|
||||
self.cancel = threading.Event()
|
||||
self.jobs: dict[str, dict] = {}
|
||||
@@ -37,25 +46,35 @@ class SessionOverviewService:
|
||||
|
||||
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()}
|
||||
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}
|
||||
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()
|
||||
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}'}
|
||||
return {
|
||||
**base,
|
||||
**cached,
|
||||
"generation": identity,
|
||||
"scene_url": (
|
||||
f"/api/v1/observation-sessions/{session_id}/overview/scene.rrd"
|
||||
f"?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}
|
||||
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]}
|
||||
|
||||
@@ -63,65 +82,117 @@ class SessionOverviewService:
|
||||
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()
|
||||
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':
|
||||
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'
|
||||
if current.get("state") != "ready" or current.get("generation") != generation:
|
||||
raise ValueError("overview generation is unavailable")
|
||||
return self.root / generation / "scene.rrd"
|
||||
|
||||
def comparison(
|
||||
self, session_id: str, generation: str, comparison_generation: str | None = None
|
||||
):
|
||||
# scene() rechecks current source identity, not merely the cached filename.
|
||||
scene = self.scene(session_id, generation)
|
||||
report = json.loads((scene.parent / "overview.json").read_text())
|
||||
return load_comparison(
|
||||
self.store.data_dir / "session-map-previews",
|
||||
generation,
|
||||
session_id,
|
||||
report["source_digests"],
|
||||
comparison_generation,
|
||||
)
|
||||
|
||||
def default_representation(self, session_id, comparison, reference_generation=None):
|
||||
if self.map_versions is None:
|
||||
return "original"
|
||||
version = (
|
||||
self.map_versions.selected(session_id)
|
||||
if reference_generation is None
|
||||
else self.map_versions.version(session_id, reference_generation)
|
||||
)
|
||||
if version is None:
|
||||
return "original"
|
||||
version.verify()
|
||||
if comparison is None or comparison.document["map_generation"] != version.generation:
|
||||
raise ValueError("Corrected overview for the pinned map is unavailable.")
|
||||
if version.document["source"]["source_digests"] != comparison.document["source_digests"]:
|
||||
raise ValueError("Corrected overview source mismatch.")
|
||||
return "corrected"
|
||||
|
||||
def _cached(self, directory: Path) -> dict | None:
|
||||
try:
|
||||
report = directory / 'overview.json'
|
||||
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']:
|
||||
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']}
|
||||
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')
|
||||
candidate = directory / ("." + uuid4().hex + ".rrd")
|
||||
staged = None
|
||||
try:
|
||||
with self.guard:
|
||||
self.jobs[identity] = {'state': 'preparing', 'messages_processed': 0}
|
||||
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))
|
||||
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')
|
||||
raise ValueError("overview source changed")
|
||||
if digests != _validated_artifact_digests(source):
|
||||
raise ValueError('overview source changed')
|
||||
raise ValueError("overview source changed")
|
||||
if candidate.stat().st_size > 32 * 1024 * 1024:
|
||||
raise ValueError('overview exceeded display budget')
|
||||
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'
|
||||
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')
|
||||
os.replace(temporary, directory / "overview.json")
|
||||
with self.guard:
|
||||
self.jobs.pop(identity, None)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception('Session overview preparation failed')
|
||||
logging.getLogger(__name__).exception("Session overview preparation failed")
|
||||
with self.guard:
|
||||
self.jobs[identity] = {'state': 'error', 'message': 'Не удалось подготовить обзор записи.'}
|
||||
self.jobs[identity] = {
|
||||
"state": "error",
|
||||
"message": "Не удалось подготовить обзор записи.",
|
||||
}
|
||||
finally:
|
||||
candidate.unlink(missing_ok=True)
|
||||
if staged is not None:
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Content-addressed, paired display derivatives, never planning references.
|
||||
|
||||
Only an offline publisher may attach an explicitly reviewed version to a source
|
||||
overview. HTTP callers select a digest, not filesystem paths or a mutable latest
|
||||
map. Both representations preserve point/pose correspondence and share colors.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from uuid import uuid4
|
||||
|
||||
import numpy as np
|
||||
|
||||
from k1link.reconstruction.map_version import json_bytes
|
||||
|
||||
SCHEMA = "missioncore.overview-comparison/v1"
|
||||
MAX_POINTS = 180_000
|
||||
MAX_POSES = 20_000
|
||||
MAX_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def _digest(value):
|
||||
if not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value):
|
||||
raise ValueError("Invalid comparison identity.")
|
||||
return value
|
||||
|
||||
|
||||
def _read(path, maximum):
|
||||
if path.is_symlink() or path.stat().st_size > maximum:
|
||||
raise ValueError("Invalid comparison artifact.")
|
||||
with path.open("rb") as stream:
|
||||
value = stream.read(maximum + 1)
|
||||
if len(value) > maximum:
|
||||
raise ValueError("Comparison exceeds display budget.")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OverviewComparison:
|
||||
generation: str
|
||||
document: dict
|
||||
original: np.ndarray
|
||||
corrected: np.ndarray
|
||||
original_route: np.ndarray
|
||||
corrected_route: np.ndarray
|
||||
|
||||
@property
|
||||
def bounds(self):
|
||||
# Only bounds are combined; there is no correspondence or fitting here.
|
||||
return np.array(
|
||||
[
|
||||
self.original.min(axis=0),
|
||||
self.original.max(axis=0),
|
||||
self.corrected.min(axis=0),
|
||||
self.corrected.max(axis=0),
|
||||
]
|
||||
)
|
||||
|
||||
def metadata(self):
|
||||
return dict(
|
||||
generation=self.generation,
|
||||
map_generation=self.document["map_generation"],
|
||||
sample_points=len(self.original),
|
||||
source_points=self.document["source_points"],
|
||||
height_min_m=min(-3.0, float(self.bounds[:, 2].min())),
|
||||
height_max_m=max(80.0, float(self.bounds[:, 2].max())),
|
||||
original_path_m=self.document["original_path_m"],
|
||||
corrected_path_m=self.document["corrected_path_m"],
|
||||
)
|
||||
|
||||
|
||||
def _arrays(payload):
|
||||
# np.savez (uncompressed) is deliberate: reject compressed archive bombs.
|
||||
import zipfile
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
|
||||
if len(archive.infolist()) != 4 or any(
|
||||
x.compress_type != zipfile.ZIP_STORED for x in archive.infolist()
|
||||
):
|
||||
raise ValueError("Invalid comparison array archive.")
|
||||
with np.load(io.BytesIO(payload), allow_pickle=False) as data:
|
||||
result = [
|
||||
np.array(data[k])
|
||||
for k in ("original", "corrected", "original_route", "corrected_route")
|
||||
]
|
||||
a, b, p, q = result
|
||||
if (
|
||||
a.shape != b.shape
|
||||
or p.shape != q.shape
|
||||
or not 1 <= len(a) <= MAX_POINTS
|
||||
or not 2 <= len(p) <= MAX_POSES
|
||||
or any(
|
||||
x.ndim != 2
|
||||
or x.shape[1:] != (3,)
|
||||
or x.dtype != np.dtype("<f4")
|
||||
or not np.isfinite(x).all()
|
||||
for x in result
|
||||
)
|
||||
):
|
||||
raise ValueError("Invalid paired comparison geometry.")
|
||||
return result
|
||||
|
||||
|
||||
def load_comparison(
|
||||
root: Path,
|
||||
overview_generation: str,
|
||||
session_id: str,
|
||||
source_digests: dict,
|
||||
generation: str | None = None,
|
||||
):
|
||||
root = Path(root)
|
||||
_digest(overview_generation)
|
||||
pointer = root / "selected" / f"{overview_generation}.json"
|
||||
if generation is None:
|
||||
if not pointer.exists():
|
||||
return None
|
||||
generation = json.loads(_read(pointer, 4096))["generation"]
|
||||
_digest(generation)
|
||||
directory = root / generation
|
||||
if directory.is_symlink():
|
||||
raise ValueError("Comparison directory must not be a link.")
|
||||
payload = _read(directory / "manifest.json", 32_768)
|
||||
if hashlib.sha256(payload).hexdigest() != generation:
|
||||
raise ValueError("Comparison manifest changed.")
|
||||
doc = json.loads(payload)
|
||||
if (
|
||||
doc.get("schema_version") != SCHEMA
|
||||
or doc.get("session_id") != session_id
|
||||
or doc.get("overview_generation") != overview_generation
|
||||
or doc.get("source_digests") != source_digests
|
||||
or doc.get("view_only") is not True
|
||||
):
|
||||
raise ValueError("Comparison belongs to another recording generation.")
|
||||
_digest(doc["map_generation"])
|
||||
arrays = _read(directory / "geometry.npz", MAX_BYTES)
|
||||
if hashlib.sha256(arrays).hexdigest() != doc["geometry_sha256"]:
|
||||
raise ValueError("Comparison geometry changed.")
|
||||
return OverviewComparison(generation, doc, *_arrays(arrays))
|
||||
|
||||
|
||||
def publish_comparison(
|
||||
root,
|
||||
*,
|
||||
session_id,
|
||||
overview_generation,
|
||||
source_digests,
|
||||
map_generation,
|
||||
source_points,
|
||||
original_path_m,
|
||||
corrected_path_m,
|
||||
original,
|
||||
corrected,
|
||||
original_route,
|
||||
corrected_route,
|
||||
):
|
||||
"""Publish a view-only pair; no catalog or mission mutation, no implicit promotion."""
|
||||
root = Path(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
_digest(overview_generation)
|
||||
_digest(map_generation)
|
||||
with TemporaryDirectory(prefix=".comparison-", dir=root) as temporary:
|
||||
stage = Path(temporary)
|
||||
np.savez(
|
||||
stage / "geometry.npz",
|
||||
**{
|
||||
name: np.asarray(value, dtype="<f4")
|
||||
for name, value in (
|
||||
("original", original),
|
||||
("corrected", corrected),
|
||||
("original_route", original_route),
|
||||
("corrected_route", corrected_route),
|
||||
)
|
||||
},
|
||||
)
|
||||
payload = _read(stage / "geometry.npz", MAX_BYTES)
|
||||
_arrays(payload)
|
||||
doc = dict(
|
||||
schema_version=SCHEMA,
|
||||
session_id=session_id,
|
||||
overview_generation=overview_generation,
|
||||
source_digests=source_digests,
|
||||
map_generation=map_generation,
|
||||
source_points=source_points,
|
||||
original_path_m=original_path_m,
|
||||
corrected_path_m=corrected_path_m,
|
||||
view_only=True,
|
||||
geometry_sha256=hashlib.sha256(payload).hexdigest(),
|
||||
)
|
||||
manifest = json_bytes(doc)
|
||||
generation = hashlib.sha256(manifest).hexdigest()
|
||||
(stage / "manifest.json").write_bytes(manifest)
|
||||
if not (root / generation).exists():
|
||||
stage.rename(root / generation)
|
||||
load_comparison(root, overview_generation, session_id, source_digests, generation)
|
||||
pointers = root / "selected"
|
||||
pointers.mkdir(exist_ok=True)
|
||||
temporary = pointers / f".{uuid4().hex}.json"
|
||||
try:
|
||||
temporary.write_bytes(json_bytes(dict(generation=generation)))
|
||||
os.replace(temporary, pointers / f"{overview_generation}.json")
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return generation
|
||||
@@ -1,4 +1,5 @@
|
||||
"""View-only height clipping and camera presets for bounded overview RRDs."""
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
@@ -8,22 +9,24 @@ import rerun as rr
|
||||
from rerun import blueprint as rrb
|
||||
from rerun.experimental import RrdReader
|
||||
|
||||
from .overview_comparison import OverviewComparison
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _geometry(path: Path, size: int, modified: int):
|
||||
if size > 32 * 1024 * 1024:
|
||||
raise ValueError('overview exceeds display budget')
|
||||
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':
|
||||
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()
|
||||
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')
|
||||
raise ValueError("overview geometry is invalid")
|
||||
return entry.application_id, entry.recording_id, xyz, colors
|
||||
|
||||
|
||||
@@ -32,15 +35,18 @@ def geometry(path: Path):
|
||||
return _geometry(path, stat.st_size, stat.st_mtime_ns)
|
||||
|
||||
|
||||
def spatial_metadata(path: Path) -> dict:
|
||||
def spatial_metadata(path: Path, comparison: OverviewComparison | None = None) -> 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)}
|
||||
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),
|
||||
**({"comparison": comparison.metadata()} if comparison else {}),
|
||||
}
|
||||
|
||||
|
||||
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.]])
|
||||
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.0, -1.0, -1.0], [1.0, 1.0, 1.0]])
|
||||
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.
|
||||
@@ -48,38 +54,104 @@ def _camera_eye(xyz: np.ndarray, mode: Literal['3d', 'top'], aspect: float) -> d
|
||||
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])
|
||||
side = np.array([-along[1], along[0], 0.0])
|
||||
direction = (
|
||||
np.array([0.0, 0.0, 1.0]) if mode == "top" else side * 0.8 + np.array([0.0, 0.0, 0.75])
|
||||
)
|
||||
direction /= np.linalg.norm(direction)
|
||||
up = side if mode == 'top' else np.array([0., 0., 1.])
|
||||
up = side if mode == "top" else np.array([0.0, 0.0, 1.0])
|
||||
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()}
|
||||
required = (
|
||||
np.maximum(
|
||||
np.abs(centered @ right) / (aspect * tangent), np.abs(centered @ screen_up) / tangent
|
||||
)
|
||||
+ depth
|
||||
)
|
||||
distance = max(2.0, 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):
|
||||
def render_spatial_update(
|
||||
path: Path,
|
||||
ceiling_m: float | None,
|
||||
mode: Literal["3d", "top"] | None,
|
||||
aspect: float = 1.5,
|
||||
comparison: OverviewComparison | None = None,
|
||||
representation: Literal["original", "corrected"] = "original",
|
||||
):
|
||||
app_id, recording_id, xyz, colors = geometry(path)
|
||||
if representation == "corrected" and comparison is None:
|
||||
raise ValueError("Corrected representation requires a pinned comparison.")
|
||||
camera_points = xyz
|
||||
route = None
|
||||
if comparison is not None:
|
||||
xyz = comparison.corrected if representation == "corrected" else comparison.original
|
||||
route = (
|
||||
comparison.corrected_route
|
||||
if representation == "corrected"
|
||||
else comparison.original_route
|
||||
)
|
||||
camera_points = comparison.bounds
|
||||
# Identical point colors in both representations: only geometry changes.
|
||||
height = comparison.original[:, 2]
|
||||
low, high = np.quantile(height, [0.05, 0.95])
|
||||
normalized = np.clip((height - low) / max(high - low, 0.01), 0, 1)
|
||||
colors = np.column_stack(
|
||||
[70 + 100 * normalized, 135 + 80 * normalized, 220 - 90 * normalized]
|
||||
).astype(np.uint8)
|
||||
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)
|
||||
# Replace only display geometry. Original recorded poses/metrics remain untouched.
|
||||
recording.log(
|
||||
"world/cloud",
|
||||
rr.Points3D(xyz[selected], colors=colors[selected], radii=rr.Radius.ui_points(1.5)),
|
||||
static=True,
|
||||
)
|
||||
if route is not None:
|
||||
recording.log(
|
||||
"world/route",
|
||||
rr.LineStrips3D([route], colors=[180, 240, 90], radii=rr.Radius.ui_points(2)),
|
||||
static=True,
|
||||
)
|
||||
recording.log(
|
||||
"world/endpoints",
|
||||
rr.Points3D(
|
||||
route[[0, -1]],
|
||||
labels=["Старт", "Финиш"],
|
||||
colors=[245, 248, 240],
|
||||
radii=rr.Radius.ui_points(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))
|
||||
eye = _camera_eye(camera_points, 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:
|
||||
|
||||
@@ -8,7 +8,7 @@ evidence and export it into the host's canonical recorded-viewer artifact.
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from collections.abc import Callable, Mapping
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Literal, Protocol
|
||||
@@ -53,6 +53,13 @@ class RecordedPointColorRenderer(Protocol):
|
||||
) -> bytes: ...
|
||||
|
||||
|
||||
class RecordedPointDisplayRenderer(Protocol):
|
||||
def __call__(self, 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]: ...
|
||||
|
||||
|
||||
ObservationArchiveDiscovery = Callable[
|
||||
[Path],
|
||||
tuple[ObservationSessionCandidate, ...],
|
||||
@@ -82,6 +89,7 @@ class ObservationRuntimeContribution:
|
||||
archives: tuple[ObservationArchiveSource, ...]
|
||||
recording_exporter: RecordingExporter
|
||||
point_color_renderer: RecordedPointColorRenderer | None = None
|
||||
point_display_renderer: RecordedPointDisplayRenderer | None = None
|
||||
overview_exporter: RecordingExporter | None = None
|
||||
planning_exporter: RecordingExporter | None = None
|
||||
submap_extractor: SubmapExtractor | None = None
|
||||
|
||||
@@ -756,6 +756,7 @@ def _source_identity(command: ReplayCommand) -> tuple[object, ...]:
|
||||
command.session_id,
|
||||
command.plugin_id,
|
||||
command.primary_artifact_id,
|
||||
command.map_version,
|
||||
]
|
||||
for artifact in command.artifacts:
|
||||
path = artifact.path
|
||||
|
||||
@@ -30,14 +30,12 @@ from .plugin_contract import (
|
||||
RecordingExporter,
|
||||
)
|
||||
|
||||
# v12 publishes a 2 Hz point-cloud operator projection while retaining complete
|
||||
# normal K1 point batches. v11 also spatially thinned every ~2.4k-point frame;
|
||||
# the latest-at AI view therefore looked visibly bald even though the raw
|
||||
# capture was complete. Frames above the explicit emergency threshold remain
|
||||
# bounded, and the native capture stays the source of record and AI input.
|
||||
CACHE_SCHEMA = "missioncore.derived-rerun-recording-cache/v12"
|
||||
# v13 preserves every point and frame. Older projections silently discarded
|
||||
# four out of five frames, losing fine geometry even in accumulated playback.
|
||||
# Invalidate only the derived RRD; raw captures and corrected maps are unchanged.
|
||||
CACHE_SCHEMA = "missioncore.derived-rerun-recording-cache/v13"
|
||||
COMPATIBLE_CACHE_SCHEMAS = frozenset({CACHE_SCHEMA})
|
||||
RECORDING_CACHE_FILENAME = "scene.operator-v12.rrd"
|
||||
RECORDING_CACHE_FILENAME = "scene.operator-v13.rrd"
|
||||
RECORDING_CACHE_SIDECAR_FILENAME = f"{RECORDING_CACHE_FILENAME}.cache.json"
|
||||
RERUN_RECORDING_MEDIA_TYPE = "application/vnd.rerun.rrd"
|
||||
RERUN_SESSION_TIMELINE = "session_time"
|
||||
@@ -812,6 +810,10 @@ class SessionRecordingMaterializer:
|
||||
raise PluginRecordingExportError(
|
||||
f"device plugin has no recording exporter: {plugin_id}"
|
||||
)
|
||||
if any(name.startswith("map-version-") for name in artifacts or {}) and not getattr(
|
||||
selected, "supports_map_versions", False
|
||||
):
|
||||
raise RecordingMaterializationError("Device exporter cannot project corrected geometry")
|
||||
exporter = cast(RrdExporter, selected)
|
||||
kwargs: dict[str, object] = {}
|
||||
if _callable_accepts_keyword(exporter, "artifacts"):
|
||||
@@ -1085,11 +1087,19 @@ def _validate_source(command: ReplayCommand) -> _ValidatedSource:
|
||||
)
|
||||
if sum(artifact.artifact_id == primary_artifact_id for artifact in validated) != 1:
|
||||
raise RecordingMaterializationError("recording primary artifact is unavailable")
|
||||
return _ValidatedSource(
|
||||
result = _ValidatedSource(
|
||||
plugin_id=plugin_id,
|
||||
primary_artifact_id=primary_artifact_id,
|
||||
artifacts=tuple(validated),
|
||||
)
|
||||
if command.map_version is not None:
|
||||
from .map_recording import map_recording_inputs
|
||||
|
||||
projected = map_recording_inputs(command, result)
|
||||
if seen_names.intersection(item.path.name for item in projected):
|
||||
raise RecordingMaterializationError("map artifact filenames conflict with native inputs")
|
||||
result = _ValidatedSource(plugin_id, primary_artifact_id, (*result.artifacts, *projected))
|
||||
return result
|
||||
|
||||
|
||||
def _validate_source_state(source: _ValidatedSource) -> _ValidatedSource:
|
||||
|
||||
@@ -56,7 +56,7 @@ LAB_ORIGIN = "missioncore.lab-instance/v1"
|
||||
LAB_ID_PATTERN = re.compile(r"^LAB [A-Z][A-Z0-9._-]{0,31}$")
|
||||
SHA256_PATTERN = re.compile(r"^[a-f0-9]{64}$")
|
||||
LAB_METHOD_SCHEMA = "missioncore.laboratory-method/v1"
|
||||
SessionScope = Literal["all", "source", "laboratory"]
|
||||
SessionScope = Literal["all", "source", "standalone", "laboratory"]
|
||||
|
||||
SCHEMA_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS observation_sessions (
|
||||
@@ -95,6 +95,16 @@ CREATE TABLE IF NOT EXISTS observation_sessions (
|
||||
CREATE INDEX IF NOT EXISTS observation_sessions_recent
|
||||
ON observation_sessions(started_at_utc DESC, session_id DESC);
|
||||
|
||||
-- Acquisition provenance, not a relabeling of physical evidence as a LAB.
|
||||
-- May be recorded before capture finalization/catalog ingestion. Deliberately
|
||||
-- survives catalog reconciliation and removal of a planner project.
|
||||
CREATE TABLE IF NOT EXISTS observation_planning_captures (
|
||||
session_id TEXT NOT NULL,
|
||||
run_id TEXT NOT NULL,
|
||||
recorded_at_utc TEXT NOT NULL,
|
||||
PRIMARY KEY (session_id, run_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS observation_session_artifacts (
|
||||
session_id TEXT NOT NULL REFERENCES observation_sessions(session_id) ON DELETE CASCADE,
|
||||
artifact_id TEXT NOT NULL,
|
||||
@@ -237,6 +247,19 @@ class SessionStore:
|
||||
connection.commit()
|
||||
return tuple(imported)
|
||||
|
||||
def record_planning_capture(self, session_id: str, run_id: str) -> None:
|
||||
"""Remember an exact capture bound by a live planner, never by its name."""
|
||||
from uuid import UUID
|
||||
|
||||
_validate_identifier(session_id, "planning capture")
|
||||
run_id = str(UUID(run_id))
|
||||
with self._lock, self._connect() as connection:
|
||||
connection.execute(
|
||||
"INSERT OR IGNORE INTO observation_planning_captures VALUES (?, ?, ?)",
|
||||
(session_id, run_id, utc_now_iso()),
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
def list_recent(
|
||||
self,
|
||||
*,
|
||||
@@ -249,6 +272,8 @@ class SessionStore:
|
||||
raise ValueError("limit must be within 1..100")
|
||||
if not isinstance(include_capability_projections, bool):
|
||||
raise ValueError("capability projection policy must be boolean")
|
||||
standalone = scope == "standalone"
|
||||
effective_scope = "source" if standalone else scope
|
||||
scope_clause = ({
|
||||
"all": "1 = 1",
|
||||
"source": (
|
||||
@@ -274,9 +299,14 @@ class SessionStore:
|
||||
"WHERE lab.session_id = sessions.session_id "
|
||||
"AND lab.replay_capability_json IS NULL)"
|
||||
),
|
||||
}).get(scope)
|
||||
}).get(effective_scope)
|
||||
if scope_clause is None:
|
||||
raise ValueError("scope must be all, source, or laboratory")
|
||||
raise ValueError("scope must be all, source, standalone, or laboratory")
|
||||
if standalone:
|
||||
scope_clause += (
|
||||
" AND NOT EXISTS (SELECT 1 FROM observation_planning_captures AS planning "
|
||||
"WHERE planning.session_id = sessions.session_id)"
|
||||
)
|
||||
parameters: list[object] = []
|
||||
where = f"WHERE {scope_clause}" # noqa: S608 - closed static scope clauses
|
||||
with self._connect() as connection:
|
||||
@@ -341,6 +371,22 @@ class SessionStore:
|
||||
detail, _snapshot_sha256 = self.get_session_with_catalog_snapshot(session_id)
|
||||
return detail
|
||||
|
||||
def display_profile_root(self, session_id: str) -> Path:
|
||||
"""Resolve only the catalogued physical directory; never accept a client path."""
|
||||
_validate_identifier(session_id, "session id")
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT allowed_root, session_root FROM observation_sessions WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise SessionNotFoundError("observation session was not found")
|
||||
root = Path(row["session_root"])
|
||||
allowed = Path(row["allowed_root"]).resolve(strict=True)
|
||||
if root.is_symlink() or not root.is_dir() or not root.resolve().is_relative_to(allowed):
|
||||
raise SessionIntegrityError("display profile escapes session directory")
|
||||
return root.resolve()
|
||||
|
||||
def get_session_with_catalog_snapshot(
|
||||
self,
|
||||
session_id: str,
|
||||
|
||||
Reference in New Issue
Block a user