Skip to content

feat: accept the temporal score computed on the device - #723

Merged
MateoLostanlen merged 7 commits into
mainfrom
feat/engine-temporal-score
Nov 6, 2026
Merged

MateoLostanlen merged 7 commits into
mainfrom
feat/engine-temporal-score

Conversation

@MateoLostanlen

@MateoLostanlen MateoLostanlen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member
  • The engine can now run the temporal smoke model on the Pi (feat(engine): temporal validation of alerts on the Pi pyro-engine#415) and sends its probabilities with each detection. The API keeps its own model for devices that cannot.
  • POST /detections takes an optional temporal_model_scores form field: a list of probabilities (0 to 1, max 3 decimals), one per bbox in the same order, like the crops. Each matched or created sequence receives the score of its own bbox, stored with engine as provenance in the existing temporal_api_version column, so no migration.
  • The validation worker applies TEMPORAL_MODEL_THRESHOLD to a device score instead of calling the temporal API. Above the threshold the sequence is validated as today (triangulation, notifications). Below it the sequence stays in the DB unvalidated and waits for the next frame, with no 10-frame window since the device scores a sliding window. The risk gate still applies first.
  • A stored temporal score only ever rises (same rule as max_conf), whatever its source: a lower device score arriving later, or under worker backlog, cannot hide a crossing of the threshold, and a frame without a score keeps the previous device verdict. The versions move with the score, so the triple always describes one scoring run. The worker's own verdict follows the stored maximum too, so a run that scored high and died before claiming is not lost on retry.
  • A device score reopens a sequence the API model had window_exhausted, so a device that starts scoring after the API gave up still gets its verdict judged.
  • set_temporal_score no longer commits: on POST /detections it is part of the single ingestion transaction (fix: commit multi-step CRUD workflows atomically #714), the worker commits explicitly.
  • pyroclient.create_detection gains the matching optional temporal_model_scores parameter and rejects non-finite values.

Comment thread src/app/models.py
TERMINAL_VALIDATION_STATUSES = (WINDOW_EXHAUSTED, VALIDATION_FAILED)
# sequences.temporal_api_version value for a score computed on the device and sent with the
# detection: the worker applies the threshold to it instead of calling the model.
TEMPORAL_SCORE_SOURCE_ENGINE = "engine"
@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.93%. Comparing base (726c3ee) to head (89ad370).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #723      +/-   ##
==========================================
+ Coverage   94.87%   94.93%   +0.05%     
==========================================
  Files          60       60              
  Lines        3279     3317      +38     
==========================================
+ Hits         3111     3149      +38     
  Misses        168      168              
Flag Coverage Δ
backend 95.07% <100.00%> (+0.04%) ⬆️
client 91.83% <100.00%> (+0.46%) ⬆️

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.

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

I think spotted 4 risks here (with Claude). This is from reading the code, I haven't run these scenarios, so tell me if I've missed something.

1. One scoreless frame can permanently kill a sequence, or trigger a false alert (detections.py, reset branch)
A single device blip resets the score to None, so the worker falls back to the API path:

  • Past MAX_FRAMES, if the API declines, the sequence becomes WINDOW_EXHAUSTED. That state is terminal, so later high device scores are stored but ignored, and a slow-growing fire may never alert.
  • If the API is unavailable, FAIL_OPEN_UNAVAILABLE validates and notifies, even if the device had been scoring the sequence low all along.

Possible fix: keep the last device verdict and only hand over to the API after N consecutive scoreless frames. I'd also let a device score revive a sequence exhausted this way, which would cover the PR's known limitation too.

2. A high score can be lost because the latest one wins (validation.py, device score branch)

  • Under backlog, with 0.9 then 0.2 queued before a claim, the worker never sees the 0.9.
  • After a failed alert attach, the retry re-reads the score and can drop a verdict that had already passed. The existing comment says a high score must never decay into a drop.

Possible fix: add a test for the attach retry first, then record that the threshold was crossed (for example, keep the max device score next to the latest one) and have the worker decide on that. This is probably one small column, so it would mean a migration.

3. A bad optional score loses the whole detection (client.py, create_detection)
NaN passes the client range check because both comparisons are false, so nan is sent and the API returns a 422. The frame and bboxes are lost because of an optional field.

Possible fix: reject non-finite values with math.isfinite, and have the engine send no scores for that frame rather than fail the upload. Any fix for #1 needs to treat that frame as a normal scoreless one.

4. The device score bypasses every other check
There's no MIN_FRAMES and no model call, so one float from a camera token can trigger triangulation and notifications.

  • A sequence can validate on its creation frame.
  • The Pi and API models share TEMPORAL_MODEL_THRESHOLD, but their scores may not be comparable.
  • The device model isn't versioned (temporal_model_version=None), so we can't tell which release produced a score or spot calibration drift.

Possible fix: send the model version with the scores and store it in temporal_model_version. I'd also check how many frames the engine uses early in a sequence, then either require a minimum there or apply MIN_FRAMES here. A separate threshold setting for device scores would let us tune the two models independently.

I'd treat #1 as the blocker. The others could be follow-ups if you'd rather keep this PR small.

@frgfm

frgfm commented Nov 2, 2026

Copy link
Copy Markdown
Member

The direction makes sense, but I’d suggest the source-handover behavior to be settled before merging. We should cover a device-scored sequence receiving a scoreless frame past the API window, with both available and unavailable API inference. Also we need to cover an API prediction completing after a newer device score arrives: the older result currently overwrites that evidence.

Let's try to make those transitions safe, include device model provenance/history assumptions, and fix the 0.9999 serialization boundary.

The engine may run the temporal smoke model itself and send its score with
the detection. Store it on the touched sequences with 'engine' as provenance
so the validation worker knows the sequence was already scored.
When the stored score came from the engine, apply the threshold to it
instead of calling the temporal API. No frame window: the engine scores a
sliding window and sends a fresh score with every frame, so a sequence below
threshold waits for the next one. The risk gate still applies.
A scored sequence that receives an unscored frame means the device's temporal
service failed open. Drop the stale device verdict so the worker falls back
to scoring the sequence itself.
The device scores each tracked object separately, so the detection route
now takes temporal_model_scores, a list aligned with bboxes like the crops,
and each matched or created sequence receives the score of its own bbox
instead of one score shared by every sequence of the request.
…-scored sequence

- a frame without a device score keeps the previous device verdict instead of
  sending the sequence back to the API path, where one scoreless frame could
  fail open into an alert or window-exhaust the sequence for good
- set_temporal_score keeps the max whatever the source, versions moving with
  the score in the same CASE; the worker's verdict follows the stored max too
- a device score reopens a window_exhausted sequence
- set_temporal_score no longer commits: part of the ingestion transaction,
  the worker commits explicitly
- the client rejects non-finite scores
@MateoLostanlen
MateoLostanlen force-pushed the feat/engine-temporal-score branch from 658cc6a to 98ccaa2 Compare November 3, 2026 16:57
@MateoLostanlen

Copy link
Copy Markdown
Member Author

Hi @fe51, thanks for the review.

  1. Confirmed, that was the real blocker. The reset is gone: a frame without a score keeps the previous device verdict, the sequence never falls back to the API path. A device score also reopens a window_exhausted sequence, which removes the known limitation.
  2. The stored score now only goes up, whatever the source (same rule as max_conf), and the worker judges on that max. No migration. For the attach retry: the verdict is already durable before the attach (claim_validation commits is_validated first), so the retry resumes without re-reading the score. test_attach_failure_past_window_does_not_window_exhaust covers it.
  3. Added math.isfinite in the client. NaN already raised a ValueError inside round, now the message is clear.
  4. No MIN_FRAMES here on purpose, the device scores its own window. Device model version and a separate threshold: agreed, I'd do them in a follow-up to keep this PR small.

@MateoLostanlen

Copy link
Copy Markdown
Member Author

Hi @frgfm, thanks.

Source handover: there is none anymore. A frame without a score keeps the device verdict, and a device score reopens a sequence the API had closed.
API prediction landing after a device score: the worker only calls the API after 4 frames with no device score at all, so this needs 4 missed frames in a row and then a recovery during the call. Even then the highest score wins and keeps its provenance, the API no longer overwrites anything.
The 0.9999 case is fixed by the rebase on #727, with a client test on 0.9996.

@MateoLostanlen
MateoLostanlen requested a review from fe51 November 4, 2026 08:20

@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 , the reset removal and the max rule address my main points. I checked them against the code, and you're right about the attach retry: claim_validation makes the verdict durable before the attach.

Tests
The behaviour @frgfm asked about is now handled in the code, but I'd add the two worker-level tests he mentioned. Both should be short with the existing helpers in test_temporal_validation.py:

  • A device-scored sequence past MAX_FRAMES that receives a scoreless frame, with the API available and then unavailable. Expected: no model call, no fail-open, no WINDOW_EXHAUSTED.
  • An API prediction landing after a higher device score, for example a mocked predict that stores a higher device score during the call. Expected: the device score and its provenance are kept.

Follow-up issue: device model version and threshold
Fine to keep this PR small. Could you open an issue covering:

  • the engine sending its model version, stored in temporal_model_version;
  • a separate threshold setting for device scores;
  • the minimum number of frames the engine scores at the start of a sequence, since MIN_FRAMES no longer applies here.
    what do you think ?

Edge case with the current trade-off
If the device stops sending scores for good in the middle of a sequence, frames keep arriving but the stored max stays below the threshold. The API never takes over and there's no fail-open, so a real fire on that sequence would never alert. It's an edge case and much less likely than the old single-blip one, so I don't think it should block this PR. I'd open an issue to handle it as simply as possible, for example:

  • store when the device last sent a score (e.g. a device_scored_at column);
  • in the worker, after N frames without a device score (e.g. MIN_FRAMES), take the API path on the last MAX_FRAMES frames;
  • in that case, skip the WINDOW_EXHAUSTED rule based on the old device score.
    Failing open there would be acceptable because it only happens after N missed frames, not after a single one. What do you think ?

Happy to approve once the two tests are in.

…e sequence

The worker re-reads the provenance after the model phase: when a device score
arrived meanwhile and won the max, the job is finished with the conditional
frame-count finish and the device branch judges it on the next run, instead of
failing open, validating or window-exhausting on the API's verdict.

Tests asked in review: a device-scored sequence past MAX_FRAMES receiving a
scoreless frame (API available and unavailable), and a device score landing
during the API call (declined and unavailable, in and past the window), plus
the API score winning over a lower device score.
@MateoLostanlen

Copy link
Copy Markdown
Member Author

Thanks @fe51. Both tests are in (89ad370), plus a third one where the API score beats a lower device score. Writing the second test showed a gap: a device score landing while the API model runs could still end in a fail-open or a window_exhausted on the API’s verdict. The worker now re-reads the provenance after the model phase and lets the device branch judge the sequence on the next run.

Follow-ups opened: pyronear/pyro-api#737 for the model version, a separate threshold and the minimum frames, pyronear/pyro-api#736 for handing a sequence back to the API when the device stops scoring, with your proposal and an alternative where the engine signals the fail-open explicitly.

@MateoLostanlen
MateoLostanlen requested a review from fe51 November 4, 2026 10:10

@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 thanks for adding the test , Goot to me

@MateoLostanlen
MateoLostanlen merged commit 830228f into main Nov 6, 2026
25 of 26 checks passed
@MateoLostanlen
MateoLostanlen deleted the feat/engine-temporal-score branch November 6, 2026 08:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants