Skip to content

fix(images): only delete an image object once no camera, pose or detection uses its key - #734

Merged
MateoLostanlen merged 7 commits into
pyronear:mainfrom
Adelagric:fix/s3-key-shared-images
Nov 7, 2026
Merged

MateoLostanlen merged 7 commits into
pyronear:mainfrom
Adelagric:fix/s3-key-shared-images

Conversation

@Adelagric

Copy link
Copy Markdown
Contributor

Fixes #733.

PATCH /cameras/image, PATCH /poses/{pose_id}/image and DELETE /detections/{detection_id} now update the row first. They then delete the old S3 object only if no camera (last_image), pose (image) or detection (bucket_key) still references its key. The check is delete_unreferenced_image in services/images.py. It extends to all three tables the check that DELETE /detections/{detection_id} already made among detections.

  • Updating first also covers the same-second retry: the updated row references the key again, so the object is kept.
  • A shared object is deleted once its last reference moves on, so nothing is left behind in the bucket.
  • The key format does not change, and there is no migration. Rows that already share a key in production are protected too.
  • If the deletion fails, the request still succeeds: the row already points to the new image, so the error is logged as a warning.

I first considered prefixing camera and pose keys, as crop_ does. That stops new collisions, but keys already shared in the database have no prefix, so their first replacement after deploy would still delete them.

Tests (test_cameras.py, test_poses.py, test_detections.py)

  • 7 fail on main and pass here:
    • the same image twice in one second, for a camera and for a pose;
    • a camera image, then a pose image, from one frame;
    • two poses with one image;
    • a detection frame, then a last image;
    • an admin deleting a detection that shares the camera's image.
      test_update_pose_image_twice now also asserts that the object exists.
  • 3 pass on both and guard the cleanup: a replaced image is still deleted, and a frame shared by sibling detections is deleted with the last one.
  • 1 checks that a failed deletion still returns 200.

Full suite: 735 passed, 1 skipped. ruff check, ruff format --check and ty check are clean. Each of these changes makes at least one test fail: removing any of the three reference checks, always or never deleting, reading the key after the update, or dropping the error handling.

Not changed

  • Two crops with the same bytes, from two requests in the same second, can share a key, and DELETE /detections/{detection_id} deletes crop_bucket_key without checking.
  • Two simultaneous PATCH requests on the same camera or pose can still race between the check and the delete. The window is narrower than on main, which always deletes.
  • cameras.last_image and poses.image have no index, so the check scans those two tables. They are small, and the check runs once per image update.

@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.33%. Comparing base (b5ee45d) to head (dcb3c5b).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #734      +/-   ##
==========================================
+ Coverage   95.18%   95.33%   +0.14%     
==========================================
  Files          60       61       +1     
  Lines        3407     3428      +21     
==========================================
+ Hits         3243     3268      +25     
+ Misses        164      160       -4     
Flag Coverage Δ
backend 95.48% <100.00%> (+0.15%) ⬆️
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.

@MateoLostanlen

Copy link
Copy Markdown
Member

Thanks, this is the right fix and the tests are solid.

Two things on DELETE /detections before merging:

  • crop_bucket_key has the same deterministic key format, so two detections in the same second can share a crop. The crop is still deleted unconditionally. Could you route it through the same reference check?
  • The crop is deleted before detections.delete(), which is the ordering this PR fixes for the frame. Worth moving it after the row delete too.

Minor: delete_unreferenced_image only catches ClientError. A connection error (S3 unreachable) still returns a 500 after the row was committed. Catching botocore.exceptions.BotoCoreError as well would cover it.

… uses its key

A failed object deletion now only logs a warning on a connection error too, and on a bucket
that can't be reached before it is cached.
@Adelagric

Copy link
Copy Markdown
Contributor Author

All three are in, in 653fd3e (tests) and 9397e44 (fix).

  • Crop references. The crop now goes through a new delete_unreferenced_crop, which looks at crop_bucket_key. I kept it apart from delete_unreferenced_image because that column has no index: checking it there would scan detections on every PATCH /cameras/image, and crop keys have their own prefix, so only another crop can share one.
  • Order. The crop is deleted after the row. If the row deletion fails, the crop and the frame both stay.
  • Errors. BotoCoreError is caught, and so is ValueError, which you didn't ask for: S3Bucket.__init__ turns connection and client errors into ValueError, so a worker without the bucket in cache would still have returned a 500. The side effect is that a missing bucket or a lasting access refusal now only logs a warning here. A failure on the crop doesn't stop the frame's deletion.

I also ran DELETE /detections with a real boto client pointed at a closed port, with the bucket cached and not cached: 200, row deleted, objects left behind.

Three things I left out, tell me if you want any of them here:

  1. No index on crop_bucket_key. A crop nobody else uses finds no row, so LIMIT 1 doesn't help and the check scans detections. It's an admin route and I haven't measured the cost on a real table. An index would need a migration.
  2. S3 calls still block the event loop, as they did before this PR. In the closed-port run, one request took 21 to 23 s and blocked the loop for up to 13 s at a time. Trying the frame after a failed crop adds a second wait. to_thread, as in cameras.py, would avoid it.
  3. A narrow race. A DELETE can remove a crop shared with a POST whose row isn't committed yet. It takes the same crop in the same second, and I haven't reproduced it.

@Adelagric

Adelagric commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

CI note: pytest-client failed on test_client_constructor, the 0.00001 s timeout case (DID NOT RAISE ReadTimeout). This PR doesn't touch client/, and feat/camera-angle-of-view had the same failure on October 18, so it looks timing-related.

Edit: it passed on 0849ed2 after merging main, so no re-run is needed. The flaky test itself is being fixed in #740. On that same commit, client (macos-latest, 3.11) was cancelled without getting a runner; it isn't a required check.

@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 @Adelagric, thanks for the PR!

All three points are in, and the crop handling looks good. Catching ValueError too makes sense.

  • I merged main into your branch to fix the import conflict in detections.py (#673 switched to compute_overlap_async).
  • (nit) Agreed on leaving the crop_bucket_key index and to_thread for a follow-up PR. The admin delete route is rare, so it can wait.

CI is green, merging.

@MateoLostanlen
MateoLostanlen merged commit 8167f1c into pyronear:main Nov 7, 2026
22 checks passed
@Adelagric
Adelagric deleted the fix/s3-key-shared-images branch November 25, 2026 14:06
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.

Replacing a camera or pose image can delete an image that is still in use

2 participants