Skip to content

Commit 4925039

Browse files
fix(driver-sqlite-wasm): disconnect() waits for its final flush instead of the pool 5 s destroy timeout (#37450)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg8ZBQe4UHadd2fGHGeWRW9V)_ repo:objectstack#5 · os-bill · session_01Utp6CbdHk3orAeensH6EzS Fixes #37429 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:开发用的本地数据库在停止服务或启动被拒时,数据一定先写到磁盘再返回;正常情况下用户无感。 - 为什么做:合并队列里一个升级测试时好时坏,把无关的变更踢出队列;查明原因是本地数据库在关闭时最多只等五秒落盘。 - 出错会怎样:最坏是关闭服务时多等几秒;改动只在一个驱动里,可直接撤回。 - 要你做什么:无。 ## What changes - **Root cause** (full evidence on the card): `SqliteWasmDriver.disconnect()` handed its final flush to the connection's `close()`, which runs as the Knex pool's destroyer. tarn waits at most `destroyTimeoutMillis` (5000 ms by default) for a destroyer, then resolves anyway. So when a whole-image write and fsync took longer than 5 s on a loaded runner, `disconnect()` returned with the flush still in flight. A refused boot's rollback (the datasource-admin plugin's `disconnectAll()`) therefore returned before the additive schema sync was on disk, and step 1b of the dogfood test read the v17 bytes. CI run 45751259665: rollback at 04:04:42.799, eviction 5.005 s later, then 1b red. - **Fix**: `disconnect()` now awaits `flush()` itself, with no timeout, before it destroys the pool, and does so only when the pool holds a connection. A flush that fails is thrown once the pool is destroyed (try/finally). - **Pin**: a new top-level `describe` in `sqlite-wasm-driver-durability.test.ts`. A pool `destroyTimeoutMillis: 50` and a 400 ms fsync stand in for the loaded disk. The file must hold the committed row as soon as `disconnect()` returns. - **Rework round (L1 S1/S2, nits N1/N3)**: - S1: a pin covers the published error path. When the final flush rejects, `disconnect()` rejects with that same error, and the pool has already been released (Knex's `client.pool` is gone). - S2: `disconnect()` memoises the disconnect in flight. A second call made while the first is destroying the pool now awaits the same promise, instead of waiting out Knex's 60 s acquire timeout on a pool that is being destroyed. The memo clears once that disconnect settles. A pin covers it: the destroyer is held for 300 ms, the second call is made after `pool.destroyed`, and it must settle in under 2 s. - N1: the code comment now names what bounds the await. - N3: the test's pool config is typed (Knex `PoolConfig`, no `as any`), and the test asserts the pool's effective `destroyTimeoutMillis` is 50. - N2: the patch of the worker-wide `FileHandle#sync` notes that it relies on vitest's per-file isolation. - The dogfood test is unchanged. There is no skip, retry, quarantine or timeout change. **Read first** (by risk): `packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-driver.ts`, the `disconnect()` hunk (try/finally order; the `hasLiveConnection` guard keeps a driver that never connected from opening the file). Then the durability test hunk. **Two-minute check**: `pnpm --filter @objectstack/driver-sqlite-wasm exec vitest run src/sqlite-wasm-driver-durability.test.ts`. Expect 4 passed. Delete the `await this.flush()` line and it turns red with `expected [] to deeply equal [ 'a1' ]`. ## Tests <details><summary>Package suite, ablation, deterministic repro, 20 repeats</summary> - `pnpm --filter @objectstack/driver-sqlite-wasm test`: Test Files 41 passed (41), Tests 769 passed (769). `typecheck` exit 0, and `--listFiles` shows it covers the durability test file. - Ablation through `scripts/ablation-replace.mjs`: the anchor `if (this.hasLiveConnection()) await this.flush();` went from 1 hit to 0, and the blob changed from 9a6e95c to e2c4a600. The run then failed: `1 failed | 3 passed`, `AssertionError: expected [] to deeply equal [ 'a1' ]`. Restore: the blob is back to 9a6e95c, equal to HEAD, and `git diff HEAD` is empty. The test imports `../src/index.js`, so no build was needed. - Deterministic repro (a scratch probe, deleted and never committed): the dogfood file with every `FileHandle.sync` in the worker delayed. - 6000 ms, before the fix: rollback, eviction 5.008 s later, 1b reads 4 columns, `2 failed | 2 passed`. This matches the CI signature. - 6000 ms, after the fix (driver `dist/` rebuilt, marker confirmed in dist): eviction about 10.7 s after rollback (the flush was awaited), `4 passed`. - 1500 ms, before the fix: green. Under the 5 s timeout, the defect cannot show. - Rework head: `pnpm --filter @objectstack/driver-sqlite-wasm test` gives Test Files 41 passed (41), Tests 771 passed (771); `typecheck` exit 0. Memo ablation (`if (!this.disconnecting) {` replaced by `if (true) {`, anchor 1 hit to 0, blob 9df1279 to 24c78a23): the overlap pin goes red with `Test timed out in 10000ms`, `1 failed | 5 passed`. Restored: blob equals HEAD and `git diff HEAD` is empty. - 20 repeated runs of `test/organization-ownership-boot-refusal-order.dogfood.test.ts` on the fixed tree (`pnpm --filter @objectstack/dogfood exec vitest run --maxWorkers=2 FILE`, 20 separate invocations under the verify lock): `SUMMARY pass=20 fail=0`, each `Tests 4 passed (4)`. </details> ## Acceptance notes - Reach beyond this test: any graceful stop of a file-backed sqlite-wasm datasource whose final flush takes more than 5 s used to return before the data was on disk. The sqlite-wasm driver is the default fallback for `os dev`, and a process that exits straight after a stop loses those writes. Covered by the same fix. - Rollback vs shutdown asymmetry, tracked in #37462 (filed by the area under #37429). A failed boot's `rollbackStartedPlugins()` destroys only plugins whose `start()` succeeded, while `performShutdown()` destroys every plugin with a `destroy`. `DefaultDatasourcePlugin` is not init-only: it has `init`, `start` and `destroy`, so this rollback skips it only when its `start()` has not completed. It did not cause #37429, because the datasource-admin plugin's `destroy()` closes the default pool. - The await in `disconnect()` has no timeout of its own. A kernel's graceful `shutdown()` caps it with `shutdownTimeout`; a refused boot's rollback has no cap, by design, because returning before the data is on disk is the defect this PR fixes. ## Verification <details><summary>Local gates (derived with --commands, narrowed to this diff)</summary> - 62 of the 64 derived commands exited 0. - NOT MEASURED, reason environmental (CI runs both): - `node scripts/check-plugin-teardown-shape.mjs --self-test`: exit 3, its pinned positive-control commit is unreachable from this shallow clone. - `pnpm check:dual-build-cjs-loads`: exit 3, PREREQUISITE NOT MET, unrelated packages have no `dist/` here. - `--ran` reconciliation: 64 derived, 62 run, the 2 above reported as unrun. - `node scripts/pm/overlap-check.mjs --branch=HEAD`: VERDICT clean. - origin/main merged once before opening. The merge brought in driver-sql schema-sync changes, so the driver suite and the dogfood file were re-run on the merged head. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CbdHk3orAeensH6EzS <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CbdHk3orAeensH6EzS --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a46efa8 commit 4925039

3 files changed

Lines changed: 172 additions & 2 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/driver-sqlite-wasm': patch
3+
---
4+
5+
fix(driver-sqlite-wasm): `disconnect()` returns only after the final flush is on disk
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A file-backed sqlite-wasm datasource wrote its final image from the connection's `close()`, which the Knex pool runs as its destroyer. The pool (tarn) stops waiting for a destroyer after 5 s and resolves anyway. So when that flush (a whole-image write and fsync) took longer, `disconnect()`, a kernel's `stop()` and a refused boot's rollback all returned before the data was on disk. A process that exited right after lost the committed writes, and a reader of the file got the old bytes. `disconnect()` now awaits the flush itself, with no timeout, before it closes the pool, and a flush that fails is thrown from `disconnect()`. A second `disconnect()` that arrives while the first one is still running shares the first one's teardown, instead of waiting for a connection from a pool that is being destroyed.

‎packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-driver-durability.test.ts‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,115 @@ describe('SqliteWasmDriver durability & resilience', () => {
126126
expect(rows[0].note).toBeNull();
127127
});
128128
});
129+
130+
/**
131+
* `disconnect()` is the durability boundary: when it returns, the committed
132+
* image is on disk, however long the final flush takes. The connection's own
133+
* final flush runs as the Knex pool's destroyer, and tarn stops waiting for a
134+
* destroyer after `destroyTimeoutMillis` (5 s by default). At that point it
135+
* resolves anyway. A whole-image fsync on a loaded disk can take longer than
136+
* that. A short pool timeout and a slowed fsync stand in for the loaded disk
137+
* here. Measured: a refused boot's rollback returned before its schema sync
138+
* was on disk, and the dogfood ownership-upgrade test read the v17 bytes.
139+
*/
140+
describe('SqliteWasmDriver disconnect waits for its final flush', () => {
141+
let dir: string | undefined;
142+
let restoreSync: (() => void) | undefined;
143+
144+
afterEach(() => {
145+
restoreSync?.();
146+
restoreSync = undefined;
147+
if (dir) rmSync(dir, { recursive: true, force: true });
148+
dir = undefined;
149+
});
150+
151+
/**
152+
* Replace `FileHandle#sync` for this worker until `restoreSync` runs. The
153+
* patch is worker-wide, which is safe only because vitest isolates each test
154+
* file: under `isolate: false` it would reach the neighbouring files.
155+
*/
156+
async function patchSync(file: string, body: (sync: () => Promise<void>) => Promise<void>): Promise<void> {
157+
const { open } = await import('node:fs/promises');
158+
const probe = await open(file, 'r');
159+
const proto = Object.getPrototypeOf(probe) as { sync: (...args: unknown[]) => Promise<void> };
160+
await probe.close();
161+
const sync = proto.sync;
162+
proto.sync = function (this: unknown, ...args: unknown[]) {
163+
return body(() => sync.apply(this, args));
164+
};
165+
restoreSync = () => {
166+
proto.sync = sync;
167+
};
168+
}
169+
170+
/** A driver over a fresh file whose pool stops waiting for a destroyer after 50 ms, with one row written. */
171+
async function driverWithPendingRow(): Promise<{ driver: SqliteWasmDriver; file: string }> {
172+
dir = mkdtempSync(join(tmpdir(), 'wasm-dur-disconnect-'));
173+
const file = join(dir, 'slow.db');
174+
const driver = new SqliteWasmDriver({
175+
filename: file,
176+
persist: 'on-disconnect',
177+
pool: { min: 1, max: 1, destroyTimeoutMillis: 50 },
178+
});
179+
await driver.initObjects([{ name: 'acct', fields: { name: { type: 'string' } } }]);
180+
// The premise: the pool really carries the short destroy timeout.
181+
expect((driver as any).knex.client.pool.destroyTimeoutMillis).toBe(50);
182+
await (driver as any).flush();
183+
await (driver as any).knex('acct').insert({ id: 'a1', name: 'A' });
184+
return { driver, file };
185+
}
186+
187+
it('a write committed before disconnect() is on disk when it returns, even when the flush outlasts the pool destroy timeout', async () => {
188+
const { driver, file } = await driverWithPendingRow();
189+
// Every fsync from here on takes 400 ms, eight times the pool's destroy timeout.
190+
await patchSync(file, async (sync) => {
191+
await new Promise((r) => setTimeout(r, 400));
192+
return sync();
193+
});
194+
195+
await driver.disconnect();
196+
197+
const reopened = new SqliteWasmDriver({ filename: file, persist: 'on-disconnect' });
198+
try {
199+
const rows = await (reopened as any).knex('acct');
200+
expect(rows.map((r: { id: string }) => r.id)).toEqual(['a1']);
201+
} finally {
202+
restoreSync?.();
203+
restoreSync = undefined;
204+
await reopened.disconnect();
205+
}
206+
});
207+
208+
it('a final flush that fails rejects disconnect() with that error, and the pool is released first', async () => {
209+
const { driver, file } = await driverWithPendingRow();
210+
const failure = new Error('fsync refused (test)');
211+
await patchSync(file, async () => {
212+
throw failure;
213+
});
214+
215+
await expect(driver.disconnect()).rejects.toBe(failure);
216+
// Released: Knex drops its pool once `destroy()` has run.
217+
expect((driver as any).knex.client.pool).toBeUndefined();
218+
});
219+
220+
it('a second disconnect() during the first one waits for that same teardown, not for an acquire timeout', async () => {
221+
const { driver } = await driverWithPendingRow();
222+
const client = (driver as any).knex.client;
223+
const pool = client.pool;
224+
// Hold the pool's destroyer for 300 ms, so the pool sits in `destroyed`
225+
// with the connection still in its free list (tarn clears that last).
226+
const destroyRaw = client.destroyRawConnection.bind(client);
227+
client.destroyRawConnection = async (conn: unknown) => {
228+
await new Promise((r) => setTimeout(r, 300));
229+
return destroyRaw(conn);
230+
};
231+
232+
const first = driver.disconnect();
233+
while (!pool.destroyed) await new Promise((r) => setTimeout(r, 5));
234+
const started = Date.now();
235+
const second = driver.disconnect();
236+
await Promise.all([first, second]);
237+
// Settles with the first teardown (about 300 ms), not after Knex's 60 s acquire timeout.
238+
expect(Date.now() - started).toBeLessThan(2_000);
239+
}, 10_000);
240+
});

‎packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-driver.ts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,26 @@ export class SqliteWasmDriver extends SqlDriver {
155155
}
156156
}
157157

158-
override async disconnect(): Promise<void> {
158+
/**
159+
* The disconnect in flight, shared by every caller that arrives during it.
160+
* A second call made while the first is destroying the pool would otherwise
161+
* see the connection still in the pool's free list, try to flush it, and
162+
* wait on an acquire from a pool that is being destroyed, until Knex's
163+
* acquire timeout (60 s). Cleared once that disconnect settles, so a later
164+
* call takes the path a disconnected driver takes.
165+
*/
166+
private disconnecting: Promise<void> | null = null;
167+
168+
override disconnect(): Promise<void> {
169+
if (!this.disconnecting) {
170+
this.disconnecting = this.disconnectOnce().finally(() => {
171+
this.disconnecting = null;
172+
});
173+
}
174+
return this.disconnecting;
175+
}
176+
177+
private async disconnectOnce(): Promise<void> {
159178
if (this.beforeExitHandler && typeof process !== 'undefined') {
160179
try {
161180
process.removeListener('beforeExit', this.beforeExitHandler);
@@ -164,7 +183,36 @@ export class SqliteWasmDriver extends SqlDriver {
164183
}
165184
this.beforeExitHandler = null;
166185
}
167-
await super.disconnect();
186+
// `disconnect()` is the durability boundary (`BootOptions.databaseFile` in
187+
// `@objectstack/verify`, a kernel's `stop()`, a refused boot's rollback):
188+
// when it returns, everything committed is on disk. The connection's own
189+
// `close()` flushes too, but it runs as the Knex pool's destroyer, and tarn
190+
// bounds a destroyer by `destroyTimeoutMillis` (5 s by default). When that
191+
// time runs out, tarn logs the rejection to its event handlers and resolves
192+
// anyway. So a final flush slower than that (a whole-image fsync on a
193+
// loaded disk) was still running when `disconnect()` returned, and a reader
194+
// of the file met the bytes from before it. The flush is awaited HERE, with
195+
// no timeout of its own. What bounds it is the caller: a kernel's graceful
196+
// `shutdown()` is capped by its `shutdownTimeout`, while a failed boot's
197+
// rollback has no cap, deliberately, because returning before the data is
198+
// on disk is the defect this closes. A flush that fails is thrown once the
199+
// pool is gone.
200+
try {
201+
if (this.hasLiveConnection()) await this.flush();
202+
} finally {
203+
await super.disconnect();
204+
}
205+
}
206+
207+
/**
208+
* Whether the pool holds a connection. A driver that never opened one has
209+
* nothing to flush, and acquiring a connection just to flush it would open
210+
* (and create) the file.
211+
*/
212+
private hasLiveConnection(): boolean {
213+
const pool = (this as any).knex?.client?.pool;
214+
if (!pool || typeof pool.numFree !== 'function' || typeof pool.numUsed !== 'function') return false;
215+
return pool.numFree() + pool.numUsed() > 0;
168216
}
169217

170218
/**

0 commit comments

Comments
 (0)