"""Explicit offline producer glue; use the existing camera control lock/worker. No startup side effects, lifecycle grants, model loading, background threads or physical I/O. bind_source/revoke must be wired into the REAL dispatcher before deployment. Actual inference producer must preserve original FrameStamp pixels. """ import hashlib import json from .alarm_eligibility import AlarmEligibility, Context, Frame, Semantic from .inspection_input import adapt_result from .inspection_runtime import CropContext, CropWorker, check_stamp, source_key from .unknown_inspection import Session, Settings def source_token(key): if type(key) is not tuple or len(key) != 3: return None return hashlib.sha256(json.dumps(key,separators=(',',':')).encode('ascii')).hexdigest() class InspectionBridge: def __init__(self, *, settings, cameras, proposal_contract, classifier_contract, owner, control_lock, controller, alarm_ready, state_provider, clock): if not isinstance(settings, Settings): raise ValueError('Calibrated settings required') self.settings, self.proposal, self.classifier = settings, proposal_contract, classifier_contract self.owner, self.control_lock, self.controller = owner, control_lock, controller self.alarm_ready, self.state_provider, self.clock = alarm_ready, state_provider, clock self.crops = CropWorker(tuple(cameras)) self.gate = AlarmEligibility(semantic_min=settings.semantic_min, margin=settings.semantic_margin, min_side=settings.min_side_px, sharpness_min=settings.min_sharpness) self.contexts = {} # Validate both actual tasks/names/SHAs even before the first frame. test = Context(tuple(cameras)[0], 1, (1,), 'validation_epoch', settings.proposal_sha, settings.classifier_sha) self.gate.begin(test, proposal_contract=proposal_contract, classifier_contract=classifier_contract) self.gate.revoke(test.camera) def revoke(self, camera, st, reason): """Existing dispatcher still performs its own STOP/invalidation.""" if st is not self.state_provider(camera): return False self.crops.revoke(camera) self.gate.revoke(camera) self.contexts.pop(camera, None) st['inspection_authorized'] = False st['inspection_common_alarm_guard'] = None if isinstance(st.get('inspection_session'), Session): st['inspection_session'].phase = 'closed' st['inspection_session'].revoke_semantics(reason) def bind_source(self, camera, st, stamp): """Trusted lifecycle hook, under the existing control lock. No grant.""" if st is not self.state_provider(camera): return False if stamp.camera_id != camera: raise ValueError('Foreign source') key = source_key(stamp) if st.get('inspection_source_binding') != key: self.revoke(camera, st, 'source_or_clock_epoch_changed') st['inspection_source_binding'] = key st.pop('inspection_detector_stamp', None) st.pop('inspection_semantic_stamp', None) st.pop('inspection_input_mono', None) st['inspection_control_deadline'] = 0. def retire_closed(self, camera, st, *, inspection_id, expected_owner): """Explicit new discovery, never an automatic reconnect/time-out retry. Caller holds the control lock and has issued a NEW owner token. Neither authorization, inspection serial nor the global no-effect latch resets. """ session = st.get('inspection_session') if (st is not self.state_provider(camera) or st.get('inspection_authorized') is not False or not isinstance(session,Session) or session.phase != 'closed' or session.inspection_id != inspection_id or expected_owner != self.owner(st) or expected_owner == session.owner): return False self.revoke(camera,st,'explicit_new_discovery') st['inspection_retired_summary'] = (session.inspection_id,session.deadline_mono,session.owner) st.pop('inspection_session',None) st.pop('inspection_detector_stamp',None) st.pop('inspection_semantic_stamp',None) st['inspection_control_deadline'] = 0. return True def _matching_context(self, camera, st): ctx = self.contexts.get(camera) session = st.get('inspection_session') if (st is not self.state_provider(camera) or not ctx or not isinstance(session,Session) or session.inspection_id != ctx.inspection_id or session.owner != ctx.owner or session.contract != self.settings or self.owner(st) != ctx.owner or source_token(st.get('inspection_source_binding')) != ctx.source_id or ctx.proposal_sha != self.settings.proposal_sha or ctx.classifier_sha != self.settings.classifier_sha): return None return ctx def common_ready(self, camera, st): ctx = self._matching_context(camera,st) return bool(ctx and self.gate.eligible(ctx,self.clock())) def active_context(self, camera): """Use as alarm_boundary.bind_guard provider: Session AND shared gate.""" st = self.state_provider(camera) ctx = self._matching_context(camera,st) return ctx if ctx and self.alarm_ready(st) else None def process(self, camera, st, stamp, frame, result, *, acquired_owner, occluded=None, visual_sample=None, handoff_check=None): """Control first; copy the accepted recognition crop after releasing lock. Occlusion False must come from validated quality evidence, not from a classifier label or assumption. None keeps semantics unusable. """ pending = None with self.control_lock(camera): # Validate the original ticket epoch atomically with controller # admission; the crop copy below still remains outside this lock. if handoff_check is not None: try: if handoff_check() is not True: return False except Exception: return False if (st is not self.state_provider(camera) or camera not in self.crops.cameras or not self.settings.enabled or not check_stamp(stamp, camera=camera, seq=getattr(stamp,'source_seq',None), owner=acquired_owner, expected_owner=self.owner(st), binding=st.get('inspection_source_binding'), now=self.clock(), age=.65)): # A foreign/late callback cannot revoke or STOP a new owner. return False ctx = self.contexts.get(camera) session = st.get('inspection_session') rec, rec_stamp = None, None if ctx and isinstance(session,Session) and ctx.owner == self.owner(st) and ctx.inspection_id == session.inspection_id: crop_ctx = CropContext(camera,ctx.inspection_id,ctx.owner,source_key(stamp),ctx.classifier_sha) row = self.crops.take_stamped(crop_ctx, now=self.clock()) if row: rec_stamp, rec = row f = Frame(rec.source_seq,rec_stamp.decode_mono_ns/1e9,rec.bbox,rec.shape) self.gate.submit(ctx, Semantic(f,rec.classifier_sha,rec.scores,rec.sharpness, rec.clipped,rec.occluded), self.clock()) adapted = adapt_result(result,camera=camera,owner=acquired_owner,source_seq=stamp.source_seq, observed_at=stamp.decode_utc_ns/1e9,frame_shape=frame.shape, actual_model_sha=self.proposal.sha256,frame_stamp=stamp, recognition=rec,recognition_stamp=rec_stamp) self.controller(camera,frame,adapted,True,stamp.source_seq, visual_sample=visual_sample) session = st.get('inspection_session') if (not isinstance(session,Session) or session.phase != 'inspection' or st.get('inspection_authorized') is not True or session.owner != self.owner(st) or not session.live(self.clock())): self.crops.revoke(camera); self.gate.revoke(camera); self.contexts.pop(camera,None) return False key = source_key(stamp) ctx = Context(camera,session.inspection_id,self.owner(st), source_token(key), self.settings.proposal_sha,self.settings.classifier_sha) if self.contexts.get(camera) != ctx: self.gate.begin(ctx,proposal_contract=self.proposal,classifier_contract=self.classifier) self.contexts[camera] = ctx st['inspection_common_alarm_guard'] = lambda: self.common_ready(camera,st) record = session.recent.get(stamp.source_seq) if record != (stamp.decode_utc_ns/1e9,session.bbox,session.shape,self.owner(st)): self.gate.revoke(camera); self.crops.revoke(camera); self.contexts.pop(camera,None) return False evidence = Frame(stamp.source_seq,stamp.decode_mono_ns/1e9,session.bbox,session.shape) if not self.gate.observe(ctx,evidence,self.clock()): return False crop_ctx = CropContext(camera,session.inspection_id,self.owner(st),key,self.settings.classifier_sha) self.crops.bind(crop_ctx) pending = crop_ctx, session.bbox return self.crops.submit(pending[0],stamp,frame,pending[1],now=self.clock(),occluded=occluded)