Skip to content

fix(cameras): cascade camera deletion to its history and stored images - #744

Merged
MateoLostanlen merged 4 commits into
pyronear:mainfrom
Majyles:feat/camera-deletion-cascade
Nov 19, 2026
Merged

MateoLostanlen merged 4 commits into
pyronear:mainfrom
Majyles:feat/camera-deletion-cascade

Conversation

@Majyles

@Majyles Majyles commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Part of #541 (camera deletion; organization deletion will follow in a separate PR).

Problem

DELETE /cameras/{id} returned a 500 as soon as the camera had poses, sequences or detections (poses_camera_id_fkey violation).

Changes

  • Cascading foreign keys (model + migration 94a223eae6ac): poses, sequences and detections → cameras, occlusion_masks → poses, alerts_sequences → sequences. The downgrade restores the previous constraints.
  • Alerts: the route collects the alerts holding a sequence of the camera before deleting it, then calls refresh_alert_state on each one, in the same transaction. Alerts left empty are deleted (with their shares, via the existing cascade); the others get their bounds and location recomputed from the remaining cameras.
  • Stored objects: after the commit, the camera's last image, pose images, detection frames and crops are deleted from the organization's bucket, except keys still referenced by another row. Deletion uses delete_objects in batches of 1000 (new S3Bucket.delete_files). A storage failure is logged and does not fail the request, since the rows are already gone.
  • Side effect: deleting a pose now also deletes its occlusion masks (occlusion_masks.pose_id cascades). A pose with detections or sequences still cannot be deleted, see the question below.

Tests

  • History removed: the camera's poses, masks, sequences, detections are deleted; an alert only fed by this camera is deleted with its share; an alert shared with another camera is kept and recomputed; the other camera's data is untouched.
  • Stored objects removed, the other organization's object kept.
  • Storage failure does not fail the deletion.

The three tests fail on main with the foreign key error. Locally: full suite passes, migration upgrade/downgrade/upgrade checked (pg_constraint.confdeltype), alembic check clean.

Notes for review

  • Migration locks: recreating the foreign keys validates existing rows, which locks the tables for writes during the scan. This should be quick, but could be noticeable on a large detections table. If needed, the constraints could be added as NOT VALID and then validated separately.
  • Out of scope, question: DELETE /poses/{id} still fails when the pose has detections or sequences (detections.pose_id is non-nullable). Should the history be deleted, detached, or should poses with history only be deactivated through active (returning a 409 instead of a 500)? Happy to handle it in a follow-up.

Generated with Claude Code

Deleting a camera with poses, sequences or detections failed on a foreign
key (500). The foreign keys to cameras, and those of occlusion masks and
alert links, now cascade. The route recomputes the alerts that held a
sequence of the camera (deleting those left empty) in the same transaction,
then deletes the stored images and crops that no row references anymore.

Part of pyronear#541.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.78%. Comparing base (156fec7) to head (3ce857a).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #744      +/-   ##
==========================================
+ Coverage   95.73%   95.78%   +0.04%     
==========================================
  Files          65       65              
  Lines        3732     3768      +36     
==========================================
+ Hits         3573     3609      +36     
  Misses        159      159              
Flag Coverage Δ
backend 95.94% <100.00%> (+0.04%) ⬆️
client 91.83% <ø> (ø)

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.

The fixture frames all share a key that camera 2 keeps, so the failure
test never reached the patched deletion. Camera 1 now gets a key of its
own, and the test asserts the deletion is attempted. Also cover the
batching and error logging of S3Bucket.delete_files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

Hi @Majyles, thanks for the PR! Clean approach and nice tests.

  • Please wrap the DB part of delete_camera (reading alert ids through the commit) in _organization_alert_lock(camera.organization_id), like label_sequence does. Otherwise a validation run can attach a sequence of this camera to a new alert in between, and that alert ends up empty forever.
  • Please add an index on alerts_sequences.sequence_id (model + migration). The PK starts with alert_id, so each cascaded sequence delete scans the whole table, which gets slow for old cameras.
  • (nit) Bucket keys start with the camera id and ids are never reused, so the "still referenced" check could be dropped. At least crops only need checking against crop_bucket_key, which has no index.
  • (nit) Worth noting in the description that deleting a pose now also deletes its occlusion masks.

Happy to merge once the first two points are fixed.

Majyles and others added 2 commits November 18, 2026 16:36
…eletion

Address review:
- run the DB part of the deletion under the organization alert lock, so a
  validation run cannot attach a sequence of the camera to a new alert
  between the read of its alerts and the commit (that alert would stay empty)
- index alerts_sequences.sequence_id: the primary key starts with alert_id
  and cannot serve the cascade's lookups by sequence
- delete the camera's objects without checking references: every key starts
  with the camera id, and ids are never reused
- rebase the migration onto a9c2e5f7b1d3

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Majyles

Majyles commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review! All four points are addressed:

  1. Lock: the DB part of delete_camera (reading the alert ids through the commit) now runs under _organization_alert_lock(camera.organization_id). A new test holds the lock and checks the deletion waits for it. No deadlock risk with the worker as far as I can see: claim_validation commits before the worker takes the lock.
  2. Index: ix_alerts_sequences_sequence_id added in the model and the migration (dropped on downgrade).
  3. Referenced check: dropped. delete_unreferenced_objects is replaced by a plain delete_objects(organization_id, bucket_keys), since every key starts with the camera id.
  4. PR description: updated with the occlusion mask side effect.

I also merged main and rebased the migration onto a9c2e5f7b1d3 (#741), to keep a single head.

@MateoLostanlen MateoLostanlen 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 @Majyles, all four points look good. Approving!

@MateoLostanlen
MateoLostanlen merged commit 4eb17f5 into pyronear:main Nov 19, 2026
22 checks passed
@Majyles
Majyles deleted the feat/camera-deletion-cascade branch November 19, 2026 16:31
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.

2 participants