From b2c5fbea601b5a49bb9d3e33d4be30eeb96e9e2b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 02:14:39 +0000 Subject: [PATCH 1/2] fix: close the collection of a failed or interrupted addCollections() call A collection that was created by addCollections() but never reached database.collections was not closed when its creation failed (for example DM4 from the autoMigrate migration) or when database.close() was called while the automatic migration was still running. Its timeouts, like the 60 seconds wait of the cleanup plugin, kept the process alive. createRxCollection() now closes the collection when the creation fails and database.close() also closes the collections of this database that are still being created. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015P6w6hnnyVPXwotts6YQ2F --- ...failed-or-interrupted-add-collections.json | 6 ++ src/rx-collection.ts | 8 +- src/rx-database.ts | 17 +++- test/unit/migration-schema.test.ts | 94 +++++++++++++++++++ 4 files changed, 118 insertions(+), 7 deletions(-) create mode 100644 orga/changelog/fix-close-collection-of-failed-or-interrupted-add-collections.json diff --git a/orga/changelog/fix-close-collection-of-failed-or-interrupted-add-collections.json b/orga/changelog/fix-close-collection-of-failed-or-interrupted-add-collections.json new file mode 100644 index 00000000000..a07c9170a80 --- /dev/null +++ b/orga/changelog/fix-close-collection-of-failed-or-interrupted-add-collections.json @@ -0,0 +1,6 @@ +{ + "$schema": "./schema.json", + "text": "FIX a collection that was created by an `addCollections()` call which failed (for example with `DM4` from the `autoMigrate` migration) or which was still running when `database.close()` was called, was never closed, so its timeouts (like the 60 seconds wait of the cleanup plugin) kept the JavaScript process alive", + "links": [], + "priority": 5 +} diff --git a/src/rx-collection.ts b/src/rx-collection.ts index f8facf57a22..6fb9d93ad78 100644 --- a/src/rx-collection.ts +++ b/src/rx-collection.ts @@ -1363,10 +1363,12 @@ export async function createRxCollection( } catch (err) { /** * If the collection creation fails, - * we yet have to close the storage instances. + * the collection must be closed so that its storage instance, + * its timeouts and everything that was started by the plugin hooks is stopped. + * When prepare() has failed before the storage instance was wrapped, + * the given storage instance is closed directly. */ - OPEN_COLLECTIONS.delete(collection); - await storageInstance.close(); + await collection.close().catch(() => storageInstance.close()); throw err; } diff --git a/src/rx-database.ts b/src/rx-database.ts index 2d948c7bb45..7caf48e6efc 100644 --- a/src/rx-database.ts +++ b/src/rx-database.ts @@ -70,7 +70,8 @@ import { mergeMap } from 'rxjs/operators'; import { - createRxCollection + createRxCollection, + OPEN_COLLECTIONS } from './rx-collection.ts'; import { flatCloneDocWithMeta, @@ -657,11 +658,19 @@ export class RxDatabaseBase< closingError = err as Error; } - // close all collections + /** + * Close all collections. + * This includes collections that are still created by a running addCollections() call + * and therefore are not in this.collections. + */ await Promise.all( - Object.keys(this.collections as any) - .map(key => (this.collections as any)[key]) + Array.from(OPEN_COLLECTIONS) + .filter(col => col.database === this.asRxDatabase) .map(col => col.close()) + .concat( + Object.keys(this.collections as any) + .map(key => (this.collections as any)[key].close()) + ) ); // close internal storage instances diff --git a/test/unit/migration-schema.test.ts b/test/unit/migration-schema.test.ts index 737429b310d..410dc82a307 100644 --- a/test/unit/migration-schema.test.ts +++ b/test/unit/migration-schema.test.ts @@ -2794,6 +2794,100 @@ describe('migration-schema.test.ts', function () { await db2.remove(); }); + describe('collection of a not finished addCollections() call', () => { + const schemaV0 = { + version: 0, + primaryKey: 'id', + type: 'object', + properties: { + id: { + type: 'string', + maxLength: 100 + }, + name: { + type: 'string' + } + }, + required: ['id', 'name'] + } as const; + const schemaV1 = Object.assign({}, schemaV0, { version: 1 } as const); + type DocType = { id: string; name: string; }; + type Collections = { todos: RxCollection; }; + async function createDatabaseWithOldDocument(name: string, storage: RxStorage) { + const db = await createRxDatabase({ + name, + storage + }); + await db.addCollections({ todos: { schema: schemaV0 } }); + await db.todos.insert({ id: 'todo1', name: 'Learn RxDB' }); + await db.close(); + } + it('should close the collection when the automatic migration fails', async () => { + const name = randomToken(10); + const storage = config.storage.getStorage(); + await createDatabaseWithOldDocument(name, storage); + + const db = await createRxDatabase({ + name, + storage + }); + const createdCollections: RxCollection[] = []; + await assertThrows( + () => db.addCollections({ + todos: { + schema: schemaV1, + migrationStrategies: { + 1: (_oldDoc, collection) => { + createdCollections.push(collection); + throw new Error('migration strategy failed'); + } + } + } + }), + 'RxError', + 'DM4' + ); + assert.ok(createdCollections.length > 0); + assert.strictEqual(createdCollections[0].closed, true); + assert.deepStrictEqual(Object.keys(db.collections), []); + + await db.close(); + }); + it('should close the collection when the database is closed during the automatic migration', async () => { + const name = randomToken(10); + const storage = config.storage.getStorage(); + await createDatabaseWithOldDocument(name, storage); + + const db = await createRxDatabase({ + name, + storage + }); + const createdCollections: RxCollection[] = []; + let releaseStrategy: () => void = () => { }; + const strategyReleased = new Promise(res => releaseStrategy = res); + const addPromise = db.addCollections({ + todos: { + schema: schemaV1, + migrationStrategies: { + 1: async (oldDoc, collection) => { + createdCollections.push(collection); + await strategyReleased; + return oldDoc; + } + } + } + }); + addPromise.catch(() => { }); + await waitUntil(() => createdCollections.length > 0); + assert.strictEqual(createdCollections[0].closed, false); + + await db.close(); + releaseStrategy(); + + assert.strictEqual(createdCollections[0].closed, true); + assert.deepStrictEqual(Object.keys(db.collections), []); + }); + }); /** * An interrupted schema migration could never complete. * As soon as a document was already stored in the new storage, From 945e717d324006a061c7fa9b5a9d95f6435d3e10 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 14:42:43 +0000 Subject: [PATCH 2/2] fix: database.close() closed each collection twice close() collected the collections from OPEN_COLLECTIONS and from this.collections. A normal collection is in both, so its close() ran twice in the same tick and the onClose handlers ran twice. The GraphQL replication then released its websocket reference twice and threw "missing value from map ws://..." as an unhandled rejection. Both lists are now merged into a Set so that each collection is closed once. The test 'should close the collection when the database is closed during the automatic migration' awaited database.close() before it released the migration strategy. Since #9661 closing waits for the running batch of the canceled migration, so the test never ended. It now releases the strategy after the migration was canceled and then awaits the close. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_015P6w6hnnyVPXwotts6YQ2F --- src/rx-database.ts | 14 ++++++++------ test/unit/migration-schema.test.ts | 9 ++++++++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/rx-database.ts b/src/rx-database.ts index 7caf48e6efc..b405d8814e2 100644 --- a/src/rx-database.ts +++ b/src/rx-database.ts @@ -662,15 +662,17 @@ export class RxDatabaseBase< * Close all collections. * This includes collections that are still created by a running addCollections() call * and therefore are not in this.collections. + * Each collection must be closed only once because + * a second close() call would run the onClose handlers again. */ await Promise.all( - Array.from(OPEN_COLLECTIONS) - .filter(col => col.database === this.asRxDatabase) - .map(col => col.close()) - .concat( - Object.keys(this.collections as any) - .map(key => (this.collections as any)[key].close()) + Array.from( + new Set( + Array.from(OPEN_COLLECTIONS) + .filter(col => col.database === this.asRxDatabase) + .concat(Object.values(this.collections as any)) ) + ).map(col => col.close()) ); // close internal storage instances diff --git a/test/unit/migration-schema.test.ts b/test/unit/migration-schema.test.ts index 410dc82a307..f81a4048c71 100644 --- a/test/unit/migration-schema.test.ts +++ b/test/unit/migration-schema.test.ts @@ -2881,8 +2881,15 @@ describe('migration-schema.test.ts', function () { await waitUntil(() => createdCollections.length > 0); assert.strictEqual(createdCollections[0].closed, false); - await db.close(); + /** + * Closing the database cancels the migration and then waits + * until the running batch of the migration has ended, + * so the strategy must be released before the close can resolve. + */ + const closePromise = db.close(); + await waitUntil(() => createdCollections[0].getMigrationState().canceled); releaseStrategy(); + await closePromise; assert.strictEqual(createdCollections[0].closed, true); assert.deepStrictEqual(Object.keys(db.collections), []);