From 0f290afa7408fd3bc20eea5738a709e24b4cfdd5 Mon Sep 17 00:00:00 2001 From: Claudear <262350598+claudear@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:59:44 +0000 Subject: [PATCH] fix(destination): drop a schema object the destination no longer holds (HS-1472155) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A meta document and its schema counterpart are two separate, non-atomic writes, so a destination can hold a meta document the schema no longer backs — from a run killed between the two writes, or from a project wedged by the stuck-index bug fixed upstream in appwrite/appwrite#15471, where the `indexes` document outlived its schema index. An Overwrite migration drops the schema copy before recreating it. `Utopia\Database`'s `deleteIndex()`/`deleteAttribute()` throw `NotFound` when the key is absent from the collection metadata, and that aborted the import *before* the meta delete that would have let the recreate through — so every retry took the same path and the orphan could never be reconciled through migration at all. Both drop-before-recreate paths now treat "the schema no longer holds it" as the end state the drop asked for, mirroring the upstream fix. The guard narrows to `NotFound`, so a dependent index or a relationship dropped as a column still surfaces as an error. Co-Authored-By: Claude Opus 5 --- phpstan-baseline.neon | 12 + src/Destinations/Appwrite.php | 28 ++- .../AppwriteOrphanSchemaDropTest.php | 213 ++++++++++++++++++ 3 files changed, 250 insertions(+), 3 deletions(-) create mode 100644 tests/Destinations/AppwriteOrphanSchemaDropTest.php diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 049e7ba8..0c5b2c2a 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -7074,12 +7074,24 @@ parameters: count: 1 path: tests/Destinations/AppwriteLegacyIndexMetadataTest.php + - + message: '#^Parameter \#1 \$callback of function array_map expects \(callable\(mixed\)\: mixed\)\|null, Closure\(Throwable\)\: string given\.$#' + identifier: argument.type + count: 1 + path: tests/Destinations/AppwriteOrphanSchemaDropTest.php + - message: '#^Parameter \#2 \$values of static method Utopia\\Query\\Query\:\:equal\(\) expects array\\|bool\|float\|int\|string\|null\>, array\ given\.$#' identifier: argument.type count: 2 path: tests/Destinations/AppwriteLegacyIndexMetadataTest.php + - + message: '#^Parameter \#2 \$values of static method Utopia\\Query\\Query\:\:equal\(\) expects array\\|bool\|float\|int\|string\|null\>, array\ given\.$#' + identifier: argument.type + count: 2 + path: tests/Destinations/AppwriteOrphanSchemaDropTest.php + - message: '#^Possibly invalid array key type int\<0, max\>\|null\.$#' identifier: offsetAccess.invalidOffset diff --git a/src/Destinations/Appwrite.php b/src/Destinations/Appwrite.php index dbc21979..bcba1897 100644 --- a/src/Destinations/Appwrite.php +++ b/src/Destinations/Appwrite.php @@ -37,6 +37,7 @@ use Utopia\Database\Exception\Authorization as AuthorizationException; use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Exception\Limit as LimitException; +use Utopia\Database\Exception\NotFound as NotFoundException; use Utopia\Database\Exception\Structure as StructureException; use Utopia\Database\Format; use Utopia\Database\Id; @@ -1489,7 +1490,7 @@ protected function createIndex(Index $resource): bool } if ($action === SchemaAction::Overwrite) { - $dbForDatabases->deleteIndex($this->tableCollectionId($database, $table), $resource->getKey()); + $this->dropFromSchema(fn () => $dbForDatabases->deleteIndex($this->tableCollectionId($database, $table), $resource->getKey())); $this->dbForProject->deleteDocument(self::META_INDEXES, $indexMetaId); $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $table->getId()); // Reload $table — in-memory copy still holds the dropped index, so IndexValidator below would over-count. @@ -1753,9 +1754,9 @@ private function dropAttributeForRecreate( $isRelationship = $resource->getType() === Column::TYPE_RELATIONSHIP; if ($isRelationship) { - $dbForDatabases->deleteRelationship($collectionId, $resource->getKey()); + $this->dropFromSchema(fn () => $dbForDatabases->deleteRelationship($collectionId, $resource->getKey())); } else { - $dbForDatabases->deleteAttribute($collectionId, $resource->getKey()); + $this->dropFromSchema(fn () => $dbForDatabases->deleteAttribute($collectionId, $resource->getKey())); } $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $attributeMetaId); @@ -2369,6 +2370,27 @@ private function dropOrphanIndex( $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $table->getId()); } + /** + * Drops a column or index from the destination schema, treating "the schema no longer + * holds it" as the end state the drop asked for rather than an error. + * + * The meta document and the schema are two non-atomic writes, so a run killed between + * them — or a destination carrying an orphan left by the stuck-index bug fixed in + * appwrite/appwrite#15471 — leaves a meta document whose schema counterpart is gone. + * `NotFound` there used to abort the import and strand the orphan for good, since the + * caller never reached the meta delete that would have let the recreate through. Unlike + * {@see self::bestEffort()} this narrows to `NotFound`, so a dependent index + * (`Dependency`) or a relationship dropped as a column still surfaces. + */ + private function dropFromSchema(callable $drop): void + { + try { + $drop(); + } catch (NotFoundException) { + // Already absent from the schema; the caller still removes the meta document. + } + } + /** Swallows deletion errors — a prior run or relationship cascade may have already removed the target. */ private function bestEffort(callable $fn): void { diff --git a/tests/Destinations/AppwriteOrphanSchemaDropTest.php b/tests/Destinations/AppwriteOrphanSchemaDropTest.php new file mode 100644 index 00000000..b5b115c3 --- /dev/null +++ b/tests/Destinations/AppwriteOrphanSchemaDropTest.php @@ -0,0 +1,213 @@ +projectDatabase(); + + [$first] = $this->transferSchema( + fn (Table $table): array => [...$this->columns($table), $this->index($table, ['ASC', 'ASC'])], + $database, + OnDuplicate::Fail, + self::OLDER_UPDATED_AT, + ); + $this->assertSame([], $this->errorMessages($first)); + $this->assertNotNull($this->schemaIndex($database), 'The index must reach the schema before it is orphaned.'); + + $this->orphanIndex($database); + + [$second, $resources] = $this->transferSchema( + fn (Table $table): array => [...$this->columns($table), $this->index($table, ['ASC', 'DESC'])], + $database, + OnDuplicate::Overwrite, + self::NEWER_UPDATED_AT, + ); + + $this->assertSame( + [], + $this->errorMessages($second), + 'Dropping an index the schema no longer holds must not fail the import.', + ); + + $index = \end($resources); + $this->assertInstanceOf(Index::class, $index); + $this->assertSame(Resource::STATUS_SUCCESS, $index->getStatus()); + + $recreated = $this->schemaIndex($database); + $this->assertNotNull($recreated, 'The orphaned index must be recreated in the schema.'); + $this->assertSame( + ['ASC', 'DESC'], + \array_map(static fn (mixed $order): ?string => $order?->value, $recreated->orders), + 'The recreated index must carry the source spec, not the orphaned one.', + ); + $this->assertCount(1, $this->indexDocuments($database), 'The orphan must be replaced, not duplicated.'); + } + + public function testAColumnTheSchemaNoLongerHoldsIsRecreated(): void + { + $database = $this->projectDatabase(); + + [, $first] = $this->transferColumn( + static fn (Table $table): Column => new Text('title', $table, size: 100), + $database, + OnDuplicate::Fail, + self::OLDER_UPDATED_AT, + ); + $this->assertSame([], $this->errorMessages($first)); + + $this->orphanColumn($database, 'title'); + + // A type change has no in-place primitive, so the overwrite goes through the drop. + [, $destination, $column] = $this->transferColumn( + static fn (Table $table): Column => new Integer('title', $table), + $database, + OnDuplicate::Overwrite, + self::NEWER_UPDATED_AT, + ); + + $this->assertSame( + [], + $this->errorMessages($destination), + 'Dropping a column the schema no longer holds must not fail the import.', + ); + $this->assertSame(Resource::STATUS_SUCCESS, $column->getStatus()); + $this->assertSame( + ColumnType::Integer, + $this->physicalColumn($database, 'title')->type, + 'The orphaned column must be recreated with the source type.', + ); + } + + /** + * Drops the schema copy of the index and leaves its meta document behind — the state + * the upstream stuck-index bug left on a project. + */ + private function orphanIndex(UtopiaDatabase $database): void + { + $collectionId = $this->tableCollectionId($database); + $database->getAuthorization()->skip( + static fn () => $database->deleteIndex($collectionId, self::INDEX_KEY), + ); + $this->purgeTable($database); + + $this->assertNull($this->schemaIndex($database), 'The orphan must have no schema counterpart.'); + $this->assertCount(1, $this->indexDocuments($database), 'The orphan must keep its meta document.'); + } + + private function orphanColumn(UtopiaDatabase $database, string $key): void + { + $collectionId = $this->tableCollectionId($database); + $database->getAuthorization()->skip( + static fn () => $database->deleteAttribute($collectionId, $key), + ); + $this->purgeTable($database); + + $this->assertFalse( + $this->attributeDocument($database)->isEmpty(), + 'The orphan must keep its meta document.', + ); + } + + /** + * @return list + */ + private function columns(Table $table): array + { + return [new Text('title', $table, size: 100), new Text('slug', $table, size: 100)]; + } + + /** + * @param list $orders + */ + private function index(Table $table, array $orders): Index + { + return new Index(self::INDEX_KEY, self::INDEX_KEY, $table, 'key', ['title', 'slug'], [], $orders); + } + + private function schemaIndex(UtopiaDatabase $database): ?UtopiaIndex + { + $collectionId = $this->tableCollectionId($database); + $collection = $database->getAuthorization()->skip( + static fn () => $database->getCollection($collectionId), + ); + + foreach ($collection->indexes() as $index) { + if ($index->key === self::INDEX_KEY) { + return $index; + } + } + + return null; + } + + /** + * @return array + */ + private function indexDocuments(UtopiaDatabase $database): array + { + return $database->getAuthorization()->skip( + static fn (): array => $database->find('indexes'), + ); + } + + private function tableCollectionId(UtopiaDatabase $database): string + { + $shop = $this->document($database, 'databases', 'shop'); + $table = $this->document($database, 'database_'.$shop->getSequence(), 'products'); + + return 'database_'.$shop->getSequence().'_collection_'.$table->getSequence(); + } + + /** The table document caches its subqueried columns and indexes; a direct schema edit bypasses that. */ + private function purgeTable(UtopiaDatabase $database): void + { + $shop = $this->document($database, 'databases', 'shop'); + $database->getAuthorization()->skip( + static fn () => $database->purgeCachedDocument('database_'.$shop->getSequence(), 'products'), + ); + } +}