Skip to content

feat(engine): temporal validation of alerts on the Pi - #415

Merged
MateoLostanlen merged 28 commits into
developfrom
feat/temporal-validator
Nov 18, 2026
Merged

MateoLostanlen merged 28 commits into
developfrom
feat/temporal-validator

Conversation

@MateoLostanlen

@MateoLostanlen MateoLostanlen commented Sep 8, 2026 •

Copy link
Copy Markdown
Member
  • While an alert is ongoing, the engine sends the last 11 frames of the pose, with their boxes, to a new pyro_temporal_api service running the temporal smoke model. The verdict comes back on the next round. Each box is uploaded with its tube score (temporal_model_scores, feat: accept the temporal score computed on the device pyro-api#723), the API applies the threshold. Boxes outside every tube, or in a tube scored 0.2 or less, are dropped.
  • Fail open: if the service errors, loses the job or takes more than 120 s, the frames go out without scores, and the window is still submitted every round so scoring resumes as soon as the service answers. The API scores a sequence the device never scored; a sequence that already received device scores keeps its last device verdict (pyro-api#723 keeps the highest score and never falls back to its own model), so a fail-open after a low device score leaves it unvalidated until a higher score or the end of the event. An event that ends while a job is pending waits for the verdict, so the last alert of an event is never lost.
  • Each distinct frame is sent once. The camera API can serve the same capture twice, and a repeated frame turned a 0.003 false positive into 0.75.
  • The service is the torch-free ONNX runtime from temporal-model (feat: ONNX export and torch-free runtime for the tube classifier temporal-model#76 and feat(onnx): split backbone/head export and release it as model 0.6.1 temporal-model#109, pinned to the v0.4.2 release), behind the compose profile temporal. Without TEMPORAL_API_URL nothing changes. make run-no-temporal starts the stack without it.
  • The service only listens on loopback and caps its inputs: 11 frames of 4 MB per job, 50 boxes per frame, 16 jobs pending. /health returns 503 when the worker is dead or stuck.
  • data/model_onnx.zip is the Hugging Face v0.6.1 package (format 2, split backbone/head), so the service caches ViT embeddings across jobs. A format 1 package still loads, without the cache.
  • Temporal API tests and ty type check run in CI, make test and make typecheck.

Tests

  • Pi 5, 8 dataset sequences (5 smokes, 3 non-smoke) replayed through the real engine: every smoke was uploaded after a positive verdict, no non-smoke reached the gate, 0 errors. About 9 s per job, 530 MB RSS for the service, host peaks at 2.4 GB of 4 GB.
  • pyro-envdev with fake cameras (feat: fake Reolink camera driven by scenarios pyro-envdev#65) and pyro-api#723: the videlles-01 false positive is rejected (max 0.12), the real fire of smoke-then-clear is still validated (0.97 to 1.0). On the 376 val sequences, engine boxes give the same verdicts as the model's own detector.

@codecov

codecov Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.47577% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.18%. Comparing base (d3c2a9b) to head (e9d038c).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
pyroengine/temporal_client.py 57.89% 8 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #415      +/-   ##
===========================================
+ Coverage    81.05%   87.18%   +6.12%     
===========================================
  Files            7        8       +1     
  Lines          871     1139     +268     
===========================================
+ Hits           706      993     +287     
+ Misses         165      146      -19     
Flag Coverage Δ
unittests 87.18% <96.47%> (+6.12%) ⬆️

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 MateoLostanlen changed the title feat: temporal validation of alerts through a sidecar service feat: temporal validation of alerts Sep 12, 2026
@MateoLostanlen MateoLostanlen changed the title feat: temporal validation of alerts feat: temporal validation of alerts on pi Sep 12, 2026
@MateoLostanlen
MateoLostanlen force-pushed the feat/temporal-validator branch 2 times, most recently from ebcfe93 to 131d4ec Compare September 12, 2026 14:08
@MateoLostanlen MateoLostanlen changed the title feat: temporal validation of alerts on pi feat(engine): temporal validation of alerts on the Pi Sep 14, 2026
@fe51 fe51 moved this to In progress in Roadmap 26-27 Oct 20, 2026
@MateoLostanlen
MateoLostanlen requested a review from fe51 October 22, 2026 12:59
MateoLostanlen added a commit to pyronear/pyro-envdev that referenced this pull request Oct 27, 2026
YOLO fires on both cameras while the temporal model rejects the sequences, so no alert is expected with temporal validation. It caught repeated frames being scored on the engine (pyronear/pyro-engine#415). Images are in the scenarios release (false-positive.zip).

@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.

Overall the gate logic looks good to me, I didn't spot a bug in _temporal_gate. I reviewed the non-test code but didn't run anything.

Before merging

  • CI: the "Run temporal API tests" step is red.
  • Pins: pyroclient (658cc6a) and temporal-model (7c1500e) point to commits that aren't on main. That's fine during development, but they need updating before merge.

Worth a look

  • False positives can inherit a real score: _overlaps accepts any overlap with the tube's box, which is the union across all frames, and we keep the highest probability. A false-positive box touching a real smoke tube therefore gets that tube's score. Would a minimum IoU be safer?
  • /health: the 503 doesn't trigger a restart, because restart: always doesn't act on unhealthy containers. If the worker gets stuck, each alert is held for 120 s and then sent unscored until someone restarts the service by hand. If the healthcheck is meant to recover from this, it needs to kill the process, like the engine heartbeat on refactor/homogeneous-logging.
  • Load on the Pi: the service has no CPU or memory limits, and every alerting pose is re-scored each round (about 9 s per job). The 2.4 GB of 4 GB peak comes from replaying 8 sequences. Has this been tested with several PTZ cameras alerting at the same time?

Conflicts

  • refactor/homogeneous-logging conflicts on .env.example, CLAUDE.md and docker-compose.yml, so whichever lands second will need a rebase.
  • engine.py merges cleanly, but the new logs don't follow that branch's conventions (f-strings without [cam_id], per-pose INFO lines). pyro_temporal_api/main.py also has its own basicConfig format and ignores LOG_LEVEL.

Questions

  • A single 5 s timeout sets temporal_bypass until the event ends, so the rest of the event goes out unscored and the API scores it instead. That seems fine since nothing is lost, but is it the intended behavior?
  • The API doesn't know which model version produced a score. Is it worth sending the version along with it?

@MateoLostanlen MateoLostanlen left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hi @fe51, thanks for the review!

  • CI is green now, temporal API tests included.
  • Overlap: a box now needs at least half of its area inside the tube to get its score, so a false positive that only touches a real tube is dropped.
  • /health now exits the process when the worker is dead or stuck, so restart: always brings it back.
  • Logs follow the [cam_id] convention and the service reads LOG_LEVEL.
  • 5 s timeout: yes, intended. Nothing is lost, the API scores the rest of the event.
  • Model version and load with several PTZ cameras: not done yet, I'll follow up.
  • Pins: still waiting on pyro-api#723 and the temporal-model ONNX export. I'll repin before merging.

…X temporal model

POST /jobs takes a window of frames plus YOLO boxes for one camera pose
and returns a job id at once; a worker thread scores it with
OnnxTemporalModel and GET /jobs/{id} serves the verdict. No torch.
With TEMPORAL_API_URL set, the engine keeps the last 10 inference frames
and boxes per camera pose, submits them when an alert becomes ongoing and
reads the verdict on the next round. Negative verdicts resubmit the
longer window; service errors fail open.
…ge, compose profile

Per-frame size limit and pending-job cap on POST /jobs, service bound to
127.0.0.1 on the host network, image added to the build-and-push matrix
so make run can pull it, and the service placed behind the temporal
compose profile so disabled stacks do not start it.
MateoLostanlen and others added 19 commits November 7, 2026 08:24
An event ending while the temporal job was pending was dropped by _end_event,
so a positive verdict never uploaded the frames held during scoring. The state
now survives until the verdict: positive stages the held frames, negative drops
the event without resubmitting.
…split export

Pins temporal-model-core to 7c1500e (feat/onnx-embedding-cache): the ONNX
package is now backbone + head, the runtime embeds only real slots and keeps
an LRU of per-slot embeddings keyed by (frame id, crop box). The engine
resubmits the same window one frame longer each round, so a job now mostly
pays the ViT for the new frame. The verdict reports embeddings_cached /
embeddings_new; a fused (format 1) package still loads with a warning.

README points at the model 0.6.0 release (pyro-dataset v4.7.0), to be
re-exported with temporal-export-onnx for the split graphs.
- clear the job on every fail-open path so a lost job cannot keep an event alive
- fail open when a job stays pending longer than temporal_job_timeout (120 s)
- submit the engine's own prediction window (widened to 10 frames) instead of a second buffer
- service: at most 10 frames per job, box and JPEG validation, duplicate frame ids rejected
- service: /health is 503 when the worker died or is stuck, results published under the lock
- 5 s client timeout, temporal API tests in CI and make test, make run-no-temporal
…hreshold

Matches pyro-api PR 723 (temporal_model_scores on POST /detections):
- the service verdict lists each scored tube with its union box and probability
- the engine scores the window every round while an alert is ongoing, uploads the boxes
  covered by a tube above temporal_min_score (0.1) with that probability, drops the others
- fail open (service down, lost or stuck job) sends the frames without scores so the API
  scores the sequence itself
- pyroclient pinned to the PR 723 commit (repoint to main once merged), requirements
  regenerated with uv 0.13.4
…frames for good

- a job remembers the frame ids it submitted; its verdict stages those frames only, frames
  captured afterwards wait for the next verdict
- a verdict rejecting an ended event marks the held frames as consumed so a later event cannot
  upload them under its own score
- window of 11 frames, all submitted (service MAX_FRAMES=11)
The camera API serves the last capture again when the engine reads a pose before the patrol refreshed it. Repeated frames push the temporal score of a false positive from 0.003 to 0.75. pyro-api scores distinct frames only. The job still covers every frame of the window, so the repeats go out with the tube scores.
temporal_min_score goes from 0.1 to 0.2 and becomes strict: a box is uploaded with its tube probability only when that probability is above 0.2. pyro-api keeps applying TEMPORAL_MODEL_THRESHOLD (0.45) to the engine score, the same threshold as for its own model.
restart: always ignores an unhealthy container, so a stuck worker held
every new event for 120 s until a manual restart. The stuck test also
relied on time.monotonic() being past STUCK_AFTER, which fails on a
fresh CI runner.
Any overlap with the union box of a tube let a false positive touching a
real smoke tube inherit its probability. Coverage of the box (not IoU,
which punishes a small box inside a long tube) must reach 0.5.
pyro-api keeps the highest temporal score and no longer falls back to its own model once a sequence received a device score. Say so where the fail-open was described as handing the sequence to the API.
…n the service

- temporal gate logs use the [cam_id] prefix with lazy %-style args; the per-round
  "pending" and "submitted" lines move to DEBUG
- pyro_temporal_api reads LOG_LEVEL, shares the engine log format and hands the
  uvicorn loggers to the root handler so the level applies service-wide, access
  lines (one per health check) kept for DEBUG only
- compose passes LOG_LEVEL to the temporal service, docs say "all three services"
…frames of an ended event

- the window keeps one extra frame so the oldest frame a job scored is still
  there when its verdict is read on the next round
- a negative verdict for an event that ended while it was pending drops that
  job's frames even when a new event already started
…oxes

- a service error no longer leaves the rest of the event unscored: the window
  is still submitted every round and the first verdict resumes scoring, since
  pyro-api keeps the last device score and never scores the sequence itself
- keep the five most confident boxes (with their scores) when backfill over the
  widened window adds more, pyroclient would otherwise drop the whole frame
@MateoLostanlen
MateoLostanlen force-pushed the feat/temporal-validator branch from d09d481 to 661c79a Compare November 7, 2026 07:36
fe51
fe51 previously approved these changes Nov 8, 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.

Thanks @MateoLostanlen, good to merge now !

@github-project-automation github-project-automation Bot moved this from In progress to In review in Roadmap 26-27 Nov 8, 2026
Replaying the October Pi captures, the device validated about 2.4x more
alerts than pyro-api on the same events (55 vs 23 at snow-valley). The
model and service are identical; the gap came from the window:

- only the frames with a detection go in the window, not the last 11
  captures, whose weak 0.05 boxes pushed the score up
- boxes sent from confidence 0.1, the service's detection threshold
  (overlapping boxes are already removed by the classifier)
- scored from the 4th to the 10th detection of the event, then the last
  verdict holds: a positive one sends the rest of the event, a negative
  one drops it; detections of an event that ended before its 4th are
  dropped

Simulated on 213 October sequences, verdicts match pyro-api on 202, with
the same volume (22 vs 21).
The previous commit counted detections and built the scoring window from
the shared 11-capture buffer, which a review showed to break in six ways:
an ended event's pending verdict validated the next event, rejected
frames leaked into it, a slow verdict skipped the full window, boxes
carried onto a staged frame made it a detection, the first detections
left the buffer before the 10th, and a final verdict on a quiet frame
lost the end of the event.

Each event now keeps its own frames (outside the detection window, which
is no longer widened), its scoring window built at capture time, its job,
verdict and crop boxes (frozen on capture). A window is submitted
whenever it grew, the event ended or not; the verdict on the full
window, or the last one of an ended event, is final for every frame of
it. A later event is scored while an earlier one waits for its verdict,
but goes out after it. Sent frames release their JPEG and context crop,
an event keeps only the tracked-boxes lookback (which ends at the
verdict's frames) and at most 3 windows of held frames. A malformed
verdict or submission reply fails open instead of raising out of
predict. One test per case.
@MateoLostanlen
MateoLostanlen merged commit e2f9e0a into develop Nov 18, 2026
13 checks passed
@MateoLostanlen
MateoLostanlen deleted the feat/temporal-validator branch November 18, 2026 14:26
@github-project-automation github-project-automation Bot moved this from In review to Done in Roadmap 26-27 Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants