"""Reconstruct logged stop boundaries through the installed gate and worker, offline.""" from contextlib import ExitStack import ast import hashlib import json import logging import math from pathlib import Path import socket import sys from types import ModuleType, SimpleNamespace import unittest from unittest.mock import patch import importlib.util WORK = Path(__file__).resolve().parent PP = Path(sys.argv[5]) SOURCE, PTZ, INPUT, PRIOR = map(Path,sys.argv[1:5]) ROOT = Path(sys.argv[8]) BASE = ROOT/'analysis_outputs/visual_probe_20261019' PKG='ptz_tracker_modular' TRACE=[] DETAIL=[] PINS = {PP: sys.argv[6], PTZ: sys.argv[7]} def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest() def load(name,path): spec=importlib.util.spec_from_file_location(name,path) module=importlib.util.module_from_spec(spec) sys.modules[name]=module spec.loader.exec_module(module) return module def deny(*args,**kwargs): raise AssertionError('No real network, CUDA, camera RPC, or model access in replay') def as_native(value): return math.nextafter(value/100,math.copysign(math.inf,value)) if value else 0. def xml_sent(fixture): return [tuple(transport.xml_axis(xml,axis) for axis in ('pan','tilt','zoom')) for xml in fixture.sent] def captured(): report=json.loads(INPUT.read_text(encoding='utf-8')) assert report['stable'] is True assert report['container']['started_at']=='2026-11-09T06:24:10.287783596Z' for camera, episodes in report['episodes'].items(): for episode in episodes: assert episode['short_count']==len(episode['short_examples']) for sample in episode['short_examples']: yield camera,episode,sample def sec(value): return float(value.removesuffix('s')) class StopBoundary(unittest.TestCase): def fixture(self, cam, kind, native, pulse): fixture=transport.UsefulZoomTransportTests() fixture.setUp() self.addCleanup(fixture.doCleanups) fixture.cam=cam fixture.stack.enter_context(patch.dict(state.ptz_states,{cam:fixture.st})) # Seed each authorized pulse independently. The log gives accounting # duration/minimum and speed, but lacks the original hard-stop deadline. command=as_native(native) allowed=pp._gate_zoom_in_pulse(fixture.st,fixture.wall,command,True, pulse_kind=kind,pulse_floor=command,pulse_timing=(pulse,.4)) self.assertGreater(allowed,0) fixture._enqueue(allowed) fixture._flush() self.assertEqual(xml_sent(fixture)[-1][2],native) self.assertTrue(fixture.st['zoom_step_pending']) return fixture def test_all_observed_short_deliveries_replay_at_worker(self): for cam,e,row in captured(): with self.subTest(camera=cam,request=row['request']): internal={'19':8,'21':10}[cam] pulse=round(sec(row['minimum'])/.7,3) f=self.fixture(internal,row['kind'],int(row['native']),pulse) f._advance(sec(row['duration'])) pan,tilt,zoom=row['requested'] self.assertEqual(zoom,0) self.assertNotEqual((pan,tilt),(0,0)) with self.assertLogs('PTZTracker.PTZ',level='INFO') as logs: # These are the recorded native values already past quantization. seq=int(row['seq']) f.st['ptz_move_seq']=seq queued=ptz_io.MoveTuple(ptz_io.PTZCmd.MOVE,internal,pan,tilt,0, source='track',generation=f.st['ptz_generation'],preset_floor_checked=True, seq=seq,safety_stop=True) state.ptz_cmd_q.put_nowait(queued) self.assertEqual((queued.pan_i,queued.tilt_i,queued.zoom_i),tuple(row['requested'])) f._flush() last=xml_sent(f)[-1] self.assertEqual(last,tuple(row['effective'])) self.assertEqual(f.st['zoom_step_last_delivery_result'],'short') self.assertEqual(f.st['zoom_in_pulse_count'],0) self.assertAlmostEqual(f.st['zoom_step_last_delivered_sec'],sec(row['duration'])) record=next(x for x in logs.output if 'result=short' in x) self.assertIn('stop_effective=(0,0,0)',record) TRACE.append(dict(camera=cam,episode=e['started_at'],complete=e['complete'], source_request=row['request'],kind=row['kind'],native=int(row['native']), logged_s=sec(row['duration']),minimum_s=sec(row['minimum']),requested=row['requested'], replay_effective=last,replay_result=f.st['zoom_step_last_delivery_result'], controller_trigger_recovered=False)) def test_positive_revalidation_keeps_original_owned_pulse_deadline(self): for cam,native in ((8,10),(10,11)): with self.subTest(cam=cam,native=native): f=self.fixture(cam,'normal',native,.34) hard_deadline=f.st['zoom_step_stop_started_mono']+f.st['zoom_step_stop_timer'].delay origin=f.st['zoom_step_put_started_mono'] deadline=f.st['zoom_step_until'] request=f.st['zoom_step_physical_request_id'] for _ in range(3): f._advance(.045) command=pp._gate_zoom_in_pulse(f.st,f.wall,.12,True,pulse_floor=.12,pulse_timing=(.34,.4)) self.assertEqual(ptz_io._zoom_speed_to_int(command),native) f._enqueue(command) f._flush() self.assertEqual(f.st['zoom_step_put_started_mono'],origin) self.assertEqual(f.st['zoom_step_until'],deadline) self.assertEqual(f.st['zoom_step_physical_request_id'],request) self.assertAlmostEqual(f.st['zoom_step_stop_started_mono']+ f.st['zoom_step_stop_timer'].delay,hard_deadline,places=6) self.assertLessEqual(hard_deadline-origin,.400001) f._advance(hard_deadline-f.mono) f.st['zoom_step_stop_timer'].fire() self.assertEqual(xml_sent(f)[-1],(0,0,0)) def test_identical_zero_when_only_vote_fails_or_safety_fails(self): tree=ast.parse((PP).read_bytes()) main=next(n for n in tree.body if getattr(n,'name','')=='postprocess_control') expr=next(n.value for n in ast.walk(main) if isinstance(n,ast.Assign) and any(isinstance(target,ast.Name) and target.id=='can_zoom_in' for target in n.targets) and 'zoom_angular_safe' in ast.unparse(n.value)) compiled=compile(ast.Expression(expr),'','eval') for label,changes in ( ('synthetic_stable_history_only',{'stable_ok':False}), ('synthetic_edge_veto',{'near_edge':True}), ('synthetic_angular_veto',{'zoom_angular_safe':False}), ('synthetic_quality_veto',{'zoom_safe':False}), ): with self.subTest(label=label): f=self.fixture(8,'normal',10,.34) f._advance(.110) env=dict(zoom_safe=True,zoom_angular_safe=True,stable_ok=True, zoom_rearm_ready=True,near_edge=False,st={},bounded_identification_request=False, fast_drift=.02,config=config,now=f.wall) can=eval(compiled,{},{**env,**changes}) self.assertFalse(can) actual=pp._gate_zoom_in_pulse(f.st,f.wall,.1,can, pulse_floor=.1,pulse_timing=(.34,.4)) self.assertEqual(actual,0.) f._enqueue(actual) f._flush() self.assertEqual(xml_sent(f)[-1],(0,0,0)) self.assertEqual(f.st['zoom_step_last_delivery_result'],'short') DETAIL.append(dict(label=label,zoom=actual,axes=xml_sent(f)[-1],status='short')) def main(): import torch import numpy global config,state,ptz_io,pp,transport assert all(sha(path)==expected for path,expected in PINS.items()) before=load('prior_replay_fixture',PRIOR) from test_frame_decision import build_cases from test_native_floor import build_floor_cases logging.getLogger('PTZTracker').setLevel(logging.ERROR) with ExitStack() as stack: for owner,name in ((socket.socket,'connect'),(socket.socket,'connect_ex'), (socket,'create_connection'),(torch,'load'),(torch.cuda,'_lazy_init')): stack.enter_context(patch.object(owner,name,deny)) stack.enter_context(patch.object(torch.cuda,'is_available',return_value=False)) package=ModuleType(PKG) package.__path__=[str(BASE/'geometry_candidate/ptz_tracker_modular'),str(ROOT)] sys.modules[PKG]=package model=ModuleType(PKG+'.model') model.model_shared,model.yolo_forward=object(),deny sys.modules[model.__name__]=model load(PKG+'.visual_control_probe', SOURCE/'visual_control_probe.py') control=load(PKG+'.visual_control',SOURCE/'visual_control.py') ptz_io=load(PKG+'.ptz_io',PTZ) pp=load(PKG+'.postprocess',PP) from ptz_tracker_modular import config,state,visual_tracker values=json.loads((BASE/'zoom_continuation_candidate/runtime_policy_snapshot.json').read_text())['values'] for key,value in values.items(): stack.enter_context(patch.object(config,key,value,create=True)) transport=load('test_zoom_useful_transport',ROOT/'tests/test_zoom_useful_transport.py') before.np,before.torch,before.config,before.state=numpy,torch,config,state before.ptz_io,before.pp,before.tracker,before.control,before.transport=ptz_io,pp,visual_tracker,control,transport suite=unittest.defaultTestLoader.loadTestsFromTestCase(StopBoundary) for name in ('test_geometry_hold_short_delivery_has_exact_synthetic_stop_caller', 'test_started_controller_pulse_keeps_hard_stop_after_owner_change', 'test_joint_steering_update_cannot_extend_original_started_pulse', 'test_visual_age_over_250ms_cannot_move_or_advance_control', 'test_detector_age_over_650ms_cannot_refresh_evidence', 'test_old_owner_sample_cannot_refresh_or_stop_new_owner', 'test_reacquire_does_not_clear_no_effect_limit'): suite.addTest(before.Replay(name)) candidate = "zoom_decision" in __import__("inspect").signature(ptz_io.move_ptz).parameters if candidate: suite.addTests(build_cases(before.Replay, pp, ptz_io)) suite.addTests(build_floor_cases(StopBoundary, before.Replay, pp, ptz_io, config, Path(sys.argv[10]), sys.argv[11] == "fixed", threshold_diagnostics="--thresholds" in sys.argv[12:])) result=unittest.TextTestRunner(verbosity=2).run(suite) result_file=Path(sys.argv[9]) result_file.write_text(json.dumps(dict(passed=result.wasSuccessful(),tests=result.testsRun, observed_expected=len(list(captured())),observed_matched=len(TRACE),telemetry_sha256=sha(INPUT), tested_source_sha256={path.name:pin for path,pin in PINS.items()},observed_rows=TRACE,synthetic=DETAIL, shared_controller_rows={key: rows for key, rows in before.TRACE.items() if not key.startswith(("test_frame_decision", "test_center_history", "test_dropped_move"))}, exact_observed_controller_replay=False,real_ptz_or_nn=False, conclusion='The same short-delivery output is compatible with a synthetic admission-only condition and mandatory safety stops. The observed controller trigger and exact deadlines are missing.'),indent=2)+'\n',encoding='utf-8') return not result.wasSuccessful() if __name__=='__main__': raise SystemExit(main())