"""Opt-in offline adapter; no model loader, thread, actuator or automatic grant. The real decoder MUST call begin_source, then accepted immediately after each successful decode, before queue/throttle/inference. Its newly allocated image buffer must remain owned by that ticket and must never be reused or mutated. Lock order: camera lifecycle barrier, then control RLock, then lens lock. A transition callback must not newly acquire lifecycle locks under control. """ from dataclasses import dataclass from types import SimpleNamespace import time from .frame_time import FrameClock from .inspection_runtime import check_stamp _configured = None def enabled(): from . import config return getattr(config, 'UNKNOWN_INSPECTION_ENABLE', False) is True def configure(adapter): global _configured if not isinstance(adapter, Handoff): raise ValueError('Explicit verified-model bridge required') from . import alarm_boundary alarm_boundary.bind_guard(adapter.bridge.gate, adapter.bridge.active_context) _configured = adapter def require_configured(): if not isinstance(_configured, Handoff): raise RuntimeError('UNKNOWN producer/dispatcher/model binding is not configured') return _configured @dataclass(frozen=True) class FrameTicket: stamp: object acquired_owner: tuple state_ref: object pixels: object camera_epoch: int handoff_epoch: int class Handoff: def __init__(self, bridge, *, camera_epoch, latest_visual, mono_ns=time.monotonic_ns, utc_ns=time.time_ns, authorize=None): self.bridge, self.camera_epoch, self.latest_visual = bridge, camera_epoch, latest_visual self.mono_ns, self.utc_ns = mono_ns, utc_ns self.sources, self.epochs = {}, {} self.authorize = authorize def begin_source(self, camera, source_id, stream_epoch, epoch): with self.bridge.control_lock(camera): st = self.bridge.state_provider(camera) if epoch != self.camera_epoch(camera): return False previous = self.sources.get(camera) key = source_id, stream_epoch, epoch, id(st) if previous and previous[0] == key: return True clock = FrameClock(camera, source_id, stream_epoch) self.bridge.revoke(camera, st, 'decoder_source_changed') self.epochs[camera] = self.epochs.get(camera, 0)+1 self.sources[camera] = key, clock, st self._clear_pending(st) return True # NEVER grants inspection_authorized def end_source(self, camera, stream_epoch=None, *, reason='decoder_disconnected'): with self.bridge.control_lock(camera): source = self.sources.get(camera) if source is None or (stream_epoch is not None and source[0][1] != stream_epoch): return self.sources.pop(camera) self.epochs[camera] += 1 st = self.bridge.state_provider(camera) self._clear_pending(st) self.bridge.revoke(camera, st, reason) st.pop('inspection_source_binding', None) st['inspection_control_deadline'] = 0. @staticmethod def _clear_pending(st): for key in ('pending_frame', 'pending_source_seq', 'pending_inspection_ticket'): st.pop(key, None) def accepted(self, camera, frame, source_seq, epoch): """Call immediately after decode; preserve receipt/owner BEFORE lock wait. This local receipt is not exposure time. A producer that already queued its image must supply the original ticket, never call accepted again. """ original_state = self.bridge.state_provider(camera) original_source = self.sources.get(camera) if not original_source or original_source[2] is not original_state: return None original_owner = self.bridge.owner(original_state) original_epoch = self.epochs.get(camera) before = self.mono_ns(); utc = self.utc_ns(); after = self.mono_ns() received = (before+after)//2 with self.bridge.control_lock(camera): st = self.bridge.state_provider(camera) source = self.sources.get(camera) if (source is not original_source or st is not original_state or original_epoch != self.epochs.get(camera) or original_owner != self.bridge.owner(st) or epoch != source[0][2] or epoch != self.camera_epoch(camera) or not 0 <= (self.mono_ns()-received)/1e9 <= .65): return None try: stamp = source[1].observe(source_seq=source_seq, mono_before_ns=before, mono_after_ns=after, utc_ns=utc) except ValueError: # another accepted newer image may have won the lock return None self.bridge.bind_source(camera, st, stamp) return FrameTicket(stamp, original_owner, st, frame, epoch, original_epoch) def current(self, ticket, *, age=.65): if not isinstance(ticket, FrameTicket): return False camera = ticket.stamp.camera_id st = self.bridge.state_provider(camera) return bool(ticket.state_ref is st and ticket.handoff_epoch == self.epochs.get(camera) and ticket.camera_epoch == self.camera_epoch(camera) and check_stamp(ticket.stamp, camera=camera, seq=ticket.stamp.source_seq, owner=ticket.acquired_owner, expected_owner=self.bridge.owner(st), binding=st.get('inspection_source_binding'), now=self.mono_ns()/1e9, age=age)) def note_age(self, ticket, stage): if self.current(ticket): ticket.state_ref.setdefault('inspection_decode_age_s', {})[stage] = max( 0., (self.mono_ns()-ticket.stamp.decode_mono_ns)/1e9) def bind_item(self, item, ticket): cam, frame, _ptz, seq, future, _queued = item if (not self.current(ticket) or ticket.stamp.camera_id != cam or frame is not ticket.pixels or seq != ticket.stamp.source_seq): return False future.inspection_ticket = ticket future.visual_sample = None self.note_age(ticket, 'enqueue') return True def pending(self, ticket): if not isinstance(ticket, FrameTicket): return False camera = ticket.stamp.camera_id with self.bridge.control_lock(camera): if not self.current(ticket): return False st = ticket.state_ref current = st.get('pending_inspection_ticket') if current and ticket.stamp.source_seq <= current.stamp.source_seq: return False st['pending_frame'], st['pending_source_seq'], st['pending_inspection_ticket'] = ( ticket.pixels, ticket.stamp.source_seq, ticket) return True def refresh(self, item): camera, _frame, _ptz, seq, future, queued = item with self.bridge.control_lock(camera): st = self.bridge.state_provider(camera) pending = st.get('pending_inspection_ticket') if pending is None: return item, False if (not self.current(pending) or st.get('pending_frame') is not pending.pixels or st.get('pending_source_seq') != pending.stamp.source_seq): self._clear_pending(st) return item, False if pending.stamp.source_seq <= seq: return item, False self._clear_pending(st) updated = camera, pending.pixels, _ptz, pending.stamp.source_seq, future, queued self.bind_item(updated, pending) # replaces the whole ticket, never a timestamp self.note_age(pending, 'pending_refresh') return updated, True def prepare(self, item): camera, _frame, ptz, _seq, future, queued = item with self.bridge.control_lock(camera): ticket = getattr(future, 'inspection_ticket', None) if (not self.current(ticket) or ticket.stamp.camera_id != camera or ticket.pixels is not _frame or ticket.stamp.source_seq != _seq): return item saved = self.latest_visual(camera, self.utc_ns()/1e9) if saved is None: return item pixels, sample = saved paired = getattr(sample, 'inspection_ticket', None) if (not self.current(paired, age=.20) or pixels is not paired.pixels or sample.source_seq != paired.stamp.source_seq or sample.owner != paired.acquired_owner or getattr(sample, 'inspection_stamp', None) != paired.stamp or sample.result.source_seq != paired.stamp.source_seq): return item future.inspection_ticket, future.visual_sample = paired, sample self.note_age(paired, 'paired_before_inference') return camera, pixels, ptz, paired.stamp.source_seq, future, queued def prune(self, items): valid = [] for item in items: camera, frame, _ptz, seq, future, _ = item ticket = getattr(future, 'inspection_ticket', None) if (self.current(ticket) and ticket.pixels is frame and ticket.stamp.camera_id == camera and ticket.stamp.source_seq == seq): self.note_age(ticket, 'before_inference') valid.append(item) elif not future.done(): future.set_result(None) return valid def process_item(self, camera, pixels, result, ptz, seq, future): ticket = getattr(future, 'inspection_ticket', None) if (not ptz or not self.current(ticket) or ticket.pixels is not pixels or ticket.stamp.camera_id != camera or ticket.stamp.source_seq != seq): return False self.note_age(ticket, 'after_inference') return self.bridge.process(camera, ticket.state_ref, ticket.stamp, pixels, result, acquired_owner=ticket.acquired_owner, visual_sample=getattr(future,'visual_sample',None), handoff_check=lambda: self._authorize_current(ticket)) def _authorize_current(self, ticket): if not self.current(ticket): return False if self.authorize is None: return True # Explicit external grant used by an embedded dispatcher. st = ticket.state_ref try: allowed = self.authorize(ticket.stamp.camera_id, ticket.acquired_owner) is True except Exception: allowed = False if not self.current(ticket): return False if not allowed and st.get('inspection_authorized') is True: self.bridge.revoke(ticket.stamp.camera_id, st, 'inspection_authorization_revoked') st['inspection_authorized'] = allowed return True # The controller handles STOP for denied active sessions. def visual_sample(self, ticket, result): if not self.current(ticket, age=.25) or result.source_seq != ticket.stamp.source_seq: return None return SimpleNamespace(owner=ticket.acquired_owner, source_seq=ticket.stamp.source_seq, captured_at=ticket.stamp.decode_utc_ns/1e9, result=result, inspection_stamp=ticket.stamp, inspection_owner=ticket.acquired_owner, inspection_ticket=ticket) def transition(self, camera, st, acquired_owner, reason, existing_transition): """Explicit FULLSTOP/manual/source retirement; callback keeps physical STOP. Never wrap arbitrary short geometry/watchdog STOP as a lifecycle revoke. Enter any camera lifecycle barrier BEFORE this API; multiple IDs use its existing ascending-ID order. The callback must never acquire a new lifecycle lock under this control RLock. Lens locks come last. """ with self.bridge.control_lock(camera): if st is not self.bridge.state_provider(camera) or acquired_owner != self.bridge.owner(st): return False self.epochs[camera] = self.epochs.get(camera, 0)+1 self._clear_pending(st) self.bridge.revoke(camera, st, reason) existing_transition() # no grant, budget/no-effect reset, or new PTZ worker return True