Skip to content

feat(cache)!: eviction-safe CAS with a rolling migration bridge - #15134

Merged
loks0n merged 16 commits into
mainfrom
codex/eviction-safe-cache-leases
Oct 31, 2026
Merged

loks0n merged 16 commits into
mainfrom
codex/eviction-safe-cache-leases

Conversation

@loks0n

@loks0n loks0n commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

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: legacy reads with both invalidation protocols, dual reads from isolated v2: keys while maintaining both protocols, then v2 only 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 the v2: 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.1 with 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.

@loks0n loks0n self-assigned this Oct 30, 2026
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)

  • 🟡 Pool versioning probe is any-adapter but calls are per-borrow — Pool.php:166
  • 🟡 getLease/loadVersioned mint immortal version-only keys on misses — Leasable.php:120

This PR extends packages/cache with optimistic-concurrency primitives: a Versioned feature exposing getLease/loadVersioned/compareAndSwap over a hidden __utopia_version__ hash field, implemented for Redis via Lua scripts and wired through the Cache facade, pool, sharding, and circuit-breaker adapters.

Files Change
packages/cache/src/Feature/Versioned.php, src/Cache.php Defines the versioned feature interface and adds lease/CAS plumbing to the Cache facade with a getGeneration fallback.
packages/cache/src/Adapter/Redis/Leasable.php, src/Adapter/Redis/Multiplexing.php Redis implementation: Lua scripts for version minting, CAS, and lease saves, with reserved-field guarding and case-folding.
packages/cache/src/Adapter/Redis.php, src/Adapter/Sharding.php, src/Adapter/Pool.php, src/Adapter/CircuitBreaker.php Adapter decoration: capability probing (supportsVersioning), per-shard routing, and pass-through of versioned calls.
packages/cache/tests/E2E/VersionedTest.php E2E coverage for lease/CAS flows, including that the version field is not exposed as a cache value.

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

@ghost

ghost commented Oct 30, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The two previously reported minor cache issues remain open, so this is mergeable after those 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.

Verdict New comments Fixed Still open
💬 Commented 0 0 2

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
File Change
composer.json Raises the minimum stable database package version for the bridge API used by Appwrite.
composer.lock Locks database 9.1.1 and its compatible cache dependency.
packages/cache/docs/versioning.md Documents opaque versioning, the legacy facade, and staged migration guidance.
packages/cache/src/Adapter/CircuitBreaker.php Routes versioned and legacy operations through circuit-breaker handling.
packages/cache/src/Adapter/Memory.php Adds in-memory versioned coordination and invalidation.
packages/cache/src/Adapter/Pool.php Forwards versioned and legacy coordination through pooled adapters.
packages/cache/src/Adapter/Redis.php Rotates opaque versions when ordinary Redis writes update cache values.
packages/cache/src/Adapter/Redis/Leasable.php Replaces numeric-generation lease behavior with the shared versioned Redis implementation.
packages/cache/src/Adapter/Redis/Multiplexing.php Adds versioned and legacy coordination over multiplexed Redis.
packages/cache/src/Adapter/Redis/Versioned.php Implements Redis snapshots, CAS, invalidation, and legacy wire operations.
packages/cache/src/Adapter/Sharding.php Routes versioned and legacy operations to the selected shard.
packages/cache/src/Cache.php Exposes opaque version operations and the temporary legacy facade.
packages/cache/src/Feature/Leasable.php Removes the numeric-generation lease capability.
packages/cache/src/Feature/Legacy.php Defines legacy coordination and TTL-aware write capabilities.
packages/cache/src/Feature/Versioned.php Defines opaque snapshot and conditional-write capabilities.
packages/cache/src/Legacy.php Implements the cache-5 compatibility facade and its guarded legacy operations.
packages/cache/tests/CircuitBreakerTest.php Tests circuit-breaker behavior for versioned and legacy coordination.
packages/cache/tests/E2E/MultiplexingDeadlineTest.php Covers versioned-operation deadlines over multiplexed Redis.
packages/cache/tests/E2E/MultiplexingLeasableTest.php Tests conditional fills and invalidation through multiplexed Redis.
packages/cache/tests/E2E/RedisLeasableTest.php Tests Redis snapshots, stale fills, and invalidation.
packages/cache/tests/E2E/VersionedTest.php Covers legacy wire compatibility, TTL writes, and opaque-operation guards.
packages/cache/tests/MemoryTest.php Tests in-memory invalidation and conditional-fill edge cases.
packages/cache/tests/PoolTest.php Tests coordination forwarding through pooled adapters.
packages/usage/composer.json Removes a redundant development-only cache constraint.
src/Appwrite/Database/Factory.php Applies the configured migration bridge when constructing database handles.
src/Appwrite/Databases/ListCache.php Uses bridge rotation with the marker TTL so list-cache invalidation covers the applicable keyspaces.
tests/unit/Database/FactoryTest.php Tests bridge namespace behavior for directly constructed database factories.
tests/unit/Databases/ListCacheTest.php Tests warm list reads and stale-fill rejection across migration phases.
⏳ Still open from earlier reviews · 2

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

@github-actions

github-actions Bot commented Oct 30, 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.

@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

local version = redis.call('HGET', KEYS[1], '__utopia_version__')
if version == false then
version = ARGV[1]
redis.call('HSET', KEYS[1], '__utopia_version__', version)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread packages/cache/src/Cache.php Resolved

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

Adds lease/versioned CAS support to the cache package across Redis, pool, sharding, and circuit-breaker adapters, plus an e2e test.

Key findings

  • 🟡 Pool versioning probe is any-adapter but calls are per-borrow — Pool.php:166
  • 🟡 getLease/loadVersioned mint immortal version-only keys on misses — Leasable.php:120

Comment on lines +166 to +180
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);
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +120 to +129
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → codex/eviction-safe-cache-leases (after).

Metric Before After Change
🚀 Requests/sec 203.41 220.53 🟢 +8.4%
⏱️ Latency P50 83.25 ms 79.34 ms ⚪ -4.7%
⏱️ Latency P95 207.78 ms 179.44 ms 🟢 -13.6%
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.34 179.44 13,680 220.53 -28.34
Account 148.72 278.55 720 12.38 -33.87
TablesDB 76.79 143.31 7,440 122.77 -20.56
Storage 72.29 163.6 3,600 60.86 -21.56
Functions 108.56 202.26 1,920 33.28 -25.95

Top API waits (after)

API request Max wait (ms)
account.name.update 459.69
functions.create 444.93
tablesdb.rows.create 437.29
functions.variables.update 372.55
account.prefs.update 362.71

@loks0n

loks0n commented Oct 30, 2026

Copy link
Copy Markdown
Member Author

Simplicity / prior-art review

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

@loks0n loks0n changed the title fix(cache): reject stale fills after eviction with versioned leases feat(cache)!: replace generation leases with CAS versions and respect circuit breakers Oct 30, 2026

@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 thread packages/cache/src/Adapter/Memory.php Resolved
@loks0n

loks0n commented Oct 30, 2026

Copy link
Copy Markdown
Member Author

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 d277e35ffcaaa575318ba5edd67dcc1507757e00: all Appwrite CI tests pass (231 successful checks, one neutral Hansi review result and four expected skips). Cache and usage package checks/tests pass, plus the full API matrix. Database PR #1049 has all 21 checks passing on 77990f1f1747623ee59ea51379bb8a60fa52a218.

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.

@loks0n

loks0n commented Oct 30, 2026

Copy link
Copy Markdown
Member Author

Preparing stable dependencies in response to the request to remove development versions:

  • Database: utopia-php/cache: ^6.0.
  • Appwrite: utopia-php/database: ^9.0.

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.

@loks0n

loks0n commented Oct 30, 2026

Copy link
Copy Markdown
Member Author

Stable release transition is complete:

  • Published cache 6.0.0, split 2fef3be8b1aee62b831625a03b221c8e041c7328, via bin/monorepo release cache 6.0.0 from the CI-green implementation.
  • Published database 9.0.0 from c0c72c75a5c47730759ddac169973826e0c05fd5, with all 21 checks passing against stable cache 6.0.0. Database PR Better docs regarding docker-compose #1049 is merged as 72d48083daec61f2760a54d31ccbe95707c8911d.
  • Appwrite requires database ^9.0, locked to 9.0.0; the database requires cache ^6.0, locked to 6.0.0. Both lockfiles have empty aliases and stability flags, with no feature-branch dependency pins. The embedded cache source exactly matches cache 6.0.0.
  • Appwrite's final stable-dependency CI on b2dc1ba5c63c3c9f8a70ec5af11607c4a4b4ede9 succeeds: 231 passing checks, one neutral Hansi review and four expected skips. No failures. The last Tokens job was delayed by runner assignment; its first two runners took other jobs, and the automatic replacement check recovered it.
  • Cloud's dependent draft now uses stable database 9.0.0 too, with 245 affected tests / 690 assertions and all four required local checks passing. Its existing CE dev-main gate remains until this Appwrite PR merges.

The documented drain/stop/clear/deploy/resume cutover remains required before deploying the new protocol. Publishing the libraries does not perform that rollout.

@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 thread packages/cache/src/Legacy.php Resolved

@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 thread packages/cache/src/Legacy.php Resolved
@loks0n

loks0n commented Oct 30, 2026

Copy link
Copy Markdown
Member Author

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.

@loks0n

loks0n commented Oct 30, 2026

Copy link
Copy Markdown
Member Author

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.

@loks0n loks0n changed the title feat(cache)!: replace generation leases with CAS versions and respect circuit breakers feat(cache)!: eviction-safe CAS with a rolling migration bridge Oct 30, 2026

@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 B · 1 blocking finding to address. Summary

Comment thread app/init/registers.php Resolved
@loks0n

loks0n commented Oct 31, 2026

Copy link
Copy Markdown
Member Author

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.

@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 · Looks good to merge. Summary

@loks0n

loks0n commented Oct 31, 2026

Copy link
Copy Markdown
Member Author

Cloud integration CI exposed an additional rolling-bridge compatibility gap. Permission-changing row/document writes call ListCache::purged(), which saves a version marker with a physical TTL. The legacy facade rejected TTL writes, producing Utopia\Cache\Exception\Unavailable and HTTP 503 before the write. Its batch-fill rejection also silently left application list reads cold.

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.

@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

if (! \is_array($value) && ! \is_string($value)) {
return false;
}
$result = $this->saveWithGeneration($key, $value, (string) $field, '*', $ttl);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@loks0n

loks0n commented Oct 31, 2026

Copy link
Copy Markdown
Member Author

Cloud integration CI exposed an additional rolling-bridge compatibility gap. Permission-changing row/document writes call ListCache::purged(), which saves a version marker with a physical TTL. The legacy facade rejected TTL writes, producing Utopia\Cache\Exception\Unavailable and HTTP 503 before the write. Its batch-fill rejection also silently left application list reads cold.

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. ListCache now reuses Bridge::rotate() with the existing version TTL. A deterministic regression demonstrates the original code caching a revoked row after a write from the other phase, then verifies both legacy→dual and dual→legacy directions with the fix. This adds one temporary bridge branch to ListCache::purge() rather than a new coordinator.

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.

@loks0n

loks0n commented Oct 31, 2026

Copy link
Copy Markdown
Member Author

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 3f1d4d1e53c6f686dabb8b9f37b31eac5ec7375f; installed source matches the tested package exactly, with no development aliases or flags.

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.

@loks0n

loks0n commented Oct 31, 2026

Copy link
Copy Markdown
Member Author

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 90e2b4e83d08f58c13f36919652bd6d4e213fc26: https://github.com/utopia-php/database/releases/tag/9.1.1 . Verified the merged/released tree exactly matches checked PR head35a91ac0d3cf8958ec6bb92fe7d81ea1114e1461. It requires stable cache^6.1.3 (source3f1d4d1e53c6f686dabb8b9f37b31eac5ec7375f), no aliases or development flags. Existing tags remain unchanged.

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.

@loks0n

loks0n commented Oct 31, 2026

Copy link
Copy Markdown
Member Author

Final Appwrite head 8cca7e3925b6b8271268b4b9ad8e9acca488fef6 includes the mixed-phase list-marker fix and stable database^9.1.1, locked to release source90e2b4e83d08f58c13f36919652bd6d4e213fc26. Composer has no aliases or development flags. Local factory/list-cache regressions:24 tests /66 assertions; Pint, PHPStan, Rector, strict Composer and monorepo validation all pass. Final CI: https://github.com/appwrite/appwrite/actions/runs/41154355871 . Review remains approved; merge will use normal policy after final CI.

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.

@loks0n
loks0n merged commit 30105a7 into main Oct 31, 2026
236 checks passed
@loks0n

loks0n commented Oct 31, 2026

Copy link
Copy Markdown
Member Author

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

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