move_detect/deploy/systemd/move-detect-edge.service
유창욱 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

73 lines
3.6 KiB
Desktop File

# move-detect edge daemon — systemd unit (Raspberry Pi 5, air-gapped/폐쇄망).
# Install: copy to /etc/systemd/system/, fill /etc/move-detect/edge.env, then
# sudo systemctl daemon-reload && sudo systemctl enable --now move-detect-edge
# The daemon tolerates the cloud being offline (events buffer in the local queue
# and flush on reconnect), so this unit only *wants* the network, not requires it.
[Unit]
Description=move-detect edge daemon (workplace-safety AI CCTV)
Documentation=file:/opt/move-detect/docs/pilot-runbook.md
Wants=network-online.target
After=network-online.target
# Never stop retrying. This MUST live in [Unit]: systemd's parser table knows
# Unit.StartLimitIntervalSec but only Service.StartLimitInterval (no "Sec"), so in
# [Service] it is an unknown key — silently ignored, leaving the default 5-starts/10s
# limit to defeat Restart=always below.
StartLimitIntervalSec=0
[Service]
# Type=exec, not simple: with simple, systemd marks the start job done the instant fork()
# returns, so an exec-step failure (226/NAMESPACE, 216/GROUP, 217/USER, 203/EXEC) never
# reaches `systemctl enable --now` and the installer reports success over a dead daemon.
Type=exec
# Dedicated unprivileged account; must be in the groups that own the camera and
# the Hailo accelerator device nodes.
User=movedetect
Group=movedetect
SupplementaryGroups=video render plugdev
WorkingDirectory=/opt/move-detect
EnvironmentFile=/etc/move-detect/edge.env
# Run the package straight from source (no pip build step needed offline).
Environment=PYTHONPATH=/opt/move-detect/src
ExecStart=/opt/move-detect/venv/bin/python -m edge
# Unattended resilience: always restart; the loop also isolates per-frame and
# periodic-op exceptions internally so a single glitch never exits the process.
Restart=always
RestartSec=5
# Writable state (offline queue sqlite lives here; keep QUEUE_DB pointed at it).
# systemd creates/owns /var/lib/move-detect for the service user.
StateDirectory=move-detect
StateDirectoryMode=0750
# Camera + accelerator device access. Once ANY DeviceAllow= is present, systemd denies every
# unlisted device node, so the CSI camera needs its nodes explicitly:
# char-video4linux USB UVC (/dev/video*) AND the CSI capture nodes
# char-media picamera2/libcamera opens /dev/media* to configure the CSI pipeline (Pi 5)
# char-dma_heap libcamera allocates capture buffers from the dma-heap on Pi 5
# Without char-media + char-dma_heap a Hailo Pi with a CSI camera is denied its own camera by this
# unit's policy. (OFF-HW: verify on the Pi — `journalctl` shows a libcamera EPERM/open failure.)
#
# NOTE: DeviceAllow= takes a device-node path OR a `char-<group>`/`block-<group>` name — NOT a
# directory. `/dev/dma_heap/` (a directory, trailing slash) is rejected at cgroup-realize time and
# silently dropped, leaving dma-heap DENIED under this deny-by-default policy. Use the char group
# (dma_heap appears in /proc/devices as a char device) so the whole /dev/dma_heap/* set is allowed.
DeviceAllow=/dev/hailo0 rw
DeviceAllow=char-video4linux rw
DeviceAllow=char-media rw
DeviceAllow=char-dma_heap rw
# Conservative hardening (loosen if it blocks device access on your image).
NoNewPrivileges=true
ProtectSystem=strict
# Do NOT add ReadWritePaths=/var/lib/move-detect here. StateDirectory= above already emits
# a recursive read-write bind mount for that exact path, which outranks a ReadWritePaths=
# entry for the same path and drops it before any path is resolved. It is dead config: it
# can neither cause nor fix a state-dir problem.
ProtectHome=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target