Skip to content
Merged
78 changes: 78 additions & 0 deletions docs/plans/2026-11-23-1609-swoole-table-atomic-operations.md

Large diffs are not rendered by default.

146 changes: 74 additions & 72 deletions src/cache/src/SwooleStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ public function get(string $key): mixed
return $value;
}

// A resolver may have stored a live null value; the locked stale-row recheck below decides whether to delete.
// A resolver may have replaced the expired row with a live null.
}

if ($record !== false) {
$this->forgetExpiredRecord($tableKey);
$this->forgetIfUnchanged($tableKey, ['expiration' => $record['expiration']]);
}

return null;
Expand Down Expand Up @@ -149,14 +149,16 @@ public function add(string $key, mixed $value, int $seconds): bool
$serialized = serialize($value);
$expiration = $this->expiration($seconds);

$result = $this->state->withRowLock($tableKey, function () use ($tableKey, $serialized, $expiration): bool {
$record = $this->rawGet($tableKey);
$result = $this->state->withRowLock($tableKey, function () use ($key, $tableKey, $serialized, $expiration): bool {
$existingExpiration = $this->table->get($tableKey, 'expiration');

if (! $this->recordIsFalseOrExpired($record)) {
if ($existingExpiration !== false && $existingExpiration > $this->getCurrentTimestamp()) {
return false;
}

return $this->rawPutSerialized($tableKey, $serialized, $expiration);
$this->putSerializedOrFail($key, $tableKey, $serialized, $expiration);

return true;
});

if ($result) {
Expand All @@ -174,20 +176,20 @@ public function increment(string $key, int $value = 1): int
$tableKey = $this->userKey($key);
$wroteNewRecord = false;

$result = $this->state->withRowLock($tableKey, function () use ($tableKey, $value, &$wroteNewRecord): int {
$result = $this->state->withRowLock($tableKey, function () use ($key, $tableKey, $value, &$wroteNewRecord): int {
$record = $this->rawGet($tableKey);

if ($this->recordIsFalseOrExpired($record)) {
$wroteNewRecord = true;
$this->rawPutSerialized($tableKey, serialize($value), PHP_FLOAT_MAX);

return $value;
$incremented = $value;
$expiration = PHP_FLOAT_MAX;
} else {
// Counters never deserialize classes, regardless of the user-value policy.
$incremented = (int) (unserialize($record['value'], ['allowed_classes' => false]) + $value);
$expiration = $record['expiration'];
}

// Counters never deserialize classes, regardless of the user-value policy.
$incremented = (int) (unserialize($record['value'], ['allowed_classes' => false]) + $value);

$this->rawPutSerialized($tableKey, serialize($incremented), $record['expiration']);
$this->putSerializedOrFail($key, $tableKey, serialize($incremented), $expiration);

return $incremented;
});
Expand Down Expand Up @@ -238,17 +240,19 @@ public function touch(string $key, int $seconds): bool
$tableKey = $this->userKey($key);

return $this->state->withRowLock($tableKey, function () use ($tableKey, $seconds): bool {
$record = $this->rawGet($tableKey);
$expiration = $this->table->get($tableKey, 'expiration');

if ($this->recordIsFalseOrExpired($record)) {
if ($record !== false) {
$this->rawForget($tableKey);
}
if ($expiration === false) {
return false;
}

if ($expiration <= $this->getCurrentTimestamp()) {
$this->rawForget($tableKey);

return false;
}

return $this->table->set($tableKey, [
return $this->table->update($tableKey, [
'expiration' => $this->expiration($seconds),
]);
});
Expand Down Expand Up @@ -339,17 +343,7 @@ public function forget(string $key): bool
*/
public function flush(): bool
{
return $this->state->withAllRowLocks(function (): bool {
foreach ($this->table as $tableKey => $record) {
if ($this->isControlKey($tableKey)) {
continue;
}

$this->rawForget($tableKey);
}

return true;
});
return $this->flushMatchingKeys(fn (string $key): bool => ! $this->isControlKey($key));
}

/**
Expand All @@ -371,13 +365,28 @@ public function flushLocks(): bool
throw new RuntimeException('Flushing locks is only supported when the lock store is separate from the cache store.');
}

return $this->state->withAllRowLocks(function (): bool {
return $this->flushMatchingKeys($this->isLockKey(...));
}

/**
* Flush matching keys while holding back concurrent writers.
*/
protected function flushMatchingKeys(Closure $matches): bool
{
return $this->state->withAllRowLocks(function () use ($matches): bool {
$keys = [];

foreach ($this->table as $key => $record) {
if ($this->isLockKey($key)) {
$this->rawForget($key);
if ($matches($key)) {
$keys[] = $key;
}
}

// Removing the current row during iteration can skip the next row in its collision chain.
foreach ($keys as $key) {
$this->rawForget($key);
}

return true;
});
}
Expand Down Expand Up @@ -414,17 +423,19 @@ public function acquireLock(string $name, string $owner, int $seconds): bool
$key = $this->lockKey($name);
$expiresAt = $seconds > 0 ? $this->expiration($seconds) : null;

return $this->state->withRowLock($key, function () use ($key, $owner, $expiresAt): bool {
return $this->state->withRowLock($key, function () use ($name, $key, $owner, $expiresAt): bool {
$lock = $this->rawLockRecord($key);

if ($lock !== null && ! $this->lockIsExpired($lock)) {
return false;
}

return $this->rawPutSerialized($key, serialize([
$this->putSerializedOrFail($name, $key, serialize([
'owner' => $owner,
'expiresAt' => $expiresAt,
]), PHP_FLOAT_MAX);

return true;
});
}

Expand Down Expand Up @@ -691,13 +702,13 @@ protected function evictionFingerprint(array $record): array
protected function flushStaleRecords(): void
{
$now = $this->getCurrentTimestamp();
$tableKeys = [];
$lockKeys = [];
$expirations = [];
$expiredLocks = [];

foreach ($this->table as $key => $row) {
if ($this->isLockKey($key)) {
if ($this->rawLockPayloadIsExpired($row)) {
$lockKeys[] = $key;
$expiredLocks[$key] = $row['value'];
}

continue;
Expand All @@ -708,16 +719,16 @@ protected function flushStaleRecords(): void
}

if ($row['expiration'] <= $now) {
$tableKeys[] = $key;
$expirations[$key] = $row['expiration'];
}
}

foreach ($tableKeys as $key) {
$this->forgetExpiredRecord($key);
foreach ($expirations as $key => $expiration) {
$this->forgetIfUnchanged((string) $key, ['expiration' => $expiration]);
}

foreach ($lockKeys as $key) {
$this->forgetExpiredLockRecord($key);
foreach ($expiredLocks as $key => $payload) {
$this->forgetIfUnchanged($key, ['value' => $payload]);
}
}

Expand All @@ -726,31 +737,24 @@ protected function flushStaleRecords(): void
*/
protected function recordHit(string $key): void
{
// Hit metadata stays lock-free for the read hot path. If a concurrent delete wins,
// Swoole can create an expired shell row that stale cleanup later prunes.
if ($this->evictionPolicy === static::EVICTION_POLICY_LRU) {
$this->table->set($key, ['last_used_at' => $this->getCurrentTimestamp()]);
$this->table->update($key, ['last_used_at' => $this->getCurrentTimestamp()]);

return;
}

if ($this->evictionPolicy === static::EVICTION_POLICY_LFU) {
$this->table->incr($key, 'used_count', 1);
// A concurrent delete can make incr allocate. A full table must not discard the hit.
@$this->table->incr($key, 'used_count', 1);
}
}

/**
* Forget an expired record by table key.
* Delete a stale row if the observed columns still match.
*/
protected function forgetExpiredRecord(string $key): void
protected function forgetIfUnchanged(string $key, array $expected): void
{
$this->state->withRowLock($key, function () use ($key): void {
$record = $this->rawGet($key);

if ($this->recordIsFalseOrExpired($record)) {
$this->rawForget($key);
}
});
$this->state->withRowLock($key, fn (): bool => $this->table->cmpdel($key, $expected));
}

/**
Expand All @@ -765,21 +769,8 @@ protected function forgetEvictionCandidate(string $key, array $fingerprint): boo
return false;
}

return $this->rawForget($key);
});
}

/**
* Forget an expired lock record.
*/
protected function forgetExpiredLockRecord(string $key): void
{
$this->state->withRowLock($key, function () use ($key): void {
$record = $this->rawGet($key);

if ($record !== false && $this->rawLockPayloadIsExpired($record)) {
$this->rawForget($key);
}
// Hit accounting can update the row without taking the stripe.
return $this->table->cmpdel($key, $record);
});
}

Expand All @@ -802,6 +793,17 @@ protected function rawPutSerialized(string $key, string $serialized, float $expi
]);
}

/**
* Store a value whose caller has already established eligibility to write.
*/
protected function putSerializedOrFail(string $key, string $tableKey, string $serialized, float $expiration): void
{
// Report the logical key even when Swoole emits an allocation warning.
if (! @$this->rawPutSerialized($tableKey, $serialized, $expiration)) {
throw new RuntimeException("The Swoole cache table is full while writing [{$key}]. Check rows and conflict_proportion in cache.swoole_tables.");
}
}

/**
* Forget a raw table record.
*/
Expand Down
11 changes: 1 addition & 10 deletions src/cache/src/SwooleTableState.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,7 @@
use Hypervel\Core\Swoole\StripedLock;

/**
* Coordinates multi-step Swoole table row mutations across workers.
*
* Swoole Table does not currently provide full-row compare-and-swap,
* set-if-absent, or delete-if-current primitives, so cache operations that need
* atomic read-check-write behavior use striped shared Atomics around tiny
* critical sections.
*
* @TODO Revisit this if Swoole Table adds full-row CAS / set-if-absent /
* delete-if-current primitives so these operations can use native table atomics
* instead of external stripe locks.
* Row stripes serialize compound mutations and let a flush hold back concurrent writers.
*/
class SwooleTableState
{
Expand Down
4 changes: 4 additions & 0 deletions src/docs/cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ The table itself is configured in the `swoole_tables` section of your `config/ca

When a Swoole store is used in a cache stack, `bytes` must be large enough for the serialized stack record, including its value and expiration data. Hypervel throws an exception when a record is too large instead of silently skipping the Swoole layer.

When you call `add` with a positive TTL, it returns `false` if the item already exists. Likewise, calling `get` on a lock returns `false` if the lock is already held. If the table has no room to add the item, acquire the lock, or store the result of an `increment` or `decrement`, Hypervel throws an exception.

When flushing a large Swoole table with `flush` or `flushLocks`, choose a time when traffic is low. If another worker waits more than one second to write to the table or remove an expired item during a read, it throws an exception.

<a name="cache-intervals"></a>
#### Cache Intervals

Expand Down
14 changes: 14 additions & 0 deletions src/phpstan/stubs/common/Swoole/Table.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Swoole;

/**
* PHPStan's bundled Table stub predates these native methods, so declare them with @method.
*
* @method bool add(string $key, array<array-key, mixed> $values)
* @method bool update(string $key, array<array-key, mixed> $values)
* @method bool cmpset(string $key, array<string, mixed> $expected, array<array-key, mixed> $values)
* @method bool cmpdel(string $key, array<string, mixed> $expected)
* @method array<array-key, float|int|string>|false|float|int|string getdel(string $key, ?string $field = null)
*/
class Table {}
Loading