Skip to content

fix(cache): store empty arrays - #15704

Merged
ArnabChatterjee20k merged 11 commits into
mainfrom
fix/cache-store-empty
Nov 17, 2026
Merged

ArnabChatterjee20k merged 11 commits into
mainfrom
fix/cache-store-empty

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Issue

Closes #15702 (narrowed to empty arrays, see below). Closes #15703 (folded in from #15705: HIBP and JWKS callers).

Every utopia-php/cache adapter refused to store []. save() and Cache::saveWithLease() returned false on empty($data), so an empty answer was never cached and was fetched again on every request.

Solution

The change is limited to empty arrays. '' and '0' stay refused, exactly as before.

  • Redis, Redis\Multiplexing, RedisCluster, Memory, Memcached, Hazelcast and Cache::saveWithLease(): empty($data) becomes $data === '' || $data === '0'. Key checks and return values are unchanged.
  • Filesystem and Storage are unchanged. They store strings and cannot round-trip an array ([] would read back as ''), so they keep refusing [], '' and '0'.
  • Pool, CircuitBreaker and Sharding delegate, so they store [] when their inner adapter does.
  • README: one line on what save() stores and refuses. The example's miss check is now if ($data === false), because if (!$data) treats a cached [] as a miss, and the line says a successful save([]) returns [], so callers compare with === false.

Needs a major release of utopia-php/cache (latest tag cache/7.1.0, so this is cache/8.0.0), because save([]) no longer returns false. Not tagged here; releasing is a separate call.

Tests

New and changed tests, all in packages/cache/tests:

  • Base::testEmptyArrayIsStored: [] saves and loads back as []; a never-written key, an expired entry (TTL 0) and a purged key load as false. Runs on every adapter test class (Memory, Pool, None, and in E2E Redis, RedisCluster, Sharding, Memcached, Hazelcast).
  • Base::testEmptyArrayIsStoredWithLease: the same through saveWithLease, on adapters that support versioning (skipped elsewhere).
  • Base::testEmptyStringIsRefused: '' and '0' are still refused on every adapter.
  • FilesystemTest, StorageTest, PoolTest (a pool of Filesystem) and NoneTest override testEmptyArrayIsStored to assert [] is still refused.
  • PoolTest::testEmptyArrayIsStoredThroughAPoolOfMemory: [] through Pool, with save and saveWithLease.
  • CircuitBreakerTest::testPassesThroughAnEmptyArray: [] through CircuitBreaker; '' and '0' still refused.
  • E2E/MultiplexingTest::testEmptyArrayIsStored: Multiplexing does not extend Base, so it gets its own copy.
  • MemoryTest::testConditionalFillsRejectTheSameEmptyInputsAsOrdinarySaves is renamed testConditionalFillsTreatEmptyInputsLikeOrdinarySaves: the '' and '0' cases stay refused, the [] case is now stored.

Locally I ran the unit tier only (no Docker, and no redis, swoole or igbinary extension). The Redis, RedisCluster, Sharding, Memcached, Hazelcast and Multiplexing tests run in CI (bin/monorepo test cache).

Red: new tests on the old source (unit tier, filtered)
$ ../../vendor/bin/phpunit --testsuite unit --filter 'EmptyArray|EmptyString|EmptyInputs|EmptyDataIsNotSaved'
FS...FF..FS...S...F..S....                                        26 / 26 (100%)

There were 5 failures:
1) Utopia\Cache\Tests\CircuitBreakerTest::testPassesThroughAnEmptyArray
Failed asserting that false is identical to Array &0 [].
2) Utopia\Cache\Tests\MemoryTest::testEmptyArrayIsStored
Failed asserting that false is identical to Array &0 [].
3) Utopia\Cache\Tests\MemoryTest::testEmptyArrayIsStoredWithLease
Failed asserting that false is identical to Array &0 [].
4) Utopia\Cache\Tests\MemoryTest::testConditionalFillsTreatEmptyInputsLikeOrdinarySaves
Failed asserting that false is identical to Array &0 [].
5) Utopia\Cache\Tests\PoolTest::testEmptyArrayIsStoredThroughAPoolOfMemory
Failed asserting that false is identical to Array &0 [].

Tests: 26, Assertions: 46, Errors: 3, Failures: 5, Skipped: 4.

The 3 errors are CodecTest data providers that need the igbinary extension, which my machine does not have. They also fail on main.

Green: same filter after the fix
Circuit Breaker
 ✔ Passes through an empty array
Filesystem
 ↩ Empty array is stored with lease
 ✔ Empty string is refused with data set "empty string"
 ✔ Empty string is refused with data set "zero string"
 ✔ Empty array is stored            (asserts it is refused)
Memory
 ✔ Empty array is stored
 ✔ Empty array is stored with lease
 ✔ Empty string is refused with data set "empty string"
 ✔ Empty string is refused with data set "zero string"
 ✔ Conditional fills treat empty inputs like ordinary saves
None
 ↩ Empty array is stored with lease
 ✔ Empty string is refused (x2)
 ✔ Empty array is stored            (asserts it is refused)
Pool
 ↩ Empty array is stored with lease
 ✔ Empty string is refused (x2)
 ✔ Empty array is stored            (asserts it is refused)
 ✔ Empty array is stored through a pool of memory
Storage
 ↩ Empty array is stored with lease
 ✔ Empty string is refused (x2)
 ✔ Empty array is stored            (asserts it is refused)
 ✔ Empty data is not saved

Tests: 26, Assertions: 60, Errors: 3, Skipped: 4.   (same 3 igbinary errors)

Full unit tier: Tests: 175, Assertions: 429, Errors: 13, Skipped: 9, 0 failures. All 13 errors need igbinary, redis or swoole, are in files this PR does not touch, and also fail on main. bin/monorepo check cache: Rector, Pint and PHPStan pass.

Follow-up: other paths [] can take

Added after review, in the shared Base so every adapter test class runs them, with the same refusal overrides as above for Filesystem, Storage, None and Pool (of Filesystem):

  • Base::testEmptyArrayIsKeptByTouch: touch() on a stored [] keeps it as []. The overrides assert save([]) and touch() both return false.
  • Base::testEmptyArrayIsStoredWithCompareAndSwap: on versioned adapters (skipped elsewhere), compareAndSwap with [] returns a version and loadVersioned returns ['version' => <that version>, 'value' => []].
  • Base::testEmptyArrayFieldIsStoredInABatch: saveMany with a field value [] round-trips through loadMany. Batch writes already accepted []; this locks it in. Skipped when the adapter does not store fields, so it runs on Redis and Sharding in E2E.
  • LoadResultsTelemetryTest::testEmptyArrayLoadIsAHit: a load of a stored [] is counted as a hit.

'' and '0' through compareAndSwap and saveMany are out of scope here and tracked in #15707.

Red: follow-up tests on the cache source of origin/main (unit tier, filtered)
$ ../../vendor/bin/phpunit --testsuite unit --filter 'KeptByTouch|WithCompareAndSwap|FieldIsStoredInABatch|EmptyArrayLoadIsAHit' --testdox
Filesystem (Utopia\Cache\Tests\Filesystem)
 ↩ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch
 ✔ Empty array is kept by touch

Load Results Telemetry (Utopia\Cache\Tests\LoadResultsTelemetry)
 ✘ Empty array load is a hit
   │
   │ Failed asserting that false is identical to Array &0 [].
   │
   │ tests/LoadResultsTelemetryTest.php:162
   │

Memory (Utopia\Cache\Tests\Memory)
 ✘ Empty array is kept by touch
   │
   │ Failed asserting that false is identical to Array &0 [].
   │
   │ tests/Base.php:195
   │
 ✘ Empty array is stored with compare and swap
   │
   │ Utopia\Cache\Exception\Unavailable: Unable to save cache snapshot
   │
   │ src/Adapter/Memory.php:34
   │ src/Cache.php:244
   │ tests/Base.php:211
   │
 ↩ Empty array field is stored in a batch

None (Utopia\Cache\Tests\None)
 ↩ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch
 ✔ Empty array is kept by touch

Pool (Utopia\Cache\Tests\Pool)
 ↩ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch
 ✔ Empty array is kept by touch

Storage (Utopia\Cache\Tests\Storage)
 ↩ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch
 ✔ Empty array is kept by touch

Tests: 16, Assertions: 10, Errors: 4, Failures: 2, Skipped: 9.

The other 3 errors are the igbinary CodecTest data providers, as above.

Green: same filter on this branch
Filesystem (Utopia\Cache\Tests\Filesystem)
 ↩ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch
 ✔ Empty array is kept by touch

Load Results Telemetry (Utopia\Cache\Tests\LoadResultsTelemetry)
 ✔ Empty array load is a hit

Memory (Utopia\Cache\Tests\Memory)
 ✔ Empty array is kept by touch
 ✔ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch

None (Utopia\Cache\Tests\None)
 ↩ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch
 ✔ Empty array is kept by touch

Pool (Utopia\Cache\Tests\Pool)
 ↩ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch
 ✔ Empty array is kept by touch

Storage (Utopia\Cache\Tests\Storage)
 ↩ Empty array is stored with compare and swap
 ↩ Empty array field is stored in a batch
 ✔ Empty array is kept by touch

Tests: 16, Assertions: 15, Errors: 3, Skipped: 9.

Full unit tier: Tests: 191, Assertions: 444, Errors: 13, Skipped: 18, 0 failures (the same 13 extension errors as before). bin/monorepo check cache: Rector, Pint and PHPStan pass.

New files, classes and tests

No new files or classes. New test methods: Base::testEmptyArrayIsKeptByTouch, Base::testEmptyArrayIsStoredWithCompareAndSwap, Base::testEmptyArrayFieldIsStoredInABatch, LoadResultsTelemetryTest::testEmptyArrayLoadIsAHit, Base::emptyStrings, Base::testEmptyArrayIsStored, Base::testEmptyArrayIsStoredWithLease, Base::testEmptyStringIsRefused, PoolTest::testEmptyArrayIsStoredThroughAPoolOfMemory, CircuitBreakerTest::testPassesThroughAnEmptyArray and MultiplexingTest::testEmptyArrayIsStored, each listed above.

Folded in from #15705

Two callers start caching an empty array once this change lands, and #15705 (merged into this branch) covers them:

  • HIBP (src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php): a 200 response with no SUFFIX:COUNT entry at all (an empty body or an HTML page) now raises GENERAL_PWNED_PASSWORDS_UNAVAILABLE, instead of being read as "no breaches" and cached for an hour. A range made only of padding entries is still valid, and is cached as no breaches.
  • JWKS (src/Appwrite/Auth/OIDC/Jwks.php): no code change. A test shows an empty key set is fetched once and cached, and that a newly published key is still picked up after the refresh cooldown.

See #15705 for the red/green output.

🤖 Generated with Claude Code

ArnabChatterjee20k and others added 2 commits November 17, 2026 13:44
Adapters and saveWithLease refused [] along with '' and '0'. Store [];
keep refusing '' and '0'. Filesystem and Storage store strings, so they
still refuse [].

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

luxor-code-review Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Empty-array save() diverges across cache adapters (Filesystem.php) — The save() empty-data guard changed from empty($data) to $data === '' || $data === '0' in Redis, Memory, Memcached, Hazelcast, RedisCluster, and Cache::saveWithLease, so save($key, []) now stores the data and returns it (packages/cache/src/Adapter/Memory.php:69).

This change relaxes the falsy-value guard in cache adapters so that empty arrays are serialized and stored instead of being rejected, with the base test suite updated to assert the new round-trip contract and adapter-specific overrides adjusted accordingly.

Files Change
packages/cache/src/Adapter/{Redis,RedisCluster,Redis/Multiplexing,Hazelcast,Memcached,Memory}.php Replace empty($value)-style rejection with strict checks so [] is serialized and persisted like any other value.
packages/cache/src/Cache.php Align the shared adapter contract/docblock with the new empty-array semantics.
packages/cache/tests/Base.php and per-adapter tests (MemoryTest, FilesystemTest, NoneTest, PoolTest, StorageTest, CircuitBreakerTest) Update contract tests to assert [] round-trips; adapter tests that intentionally keep refusing [] get explicit overrides.
packages/cache/tests/E2E/MultiplexingTest.php, packages/cache/README.md Add E2E coverage for the multiplexing path and document the new empty-array behavior.

Reviewed commit: 88eb19d

@appwrite

appwrite Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The cache adapters now accept empty arrays while continuing to reject empty and zero strings, with tests covering ordinary writes, leases, touch, CAS, batching, and telemetry. HIBP now distinguishes empty or HTML responses from padded empty ranges, and JWKS tests cover caching an empty key set and later refresh behavior.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 6
File Change
packages/cache/README.md Documents empty-array save behavior and uses an explicit false check for cache misses.
packages/cache/src/Adapter/{Hazelcast,Memcached,Memory,Redis,Redis/Multiplexing,RedisCluster}.php and Cache.php Allows empty arrays through ordinary saves and lease-based saves while retaining string refusals.
packages/cache/tests/{Base,CircuitBreakerTest,E2E/MultiplexingTest,FilesystemTest,LoadResultsTelemetryTest,MemoryTest,NoneTest,PoolTest,StorageTest}.php Adds coverage for empty-array caching and preserves refusal behavior for adapters that cannot round-trip arrays.
src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php Rejects HIBP responses with no recognized entries and parses hexadecimal suffixes.
tests/unit/Auth/OIDC/JwksTest.php Tests caching an empty JWKS key set and refreshing after the cooldown.
tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php Covers cached empty ranges and rejects empty or HTML responses.
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Only count well-formed HIBP entries as valid Verifier: This is a hardening nitpick. The code already throws when a 200 response has no hex-prefixed lines, and it skips lines without a colon or with a non-hex prefix. A 200 response from HIBP whose lines are A:0 and nothing else is not a realistic input. The finding names no concrete path where a breached password gets accepted in practice.

Reviewed a1c6fb6 · Details · Comment @appwrite review to re-run, or mention @appwrite with a question.

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

🟢 Tier S · Looks good to merge. Summary

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • 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.

luxor-code-review[bot]
luxor-code-review Bot previously approved these changes Nov 17, 2026
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@Luxor-Code-Review Thanks. The difference between adapters is intended. Filesystem and Storage store strings, so they cannot round-trip an array: a stored [] would read back as ''.

  • packages/cache/src/Adapter/Filesystem.php:58 writes the value with file_put_contents(), and :32 reads it back with file_get_contents(), which always returns a string.
  • packages/cache/src/Adapter/Storage.php:71-76 joins an array's values into one string body.

So both keep their empty($data) guard (Filesystem.php:47, Storage.php:66) and refuse [], '' and '0'. FilesystemTest, StorageTest and PoolTest (whose pool holds Filesystem adapters) override testEmptyArrayIsStored to assert that [] is still refused. packages/cache/README.md:45 already says which adapters store []: "It stores an empty array [], except on Filesystem and Storage, which store strings and refuse it too." No change needed.

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/cache-store-empty (after).

Metric Before After Change
🚀 Requests/sec 215.56 219.82 ⚪ +2%
⏱️ Latency P50 80.01 ms 79.27 ms ⚪ -0.9%
⏱️ Latency P95 188.74 ms 185.04 ms ⚪ -2%
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.27 185.04 13,680 219.82 -3.69
Account 153.19 291.74 720 12.25 -1.54
TablesDB 76.27 135.13 7,440 121.91 -0.94
Storage 71.79 167.91 3,600 60.95 -19.29
Functions 115.9 213.09 1,920 33.25 -30.24

Top API waits (after)

API request Max wait (ms)
storage.buckets.create 507.74
account.name.update 484.18
account.prefs.update 393.02
storage.files.delete 357.54
functions.variables.create 349.75

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@appwrite review

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@tenki-reviewer review

@luxor-code-review

luxor-code-review Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Review complete. No issues found — approved ✅.


This PR replaces the truthiness-based empty($data) guards across the cache package with a strict check that only rejects '' and '0', letting adapters persist an empty array as a real cache value.

Files Change
packages/cache/src/Adapter/*, packages/cache/src/Cache.php Each adapter's save (and Cache::saveWithLease) now rejects only '' and '0', so [] is stored and returned by load rather than treated as a miss; the string-only adapters keep their existing behavior.
packages/cache/tests/* Shared Base contract tests, adapter suites, an E2E Multiplexing test, and README updates lock in the new empty-array semantics, including telemetry hit counting and per-adapter overrides.

Verified candidates did not meet the confidence threshold, so the review is an approval; correctness-3 (a test-only file) never published, accepted as a gap given the other coverage of the same test suite.

Reviewed commit: c6bea66

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

🟢 Tier S · Looks good to merge. Summary

luxor-code-review[bot]
luxor-code-review Bot previously approved these changes Nov 17, 2026
@luxor-code-review
luxor-code-review Bot dismissed their stale review November 17, 2026 08:41

Superseded by a newer Luxor approval on this pull request.

ArnabChatterjee20k and others added 2 commits November 17, 2026 14:33
fix(auth): refuse unreadable HIBP ranges, cache empty HIBP ranges and JWKS key sets
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@appwrite review

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@tenki-reviewer review

@luxor-code-review

luxor-code-review Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Review complete. No issues found — approved ✅.


This change standardizes how the packages/cache adapters and Cache facade treat saving an empty array, and hardens the HIBP validator response parsing.

Files Change
packages/cache/src/Adapter/*, packages/cache/src/Cache.php Adapters and the facade now consistently reject or handle empty-array saves, with aligned touch/lease behavior across backends.
src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php Range parsing now validates hex suffixes and numeric counts strictly, distinguishing malformed bodies from empty ranges before caching.
packages/cache/tests/*, tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php, tests/unit/Auth/OIDC/JwksTest.php New unit and e2e tests covering the empty-value contract, HIBP parsing, and JWKS caching semantics.

No high-confidence defects were found in the verified candidates; the one remaining verified item was below the reporting threshold. The generated/large files listed as skipped in the diff summary were not reviewed.

Reviewed commit: a1c6fb6

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

🟢 Tier S · Looks good to merge. Summary

@luxor-code-review
luxor-code-review Bot dismissed their stale review November 17, 2026 09:14

Superseded by a newer Luxor approval on this pull request.

@ArnabChatterjee20k
ArnabChatterjee20k merged commit 65493f2 into main Nov 17, 2026
140 of 142 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.

auth: cache empty HIBP ranges and JWKS key sets cache: store empty arrays instead of refusing them

2 participants