Skip to content

fix(limit): serialize token bucket updates - #519

Closed
UfukNode wants to merge 1 commit into
flop-labs:mainfrom
UfukNode:guard-token-bucket
Closed

UfukNode wants to merge 1 commit into
flop-labs:mainfrom
UfukNode:guard-token-bucket

Conversation

@UfukNode

@UfukNode UfukNode commented Aug 30, 2026 •

Copy link
Copy Markdown

What

Serialize each token-bucket read/update/write and refund with a leaf lock. The bucket clock is sampled after entering that lock.

Why

Starlette runs synchronous routes in a thread pool. Parallel requests from one IP could all read the same balance, all be admitted, and overwrite one another's decrements. Refunds could lose updates the same way.

The first version sampled time before acquiring the lock. A thread holding an older sample could enter after a newer one, apply a negative refill interval, rewind the bucket timestamp and return an inflated wait. Sampling inside the critical section keeps mutation order and clock order aligned.

The tests force all three interleavings rather than relying on scheduler luck: concurrent grants, concurrent refunds, and reversed lock entry after clock sampling.

Checks

  • 667 passed, 1 skipped; 98.01% coverage
  • Ruff, format and ty checks pass
  • Core size remains at its 2256-line baseline
  • No API change or new public surface

sv pushed a commit that referenced this pull request Aug 30, 2026
… lru_cache

The three memo caches behind /rooms — store._window_memo, store._topics_memo and
app._rooms_cache — were hand-rolled OrderedDict LRUs with no lock, read and written
from Starlette's threadpool. Each carried the same two bugs (a KeyError when a
concurrently evicted key is promoted after a hit; a lost update on the insert path),
and each was being fixed site by site with a rearrangement of the same unguarded
read-modify-write. This replaces the pattern instead of patching the sites.

All three validated a stamp stored *beside* the value. The stamp moves into the KEY,
so validity is no longer something to find and check: a superseded entry is a key
nobody looks up. There is no get-then-promote and no pop-then-insert left, and the
bookkeeping that remains is functools.lru_cache's own, which is documented threadsafe.
No correctness claim here rests on GIL scheduling, and the diff contains no unguarded
read-modify-write on shared state. stdlib throughout; no new dependency.

- store._cached_window: @lru_cache(maxsize=_WINDOW_MEMO_MAX) keyed
  (str(root), name, (mtime_ns, size)). Returns the nick window as a tuple — one entry
  is handed to every thread and outlives all of them; the callers were audited and
  mutate nothing, and _unanswered/_engagement/_rollup now take Sequence[str].
- store._cached_topic: one entry per room under an LRU, where it was a single mutable
  slot any mismatched stamp reset, so two /rooms callers straddling a topic write reset
  each other on every one of their ~50 lookups and neither ever hit.
- app._rooms_view: splits into _rooms_payload (the walk) and _rooms_walk (that under
  the LRU), keyed (limit, stamp, bucket).

The two TTL'd caches encode the clock as a coarse bucket in the key (store._time_bucket).
A bucket boundary can only move an expiry *earlier* than the entry's own insertion would
have — an entry gets the tail of the window it landed in, never more than a full window —
so the published staleness bounds still hold; it is checked at the boundary in
test_a_bucket_boundary_can_only_expire_an_entry_sooner_than_its_own_window. A ttl of 0
bypasses the cache entirely rather than dividing by zero, including for entries created
while the knob was positive: reading NOTE_STATS_CACHE_SECONDS per call keeps disabling an
existing entry, and nothing is evicted for it.

Responses are byte-identical; _rooms_stamp's ordering essay is rewritten for the new
mechanism rather than dropped, and ROOMS_STAMP_KEYS is untouched. Net core code lines
-11 (app.py -3, store.py -8), and sz-baseline.json carries the new floor
(`uv run sz.py --update-baseline`, which leaves the caps untouched) so the ratchet moves
down with the shrink. The caps are unchanged and now have headroom; tightening them is a
policy call, not this change's to make.

Supersedes: #376, #229, #515, and the _window_memo half of #451/#458 (their _buckets
half is limit.py's, out of scope here and left to #519/#486).

New tests, tests/unit/test_memo_caches.py — barrier-instrumented, no sleeps, in the
style of #519: every worker parked inside a miss over a cache already filled to its
bound, for each of the three caches, asserting the value returned belongs to the key
asked for; the #515 thrash measured as "a warm cache re-reads no topic, however many
threads ask under whichever generation"; and staleness end to end, a write moving the
key so the next walk is the fresh view.

Existing tests that reached into the deleted internals, adapted (bodies otherwise
unchanged):

- tests/_client.py — `_rooms_cache.clear()` becomes cache_clear() on all three caches,
  and the fixture pins store._time_bucket to its own start. Validity is key material
  now, so a window boundary cut on a free-running clock would land inside roughly one
  test per ROOMS_CACHE_SECONDS of suite time and make a pinned-60s test miss for a
  reason no test body could name.
- tests/http/test_stats.py, tests/test_mcp.py, tests/capacity_bench.py — the same
  clear() -> cache_clear() rename (and the bench's comment naming it).
- tests/http/test_rooms.py::test_rooms_cache_can_be_disabled_and_never_grows_past_its_bound
  — `== {}` becomes cache_info().currsize == 0; maxsize is fixed at build time, so the
  MAX_ROOMS_CACHE monkeypatch is replaced by a real flood of MAX_ROOMS_CACHE + 8 limits.
- tests/http/test_rooms.py::test_a_lost_counter_bump_costs_one_window_and_not_the_listing
  — ageing an entry's stored expiry becomes moving the bucket, which is where the window
  lives now. Same claim, same absence of a sleep.
- tests/http/test_rooms.py::test_a_rewalked_entry_is_the_newest_and_the_oldest_is_what_leaves
  — rewritten as test_a_used_entry_is_the_newest_and_the_coldest_is_what_leaves. Its
  subject was the pop-then-insert convention, which no longer exists, and its documented
  policy has changed: ordering is by last *use*, so a cycling caller can no longer push
  out a `limit` it hits on every request. The new body asserts that policy and the bound.
- tests/unit/test_store.py::test_room_windows_are_memoized_against_the_stat_the_walk_already_does
  — adds a cache_clear() for isolation; the `_WINDOW_MEMO_MAX = 1` monkeypatch (maxsize
  is not settable) becomes an assertion that a superseded stat lingers and maxsize is
  what bounds it. Eviction past the bound is covered under threads in the new file.

Gates: ruff check, ruff format --check, ty check, 495 passed, coverage 97.32%,
sz.py --caps within every cap.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y54d6g7WuFL3Su1JLxqwHb
sv added a commit that referenced this pull request Aug 30, 2026
… lru_cache (#534)

* refactor(cache): retire the hand-rolled memo LRUs for validity-in-key lru_cache

The three memo caches behind /rooms — store._window_memo, store._topics_memo and
app._rooms_cache — were hand-rolled OrderedDict LRUs with no lock, read and written
from Starlette's threadpool. Each carried the same two bugs (a KeyError when a
concurrently evicted key is promoted after a hit; a lost update on the insert path),
and each was being fixed site by site with a rearrangement of the same unguarded
read-modify-write. This replaces the pattern instead of patching the sites.

All three validated a stamp stored *beside* the value. The stamp moves into the KEY,
so validity is no longer something to find and check: a superseded entry is a key
nobody looks up. There is no get-then-promote and no pop-then-insert left, and the
bookkeeping that remains is functools.lru_cache's own, which is documented threadsafe.
No correctness claim here rests on GIL scheduling, and the diff contains no unguarded
read-modify-write on shared state. stdlib throughout; no new dependency.

- store._cached_window: @lru_cache(maxsize=_WINDOW_MEMO_MAX) keyed
  (str(root), name, (mtime_ns, size)). Returns the nick window as a tuple — one entry
  is handed to every thread and outlives all of them; the callers were audited and
  mutate nothing, and _unanswered/_engagement/_rollup now take Sequence[str].
- store._cached_topic: one entry per room under an LRU, where it was a single mutable
  slot any mismatched stamp reset, so two /rooms callers straddling a topic write reset
  each other on every one of their ~50 lookups and neither ever hit.
- app._rooms_view: splits into _rooms_payload (the walk) and _rooms_walk (that under
  the LRU), keyed (limit, stamp, bucket).

The two TTL'd caches encode the clock as a coarse bucket in the key (store._time_bucket).
A bucket boundary can only move an expiry *earlier* than the entry's own insertion would
have — an entry gets the tail of the window it landed in, never more than a full window —
so the published staleness bounds still hold; it is checked at the boundary in
test_a_bucket_boundary_can_only_expire_an_entry_sooner_than_its_own_window. A ttl of 0
bypasses the cache entirely rather than dividing by zero, including for entries created
while the knob was positive: reading NOTE_STATS_CACHE_SECONDS per call keeps disabling an
existing entry, and nothing is evicted for it.

Responses are byte-identical; _rooms_stamp's ordering essay is rewritten for the new
mechanism rather than dropped, and ROOMS_STAMP_KEYS is untouched. Net core code lines
-11 (app.py -3, store.py -8), and sz-baseline.json carries the new floor
(`uv run sz.py --update-baseline`, which leaves the caps untouched) so the ratchet moves
down with the shrink. The caps are unchanged and now have headroom; tightening them is a
policy call, not this change's to make.

Supersedes: #376, #229, #515, and the _window_memo half of #451/#458 (their _buckets
half is limit.py's, out of scope here and left to #519/#486).

New tests, tests/unit/test_memo_caches.py — barrier-instrumented, no sleeps, in the
style of #519: every worker parked inside a miss over a cache already filled to its
bound, for each of the three caches, asserting the value returned belongs to the key
asked for; the #515 thrash measured as "a warm cache re-reads no topic, however many
threads ask under whichever generation"; and staleness end to end, a write moving the
key so the next walk is the fresh view.

Existing tests that reached into the deleted internals, adapted (bodies otherwise
unchanged):

- tests/_client.py — `_rooms_cache.clear()` becomes cache_clear() on all three caches,
  and the fixture pins store._time_bucket to its own start. Validity is key material
  now, so a window boundary cut on a free-running clock would land inside roughly one
  test per ROOMS_CACHE_SECONDS of suite time and make a pinned-60s test miss for a
  reason no test body could name.
- tests/http/test_stats.py, tests/test_mcp.py, tests/capacity_bench.py — the same
  clear() -> cache_clear() rename (and the bench's comment naming it).
- tests/http/test_rooms.py::test_rooms_cache_can_be_disabled_and_never_grows_past_its_bound
  — `== {}` becomes cache_info().currsize == 0; maxsize is fixed at build time, so the
  MAX_ROOMS_CACHE monkeypatch is replaced by a real flood of MAX_ROOMS_CACHE + 8 limits.
- tests/http/test_rooms.py::test_a_lost_counter_bump_costs_one_window_and_not_the_listing
  — ageing an entry's stored expiry becomes moving the bucket, which is where the window
  lives now. Same claim, same absence of a sleep.
- tests/http/test_rooms.py::test_a_rewalked_entry_is_the_newest_and_the_oldest_is_what_leaves
  — rewritten as test_a_used_entry_is_the_newest_and_the_coldest_is_what_leaves. Its
  subject was the pop-then-insert convention, which no longer exists, and its documented
  policy has changed: ordering is by last *use*, so a cycling caller can no longer push
  out a `limit` it hits on every request. The new body asserts that policy and the bound.
- tests/unit/test_store.py::test_room_windows_are_memoized_against_the_stat_the_walk_already_does
  — adds a cache_clear() for isolation; the `_WINDOW_MEMO_MAX = 1` monkeypatch (maxsize
  is not settable) becomes an assertion that a superseded stat lingers and maxsize is
  what bounds it. Eviction past the bound is covered under threads in the new file.

Gates: ruff check, ruff format --check, ty check, 495 passed, coverage 97.32%,
sz.py --caps within every cap.



* test(cache): put the #515 regression in the interleaving the issue reported

The topic-thrash test walked the two stamp generations in two blocks. The reported
shape is room-major — two threadpool /rooms requests alternating on every lookup — and
that is the order one shared slot is worst in: it resets on all 48 lookups of a pass and
hits zero times, where the blocked order resets twice. Both orders fail against the old
cache and pass against this one, so this changes no verdict; it makes the test a
statement about the bug that was filed rather than about a rearrangement of it.

Checked against main in a scratch worktree: PR #515's own test, run verbatim there,
re-reads all ten topics on its second pass. On this branch it re-reads none.

@jokazza84 jokazza84 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I reproduced the original lost-update race and independently checked this exact head (8e1aeb9f3faf44e0161687af7a3b9d079d4f9a04). The new lock correctly makes the two submitted regression tests pass, but take() still samples time.monotonic() before acquiring that lock. Lock acquisition order is not guaranteed to match sampling order, so an older sample can mutate the bucket after a newer one.

A deterministic reversed-entry schedule produced this on the PR head:

waits=[0.0, 11.0] balance=-10.000000 last=10.000000

The correct result for the same one-token bucket is:

waits=[0.0, 1.0] balance=0.000000 last=20.000000

The stale sampler applies a negative refill interval, returns an inflated wait, and rewinds last. Moving now = time.monotonic() inside with _buckets_lock:, immediately before _buckets.get(...), fixes the schedule. With that one-line move:

  • the two submitted tests remain 2/2 PASS;
  • the independent timestamp-order regression passes;
  • bucket mutation order and timestamp order agree.

Reproduction provenance:

  • base 169ca890e8bec70eef1541ca3f0c6ec09c36d6f3: submitted regression tests 0/2, both original races reproduced;
  • head 8e1aeb9f3faf44e0161687af7a3b9d079d4f9a04: submitted tests 2/2, repeated five times;
  • independent regression SHA-256: b9d2f737da97731d60db6a0bfce29bbb61974b22d5e38d4af41a72f30f17b04f.

I materialized the exact GitHub versions of limit.py, config.py, and the submitted test; unrelated Starlette/store imports were stubbed for this focused harness. I am not claiming a full-suite pass: the Actions run for this head currently reports action_required.

Comment thread src/limit.py
_buckets.move_to_end((ip, kind))
while len(_buckets) > max_buckets:
_buckets.popitem(last=False)
with _buckets_lock:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

now is sampled before this lock. A thread that sampled earlier can acquire after a newer sampler, making (now - last) negative, rewinding last, and inflating the wait. Please move now = time.monotonic() inside this block, immediately before _buckets.get(...); the submitted tests still pass and a deterministic reversed-entry regression changes from wait=11, balance=-10, last=10 to wait=1, balance=0, last=20.

@UfukNode UfukNode changed the title fix(limit): guard the token bucket so a burst from one IP cannot overdraft it fix(limit): serialize token bucket updates Sep 4, 2026
@UfukNode

UfukNode commented Sep 4, 2026

Copy link
Copy Markdown
Author

Addressed the review on current main. The clock is now sampled inside the bucket lock, and a deterministic reversed-entry test covers the stale-sample case alongside the grant and refund races. I also removed the now-incorrect comment that described buckets as intentionally unlocked. Full suite: 667 passed, 1 skipped; Ruff, formatting, ty and size caps pass.

Copy link
Copy Markdown

One remaining edge case in refund() is that it can recreate an evicted bucket without re-applying the LRU bound.

take() enforces while len(_buckets) > max_buckets: popitem(...), but _settle_room_budget() may call refund() later, after the charged (ip, "create") entry has been evicted by other traffic. On that missing-key path, refund() defaults to a full bucket and inserts the key, but it neither moves it to the LRU end nor enforces MAX_BUCKETS. A sufficiently large set of in-flight room-creation requests can therefore finish/refund after their keys were evicted and grow _buckets above the bound that is meant to cap memory; no later take() is required for those inserts.

Could refund() preserve the same capacity/LRU invariant as take() when it has to recreate a missing key? A focused regression can seed a full small-cap map, evict the charged key, refund it, and assert the map remains within the cap.

sv commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Triage: closing as a duplicate of #163.

Four open PRs fix the same race the same way — a module-level threading.Lock wrapped around the _buckets read-modify-write in both take() and refund(), with the time.monotonic() sample moved inside the lock: #163, #420, #519, #691. The diffs against src/limit.py are near-identical.

Keeping #163 as the one to review: it is the earliest of the four (2026-08-25), it covers both take() and refund(), and it merges cleanly against main.

Per CONTRIBUTING's "Overlapping work", the useful next step is to review or build on #163 rather than carry a parallel branch. Two things here are worth carrying over: tests/unit/test_token_bucket.py, and the correction to the _dupes comment that stops claiming the buckets are the unlocked structure. Reopen if a maintainer prefers this implementation.


Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants