Skip to content

fix(cache): fail cache purges the breaker can't confirm - #14642

Merged
abnegate merged 3 commits into
mainfrom
fix-cache-unavailable
Oct 19, 2026
Merged

abnegate merged 3 commits into
mainfrom
fix-cache-unavailable

Conversation

@abnegate

@abnegate abnegate commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Root cause

Utopia\Cache\Adapter\CircuitBreaker returns its fallback for every call when the circuit is open or the inner adapter throws. For purge() that fallback was false, which is the same value as purging a key that is not there. utopia-php/database reads false from a purge as "nothing to invalidate". So a write made during a short Redis failure (one missed 0.1s readTimeout, or a 30s breaker-open window in Cloud) committed, and the old cached document, $permissions included, was served for up to 24h once Redis recovered.

A probe against utopia-php/database 8.3.9 confirmed this for single updates (inside and outside transactions), deletes, batch updates and purgeCachedCollection().

Fix

  • CircuitBreaker::purge() throws Utopia\Cache\Exception\Unavailable when the circuit is open and when the adapter fails the purge. The adapter's error is kept as previous, and the failure still counts towards opening the circuit.
  • A false returned by the adapter itself, such as purging a missing key, is still returned.
  • Every other operation keeps its fallback. A failed load or save only leaves a cache miss, which is never stale, so throwing there would cost availability for nothing. In Cloud a trip opens the circuit for 30s per worker.

The breaker can only tell the two cases apart if no adapter reports an error as false. These adapters now separate them:

Adapter Before After
Redis (php-redis) a lease script's error reply came back as false, so purge() returned false throws RedisException with getLastError(). A lease script always replies with an integer
RedisCluster HDEL's error reply was coerced to 0, so false throws RedisClusterException
Memcached, Hazelcast any failed delete returned false throws unless the result code is RES_NOTFOUND
Filesystem a failed unlink() returned false throws if the file is still there
Redis\Multiplexing already threw on error replies unchanged; a test now pins it

Before / after

Purge Before After
circuit open false throws Unavailable, adapter not called
adapter throws (e.g. TimeoutException) false throws Unavailable (previous: the cause), counted as a failure
missing key false false
load / save / saveWithLease / touch / list / getGeneration / flush / ping / getSize while open fallback fallback (unchanged)

Tests

These fail on main and pass here:

  • CircuitBreakerTest::testAFailedPurgeThrowsInsteadOfReportingNothingToPurge
  • CircuitBreakerTest::testAPurgeWhileTheCircuitIsOpenThrowsWithoutReachingTheAdapter
  • E2E\RedisTest::testAPurgeTheServerRejectsThrowsInsteadOfReportingNothingToPurge (WRONGTYPE)
  • E2E\MemcachedTest::testAPurgeTheServerRejects… (key longer than 250 bytes)
  • FilesystemTest::testAPurgeThatCannotRemoveTheFileThrows…

New guards, which also pass on main: testAFailedPurgeCountsTowardsOpeningTheCircuit, testOtherOperationsKeepTheirFallbacksWhileTheCircuitIsOpen, testPurgingAMissingKeyStillReturnsFalse, and the RedisCluster / Multiplexing WRONGTYPE purge tests.

I could not run the RedisCluster and Multiplexing E2E tests locally (amd64-only cluster image on arm64, and a local Swoole build that segfaults); CI runs them. bin/monorepo check cache passes: Pint, Rector and PHPStan. The PHPStan baseline count drops by one now that RedisCluster::purge() is typed.

The database side is utopia-php/database#1042: batch writes and schema changes are retired before they commit, so the throw rolls them back.

🤖 Generated with Claude Code

When the circuit was open or the adapter failed, CircuitBreaker::purge()
returned false. That is the same value as purging a key that is not
there, so utopia-php/database read it as nothing to invalidate. It
committed the write and served the old cached document, permissions
included, once Redis recovered. purge() now throws
Exception\Unavailable in both cases, with the adapter's error as the
previous exception. A false from the adapter itself is still returned.

Reads and saves keep their fallbacks. A failed save leaves a cache miss,
which is not stale, so throwing there would only cost availability. In
Appwrite Cloud a breaker trip opens the circuit for 30 seconds per
worker.

That only works if no adapter reports an error as false, so the purges
now tell the two apart:
- Redis: php-redis reports a lease script's error reply as false with
  getLastError(). A lease script always replies with an integer, so
  false now throws.
- RedisCluster: HDEL's error reply was coerced to 0, and now throws.
- Memcached and Hazelcast: a delete that fails with anything other than
  RES_NOTFOUND throws.
- Filesystem: an unlink that leaves the file in place throws.
Redis\Multiplexing already threw on error replies, and a test now pins
that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (1)

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — purge throw contract breaks uncaught production callers · Cache.php:291–309 · file not in diff

// packages/cache/src/Cache.php
291	    public function purge(string $key, string $hash = ''): bool
292	    {
293	        $key = $this->caseSensitive ? $key : strtolower($key);
294	        $hash = $this->caseSensitive ? $hash : strtolower($hash);
295	
296	        foreach (\array_keys($this->recordedPurges) as $recording) {
297	            $this->recordedPurges[$recording][$key][$hash] = true;
298	        }
299	
300	        $start = microtime(true);
301	        $result = $this->adapter->purge($key, $hash);
302	        $duration = microtime(true) - $start;

confirmScript (packages/cache/src/Adapter/Redis.php:320) now throws \RedisException when a lease script returns a false error reply, and Leasable::purge (packages/cache/src/Adapter/Redis/Leasable.php:187) catches only NoScript, so the throw propagates. Cache::purge (packages/cache/src/Cache.php:291) still documents "Returns true on success of false on failure" with no @throws, and Appwrite's production stack wraps Redis in Sharding (packages/cache/src/Adapter/Sharding.php:125), not CircuitBreaker, so nothing converts the exception. A Redis error reply (e.g. OOM, READONLY during failover) now aborts the request or worker loop instead of degrading to a lost purge — and on post-commit purge paths (e.g. the deletes worker's per-file loop at src/Appwrite/Platform/Workers/Deletes.php:674 and the databases transaction commit path at Transactions/Update.php:400) it both fails the operation and leaves the stale entry cached. Other bare callers: src/Appwrite/Utopia/Database/Hook/FunctionCache.php:58, src/Appwrite/Platform/Modules/S3/Http/S3/Base.php:839,971-972, src/Appwrite/Presences/State.php:268. The intentional Exception\Unavailable conversion only exists for callers that opt into CircuitBreaker.


The change makes every cache adapter's purge() distinguish a missing key (false) from a backend failure (throw), and adds a CircuitBreaker wrapper with fallbacks plus an Exception\Unavailable type so callers can opt into graceful degradation. Lease-based Redis adapters now confirm purge via eval/evalSha and throw on error replies, and tests cover throw paths, missing-key paths, and coroutine propagation.

Files Change
packages/cache/src/Adapter/CircuitBreaker.php, src/Exception/Unavailable.php New breaker wrapper and exception; open-circuit ops throw Unavailable while read ops fall back to defaults
packages/cache/src/Adapter/Redis.php, RedisCluster.php, Memcached.php, Hazelcast.php, Filesystem.php purge() now throws on server failure (error replies, result codes, unlink errors) and returns false only for absent keys
packages/cache/tests/CircuitBreakerTest.php, tests/FilesystemTest.php Unit tests for breaker transitions and Filesystem unlink-failure handling
packages/cache/tests/E2E/*.php E2E coverage of purge failure vs missing-key behavior, including multiplexing coroutine propagation
packages/cache/README.md, phpstan-baseline.neon Documentation of the new purge contract; baseline adjustments

Reviewed commit: 7a3dfbb

@ghost

ghost commented Oct 19, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

Adapter changes distinguish failed deletes from missing keys across filesystem, Redis, Memcached, Hazelcast. Redis Cluster, with regression coverage for breaker and backend behavior.

Latest changes: The latest commit allows purging from a not-yet-created filesystem cache directory to return false, and adds a regression test for that case.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 16
File Change
packages/cache/README.md Documents the circuit breaker's exception behavior for unconfirmed purges.
packages/cache/phpstan-baseline.neon Updates the RedisCluster baseline after typing its purge result.
packages/cache/src/Adapter/CircuitBreaker.php Throws Unavailable when purge cannot be confirmed, retaining other operation fallbacks.
packages/cache/src/Adapter/Filesystem.php Detects unconfirmed file deletion and treats an absent cache directory as a miss.
packages/cache/src/Adapter/Hazelcast.php Distinguishes missing keys from failed deletes.
packages/cache/src/Adapter/Memcached.php Distinguishes missing keys from failed deletes.
packages/cache/src/Adapter/Redis.php Validates purge replies and surfaces Redis lease-script errors.
packages/cache/src/Adapter/RedisCluster.php Throws for invalid purge replies and uses the native command return type.
packages/cache/src/Exception/Unavailable.php Adds the exception used for unconfirmed breaker purges.
packages/cache/tests/CircuitBreakerTest.php Covers purge errors, open-circuit behavior, and unchanged fallbacks.
packages/cache/tests/E2E/HazelcastTest.php Tests rejected and missing-key purges against Hazelcast.
packages/cache/tests/E2E/MemcachedTest.php Tests rejected and missing-key purges against Memcached.
packages/cache/tests/E2E/MultiplexingTest.php Pins Redis multiplexing purge behavior on command errors.
packages/cache/tests/E2E/RedisClusterTest.php Covers wrong-type and missing-key Redis Cluster purges.
packages/cache/tests/E2E/RedisTest.php Covers wrong-type and missing-key Redis purges.
packages/cache/tests/FilesystemTest.php Covers failed deletion, inaccessible directories, and a not-yet-created cache directory.
✅ Fixed since the last review · 1
  • Treat a missing cache directory as an ordinary cache miss · packages/cache/src/Adapter/Filesystem.php:100
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Don't treat an inaccessible ancestor as a missing cache directory Already reported in an earlier review

Reviewed the commits since d4b607d · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@ghost ghost 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.

🔵 Tier A · See the inline comments. Summary

@luxor-code-review luxor-code-review Bot 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.

This PR hardens the packages/cache purge path so backend failures surface as exceptions (backed by a new CircuitBreaker adapter and Unavailable exception) instead of silent false returns, with E2E and unit coverage across Redis, RedisCluster, Memcached, Hazelcast, and Filesystem adapters.

Key findings

@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-cache-unavailable (after).

Metric Before After Change
🚀 Requests/sec 215.81 223.91 ⚪ +3.8%
⏱️ Latency P50 79.66 ms 78.26 ms ⚪ -1.7%
⏱️ Latency P95 193 ms 173.54 ms 🟢 -10.1%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 78.26 173.54 13,680 223.91 -19.46
Account 142.12 263.77 720 12.49 -3.32
TablesDB 77.06 146.4 7,440 124.28 -7.96
Storage 69.41 157.44 3,600 61.87 -19.67
Functions 107.43 195.69 1,920 33.75 -20.36

Top API waits (after)

API request Max wait (ms)
functions.create 517.48
account.name.update 425.89
account.prefs.update 412.6
tokens.delete 332.47
tablesdb.rows.create 314.95

RedisCluster's DEL branch still declared an int return. Without strict
types, a false error reply was coerced to 0 and read as nothing to
purge. Filesystem's file_exists() also returns false when the cache
directory cannot be searched, so a purge that never reached the file
reported a missing key. Both now throw. A Hazelcast E2E case pins the
same RES_NOTFOUND distinction that Memcached has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@abnegate

Copy link
Copy Markdown
Member Author

On the finding outside the diff (Cache::purge callers not behind CircuitBreaker): Redis::purge() already threw on connection errors, because execute() rethrows RedisException, so every caller already has to handle a throwing purge. The only new throw is a lease script's error reply (OOM, READONLY during failover). Returning false there was the bug: the entry stays cached and the caller reads it as a missing key. Surfacing it is intentional.

@ghost ghost 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.

🔵 Tier A · See the inline comments. Summary

A Filesystem cache whose directory was never created has nothing in it.
Only a directory that exists and cannot be searched leaves the purge
unconfirmed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@ghost ghost 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.

🟢 Tier S · Looks good to merge. Summary

@abnegate
abnegate merged commit f79bed3 into main Oct 19, 2026
74 checks passed
sub4biz pushed a commit to sub4biz/appwrite that referenced this pull request Oct 19, 2026
Retires cached documents before a write the cache cannot confirm commits
(utopia-php/database#1042), paired with the cache purge fix in appwrite#14642.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
dinodinu pushed a commit to dinodinu/appwrite that referenced this pull request Oct 23, 2026
Since appwrite#14642, a purge the circuit breaker cannot confirm throws
Utopia\Cache\Exception\Unavailable. The error hook had no case for it,
so it reached clients as a 500 general_unknown that SDKs do not retry.
Map it to a new general_cache_unavailable (503).

It is not described as "not applied": a purge after the commit can fail
too, so the client is told to read the affected resources back before
retrying.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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