fix: free expired states promptly and drop disk manager locks on purge

Merged
FA
2mo ago
+197-12

Summary

Two memory-lifetime bugs in the state managers. Both were measured on main at b7dd25a6d with a real app: prod backend, one granian worker, REFLEX_REDIS_TOKEN_EXPIRATION=30, 500 hydrated websocket sessions, then disconnect and wait past expiry. Expiry itself works: the memory manager's states, _token_expires_at and _states_locks all drop from 500 to 0 about 30 s after the last touch.

Bug A: purged state trees wait for a cyclic GC (memory and disk managers)

A purge only popped the token's entries from states/_states_locks/_token_expires_at. Each state tree has reference cycles (parent_state <-> substates), so reference counting does not free the popped tree. On an idle server the cyclic GC does not run, so the trees stay in memory indefinitely. Measured: 3,500 BaseState instances (7 per session) still alive after the purge, about 13 MB for 500 sessions. gc.collect() frees them all.

Fix: a new private helper _release_state_tree in reflex/istate/manager/__init__.py clears the substates dicts of the purged tree (depth first). That removes every downward edge, so reference counting frees the tree right away. parent_state is the only upward link on BaseState, and clearing the downward links is enough to break every cycle. Each root is created per token, so no other token shares the tree. Only purged, unlocked tokens are released. The helper does not call gc.collect().

Bug B: StateManagerDisk._states_locks grows without bound

The disk manager's write-queue loop popped _token_last_touched and states for expired tokens, but never _states_locks. One lock per expired token stayed forever (measured: 500 locks remained after expiry).

Fix: StateManagerDisk._purge_token now pops the lock and releases the state tree, like StateManagerMemory._purge_token. To make the lock pop and the tree release safe, the disk expiry now uses the same rules as the memory manager:

  • _token_last_touched stores (time, token), so the loop can find the token's lock_key. For non-BaseStateToken tokens, lock_key is different from cache_key.
  • A token whose lock is held is skipped. Before, its state was popped while a modify_state holder was still using it.
  • A token with a pending debounced write is skipped until the write finishes. When token_expiration is less than the write debounce, the queued item holds the same tree, and a release before the write would drop its substates from the disk.
  • set_state refreshes the token's expiration window, like the memory manager does. A lock that was just released is then never expired in the gap before a queued waiter acquires it. Popping it in that gap would let a new modify_state create a second lock.
  • When debounce is disabled, the loop sleeps until the next expiration of an unlocked token. Otherwise a token that is still locked after its expiry would make the sleep negative and the loop would spin.

Redis manager

StateManagerRedis has the same pattern only in its local oplock cache. _cached_states entries are popped when the lease breaks (after oplock_hold_time_ms) and are handed to set_state without breaking their cycles. _cached_states_locks is never pruned; there is an existing # TODO: clean up the cached states locks periodically. Both only apply when oplock leases are in use. The states are short-lived, and the locks are the same small leak as Bug B. This PR does not change the Redis manager. The lock pruning there interacts with the lease and contention handlers, so it should be a separate follow-up.

Context

This complements the reflex-bench memory benchmark work (#7292, memory.per_session), which observed the residual. Most of the remaining post-expiry resident memory (about 70 MB per 500 sessions) is granian's jemalloc, which does not return freed pages on an idle worker. About 24 MB is pymalloc arena fragmentation. Both are out of scope here.

Tests

New tests in tests/units/istate/manager/test_expiration.py. Each one failed before the fix and passes after it:

  • test_memory_state_manager_frees_expired_state_tree: with the cyclic GC disabled, weakrefs to the root and a substate are dead once the token expires.
  • test_disk_state_manager_evicts_expired_lock_and_state_tree: the expired token's lock is gone from _states_locks, and the root and substate are dead with the GC disabled.
  • test_disk_state_manager_keeps_held_token: a token whose lock is held past its expiry keeps its state and lock, and it is purged after release.
  • test_disk_state_manager_set_state_refreshes_expiration: set_state moves the last-touched time forward.
  • test_disk_state_manager_writes_expired_pending_state_tree: a tree that expires while its debounced write is pending is still written with its substates. This test fails if the pending-write guard is removed.

Checks

  • uv run pytest tests/units: 8343 passed, 18 skipped
  • uv run pytest tests/units/istate tests/units/test_state.py -q: 265 passed
  • uv run ruff check .: clean
  • uv run ruff format --check .: clean
  • uv run pyright reflex tests: 0 errors
  • uv run pre-commit run --files <changed files>: all passed

Note: running tests/units/istate tests/units/test_state.py tests/units/test_app.py together in one process gives 13 test_app.py failures. These failures are the same on unmodified main (a test-order interaction). The full tests/units run passes.