Skip to content

Use atomic Swoole Table operations for shared framework state - #128

Merged
binaryfire merged 9 commits into
0.4from
perf/swoole-table-atomics
Nov 23, 2026
Merged

binaryfire merged 9 commits into
0.4from
perf/swoole-table-atomics

Conversation

@binaryfire

@binaryfire binaryfire commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

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.

Written for commit dfcfa0d. Summary will update on new commits.

View guided diff Turn on auto-fix

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.

Record which single-row operations can run under the native bucket lock
and where cache flushes, paired presence transitions and grouped rate
limits still need coordination across rows. Document the failure modes,
caller contracts and regression cases for each driver.
Declare the five native methods missing from the bundled Table stub so
applications and framework packages can analyze conditional writes and
atomic deletions. Use the existing common stub loader and preserve the
extension's parameter names and return types.
Collect keys before deleting them so a flush visits every collision row
while holding the writer barrier. Compare the observed expiry or lock
payload during stale cleanup, and compare the full eviction candidate
at deletion so a concurrent hit can save it.

Update only existing rows for LRU hits and touches. Distinguish failed
allocations from contention and successful counter writes, while keeping
ordinary cache write exceptions available to failover. Cover both flush
families, interval refresh, races and table exhaustion with real tables.
Explain when an add with a positive TTL or a lock acquisition returns
false, and when the Swoole store throws because it cannot allocate a row.
Describe what callers can rely on when a counter returns a value.
Consume smoothing markers in one operation and condition throttle
renewals on the observed timestamp. Distinguish duplicate inserts from
capacity failures even when Swoole warnings are disabled.

Reserve both presence rows before publishing either count, and check
the connection cap before incrementing under the app stripe. This keeps
first and last member events paired and prevents a rejected connection
from temporarily occupying a slot. Cover competing clears, renewals,
slot releases and exhausted tables.
Handle the native allocation result at the write boundary so framework
warning conversion cannot bypass rollback, pruning and retry. Read each
distinct group key once and preserve whether the physical row existed.

Prune only rows that still have the expired deadline observed by the
scan. Keep the key stripe during deletion so pruning cooperates with
group rollback. Exercise exhaustion with production warning handling
and verify that a renewed window survives maintenance.
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change updates Swoole Table operations in the cache, Reverb shared state, and rate limiter. It adds conditional row deletion, checked writes, and grouped reads, with regression tests, cache documentation, a PHPStan stub, and a plan document.

Changes: Swoole Table Atomic Operations

Layer / File(s) Summary
Native Table method contract
docs/plans/2026-11-23-1609-swoole-table-atomic-operations.md, src/phpstan/stubs/common/Swoole/Table.stub
The plan describes the cache, Reverb, and rate-limiter changes. The PHPStan stub declares add, update, cmpset, cmpdel, and getdel.
Cache row updates and cleanup
src/cache/src/SwooleStore.php, src/cache/src/SwooleTableState.php, src/docs/cache.md, tests/Cache/*
Cache cleanup and eviction conditionally delete observed rows. Flushes collect matching keys before deletion. Eligible add, increment, and lock writes throw when the table cannot store the row. Tests cover races, flushes, and capacity behavior; the cache documentation describes stated return values and exceptions.
Reverb counters, slots, and markers
src/reverb/src/Servers/Hypervel/Scaling/SwooleTableSharedState.php, tests/Reverb/Servers/Hypervel/Scaling/*
Striped locks coordinate counter and connection-slot updates. Lock acquisition and marker handling use native table operations. Tests cover admission retries, allocation failures, and lock races.
Rate-limit reads and pruning
src/rate-limiter/src/SwooleStore.php, tests/RateLimiter/SwooleStoreTest.php
Grouped reads fetch each key’s row once. Pruning conditionally deletes rows under key stripes. Tests cover pruning races and full-table warning handling.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant SwooleTableSharedState
  participant StripedLock
  participant SwooleTable
  SwooleTableSharedState->>StripedLock: Lock the connection key
  SwooleTableSharedState->>SwooleTable: Read the current slot count
  SwooleTableSharedState->>SwooleTable: Increment count if below the limit
  SwooleTableSharedState->>StripedLock: Release the connection key
Loading

Possibly related PRs

Merge Risk: Minimal · up to ef002

This change replaces compound table operations in the cache, Reverb shared state and rate limiter with Swoole's atomic row operations, and adds regression tests. No concrete defect was established, and the CI failures come from dependency installation, not the changed code. It looks mergeable after the normal test run.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: the PR moves shared framework state in the Swoole cache, Reverb, and the rate limiter onto Swoole Table's atomic row operations. The diff adds the atomic methods (add,…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the template's main sections: it marks the contribution type as Bug fix, explains the problem and change for the cache, Reverb, and rate limiter, gives regression-test evidence…
Full details: Title check

Explanation

The title names the main change: the PR moves shared framework state in the Swoole cache, Reverb, and the rate limiter onto Swoole Table's atomic row operations. The diff adds the atomic methods (add, update, cmpset, cmpdel, getdel) and rewrites flushes, stale cleanup, Reverb admission, and rate-limit writes around them. The title is specific and matches the changeset.

Full details: Description check

Explanation

The description follows the template's main sections: it marks the contribution type as Bug fix, explains the problem and change for the cache, Reverb, and rate limiter, gives regression-test evidence with the failing-before and passing-after behavior for the cache flush tests, and lists verification commands and results. The 'Before submitting' checklist is not ticked, which the template reserves for the author and reviewers to confirm after opening the PR. The Macroscope and cubic auto-generated blocks are extra content but do not remove any required information. The Reverb and rate limiter sections do not link an issue or give a failing-then-passing test result, but the bug-fix requirement only asks for a regression test with failing and passing results, and the cache section supplies that. The description is mostly complete.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 87e8798 and ef00293.

Files selected for processing: 12

  • docs/plans/2026-11-23-1609-swoole-table-atomic-operations.md
  • src/cache/src/SwooleStore.php
  • src/cache/src/SwooleTableState.php
  • src/docs/cache.md
  • src/phpstan/stubs/common/Swoole/Table.stub
  • src/rate-limiter/src/SwooleStore.php
  • src/reverb/src/Servers/Hypervel/Scaling/SwooleTableSharedState.php
  • tests/Cache/CacheSwooleStoreIntervalTest.php
  • tests/Cache/CacheSwooleStoreTest.php
  • tests/RateLimiter/SwooleStoreTest.php
  • tests/Reverb/Servers/Hypervel/Scaling/SwooleTableSharedStateLockTest.php
  • tests/Reverb/Servers/Hypervel/Scaling/SwooleTableSharedStateTest.php

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@binaryfire

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Use atomic Swoole Table operations for shared framework state

🐞 Bug fix ✨ Enhancement 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Prevent cache flushes and stale cleanup from skipping or deleting the wrong rows.
• Make Reverb admission, presence counts, and webhook markers safe under competing workers.
• Preserve rate-limit rollback on table exhaustion and add collision, capacity, and race
 regressions.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 4 capabilities

  • 4 affected capabilities span independent functional scopes: Reverb Swoole shared-state integration, Swoole cache backend integration, Swoole rate-limiter integration.
  • These operations share one bounded cache backend and one physical Swoole table, while cache values, interval metadata, lock rows, and eviction maintenance are distinct end-to-end cache behaviors exposed through the same integration.
  • The propagation path is from the changed native row operation through the cache store to cache callers and lock consumers, rather than treating each table column or helper as a separate capability.
  • Subscription counts, presence user counts, transition flags, and connection-slot admission are coordinated outcomes of the same Reverb shared-state integration and main counter table.
  • They are separate operations but share the bounded Reverb scaling scope; the changed lock and counter paths propagate into channel membership events and connection admission rather than forming independent deployment-layer capabilities.
  • Throttle locks, cache-miss dedupe locks, and smoothing markers produce the bounded outcome of suppressing or permitting deferred webhook delivery.
  • They share the lock table and Reverb webhook integration, while remaining a distinct useful operation from subscription-count state.
  • Grouped and single-key policy operations all determine the bounded end-to-end outcome of allowing, denying, or delaying work based on shared limiter state.
  • The changed read, write, rollback, and prune paths are implementation hops within that integration, while the affected consumer behavior is rate-limit enforcement.
Behavioral complexity 🔴 High 🧩 Multiple interactions

  • Before, cache mutations used striped read-check-write sequences and deletion during scans could interact with Swoole collision traversal.
  • After, eligibility, update, conditional deletion, two-pass iteration, hit accounting, and capacity diagnostics are split across native operations and lock scopes.
  • The new correctness conditions are that a stale cleanup or eviction delete must match the observed row, flush collection must finish before deletion, a failed eligible write must be distinguished from a duplicate, and warning/false behavior must remain compatible with cache-stack failover.
  • The ordinary serialization and existing eviction policy are reused rather than treated as new algorithmic complexity.
Potential damage 🟡 Medium 🩹 Recoverable

  • A wrong cache value, missed expiry, stale lock, or failed cache write primarily causes stale reads, cache misses, temporary lock contention, or backend failover/exception behavior.
  • Cache data is normally reconstructible and a code revert restores the old behavior, but rows already deleted or stale locks already exposed may require TTL expiry, explicit flush, or application-level cache repopulation.
  • The main user-visible capability remains transiently degraded rather than causing irreversible data loss.
  • Revert restores future operations.
  • Existing stale or missing cache rows require TTL expiry, explicit cache/lock flush, or repopulation; an already-triggered application-side lock or cache miss cannot be retroactively compensated.
  • Capacity errors require freeing rows or increasing table capacity.
Assessed commit dfcfa0d
Diagram

graph TD
  C["Cache store"] --> S["Striped coordination"] --> T[("State tables")]
  R["Reverb state"] --> S
  L["Rate limiter"] --> S
  R --> W[("Webhook table")]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use stripes for every shared-state mutation
  • ➕ Relies less on native compare-and-mutate behavior.
  • ➖ Adds contention to webhook markers and cache hit accounting.
  • ➖ Still requires careful handling of table exhaustion and collision-chain iteration.

Recommendation: Prefer the PR's hybrid approach: native single-row operations protect observed values, while stripes remain where a flush or multi-row transition needs broader coordination. Review capacity diagnostics and the boundaries between striped and lock-free mutations closely.

Files changed (12) +613 / -317

Enhancement (1) +14 / -0
Table.stubDeclare native Table methods for PHPStan +14/-0

Declare native Table methods for PHPStan

• Adds signatures for add, update, cmpset, cmpdel, and getdel, which are absent from the bundled Table definition.

src/phpstan/stubs/common/Swoole/Table.stub

Bug fix (3) +176 / -237
SwooleStore.phpMake cache flushes and row decisions race-safe +73/-72

Make cache flushes and row decisions race-safe

• Collects flush keys before deletion and conditionally deletes observed stale or eviction rows. Uses existing-row updates for LRU hits and touches, and throws when eligible adds, locks, or counters cannot be stored.

src/cache/src/SwooleStore.php

SwooleStore.phpPreserve rate-limit rollback on allocation failure +25/-17

Preserve rate-limit rollback on allocation failure

• Reads each distinct grouped key once and suppresses native write warnings so failed writes reach the existing rollback and prune-retry path. Pruning now conditionally deletes the expiration observed during scanning.

src/rate-limiter/src/SwooleStore.php

SwooleTableSharedState.phpAtomically manage Reverb markers and admission +78/-148

Atomically manage Reverb markers and admission

• Uses native operations for marker consumption, throttle acquisition, and counter increments while retaining stripes around presence transitions. Checks connection capacity before incrementing under one stripe and distinguishes duplicate inserts from exhausted tables.

src/reverb/src/Servers/Hypervel/Scaling/SwooleTableSharedState.php

Tests (5) +342 / -70
CacheSwooleStoreIntervalTest.phpCover interval refresh replacing an expired row +1/-0

Cover interval refresh replacing an expired row

• Starts the null-resolver case with an expired physical cache row to verify that stale cleanup preserves the fresh null result.

tests/Cache/CacheSwooleStoreIntervalTest.php

CacheSwooleStoreTest.phpExercise cache collisions, races, and exhaustion +176/-13

Exercise cache collisions, races, and exhaustion

• Adds real-table collision-chain flush and capacity cases, plus deterministic stale-cleanup and eviction interleavings. Updates the LRU deletion expectation and verifies that failed LFU accounting does not discard a cache hit.

tests/Cache/CacheSwooleStoreTest.php

SwooleStoreTest.phpTest rollback and pruning under production warnings +55/-6

Test rollback and pruning under production warnings

• Runs capacity and group-rollback cases with framework warning conversion enabled. Adds an interleaving showing that pruning leaves a renewed window intact.

tests/RateLimiter/SwooleStoreTest.php

SwooleTableSharedStateLockTest.phpReproduce the rejected-connection slot race +20/-38

Reproduce the rejected-connection slot race

• Replaces an obsolete webhook-stripe probe with a lock-release interleaving that verifies rejected admission does not block a connection after a slot is freed.

tests/Reverb/Servers/Hypervel/Scaling/SwooleTableSharedStateLockTest.php

SwooleTableSharedStateTest.phpCover Reverb capacity and competing throttle writes +90/-13

Cover Reverb capacity and competing throttle writes

• Tests counter and webhook-table exhaustion with native warnings both enabled and disabled. Simulates a clear or renewal between reading an expired throttle and attempting its conditional replacement.

tests/Reverb/Servers/Hypervel/Scaling/SwooleTableSharedStateTest.php

Documentation (3) +81 / -10
2026-11-23-1609-swoole-table-atomic-operations.mdRecord the atomic-operation migration plan +78/-0

Record the atomic-operation migration plan

• Documents Swoole's single-row guarantees, the coordination retained by each driver, capacity contracts, and regression coverage.

docs/plans/2026-11-23-1609-swoole-table-atomic-operations.md

SwooleTableState.phpClarify the role of cache row stripes +1/-10

Clarify the role of cache row stripes

• Replaces the obsolete claim that Swoole lacks conditional row operations with the remaining purpose of stripes: compound mutations and flush writer exclusion.

src/cache/src/SwooleTableState.php

cache.mdDocument Swoole cache capacity failures +2/-0

Document Swoole cache capacity failures

• Distinguishes an existing item or held lock from a failed allocation and explains that a counter throws if its result cannot be stored.

src/docs/cache.md

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Findings visible per group, which tucks the rest behind a View link

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[High impact] The PR appears safe to merge; no actionable new issues were found.

Summary

Uses atomic Swoole Table operations to protect shared cache, Reverb, and rate-limit state.

  • Cache flushes and cleanup keep rows that change during the work.
  • Reverb updates shared markers and counters without losing concurrent changes.
  • Rate-limit groups recover cleanly when a table fills or a window changes.

No actionable new issues or rule violations were found. Tests were not run during this review.

Reviews (2) · Last reviewed commit: "Document how flushing a large Swoole cac..." · Reviewed by Greptile

Record how conditional writes expose allocation failures under both Swoole warning settings. Distinguish live cache hits from reads that need a stripe to remove an expired item during a flush.
…modes

Handle the native allocation warning at the checked write so add, counter updates, and lock acquisition report the logical key and the table settings an operator can adjust. Ordinary writes still pass native exceptions through to cache failover.

Exercise the three conditional operations on a full table with warnings enabled and disabled under the framework error handler.
Explain when a competing write or expired-item cleanup can reach the one-second lock timeout. This gives operators a reason to schedule large flushes during low traffic.
@binaryfire

Copy link
Copy Markdown
Member Author

I updated the PR description with the contribution type, the two flush regression cases, their results before and after the fix, and the local verification commands.

@binaryfire
binaryfire merged commit e734943 into 0.4 Nov 23, 2026
55 of 56 checks passed
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.

1 participant