diff --git a/.codex/skills/mission-core-product-ui/SKILL.md b/.codex/skills/mission-core-product-ui/SKILL.md index 6eed3385..e795c5fa 100644 --- a/.codex/skills/mission-core-product-ui/SKILL.md +++ b/.codex/skills/mission-core-product-ui/SKILL.md @@ -193,7 +193,7 @@ The compact summary must cover: - retained authority. Keep manifests, long hashes, implementation files, validation logs, regressions, -rejected approaches, and next-stage planning in the Mission Core Ops report. +rejected approaches, and next-stage planning in local engineering evidence. Do not expose roadmap steps, next-gate checklists, internal reason taxonomies, debug controls, placeholder blocks, or implementation scaffolding in product @@ -214,26 +214,14 @@ UI. - Keep renderer colors semantic and token-derived. Never use them to invent control states or persistent colored outlines. -## Ops report boundary +## Ops result boundary — owner revision, 2026-10-09 -When the task includes reporting a completed LAB or architecture milestone, use -the direct `nodedc-ops-agent` tools and write titled structured blocks in this -order: - -1. Objective and architecture stage. -2. Decision question and hypothesis. -3. Immutable source evidence and bounds. -4. Method, preprocessing, models, algorithms, tools, and identities. -5. Worker/runtime topology and resource policy. -6. Experimental implementation. -7. Validation and reproduced evidence. -8. Results. -9. Regressions, rejected approaches, and limitations. -10. Decision. -11. Next stage and forbidden authority. -12. Acceptance checker. - -Do not turn the product UI into a duplicate Ops report. +Use the direct `nodedc-ops-agent` tools only for concise verified delivered +results: what works, what implementation is used, and the accepted scope. +Keep intermediate measurements, failed attempts, architecture proposals, +hypotheses and next-stage plans in local engineering evidence, not Ops. +Consolidate superseded intermediate blocks instead of appending a run diary. +Do not turn a partial experiment into a completed-product claim. ## Validation diff --git a/AGENTS.md b/AGENTS.md index efe5dd1b..74f1fb1d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -208,7 +208,7 @@ decoders before BLE/Wi-Fi/data-session evidence exists. canonical Design Guideline exports. - Product UI must not expose implementation steps, roadmap gates, internal reason taxonomies, debug controls, placeholder status blocks, or temporary - experiment scaffolding. Keep these in Ops, engineering reports, or developer + experiment scaffolding. Keep these in local engineering reports or developer tooling. - Extend one reusable application pattern instead of adding per-LAB layouts. A new LAB supplies data and renderer configuration; it does not invent a new @@ -245,11 +245,12 @@ decoders before BLE/Wi-Fi/data-session evidence exists. - The compact summary must explain the decision question, immutable source, tested method/models/algorithms, experimental mode, principal result, limitations, and retained authority. It is not the engineering report. -- The complete engineering report belongs in the Mission Core Ops card as - titled structured blocks: objective and architecture stage, source evidence, - method/models/algorithms, worker/runtime, implementation, validation, - results, regressions and limitations, decision, next stage, and acceptance - checker. +- Owner reporting rule (2026-10-09): Ops contains concise, verified delivered + results only: what works, the implementation used, and its accepted scope. + Keep intermediate experiments, failed attempts, architecture proposals, + detailed logs and future plans in local engineering evidence, not Ops. + Consolidate superseded intermediate blocks instead of appending a run diary. + Never present a partial experiment as a completed product result. - Spatial evidence uses 3D by default. Image-space reprojection may be offered as a 2D diagnostic mode inside the same reusable viewer. Primary evidence viewers must provide the canonical expand/restore action. diff --git a/apps/control-station/src/components/simulation/AiInferencePreview.tsx b/apps/control-station/src/components/simulation/AiInferencePreview.tsx index b0e92e5e..6f52082b 100644 --- a/apps/control-station/src/components/simulation/AiInferencePreview.tsx +++ b/apps/control-station/src/components/simulation/AiInferencePreview.tsx @@ -1,6 +1,6 @@ import { lazy, Suspense, useEffect, useState } from "react"; import { LoadingRegion } from "@nodedc/ui-react"; -import { polygonRequest } from "../../core/simulation/aiPolygon"; +import { connectPreviewStream } from "../../core/simulation/previewStream"; const SpatialPreview=lazy(()=>import("./AiSpatialPreview").then(m=>({default:m.AiSpatialPreview}))); export interface InferencePreview { frame_id:number;simulation_time_ns:number;received_at:string;environment:"park"|"natural"|"urban"; @@ -12,17 +12,7 @@ export function useInferencePreview(runId:string|undefined,active:boolean) { const [preview,setPreview]=useState(null); useEffect(()=>{ setPreview(null);if(!runId || !active)return; - const abort=new AbortController();let timer=0; - const poll=async()=>{ - try { - if(document.visibilityState==="visible") { - const value=await polygonRequest(`/runs/${runId}/inference-preview`,{signal:abort.signal}); - if(!abort.signal.aborted)setPreview(value); - } - } catch { /* Main status owns connection errors; retain the dated last frame. */ } - if(!abort.signal.aborted)timer=window.setTimeout(()=>void poll(),500); - }; - void poll();return()=>{abort.abort();clearTimeout(timer);}; + return connectPreviewStream(runId,setPreview); },[runId,active]); return preview; } diff --git a/apps/control-station/src/core/simulation/previewStream.ts b/apps/control-station/src/core/simulation/previewStream.ts new file mode 100644 index 00000000..0b0af124 --- /dev/null +++ b/apps/control-station/src/core/simulation/previewStream.ts @@ -0,0 +1,21 @@ +/** One visible subscriber; reconnect reads the latest frame, never a backlog. */ +export function connectPreviewStream(runId:string,receive:(value:T)=>void, + create:(url:string)=>EventSource=url=>new EventSource(url), + visibility:Pick=document) { + let events:EventSource|null=null, disposed=false, ended=false; + const close=()=>{events?.close();events=null;}; + const update=()=>{ + close(); + if(disposed || ended || visibility.visibilityState!=='visible')return; + const stream=create(`/api/v1/ai-polygon/runs/${encodeURIComponent(runId)}/inference-preview/events`); + events=stream; + stream.onmessage=event=>{ + if(events!==stream)return; + try {receive(JSON.parse(event.data) as T);}catch {/* Retain the dated last valid frame. */} + }; + stream.addEventListener('end',()=>{if(events===stream){ended=true;close();}}); + }; + visibility.addEventListener('visibilitychange',update); + update(); + return()=>{disposed=true;close();visibility.removeEventListener('visibilitychange',update);}; +} diff --git a/apps/control-station/test/previewStream.test.mjs b/apps/control-station/test/previewStream.test.mjs new file mode 100644 index 00000000..7ced7491 --- /dev/null +++ b/apps/control-station/test/previewStream.test.mjs @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {test} from 'node:test'; +import ts from 'typescript'; +const code=ts.transpileModule(readFileSync(new URL('../src/core/simulation/previewStream.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText; +const {connectPreviewStream}=await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); +function setup(){ + const callbacks=new Map(),opened=[],received=[]; + const visibility={visibilityState:'visible',addEventListener:(k,f)=>callbacks.set(k,f),removeEventListener:k=>callbacks.delete(k)}; + const create=url=>{const s={url,closed:false,events:new Map(),close(){this.closed=true;},addEventListener(k,f){this.events.set(k,f);}};opened.push(s);return s;}; + const cleanup=connectPreviewStream('airun-test',v=>received.push(v),create,visibility); + return {visibility,callbacks,opened,received,cleanup}; +} +test('visible subscriber receives push; hidden and disposed viewers release connections',()=>{ + const s=setup();assert.equal(s.opened.length,1);s.opened[0].onmessage({data:'{"frame_id":1}'}); + assert.deepEqual(s.received,[{frame_id:1}]);s.visibility.visibilityState='hidden';s.callbacks.get('visibilitychange')(); + assert.ok(s.opened[0].closed);s.opened[0].onmessage({data:'{"frame_id":2}'});assert.equal(s.received.length,1); + s.visibility.visibilityState='visible';s.callbacks.get('visibilitychange')();assert.equal(s.opened.length,2); + s.cleanup();assert.ok(s.opened[1].closed);assert.equal(s.callbacks.size,0); +}); +test('terminal run closes without browser reconnect; malformed event retains last frame',()=>{ + const s=setup();s.opened[0].onmessage({data:'{bad'});assert.equal(s.received.length,0); + s.opened[0].events.get('end')();assert.ok(s.opened[0].closed); + s.callbacks.get('visibilitychange')();assert.equal(s.opened.length,1);s.cleanup(); +}); diff --git a/docs/17_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md b/docs/17_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md index 79131363..e13153c3 100644 --- a/docs/17_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md +++ b/docs/17_PRODUCT_UI_AND_LAB_PRESENTATION_CANON.md @@ -11,7 +11,7 @@ predictable, and based on the approved NODE.DC Design Guideline. This document governs Control Station product UI, laboratory summaries, evidence viewers, selected-LAB evidence reports, and the boundary with -implementation history and architecture narratives in Ops. +verified delivery summaries in Ops. It complements `docs/15_LABORATORY_RUN_CANON.md`, which governs publication and provenance. New non-LAB surfaces and their placement are governed by `docs/19_PRODUCT_SURFACE_EXTENSION_PROTOCOL.md`. @@ -154,7 +154,7 @@ viewer: Show short product names and exact identities only where they aid comparison. Long manifests, hashes, implementation file lists, validation logs, and the -history of rejected approaches belong in Ops. +history of rejected approaches belong in local engineering evidence. ## Evidence viewer contract @@ -312,33 +312,18 @@ Do not render: - a separate layout because one LAB has a different algorithm. If information is necessary only for development or governance, place it in -Ops, an ADR, a runbook, or developer tooling. Evidence needed to verify the +local engineering evidence, an ADR, a runbook, or developer tooling. Evidence needed to verify the selected LAB belongs in its product evidence report. -## Ops engineering report +## Ops delivered results — owner revision, 2026-10-09 -The complete implementation history and architecture narrative for a LAB or -milestone lives in the Mission Core Ops project. It links the canonical product -evidence report instead of retyping its metrics. Keep the issue description -concise and place the narrative in titled structured blocks. Use this order: - -1. Objective and architecture stage. -2. Decision question and hypothesis. -3. Immutable source evidence and tested bounds. -4. Method, preprocessing, models, algorithms, tools, and identities. -5. Worker/runtime topology and resource policy. -6. Experimental changes and implementation. -7. Validation and reproduced evidence. -8. Quantitative and qualitative results. -9. Regressions, rejected approaches, and honest limitations. -10. Decision: continue, revise, reject, or promote. -11. Next stage and authority that remains forbidden. -12. Acceptance checker with short verifiable items. - -The product summary and selected-LAB evidence report are projections of -immutable runtime evidence, never a second independent narrative. Ops adds -engineering context, ownership, implementation history, and future work; it is -not a substitute for source/runtime/metric/artifact proof. +Ops contains concise, verified outcomes: what works, what implementation is used, +and the accepted scope. Do not append intermediate runs, failed experiments, +architecture proposals, hypotheses or future plans. Consolidate superseded +intermediate blocks when a result is delivered. Keep detailed engineering +reports, hashes, validation logs and negative evidence locally under the +repository's established evidence lifecycle. A partial test never becomes a +claim of complete product acceptance. ## Review gate before A3 diff --git a/simulation/ai-polygon/inference_preview.py b/simulation/ai-polygon/inference_preview.py index c7ad1f9a..a6288259 100644 --- a/simulation/ai-polygon/inference_preview.py +++ b/simulation/ai-polygon/inference_preview.py @@ -172,7 +172,7 @@ class InferencePreview: def publish(self, rgb, values, observation, frame_id): now = time.monotonic() - if now - self.last < 0.5: + if now - self.last < 0.125: return self.last = now original = Image.fromarray(rgb) diff --git a/simulation/ai-polygon/mounted_sensors.py b/simulation/ai-polygon/mounted_sensors.py index 8c37ac9f..20b921a6 100644 --- a/simulation/ai-polygon/mounted_sensors.py +++ b/simulation/ai-polygon/mounted_sensors.py @@ -188,7 +188,9 @@ class MountedSensors: class MountedRange: def __init__(self, rig, contact_height): from terrain import RangeSensor + from carb import Float3 + self.query_vector = lambda xyz: Float3(*xyz) legacy = RangeSensor() self.query = legacy.query self.mounts, self.contact_height = rig["mounts"], contact_height @@ -244,7 +246,7 @@ class MountedRange: origins.append(origin) observed, clear, depth, paths = mounted_range_returns( self.query, origin, rays @ rotation, key, self.mounts[key], self.rs_rays[:, 0], - organized_ranges=view_ranges, + organized_ranges=view_ranges, query_vector=self.query_vector, ) points.extend(observed) ends.extend(clear) @@ -268,7 +270,8 @@ class MountedRange: return np.asarray(points, np.float32).reshape(-1, 3) -def mounted_range_returns(query, origin, directions, key, spec, forward, *, organized_ranges=None): +def mounted_range_returns(query, origin, directions, key, spec, forward, *, + organized_ranges=None, query_vector=tuple): """Same first-hit rays, with range filtering outside the Python query loop. Keep per-beam ownership and order. A self hit never becomes a no-return @@ -277,14 +280,16 @@ def mounted_range_returns(query, origin, directions, key, spec, forward, *, orga """ count = len(directions) maximum = np.full(count, 8.0) if key == "k1" else np.minimum(8.0, 6.0 / forward) - mount = tuple(origin) + # PhysX consumes Float3 internally. Native callers avoid repeated pybind + # sequence conversion; portable checks can use the identical tuple contract. + mount = query_vector(origin) positions = np.full((count, 3), np.nan) no_hit = np.zeros(count, dtype=bool) paths = [None] * count for row, (direction, limit) in enumerate( zip(directions.tolist(), maximum.tolist(), strict=True) ): - hit = query.raycast_closest(mount, tuple(direction), limit, bothSides=True) + hit = query.raycast_closest(mount, query_vector(direction), limit, bothSides=True) if not hit["hit"]: no_hit[row] = True elif not ( diff --git a/simulation/ai-polygon/native_experience.py b/simulation/ai-polygon/native_experience.py new file mode 100644 index 00000000..e386e8c6 --- /dev/null +++ b/simulation/ai-polygon/native_experience.py @@ -0,0 +1,51 @@ +"""Run-owned Isaac configuration without unrelated robot demonstration downloads. + +Derive both SDK profiles, retaining every renderer/physics setting and every +other dependency. Never edit the installed SDK or inherit persistent UI state. +""" + +import hashlib +import json +import tomllib +from pathlib import Path + + +DEMO = '"isaacsim.robot.policy.examples" = {}' +BASE = '"isaacsim.exp.base" = {}' + + +def prepare_experience(apps, directory): + apps, directory = Path(apps).resolve(), Path(directory).resolve() + base_path = apps / "isaacsim.exp.base.kit" + python_path = apps / "isaacsim.exp.base.python.kit" + base, python = base_path.read_text(), python_path.read_text() + parsed_base, parsed_python = tomllib.loads(base), tomllib.loads(python) + if not all(p["package"]["version"] == "6.1.0" for p in (parsed_base, parsed_python)): + raise RuntimeError("Unsupported Isaac experience profile; expected 6.1.0") + if base.count(DEMO) != 1 or python.count(BASE) != 1: + raise RuntimeError("Isaac experience dependencies changed; review required") + if parsed_python["settings"]["app"]["settings"]["persistent"] is not False: + raise RuntimeError("Native simulation must not inherit persistent UI settings") + # JSON strings are also valid TOML strings, including Windows path escaping. + sdk = json.dumps(apps.as_posix())[1:-1] + base = base.replace(DEMO, "").replace("${app}", sdk) + python = python.replace(BASE, '"missioncore.native.base" = {}').replace("${app}", sdk) + # Keep the SDK search paths and add only this run's derived base profile. + folders = "'++' = [" + if python.count(folders) != 1: + raise RuntimeError("Isaac extension search paths changed; review required") + python = python.replace(folders, folders + "\n " + json.dumps(directory.as_posix()) + ",", 1) + tomllib.loads(base); tomllib.loads(python) + directory.mkdir(parents=True, exist_ok=True) + derived_base = directory / "missioncore.native.base.kit" + derived_python = directory / "missioncore.native.python.kit" + derived_base.write_text(base) + derived_python.write_text(python) + receipt = { + "schema_version": "missioncore.native-experience/v1", + "excluded_dependency": "isaacsim.robot.policy.examples", + "sources": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in (base_path, python_path)}, + "derived": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in (derived_base, derived_python)}, + } + (directory / "receipt.json").write_text(json.dumps(receipt, indent=2)) + return str(derived_python) diff --git a/simulation/ai-polygon/realtime_worker.py b/simulation/ai-polygon/realtime_worker.py index 84a20d03..fc6df976 100644 --- a/simulation/ai-polygon/realtime_worker.py +++ b/simulation/ai-polygon/realtime_worker.py @@ -74,15 +74,23 @@ def acquire_service_lock(path): def publish_previews(client, episode, run_id, stopped): """Best-effort view telemetry has its own connection and never delays control.""" - last_frame = -1 - while not stopped.wait(0.5): + last_frame, last_modified = -1, None + path = episode / "inference-preview.json" + while not stopped.wait(0.05): try: - preview = read_json(episode / "inference-preview.json") + if not path.exists(): + continue + modified = path.stat().st_mtime_ns + if modified == last_modified: + continue + preview = read_json(path) if preview and preview["frame_id"] > last_frame: client.request("/worker/runs/" + run_id + "/inference-preview", preview) last_frame = preview["frame_id"] + last_modified = modified except Exception as exc: logging.warning("Inference preview unavailable: %s", type(exc).__name__) + stopped.wait(1) def preparation_heartbeat(client, hello, run_id): diff --git a/simulation/ai-polygon/run_realtime.py b/simulation/ai-polygon/run_realtime.py index 2703c6e5..17cda54f 100644 --- a/simulation/ai-polygon/run_realtime.py +++ b/simulation/ai-polygon/run_realtime.py @@ -3,6 +3,7 @@ import argparse import json import math +import os import shutil import sys import time @@ -62,6 +63,7 @@ def main(): CONTROL_PROFILE = robot["control"] startup_phase("native-runtime") from isaacsim import SimulationApp + from native_experience import prepare_experience app = SimulationApp( { @@ -85,7 +87,8 @@ def main(): "--/app/runLoops/main/manualModeEnabled=false", "--/exts/isaacsim.core.throttling/enable_manualmode=false", ], - } + }, + experience=prepare_experience(os.environ["EXP_PATH"], directory / "native-experience"), ) import carb.settings import numpy as np diff --git a/src/k1link/simulation/ai_polygon/preview_events.py b/src/k1link/simulation/ai_polygon/preview_events.py new file mode 100644 index 00000000..4a13df66 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/preview_events.py @@ -0,0 +1,47 @@ +"""Coalesced wakeups for latest-only operator previews; no frame history.""" + +import asyncio +import threading + + +class PreviewEvents: + def __init__(self): + self.lock = threading.Lock() + self.listeners = {} + + def subscribe(self): + loop = asyncio.get_running_loop() + queue = asyncio.Queue(maxsize=1) + key = object() + + def wake(): + with self.lock: + listener = self.listeners.get(key) + if listener is None: + return + listener[2] = False + if queue.empty(): + queue.put_nowait(None) + + with self.lock: + if len(self.listeners) >= 16: + raise RuntimeError("Слишком много подключений просмотра.") + self.listeners[key] = [loop, wake, False] + + def close(): + with self.lock: + self.listeners.pop(key, None) + + return queue, close + + def notify(self): + with self.lock: + for listener in self.listeners.values(): + loop, wake, pending = listener + if not pending and not loop.is_closed(): + # Bound both the event queue and cross-thread loop callbacks. + listener[2] = True + try: + loop.call_soon_threadsafe(wake) + except RuntimeError: + pass # A closing browser event loop owns no live consumer. diff --git a/src/k1link/simulation/ai_polygon/runs.py b/src/k1link/simulation/ai_polygon/runs.py index 54110307..186ec996 100644 --- a/src/k1link/simulation/ai_polygon/runs.py +++ b/src/k1link/simulation/ai_polygon/runs.py @@ -28,6 +28,7 @@ from k1link.simulation.ai_polygon.contracts import ( ) from k1link.simulation.ai_polygon.library import LibraryMetadata from k1link.simulation.ai_polygon.plans import PlanStore +from k1link.simulation.ai_polygon.preview_events import PreviewEvents from k1link.simulation.ai_polygon.robots import select_robot from k1link.simulation.ai_polygon.run_inputs import ( CONTINUOUS_SENSOR_SCHEMA, @@ -55,6 +56,7 @@ class RunStore: self.plans = PlanStore(worlds.root.parent / "plans") self.lock = threading.RLock() self.preview = None + self.preview_events = PreviewEvents() self.worker: dict | None = None self.seen = 0.0 self.active: str | None = None @@ -147,6 +149,7 @@ class RunStore: self._save(row) if self.active == run_id: self.active = None + self.preview_events.notify() def update_library(self, kind, identity, changes): with self.lock: @@ -486,9 +489,16 @@ class RunStore: raise ValueError("Invalid inference preview raster") image.verify() self.preview = (run_id, {**preview.model_dump(), "received_at": utc_now_iso()}) + self.preview_events.notify() return {"accepted": True} return self.preview[1] if self.preview and self.preview[0] == run_id else None + def preview_snapshot(self, run_id): + """RAM-only snapshot; subscription never polls files or the Worker.""" + with self.lock: + value = self.preview[1] if self.preview and self.preview[0] == run_id else None + return value, self.active == run_id + def view(self, run_id: str, camera: str, navigation=None) -> dict: with self.lock: row = self.get(run_id) diff --git a/src/k1link/web/ai_polygon_api.py b/src/k1link/web/ai_polygon_api.py index 2ff5e3cf..bdcca06d 100644 --- a/src/k1link/web/ai_polygon_api.py +++ b/src/k1link/web/ai_polygon_api.py @@ -5,7 +5,8 @@ from pathlib import Path from typing import Literal from fastapi import APIRouter, Header, HTTPException, Request, Response -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, StreamingResponse +from k1link.web.ai_preview_stream import preview_stream from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue from k1link.simulation.ai_polygon.composition import compose, registry @@ -244,6 +245,14 @@ def build_ai_polygon_router( response.headers["Cache-Control"] = "no-store" return invoke(runs.inference_preview, run_id) + @router.get("/runs/{run_id}/inference-preview/events") + async def inference_preview_events(run_id: str): + invoke(runs.get, run_id) + return StreamingResponse( + preview_stream(runs, run_id), media_type="text/event-stream", + headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"}, + ) + @router.post("/worker/runs/{run_id}/inference-preview") def publish_inference_preview( run_id: str, diff --git a/src/k1link/web/ai_preview_stream.py b/src/k1link/web/ai_preview_stream.py new file mode 100644 index 00000000..cb1cccf2 --- /dev/null +++ b/src/k1link/web/ai_preview_stream.py @@ -0,0 +1,25 @@ +"""Push the current preview on arrival; slow viewers skip obsolete frames.""" + +import asyncio +import json + + +async def preview_stream(runs, run_id): + queue, close = runs.preview_events.subscribe() + last_frame = -1 + try: + yield "retry: 1000\n\n" + while True: + preview, active = runs.preview_snapshot(run_id) + if preview is not None and preview["frame_id"] > last_frame: + last_frame = preview["frame_id"] + yield "data: " + json.dumps(preview, separators=(",", ":")) + "\n\n" + if not active: + yield "event: end\ndata: null\n\n" + return + try: + await asyncio.wait_for(queue.get(), timeout=10) + except TimeoutError: + yield ": keepalive\n\n" + finally: + close() diff --git a/tests/test_ai_preview_stream.py b/tests/test_ai_preview_stream.py new file mode 100644 index 00000000..25dae5fe --- /dev/null +++ b/tests/test_ai_preview_stream.py @@ -0,0 +1,60 @@ +"""Slow/reconnecting viewers receive current frames without growing queues.""" +import asyncio +import threading +from types import SimpleNamespace + +from k1link.simulation.ai_polygon.preview_events import PreviewEvents +from k1link.web.ai_preview_stream import preview_stream + + +def test_notifications_coalesce_before_and_after_event_loop_delivery(): + async def run(): + events = PreviewEvents() + queue, close = events.subscribe() + thread = threading.Thread(target=lambda: [events.notify() for _ in range(100)]) + thread.start(); thread.join() + assert len(events.listeners) == 1 + assert all(listener[2] for listener in events.listeners.values()) + await asyncio.sleep(0) + assert queue.qsize() == 1 + events.notify(); await asyncio.sleep(0) + assert queue.qsize() == 1 + close(); events.notify() + assert not events.listeners + asyncio.run(run()) + + +def test_slow_and_reconnecting_viewers_skip_obsolete_frames_and_close(): + async def run(): + state = [dict(frame_id=1, layers=[]), True] + events = PreviewEvents() + runs = SimpleNamespace(preview_events=events, preview_snapshot=lambda run_id: tuple(state)) + stream = preview_stream(runs, 'run') + assert 'retry' in await anext(stream) + assert '"frame_id":1' in await anext(stream) + state[0] = dict(frame_id=2, layers=[]); events.notify() + state[0] = dict(frame_id=3, layers=[]); events.notify() + assert '"frame_id":3' in await anext(stream) + await stream.aclose() + assert not events.listeners + again = preview_stream(runs, 'run') + await anext(again) + assert '"frame_id":3' in await anext(again) + state[1] = False; events.notify() + assert 'event: end' in await anext(again) + await again.aclose() + assert not events.listeners + asyncio.run(run()) + + +def test_cancel_waiting_viewer_releases_subscription(): + async def run(): + events = PreviewEvents() + runs = SimpleNamespace(preview_events=events, preview_snapshot=lambda run_id: (None, True)) + stream = preview_stream(runs, 'run'); await anext(stream) + task = asyncio.create_task(anext(stream)); await asyncio.sleep(0) + task.cancel() + try: await task + except asyncio.CancelledError: pass + assert not events.listeners + asyncio.run(run()) diff --git a/tests/test_native_sensor_throughput.py b/tests/test_native_sensor_throughput.py new file mode 100644 index 00000000..7cfbf51a --- /dev/null +++ b/tests/test_native_sensor_throughput.py @@ -0,0 +1,85 @@ +"""Sensor call optimization preserves obstacle and unknown-space semantics.""" +import sys +import tomllib +from pathlib import Path + +import numpy as np +import pytest + +sys.path.insert(0, str(Path(__file__).parents[1] / "simulation/ai-polygon")) +from mounted_sensors import mounted_range_returns +from native_experience import prepare_experience + + +@pytest.mark.parametrize("key", ["k1", "realsense"]) +def test_native_vectors_preserve_first_hits_self_occlusion_and_unknown(key): + hits = [ + dict(hit=True, position=[1, 0, 0], collision="/World/ThinSurface"), + dict(hit=True, position=[0.5, 0, 0], rigidBody="/World/Rover/chassis"), + dict(hit=False), + dict(hit=True, position=[0.01, 0, 0], collision="/World/TooNear"), + dict(hit=True, position=[2, 0, 0], collision="/World/Rover/chassis/Sensor"), + ] + class Query: + def __init__(self): self.calls = [] + def raycast_closest(self, origin, direction, distance, bothSides): + assert bothSides is True + self.calls.append((tuple(origin), tuple(direction), distance)) + return hits[len(self.calls) - 1] + class NativeVector(tuple): + pass + outputs = [] + for factory in (tuple, NativeVector): + q = Query(); organized = [] + result = mounted_range_returns(q, np.zeros(3), np.tile([1., 0, 0], (5, 1)), key, + dict(range_m=[0.1, 8], depth_z_range_m=[0.1, 6]), np.ones(5), + organized_ranges=organized, query_vector=factory) + assert len(q.calls) == 5 + assert result[3] == ["/World/ThinSurface"] + np.testing.assert_array_equal(organized[0], [1, 0, 8 if key == "k1" else 0, 0, 0]) + assert len(result[1]) == (2 if key == "k1" else 1) + if key == "realsense": + np.testing.assert_array_equal(result[2], [1, np.nan, np.nan, np.nan, np.nan]) + outputs.append((result, q.calls)) + for a, b in zip(outputs[0][0][:3], outputs[1][0][:3]): np.testing.assert_array_equal(a, b) + assert outputs[0][1] == outputs[1][1] + + +def test_derived_experience_preserves_sdk_and_renderer_configuration(tmp_path): + sdk = tmp_path / "SDK apps"; sdk.mkdir() + base = sdk / "isaacsim.exp.base.kit" + base.write_text('''[package] +version = "6.1.0" +[dependencies] +"isaacsim.robot.policy.examples" = {} +"omni.physics.physx" = {} +[settings] +"raytracing.quality" = 5 +[settings.app] +versionFile = "${app}/../VERSION" +''') + python = sdk / "isaacsim.exp.base.python.kit" + python.write_text('''[package] +version = "6.1.0" +[dependencies] +"isaacsim.exp.base" = {} +[settings.app] +settings.persistent = false +[settings.app.exts.folders] +'++' = ["${app}", "${app}/../exts"] +''') + original = (base.read_bytes(), python.read_bytes()) + out = tmp_path / "run" + result = Path(prepare_experience(sdk, out)) + derived = tomllib.loads((out / "missioncore.native.base.kit").read_text()) + assert derived["dependencies"] == {"omni.physics.physx": {}} + assert derived["settings"]["raytracing.quality"] == 5 + child = tomllib.loads(result.read_text()) + assert child["settings"]["app"]["settings"]["persistent"] is False + assert child["dependencies"] == {"missioncore.native.base": {}} + assert child["settings"]["app"]["exts"]["folders"]["++"] == [str(out), str(sdk), str(sdk) + "/../exts"] + assert original == (base.read_bytes(), python.read_bytes()) + first = result.read_bytes() + assert Path(prepare_experience(sdk, out)).read_bytes() == first + python.write_text(python.read_text().replace("6.1.0", "6.2.0")) + with pytest.raises(RuntimeError, match="Unsupported"): prepare_experience(sdk, out) diff --git a/tests/test_simulation_observer_profiles.py b/tests/test_simulation_observer_profiles.py index d1bccc1f..7ffb317b 100644 --- a/tests/test_simulation_observer_profiles.py +++ b/tests/test_simulation_observer_profiles.py @@ -100,10 +100,18 @@ def test_uncertain_path_is_not_a_persistent_obstacle_but_cannot_supply_a_goal(): adapter.segmenter_id = "simulation-segformer-ade" adapter.models = SimpleNamespace(labels={}) adapter.mission = WaypointMission([[2, 0]]) + from k1link.simulation.ai_polygon.robots import select_robot + from k1link.simulation.ai_polygon.run_inputs import sensor_rig + from k1link.simulation.ai_polygon.source_projection import PinholeSource + robot = select_robot("dcd006-v020") + adapter.geometry = robot["physics"] + adapter.source = PinholeSource(sensor_rig(robot, 0.8)) labels = np.full((512, 512), 13, dtype=np.uint8) labels[:, :100] = 9 # A lawn is still an explicit profile exclusion. output = adapter.plan_mission( { + "navigation.route": None, + "segmentation.known": np.zeros_like(labels, dtype=bool), "segmentation.labels": labels, "segmentation.surface": np.zeros_like(labels, dtype=bool), "source.lidar": np.array([[x, y, 0] for x in [1.5, 2, 2.5] for y in [-0.2, 0, 0.2]]),