diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d6359a6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +integration/ptz_zoom_zero_decision/server.patch text eol=lf -whitespace diff --git a/integration/ptz_zoom_zero_decision/README.md b/integration/ptz_zoom_zero_decision/README.md new file mode 100644 index 0000000..abbcf79 --- /dev/null +++ b/integration/ptz_zoom_zero_decision/README.md @@ -0,0 +1,17 @@ +# Диагностика решения об остановке зума + +При активном или ожидающем импульсе TRACK записывает `ZOOM DECISION`, когда итоговая команда кадра прекращает приближение и MOVE принят очередью. Строка содержит кадр, идентификатор импульса, причину, действующие ограничения, источник и native zoom. Пара `cam`, `gen`, `seq` сопоставляется с `cam`, `stop_gen`, `stop_seq` из `ZOOM DELIVERY` PR №3. Для однозначной атрибуции импульса сверяется и `request`. Порядок строк зависит от работы потока доставки. + +`reason` показывает ветку решения. `blockers` показывает ограничения того же кадра, включая раздельные признаки недостаточной истории центровки, отклонённого текущего кадра и недостаточной истории трека. `size_controller` объединяет случаи без более конкретной причины. Прямые защитные остановки продолжают использовать прежний путь. Подтверждение доставки берётся из `ZOOM DELIVERY`. + +## Офлайн-проверка + +Патч рассчитан на две точные серверные копии из `pins.json`. Репозиторий хранит патч отдельно от своих исходных файлов, которые отличаются от серверных. Прямой и обратный патчи проверены побайтно. При проверке на Windows задайте `git -c core.autocrlf=false apply`. + +```text +python -B replay.py SERVER_SNAPSHOT PTZ_IO TELEMETRY_JSON CONTROLLER_FIXTURE POSTPROCESS PP_SHA IO_SHA PROJECT_ROOT RESULT_JSON +``` + +`SERVER_SNAPSHOT` содержит `visual_control.py` и `visual_control_probe.py`. `CONTROLLER_FIXTURE` — локальный `cc1_cc2_control_replay_20261026/test_control_replay.py`. `PROJECT_ROOT` предоставляет существующие фикстуры из `tests` и `analysis_outputs/visual_probe_20261019`. Историческая телеметрия и серверные снимки остаются в локальном рабочем контуре. + +В `verification.json` зафиксированы 10 базовых и 13 кандидатных тестов. Совпали решения, команды и остановки на 23 синтетических кадрах. Воспроизведены 19 исторических доставок PTZ19 и PTZ21 от границы очереди. Исторические журналы не содержат причин решения на исходных кадрах. Защитный STOP, модель и правила тревоги сохранены. Патч проверен локально. diff --git a/integration/ptz_zoom_zero_decision/pins.json b/integration/ptz_zoom_zero_decision/pins.json new file mode 100644 index 0000000..62d51ba --- /dev/null +++ b/integration/ptz_zoom_zero_decision/pins.json @@ -0,0 +1,13 @@ +{ + "requires": "PTZ stop attribution PR #3", + "files": { + "ptz_tracker_modular/postprocess.py": { + "before": "5326c9d3093b7c863310b9c0a7a85010a1a83ff014631a054ac9a16cc31c8fc5", + "after": "8eb5f6beb79141ef1f1ce9dbad3577006821202557a87c7195e770bbba7b4ba3" + }, + "ptz_tracker_modular/ptz_io.py": { + "before": "3c3f10eaebc2a1c0f67725d6a487bad9e1537b1bb277705fc503c2526c779600", + "after": "13d31539193b1a773a5d1db2187cc2a0c8db67d0aacaad89082face64df07499" + } + } +} diff --git a/integration/ptz_zoom_zero_decision/replay.py b/integration/ptz_zoom_zero_decision/replay.py new file mode 100644 index 0000000..98c4b6a --- /dev/null +++ b/integration/ptz_zoom_zero_decision/replay.py @@ -0,0 +1,219 @@ +"""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 + 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)) + 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()) diff --git a/integration/ptz_zoom_zero_decision/server.patch b/integration/ptz_zoom_zero_decision/server.patch new file mode 100644 index 0000000..d267d9e --- /dev/null +++ b/integration/ptz_zoom_zero_decision/server.patch @@ -0,0 +1,406 @@ +--- a/ptz_tracker_modular/postprocess.py ++++ b/ptz_tracker_modular/postprocess.py +@@ -4357,6 +4357,7 @@ + max_image_rate: float, + max_outward_rate: float, + err_growth_tol: float, ++ settled_sample: list[bool] | None = None, + ) -> bool: + """Return True only after a tight, non-diverging image-space hold. + +@@ -4381,6 +4382,8 @@ + and outward_rate <= max(0.0, float(max_outward_rate)) + and non_diverging + ) ++ if settled_sample is not None: ++ settled_sample.append(bool(settled)) + previous_frames = int(st.get(frames_key, 0) or 0) + if settled: + frames = previous_frames + 1 +@@ -4411,6 +4414,7 @@ + vx: float, + vy: float, + center_gate: float | None = None, ++ settled_sample: list[bool] | None = None, + ) -> bool: + return _update_center_lock_state( + st, +@@ -4436,6 +4440,7 @@ + max_image_rate=float(getattr(config, "ZOOM_CENTER_LOCK_MAX_IMAGE_RATE", 0.28)), + max_outward_rate=float(getattr(config, "ZOOM_CENTER_LOCK_MAX_OUTWARD_RATE", 0.08)), + err_growth_tol=float(getattr(config, "ZOOM_CENTER_LOCK_ERR_GROWTH_TOL", 0.018)), ++ settled_sample=settled_sample, + ) + + +@@ -4553,6 +4558,12 @@ + st["acquire_zoom_prev_err"] = None + + ++def _reject_zoom_step(reason: str, trace: list[str] | None) -> float: ++ if trace is not None: ++ trace.append(reason) ++ return 0.0 ++ ++ + def _gate_zoom_in_pulse( + st: dict, + now: float, +@@ -4565,6 +4576,7 @@ + pulse_floor: float = 0.0, + pulse_timing: Tuple[float, float] | None = None, + optics_observed_now: float | None = None, ++ stop_trace: list[str] | None = None, + ) -> float: + """Break continuous zoom-in into short feedback-controlled steps.""" + pulse_until = float(st.get("zoom_step_until", 0.0) or 0.0) +@@ -4581,15 +4593,15 @@ + return float(zoom_cmd if can_zoom_in else 0.0) + if bool(st.get("zoom_no_effect_blocked", False)): + st["zoom_followup_reason"] = "no_effect_limit" +- return 0.0 ++ return _reject_zoom_step("no_effect_limit", stop_trace) + if not can_zoom_in: + if pulse_until > 0.0 or bool(st.get("zoom_step_pending", False)): + _finish_zoom_step(st, now, stable_key=stable_key) +- return 0.0 ++ return _reject_zoom_step("permission", stop_trace) + + if bool(st.get("zoom_step_pending", False)): + if bool(st.get("zoom_step_cancel_requested", False)): +- return 0.0 ++ return _reject_zoom_step("cancel_requested", stop_trace) + if pulse_timing is not None: + try: + authorized = tuple(map(float, pulse_timing)) +@@ -4602,7 +4614,7 @@ + timing_ok = False + if not timing_ok: + _finish_zoom_step(st, now, stable_key=stable_key) +- return 0.0 ++ return _reject_zoom_step("pending_timing", stop_trace) + useful_cmd = float(st.get("zoom_step_pending_useful_cmd", 0.0) or 0.0) + if useful_cmd > 0.0: + # A useful-pulse caller revalidates its entire framing envelope on +@@ -4614,7 +4626,7 @@ + or float(getattr(config, "ZOOM_STEP_MAX_IN_CMD", 0.12)) < useful_cmd + ): + _finish_zoom_step(st, now, stable_key=stable_key) +- return 0.0 ++ return _reject_zoom_step("pending_native_floor", stop_trace) + zoom_cmd = useful_cmd + physical_started = float(st.get("zoom_step_physical_started_at", 0.0) or 0.0) + if physical_started > 0.0: +@@ -4624,7 +4636,7 @@ + float(getattr(config, "ZOOM_STEP_MAX_IN_CMD", 0.18)), + ) + _finish_zoom_step(st, now, stable_key=stable_key) +- return 0.0 ++ return _reject_zoom_step("pulse_window_ended", stop_trace) + expires_at = float(st.get("zoom_step_pending_expires_at", 0.0) or 0.0) + if expires_at > 0.0 and float(now) >= expires_at: + _clear_pending_zoom_request( +@@ -4633,7 +4645,7 @@ + reason="delivery_timeout", + retry_cooldown=True, + ) +- return 0.0 ++ return _reject_zoom_step("delivery_timeout", stop_trace) + # Keep authorizing the same request until the worker either delivers it + # or a newer safety command cancels it. No counters are consumed here. + return min( +@@ -8614,6 +8626,7 @@ + ) + if approach_margin is not None: + lock_gate = max(lock_gate, .12) ++ center_sample = [] + center_locked_for_zoom = _update_zoom_center_lock( + st, + now, +@@ -8625,6 +8638,7 @@ + vx=float(zoom_vx), + vy=float(zoom_vy), + center_gate=lock_gate, ++ settled_sample=center_sample, + ) + + use_zoom_v3 = bool(getattr(config, "ZOOM_V3_ENABLE", True)) +@@ -8867,6 +8881,9 @@ + and now >= float(st.get("focus_settle_until", 0.0) or 0.0) + ) + ++ center_settled = center_sample[0] if center_sample else None ++ track_stable = int(st.get("stable_frames", 0) or 0) >= min_stable ++ + # A safe probe is an explicit bounded identification request, not merely + # permission for the ordinary size controller. Without this request a + # tiny distant aircraft could pass every probe gate yet never zoom because +@@ -8929,6 +8946,7 @@ + if size_err_abs <= float(getattr(config, "ZOOM_V3_BRAKE_ERR", 0.030)): + zoom_ff = 0.0 + zoom_cmd = clipf(zoom_pi + zoom_ff, _Z_SPEED_LIMIT_OUT, _Z_SPEED_LIMIT_IN) ++ zoom_zero_reason = "size_controller" + if not out_edge_crit: + brake_err = float(getattr(config, "ZOOM_V3_BRAKE_ERR", 0.030)) + brake_k = clipf(abs(err_size) / max(1e-6, brake_err), 0.0, 1.0) +@@ -8936,6 +8954,7 @@ + + if st.get("zoom_lock", False) and not bounded_identification_request: + zoom_cmd = min(zoom_cmd, -0.12) if out_edge_effective else 0.0 ++ zoom_zero_reason = "zoom_lock" + st["zoom_int"] *= 0.90 + else: + if st["zoom_state"] > 0: +@@ -8947,6 +8966,7 @@ + if normal_size_hold and not out_edge_effective: + st["zoom_state"] = 0 + zoom_cmd = 0.0 ++ zoom_zero_reason = "size_hold" + st["zoom_int"] *= 0.70 + st["zoom_size_rate"] = float(st.get("zoom_size_rate", 0.0) or 0.0) * 0.6 + if cruise_active and (not approaching) and (not out_edge_effective) and (not near_react_edge): +@@ -8973,6 +8993,7 @@ + last_flip = float(st.get("zoom_v3_last_sign_flip_t", 0.0) or 0.0) + if (now - last_flip) < sign_cd: + zoom_cmd = 0.0 ++ zoom_zero_reason = "sign_cooldown" + else: + st["zoom_v3_last_sign_flip_t"] = now + +@@ -8983,6 +9004,8 @@ + elif z_state < 0: + zoom_cmd = -_Z_MIN_CMD + else: ++ if zoom_cmd != 0.0: ++ zoom_zero_reason = "deadband" + zoom_cmd = 0.0 + + cmd_mag_est = max( +@@ -8993,10 +9016,14 @@ + gate_v = float(getattr(config, "Z_VELOCITY_GATE", 0.45)) + over_v = max(0.0, cmd_mag_est - gate_v) + zoom_cmd *= clipf(1.0 - over_v / max(1e-6, gate_v * 1.2), 0.0, 1.0) ++ if zoom_cmd == 0.0: ++ zoom_zero_reason = "steering_speed" + err_gate = float(getattr(config, "Z_ERR_GATE", 0.18)) + if (max(abs(sm_dx), abs(sm_dy)) > err_gate) and (zoom_cmd > 0.0): + over_e = max(0.0, max(abs(sm_dx), abs(sm_dy)) - err_gate) + zoom_cmd *= clipf(1.0 - over_e / max(1e-6, err_gate * 1.5), 0.0, 1.0) ++ if zoom_cmd == 0.0: ++ zoom_zero_reason = "center_error" + # Center-first policy: when target is noticeably off-center, prioritize pan/tilt over zoom-in. + center_prio_err = float(getattr(config, "ZOOM_CENTER_PRIORITY_ERR", 0.11)) + center_prio_margin = float(getattr(config, "ZOOM_CENTER_PRIORITY_MARGIN", 0.14)) +@@ -9007,19 +9034,26 @@ + zoom_cmd *= clipf(min_margin / max(1e-6, center_prio_margin), 0.0, 1.0) + if near_edge and zoom_cmd > 0.0: + zoom_cmd = 0.0 ++ zoom_zero_reason = "near_edge" + + if zoom_cmd > 0.0: + vel_ref = float(getattr(config, "ZOOM_IN_SCALE_VEL_REF", 0.22)) + vel_k = clipf(1.0 - vel / max(1e-6, vel_ref), float(getattr(config, "ZOOM_IN_SCALE_MIN", 0.20)), 1.0) + zoom_cmd *= min(zoom_safe_scale, vel_k) +- ++ if zoom_cmd == 0.0: ++ zoom_zero_reason = "framing_scale" ++ ++ before_edge = zoom_cmd + zoom_cmd = _apply_predictive_edge_zoom_out( + zoom_cmd, + risk_margin=edge_risk_margin, + react_margin=react_margin, + moving_out=moving_out, + ) ++ if before_edge > 0.0 and zoom_cmd <= 0.0: ++ zoom_zero_reason = "predictive_edge" + recent_zoom_steering = _recent_zoom_steering_active(st, now, zoom_cmd) ++ before_recenter = zoom_cmd + zoom_cmd = _apply_zoom_recenter_guard( + zoom_cmd, + center_err=float(center_err), +@@ -9027,6 +9061,8 @@ + recent_zoom=bool(recent_zoom_steering), + approach_margin=approach_margin, + ) ++ if before_recenter > 0.0 and zoom_cmd <= 0.0: ++ zoom_zero_reason = "recenter" + zoom_out_emergency = bool( + out_edge_effective + or float(min_margin) < float(getattr(config, "Z_SAFETY_EDGE", 0.05)) +@@ -9114,6 +9150,8 @@ + request_id_before_gate = int(st.get("zoom_step_request_id", 0) or 0) + with _zoom_command_lock(cam_idx): + zoom_gate_now = time.time() ++ decision_request = int(st.get("zoom_step_physical_request_id", 0) or ++ st.get("zoom_step_pending_id", 0) or 0) + pulse_family = str(st.get("zoom_step_pending_kind") or pulse_kind) + pulse_cap = float(getattr(config, "ZOOM_STEP_MAX_IN_CMD", 0.12)) + if "probe" in pulse_family: +@@ -9142,6 +9180,7 @@ + proposed_zoom_cmd = max(zoom_cmd, min(pre_ramp_zoom_cmd, pulse_cap, .12)) + if _zoom_native_response_available(st, _zoom_speed_to_int(proposed_zoom_cmd), hfov_deg, shared_wide_hfov): + zoom_cmd = proposed_zoom_cmd ++ before_shape = zoom_cmd + zoom_cmd, useful_reason = _shape_useful_zoom_pulse( + zoom_cmd, + can_zoom_in=can_zoom_in, +@@ -9154,6 +9193,8 @@ + approach_margin=approach_margin, + ) + st["zoom_useful_pulse_reason"] = useful_reason ++ if before_shape > 0.0 and zoom_cmd <= 0.0: ++ zoom_zero_reason = useful_reason + response_timing = _select_zoom_response_timing( + st, useful=useful_reason == "useful", + hfov_deg=float(hfov_deg), wide_hfov_deg=float(shared_wide_hfov), +@@ -9166,6 +9207,8 @@ + if useful_reason == "useful" and response_timing == (0.0, 0.0): + zoom_cmd = 0.0 + st["zoom_useful_pulse_reason"] = "wait_response_framing" ++ zoom_zero_reason = "response_framing" ++ gate_stop = [] if decision_request else None + zoom_cmd = _gate_zoom_in_pulse( + st, + # Keep new-request expiry tied to the frame that authorized +@@ -9180,7 +9223,10 @@ + pulse_floor=(zoom_cmd if useful_reason == "useful" else 0.0), + pulse_timing=response_timing, + optics_observed_now=zoom_gate_now, ++ stop_trace=gate_stop, + ) ++ if gate_stop: ++ zoom_zero_reason = gate_stop[-1] + if ( + probe_start_candidate + and zoom_cmd > 0.0 +@@ -9433,6 +9479,7 @@ + or visual_control_coast != was_visual_control_coast + ) + if visual_control_coast: ++ before_coast = zoom_cmd + adj_pan, adj_tilt, zoom_cmd = _bound_visual_coast_commands( + st, + adj_pan, +@@ -9463,7 +9510,11 @@ + # Appearance continuity is sufficient for bounded steering only. + # It never authorizes an alarm without a current detector match. + alarm_eligible = False ++ if before_coast > 0.0 and zoom_cmd <= 0.0: ++ zoom_zero_reason = "visual_coast" + elif visual_control_stale: ++ if zoom_cmd > 0.0: ++ zoom_zero_reason = "visual_stale" + # Stale detector validation makes image-space steering unsafe, but a + # previously calculated edge-recovery zoom-out only widens the field + # of view. Preserve that bounded negative command while cancelling +@@ -9532,6 +9583,7 @@ + # immediately by the forced command below. + if float(zoom_cmd) > 0.0: + zoom_cmd = 0.0 ++ zoom_zero_reason = "final_brake" + st["zoom_prev_cmd"] = 0.0 + st["stable_frames"] = 0 + +@@ -9673,7 +9725,33 @@ + _arm_zoom_revalidation_locked(st, time.time(), 'visual_control_expired') + stop_ptz(cam_idx, source='stop', generation=int(st.get('ptz_generation', 0) or 0)) + return +- _dispatch_owned_zoom_tracking(cam_idx, _PAN_SIGN * adj_pan, _TILT_SIGN * adj_tilt, zoom_cmd, force=force_track_ptz) ++ zoom_decision = None ++ if decision_request and zoom_cmd <= 0.0: ++ blockers = tuple(name for name, blocked in ( ++ ("quality", not zoom_quality_ok), ++ ("framing", not zoom_safe), ++ ("followup", not followup_ready), ++ ("angle", not zoom_angular_safe), ++ ("center_sample_unknown", center_settled is None), ++ ("center_sample", center_settled is False), ++ ("center_history", center_settled is True and not center_locked_for_zoom), ++ ("track_history", not track_stable), ++ ("rearm", not zoom_rearm_ready), ++ ("edge", near_edge or edge_recovery_active), ++ ("lock", st.get("zoom_lock", False) and not bounded_identification_request), ++ ("drift", fast_drift > float(getattr(config, "ZOOM_IN_FAST_DRIFT_MAX", 0.45))), ++ ("focus", now < float(st.get("focus_settle_until", 0.0) or 0.0)), ++ ("coast", visual_control_coast), ++ ("stale", visual_control_stale), ++ ("brake", final_guard_active), ++ ) if blocked) ++ zoom_decision = (source_seq, decision_request, zoom_zero_reason, "+".join(blockers) or "-") ++ dispatch_kwargs = {"force": force_track_ptz} ++ if zoom_decision is not None: ++ dispatch_kwargs["zoom_decision"] = zoom_decision ++ _dispatch_owned_zoom_tracking( ++ cam_idx, _PAN_SIGN * adj_pan, _TILT_SIGN * adj_tilt, zoom_cmd, **dispatch_kwargs ++ ) + if visual_control.enabled(): + dispatch_at = time.monotonic() + samples = st.setdefault('control_dispatch_samples', []) +--- a/ptz_tracker_modular/ptz_io.py ++++ b/ptz_tracker_modular/ptz_io.py +@@ -1903,10 +1903,11 @@ + source: Optional[str] = None, + generation: Optional[int] = None, + preset_floor_checked: bool = False, ++ zoom_decision: Optional[Tuple[Optional[int], int, str, str]] = None, + ) -> None: + """Serialize frame commands with the independent lens hard-stop timer.""" + with _zoom_command_lock(cam_idx): +- _move_ptz_locked( ++ queued = _move_ptz_locked( + cam_idx, + pan, + tilt, +@@ -1915,6 +1916,15 @@ + source=source, + generation=generation, + preset_floor_checked=preset_floor_checked, ++ zoom_decision=zoom_decision, ++ ) ++ if zoom_decision is not None and queued is not None: ++ cmd_source, generation, seq, native_zoom = queued ++ frame, request, reason, blockers = zoom_decision ++ logger.info( ++ "[ZOOM DECISION] cam=%s frame=%s request=%s source=%s gen=%s seq=%s " ++ "queued_zoom=%s reason=%s blockers=%s", ++ cam_idx, frame, request, cmd_source, generation, seq, native_zoom, reason, blockers, + ) + + +@@ -1929,7 +1939,8 @@ + generation: Optional[int] = None, + preset_floor_checked: bool = False, + hard_stop: bool = False, +-) -> None: ++ zoom_decision: Optional[Tuple[Optional[int], int, str, str]] = None, ++) -> Optional[Tuple[str, int, int, int]]: + """ + Отправка relative/continuous PTZ-команды. + +@@ -2105,6 +2116,9 @@ + # The MOVE is already queued. Report watchdog setup separately; + # pretending that the MOVE was dropped would corrupt dedupe state. + logger.error("[ZOOM WATCHDOG] setup failed cam=%s: %s", cam_idx, exc) ++ if zoom_decision is not None: ++ return cmd_source, cmd_generation, move_seq, zoom_i ++ return None + + + def stop_ptz(cam_idx: int, *, source: str = "stop", generation: Optional[int] = None) -> None: +@@ -2253,6 +2267,7 @@ + force: bool = False, + source: Optional[str] = None, + generation: Optional[int] = None, ++ zoom_decision: Optional[Tuple[Optional[int], int, str, str]] = None, + ) -> None: + """ + Обёртка над move_ptz. +@@ -2295,6 +2310,7 @@ + source=source, + generation=generation, + preset_floor_checked=True, ++ zoom_decision=zoom_decision, + ) + + diff --git a/integration/ptz_zoom_zero_decision/test_frame_decision.py b/integration/ptz_zoom_zero_decision/test_frame_decision.py new file mode 100644 index 0000000..2473f7d --- /dev/null +++ b/integration/ptz_zoom_zero_decision/test_frame_decision.py @@ -0,0 +1,71 @@ +"""Offline frame-to-queue/ACK tests built on the established fake PTZ worker.""" +from unittest.mock import patch + + +def build_cases(replay_base, controller, transport): + class FrameDecision(replay_base): + def test_frame_decision_joins_protective_stop_ack(self): + self.start_pulse() + request = self.st["zoom_step_physical_request_id"] + with patch.object(controller, "_shape_useful_zoom_pulse", + return_value=(0.0, "stale_optics")) as shape: + with self.assertLogs("PTZTracker.PTZ", level="INFO") as logs: + row = self.tick(.035) + self.assertGreater(shape.call_args.args[0], 0.0) + decision = self.log_fields(logs, "[ZOOM DECISION]") + delivery = self.log_fields(logs, "[ZOOM DELIVERY]") + self.assertEqual(decision["frame"], str(row["seq"])) + self.assertEqual(decision["request"], str(request)) + self.assertEqual(decision["reason"], "stale_optics") + self.assertEqual(decision["queued_zoom"], "0") + self.assertEqual(decision["source"], "track") + self.assertEqual(decision["gen"], delivery["stop_gen"]) + self.assertEqual(decision["seq"], delivery["stop_seq"]) + self.assertEqual(delivery["request"], str(request)) + self.assertEqual(delivery["stop_effective"], "(0,0,0)") + self.assertEqual(row["sent"][-1], (0, 0, 0)) + + def test_center_history_is_distinct_from_current_sample(self): + for settled, expected in ((True, "center_history"), (False, "center_sample")): + with self.subTest(settled=settled): + self.start_pulse() + def unsettled(*args, settled_sample, **kwargs): + settled_sample.append(settled) + return False + with patch.object(controller, "_update_zoom_center_lock", side_effect=unsettled): + with self.assertLogs("PTZTracker.PTZ", level="INFO") as logs: + row = self.tick(.035) + decision = self.log_fields(logs, "[ZOOM DECISION]") + blockers = decision["blockers"].split("+") + self.assertEqual(decision["frame"], str(row["seq"])) + self.assertIn(expected, blockers) + self.assertNotIn("center_sample" if settled else "center_history", blockers) + self.assertEqual(row["sent"][-1], (0, 0, 0)) + + def test_dropped_move_does_not_emit_decision(self): + with patch.object(transport.state.ptz_cmd_q, "put_nowait", side_effect=RuntimeError("queue full")): + with self.assertLogs("PTZTracker.PTZ", level="INFO") as logs: + transport.move_ptz_bounded(self.cam, .1, .05, 0., force=True, + zoom_decision=(104, 7, "permission", "center_history")) + self.assertTrue(any("[PTZ QUEUE] drop" in entry for entry in logs.output)) + self.assertFalse(any("[ZOOM DECISION]" in entry for entry in logs.output)) + + def start_pulse(self): + for _ in range(24): + row = self.tick(.1) + if any(axes[2] > 0 for axes in row["sent"]): + self.assertGreater(self.st["zoom_step_physical_request_id"], 0) + return + self.fail("No authorized zoom pulse in the offline fixture") + + def log_fields(self, logs, tag): + entries = [entry for entry in logs.output if tag in entry] + self.assertEqual(len(entries), 1, logs.output) + return dict(part.split("=", 1) for part in entries[0].split(tag, 1)[1].split() + if "=" in part) + + return [FrameDecision(name) for name in ( + "test_frame_decision_joins_protective_stop_ack", + "test_center_history_is_distinct_from_current_sample", + "test_dropped_move_does_not_emit_decision", + )] diff --git a/integration/ptz_zoom_zero_decision/verification.json b/integration/ptz_zoom_zero_decision/verification.json new file mode 100644 index 0000000..911dc46 --- /dev/null +++ b/integration/ptz_zoom_zero_decision/verification.json @@ -0,0 +1,9 @@ +{ + "baseline_tests_passed": 10, + "candidate_tests_passed": 13, + "historical_worker_cases_matched": 19, + "shared_controller_frames_identical": 23, + "real_camera_or_model_access": false, + "patch_apply_and_reverse_byte_exact": true, + "historical_decision_reason_recovered": false +}