Skip to content

Fix #768: TinyUfo weight underflow panic from evict race condition#823

Open
cobyfrombrooklyn-bot wants to merge 1 commit intocloudflare:mainfrom
cobyfrombrooklyn-bot:fix-issue-768
Open

Fix #768: TinyUfo weight underflow panic from evict race condition#823
cobyfrombrooklyn-bot wants to merge 1 commit intocloudflare:mainfrom
cobyfrombrooklyn-bot:fix-issue-768

Conversation

@cobyfrombrooklyn-bot
Copy link

A race condition exists in TinyUfo where one thread evicts an item (subtracting its weight via fetch_sub) before another thread finishes adding the weight after insertion. This causes the atomic usize to underflow (wrap to usize::MAX), which then triggers attempt to add with overflow panic in evict_to_limit.

Fix

  1. Replaced all 4 fetch_sub calls on small_weight and main_weight with fetch_update using saturating_sub - prevents underflow from wrapping.
  2. Used saturating_add in evict_to_limit weight comparison - prevents overflow when summing weights.

This is a minimal, lock-free fix that preserves the existing concurrent design.

Tests

Added two tests:

  • test_weight_saturating_sub_no_underflow: Directly verifies that weight atomics handle underflow gracefully by setting weight to 0 then subtracting, and that evict_to_limit handles near-usize::MAX weights without panicking.
  • test_concurrent_put_no_overflow_panic: Stress test with 20 threads doing concurrent put/get operations (reproduces the original race from the issue).

All 16 TinyUfo tests pass on macOS ARM (Apple Silicon).

Fixes #768

…anic

A race condition exists where one thread evicts an item (subtracting
its weight) before another thread finishes adding the weight after
insertion. This causes fetch_sub to underflow the atomic usize,
wrapping to usize::MAX, which then causes 'attempt to add with
overflow' panic in evict_to_limit.

Replace all fetch_sub on weight atomics with fetch_update using
saturating_sub, and use saturating_add in evict_to_limit's weight
comparison. This prevents the underflow without adding locks.

Fixes cloudflare#768
@drcaramelsyrup drcaramelsyrup added the bug Something isn't working label Feb 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TinyUfo: evict race condition updating weights

2 participants