From 2376fb81a5def29818e2bbdbeb08f34b2a445bfa Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 10:28:13 +0000 Subject: [PATCH 1/4] perf(cache): memoise filter signatures and document key hashes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/Database/Database.php | 70 +++++++++++++++++++++++++++--- tests/unit/CacheKeyTest.php | 86 +++++++++++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+), 7 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 5e72088cb..0a5134bd2 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -215,6 +215,24 @@ class Database protected static bool $defaultFiltersRegistered = false; + /** + * The filter signatures last built and the inputs they were built from, kept because cache keys need them on + * every read. An input that has not changed is the same array, which compares in constant time. + * + * @var array{filters: array, codecs: array, exclusions: array, signatures: array}|null + */ + private static ?array $filterSignatures = null; + + /** + * Document cache key hashes under the filter signatures last built, by whether filters apply, the relationships + * flag and the sorted selects. + * + * @var array + */ + private static array $documentKeyHashes = []; + + private const int DOCUMENT_KEY_HASHES_LIMIT = 1024; + /** * @var array> */ @@ -2785,12 +2803,27 @@ public function getCacheKeys(string $collectionId, ?string $documentId = null, a $sortedSelects = $selects; \sort($sortedSelects); - $payload = \json_encode([ - 'selects' => $sortedSelects, - 'relationships' => $collectionId !== self::METADATA && ($this->relationshipHook?->isEnabled() ?? false), - 'filters' => $this->getActiveFilterSignatures(), - ]) ?: ''; - $documentHashKey = $documentKey . ':' . \md5($payload); + $relationships = $collectionId !== self::METADATA && ($this->relationshipHook?->isEnabled() ?? false); + $filters = $this->getActiveFilterSignatures(); + $memoKey = ($filters === [] ? '-' : '+') + .($relationships ? '1' : '0') + .($sortedSelects === [] ? '' : (\json_encode($sortedSelects) ?: "\0")); + + $hash = self::$documentKeyHashes[$memoKey] ?? null; + if ($hash === null) { + $payload = \json_encode([ + 'selects' => $sortedSelects, + 'relationships' => $relationships, + 'filters' => $filters, + ]) ?: ''; + $hash = \md5($payload); + + if (\count(self::$documentKeyHashes) >= self::DOCUMENT_KEY_HASHES_LIMIT) { + self::$documentKeyHashes = []; + } + self::$documentKeyHashes[$memoKey] = $hash; + } + $documentHashKey = $documentKey . ':' . $hash; } return [ @@ -2947,15 +2980,38 @@ private function getActiveFilterSignatures(): array return []; } + $codecs = $this->codecs?->signatures() ?? []; + $exclusions = $this->filterExclusions()->get() ?? []; + + $built = self::$filterSignatures; + if ( + $built !== null + && $built['filters'] === self::$filters + && $built['codecs'] === $codecs + && $built['exclusions'] === $exclusions + ) { + return $built['signatures']; + } + $signatures = []; foreach (self::$filters as $name => $callbacks) { $signatures[$name] = $callbacks['signature']; } - $signatures = \array_diff_key(($this->codecs?->signatures() ?? []) + $signatures, $this->filterExclusions()->get() ?? []); + $signatures = \array_diff_key($codecs + $signatures, $exclusions); \ksort($signatures); + if ($built === null || $built['signatures'] !== $signatures) { + self::$documentKeyHashes = []; + } + self::$filterSignatures = [ + 'filters' => self::$filters, + 'codecs' => $codecs, + 'exclusions' => $exclusions, + 'signatures' => $signatures, + ]; + return $signatures; } diff --git a/tests/unit/CacheKeyTest.php b/tests/unit/CacheKeyTest.php index ee604ade1..6fb67143c 100644 --- a/tests/unit/CacheKeyTest.php +++ b/tests/unit/CacheKeyTest.php @@ -163,6 +163,92 @@ public function testFiltersDisabledEntirelyProducesDifferentCacheKey(): void $this->assertNotEquals($hashEnabled, $hashDisabled); } + /** + * The digest other readers of the cache (such as the Rust port) rebuild: md5 of the JSON of the sorted + * selects, the relationships flag and the active filter signatures sorted by name. + */ + private function expectedHashKey(Database $db, array $selects, array $exclusions = []): string + { + $filters = (new \ReflectionProperty(Database::class, 'filters'))->getValue(); + $signatures = []; + foreach ($filters as $name => $callbacks) { + $signatures[$name] = $callbacks['signature']; + } + $signatures = \array_diff_key($db->getFilters()->signatures() + $signatures, $exclusions); + \ksort($signatures); + \sort($selects); + + [, $documentKey] = $db->getCacheBaseKeys('col', 'doc1'); + + return $documentKey.':'.\md5(\json_encode([ + 'selects' => $selects, + 'relationships' => false, + 'filters' => $signatures, + ]) ?: ''); + } + + public function testRepeatedHashKeysMatchTheirDigest(): void + { + $db = $this->createDatabase(); + + foreach ([[], ['name'], ['email', 'name'], []] as $selects) { + for ($i = 0; $i < 2; $i++) { + [, , $hashKey] = $db->getCacheKeys('col', 'doc1', $selects); + $this->assertSame($this->expectedHashKey($db, $selects), $hashKey); + } + } + } + + public function testFilterAddedAfterAKeyWasBuiltChangesTheKey(): void + { + $db = $this->createDatabase(); + $before = $this->getHashKey($db); + + Database::addFilter('cacheKeyLateFilter'.\uniqid(), static fn (mixed $value): mixed => $value, static fn (mixed $value): mixed => $value); + + $after = $this->getHashKey($db); + $this->assertNotSame($before, $after); + $this->assertSame($this->expectedHashKey($db, []), $after); + } + + public function testCodecRegisteredOnASharedRegistryAfterAKeyWasBuiltChangesTheKey(): void + { + $db = $this->createDatabase(); + $other = $this->createDatabase()->setFilters($db->getFilters()); + $before = $this->getHashKey($db); + + $noop = static fn (mixed $value): mixed => $value; + $other->getFilters()->register(new Callback('sharedLateCodec', $noop, $noop)); + + $after = $this->getHashKey($db); + $this->assertNotSame($before, $after); + $this->assertSame($this->expectedHashKey($db, []), $after); + $this->assertSame($after, $this->getHashKey($other)); + } + + public function testAlternatingFilterExclusionsKeepTheirOwnKeys(): void + { + $db = $this->createDatabase(); + $skipJson = fn (): string => $db->skipFilters(fn (): string => $this->getHashKey($db), ['json']); + + $enabled = $this->getHashKey($db); + $skipped = $skipJson(); + + $this->assertSame($this->expectedHashKey($db, [], ['json' => true]), $skipped); + for ($i = 0; $i < 3; $i++) { + $this->assertSame($enabled, $this->getHashKey($db)); + $this->assertSame($skipped, $skipJson()); + } + + $db->setFiltering(false); + $off = $this->getHashKey($db); + $db->setFiltering(true); + $this->assertSame($enabled, $this->getHashKey($db)); + $db->setFiltering(false); + $this->assertSame($off, $this->getHashKey($db)); + $db->setFiltering(true); + } + public function testQueryCacheKeyUsesQueryCacheShape(): void { $adapter = self::createStub(FeatureAdapterStub::class); From 3d34a4efebfc619ee2e61dd77f1d05e3475a3a7a Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 10:58:47 +0000 Subject: [PATCH 2/4] test(cache): type the cache key digest helper Co-Authored-By: Claude Opus 5.5 --- tests/unit/CacheKeyTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/unit/CacheKeyTest.php b/tests/unit/CacheKeyTest.php index 6fb67143c..3049246c2 100644 --- a/tests/unit/CacheKeyTest.php +++ b/tests/unit/CacheKeyTest.php @@ -166,9 +166,13 @@ public function testFiltersDisabledEntirelyProducesDifferentCacheKey(): void /** * The digest other readers of the cache (such as the Rust port) rebuild: md5 of the JSON of the sorted * selects, the relationships flag and the active filter signatures sorted by name. + * + * @param list $selects + * @param array $exclusions */ private function expectedHashKey(Database $db, array $selects, array $exclusions = []): string { + /** @var array $filters */ $filters = (new \ReflectionProperty(Database::class, 'filters'))->getValue(); $signatures = []; foreach ($filters as $name => $callbacks) { From 29594afbabe7cf6c4d7e58dc4f5e7aa914a37855 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 12:38:29 +0000 Subject: [PATCH 3/4] test(cache): restore the static filters after registering one Co-Authored-By: Claude Opus 5.5 --- tests/unit/CacheKeyTest.php | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/tests/unit/CacheKeyTest.php b/tests/unit/CacheKeyTest.php index 3049246c2..1cde0483c 100644 --- a/tests/unit/CacheKeyTest.php +++ b/tests/unit/CacheKeyTest.php @@ -172,10 +172,8 @@ public function testFiltersDisabledEntirelyProducesDifferentCacheKey(): void */ private function expectedHashKey(Database $db, array $selects, array $exclusions = []): string { - /** @var array $filters */ - $filters = (new \ReflectionProperty(Database::class, 'filters'))->getValue(); $signatures = []; - foreach ($filters as $name => $callbacks) { + foreach (FilterRegistry::filters() as $name => $callbacks) { $signatures[$name] = $callbacks['signature']; } $signatures = \array_diff_key($db->getFilters()->signatures() + $signatures, $exclusions); @@ -207,12 +205,20 @@ public function testFilterAddedAfterAKeyWasBuiltChangesTheKey(): void { $db = $this->createDatabase(); $before = $this->getHashKey($db); + $filters = FilterRegistry::filters(); + $defaultsRegistered = FilterRegistry::defaultsRegistered(); - Database::addFilter('cacheKeyLateFilter'.\uniqid(), static fn (mixed $value): mixed => $value, static fn (mixed $value): mixed => $value); + try { + Database::addFilter('cacheKeyLateFilter', static fn (mixed $value): mixed => $value, static fn (mixed $value): mixed => $value); - $after = $this->getHashKey($db); - $this->assertNotSame($before, $after); - $this->assertSame($this->expectedHashKey($db, []), $after); + $after = $this->getHashKey($db); + $this->assertNotSame($before, $after); + $this->assertSame($this->expectedHashKey($db, []), $after); + } finally { + FilterRegistry::restore($filters, $defaultsRegistered); + } + + $this->assertSame($before, $this->getHashKey($db)); } public function testCodecRegisteredOnASharedRegistryAfterAKeyWasBuiltChangesTheKey(): void From 7991a146e0238feff4499ece5d596e004c86fcea Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 30 Nov 2026 13:22:44 +0000 Subject: [PATCH 4/4] perf(cache): declare the memo state below the default filters 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 --- src/Database/Database.php | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 0a5134bd2..fe21d45c0 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -215,24 +215,6 @@ class Database protected static bool $defaultFiltersRegistered = false; - /** - * The filter signatures last built and the inputs they were built from, kept because cache keys need them on - * every read. An input that has not changed is the same array, which compares in constant time. - * - * @var array{filters: array, codecs: array, exclusions: array, signatures: array}|null - */ - private static ?array $filterSignatures = null; - - /** - * Document cache key hashes under the filter signatures last built, by whether filters apply, the relationships - * flag and the sorted selects. - * - * @var array - */ - private static array $documentKeyHashes = []; - - private const int DOCUMENT_KEY_HASHES_LIMIT = 1024; - /** * @var array> */ @@ -2971,6 +2953,24 @@ protected function getCollectionMetadataCacheKey(string $collection): string .'::'.$tenantKey.'::'.$collection; } + /** + * The filter signatures last built and the inputs they were built from, kept because cache keys need them on + * every read. An input that has not changed is the same array, which compares in constant time. + * + * @var array{filters: array, codecs: array, exclusions: array, signatures: array}|null + */ + private static ?array $filterSignatures = null; + + /** + * Document cache key hashes under the filter signatures last built, by whether filters apply, the relationships + * flag and the sorted selects. + * + * @var array + */ + private static array $documentKeyHashes = []; + + private const int DOCUMENT_KEY_HASHES_LIMIT = 1024; + /** * @return array */