Skip to content

fix(databases): appwrite:appwrite:alert#4628 scope cached list fields to the version they were read at - #15187

Merged
ChiragAgg5k merged 1 commit into
mainfrom
fix/list-cache-version-scoped-fields
Nov 10, 2026
Merged

ChiragAgg5k merged 1 commit into
mainfrom
fix/list-cache-version-scoped-fields

Conversation

@claudear

@claudear claudear commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

What

Closes code-scanning alert appwrite:appwrite:alert#4628.

ListCache documents the invariant "a read that ran while a purge happened is not cached", but did not enforce it: save() compared the collection's list version with the version captured before the query, and then wrote the rows with a separate, unconditional saveMany. ListCache::purged() wraps a permission-changing write with a purge before and after it, and each purge rotates the version and drops the hash as two more commands.

A list read on a documentSecurity collection could therefore:

  1. miss the cache and capture the version left by the pre-write purge,
  2. query the rows before the permission write committed (so it still saw the old permissions),
  3. pass the version comparison before the post-write purge rotated the version,
  4. and land its HMSET after that purge had dropped the hash.

The rows survived under the same hash field, because the field is derived from the collection schema, collection permissions, caller roles and query set — none of which change when one document's $permissions change. Later list requests from the same roles were served those rows with no permission check, for the caller-chosen ttl of up to 24 hours. The TablesDB rows list inherits the handler.

How

Name the hash field after the version the read was taken at, so the version is part of the lookup rather than a check preceding an unconditional write:

  • ListCache::save() writes its fields under <version>:<field>, and a new ListCache::load() reads a field under a given version. A purge changes the version and drops the hash, so a field of a superseded version is both empty and unreachable: a fill that lands after the purge that should have stopped it ages out instead of being served.
  • Documents/XList takes the version once, before every query in the cached branch, and uses it for every lookup and save. A version it could not read now caches nothing and serves nothing, where before it would still read the hash.

This also moves the three try/catch blocks around the cache loads into ListCache::load(), and drops the second getVersion() the total path used to take.

The cached-hit path now spends one extra HGET (the version key), which the miss path already spent.

Alternatives considered: Versioned::compareAndSwap() applies the predicate and the write in one Lua script, but writes a single field and rotates the version, so the second and third field of one list response could never land; setLeaseGraceWindow() tombstones are ignored by saveMany and are sized to a worst-case staleness nobody configures.

Test plan

  • tests/unit/Databases/ListCacheTest.php — new testReadSavedAfterAPurgeOvertookItsVersionIsNotServed drives the exact interleaving through a named fake (Interleaved) that runs a permission write right after the version read answers, i.e. between the comparison and the write of the rows. It fails on main ('row read before the revocation' is served) and passes here. The existing assertions now read through ListCache::load(), the reader's view.
  • tests/e2e/Services/Databases --filter=Cache: 59 passing, 4 pre-existing testGetDocumentCacheEmpty failures that reproduce identically on the base commit in this environment (database creation returns an empty body).
  • testListDocumentsCacheBustedByDocumentPermissionChange (all six revocation flavors — update, bulk update, transaction, upsert, bulk upsert, transaction bulk upsert) passes, as do testListDocumentsWithCache, testListDocumentsCacheBustedByPermissionChange, testListDocumentsCachePurgedByUpdate and testListDocumentsCachedWithoutSelectQuery.
  • composer lint, composer analyze on the changed files, and composer refactor:check are clean.

🤖 Generated with Claude Code

…d at

A list read took the collection's list version before it queried and saved
its rows only while that version was unchanged, but the comparison and the
write were two separate cache operations. A purge landing between them left
the rows in the hash under a field readers still look up, so a caller whose
document read permission had just been revoked kept being served the revoked
rows for its chosen ttl, up to 24 hours.

Name the field after the version instead. A read now looks up and saves a
field of the version it queried at, and a purge both changes the version and
drops the hash, so a fill that lands after the purge that should have stopped
it is written where no later read looks.

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

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

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

🟡 Medium — Failed post-write purge leaves revoked rows servable · ListCache.php:122–128 · unchanged line

// src/Appwrite/Databases/ListCache.php
122	        foreach ($caches as $cache) {
123	            try {
124	                $cache->purge();
125	            } catch (\Throwable $error) {
126	                Console::warning('Failed to purge the cached list responses of ' . $cache->key . ' after a permission change: ' . $error->getMessage());
127	            }
128	        }

In ListCache::purged() the post-write purge catches \Throwable and only logs a warning (src/Appwrite/Databases/ListCache.php:122-128). purge() saves the new version key before purging the hash, so when that version-key save fails the version stays at the pre-write value and rows cached during the permission write — potentially reflecting revoked permissions — remain reachable and served until their TTL expires. The pre-write purge fails closed (throws Unavailable and refuses the write), so a transient cache failure on the second purge silently disables the very invalidation the first one guarantees.

🧹 Nitpicks (2) — 🟢 2 low
  • 🟢 Interleaved test fires purge before save compares versions (Interleaved.php:34) — The new testReadSavedAfterAPurgeOvertookItsVersionIsNotServed claims to inject the permission write between save()'s version comparison and its write of the rows (tests/unit/Databases/ListCacheTest.php:108-124), but Interleaved::load fires the write after any :version key load (tests/unit/Databases/Interleaved.php:34).
  • 🟢 Empty list results are never cached (XList.php:214) — On a cache miss, documents are saved only if ($documents !== []) (src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php:214), so a query that legitimately returns zero rows is never cached while total for the same query is.

This PR introduces a versioned list cache layer for listing documents, keyed by collection, roles, and queries, with version-purge invalidation wired into the documents list endpoint.

Files Change
src/Appwrite/Databases/ListCache.php New ListCache domain library: versioned cache fields per role/query combination, load/save/purged flow over the Redis cache backend.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php Documents list endpoint now consults the cache on miss/hit, records cached operations, sets the X-Appwrite-Cache header, and triggers purge on writes.
tests/unit/Databases/Interleaved.php Unit test helper simulating interleaved cache reads/writes to exercise version-purge ordering.
tests/unit/Databases/ListCacheTest.php Unit tests covering ListCache load/save/purge behavior and version bumping.

Reviewed commit: 772c8bf

@ghost

ghost commented Nov 2, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

List-cache fields are now read and written under the collection version captured before the list query, preventing fills from superseded versions from being served after a purge. The documents list handler takes one version for document, operation, and total cache access, and the unit tests cover the purge interleaving.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 4
File Change
src/Appwrite/Databases/ListCache.php Adds version-scoped list-cache loads and writes.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php Uses one captured cache version for all fields in a list response.
tests/unit/Databases/Interleaved.php Adds a cache test double that interleaves a purge after a version read.
tests/unit/Databases/ListCacheTest.php Updates cache assertions and adds a regression test for the purge/save race.

Reviewed 772c8bf · 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 S · Looks good to merge. Summary

@github-actions

github-actions Bot commented Nov 2, 2026

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.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/list-cache-version-scoped-fields (after).

Metric Before After Change
🚀 Requests/sec 202.36 203.27 ⚪ +0.4%
⏱️ Latency P50 83.5 ms 86.14 ms ⚪ +3.2%
⏱️ Latency P95 201.69 ms 196.75 ms ⚪ -2.4%
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 86.14 196.75 12,540 203.27 -4.94
Account 161.16 287.64 660 11.49 -22.71
TablesDB 82.92 152.35 6,820 113.24 +1.81
Storage 80.87 189.44 3,300 56.48 -3.02
Functions 120.47 220.13 1,760 30.79 -24.64

Top API waits (after)

API request Max wait (ms)
account.name.update 388.88
storage.files.create 373.31
storage.buckets.create 372.75
account.get 355.25
functions.create 320.19

@ChiragAgg5k
ChiragAgg5k merged commit 33031c7 into main Nov 10, 2026
38 checks passed
ChiragAgg5k added a commit that referenced this pull request Nov 12, 2026
…-fields

fix(databases): appwrite:appwrite:alert#4628 scope cached list fields to the version they were read at

(cherry picked from commit 33031c7)
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.

3 participants