You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(cache): memoise filter signatures and document key hashes - #1092
getCacheKeys() no longer rebuilds the filter-signature map and md5's its JSON on every call:
getActiveFilterSignatures() keeps the signatures it last built, together with the three inputs they came from: self::$filters, the codec registry's signatures and the filter exclusions. Each input is compared with ===. An unchanged input is the same array, so the check takes constant time. A changed one is a new array (copy-on-write), so it rebuilds. This holds even when a subclass writes static::$filters directly.
getCacheKeys() keeps the document hash per (filters active, relationships flag, sorted selects), and drops them all when the signatures change. The map is capped at 1024 entries.
getQueryCacheField() calls getActiveFilterSignatures() too, so find() cache keys also benefit.
The key bytes are unchanged. The md5 is computed over the same json_encode payload as before, and a new test checks the hash against an independent md5(json_encode([...])). The Rust port (appwrite/appwrite#14308, crates/utopia/database/src/database/keys.rs) rebuilds these keys and shares Redis with PHP during the migration, so this matters.
The memo state is declared next to getActiveFilterSignatures(), below registerDefaultFilters(), on purpose. The default filters are closures, and a closure's signature is the file and line it starts on. Those signatures go into every document cache key, so any line added to Database.php above registerDefaultFilters() changes every key: the whole cache misses once after the upgrade, and the Rust port's pinned line numbers (crates/utopia/database/src/database/filters.rs) stop matching. An earlier revision of this PR did exactly that, shifting each closure by 18 lines. That revision was never released, and it's fixed here; I checked that the default signatures and a sample key are byte-identical to main. Signing the default filters by name instead of by closure location would remove this trap for good; I've raised that on #1089.
Why
Part of #1089. Every getDocument computes two cache keys: the collection definition's and the document's. With Appwrite Cloud's ~45 filters, each key cost ~16 µs: ~4.5 µs rebuilding the signature map (array_diff_key + ksort) and ~10.5 µs for json_encode + md5 of the ~4 KB payload.
Benchmark
PHP 8.5.8 with opcache and tracing JIT (as in production), inside a Swoole coroutine, --cpus=1. Real MariaDB and Redis through Redis\Multiplexing, 40 registered filters. Median CPU µs per call across 3 interleaved runs; the box was shared, so read ±15%.
How to read the numbers: each cell is the CPU time one call takes, in microseconds (µs); lower is better. It is the median over 3 runs, each the best of 7 rounds of 3,000 calls, measured with getrusage (CPU time, not wall clock, so time spent waiting on Redis or MariaDB isn't counted). "before" is main, "after" is this branch. The JSON/igbinary rows say which codec the Redis cache used: Cloud writes JSON today and plans to switch to igbinary. "20 / 80 attributes" is the size of the collection whose document is read: the bigger the collection definition, the more each read costs.
A cleaner 3-run A/B earlier in the day measured getDocument hits at −25.5% (20 attributes) and −15.8% (80 attributes), with untouched control rows within ±4%.
Tests
tests/unit/CacheKeyTest.php:
repeated keys (with and without selects, in any order) equal the independent digest;
a filter added with addFilter() after a key was built changes the key;
a codec registered on a shared Registry after a key was built changes the key on every handle sharing it;
keys under alternating skipFilters() exclusions and setFiltering() toggles stay stable and distinct.
The unit suite passes (13,223 tests). Pint and PHPStan are clean.
The deep compare and clone in createDefinitionInstance. The bigger cost on that path turned out to be decoding the cached definition. A decode memo in utopia-php/cache removes the decode, and it makes the compare constant-time too, because both sides become the same array. It's in a separate PR to appwrite/appwrite.
A cheaper Document::__clone. I measured it at under 3 µs saved, which is inside the noise, and it changed when subclass offsetSet hooks run during a clone, so I dropped it.
A fill token in the definition entry instead of ===. It would change the entry shape the Rust port reads, to save 3–10 µs that the decode memo already removes.
Document cache keys now update when active filters, filter exclusions, or registered codecs change, preventing results from being reused across different filtering states.
Repeated requests with the same selections and filtering settings continue to use consistent cache keys, improving cache reliability.
Every getDocument computes two cache keys (the collection definition's
and the document's). Each rebuilt the active filter signature map
(array_diff_key + ksort over ~45 filters) and md5'd its ~4 KB JSON,
about 16 µs per key, so 30+ µs of each cache hit.
The signatures are now rebuilt only when self::$filters, the codec
registry's signatures or the filter exclusions change, which the memo
checks by array identity (constant time while unchanged). Key hashes
are kept per (filters active, relationships flag, sorted selects) and
dropped whenever the signatures change. The key bytes are unchanged, so
other readers of the cache (the Rust port) are unaffected.
Refs #1089
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The incremental change only relocates class declarations and does not alter behavior.
The pull request memoizes active filter signatures and document cache-key hashes while preserving the existing JSON/MD5 cache-key format. It adds tests covering digest stability and changes to filters, codecs, exclusions, and filtering state. The latest commit moves the memoization state declarations nearer to the helper that uses them.
Latest changes: The newest commit relocates the filter-signature and document-key-hash state declarations from the class property block to just above getActiveFilterSignatures().
Walkthrough (2)
File
Change
src/Database/Database.php
Memoizes active filter signatures and document cache-key hashes; the latest commit relocates the associated state declarations next to the helper.
tests/unit/CacheKeyTest.php
Covers unchanged digest output and cache-key updates across filter and codec changes, exclusions, and filtering toggles.
Reviewed the commits since 29594af
Tip
Comment @appwrite review to re-run, or mention @appwrite with a question.
No actionable comments were generated in the recent review.
Walkthrough
The database now caches active filter signatures and document cache-key hashes. Unit tests check generated hashes against reconstructed digests and cover changes to filters, codecs, exclusions, and filtering state.
Changes: Cache key memoization
Layer / File(s)
Summary
Active filter signature caching src/Database/Database.php, tests/unit/CacheKeyTest.php
The database reuses active filter signatures when global filters, codec signatures, and exclusions match. Changes to signatures clear cached document hashes. Tests cover filter registration, shared-registry codec registration, and changes to exclusions and filtering state.
The database memoizes hashes using active-filter presence, relationship-hook state, and sorted selections. The memo clears at 1,024 entries. Tests compare generated keys with reconstructed digests for repeated calls and different select lists.
utopia-php/database issue 1089 — This PR memoizes filter signatures and document hashes. It does not address the issue’s other topics: cloning definition instances and cache decode costs.
Suggested reviewers:abnegate, fogelito
Merge Risk: Minimal · up to 7991a
This change speeds up cache-key generation by memoising filter signatures and document key hashes, and it keeps the key bytes the same. No concrete regression was found. The memo is cleared whenever the filters, codecs or exclusions change, and the new unit tests cover those changes. The change is low risk to merge.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title "perf(cache): memoise filter signatures and document key hashes" matches the main change. The Database.php summary describes memoizing document cache-key hashes and active filter signatures.…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check
Explanation
The title "perf(cache): memoise filter signatures and document key hashes" matches the main change. The Database.php summary describes memoizing document cache-key hashes and active filter signatures. The objectives describe the same memoization, with the same signature and hash targets. The title uses a Conventional Commits style prefix, which is acceptable. The title is specific and concise.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Reviewing files that changed from the base of the PR and between 3d34a4e and 7991a14.
Files selected for processing: 2
src/Database/Database.php
tests/unit/CacheKeyTest.php
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Additional comments: 1
tests/unit/CacheKeyTest.php-211-211: 1
211-211: Minor · Maintainability & Code Quality · Quick win
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Restore the global filter registry after this test.
Database::addFilter() changes Database::$filters for every database in the process. This test leaves its unique filter registered after success or an assertion failure. Later tests therefore build keys with an additional signature.
Save the registry after createDatabase() initializes the defaults. Restore it in finally. The next key read will detect the restored inputs and refresh the memo.
Based on learnings, tests that change static registries must restore the original state even when an assertion throws.
Reviewing files that changed from the base of the PR and between 0b2dbbd and 3d34a4e.
Files selected for processing: 2
src/Database/Database.php
tests/unit/CacheKeyTest.php
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
A default filter's signature is the file and lines of its PHP closures,
and it goes into every document's cache key. utopia-database hardcodes
them (database/filters.rs), so a utopia-php/database release that moves
those lines (utopia-php/database#1092 moves them 18 down) would leave
PHP and Rust building different keys for every document: each side
misses the other's cache entries, silently.
default_signatures_match_the_php_source compares them with a
Database.php, but only when UTOPIA_DATABASE_PHP names one, and nothing
set it. The database comparison job now runs it against the Appwrite
image's vendor copy, so the PR that bumps utopia-php/database fails until
the Rust numbers follow. The test also fails, instead of passing, when the
file it is given can't be read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The default filters are signed by the file and line of their closures,
and those signatures go into every document cache key. Declaring the
memo state above them moved each closure 18 lines and so changed every
key. Declared next to getActiveFilterSignatures(), the closures keep
their lines and the keys stay byte-identical to main.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
getCacheKeys()no longer rebuilds the filter-signature map and md5's its JSON on every call:getActiveFilterSignatures()keeps the signatures it last built, together with the three inputs they came from:self::$filters, the codec registry's signatures and the filter exclusions. Each input is compared with===. An unchanged input is the same array, so the check takes constant time. A changed one is a new array (copy-on-write), so it rebuilds. This holds even when a subclass writesstatic::$filtersdirectly.getCacheKeys()keeps the document hash per (filters active, relationships flag, sorted selects), and drops them all when the signatures change. The map is capped at 1024 entries.getQueryCacheField()callsgetActiveFilterSignatures()too, sofind()cache keys also benefit.The key bytes are unchanged. The md5 is computed over the same
json_encodepayload as before, and a new test checks the hash against an independentmd5(json_encode([...])). The Rust port (appwrite/appwrite#14308,crates/utopia/database/src/database/keys.rs) rebuilds these keys and shares Redis with PHP during the migration, so this matters.The memo state is declared next to
getActiveFilterSignatures(), belowregisterDefaultFilters(), on purpose. The default filters are closures, and a closure's signature is the file and line it starts on. Those signatures go into every document cache key, so any line added toDatabase.phpaboveregisterDefaultFilters()changes every key: the whole cache misses once after the upgrade, and the Rust port's pinned line numbers (crates/utopia/database/src/database/filters.rs) stop matching. An earlier revision of this PR did exactly that, shifting each closure by 18 lines. That revision was never released, and it's fixed here; I checked that the default signatures and a sample key are byte-identical tomain. Signing the default filters by name instead of by closure location would remove this trap for good; I've raised that on #1089.Why
Part of #1089. Every
getDocumentcomputes two cache keys: the collection definition's and the document's. With Appwrite Cloud's ~45 filters, each key cost ~16 µs: ~4.5 µs rebuilding the signature map (array_diff_key+ksort) and ~10.5 µs forjson_encode+md5of the ~4 KB payload.Benchmark
PHP 8.5.8 with opcache and tracing JIT (as in production), inside a Swoole coroutine,
--cpus=1. Real MariaDB and Redis throughRedis\Multiplexing, 40 registered filters. Median CPU µs per call across 3 interleaved runs; the box was shared, so read ±15%.How to read the numbers: each cell is the CPU time one call takes, in microseconds (µs); lower is better. It is the median over 3 runs, each the best of 7 rounds of 3,000 calls, measured with
getrusage(CPU time, not wall clock, so time spent waiting on Redis or MariaDB isn't counted). "before" ismain, "after" is this branch. The JSON/igbinary rows say which codec the Redis cache used: Cloud writes JSON today and plans to switch to igbinary. "20 / 80 attributes" is the size of the collection whose document is read: the bigger the collection definition, the more each read costs.getCacheKeys(document)getDocumentcache hit, 20 attributes, JSON cachegetDocumentcache hit, 80 attributes, JSON cachegetDocumentcache hit, 20 attributes, igbinary cachegetDocumentcache hit, 80 attributes, igbinary cacheA cleaner 3-run A/B earlier in the day measured
getDocumenthits at −25.5% (20 attributes) and −15.8% (80 attributes), with untouched control rows within ±4%.Tests
tests/unit/CacheKeyTest.php:addFilter()after a key was built changes the key;Registryafter a key was built changes the key on every handle sharing it;skipFilters()exclusions andsetFiltering()toggles stay stable and distinct.The unit suite passes (13,223 tests). Pint and PHPStan are clean.
Not in this PR
The rest of #1089:
createDefinitionInstance. The bigger cost on that path turned out to be decoding the cached definition. A decode memo inutopia-php/cacheremoves the decode, and it makes the compare constant-time too, because both sides become the same array. It's in a separate PR to appwrite/appwrite.Document::__clone. I measured it at under 3 µs saved, which is inside the noise, and it changed when subclassoffsetSethooks run during a clone, so I dropped it.===. It would change the entry shape the Rust port reads, to save 3–10 µs that the decode memo already removes.🤖 Generated with Claude Code
Summary by CodeRabbit