move_detect/tests/test_multicam.py
유창욱 2ea0420de7 fix(delivery): resolve codex + workflow review findings across edge/cloud/deploy
Two independent adversarial reviews (codex CLI + a 6-dimension verification
workflow) of the delivery-hardening branch surfaced ~40 findings; this closes
the confirmed correctness/security/deploy blockers plus a codex re-review pass.

edge:
- geometry: track_displacement per-second threshold recalibrated (0.02->0.25,
  env-tunable via MOTION_THR, validated finite/positive); confidence-filter
  keypoints with a bbox-center fallback so hallucinated points don't fake motion
- fall: low-confidence frames no longer cancel an active FALLING/FALLEN incident
  (freeze + reset recovery timer so recovery needs a fresh confident streak);
  baseline height only seeded from trusted frames
- queue: PostClient.send() returns a tri-state SendResult; only definite 4xx
  count toward the poison drop cap, so a network outage (incl. 408/425/429/5xx)
  never deletes queued safety events; legacy rows persist their minted uuid
- config: reject placeholder / http / short DEVICE_SECRET at startup
- zones: warn+skip legacy pixel-space polygons that would silently match nothing

cloud:
- zone endpoints wired into P3-2b site-scope (cross-site read/write/delete
  closed) + role gate on list; catch narrowed so DB faults surface as 500
- snapshot purge keeps the DB row when unlink() fails (no untrackable PIPA orphan)
- ingest dedup path re-stores missing snapshots (+ short-write guard); UNIQUE
  (event_id, content_hash) makes recovery idempotent under retry/race
- event list cursor carries full-precision occurred_at (no float rounding at the
  page boundary); string keyset end-to-end
- SiteScope '' fails closed (only NULL is global); dashboard fetches full page cap
- runnable migration (site/event_uuid + backfill ordering + indexes); rate-limit
  reap fails open

deploy:
- offline bundle hashes EVERY file (fatal on missing/failed/injected; models in
  SBOM; arch in tarball name; REQUIRE_SIGNATURE option)
- installer verifies before any mutation, Hailo arch preflight before install,
  atomic src swap, backend reconcile preserves a working operator choice
- systemd DeviceAllow=char-dma_heap (the /dev/dma_heap/ dir form was inert)

Verified: edge pytest 165 passed / 2 skipped; cloud phpunit 109 passed / 4
skipped; deploy scripts bash -n clean. Reviewed by codex twice (findings +
fixes) with the second-pass findings folded in.
2026-07-17 19:24:42 +09:00

106 lines
4.4 KiB
Python

"""TDD for multi-camera support: per-camera zone routing, a run_loop that steps
N cameras per tick, and CAMERAS env parsing. All with fakes (no hardware)."""
import pytest
from edge.zones import zones_from_config
from edge.daemon import run_loop, parse_cameras, build_runtimes
def _cfg_two_cams():
# Polygons are stored NORMALIZED (0..1 of the image); zones_from_config now rejects
# un-normalized (pixel-space) coordinates as legacy data.
return {"zones": [
{"zone_id": "z1", "camera_id": "cam-01", "level": "restricted",
"polygon_json": "[[0,0],[0.9,0],[0.9,0.9]]"},
{"zone_id": "z2", "camera_id": "cam-02", "level": "warning",
"polygon_json": "[[0,0],[0.5,0],[0.5,0.5]]"},
], "thresholds": {}}
def test_zones_filtered_by_camera():
cfg = _cfg_two_cams()
assert [z.zone_id for z in zones_from_config(cfg, "cam-01")] == ["z1"]
assert [z.zone_id for z in zones_from_config(cfg, "cam-02")] == ["z2"]
assert len(zones_from_config(cfg)) == 2 # no filter -> all (backward compat)
assert zones_from_config(cfg, "cam-99") == [] # unknown camera -> none
class _RT:
def __init__(self, cam): self.camera_id = cam; self.steps = 0; self.applied = None
def step(self, now): self.steps += 1; return []
def apply_zones(self, z): self.applied = z
class _Client:
def __init__(self, cfg): self._cfg = cfg; self.configs = 0; self.beats = 0
def fetch_config(self): self.configs += 1; return self._cfg
def send_heartbeat(self, m): self.beats += 1; return True
class _Q:
def __init__(self): self.flushes = 0
def flush(self): self.flushes += 1; return 0
def test_run_loop_steps_all_cameras_and_routes_zones_per_camera():
cfg = _cfg_two_cams()
r1, r2 = _RT("cam-01"), _RT("cam-02")
run_loop([r1, r2], _Client(cfg), _Q(), clock=lambda: 0.0, sleep=lambda s: None,
iterations=5, sync_every=5, heartbeat_every=99, flush_every=99,
zones_for=lambda c, rt: zones_from_config(c, rt.camera_id))
assert r1.steps == 5 and r2.steps == 5
assert [z.zone_id for z in r1.applied] == ["z1"]
assert [z.zone_id for z in r2.applied] == ["z2"]
def test_run_loop_one_camera_glitch_does_not_stop_the_other():
class Boom(_RT):
def step(self, now):
self.steps += 1
if self.steps == 2:
raise RuntimeError("cam glitch")
return []
r1, r2 = Boom("cam-01"), _RT("cam-02")
counters = run_loop([r1, r2], _Client(_cfg_two_cams()), _Q(),
clock=lambda: 0.0, sleep=lambda s: None, iterations=3,
sync_every=99, heartbeat_every=99, flush_every=99)
assert r1.steps == 3 and r2.steps == 3 # both kept going
assert counters["errors"] == 1
def test_parse_cameras_multi_and_single():
assert parse_cameras({"CAMERAS": "csi:0:cam-01, uvc:1:cam-02"}, "def") == \
[("csi", "0", "cam-01"), ("uvc", "1", "cam-02")]
assert parse_cameras({"CAMERA_BACKEND": "csi", "CSI_DEVICE": "2"}, "cam-09") == \
[("csi", "2", "cam-09")]
assert parse_cameras({}, "cam-01") == [("uvc", "0", "cam-01")]
def test_parse_cameras_rejects_blank_entries_never_zero_cameras():
# A non-empty-but-all-blank CAMERAS must fail loudly, never yield zero cameras
# (a safety daemon monitoring nothing while looking healthy).
with pytest.raises(ValueError):
parse_cameras({"CAMERAS": " , "}, "cam-01")
with pytest.raises(ValueError):
parse_cameras({"CAMERAS": "csi:0"}, "cam-01") # wrong arity
def test_build_runtimes_skips_a_camera_that_fails_to_start():
# An unseated/absent CSI camera raises at construction; it must be skipped so the
# working USB camera still runs (construction resilience, not just step isolation).
def make_source(backend, device):
if backend == "csi":
raise RuntimeError("no CSI camera attached")
return ("src", backend, device)
logs = []
rts = build_runtimes([("csi", "0", "cam-01"), ("uvc", "0", "cam-02")],
make_source, lambda cam, src: (cam, src), log=logs.append)
assert rts == [("cam-02", ("src", "uvc", "0"))]
assert any("cam-01" in m for m in logs)
def test_build_runtimes_raises_when_all_cameras_fail():
def boom(*_a):
raise RuntimeError("gone")
with pytest.raises(RuntimeError):
build_runtimes([("csi", "0", "c")], boom, lambda c, s: None, log=lambda m: None)