Skip to content

fix: stop serving and scoring frozen frames when a patrol hangs - #458

Merged
MateoLostanlen merged 12 commits into
developfrom
fix/camera-api-stale-patrol
Nov 9, 2026
Merged

MateoLostanlen merged 12 commits into
developfrom
fix/camera-api-stale-patrol

Conversation

@MateoLostanlen

@MateoLostanlen MateoLostanlen commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Part of pyronear/roadmap#16, fixes #422. Replaces #459, closed in favour of this one.

A patrol thread could hang on a Reolink call without timeout. The camera API then served the same frame for hours, and the engine either scored dead frames or slept all day as "night". Both sides are fixed here.

Camera API

  • Every Reolink request now has a 10 s default timeout. A PTZ call without timeout could block a patrol thread forever.
  • Each stored image keeps its capture time. latest_image returns 204 when the image is older than max_age_s (default 300 s), so the engine stops scoring frozen frames and stops sending heartbeats for that camera.
  • /health/patrols returns 503 when a running patrol makes no progress for 10 min. The compose healthcheck then kills every process but PID 1 (tini, via init: true) so restart: always brings the container back. /health stays a plain liveness check, as the Shelly watchdog uses it to decide whether to power-cycle the Pi.

Engine

  • Night patrols were only stopped when already stopped (inverted condition), so they ran all night. They are now stopped when running.
  • Day or night was decided from the last frame of the loop, so one stale or infrared frame could put the whole site to sleep in daylight. Each frame is now checked and night frames are not analyzed. Only cameras with a fresh frame count, so a dead camera neither keeps the site awake nor puts it to sleep, and the site sleeps after 3 passes in a row where every fresh frame is a night frame. A camera's detection history is dropped after 3 new night frames in a row, so an isolated infrared frame does not reset an ongoing event and evening frames are not combined with the next morning's. A camera in infrared while others see daylight is warned once.
  • A frame identical to the previous one for the same pose is skipped. A frozen camera at Epinay re-uploaded the same false positive every 30 s for 9 days.
    Since an unchanged frame is no longer re-scored, the same image can no longer fill the sliding window several times. This does not affect our cameras, but on webcams that refresh their snapshot slowly (e.g. every 10 min) an alert now needs several distinct images and can take much longer.

@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.59036% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 84.32%. Comparing base (d3c2a9b) to head (d26367e).

Files with missing lines Patch % Lines
pyroengine/core.py 97.26% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #458      +/-   ##
===========================================
+ Coverage    81.05%   84.32%   +3.27%     
===========================================
  Files            7        7              
  Lines          871      938      +67     
===========================================
+ Hits           706      791      +85     
+ Misses         165      147      -18     
Flag Coverage Δ
unittests 84.32% <97.59%> (+3.27%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@MateoLostanlen

Copy link
Copy Markdown
Member Author

Tested on pi-test (Pi 5, Debian 13, Docker 29), branch develop + #419 + #459 + #461 (includes this PR), images built on the Pi, real cameras unplugged.

Reolink call that hangs: OK

  • Fault: iptables -t nat DNAT of 192.168.1.11:443 to a local TCP listener that accepts and never answers (the Epinay case; an unplugged camera fails fast with "No route to host" and does not reproduce it).
  • Seen: Error at pose 5: ... Read timed out. (read timeout=10), then pose 6 exactly 10 s later. The patrol kept going.

Camera API frozen, healthcheck restarts it: OK

  • Fault: kill -STOP on the uvicorn process from the host (port open, nothing answers).
  • Seen: frozen 11:42:56, healthcheck at 11:43:23 timed out (curl rc 28), kill -9 -1, container back and healthy at 11:43:49.
  • Unplugged cameras: latest_image answered 204 for every pose and the engine stopped scoring.

Not tested on the Pi: the /health/patrols 503 after 10 min without progress (needs one thread frozen, left to test_stale_patrol.py).

Remark: the kill is inside the healthcheck command, so it fires on the first failed check and retries: 3 has no effect.

MateoLostanlen pushed a commit that referenced this pull request Oct 28, 2026
… camera

- The pass only collected the frames it received, so one night frame next to
  a camera answering 204 (no fresh image, PR #458) read as "every camera
  reports night" and put the site to sleep for an hour. The site now sleeps
  only when every expected frame came back and all of them are night frames;
  one day frame still wakes it.
- After the night sleep, only the first camera was probed: in infrared or down,
  it kept the whole site asleep in daylight. Every camera is probed until one
  shows daylight, and the site stays asleep only when all of them answer night.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@MateoLostanlen
MateoLostanlen requested a review from fe51 October 29, 2026 08:56
MateoLostanlen pushed a commit that referenced this pull request Oct 29, 2026
… camera

- The pass only collected the frames it received, so one night frame next to
  a camera answering 204 (no fresh image, PR #458) read as "every camera
  reports night" and put the site to sleep for an hour. The site now sleeps
  only when every expected frame came back and all of them are night frames;
  one day frame still wakes it.
- After the night sleep, only the first camera was probed: in infrared or down,
  it kept the whole site asleep in daylight. Every camera is probed until one
  shows daylight, and the site stays asleep only when all of them answer night.
@MateoLostanlen
MateoLostanlen force-pushed the fix/camera-api-stale-patrol branch from 719ea53 to 3bc0f60 Compare October 29, 2026 09:12
MateoLostanlen pushed a commit that referenced this pull request Oct 29, 2026
… camera

- The pass only collected the frames it received, so one night frame next to
  a camera answering 204 (no fresh image, PR #458) read as "every camera
  reports night" and put the site to sleep for an hour. The site now sleeps
  only when every expected frame came back and all of them are night frames;
  one day frame still wakes it.
- After the night sleep, only the first camera was probed: in infrared or down,
  it kept the whole site asleep in daylight. Every camera is probed until one
  shows daylight, and the site stays asleep only when all of them answer night.
@MateoLostanlen MateoLostanlen changed the title fix(camera-api): stop serving frozen frames when a patrol hangs fix: stop serving and scoring frozen frames when a patrol hangs Oct 29, 2026

@fe51 fe51 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MateoLostanlen Reviewed the diff and the code around it. No blocker in the mechanics, CI is green. A few points on behaviour, most important first.

1. A camera stuck in infrared goes blind silently, and one IR frame wipes its history (core.py, _analyze)

  • A camera stuck in IR during the day is no longer analyzed. Since predict isn't called, it also stops sending heartbeats, and the only trace is one INFO line per frame. #461 won't catch it either, as IR frames are fresh and changing.
  • A single night frame runs self.engine._states.pop(cam_id, None), which also drops ongoing and the frozen crop boxes. An isolated IR frame during an ongoing fire restarts that event from zero.

Suggestion: only drop the state after N consecutive night frames, and log a WARNING when a camera is in IR while others on the site see daylight.

2. The healthcheck can restart the API after about 25 s of load (docker-compose.yml)
The kill is inside the test command, so retries: 3 has no effect (as you noted). The only margin is 3 curl attempts, about 25 s. A saturated Pi could therefore restart the whole camera API, with every camera and any live stream. A restart may also skip the zoom restore done when a stream stops (not verified).

Suggestion: wait about 2 min by extending the curl retries, with timeout above their total duration (not tested):

test: ["CMD-SHELL", "curl -sf --max-time 5 --retry 8 --retry-delay 10 http://localhost:8081/health/patrols; rc=$$?; [ $$rc -eq 0 ] && exit 0; [ $$rc -eq 7 ] && exit 1; kill -9 -1"]
timeout: 140s

That gives 9 × 5 s + 8 × 10 s = 125 s before the kill, which is still small next to the 10 min STALL_LIMIT.

what do you think ?

3. One dead camera keeps the site awake all night (can be a follow-up)
With cameras A and B on night frames and C dead, len(day_frames) == expected is never true, and _probe_day also wakes the site when a camera doesn't answer. Detection isn't affected, since night frames are skipped, but PTZs patrol all night and the hourly autofocus runs on IR images. With #461, C's patrol also stays active overnight, so the detector keeps counting no_fresh_image and spends its reboot attempts on it.

Suggestion: only count the cameras that answered, with N passes of confirmation so one frame can't put the site to sleep.

4. Identical frame warning (minor, optional)
The comment says a live camera never returns the same pixels twice, but the engine reads the API cache. When a pass is shorter than the patrol cycle, reading the same image twice is normal, so skipping it is fine but the WARNING can be a false signal. #461 handles the real failure by comparing actual captures through last_image_at, then rebooting the camera. I would keep the digest here to avoid re-uploads, and move the log to DEBUG with a corrected comment.

Points 1 and 2 are the ones I'd settle before merging.

Co author with Claude

@MateoLostanlen

Copy link
Copy Markdown
Member Author

Hi @fe51, thanks for the detailed review!

All four points are addressed in 10cc832:

  • IR: the history is dropped after 3 night frames in a row, and a camera in IR while others see daylight is warned once.
  • Healthcheck: took your curl --retry 8 / timeout: 140s suggestion.
  • Dead camera: only cameras with a fresh frame count, and the site sleeps after 3 all-night passes.
  • Identical frame: log moved to DEBUG, comment fixed.

Also merged develop (#417) and fixed two more things in 137c461: an unchanged frame no longer counts as a new night frame, and it still sends the camera heartbeat.

MateoLostanlen and others added 12 commits November 7, 2026 08:27
…atrols

The Shelly watchdog reads /health to decide whether to power-cycle the Pi.
The healthcheck kills on every curl failure but rc 7, which looked like a hole:
a uvicorn that never binds would stay unhealthy forever. Killing on rc 7 would
loop at startup instead, as the kill runs during start_period too, and a hang
before the bind is bounded by the 10 s timeout on every camera call.
… camera

- The pass only collected the frames it received, so one night frame next to
  a camera answering 204 (no fresh image, PR #458) read as "every camera
  reports night" and put the site to sleep for an hour. The site now sleeps
  only when every expected frame came back and all of them are night frames;
  one day frame still wakes it.
- After the night sleep, only the first camera was probed: in infrared or down,
  it kept the whole site asleep in daylight. Every camera is probed until one
  shows daylight, and the site stays asleep only when all of them answer night.
…at answered

A single infrared frame dropped the camera's detection history, and with it an
ongoing event: cameras flicker between colour and infrared at dusk. The history
is now dropped after 3 night frames in a row, and a camera in infrared while
the others see daylight is warned once, as it sends no heartbeat.

A camera without a fresh image never counted as night, so one dead camera kept
the site awake all night: PTZ patrols ran, autofocus ran on infrared images,
and the stuck detector spent its reboot budget overnight. Only cameras with a
fresh frame count now, and the site sleeps after 3 all-night passes. The
frozen frame case is already handled by the API, which drops it after
max_age_s. Same rule for the wake-up probe.

The identical frame log goes to DEBUG: the engine reads the API cache, which
the patrol refreshes slower than the loop runs, so the same frame twice is the
normal case. The API's stuck detector diagnoses frozen cameras.

The healthcheck killed the API after 25 s of failed checks, as the kill runs
inside the check and `retries` gives no margin. The probe now retries for about
2 min, still well under the 10 min stall limit. The image ships no curl
anymore, so the probe uses Python's HTTP client with the same retries.

Also:
- an unchanged frame no longer counts as a new night frame, so one cached
  infrared capture read on several passes cannot drop an ongoing event
- an unchanged frame still sends the camera heartbeat, so a slow URL camera
  does not look offline
@MateoLostanlen
MateoLostanlen force-pushed the fix/camera-api-stale-patrol branch from 137c461 to d26367e Compare November 7, 2026 07:36
@MateoLostanlen
MateoLostanlen requested a review from fe51 November 7, 2026 07:49

@fe51 fe51 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @MateoLostanlen, all four points are addressed and the night logic is much safer now. LGTM.

One note for the PR description: since an identical frame is no longer re-scored, the same image no longer fills the sliding window several times. Alerts are more trustworthy, but they can take one or two more rounds than before, and much longer on a network refreshing slowly (e.g. 10 min). Worth a line so nobody is surprised if alert latency moves.

@MateoLostanlen
MateoLostanlen merged commit 1b448e5 into develop Nov 9, 2026
13 checks passed
@MateoLostanlen
MateoLostanlen deleted the fix/camera-api-stale-patrol branch November 9, 2026 07:59
@MateoLostanlen

Copy link
Copy Markdown
Member Author

Thanks @fe51! Added the note on alert latency to the description: it only affects webcams that refresh their snapshot slowly, not our cameras.

MateoLostanlen added a commit that referenced this pull request Nov 18, 2026
#461)

* fix(reolink): default timeout on every camera request

* fix(camera-api): return 204 from latest_image when the frame is stale

* fix(camera-api): restart the container when a patrol thread hangs

* refactor(camera-api): restart on a hung patrol from the compose healthcheck

* fix(camera-api): keep /health as liveness, check patrols on /health/patrols

The Shelly watchdog reads /health to decide whether to power-cycle the Pi.

* docs(compose): say why connection refused does not kill the camera API

The healthcheck kills on every curl failure but rc 7, which looked like a hole:
a uvicorn that never binds would stay unhealthy forever. Killing on rc 7 would
loop at startup instead, as the kill runs during start_period too, and a hang
before the bind is bounded by the 10 s timeout on every camera call.

* fix(engine): stop running patrols at night

* fix(engine): decide day or night per frame, sleep only when every camera is at night

* fix(engine): skip a frame identical to the previous one for the same pose

* fix(engine): keep day evidence on prediction errors and drop night history

* fix(engine): a missing frame never proves night, wake-up probes every camera

- The pass only collected the frames it received, so one night frame next to
  a camera answering 204 (no fresh image, PR #458) read as "every camera
  reports night" and put the site to sleep for an hour. The site now sleeps
  only when every expected frame came back and all of them are night frames;
  one day frame still wakes it.
- After the night sleep, only the first camera was probed: in infrared or down,
  it kept the whole site asleep in daylight. Every camera is probed until one
  shows daylight, and the site stays asleep only when all of them answer night.

* fix(engine): confirm night over several frames, count only cameras that answered

A single infrared frame dropped the camera's detection history, and with it an
ongoing event: cameras flicker between colour and infrared at dusk. The history
is now dropped after 3 night frames in a row, and a camera in infrared while
the others see daylight is warned once, as it sends no heartbeat.

A camera without a fresh image never counted as night, so one dead camera kept
the site awake all night: PTZ patrols ran, autofocus ran on infrared images,
and the stuck detector spent its reboot budget overnight. Only cameras with a
fresh frame count now, and the site sleeps after 3 all-night passes. The
frozen frame case is already handled by the API, which drops it after
max_age_s. Same rule for the wake-up probe.

The identical frame log goes to DEBUG: the engine reads the API cache, which
the patrol refreshes slower than the loop runs, so the same frame twice is the
normal case. The API's stuck detector diagnoses frozen cameras.

The healthcheck killed the API after 25 s of failed checks, as the kill runs
inside the check and `retries` gives no margin. The probe now retries for about
2 min, still well under the 10 min stall limit. The image ships no curl
anymore, so the probe uses Python's HTTP client with the same retries.

Also:
- an unchanged frame no longer counts as a new night frame, so one cached
  infrared capture read on several passes cannot drop an ongoing event
- an unchanged frame still sends the camera heartbeat, so a slow URL camera
  does not look offline

* feat(camera-api): detect frozen cameras and missing images, cap reboots

* feat(camera-api): run the stuck detector on every camera, add ALLOW_STILL_CAMERA

* fix(camera-api): read stored images from one copy, report reboot attempts

* fix(camera-api): persist the reboot budget, hide the camera password, grace after reboot

- Reboot attempts were in memory with monotonic times, so every container
  restart (healthcheck, update) handed out three new attempts. They are now
  wall-clock times saved in data/camera_recovery.json (RECOVERY_STATE_FILE)
  and loaded at startup, pruned to the last 24 h.
- `Reboot raised: <exc>` logged the Reolink URL with the camera password.
  Only the exception type is logged.
- A static camera rebooted by the detector failed its next two captures while
  booting and entered the 30 min skip window. The detector now resets the
  failure count and gives it 90 s before captures count again.
- /patrol_status iterated the attempts deque while the detector appended to
  it: both sides now hold a lock.
- "reboot budget spent" is logged once per episode instead of every 5 min.

* fix(camera-api): report the saved reboot attempt after a restart

/patrol_status showed one attempt in the last 24 h but no last_reboot_attempt
once the detector restarted: derive it from the attempts loaded from disk.

* fix(camera-api): ignore frozen and log once for cameras that cannot reboot

A URL or REST source may serve the same cached picture for minutes, which was seen as frozen and logged an error every check.

---------

Co-authored-by: Mateo Lostanlen <mateo@pyronear.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Patrol thread hangs on a Reolink HTTP call without timeout, engine then sleeps all day as "night"

2 participants