From 9cdf6463058538a3a3ef60ea170b5b6489c04aa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=AF=D1=80=D0=BE=D1=81=D0=BB=D0=B0=D0=B2=20=D0=9A=D0=B0?= =?UTF-8?q?=D1=80=D1=82=D0=B0=D1=88=D0=BE=D0=B2?= Date: Wed, 11 Nov 2026 15:28:07 +0700 Subject: [PATCH] Count pre-zoom block reasons on PR7 TRACK --- .gitattributes | 2 + .../ptz_pr7_zoom_block_reason/README.md | 7 ++ .../pr7_zoom_block_reason.patch | 71 ++++++++++++++ .../pr7_zoom_block_reason_pins.json | 4 + .../prepare_pr7_diagnostics.py | 98 +++++++++++++++++++ .../verify_pr7_diagnostics.py | 90 +++++++++++++++++ 6 files changed, 272 insertions(+) create mode 100644 integration/ptz_pr7_zoom_block_reason/README.md create mode 100644 integration/ptz_pr7_zoom_block_reason/pr7_zoom_block_reason.patch create mode 100644 integration/ptz_pr7_zoom_block_reason/pr7_zoom_block_reason_pins.json create mode 100644 integration/ptz_pr7_zoom_block_reason/prepare_pr7_diagnostics.py create mode 100644 integration/ptz_pr7_zoom_block_reason/verify_pr7_diagnostics.py diff --git a/.gitattributes b/.gitattributes index baa1e9d..941e197 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,5 @@ integration/ptz_zoom_zero_decision/server.patch text eol=lf -whitespace integration/ptz_native_floor_continuation/server.patch text eol=lf -whitespace integration/ptz_same_native_diagnostics/server.patch text eol=lf -whitespace integration/ptz_zoom_threshold_diagnostics/server.patch text eol=lf -whitespace +integration/ptz_pr7_zoom_block_reason/*.patch text eol=lf -whitespace +integration/ptz_pr7_zoom_block_reason/*.py text eol=lf diff --git a/integration/ptz_pr7_zoom_block_reason/README.md b/integration/ptz_pr7_zoom_block_reason/README.md new file mode 100644 index 0000000..5b7a48a --- /dev/null +++ b/integration/ptz_pr7_zoom_block_reason/README.md @@ -0,0 +1,7 @@ +# Причины блокировки зума на PR №7 + +Диагностический патч для закреплённой копии postprocess.py из PR №7. Защитные условия и команды остаются в действующих ветках контроллера. По умолчанию диагностика выключена. При включении ZOOM_BLOCK_DIAG_ENABLE по умолчанию учитываются внутренние камеры 8 и 10 (PTZ19 и PTZ21). + +На каждом тике TRACK, дошедшем до решения о движении, запись ZOOM BLOCK указывает zoom_block_reason, все одновременно действующие блокировки и накопленные счётчики. В before_first_positive_decision отслеживается стадия до первого решения контроллера подать положительную команду. Фактическую доставку и движение оптики по-прежнему определяют записи ZOOM DELIVERY и статус камеры. Новый TRACK или поколение команд начинает новый счётчик. + +Для проверки на точной копии исходника передайте путь к postprocess.py в verify_pr7_diagnostics.py. Проверка применяет и обращает патч во временном каталоге, сравнивает AST вне диагностического блока и проверяет фазу, сброс счётчиков и работу выключенного режима. На Windows сохраняется исходный LF. diff --git a/integration/ptz_pr7_zoom_block_reason/pr7_zoom_block_reason.patch b/integration/ptz_pr7_zoom_block_reason/pr7_zoom_block_reason.patch new file mode 100644 index 0000000..931dd9c --- /dev/null +++ b/integration/ptz_pr7_zoom_block_reason/pr7_zoom_block_reason.patch @@ -0,0 +1,71 @@ +--- a/postprocess.py ++++ b/postprocess.py +@@ -6640,6 +6640,28 @@ + detector_conf=max(alarm_conf, identity_conf), + alarm_eligible=alarm_eligible, cam_idx=cam_idx) + alarms.ingest_detection(cam_idx, alarm_eligible) ++ ++ ++def _log_zoom_block_tick(st, cam, source_seq, zoom, reason, blockers): ++ """Count TRACK decisions without taking part in actuator authorization.""" ++ owner = (st.get("ptz_generation"), st.get("track_started_at")) ++ record = st.get("zoom_block_diag") ++ if record is None or record["owner"] != owner: ++ record = {"owner": owner, "first_positive": False, "total": {}, "before_first": {}} ++ st["zoom_block_diag"] = record ++ if zoom > 0.0: ++ record["first_positive"] = True ++ return ++ before_first = not record["first_positive"] ++ for key in ("total", "before_first") if before_first else ("total",): ++ counts = record[key] ++ counts[reason] = counts.get(reason, 0) + 1 ++ logger.info( ++ "[ZOOM BLOCK] cam=%s gen=%s track=%s frame=%s zoom_block_reason=%s " ++ "before_first_positive_decision=%s blockers=%s counts=%s", ++ cam, owner[0], owner[1], source_seq, reason, before_first, ++ "+".join(blockers) or "-", json.dumps(record["total"], separators=(",", ":")), ++ ) + + + @visual_control.serialized_control +@@ -9844,6 +9866,39 @@ + ("brake", final_guard_active), + ) if blocked) + zoom_decision = (source_seq, decision_request, zoom_zero_reason, "+".join(blockers) or "-") ++ if (bool(getattr(config, "ZOOM_BLOCK_DIAG_ENABLE", False)) ++ and cam_idx in getattr(config, "ZOOM_BLOCK_DIAG_CAM_IDS", (8, 10))): ++ if zoom_cmd > 0.0: ++ _log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd, "", ()) ++ else: ++ diagnostic_flags = tuple(name for name, active in ( ++ ("gimbal_brake", final_guard_active), ++ ("edge_margin_low", near_edge or edge_recovery_active), ++ ("stale_visual", visual_control_stale), ++ ("visual_coast", visual_control_coast), ++ ("geometry_rearm", not zoom_rearm_ready), ++ ("size_controller", not raw_zoom_needed or normal_size_hold), ++ ("low_tracker_score", current_track_source == "visual" ++ and float(st.get("visual_tracker_score", 0.0) or 0.0) ++ < float(getattr(config, "VISUAL_TRACKER_ZOOM_SCORE", 0.42))), ++ ("waiting_yolo", current_track_source == "visual" and not zoom_quality_ok ++ and visual_zoom_validation_age ++ > float(getattr(config, "VISUAL_TRACKER_ZOOM_MAX_UNVALIDATED_SEC", 1.0))), ++ ("quality_or_validation", not zoom_quality_ok), ++ ("fov_cooldown", not followup_ready), ++ ("framing", not zoom_safe), ++ ("angular_limit", not zoom_angular_safe), ++ ("not_centered", not center_locked_for_zoom), ++ ("track_history", not track_stable), ++ ("focus_settle", now < float(st.get("focus_settle_until", 0.0) or 0.0)), ++ ) if active) ++ # size_controller is initialized before any gate is evaluated. ++ # Prefer a specific stop stage when one was actually recorded. ++ diagnostic_reason = zoom_zero_reason ++ if diagnostic_reason in ("size_controller", "permission") and diagnostic_flags: ++ diagnostic_reason = diagnostic_flags[0] ++ _log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd, ++ diagnostic_reason, diagnostic_flags) + dispatch_kwargs = {"force": force_track_ptz} + if zoom_decision is not None: + dispatch_kwargs["zoom_decision"] = zoom_decision diff --git a/integration/ptz_pr7_zoom_block_reason/pr7_zoom_block_reason_pins.json b/integration/ptz_pr7_zoom_block_reason/pr7_zoom_block_reason_pins.json new file mode 100644 index 0000000..d54a27d --- /dev/null +++ b/integration/ptz_pr7_zoom_block_reason/pr7_zoom_block_reason_pins.json @@ -0,0 +1,4 @@ +{ + "before": "776b5b337e5f898e69770fec517c4459560f4cc6adeb951af40ac8f0b2178534", + "after": "a9315ef80ca1cc6064088acfba0e854ed4617f3594753663050b13f82dd3c8fa" +} diff --git a/integration/ptz_pr7_zoom_block_reason/prepare_pr7_diagnostics.py b/integration/ptz_pr7_zoom_block_reason/prepare_pr7_diagnostics.py new file mode 100644 index 0000000..eb9ba6d --- /dev/null +++ b/integration/ptz_pr7_zoom_block_reason/prepare_pr7_diagnostics.py @@ -0,0 +1,98 @@ +"""Prepare an opt-in observation-only patch for the pinned PR7 controller.""" +from hashlib import sha256 +from pathlib import Path +import difflib +import json +import sys + +OUT = Path(__file__).resolve().parent +SOURCE = OUT.parent / "ptz_zoom_threshold_maintenance_20261111/postprocess.py" +BASE_SHA = "776b5b337e5f898e69770fec517c4459560f4cc6adeb951af40ac8f0b2178534" + +HELPER = '''def _log_zoom_block_tick(st, cam, source_seq, zoom, reason, blockers): + """Count TRACK decisions without taking part in actuator authorization.""" + owner = (st.get("ptz_generation"), st.get("track_started_at")) + record = st.get("zoom_block_diag") + if record is None or record["owner"] != owner: + record = {"owner": owner, "first_positive": False, "total": {}, "before_first": {}} + st["zoom_block_diag"] = record + if zoom > 0.0: + record["first_positive"] = True + return + before_first = not record["first_positive"] + for key in ("total", "before_first") if before_first else ("total",): + counts = record[key] + counts[reason] = counts.get(reason, 0) + 1 + logger.info( + "[ZOOM BLOCK] cam=%s gen=%s track=%s frame=%s zoom_block_reason=%s " + "before_first_positive_decision=%s blockers=%s counts=%s", + cam, owner[0], owner[1], source_seq, reason, before_first, + "+".join(blockers) or "-", json.dumps(record["total"], separators=(",", ":")), + ) + + +''' +HOOK = ''' if (bool(getattr(config, "ZOOM_BLOCK_DIAG_ENABLE", False)) + and cam_idx in getattr(config, "ZOOM_BLOCK_DIAG_CAM_IDS", (8, 10))): + if zoom_cmd > 0.0: + _log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd, "", ()) + else: + diagnostic_flags = tuple(name for name, active in ( + ("gimbal_brake", final_guard_active), + ("edge_margin_low", near_edge or edge_recovery_active), + ("stale_visual", visual_control_stale), + ("visual_coast", visual_control_coast), + ("geometry_rearm", not zoom_rearm_ready), + ("size_controller", not raw_zoom_needed or normal_size_hold), + ("low_tracker_score", current_track_source == "visual" + and float(st.get("visual_tracker_score", 0.0) or 0.0) + < float(getattr(config, "VISUAL_TRACKER_ZOOM_SCORE", 0.42))), + ("waiting_yolo", current_track_source == "visual" and not zoom_quality_ok + and visual_zoom_validation_age + > float(getattr(config, "VISUAL_TRACKER_ZOOM_MAX_UNVALIDATED_SEC", 1.0))), + ("quality_or_validation", not zoom_quality_ok), + ("fov_cooldown", not followup_ready), + ("framing", not zoom_safe), + ("angular_limit", not zoom_angular_safe), + ("not_centered", not center_locked_for_zoom), + ("track_history", not track_stable), + ("focus_settle", now < float(st.get("focus_settle_until", 0.0) or 0.0)), + ) if active) + # size_controller is initialized before any gate is evaluated. + # Prefer a specific stop stage when one was actually recorded. + diagnostic_reason = zoom_zero_reason + if diagnostic_reason in ("size_controller", "permission") and diagnostic_flags: + diagnostic_reason = diagnostic_flags[0] + _log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd, + diagnostic_reason, diagnostic_flags) +''' + + +def build(path): + raw = path.read_bytes() + if sha256(raw).hexdigest() != BASE_SHA: + raise ValueError("Expected pinned PR7 postprocess.py") + old = raw.decode() + marker = "@visual_control.serialized_control\ndef postprocess_control(" + anchor = ' dispatch_kwargs = {"force": force_track_ptz}\n' + if old.count(marker) != 1 or old.count(anchor) != 1: + raise ValueError("Unexpected integration point") + new = old.replace(marker, HELPER+marker).replace(anchor,HOOK+anchor) + return old,new + + +def main(): + source = Path(sys.argv[1]) if len(sys.argv) > 1 else SOURCE + old,new = build(source) + compile(new,"postprocess.py","exec") + patch = "".join(difflib.unified_diff(old.splitlines(True),new.splitlines(True), + "a/postprocess.py","b/postprocess.py")) + (OUT/"pr7_zoom_block_reason.patch").write_bytes(patch.encode()) + (OUT/"pr7_zoom_block_reason_pins.json").write_text( + json.dumps({"before":BASE_SHA,"after":sha256(new.encode()).hexdigest()},indent=2)+"\n", + encoding="utf-8") + print("Prepared diagnostic patch and hashes") + + +if __name__=="__main__": + main() diff --git a/integration/ptz_pr7_zoom_block_reason/verify_pr7_diagnostics.py b/integration/ptz_pr7_zoom_block_reason/verify_pr7_diagnostics.py new file mode 100644 index 0000000..be62250 --- /dev/null +++ b/integration/ptz_pr7_zoom_block_reason/verify_pr7_diagnostics.py @@ -0,0 +1,90 @@ +"""Verify the pinned PR7 diagnostic patch, its counts and its observation-only hook.""" +from hashlib import sha256 +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock +import ast +import json +import subprocess +import sys +import tempfile + +from prepare_pr7_diagnostics import BASE_SHA, OUT, SOURCE + + +def function(tree, name): + return next(x for x in tree.body if isinstance(x, ast.FunctionDef) and x.name == name) + + +def dump(node): + return ast.dump(node, include_attributes=False) + + +def main(): + pins = json.loads((OUT / "pr7_zoom_block_reason_pins.json").read_bytes()) + patch = str(OUT / "pr7_zoom_block_reason.patch") + with tempfile.TemporaryDirectory(dir=OUT) as directory: + source = Path(directory)/"postprocess.py" + original = Path(sys.argv[1]) if len(sys.argv) > 1 else SOURCE + base = original.read_bytes() + assert sha256(base).hexdigest()==BASE_SHA + source.write_bytes(base) + git = ["git","-c","core.autocrlf=false","apply"] + subprocess.run([*git,"--whitespace=error",patch],cwd=directory,check=True) + after=source.read_bytes() + assert sha256(after).hexdigest()==pins["after"] + subprocess.run([*git,"-R",patch],cwd=directory,check=True) + assert source.read_bytes()==base + + old, new = ast.parse(base), ast.parse(after) + proc = function(new,"postprocess_control") + control = function(old,"postprocess_control") + anchor = next(node for node in ast.walk(proc) if isinstance(node,ast.If) + and "ZOOM_BLOCK_DIAG_ENABLE" in dump(node.test)) + # Removing the optional hook and its sole helper restores the entire AST. + for parent in ast.walk(proc): + for field,value in ast.iter_fields(parent): + if isinstance(value,list) and anchor in value: + value.remove(anchor) + new.body.remove(function(new,"_log_zoom_block_tick")) + assert dump(proc)==dump(control) and dump(old)==dump(new) + + helper=function(ast.parse(after),"_log_zoom_block_tick") + log=Mock() + env={"json":json,"logger":log} + exec(compile(ast.Module(body=[helper],type_ignores=[]),"","exec"),env) + report=env[helper.name] + st={"ptz_generation":4,"track_started_at":100.0} + state={ + "config":SimpleNamespace(ZOOM_BLOCK_DIAG_ENABLE=False), "cam_idx":8, "st":st, + "source_seq":1,"zoom_cmd":0.,"final_guard_active":False,"near_edge":False, + "edge_recovery_active":False,"visual_control_stale":False,"visual_control_coast":False, + "zoom_rearm_ready":True,"raw_zoom_needed":True,"normal_size_hold":False, + "current_track_source":"visual","visual_zoom_validation_age":0.2,"zoom_quality_ok":True, + "followup_ready":True,"zoom_safe":True,"zoom_angular_safe":True, + "center_locked_for_zoom":False,"track_stable":False,"now":101., + "zoom_zero_reason":"size_controller","_log_zoom_block_tick":report, + } + call=compile(ast.Module(body=[anchor],type_ignores=[]),"","exec") + exec(call,state) + assert "zoom_block_diag" not in st + state["config"].ZOOM_BLOCK_DIAG_ENABLE=True + st["visual_tracker_score"]=.8 + exec(call,state) + assert st["zoom_block_diag"]["before_first"]=={"not_centered":1} + state.update(zoom_cmd=.10) + exec(call,state) + assert st["zoom_block_diag"]["first_positive"] + state.update(zoom_cmd=0.,zoom_zero_reason="final_brake",final_guard_active=True) + exec(call,state) + assert st["zoom_block_diag"]["total"]=={"not_centered":1,"final_brake":1} + assert st["zoom_block_diag"]["before_first"]=={"not_centered":1} + st.update(ptz_generation=5,track_started_at=103.0) + exec(call,state) + assert st["zoom_block_diag"]["before_first"]=={"final_brake":1} + assert log.info.call_count==3 + print("Round-trip exact, control AST unchanged outside the hook, toggle/phase/owner/count checks passed.") + + +if __name__=="__main__": + main()