feat(viewer): unify spatial clipping, planning and observation surfaces

Share spatial clipping and height slices across live planning and recorded observations. Refine scene navigation, report serialization and viewer presentation.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent f48411f8fe
commit 7878937691
40 changed files with 464 additions and 138 deletions
+31
View File
@@ -0,0 +1,31 @@
import numpy as np
import pytest
from k1link.height_slice import height_mask
from k1link.missions.live_scene import clip_reference, clip_query
def test_both_sides_are_inclusive_reversible_and_do_not_mutate_source():
points = np.array([[1., 0, -2], [2., 0, 0], [3., 0, 2], [4., 0, 6]])
original = points.copy()
np.testing.assert_equal(clip_reference(points, 2, 0), points[1:3])
np.testing.assert_equal(clip_reference(points, None, 2), points[2:])
np.testing.assert_equal(clip_reference(points, 0), points[:2])
np.testing.assert_equal(clip_reference(points, None), original)
np.testing.assert_equal(points, original)
def test_query_slices_in_calibrated_world_height_without_changing_local_coordinates():
points = np.array([[0., 0, -5], [0., 0, -3], [0., 0, 1]])
matrix = np.eye(4); matrix[2, 3] = 5
np.testing.assert_equal(clip_query(points, matrix, 3, 1), points[1:2])
np.testing.assert_equal(clip_query(points, matrix, None), points)
def test_invalid_bounds_rejected_and_empty_band_and_cloud_are_supported():
points = np.array([[0., 0, 0], [0., 0, 2], [0., 0, np.nan]])
np.testing.assert_equal(height_mask(points, 2, 2), [False, True, False])
assert not height_mask(points, 3, 4).any()
assert len(height_mask(np.empty((0, 3)), 0, 3)) == 0
for low, high in [(4, 3), (float('inf'), None), (None, float('nan'))]:
with pytest.raises(ValueError): height_mask(points, low, high)
+9 -10
View File
@@ -1,4 +1,5 @@
"""Periodic planning reports must not serialize/compress on the ASGI loop."""
import json
import threading
from types import SimpleNamespace
@@ -14,22 +15,19 @@ from k1link.web.response_compression import ResponseCompressionMiddleware
def test_active_report_keeps_content_and_encodes_off_loop(monkeypatch, encoding):
document = {"state": "completed", "evidence": [{"label": "Проверка", "x": 1.25}] * 50}
calls = []
original_json = planning_live_api.JSONResponse
original_compress = planning_live_api.gzip.compress
class RecordedJSON(original_json):
def render(self, content):
calls.append(("json", threading.get_ident()))
return super().render(content)
def encoded():
calls.append(("json", threading.get_ident()))
return json.dumps(document).encode()
def compress(*args, **kwargs):
calls.append(("gzip", threading.get_ident()))
return original_compress(*args, **kwargs)
monkeypatch.setattr(planning_live_api, "JSONResponse", RecordedJSON)
monkeypatch.setattr(planning_live_api.gzip, "compress", compress)
app = FastAPI()
app.include_router(planning_live_api.build_planning_live_router(SimpleNamespace(get=lambda: document)))
app.include_router(planning_live_api.build_planning_live_router(SimpleNamespace(get_json=encoded)))
app.add_middleware(ResponseCompressionMiddleware)
@app.get("/loop-thread")
@@ -38,7 +36,8 @@ def test_active_report_keeps_content_and_encodes_off_loop(monkeypatch, encoding)
with TestClient(app) as client:
loop_id = client.get("/loop-thread").json()
result = client.get("/api/v1/mission-planner/live-tests/active", headers={"Accept-Encoding": encoding})
result = client.get("/api/v1/mission-planner/live-tests/active",
headers={"Accept-Encoding": encoding})
assert result.status_code == 200
assert result.json() == document # Includes HTTP decompression; no double gzip.
assert result.headers["cache-control"] == "no-store"
@@ -53,7 +52,7 @@ def test_active_report_keeps_content_and_encodes_off_loop(monkeypatch, encoding)
def test_active_report_retains_empty_and_failure_contract():
service = SimpleNamespace(get=lambda: None)
service = SimpleNamespace(get_json=lambda: b"null")
app = FastAPI()
app.include_router(planning_live_api.build_planning_live_router(service))
with TestClient(app) as client:
@@ -63,7 +62,7 @@ def test_active_report_retains_empty_and_failure_contract():
def fail():
raise RuntimeError("synthetic unavailable report")
service.get = fail
service.get_json = fail
result = client.get("/api/v1/mission-planner/live-tests/active")
assert result.status_code == 409
assert result.json() == {"detail": "synthetic unavailable report"}
+4 -3
View File
@@ -122,8 +122,9 @@ def test_delta_sends_only_changed_chunks_pose_and_transform(monkeypatch):
)
np.testing.assert_equal(dict((n, v) for n, v, _ in logs)["world/query/live"], [[1, 1, 0]])
logs.clear()
render(options={"ceiling_m": -0.1})
assert len(dict((n, v) for n, v, _ in logs)["world/query/live"]) == 0
for options in ({"ceiling_m": -0.1}, {"floor_m": 1.1}, {"floor_m": 1.1, "ceiling_m": 3}):
render(options=options)
assert len(dict((n, v) for n, v, _ in logs)["world/query/live"]) == 0
logs.clear()
assert render(cursor)[0] == b""
assert logs == []
@@ -165,7 +166,7 @@ def test_presentation_changes_and_geometry_repairs_never_reset_camera(monkeypatc
assert render().startswith(b"RRF2")
assert len(views) == 1
for options in ({"ceiling_m": 3}, {"reference": False}, {"query": False},
for options in ({"ceiling_m": 3}, {"floor_m": 0}, {"floor_m": 0, "ceiling_m": 3}, {"reference": False}, {"query": False},
{"trajectory": False}, {"point_size": 4}, {"grid": False}, {}):
assert render(options).startswith(b"RRF2")
assert len(views) == 1
+81
View File
@@ -0,0 +1,81 @@
"""Legacy full reports keep exact content without repeated evidence traversal."""
import json
import pytest
from test_planning_live import fixture_service
from test_planning_status import run_document
from k1link.missions.live_report_json import ReportJSONCache
class CountedEvidence(list):
traversals = 0
def __iter__(self):
self.traversals += 1
return super().__iter__()
def test_cached_evidence_is_not_traversed_and_dynamic_values_stay_fresh():
evidence = CountedEvidence([{"label": "Проверка", "values": [1, 2.5, None]}])
report = {"state": "completed", "evidence": evidence, "stale": False}
cache = ReportJSONCache()
first = json.loads(cache.encode(report, 1, {"stale": False, "age": 1}, cacheable=True))
second = json.loads(cache.encode(report, 1, {"stale": True, "age": 10}, cacheable=True))
assert evidence.traversals == 1
assert first == report | {"stale": False, "age": 1}
assert second == report | {"stale": True, "age": 10}
# A revised terminal report must never reuse older evidence.
evidence.append({"new": True})
assert json.loads(cache.encode(report, 2, {}, cacheable=True)) == report
assert evidence.traversals == 2
replacement = {"state": "completed", "evidence": [3]}
assert json.loads(cache.encode(replacement, 2, {}, cacheable=True)) == replacement
def test_active_reports_and_oversized_reports_are_not_retained():
evidence = CountedEvidence([1])
report = {"evidence": evidence}
cache = ReportJSONCache(max_bytes=16)
for n in range(2):
evidence.append(n)
assert json.loads(cache.encode(report, 1, {}, cacheable=False)) == report
assert evidence.traversals == 2
for _ in range(2):
assert json.loads(cache.encode(report, 1, {}, cacheable=True)) == report
assert evidence.traversals == 4
assert cache._prefix is None
@pytest.mark.parametrize("report,overlay", [({}, {}), ({"x": 1}, {}),
({}, {"x": 1}), ({"x": 1}, {"x": 2})])
def test_json_splice_is_single_object_without_duplicate_keys(report, overlay):
raw = ReportJSONCache().encode(report, 0, overlay, cacheable=True)
pairs = json.loads(raw, object_pairs_hook=list)
assert len(pairs) == len(dict(pairs))
assert dict(pairs) == report | overlay
def test_service_cached_json_matches_full_contract_and_invalidates(tmp_path, monkeypatch):
service, _, _, draft = fixture_service(tmp_path, monkeypatch)
assert service.get_json() == b"null"
service.run = run_document(draft) | {"state": "completed", "display": {"saved": [1]}}
service.run["calculation_history"] = CountedEvidence([{"kept": [1, 2]}])
clock = [10_000_000_000]
monkeypatch.setattr("k1link.missions.live_tests.time.monotonic_ns", lambda: clock[0])
monkeypatch.setattr(service, "persist", lambda: None)
service.last_frame_ns = service.last_result_ns = clock[0] - 1_000_000_000
first = json.loads(service.get_json())
assert first == service.get()
clock[0] += 10_000_000_000
second = json.loads(service.get_json())
assert second == service.get()
assert second["stale"] and second["frame_age_s"] == 11
assert first["frame_age_s"] == 1 and not first["stale"]
service.get()["display"]["saved"].append(2)
assert service.run["display"] == {"saved": [1]}
service.update(message="Revised terminal report")
assert json.loads(service.get_json()) == service.get()
assert json.loads(service.get_json())["message"] == "Revised terminal report"
service.run = None
assert service.get_json() == b"null" and service._report_json._prefix is None
+74
View File
@@ -0,0 +1,74 @@
"""Status polls stay independent of retained, potentially huge report evidence."""
import copy
import json
import time
from fastapi import FastAPI
from fastapi.testclient import TestClient
from test_planning_live import fixture_service
from k1link.web.planning_live_api import build_planning_live_router
class UnvisitedEvidence:
def __deepcopy__(self, memo):
raise AssertionError("status traversed full calculation evidence")
def run_document(draft):
return {"id": "1", "schema_version": "missioncore.planning-live-test/v1",
"profile": "planning", "plugin_id": "test-plugin", "draft": draft,
"state": "waiting", "query_session_id": None, "distance_m": 0,
"message": "Ожидаем запись", "result": None, "vehicle_control": False}
def test_status_copies_only_presentation_fields_and_tracks_transitions(tmp_path, monkeypatch):
service, source, lock, draft = fixture_service(tmp_path, monkeypatch)
assert service.get_status() is None
service.run = run_document(draft)
service.run["calculation_history"] = UnvisitedEvidence()
service.run["draft"]["route"]["points"] = UnvisitedEvidence()
service.run["result"] = {"status": "candidate", "overlap": .9, "inlier_rmse_m": .1,
"reasons": [], "matched_query_indices": UnvisitedEvidence(),
"initialization": UnvisitedEvidence()}
first = service.get_status()
assert first["schema_version"] == "missioncore.planning-live-status/v1"
assert len(json.dumps(first)) < 2500
assert first["query_session_id"] is None and first["state"] == "waiting"
assert first["draft"]["route"]["length_m"] == 20
assert "points" not in first["draft"]["route"]
assert "matched_query_indices" not in first["result"]
first["result"]["reasons"].append("only caller's copy")
first["draft"]["zone"]["label"] = "only caller's copy"
assert service.run["result"]["reasons"] == []
assert "label" not in service.run["draft"]["zone"]
service.run.update(state="running", query_session_id="B", query_generation=1,
planning_phase="collecting", tracking_state="acquiring")
service.last_frame_ns = time.monotonic_ns()
second = service.get_status()
assert second["state"] == "running" and second["query_session_id"] == "B"
assert second["planning_phase"] == "collecting" and not second["stale"]
assert second["frame_age_s"] >= 0
service.run.update(state="completed", planning_phase="ended")
assert service.get_status()["state"] == "completed"
assert not lock.locked() and source.owner is None
def test_status_api_does_not_read_report_and_report_remains_complete(tmp_path, monkeypatch):
service, _, _, draft = fixture_service(tmp_path, monkeypatch)
service.run = run_document(draft)
service.run["calculation_history"] = [{"synthetic": list(range(10))}]
original = copy.deepcopy(service.run)
app = FastAPI()
app.include_router(build_planning_live_router(service))
with TestClient(app) as client:
status = client.get("/api/v1/mission-planner/live-tests/status")
report = client.get("/api/v1/mission-planner/live-tests/active")
assert status.status_code == report.status_code == 200
assert status.headers["cache-control"] == "no-store"
assert "calculation_history" not in status.json()
assert report.json()["calculation_history"] == original["calculation_history"]
assert report.json()["draft"]["route"]["points"] == draft["route"]["points"]
assert service.run == original
service.run = None
assert client.get("/api/v1/mission-planner/live-tests/status").json() is None
+3 -2
View File
@@ -90,8 +90,8 @@ def test_height_slice_is_reversible_and_only_replaces_display_points(tmp_path):
recording.flush(); recording.disconnect()
digest = hashlib.sha256(source.read_bytes()).hexdigest()
assert spatial_metadata(source) == {'height_min_m': 0, 'height_max_m': 8, 'sample_points': 3}
for ceiling, expected in [(3, 2), (-1, 0), (None, 3)]:
data, count, eye = render_spatial_update(source, ceiling, 'top')
for floor, ceiling, expected in [(None, 3, 2), (None, -1, 0), (2, None, 2), (2, 4, 1), (3, 3, 1), (None, None, 3)]:
data, count, eye = render_spatial_update(source, ceiling, 'top', floor_m=floor)
assert count == expected and eye['eyeUp'] == [0, 1, 0]
assert eye['position'][2] > eye['lookTarget'][2]
out = tmp_path / f'view-{expected}.rrd'; out.write_bytes(data)
@@ -99,6 +99,7 @@ def test_height_slice_is_reversible_and_only_replaces_display_points(tmp_path):
points = cloud.to_record_batch().column('Points3D:positions')[0].values.values.to_numpy().reshape(-1, 3)
assert len(points) == expected
assert ceiling is None or np.all(points[:, 2] <= ceiling)
assert floor is None or np.all(points[:, 2] >= floor)
assert RrdReader(out).recordings()[0].recording_id == RrdReader(source).recordings()[0].recording_id
assert hashlib.sha256(source.read_bytes()).hexdigest() == digest