Use atomic Swoole Table operations for shared framework state

Merged
BI
2d ago
+615-317

Contribution type

  • Bug fix

Problem and change

This PR fixes races using the atomic row operations in Swoole 6.3 in the Swoole cache, Reverb, and the rate limiter. The framework already requires a version of Swoole that provides these methods.

Cache

A flush could report success and leave entries behind. Swoole iterates through colliding keys by position. Deleting one row during the scan moves the next row into its place, and the iterator can skip it. Both cache and lock flushes now collect the matching keys first, then delete them while writers are still excluded.

Stale cleanup compares the expiration or lock payload it observed before deleting a row. Eviction also checks that the whole row still matches at the point of deletion. This matters because a cache hit can update the eviction metadata after the candidate has been selected. LRU hits and TTL updates now modify existing rows without creating new ones.

When the table fills up, a conditional write can fail even though the key is free. The Swoole store now distinguishes that failure from an existing cache entry or a held lock. These failures now identify the cache key or lock name and the configuration that controls table capacity, whether Swoole displays warnings or runs quietly. A counter returns its new value only after the write succeeds. Ordinary write exceptions still reach cache failover.

Reverb

Consuming a webhook smoothing marker now reads its timestamp and removes it in one call. Throttle acquisition can insert a missing marker or replace an expired timestamp only if it still matches. If another worker clears or renews the marker, the caller reads it again. A full table still follows the existing error-reporting path.

Connection admission now checks the cap before incrementing the count, under the same lock. Previously, a rejected connection could temporarily occupy a slot and cause a second connection to be refused even after a slot had been released. Presence subscriptions continue to update the channel and member counts together so both transitions belong to the right connection.

Rate limiter

If a group of limits runs out of table space partway through a write, the store restores earlier charges before releasing the locks. Previously the framework's warning handler could throw before that rollback ran. Group admission now reads each distinct key once, and pruning deletes a candidate only if its expired deadline still matches.

Regression coverage

CacheSwooleStoreTest::testFlushDeletesUserRowsAndPreservesControlRows and testFlushLocksDeletesLockRowsAndPreservesCacheAndIntervalRows exercise real collision chains. With the previous implementation, both flushes reported success and left rows they were supposed to remove. With this change, only the expected rows remain.

testConditionalWriteReportsAllocationFailure fills a real table. Before the diagnostic fix, displaying Swoole warnings produced an exception containing only the hashed key. The same operations now report the logical key in both warning modes.

Verification

composer lint:fix and composer analyse passed from the repository root. The cache, Reverb, and rate limiter suites passed, including the forked concurrency tests and the two-worker Reverb integration tests. The focused command for the cache change also passed:

composer test:parallel -- --processes=4 --filter='Cache(SwooleStore(Concurrency)?|FailoverStore)Test' tests/Cache

Summary by cubic

Uses Swoole 6.3's atomic row operations to eliminate races in the cache, Reverb shared state, and the rate limiter.

Cache

  • Flushes collect matching keys before deleting, so collision chains are fully cleared.
  • Stale cleanup and eviction compare the observed row before deleting, so a concurrent renewal or hit survives.
  • Allocation failures are distinguished from a live entry or held lock; counters throw instead of reporting a value they never stored.
  • Capacity errors name the logical key and the rows/conflict_proportion settings, behaving the same whether Swoole warnings are enabled or disabled.
  • LRU hits and touches update existing rows without creating expired shells.
  • The docs now explain when add and lock acquisition return false versus throw, and note that a flush can make competing writes hit the one-second lock timeout.

Reverb and rate limiter

  • Smoothing markers are read and removed in one call; throttle renewal retries when a competitor changes the row.
  • Connection admission checks the cap before incrementing, so a rejected connection no longer blocks a released slot.
  • Presence rows are reserved before publishing counts, keeping first/last member events paired.
  • Group rate-limit writes restore earlier charges when the table fills, and pruning only deletes rows still at their observed expired deadline.

[!NOTE]

Use atomic Swoole Table operations for shared framework state

  • Replaces manual read-check-write sequences with native Swoole Table atomics (add, cmpset, cmpdel, getdel, update) across the cache, rate limiter, and Reverb shared state. Compound mutations still coordinate through row stripes, held by callers.
  • Cache (SwooleStore.php) now deletes stale rows only when observed values still match, flushes collect keys before deleting under all stripes, and failed eligible writes (add, increment, lock) throw a RuntimeException naming the logical key instead of silently returning false.
  • Rate limiter (SwooleStore.php) reads each distinct key once in grouped consumption and conditionally deletes expired rows during pruning.
  • Reverb shared state (SwooleTableSharedState.php) uses native increments with strict-false capacity checks, distinguishes duplicate rows from table exhaustion in addRow, retries throttle compare-and-set with a fresh read, and checks the connection-slot limit before incrementing. Adds PHPStan stubs in Table.stub.
  • Risk: failed writes now throw where they previously returned false or were suppressed — callers of SwooleStore::add, increment, and acquireLock in both cache stores, and counter allocation in Reverb, must handle RuntimeException. Tests cover both Swoole warning modes.

Macroscope summarized dfcfa0d.

Summary by CodeRabbit

  • Bug Fixes
    • Cache cleanup and eviction now avoid removing entries that were renewed or replaced concurrently.
    • Cache flushes preserve control data while clearing matching user entries.
    • Rate-limit cleanup now preserves windows renewed during pruning.
    • Reverb connection-slot limits and shared counters are handled more consistently under concurrent activity.
  • Documentation
    • Clarified when cache operations return false and when insufficient table capacity raises an exception.