"""Ranked stationary hypotheses followed by disjoint, fresh geometric checks. A prior is a hypothesis, never a CausalTracking result. Receipt continuity does not prove SLAM frame continuity; this remains a laboratory-only protocol. """ import numpy as np from .causal_tracking import TRACKING_POLICY, CausalTracking from .live_buffer import LiveCloudBuffer from .registration import rigid from .stationary_entry import STATIONARY_POLICY, StationaryPrefix BOOTSTRAP_POLICY = dict( version="stationary-fresh-bootstrap/v4", prefix_seconds=10.0, maximum_motion_m=0.10, maximum_search_wall_s=30.0, maximum_prior_source_age_s=40.0, maximum_pre_ready_gaps=1, maximum_pre_validation_gaps=1, prior_lifetime_s=10.0, minimum_fresh_span_s=2.0, check_interval_s=5.0, maximum_initializations=1, trials_per_hypothesis=1, allow_travel_heading_fallback=False, ) class StationaryBootstrap: def __init__( self, reference_path, *, initialization_policy=STATIONARY_POLICY, point_radius_m=20.0 ): self.reference_path = np.asarray(reference_path) self.point_radius_m = point_radius_m self.prefix = StationaryPrefix(reference_path, point_radius_m=point_radius_m) self.initialization_policy = initialization_policy self.gate = CausalTracking() self.phase = "collecting" self.reason = "prefix" self.identity = None self.last_event_ns = None self.last_sequence = -1 self.origin = None self.segment = 0 self.initialization_sample = None self.search_started_ns = None self.ready_ns = None self.prior = None self.fresh = None self.floor_ns = None self.last_check_ns = None self.validation_pending = False self.tracking_established = False self.candidate_queue = [] self.candidate_trial = 0 self.candidate_index = None self.dense_start_prior = False self.retry_route_search = False self.last_pose_ns = None self.last_cloud_ns = None self.search_continuity_proven = False @property def continuous_search(self): return self.initialization_policy.get("hypothesis_freshness") == ( "stationary-receipts-and-disjoint-confirmation/v1" ) def stop(self, reason): self.prior = None self.fresh = None self.validation_pending = False self.candidate_queue = [] self.retry_route_search = False self.gate.clear(reason) self.search_continuity_proven = False self.phase = "lost" self.reason = reason def ingest(self, event, segment): identity = (event.session_id, event.generation) if self.identity is None: self.identity, self.origin = identity, event.monotonic_ns if identity != self.identity: self.stop("identity-changed") raise ValueError("Session or generation changed during stationary bootstrap.") if self.last_event_ns is not None and ( event.monotonic_ns < self.last_event_ns or event.sequence <= self.last_sequence ): self.stop("source-order-changed") raise ValueError("Source sequence or receipt clock regressed.") self.last_event_ns, self.last_sequence = event.monotonic_ns, event.sequence if event.kind == "pose": self.last_pose_ns = event.monotonic_ns if self.phase == "searching" and self.continuous_search: motion = float(np.linalg.norm( np.asarray(event.position) - self.prefix.first_position )) if not np.isfinite(motion) or motion > BOOTSTRAP_POLICY["maximum_motion_m"]: self.stop("search-motion") elif event.kind == "points": self.last_cloud_ns = event.monotonic_ns if segment != self.segment: # Worker completion is not a data receipt. A gap straddling that # instant may finish before the first fresh cloud. No validation has # used the prior yet: start a new continuous window without extending # its lifetime or allowing more gaps than the original prefix budget. awaiting_first_cloud = ( self.phase == "refreshing" and self.prior is not None and not self.validation_pending and not self.fresh.events and 0 <= segment - self.initialization_sample["segment"] <= BOOTSTRAP_POLICY["maximum_pre_validation_gaps"] ) if awaiting_first_cloud: self.segment = segment self._reset_fresh(self.floor_ns) elif self.phase in {"refreshing", "validating", "tracking"} or ( self.phase == "searching" and self.continuous_search ): self.stop("receipt-gap") self.segment = segment if self.phase == "collecting": self.prefix.ingest(event) elif self.fresh is not None and event.monotonic_ns > self.floor_ns: self.fresh.ingest(event) def tick(self, now_ns, segment): self.gate.tick(now_ns, segment) if self.phase == "searching" and self.continuous_search: # Old geometry may propose a place only while the live scanner is # still stationary in the same receipt segment. Neither a cloud-only # nor a pose-only stream can keep a long search alive. if segment != self.initialization_sample["segment"]: self.stop("receipt-gap") elif any(stamp is None or not 0 <= (now_ns - stamp) / 1e9 <= TRACKING_POLICY["maximum_age_s"] for stamp in (self.last_pose_ns, self.last_cloud_ns)): self.stop("search-source-stale") if self.phase in {"validating", "tracking"} and self.gate.reason == "stale": self.stop("stale") if self.phase == "refreshing" and ( now_ns - self.ready_ns > BOOTSTRAP_POLICY["prior_lifetime_s"] * 1e9 ): self.stop("prior-expired") def start_search(self, now_ns): if self.phase != "collecting" or self.origin is None: return None if (now_ns - self.origin) / 1e9 < BOOTSTRAP_POLICY["prefix_seconds"]: return None sample, initial, forward, meta = self.prefix.freeze() sample["segment"] = self.segment self.initialization_sample = sample self.search_started_ns = now_ns self.phase, self.reason = "searching", "bounded-entry-search" return sample, initial, forward, meta def offer_prior(self, result, now_ns, segment): self.tick(now_ns, segment) if self.phase != "searching": return dict(accepted=False, reason=self.reason if self.phase == "lost" else "inactive-initialization", provisional=False) sample = self.initialization_sample age = (now_ns - sample["monotonic_ns"]) / 1e9 initialization = result.get("initialization", {}) reason = None if result["status"] != "candidate": reason = { "incomplete-search": "initialization-incomplete", "incomplete-route-search": "initialization-incomplete", "ambiguous-route-location": "initialization-ambiguous", "no-route-location": "initialization-no-route-location", }.get(initialization.get("reason"), "initialization-rejected") elif ( not initialization.get("complete") or initialization.get("policy") != self.initialization_policy ): reason = "initialization-incomplete" elif self.initialization_policy is STATIONARY_POLICY and len( initialization.get("attempts", []) ) != 108: # Preserve the strict evidence count for the existing local-start # protocol and use an explicit dynamic count for route retrieval. reason = "initialization-incomplete" elif self.initialization_policy.get("scope") == "selected-route" and ( initialization.get("scope") != "selected-route" or initialization.get("expected_attempts") != len(initialization.get("attempts", [])) ): reason = "initialization-incomplete" elif not self.continuous_search and not ( 0 <= (now_ns - self.search_started_ns) / 1e9 <= self.initialization_policy.get( "maximum_search_wall_s", BOOTSTRAP_POLICY["maximum_search_wall_s"] ) ): reason = "initialization-expired" elif age < 0 or (not self.continuous_search and age > BOOTSTRAP_POLICY["maximum_prior_source_age_s"]): reason = "prior-source-expired" elif not 0 <= segment - sample["segment"] <= BOOTSTRAP_POLICY["maximum_pre_ready_gaps"]: reason = "too-many-receipt-gaps" if reason: self.stop(reason) return dict(accepted=False, reason=reason, age_s=age, provisional=False) queue = initialization.get("candidate_queue", []) if queue and queue[0].get("ambiguous", True): self.stop("initialization-ambiguous") return dict(accepted=False, reason=self.reason, provisional=False, age_s=age) if queue and not np.allclose(rigid(queue[0]["T_reference_query"]), rigid(result["T_reference_query"])): self.stop("initialization-incomplete") return dict(accepted=False, reason=self.reason, provisional=False, age_s=age) self.candidate_queue = [dict(item) for item in queue[1:]] self.search_continuity_proven = self.continuous_search self.candidate_trial = 1 self.candidate_index = initialization.get("selected_candidate_index") stages = initialization.get("stages", []) self.dense_start_prior = bool(stages and len(stages) == 1 and stages[0]["name"] == "dense-start") self.prior = rigid(result["T_reference_query"]).copy() self.ready_ns = now_ns self.segment = segment self._reset_fresh(now_ns) self.phase, self.reason = "refreshing", "provisional-prior" # Deliberately never call gate.accept with the old initialization sample. return dict( accepted=False, reason=self.reason, age_s=age, provisional=True, source_segment=sample["segment"], validation_segment=segment, stationary_search_continuity=self.search_continuity_proven, ) def _reset_fresh(self, floor_ns): self.floor_ns = floor_ns self.fresh = LiveCloudBuffer(self.reference_path, point_radius_m=self.point_radius_m) self.fresh.segment = self.segment def _advance_candidate(self, now_ns): """A different hypothesis gets a new receipt fence, never a reused fit. This is available only before tracking. Once tracking is established, loss must use the ordinary last-confirmed-place recovery instead. The legacy local protocol retains its source-age fence. Whole-route hypotheses have proved stationary receipt continuity and still need a new, disjoint current-data trial for EACH candidate. """ age = (now_ns - self.initialization_sample["monotonic_ns"]) / 1e9 if age < 0 or (not self.search_continuity_proven and age > BOOTSTRAP_POLICY["maximum_prior_source_age_s"]): self.stop("prior-source-expired") return candidate = self.candidate_queue.pop(0) if candidate["ambiguous"]: self.stop("initialization-ambiguous") return self.prior = rigid(candidate["T_reference_query"]).copy() self.candidate_trial += 1 self.candidate_index = candidate["candidate_index"] self.ready_ns = now_ns self.last_check_ns = None self.validation_pending = False self.gate.clear("next-candidate") self._reset_fresh(now_ns) self.phase, self.reason = "refreshing", "provisional-prior" def validation(self, now_ns, distance): self.tick(now_ns, self.segment) if self.phase not in {"refreshing", "validating", "tracking"} or self.validation_pending: return None if self.last_check_ns is not None and ( now_ns - self.last_check_ns < BOOTSTRAP_POLICY["check_interval_s"] * 1e9 ): return None if not self.fresh.events or ( self.fresh.sample_ns - self.fresh.events[0]["monotonic_ns"] < BOOTSTRAP_POLICY["minimum_fresh_span_s"] * 1e9 ): return None sample = self.fresh.snapshot() if len(sample["points"]) < 300: return None seed = self.prior if self.phase == "refreshing" else self.gate.matrix if seed is None: self.stop("missing-fresh-seed") return None sample["distance"] = distance sample["fresh_floor_ns"] = self.floor_ns self.validation_pending = True self.last_check_ns = now_ns self.prior = None # One trial per hypothesis; never reseed the failed one. self._reset_fresh(sample["monotonic_ns"]) return sample, seed.copy() def accept_fresh(self, result, sample, now_ns, segment): self.tick(now_ns, segment) if self.phase not in {"refreshing", "validating", "tracking"}: return dict(accepted=False, reason=self.reason) self.validation_pending = False if not sample["events"] or any( e["monotonic_ns"] <= sample["fresh_floor_ns"] for e in sample["events"] ): self.stop("pre-validation-data") return dict(accepted=False, reason=self.reason) temporal = self.gate.accept(result, sample, now_ns, segment) if not temporal["accepted"]: geometric_rejection = temporal["reason"] in { "registration-rejected", "inconsistent-candidate" } if not self.tracking_established and geometric_rejection and self.candidate_queue: failed_trial = self.candidate_trial self._advance_candidate(now_ns) temporal.update( rejected_candidate_trial=failed_trial, next_candidate_trial=self.candidate_trial if self.prior is not None else None, continuation_reason=self.reason, ) else: retry_route_search = ( not self.tracking_established and geometric_rejection and self.dense_start_prior ) self.stop(temporal["reason"]) self.retry_route_search = retry_route_search else: self.phase = "tracking" if self.gate.state == "tracking" else "validating" self.reason = self.gate.reason self.tracking_established |= self.phase == "tracking" if self.tracking_established: self.candidate_queue = [] return temporal