Attribute acknowledged stops in PTZ zoom delivery logs

feature/ptz-zoom-stop-attribution
Ярослав Карташов 2 weeks ago
parent 587658c3b1
commit c762f2b908

1
.gitattributes vendored

@ -0,0 +1 @@
/integration/ptz_zoom_stop_attribution/server.patch text eol=lf -whitespace

@ -0,0 +1,13 @@
# Атрибуция завершения импульса PTZ
В двух эпизодах 9 ноября журнал пометил 12 импульсов PTZ19 и 23 импульса PTZ21 как `short` с общей причиной `physical_stop`. Текущий журнал фиксирует `PTZ SEND` до отправки, поэтому одного соседнего сообщения недостаточно, чтобы связать короткую доставку с подтверждённой заменой команды.
Патч дополняет существующую строку `ZOOM DELIVERY` после успешного завершения. В неё входят тип и native исходного импульса, источник, поколение и последовательность замены, запрошенные и фактически отправленные оси. Для приоритетной остановки записываются её оси и исходная причина. Старые поля сохранены.
Патч рассчитан на фактический серверный `ptz_io.py` с хешем baseline из `pins.json`. Прямой и обратный патчи проверены побайтно на локальной копии. Офлайн-проверка принимает исходный и изменённый файлы:
```sh
python -B test_stop_attribution.py /path/to/original/ptz_io.py /path/to/candidate/ptz_io.py
```
Шесть тестов проверяют формат атрибуции, фактические точки вызова и равенство состояния и решений исходного контроллера. Поведение движения, лимиты, модель и тревоги не меняются. На объекте правка не установлена.

@ -0,0 +1,10 @@
{
"files": {
"ptz_tracker_modular/ptz_io.py": {
"baseline": "dacc7e95a2abc58deee0e3f6a4614aeb529acbee33aab5bd692ef16c39e33da7",
"candidate": "3c3f10eaebc2a1c0f67725d6a487bad9e1537b1bb277705fc503c2526c779600"
}
},
"patch_sha256": "54404c37ff7f618bd48180cbd84f6cf1d2512f2d6fed82a098ebef30feef4052",
"diagnostics_only": true
}

@ -0,0 +1,52 @@
--- a/ptz_tracker_modular/ptz_io.py
+++ b/ptz_tracker_modular/ptz_io.py
@@ -800,2 +800,4 @@
reason: str,
+ stop_axes: Optional[tuple[int, int, int]] = None,
+ stop_command: Optional[MoveTuple] = None,
) -> bool:
@@ -830,3 +832,4 @@
st["zoom_step_feedback_pulse_sec"] = full_window
- st["zoom_step_feedback_native_cmd"] = int(st.get("zoom_step_physical_native_cmd", 0) or 0)
+ native_cmd = int(st.get("zoom_step_physical_native_cmd", 0) or 0)
+ st["zoom_step_feedback_native_cmd"] = native_cmd
st["zoom_step_feedback_full_window"] = bool(delivered + 1e-6 >= full_window)
@@ -946,4 +949,18 @@
st["acquire_zoom_prev_err"] = None
+ # Capture the ACKed replacement, since PTZ SEND logs only a pre-send attempt.
+ effective_axes = stop_axes if stop_axes is not None else (None, None, None)
+ requested_axes = (
+ (stop_command.pan_i, stop_command.tilt_i, stop_command.zoom_i)
+ if stop_command is not None else effective_axes
+ )
+ stop_source = _cmd_source(stop_command) if stop_command is not None else (
+ "priority_stop" if stop_axes is not None else "unknown"
+ )
+ stop_generation = _cmd_generation(stop_command) if stop_command is not None else (
+ int(st.get("ptz_generation", 0) or 0) if stop_axes is not None else None
+ )
logger.info(
- "[ZOOM DELIVERY] cam=%s request=%s result=%s duration=%.3fs min=%.3fs optics=%s reason=%s zstep=%s",
+ "[ZOOM DELIVERY] cam=%s request=%s result=%s duration=%.3fs min=%.3fs optics=%s reason=%s zstep=%s "
+ "kind=%s native=%s stop_source=%s stop_gen=%s stop_seq=%s "
+ "stop_requested=(%s,%s,%s) stop_effective=(%s,%s,%s)",
cam_idx,
@@ -964,2 +981,9 @@
int(st.get("zoom_in_pulse_count", 0) or 0),
+ kind,
+ native_cmd,
+ stop_source,
+ stop_generation,
+ _cmd_move_seq(stop_command),
+ *requested_axes,
+ *effective_axes,
)
@@ -1305,2 +1329,3 @@
reason=f"priority_stop:{reason}",
+ stop_axes=(pan_i, tilt_i, 0),
)
@@ -3530,2 +3555,4 @@
reason="physical_stop",
+ stop_axes=(pan_i, tilt_i, zoom_i),
+ stop_command=cmd,
)

@ -0,0 +1,96 @@
"""Compare real baseline and candidate pulse finalizers without loading hardware code."""
import ast
import math
from pathlib import Path
import sys
from types import SimpleNamespace
import unittest
BASELINE, CANDIDATE = map(Path, sys.argv[1:3])
sys.argv[:] = [sys.argv[0]]
FINALIZE = '_finalize_zoom_step_physical_delivery'
PURE = {FINALIZE, '_zoom_step_timing', '_clear_zoom_step_feedback_transaction',
'_cmd_source', '_cmd_generation', '_cmd_move_seq'}
def run_file(path, *, elapsed, optical, discard, metadata):
tree = ast.parse(path.read_bytes())
relevant = [node for node in tree.body if getattr(node, 'name', None) in PURE]
records, charged = [], []
config = SimpleNamespace(ZOOM_STEP_MIN_DELIVERED_RATIO=.7)
env = dict(math=math, config=config, time=SimpleNamespace(monotonic=lambda:50.+elapsed),
clipf=lambda x, lo, hi: min(hi,max(lo,x)),
logger=SimpleNamespace(info=lambda fmt, *args: records.append(fmt % args)),
_zoom_step_optics_changed=lambda st, now:optical,
_commit_zoom_step_optics_confirmation=lambda *a, **kw:charged.append(kw))
exec(compile(ast.Module(body=[tree.body[0],*relevant],type_ignores=[]),str(path),'exec'), env)
st = dict(zoom_step_pending=True, zoom_step_pending_id=12,
zoom_step_pending_generation=3, zoom_step_physical_request_id=12,
zoom_step_physical_started_at=100., zoom_step_physical_started_mono=50.,
zoom_step_put_started_at=100., zoom_step_put_started_mono=50.,
zoom_step_physical_native_cmd=10, zoom_step_pending_kind='normal',
zoom_step_pending_pulse_sec=.26, zoom_step_pending_hard_sec=.34,
zoom_step_discard_on_finalize=discard, ptz_generation=3)
allowed = env[FINALIZE](8,st,100.+elapsed,**metadata)
return allowed, st, charged, records
class AttributionTests(unittest.TestCase):
def compare(self, *, elapsed=.12, optical=False, discard=False, **metadata):
reason = metadata['reason']
options = dict(elapsed=elapsed,optical=optical,discard=discard)
old = run_file(BASELINE,**options,metadata=dict(reason=reason))
new = run_file(CANDIDATE,**options,metadata=metadata)
self.assertEqual(old[:3],new[:3])
self.assertEqual(len(new[3]),1)
self.assertTrue(new[3][0].startswith(old[3][0]+' kind=normal native=10 '))
return new[3][0]
def test_controller_zero_and_movement_only_are_distinguishable(self):
for axes in ((0,0,0),(9,-2,0)):
with self.subTest(axes=axes):
move = SimpleNamespace(pan_i=axes[0],tilt_i=axes[1],zoom_i=axes[2],
source='track',generation=3,seq=17)
row = self.compare(reason='physical_stop',stop_axes=axes,stop_command=move)
compact = str(axes).replace(' ','')
self.assertIn(f'stop_source=track stop_gen=3 stop_seq=17 stop_requested={compact} stop_effective={compact}',row)
self.assertIn('result=short',row)
def test_worker_override_is_visible(self):
move = SimpleNamespace(pan_i=8,tilt_i=3,zoom_i=10,source='track',generation=3,seq=18)
row = self.compare(reason='physical_stop',stop_axes=(0,0,0),stop_command=move)
self.assertIn('stop_requested=(8,3,10) stop_effective=(0,0,0)',row)
def test_priority_stop_records_actual_axes(self):
row = self.compare(elapsed=.26,reason='priority_stop:watchdog',stop_axes=(4,0,0))
self.assertIn('result=delivered_wait_optics',row)
self.assertIn('stop_source=priority_stop stop_gen=3 stop_seq=-1 stop_requested=(4,0,0) stop_effective=(4,0,0)',row)
def test_optical_confirmation_and_owner_discard_are_preserved(self):
for discard in (True,False):
with self.subTest(discard=discard):
row = self.compare(elapsed=.26,optical=True,discard=discard,
reason='priority_stop:cancel_after_put',stop_axes=(0,0,0))
self.assertIn('result=discarded' if discard else 'result=confirmed',row)
def test_legacy_finalize_caller_has_no_fabricated_stop(self):
row = self.compare(reason='legacy')
self.assertIn('stop_source=unknown stop_gen=None stop_seq=-1',row)
self.assertIn('stop_effective=(None,None,None)',row)
def test_both_live_call_sites_pass_effective_axes(self):
tree = ast.parse(CANDIDATE.read_bytes())
calls = {}
for fn in tree.body:
for call in ast.walk(fn):
if isinstance(call,ast.Call) and isinstance(call.func,ast.Name) and call.func.id==FINALIZE:
calls[fn.name] = {k.arg:ast.unparse(k.value) for k in call.keywords}
self.assertEqual(calls,{
'_deliver_priority_lens_stop_locked':dict(reason="f'priority_stop:{reason}'",stop_axes='(pan_i, tilt_i, 0)'),
'_ptz_worker':dict(reason="'physical_stop'",stop_axes='(pan_i, tilt_i, zoom_i)',stop_command='cmd'),
})
if __name__=='__main__':
unittest.main(verbosity=2)
Loading…
Cancel
Save