Skip to content

fix(cache): throw when a write through the circuit breaker fails - #14643

Open
abnegate wants to merge 2 commits into
mainfrom
fix/cache-breaker-write-failures
Open

abnegate wants to merge 2 commits into
mainfrom
fix/cache-breaker-write-failures

Conversation

@abnegate

Copy link
Copy Markdown
Member

What

Utopia\Cache\Adapter\CircuitBreaker now throws Utopia\Cache\Exception\Unavailable for writes that change what the cache holds: save, saveMany, purge and flush. It throws when the adapter fails and when the breaker is open, and chains the cause. Reads keep their fallbacks.

Operation Adapter fails / breaker open
save, saveMany (also when the adapter reports false) throws Unavailable (was false)
purge, flush throws Unavailable (was false)
load, loadMany, list, getGeneration, ping, getSize fallback, unchanged
saveWithLease, touch false, unchanged: losing one only skips a fill or a refresh

A save the adapter reports as false now counts as a breaker failure. The Redis adapters return false for a write that misses its deadline, so before this the breaker never counted those. Input every adapter refuses (an empty key, or empty data such as '0') still returns false and does not count. A purge that removed nothing still returns false.

The API maps Unavailable to a new general_cache_unavailable error (503) instead of a bare 500.

Why

Only Appwrite Cloud puts the breaker in front of the database cache. With every Redis error turned into false, utopia-php/database read a failed purge as done and a failed epoch load as "nothing to invalidate". A write made during one 250ms timeout, or while the breaker was open, committed. Once Redis recovered, the old document (with its old $permissions) was served for up to 24h. With this change the library's existing rollback paths see the failure and roll the write back. The utopia-php/database follow-up covers registration retries and schema changes.

Availability trade-off: while the cache is down, writes that must invalidate it fail with a 503 instead of committing stale. Reads still fall back to the database.

Tests

packages/cache/tests/CircuitBreakerTest.php:

Test Before After
testWritesThrowWhenCacheOperationsFail fail (false returned) pass
testWriteReportedAsFalseThrowsAndOpensTheBreaker fail pass
testSaveManyReportedAsFalseThrows fail pass
testOpenBreakerThrowsOnWritesWithoutCallingTheAdapter fail pass
testCacheSurfacesWriteFailures fail pass
testReadsFallBackWhenCacheOperationsFail pass pass
testSavesEveryAdapterRefusesAreNotFailures pass pass
testPurgeOfAMissingKeyIsNotAFailure pass pass

Before = the same tests run against main's CircuitBreaker.php. The cache unit suite passes (121 tests), and bin/monorepo check cache (Rector, Pint, PHPStan) is clean.

🤖 Generated with Claude Code

abnegate and others added 2 commits October 19, 2026 16:56
The breaker turned every cache error into a fallback value, so a failed
save or purge came back as false. utopia-php/database reads false from a
purge as "nothing was there" and false from a load as "no epoch to
invalidate", so a write made while Redis timed out or the breaker was
open committed and left the old document cached for up to 24 hours.
The Redis adapters also report a save that misses its deadline as false
rather than throwing, so the breaker never counted those as failures.

save, saveMany, purge and flush now throw Exception\Unavailable when the
adapter fails or the breaker is open, with the cause chained. A save or
saveMany reported as false counts as a failure too. Input every adapter
refuses (an empty key or empty data) still returns false and does not
count against the breaker; a purge that removed nothing still returns
false.

Reads keep falling back: load, loadMany, list, getGeneration, ping and
getSize. So do saveWithLease and touch. Losing either only skips a fill
or a refresh and never leaves stale data behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A write that cannot invalidate the cache now fails with
Utopia\Cache\Exception\Unavailable. Map it to general_cache_unavailable
(503) so clients see a retryable error instead of a bare 500.

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. No issues found — approved ✅.


This PR introduces a circuit-breaker-wrapped cache adapter so failed cache writes surface as an explicit 503 instead of being silently mistaken for success, plus the error-catalog and exception wiring to translate that to API clients.

Files Change
packages/cache/src/Adapter/CircuitBreaker.php, src/Exception/Unavailable.php New breaker adapter: reads degrade to cache miss, writes and invalidations throw Unavailable, and failures trip the breaker.
packages/cache/tests/CircuitBreakerTest.php Unit coverage for breaker open/close behavior and write-failure semantics.
app/config/errors.php, src/Appwrite/Extend/Exception.php New GENERAL_CACHE_UNAVAILABLE error code (503) added to the public error catalog and exception type map.
app/controllers/general.php Router switch translates the new Unavailable exception into the 503 error response.
packages/cache/README.md Documents the throw-on-write contract for the adapter.

Reviewed commit: 22713e9

@ghost

ghost commented Oct 19, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The change is otherwise mergeable, with two minor false-return cases that should be corrected.

This change makes circuit-breaker cache writes surface Unavailable exceptions and maps them to a 503 API error, while retaining fallbacks for reads. It also documents the write behavior and adds coverage for failed and refused cache operations.

Verdict New comments Fixed Still open
💬 Commented 2 0 0

Note

Not approving while a bug finding is open: Preserve adapter refusals for reserved Redis fields

Finding Where
🟡 Preserve adapter refusals for reserved Redis fields packages/cache/src/Adapter/CircuitBreaker.php:72
🟡 Treat a false flush result as a failed write packages/cache/src/Adapter/CircuitBreaker.php:199
Fix with agent prompt
### Issue 1
packages/cache/src/Adapter/CircuitBreaker.php:72-75
**Preserve adapter refusals for reserved Redis fields**

Redis adapters deliberately return `false` for reserved fields such as `__utopia_gen__`; `saveMany` can also return `false` when all fields are reserved. These are input refusals, not cache outages, but this branch now counts them as breaker failures and turns them into `Unavailable` (and an API 503), despite the stated behavior of preserving refusals.

### Issue 2
packages/cache/src/Adapter/CircuitBreaker.php:199
**Treat a false flush result as a failed write**

With `stored: false`, a `false` result passes through without counting against the breaker or throwing. For example, Hazelcast explicitly returns `false` because it cannot flush, and `Sharding::flush()` returns `false` when a shard fails; callers therefore still receive an ordinary failure value instead of the promised `Unavailable`.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 7
File Change
app/config/errors.php Adds the 503 cache-unavailable API error definition.
app/controllers/general.php Maps cache Unavailable exceptions to the new API error.
packages/cache/README.md Documents which circuit-breaker writes throw.
packages/cache/src/Adapter/CircuitBreaker.php Adds write handling that throws on adapter exceptions or failed saves.
packages/cache/src/Exception/Unavailable.php Introduces the cache write failure exception.
packages/cache/tests/CircuitBreakerTest.php Covers write failures, breaker behavior, and input refusals.
src/Appwrite/Extend/Exception.php Adds the cache-unavailable exception type constant.

Reviewed 22713e9 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@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

Comment on lines +72 to +75
if ($stored && $result === false) {
$attempt->failure = new Unavailable("Cache {$method} of '{$key}' was not stored");

throw $attempt->failure;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Preserve adapter refusals for reserved Redis fields

Redis adapters deliberately return false for reserved fields such as __utopia_gen__; saveMany can also return false when all fields are reserved. These are input refusals, not cache outages, but this branch now counts them as breaker failures and turns them into Unavailable (and an API 503), despite the stated behavior of preserving refusals.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/cache/src/Adapter/CircuitBreaker.php
Line: 72-75

Comment:
**Preserve adapter refusals for reserved Redis fields**

Redis adapters deliberately return `false` for reserved fields such as `__utopia_gen__`; `saveMany` can also return `false` when all fields are reserved. These are input refusals, not cache outages, but this branch now counts them as breaker failures and turns them into `Unavailable` (and an API 503), despite the stated behavior of preserving refusals.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

{
/** @var bool $result */
$result = $this->delegate(__FUNCTION__, \func_get_args(), false);
$result = $this->write(__FUNCTION__, [], '', stored: false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Treat a false flush result as a failed write

With stored: false, a false result passes through without counting against the breaker or throwing. For example, Hazelcast explicitly returns false because it cannot flush, and Sharding::flush() returns false when a shard fails; callers therefore still receive an ordinary failure value instead of the promised Unavailable.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/cache/src/Adapter/CircuitBreaker.php
Line: 199

Comment:
**Treat a false flush result as a failed write**

With `stored: false`, a `false` result passes through without counting against the breaker or throwing. For example, Hazelcast explicitly returns `false` because it cannot flush, and `Sharding::flush()` returns `false` when a shard fails; callers therefore still receive an ordinary failure value instead of the promised `Unavailable`.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

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

@github-actions

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/cache-breaker-write-failures (after).

Metric Before After Change
🚀 Requests/sec 208.17 215.86 ⚪ +3.7%
⏱️ Latency P50 81.75 ms 79.23 ms ⚪ -3.1%
⏱️ Latency P95 187.62 ms 193.18 ms ⚪ +3%
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 79.23 193.18 13,680 215.86 +5.56
Account 156.1 300.93 720 12.06 +30.13
TablesDB 75.56 142.63 7,440 120.77 -9.25
Storage 74.79 168.45 3,600 59.84 -8.18
Functions 118.16 236.54 1,920 32.65 +20.88

Top API waits (after)

API request Max wait (ms)
account.name.update 544.03
account.prefs.update 420.36
functions.create 406.74
functions.variables.update 397.95
functions.variables.create 378.29

This branch has not been deployed

No deployments
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