From cde96191cede86686a24cdaa1a518ceb37d73b10 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Tue, 1 Dec 2026 16:22:10 +0000 Subject: [PATCH 1/2] perf(cache): share a cached definition's attribute and index documents across its reads A cache hit on a collection definition deep-cloned the kept model, cloning every attribute and index document, and Collection::__clone then dropped those clones' caches and reattached the models it already had. Clones of the kept model now share its attribute and index lists and copy a list only when something reads it raw, through a final internal SharedCollection. Co-Authored-By: Claude Opus 5.5 --- src/Database/Collection.php | 99 +++++++++++- src/Database/Document.php | 10 +- src/Database/SharedCollection.php | 30 ++++ src/Database/Trait/Documents.php | 2 +- tests/unit/Model/SharedCollectionTest.php | 189 ++++++++++++++++++++++ 5 files changed, 322 insertions(+), 8 deletions(-) create mode 100644 src/Database/SharedCollection.php create mode 100644 tests/unit/Model/SharedCollectionTest.php diff --git a/src/Database/Collection.php b/src/Database/Collection.php index 593c9a696..1113bff58 100644 --- a/src/Database/Collection.php +++ b/src/Database/Collection.php @@ -40,6 +40,12 @@ class Collection extends Document private mixed $fingerprintDocumentSecurity = null; + /** @var array keys whose nested documents clones may share, as nothing writes to them */ + private array $frozen = []; + + /** @var array keys still holding nested documents shared with the collection this was cloned from */ + private array $shared = []; + /** * @param array $input */ @@ -140,7 +146,7 @@ public function toDocument(): Document */ public function attributes(): array { - $source = $this->getAttribute(self::ATTRIBUTES); + $source = $this->raw(self::ATTRIBUTES); if ($this->attributeModels !== null && $source === $this->attributeSource) { return $this->attributeModels; } @@ -194,7 +200,7 @@ public function attributesWith(array $internal): array */ public function indexes(): array { - $source = $this->getAttribute(self::INDEXES); + $source = $this->raw(self::INDEXES); if ($this->indexModels !== null && $source === $this->indexSource) { return $this->indexModels; } @@ -272,37 +278,70 @@ public function declaredPermissions(): ?array return $this->offsetExists(self::PERMISSIONS) ? $this->getPermissions() : null; } + /** + * A deep copy of this collection whose clones share its attribute and index documents, each clone copying them + * only when something reads them raw. Only for a copy nothing writes to, such as a cached definition's kept + * model. + * + * @internal + */ + public function frozen(): SharedCollection + { + $frozen = new SharedCollection(\iterator_to_array((clone $this)->getIterator())); + $frozen->frozen = [self::ATTRIBUTES => true, self::INDEXES => true]; + + return $frozen; + } + #[\Override] public function __clone() { - $attributes = $this->attributeModels !== null && $this->getAttribute(self::ATTRIBUTES) === $this->attributeSource + $attributes = $this->attributeModels !== null && $this->raw(self::ATTRIBUTES) === $this->attributeSource ? $this->attributeModels : null; - $indexes = $this->indexModels !== null && $this->getAttribute(self::INDEXES) === $this->indexSource + $indexes = $this->indexModels !== null && $this->raw(self::INDEXES) === $this->indexSource ? $this->indexModels : null; $fingerprint = $attributes !== null && $indexes !== null ? $this->fingerprint : null; + $shared = []; + foreach ([self::ATTRIBUTES, self::INDEXES] as $key) { + if ((isset($this->frozen[$key]) || isset($this->shared[$key])) && \is_array($this->raw($key))) { + $shared[$key] = true; + } + } + $this->frozen = []; + $this->shared = $shared; + parent::__clone(); $this->forget(self::ATTRIBUTES); $this->forget(self::INDEXES); if ($attributes !== null) { $this->attributeModels = $attributes; - $this->attributeSource = $this->getAttribute(self::ATTRIBUTES); + $this->attributeSource = $this->raw(self::ATTRIBUTES); } if ($indexes !== null) { $this->indexModels = $indexes; - $this->indexSource = $this->getAttribute(self::INDEXES); + $this->indexSource = $this->raw(self::INDEXES); } $this->fingerprint = $fingerprint; } + #[\Override] + protected function sharesOnClone(int|string $key): bool + { + return \is_string($key) && isset($this->shared[$key]); + } + #[\Override] public function offsetSet(mixed $key, mixed $value): void { parent::offsetSet($key, $value); $this->forget($key); + if ($key !== null) { + unset($this->shared[$key], $this->frozen[$key]); + } } #[\Override] @@ -310,6 +349,7 @@ public function offsetUnset(mixed $key): void { parent::offsetUnset($key); $this->forget($key); + unset($this->shared[$key], $this->frozen[$key]); } /** @@ -319,6 +359,8 @@ public function offsetUnset(mixed $key): void #[\Override] public function exchangeArray(array|object $array): array { + $this->unshareAll(); + $this->frozen = []; $previous = parent::exchangeArray($array); if (($previous[self::ATTRIBUTES] ?? null) !== $this->getAttribute(self::ATTRIBUTES)) { @@ -331,6 +373,51 @@ public function exchangeArray(array|object $array): array return $previous; } + /** + * The stored value without copying a shared list. + */ + private function raw(string $key): mixed + { + return $this->offsetExists($key) ? parent::offsetGet($key) : null; + } + + /** + * Gives this collection its own copies of every list it still shares. + */ + protected function unshareAll(): void + { + foreach (\array_keys($this->shared) as $key) { + $this->unshare($key); + } + } + + /** + * Gives this collection its own copies of a list it still shares, keeping the models built from it. + */ + protected function unshare(mixed $key): void + { + if (! \is_string($key) || ! isset($this->shared[$key])) { + return; + } + unset($this->shared[$key]); + $value = parent::offsetGet($key); + if (! \is_array($value)) { + return; + } + + $copy = []; + foreach ($value as $index => $item) { + $copy[$index] = $item instanceof Document ? clone $item : $item; + } + parent::offsetSet($key, $copy); + + if ($key === self::ATTRIBUTES && $this->attributeModels !== null && $this->attributeSource === $value) { + $this->attributeSource = $copy; + } elseif ($key === self::INDEXES && $this->indexModels !== null && $this->indexSource === $value) { + $this->indexSource = $copy; + } + } + private function forget(mixed $key): void { if ($key === self::ATTRIBUTES) { diff --git a/src/Database/Document.php b/src/Database/Document.php index c8e479327..b9876d366 100644 --- a/src/Database/Document.php +++ b/src/Database/Document.php @@ -610,7 +610,7 @@ public function __clone() continue; } - if (! \is_array($value) || $value === []) { + if (! \is_array($value) || $value === [] || $this->sharesOnClone($key)) { continue; } @@ -621,4 +621,12 @@ public function __clone() $this[$key] = $copy; } } + + /** + * Whether a clone keeps this key's list of nested documents shared with the original instead of cloning it. + */ + protected function sharesOnClone(int|string $key): bool + { + return false; + } } diff --git a/src/Database/SharedCollection.php b/src/Database/SharedCollection.php new file mode 100644 index 000000000..b6e0c77a9 --- /dev/null +++ b/src/Database/SharedCollection.php @@ -0,0 +1,30 @@ +unshare($key); + + return parent::offsetGet($key); + } + + #[\Override] + public function getIterator(): \Iterator + { + $this->unshareAll(); + + return parent::getIterator(); + } +} diff --git a/src/Database/Trait/Documents.php b/src/Database/Trait/Documents.php index c7380496d..0e549abe9 100644 --- a/src/Database/Trait/Documents.php +++ b/src/Database/Trait/Documents.php @@ -974,7 +974,7 @@ private function createDefinitionInstance(string $documentKey, array $cached): D if (\count(self::$definitionModels) >= self::DEFINITION_MODELS_LIMIT) { self::$definitionModels = []; } - $kept = clone $model; + $kept = $model instanceof Collection ? $model->frozen() : clone $model; try { $kept->getPermissions(); } catch (StructureException) { diff --git a/tests/unit/Model/SharedCollectionTest.php b/tests/unit/Model/SharedCollectionTest.php new file mode 100644 index 000000000..ab3b3891d --- /dev/null +++ b/tests/unit/Model/SharedCollectionTest.php @@ -0,0 +1,189 @@ +collection(); + $frozen = $collection->frozen(); + + $this->assertSame(Collection::class, $collection::class); + $this->assertSame($collection->getArrayCopy(), $frozen->getArrayCopy()); + } + + /** + * @return array + */ + public static function reads(): array + { + return [ + 'getAttribute' => [static function (Collection $collection): Document { + $attributes = $collection->getAttribute('attributes'); + self::assertIsArray($attributes); + self::assertInstanceOf(Document::class, $attributes[0]); + + return $attributes[0]; + }], + 'array access' => [static function (Collection $collection): Document { + $attributes = $collection['attributes']; + self::assertIsArray($attributes); + self::assertInstanceOf(Document::class, $attributes[0]); + + return $attributes[0]; + }], + 'getDocuments' => [static fn (Collection $collection): Document => $collection->getDocuments('attributes')[0]], + 'iteration' => [static function (Collection $collection): Document { + foreach ($collection as $key => $value) { + if ($key === 'attributes' && \is_array($value) && $value[0] instanceof Document) { + return $value[0]; + } + } + self::fail('Iteration did not reach the attributes'); + }], + 'getAttributes' => [static function (Collection $collection): Document { + $attributes = $collection->getAttributes()['attributes'] ?? null; + self::assertIsArray($attributes); + self::assertInstanceOf(Document::class, $attributes[0]); + + return $attributes[0]; + }], + 'exchangeArray' => [static function (Collection $collection): Document { + $previous = $collection->exchangeArray([]); + $attributes = $previous['attributes'] ?? null; + self::assertIsArray($attributes); + self::assertInstanceOf(Document::class, $attributes[0]); + + return $attributes[0]; + }], + ]; + } + + /** + * @param \Closure(Collection): Document $read + */ + #[DataProvider('reads')] + public function testAWriteToANestedDocumentStaysInTheCloneThatReadIt(\Closure $read): void + { + $frozen = $this->collection()->frozen(); + $writer = clone $frozen; + $reader = clone $frozen; + $later = clone $writer; + + $read($writer)->setAttribute('size', 999); + + foreach ([$frozen, $reader, $later, clone $frozen] as $other) { + $this->assertSame(128, $other->getDocuments('attributes')[0]->getAttribute('size')); + } + } + + public function testAWriteToTheFrozenOriginalNeverReachesTheFrozenCopy(): void + { + $collection = $this->collection(); + $frozen = $collection->frozen(); + + $collection->getDocuments('attributes')[0]->setAttribute('size', 999); + $collection->getDocuments('indexes')[0]->setAttribute('attributes', ['other']); + + $this->assertSame(128, $frozen->getDocuments('attributes')[0]->getAttribute('size')); + $this->assertSame(128, (clone $frozen)->getDocuments('attributes')[0]->getAttribute('size')); + $this->assertSame(['title'], (clone $frozen)->getDocuments('indexes')[0]->getAttribute('attributes')); + } + + public function testAnIndexWriteStaysInTheCloneThatReadIt(): void + { + $frozen = $this->collection()->frozen(); + $writer = clone $frozen; + + $writer->getDocuments('indexes')[0]->setAttribute('attributes', ['other']); + + $this->assertSame(['title'], $frozen->getDocuments('indexes')[0]->getAttribute('attributes')); + $this->assertSame(['title'], (clone $frozen)->getDocuments('indexes')[0]->getAttribute('attributes')); + } + + public function testACloneKeepsTheModelsAndFingerprintBuiltBeforeIt(): void + { + $frozen = $this->collection()->frozen(); + $fingerprint = $frozen->fingerprint(); + $attributes = $frozen->attributes(); + $indexes = $frozen->indexes(); + + $clone = clone $frozen; + + $this->assertSame($attributes, $clone->attributes()); + $this->assertSame($indexes, $clone->indexes()); + $this->assertSame($fingerprint, $clone->fingerprint()); + + $clone->getAttribute('attributes'); + + $this->assertSame($attributes, $clone->attributes()); + $this->assertSame($fingerprint, $clone->fingerprint()); + } + + public function testASchemaChangeOnACloneRebuildsOnlyItsModels(): void + { + $frozen = $this->collection()->frozen(); + $fingerprint = $frozen->fingerprint(); + $clone = clone $frozen; + + $clone->setAttribute('attributes', Attribute::integer('pages')->toDocument(), SetType::Append); + + $this->assertSame(['title', 'pages'], $this->attributeKeys($clone)); + $this->assertNotSame($fingerprint, $clone->fingerprint()); + $this->assertSame(['title'], $this->attributeKeys($frozen)); + $this->assertSame(['title'], $this->attributeKeys(clone $frozen)); + $this->assertSame($fingerprint, (clone $frozen)->fingerprint()); + } + + public function testANestedWriteSetBackRebuildsTheModels(): void + { + $clone = clone $this->collection()->frozen(); + + $clone->getDocuments('attributes')[0]->setAttribute('size', 256); + $clone->setAttribute('attributes', $clone->getAttribute('attributes')); + + $this->assertSame(256, $clone->attributes()[0]->size); + } + + public function testAnExportedCopyCarriesNoSharedDocument(): void + { + $frozen = $this->collection()->frozen(); + $clone = clone $frozen; + + $export = $clone->getArrayCopy(); + $this->assertIsArray($export['attributes']); + $this->assertIsArray($export['attributes'][0]); + + $this->assertSame($frozen->getArrayCopy(), $export); + } + + private function collection(): Collection + { + $collection = Collection::create( + id: 'books', + attributes: [Attribute::string('title', 128)], + indexes: [Index::key('by_title', ['title'])], + ); + $collection->attributes(); + $collection->indexes(); + + return $collection; + } + + /** + * @return list + */ + private function attributeKeys(Collection $collection): array + { + return \array_map(static fn (Attribute $attribute): string => $attribute->key, $collection->attributes()); + } +} From ef49e7d6d5bc7f0b3fbf20b9f8c30969a93488ab Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Tue, 1 Dec 2026 16:29:51 +0000 Subject: [PATCH 2/2] test(cache): reading a missing key from a shared collection does not create it Co-Authored-By: Claude Opus 5.5 --- tests/unit/Model/SharedCollectionTest.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/unit/Model/SharedCollectionTest.php b/tests/unit/Model/SharedCollectionTest.php index ab3b3891d..96c63ce3c 100644 --- a/tests/unit/Model/SharedCollectionTest.php +++ b/tests/unit/Model/SharedCollectionTest.php @@ -144,6 +144,15 @@ public function testASchemaChangeOnACloneRebuildsOnlyItsModels(): void $this->assertSame($fingerprint, (clone $frozen)->fingerprint()); } + public function testReadingAMissingKeyDoesNotCreateIt(): void + { + $clone = clone $this->collection()->frozen(); + + $this->assertNull($clone->getAttribute('missing')); + $this->assertFalse($clone->offsetExists('missing')); + $this->assertArrayNotHasKey('missing', $clone->getArrayCopy()); + } + public function testANestedWriteSetBackRebuildsTheModels(): void { $clone = clone $this->collection()->frozen();