Repository navigation
feat(cache)!: eviction-safe CAS with a rolling migration bridge - #15134
Conversation
|
Review complete. 🟡 2 medium 💬 Inline comments (2)
This PR extends
Two medium issues survive verification: pooled adapters can route version probes and CAS calls to different resources, breaking optimistic-locking semantics in mixed or even homogeneous pools, and read-path version minting creates immortal version-only phantom keys on misses. Reviewed commit: 64b0a73 |
🔵 Tier A · Mergeable after minor fixes
This PR replaces numeric cache generations with opaque snapshots and CAS, adds versioned Redis, memory, pooled, sharded, multiplexed, and circuit-breaker support, and provides a temporary cache-5 facade for staged legacy/dual/v2 migration. Appwrite’s database factory adopts the migration bridge, and database list caching keeps invalidation coordinated across migration phases. Documentation and tests cover the cache protocol, transports, bridge behavior, and application integration. Latest changes: The latest commits route list-cache version invalidation through the bridge’s TTL-aware rotation, add warm-read and cross-phase stale-fill regressions, and require/lock database 9.1.1.
Note Not approving while a bug finding is open: Legacy batch writes are no longer atomic Fix with agent prompt### Issue 1
packages/cache/src/Adapter/Redis/Leasable.php:124
**Version probes leave permanent records for misses**
When `getLease()` or `loadVersioned()` probes a key that does not exist, this `HSET` creates a hash containing only the version and does not set an expiry. A database miss or failed fill therefore leaves the key resident without a TTL (unless Redis later evicts it), so high-cardinality negative lookups can steadily consume cache memory.
### Issue 2
packages/cache/src/Legacy.php:42
**Legacy batch writes are no longer atomic**
Each field is written by a separate Lua call, whereas the normal Redis `saveMany()` commits the batch with one `HSET`. A concurrent batch read can therefore see a mixture of old and new fields, and a later invalid field or Redis failure returns `false` after earlier fields have already been written.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.📂 Walkthrough · 28
⏳ Still open from earlier reviews · 2
Reviewed the commits since |
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
| local version = redis.call('HGET', KEYS[1], '__utopia_version__') | ||
| if version == false then | ||
| version = ARGV[1] | ||
| redis.call('HSET', KEYS[1], '__utopia_version__', version) |
There was a problem hiding this comment.
Version probes leave permanent records for misses
When getLease() or loadVersioned() probes a key that does not exist, this HSET creates a hash containing only the version and does not set an expiry. A database miss or failed fill therefore leaves the key resident without a TTL (unless Redis later evicts it), so high-cardinality negative lookups can steadily consume cache memory.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/cache/src/Adapter/Redis/Leasable.php
Line: 124
Comment:
**Version probes leave permanent records for misses**
When `getLease()` or `loadVersioned()` probes a key that does not exist, this `HSET` creates a hash containing only the version and does not set an expiry. A database miss or failed fill therefore leaves the key resident without a TTL (unless Redis later evicts it), so high-cardinality negative lookups can steadily consume cache memory.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · performance · Reply if this doesn't apply.
There was a problem hiding this comment.
Adds lease/versioned CAS support to the cache package across Redis, pool, sharding, and circuit-breaker adapters, plus an e2e test.
Key findings
- 🟡
Poolversioning probe is any-adapter but calls are per-borrow — Pool.php:166 - 🟡
getLease/loadVersionedmint immortal version-only keys on misses — Leasable.php:120
| public function supportsVersioning(): bool | ||
| { | ||
| return $this->pool->use(fn (Adapter $adapter): bool => $adapter instanceof \Utopia\Cache\Feature\Versioned && $adapter->supportsVersioning()); | ||
| } | ||
|
|
||
| public function getVersion(string $key): string | ||
| { | ||
| return $this->pool->use(function (Adapter $adapter) use ($key): string { | ||
| if (! $adapter instanceof \Utopia\Cache\Feature\Versioned) { | ||
| throw new \Utopia\Cache\Exception\Unavailable("Versioned cache required"); | ||
| } | ||
|
|
||
| return $adapter->getVersion($key); | ||
| }); | ||
| } |
There was a problem hiding this comment.
🟡 bug · medium
Pool versioning probe is any-adapter but calls are per-borrow
Pool::supportsVersioning() (packages/cache/src/Adapter/Pool.php:166-169) borrows exactly one resource via pool->use and reports versioning support from that single adapter, while the versioned methods at Pool.php:171-204 throw Unavailable whenever the adapter borrowed on that particular call is not Versioned. A mixed pool therefore makes Cache::getLease() intermittently throw instead of taking its documented fallback to getGeneration(), and even an all-Versioned pool is broken: each pool->use may route getVersion and the later compareAndSwap to different pooled resources, so the version captured from one adapter is compared against another's and the CAS fails. Sharding::supportsVersioning() (packages/cache/src/Adapter/Sharding.php:175-178) shows the intended all-members aggregation.
📋 Prompt for AI Agents
In packages/cache/src/Adapter/Pool.php lines 166-180, make the Versioned feature coherent: change supportsVersioning() to require ALL pooled adapters to implement Feature\Versioned with supportsVersioning() true (matching the array_all pattern in packages/cache/src/Adapter/Sharding.php:175-178) instead of probing a single pool->use borrow. This makes Cache::getLease() (packages/cache/src/Cache.php) reliably fall back to getGeneration() for mixed pools instead of intermittently throwing Unavailable, and avoids per-call routing to different adapters.
| private const string LUA_VERSION = <<<'LUA' | ||
| local version = redis.call('HGET', KEYS[1], '__utopia_version__') | ||
| if version == false then | ||
| version = ARGV[1] | ||
| redis.call('HSET', KEYS[1], '__utopia_version__', version) | ||
| end | ||
| local value = false | ||
| if ARGV[2] ~= '' then value = redis.call('HGET', KEYS[1], ARGV[2]) end | ||
| return {version, value} | ||
| LUA; |
There was a problem hiding this comment.
🟡 bug · medium
getLease/loadVersioned mint immortal version-only keys on misses
The new LUA_VERSION script HSETs a fresh random __utopia_version__ whenever the field is absent (packages/cache/src/Adapter/Redis/Leasable.php:120-129), so the read-path getVersion() backing Cache::getLease() performs a write. On a nonexistent, expired, or purged key this materializes a hash holding only __utopia_version__ with no TTL — unlike the generation path, where getGeneration() is a pure HGET that never writes — and it is never expired, since only value writes issue EXPIRE. In cache-aside flows that acquire a lease before knowing whether the key exists, every miss leaves a permanent phantom key and turns pure readers into writers, so Redis key count and DBSIZE grow without bound.
📋 Prompt for AI Agents
In packages/cache/src/Adapter/Redis/Leasable.php, change the LUA_VERSION script (lines 120-129) so that when utopia_version is absent it is either not persisted (return a random version without HSET) or persisted with an EXPIRE, so that Cache::getLease()/Cache::loadVersioned() (packages/cache/src/Cache.php lines 206-220) no longer materialize permanent version-only hash keys on cache misses. Prefer restricting lazy allocation to the write path (compareAndSwap) so getVersion() stays read-only.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
Simplicity / prior-art reviewResearch and code review only; no PR code changed in this pass. The fundamental primitive is conventional optimistic concurrency: read a version, conditionally write if it still matches, and reject stale work after eviction/recreation. Memcached gets/cas and its meta protocol are close prior art. Its meta N/W/Z flags additionally choose a recache winner. Our current getLease gives concurrent readers the same version; their database reads are not coalesced. CAS fences fills but does not itself prevent a database stampede. Avoid describing the new capability as exclusive writer/recache ownership. References:
Concrete simplification candidate for #1049: use the atomic snapshot/CAS version as the collection epoch. Currently Mutation stores a random epoch in the record while the cache stores another independently generated version, and both change on each state mutation. CAS could return the version it actually committed (false on conflict, exceptions for unavailability), allowing the record to contain only owner registrations and the returned/snapshotted version to be the epoch. Do not reread the version after a boolean CAS: another writer may have changed it. This candidate needs the existing eviction, late-completion, overlapping-writer and stale-fill regressions rerun before adoption; it has not been implemented or experimentally verified here. The largest structural deletion is the legacy protocol, not Lua formatting. A deliberate breaking migration could retire started/finished accounting and the old generation-based leasing contract, require one opaque-version capability, and bypass coordinated caching on unsupported adapters. This removes a substantial parallel state machine and the numeric/version-prefixed compatibility split. It changes library compatibility and must be a deliberate release choice, not silently slipped into the existing backwards-compatible fix. Keep the single atomic record, fresh identity on cold state, late-writer completion fencing, and unavailable-vs-missing distinction. Keep writer registrations unless the no-cache-during-overlapping-writes contract is explicitly redesigned and verified. Replacing owners with one busy bit or deleting state on any writer finish would allow an older finisher to clear a newer writer's barrier. Operational review point: versioned calls currently bypass CircuitBreaker entirely. Prefer honoring its OPEN state by throwing Unavailable, rather than converting OPEN to a cache miss or always reaching the unhealthy backend. That preserves coordination semantics and fast rejection. This is a resilience improvement, not evidence that a breaker caused the incident. Recommendation: first evaluate merging epoch/version identities and fixing breaker semantics; treat removal of legacy compatibility as a separately declared release decision. Keep one-key Lua for the current hash/multiplexed transport unless a measured, compatible native primitive is demonstrated to simplify it. |
|
Implemented the three simplifications with utopia-php/database#1049: the CAS version is the collection epoch, the numeric/legacy protocol is deleted, and versioned operations respect circuit-breaker OPEN, failure counting and half-open recovery. No separate Dragonfly or DSN is required. Validation on Local evidence: cache 130 unit tests / 284 assertions and 124 transport E2E tests / 482 assertions; database 13,140 unit tests / 199,559 assertions; usage 112 unit tests / 460 assertions and 278 E2E tests / 1,480 assertions. Rector, Pint, PHPStan and monorepo validation pass. Negative controls fail when the breaker is bypassed or post-commit version rotation is omitted. The broad CI run found one real integration issue: usage's redundant dev-only cache constraint made linked tests combine the new cache with the released database API. Removing the constraint lets the database select its compatible cache. The earlier Rector parser crash, image-pull timeouts and Gitea archive queue error did not recur in the fresh full run. Release as cache 6.x with the matching database major; replace temporary development pins before production. Follow the documented drain/stop/clear/deploy/resume cutover everywhere, including workers and tasks. Cloud integration appwrite-labs/cloud#7131 is refreshed and has 58 checks passing; its existing CE dev-main gate stays intact until upstream lands. Durable replay of lost post-commit invalidations remains separate work. |
|
Preparing stable dependencies in response to the request to remove development versions:
Those stable releases do not exist yet; the latest tags are cache 5.2.0 and database 8.3.15. The constraints are prepared locally. Existing PR revisions/lockfiles remain unchanged until publication, so they still represent the tested dependency set rather than fabricated stable versions. Release order: publish cache 6.0.0 from the CI-green cache implementation; update the database constraint/lock to stable cache 6, rerun CI and publish database 9.0.0; update Appwrite's constraint/lock to stable database 9 and rerun CI. Then update Cloud through its existing upstream-main policy. Release notes and the drain/clear cutover are prepared. Awaiting approval to publish the two breaking major releases. |
|
Stable release transition is complete:
The documented drain/stop/clear/deploy/resume cutover remains required before deploying the new protocol. Publishing the libraries does not perform that rollout. |
|
Cache 6.1.0 is published and on Packagist after the complete cache package CI passed: https://github.com/utopia-php/cache/releases/tag/6.1.0. The immutable mirror tag/source is 848b2b703cb5ce47809b739e7b0467781e8f9895; the embedded source matches it. Local cache QA passes 136 unit tests / 299 assertions (four existing skips), 126 transport tests / 508 assertions, Rector, Pint and PHPStan. Database #1050 now installs the stable 6.1.0 package, with 13 compatibility/eviction tests /132 assertions passing against that released package. Its stable lock CI is next; database 9.1.0 publication is approved after checks pass. No production changes. |
|
Cache 6.1.0 remains immutable. The Cloud 1,000ms lease-grace setting exposed a migration-only bug: ordinary legacy owner registration used the conditional-fill helper and was incorrectly refused during fill grace. A one-line Lua condition now excludes unconditional registrations from that guard while retaining it for conditional fills. Both real Redis transports fail the new test on 6.1.0 and pass with the correction; actual successive SQL bulk writes also reproduce/fix it. Cache 6.1.1 will carry this correction, and database #1050 will require ^6.1.1 before publication. No production deployment has happened. |
|
Review follow-up in301ab58063: bridge selection now happens in the Factory constructor, so registered HTTP/worker factories and direct realtime/MQTT constructions share the same migration setting. The direct-construction regression verifies cache namespace isolation, not just a type check. Cloud realtime also explicitly selects its configured migration mode (Cloud PR7131); the dedicated-schema factory already inherits the wrapped cache from dbForProject and must not be wrapped twice. Valid cache-contract comments are fixed: Memory touch rotates its version; conditional fills reject ordinary-save empty inputs; Legacy normalizes the0/default-field sentinel for writes and full-key purges; opaque legacy guards are now tested on both Redis transports and leave hashes unchanged. Package QA,138 unit tests /313 assertions, six focused transport tests /74 assertions, and15 factory tests /33 assertions pass locally. A corrective cache6.1.2 release will follow its package CI; database9.1.0 remains compatible. Version-only identity records retain the existing evictable-cache lifetime policy: the deployed cache budget/eviction policy bounds them, and the protocol tolerates physical loss. Adding per-probe TTL would also require changing ordinary-save TTL preservation and owner-record lifetime rules, so that separate retention-policy change is intentionally outside this minimal bridge. |
|
Cloud integration CI exposed an additional rolling-bridge compatibility gap. Permission-changing row/document writes call The fix keeps those application values in the cache-5 envelope: ordinary legacy writes can set TTL atomically in the existing generation script, and temporary batch fills reuse that writer per field. No opaque fields are added to legacy hashes. The database bridge delegates batch fills to its selected reader. A real Redis regression reproduces the cold-fill failure on database 9.1.0 and passes with the fix through legacy, dual, and v2; permission writes remain available and invalidate list responses. Stable corrective releases will replace cache 6.1.2/database 9.1.0 in the integration after their checks pass. Existing release tags remain unchanged. No production deployment has been performed. The unrelated SMTP audit timeout is still under investigation; final Cloud CI must pass after the CE-main dependency update. |
| if (! \is_array($value) && ! \is_string($value)) { | ||
| return false; | ||
| } | ||
| $result = $this->saveWithGeneration($key, $value, (string) $field, '*', $ttl); |
There was a problem hiding this comment.
Legacy batch writes are no longer atomic
Each field is written by a separate Lua call, whereas the normal Redis saveMany() commits the batch with one HSET. A concurrent batch read can therefore see a mixture of old and new fields, and a later invalid field or Redis failure returns false after earlier fields have already been written.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/cache/src/Legacy.php
Line: 42
Comment:
**Legacy batch writes are no longer atomic**
Each field is written by a separate Lua call, whereas the normal Redis `saveMany()` commits the batch with one `HSET`. A concurrent batch read can therefore see a mixture of old and new fields, and a later invalid field or Redis failure returns `false` after earlier fields have already been written.
---
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.
|
Cloud integration CI exposed an additional rolling-bridge compatibility gap. Permission-changing row/document writes call The fix keeps those application values in the cache-5 envelope: ordinary legacy writes can set TTL atomically in the existing generation script, and temporary batch fills reuse that writer per field. No opaque fields are added to legacy hashes. The database bridge delegates batch fills to its selected reader. A real Redis regression reproduces the cold-fill failure on database 9.1.0 and passes with the fix through legacy, dual, and v2; permission writes remain available and invalidate list responses. Stable corrective releases will replace cache 6.1.2/database 9.1.0 in the integration after their checks pass. Existing release tags remain unchanged. No production deployment has been performed. The unrelated SMTP audit timeout is still under investigation; final Cloud CI must pass after the CE-main dependency update. The application version marker also needs rotation in both keyspaces during mixed-phase writes. Local validation: 13,152 database unit tests /199,733 assertions; 128 cache transport tests /548 assertions; cache unit and package QA green; 9 Appwrite list-cache tests /33 assertions; targeted PHPStan, Pint, and Rector green. Corrective releases target cache 6.1.3 and database 9.1.1 after CI. |
|
Cache 6.1.3 is now published after the package CI job passed: https://github.com/appwrite/appwrite/actions/runs/41151292656/job/124390390970 . The split/release workflow passed: https://github.com/appwrite/appwrite/actions/runs/41152496297 . Verified stable GitHub release and Composer installation at source The required database follow-up is utopia-php/database#1051 (stable cache ^6.1.3, lock6.1.3). Actual released-package bridge tests pass12 tests /180 assertions. It will ship as database9.1.1 after its checks pass. Appwrite's local integration additionally rotates list version markers in both keyspaces; the final PR update will include that change and the stable database lock. Cloud will then return to CEdev-main after Appwrite merges. Existing immutable tags are unchanged; no production deployment. |
|
Merged #1051 normally after all21 checks passed, including every adapter lane, PHPStan, lint and CodeRabbit. CI unit suite:13,152 tests /199,773 assertions (https://github.com/utopia-php/database/actions/runs/41153224951/job/124394589098). Published stable database9.1.1 at Appwrite is updating its stable lock and list-marker integration before final CI. Cloud then returns to its required CEdev-main revision after Appwrite merges. No production deployment has been performed. |
|
Final Appwrite head Cloud's local integration is prepared against the exact same CE8cca source and actual stable database9.1.1; its embedded cache source matches cache6.1.3. Database/migration/adapter/delete-worker coverage passes443 tests /1,183 assertions. Required Cloud Pint, Rector, full2,510-file PHPStan, monorepo validation, strict Composer and audit pass. The only development flag is the existing CE integration package; library versions are stable and there are no aliases. No new library/source edits remain locally. After Appwrite merges, restore Cloud's required CEdev-main constraint, lock the merged revision, rerun final gates, and run final Cloud CI. Its dependency gate remains intact. The staging phase-transition/rollback and cross-region purge drill remains a promotion prerequisite. No production or application-configuration changes have been made. |
|
#15134 merged normally with a merge commit (repository policy requires it), after final CI passed231 checks, with4 expected skips and1 neutral status: https://github.com/appwrite/appwrite/actions/runs/41154355871 . Final reviewed PR head8cca7e3925b6b8271268b4b9ad8e9acca488fef6; merge/main source30105a73561c7c5f1584b317dad8f709de9e347d. Cache source, database dependency/lock, factory and ListCache files match the prepared source exactly. Main also contains subsequent unrelated changes, so Cloud is being validated against the actual merged CE revision. Stable cache6.1.3 and database9.1.1 are published; source tags remain immutable. Cloud's required CEdev-main dependency is now being restored and locked to the merged revision. Local Cloud prepared-source validation passed443 tests /1183 assertions and every required static gate. Final merged-source Cloud checks and CI remain; no production deployment has been performed. |
Eviction could reset a numeric generation and make an old fill token valid again, or leave console collections permanently uncached. Use opaque cache versions and atomic snapshots/CAS; the committed CAS identity is the database collection epoch. Coordination failures and circuit-breaker OPEN throw instead of becoming cache misses.
The normal v2 protocol removes numeric generation fallback. An explicit, temporary
Cache::legacy()facade preserves the released cache-5 wire format for a rolling upgrade on the existing Dragonfly. It shares Redis/multiplexing transports, pools, sharding and the circuit breaker, and never inserts opaque version fields into legacy owner hashes. Ordinary registrations bypass conditional-fill grace; conditional fills remain fenced. Expiring application values and batch fills retain their old envelopes.The database bridge supports three separate rolling passes:
legacyreads with both invalidation protocols,dualreads from isolatedv2:keys while maintaining both protocols, thenv2only after all legacy readers and the rollback window retire. Every legacy-only process and its in-flight SQL must finish before advancing to dual reads. Keep thev2:namespace through eventual bridge cleanup. Appwrite's factory constructor applies the optional mode to registered and direct HTTP/worker/realtime/MQTT database handles. Cloud supplies its legacy default explicitly.Application list caches reuse the bridge's existing region rotation for version markers in both keyspaces. Permission-changing writes remain available, batch list reads stay warm, and permission writes retire a list version captured by a reader in either phase.
Stable releases: cache 6.1.3 and database 9.1.1. Embedded cache source matches the release; Composer requires database
^9.1.1with a stable lock and no development aliases or flags. Database implementation: #1050, corrective application-cache compatibility #1051. Cloud integration: appwrite-labs/cloud#7131.Validation: cache package Rector/Pint/PHPStan, 138 unit tests (4 existing skips), and 128 real transport tests /548 assertions. Database full unit suite passes13,152 tests, with released database8.3.15/cache5.2.0 compatibility subprocesses sharing Redis and SQL with bridge readers/writers; final bridge regressions pass12 tests /180 assertions against released cache6.1.3. Appwrite's factory and list-cache regressions cover direct constructors, namespace isolation, warm reads, available permission writes, physical version TTLs and mixed-phase stale-fill rejection. The original cross-phase purge deterministically fails the new regression by caching a revoked row. Final integration CI is recorded below.
Promotion requires a staging drill of phase transitions, rollback, and cross-region/queued purges; readiness alone does not prove a fleet barrier. Watch cache evictions, memory for both keyspaces, SQL headroom, queue age, latency and errors during gradual warming. This PR does not deploy production or execute the staging drill.