"""Bounded 1x replay of stationary collection, provisional search and fresh checks.""" import json import time from concurrent.futures import ThreadPoolExecutor import numpy as np from k1link.artifacts import utc_now_iso from .causal_replay import digest from .causal_tracking import TRACKING_POLICY from .entry_acquisition_worker import run_entry_acquisition from .live_buffer import LiveCloudBuffer from .registration import POLICY from .registration_worker import run_registration from .stationary_bootstrap import BOOTSTRAP_POLICY, StationaryBootstrap from .stationary_entry import STATIONARY_POLICY def replay_stationary( events, reference, reference_path, directory, *, calculate=run_registration, initialize=run_entry_acquisition, max_seconds=65.0, max_distance=40.0, ): if not 0 < max_seconds <= 120 or not 0 < max_distance <= 40: raise ValueError("Replay exceeds functional probe bounds.") iterator = iter(events) event = next(iterator, None) if event is None: raise ValueError("Empty replay.") directory.mkdir(parents=True, exist_ok=False) origin, started = event.monotonic_ns, time.monotonic_ns() boot, buffer = StationaryBootstrap(reference_path), LiveCloudBuffer(reference_path) deliveries, steps, transitions = [], [], [] report = dict( schema_version="missioncore.stationary-causal-replay/v1", created_at_utc=utc_now_iso(), started_monotonic_ns=started, query_origin_monotonic_ns=origin, pace=1, bootstrap_policy=BOOTSTRAP_POLICY, registration_policy=POLICY, stationary_policy=STATIONARY_POLICY, tracking_policy=TRACKING_POLICY, maximum_seconds=max_seconds, maximum_distance_m=max_distance, vehicle_control=False, localization_confirmed=False, slam_reset_verified=False, first_prior_s=None, first_candidate_s=None, first_tracking_s=None, steps=steps, transitions=transitions, ) future, pending, last_state = None, None, None def source_now(): return origin + time.monotonic_ns() - started def observe(now): nonlocal last_state state = (boot.phase, boot.reason, boot.gate.state, boot.gate.reason, buffer.segment) if state != last_state: transitions.append( dict( time_s=(now - origin) / 1e9, phase=boot.phase, reason=boot.reason, tracking_state=boot.gate.state, tracking_reason=boot.gate.reason, streak=boot.gate.streak, segment=buffer.segment, ) ) last_state = state def finish(now, *, active=True): nonlocal future, pending if future is None or not future.done(): return sample, info = pending try: result = future.result() except (ValueError, RuntimeError) as exc: result = dict(status="rejected", reasons=["worker-error"], error=str(exc)) future = None if not active: temporal = dict(accepted=False, reason="input-ended") elif info["role"] == "stationary-initialization": temporal = boot.offer_prior(result, now, buffer.segment) if temporal.get("provisional"): report["first_prior_s"] = (now - origin) / 1e9 else: temporal = boot.accept_fresh(result, sample, now, buffer.segment) info.update( completed_s=(now - origin) / 1e9, worker_wall_s=(now - info.pop("_started_ns")) / 1e9, temporal=temporal, phase=boot.phase, tracking_state=boot.gate.state, streak=boot.gate.streak, result={k: v for k, v in result.items() if k != "matched_query_indices"}, ) steps.append(info) if temporal["accepted"] and report["first_candidate_s"] is None: report["first_candidate_s"] = info["completed_s"] if boot.gate.state == "tracking" and report["first_tracking_s"] is None: report["first_tracking_s"] = info["completed_s"] observe(now) def stage(sample, now, role, extra=None): step = len(steps) + 1 target = directory / f"step-{step:03d}" target.mkdir() info = dict( step=step, role=role, requested_s=(now - origin) / 1e9, sample_s=(sample["monotonic_ns"] - origin) / 1e9, sequence=sample["sequence"], segment=sample["segment"], distance_m=sample["distance"], points=len(sample["points"]), source_events=sample["events"], fresh_floor_ns=sample.get("fresh_floor_ns"), **(extra or {}), ) (target / "source.json").write_text(json.dumps(info, allow_nan=False)) np.save(target / "query-path.npy", sample["path"], allow_pickle=False) return target, (sample, {**info, "_started_ns": now}) pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="stationary-replay-fit") try: while event is not None: due = (event.monotonic_ns - origin) / 1e9 if due > max_seconds: report["end_reason"] = "time-bound" break now = source_now() if (now - origin) / 1e9 > max_seconds + 35: raise ValueError("Replay exceeded wall-clock allowance.") boot.tick(now, buffer.segment) finish(now) # All prefix receipts have been delivered before freezing. The pending # event contributes only its due time, never its future pose or points. if future is None and due > BOOTSTRAP_POLICY["prefix_seconds"]: acquisition = boot.start_search(now) if acquisition is not None: sample, initial, basis, meta = acquisition target, pending = stage( sample, now, "stationary-initialization", {"prefix": meta} ) future = pool.submit( initialize, target, reference, sample["points"], initial, sample["path"][0], basis, mode="stationary", ) observe(now) if now < event.monotonic_ns: time.sleep(min(0.02, (event.monotonic_ns - now) / 1e9)) continue before = time.monotonic_ns() buffer.ingest(event) boot.ingest(event, buffer.segment) deliveries.append( dict( sequence=event.sequence, kind=event.kind, time_s=due, lateness_s=max(0, (now - event.monotonic_ns) / 1e9), ingest_s=(time.monotonic_ns() - before) / 1e9, ) ) boot.tick(source_now(), buffer.segment) observe(source_now()) if buffer.distance >= max_distance: report["end_reason"] = "distance-bound" break if future is None and event.kind == "points" and len(steps) < 24: now = source_now() validation = boot.validation(now, buffer.distance) if validation is not None: sample, hint = validation target, pending = stage(sample, now, "fresh-validation") future = pool.submit(calculate, target, reference, sample["points"], hint) event = next(iterator, None) report.setdefault("end_reason", "input-ended") report["input_end_s"] = (source_now() - origin) / 1e9 boot.stop("input-ended") observe(source_now()) while future is not None: finish(source_now(), active=False) if future is not None: time.sleep(0.02) report["state"] = "completed" except Exception as exc: boot.stop("replay-error") observe(source_now()) report.update(state="error", error=f"{type(exc).__name__}: {exc}") raise finally: pool.shutdown(wait=True, cancel_futures=True) close = getattr(iterator, "close", None) if close: close() report.update( finished_at_utc=utc_now_iso(), elapsed_s=(time.monotonic_ns() - started) / 1e9, gaps=buffer.gaps, distance_m=buffer.distance, ) (directory / "deliveries.json").write_text(json.dumps(deliveries)) report["artifacts"] = { str(p.relative_to(directory)): digest(p) for p in directory.rglob("*") if p.is_file() } (directory / "report.json").write_text(json.dumps(report, allow_nan=False, indent=2)) return report