From ccd5777ace58387134f93394ad9ed9bb0601634d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 11:08:26 -0800 Subject: [PATCH 1/9] test(shared): an abandoned read must not block the next read Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/nodeSqliteClient.test.ts | 125 ++++++++++++++++++- 1 file changed, 124 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 5c7b086642a42..a4afe26515177 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -29,17 +29,29 @@ const workerExits = vi.hoisted(() => new WeakMap ({ on: false, readyOnTerminate: false })); const failingWorkers = vi.hoisted(() => ({ message: undefined as string | undefined })); const checkpointWorkers = vi.hoisted((): Array => []); +const statementStarts = vi.hoisted(() => ({ notify: (_sql: string) => {} })); +const heldExits = vi.hoisted(() => ({ + on: false, + held: [] as Array<{ worker: NodeWorkerThreads.Worker; code: unknown }>, +})); vi.mock("node:worker_threads", async (importOriginal) => { const actual = await importOriginal(); class RecordedWorker extends actual.Worker { constructor(...args: ConstructorParameters) { + const [source, options] = args; super( ...((silentWorkers.on ? ["setInterval(() => {}, 1 << 30);", { eval: true }] : failingWorkers.message !== undefined ? [`throw new Error(${JSON.stringify(failingWorkers.message)});`, { eval: true }] - : args) as ConstructorParameters), + : [ + String(source).replace( + 'operation = "execute";', + 'operation = "execute"; parentPort.postMessage({ type: "executing", sql });', + ), + options, + ]) as ConstructorParameters), ); startedWorkers.push(this); workerExits.set(this, new Promise((resolve) => this.once("exit", () => resolve()))); @@ -50,6 +62,18 @@ vi.mock("node:worker_threads", async (importOriginal) => { if (silentWorkers.readyOnTerminate) this.emit("message", { type: "ready" }); return super.terminate(); } + override emit(event: string | symbol, ...values: Array) { + if (event === "message" && values[0]?.type === "executing") { + statementStarts.notify(values[0].sql); + return true; + } + // Stands in for a retired worker whose native statement has not returned yet. + if (event === "exit" && heldExits.on) { + heldExits.held.push({ worker: this, code: values[0] }); + return true; + } + return super.emit(event, ...values); + } } return { ...actual, Worker: RecordedWorker }; }); @@ -574,6 +598,105 @@ it.effect("fails a read-only transaction whose reader stops, then starts a new r ), ); +const slowCount = ` + WITH RECURSIVE sequence(n) AS ( + SELECT 1 UNION ALL SELECT n + 1 FROM sequence WHERE n < 5000000 + ) SELECT COUNT(*) AS count FROM sequence +`; + +const startSlowRead = ( + read: (slow: Effect.Effect) => Effect.Effect, + sql: SqlClient.SqlClient, +) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + statementStarts.notify = (statement) => { + if (statement.includes("WITH RECURSIVE")) Deferred.doneUnsafe(started, Effect.void); + }; + const fiber = yield* Effect.forkChild(read(sql.unsafe(slowCount)).pipe(SqliteClient.readOnly), { + startImmediately: true, + }); + yield* Deferred.await(started); + return fiber; + }); + +it.effect("gives the next read a new reader when a read is abandoned mid-statement", () => + withReaderClient((sql) => + Effect.gen(function* () { + const startedBefore = startedWorkers.length; + yield* Fiber.interrupt(yield* startSlowRead((slow) => slow, sql)); + + assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); + assert.equal(startedWorkers.length, startedBefore + 2); + }), + ), +); + +it.effect( + "settles a read-only transaction abandoned mid-statement, then reads on a new reader", + () => + withReaderClient((sql) => + Effect.gen(function* () { + const startedBefore = startedWorkers.length; + const transaction = yield* startSlowRead( + (slow) => sql.withTransaction(Effect.andThen(countEntries(sql), slow)), + sql, + ); + yield* Fiber.interrupt(transaction); + + assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(transaction))); + assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); + assert.equal(startedWorkers.length, startedBefore + 2); + }), + ), +); + +it.effect("keeps an abandoned read on its reader once four readers are still retiring", () => + withReaderClient((sql) => + Effect.gen(function* () { + yield* Effect.acquireRelease( + Effect.sync(() => { + heldExits.on = true; + }), + () => + Effect.sync(() => { + heldExits.on = false; + for (const { worker, code } of heldExits.held.splice(0)) worker.emit("exit", code); + }), + ); + const startedBefore = startedWorkers.length; + for (let index = 0; index < 5; index++) { + yield* Fiber.interrupt(yield* startSlowRead((slow) => slow, sql)); + } + + assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); + assert.equal(startedWorkers.length, startedBefore + 5); + }).pipe(Effect.scoped), + ), +); + +it.effect("keeps the reader when a read-only transaction is interrupted between statements", () => + withReaderClient((sql) => + Effect.gen(function* () { + const read = yield* Deferred.make(); + const transaction = yield* sql + .withTransaction( + countEntries(sql).pipe( + Effect.andThen(Deferred.succeed(read, undefined)), + Effect.andThen(Effect.never), + ), + ) + .pipe(SqliteClient.readOnly, Effect.forkChild); + yield* Deferred.await(read); + const startedBefore = startedWorkers.length; + yield* Fiber.interrupt(transaction); + + assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); + assert.equal(startedWorkers.length, startedBefore); + }), + ), +); + const withFileClient = ( setup: ( sql: SqlClient.SqlClient, From af6e8223d2e0bde176c743bfa05ce7734b2e62db Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 11:20:58 -0800 Subject: [PATCH 2/9] fix(shared): an abandoned database read no longer blocks the next one node:sqlite cannot interrupt a running statement. An interrupted read freed its reader slot while the worker still ran the statement, so the next read queued behind it. An interrupted read that is still running in its worker now stops and terminates that worker, and the slot starts a new one. The old thread exits when its statement returns. At most four readers retire at once; past that, an abandoned read keeps its reader busy as before. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/nodeSqliteClient.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index 51e47c4bb5530..afc16b43a8033 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -352,6 +352,9 @@ const READER_POOL_SIZE = 4; const READER_STARTUP_TIMEOUT = Duration.seconds(10); const READER_RETRY_DELAY = Duration.seconds(1); const READER_RETRY_MAX_DELAY = Duration.minutes(1); +// node:sqlite cannot interrupt a statement, so an abandoned read keeps its thread and connection +// until the statement returns. Past this many, an abandoned read keeps its reader busy instead. +const MAX_RETIRING_READERS = READER_POOL_SIZE; // Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement. const makeWorkerConnection = Effect.fnUntraced(function* (options: { @@ -359,6 +362,7 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { readonly role: "reader" | "writer"; readonly readOnly: boolean; readonly onReply?: () => void; + readonly pool?: { retiring: number }; }) { const label = options.role === "reader" ? "Database reader" : "Database writer"; const readOnly = options.readOnly; @@ -411,6 +415,7 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { ); } pending.clear(); + worker.unref(); }; worker.on("message", (reply: WorkerReply | WorkerStartup) => { if ("type" in reply) { @@ -469,6 +474,15 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { const cached = input.cached && !hasLargeBinding(input.params); // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin. worker.postMessage({ id, safeIntegers, ...input, cached, received }); + const pool = options.pool; + if (pool === undefined) return; + return Effect.sync(() => { + if (!pending.has(id) || pool.retiring >= MAX_RETIRING_READERS) return; + pool.retiring++; + worker.once("exit", () => pool.retiring--); + stop(`${label} abandoned a running statement`); + void worker.terminate(); + }); }); // A posted write runs to the end, as it did on the event loop; the caller and its lock // must not move on while the worker is still applying it. Reads stay cancellable. @@ -583,8 +597,11 @@ const startFailure = (error: SqlError) => { // A reader that cannot start turns off the whole pool, so routing never picks a dead slot, until // one background retry starts it again. -const makeReader = Effect.fnUntraced(function* (filename: string, pool: { unavailable: boolean }) { - const acquire = yield* makeWorkerConnection({ filename, role: "reader", readOnly: true }); +const makeReader = Effect.fnUntraced(function* ( + filename: string, + pool: { unavailable: boolean; retiring: number }, +) { + const acquire = yield* makeWorkerConnection({ filename, role: "reader", readOnly: true, pool }); const scope = yield* Effect.scope; const context = yield* Effect.context(); @@ -915,7 +932,7 @@ const make = Effect.fn("makeWithDatabase")(function* ( ); } } - const readerPool = { unavailable: false }; + const readerPool = { unavailable: false, retiring: 0 }; const readers = options.readerWorker && isFileDatabase ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () => From 87bc31886e1dd469ed71437e04d9fddf9d9f8c78 Mon Sep 17 00:00:00 2001 From: Zack Jackson <25274700+ScriptedAlchemy@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:51:12 -0800 Subject: [PATCH 3/9] fix(shared): leave retiring SQLite workers unreferenced --- packages/shared/src/nodeSqliteClient.test.ts | 4 ++++ packages/shared/src/nodeSqliteClient.ts | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index a4afe26515177..e38e91e04799d 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -624,8 +624,12 @@ it.effect("gives the next read a new reader when a read is abandoned mid-stateme withReaderClient((sql) => Effect.gen(function* () { const startedBefore = startedWorkers.length; + const referencedPorts = () => + process.getActiveResourcesInfo().filter((resource) => resource === "MessagePort").length; + const referencedBefore = referencedPorts(); yield* Fiber.interrupt(yield* startSlowRead((slow) => slow, sql)); + assert.equal(referencedPorts(), referencedBefore); assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); assert.equal(startedWorkers.length, startedBefore + 2); }), diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index afc16b43a8033..ccb210e51b811 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -480,8 +480,9 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { if (!pending.has(id) || pool.retiring >= MAX_RETIRING_READERS) return; pool.retiring++; worker.once("exit", () => pool.retiring--); - stop(`${label} abandoned a running statement`); + // terminate() references the worker again, so stop must unref it afterward. void worker.terminate(); + stop(`${label} abandoned a running statement`); }); }); // A posted write runs to the end, as it did on the event loop; the caller and its lock From f4f19f46384d61aebf5fc5077fbcd79ce46b9c8f Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 11:52:59 -0800 Subject: [PATCH 4/9] test(shared): an abandoned read keeps its reader busy without failing live reads The previous tests asserted that an interrupted read retires its reader at once. That rule failed live reads queued on the same reserved connection or transaction, and started a worker for every short cancellation. These tests describe the replacement rule: the abandoned statement keeps its reader occupied, the next read takes an idle reader, a reader is replaced only when every reader is busy with abandoned work, at most four replaced readers may still be running, and closing the client does not wait for abandoned work. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/nodeSqliteClient.test.ts | 237 +++++++++++++------ 1 file changed, 171 insertions(+), 66 deletions(-) diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index e38e91e04799d..ccc20859ed548 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -29,7 +29,14 @@ const workerExits = vi.hoisted(() => new WeakMap ({ on: false, readyOnTerminate: false })); const failingWorkers = vi.hoisted(() => ({ message: undefined as string | undefined })); const checkpointWorkers = vi.hoisted((): Array => []); -const statementStarts = vi.hoisted(() => ({ notify: (_sql: string) => {} })); +const posts = vi.hoisted(() => new Set<(sql: string, worker: NodeWorkerThreads.Worker) => void>()); +const readerWorkers = vi.hoisted(() => new WeakSet()); +// Statements marked "/* hold */" wait in their worker until the gate opens. +const statementGate = vi.hoisted(() => { + const gate = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)); + gate[0] = 1; + return gate; +}); const heldExits = vi.hoisted(() => ({ on: false, held: [] as Array<{ worker: NodeWorkerThreads.Worker; code: unknown }>, @@ -48,12 +55,13 @@ vi.mock("node:worker_threads", async (importOriginal) => { : [ String(source).replace( 'operation = "execute";', - 'operation = "execute"; parentPort.postMessage({ type: "executing", sql });', + 'operation = "execute"; if (sql.includes("/* hold */")) Atomics.wait(workerData.statementGate, 0, 0);', ), - options, + { ...options, workerData: { ...options?.workerData, statementGate } }, ]) as ConstructorParameters), ); startedWorkers.push(this); + if (options?.workerData?.requireWal === true) readerWorkers.add(this); workerExits.set(this, new Promise((resolve) => this.once("exit", () => resolve()))); if (args[1]?.workerData?.frames !== undefined) checkpointWorkers.push(this); } @@ -62,13 +70,13 @@ vi.mock("node:worker_threads", async (importOriginal) => { if (silentWorkers.readyOnTerminate) this.emit("message", { type: "ready" }); return super.terminate(); } + override postMessage(message: any, ...rest: Array) { + if (typeof message?.sql === "string") for (const notify of posts) notify(message.sql, this); + return super.postMessage(message, ...rest); + } override emit(event: string | symbol, ...values: Array) { - if (event === "message" && values[0]?.type === "executing") { - statementStarts.notify(values[0].sql); - return true; - } - // Stands in for a retired worker whose native statement has not returned yet. - if (event === "exit" && heldExits.on) { + // Stands in for a reader whose native statement has not returned yet. + if (event === "exit" && heldExits.on && readerWorkers.has(this)) { heldExits.held.push({ worker: this, code: values[0] }); return true; } @@ -598,87 +606,184 @@ it.effect("fails a read-only transaction whose reader stops, then starts a new r ), ); -const slowCount = ` - WITH RECURSIVE sequence(n) AS ( - SELECT 1 UNION ALL SELECT n + 1 FROM sequence WHERE n < 5000000 - ) SELECT COUNT(*) AS count FROM sequence -`; +const held = "SELECT /* hold */ COUNT(*) AS count FROM entries"; -const startSlowRead = ( - read: (slow: Effect.Effect) => Effect.Effect, - sql: SqlClient.SqlClient, -) => +const holdStatements = Effect.acquireRelease( + Effect.sync(() => Atomics.store(statementGate, 0, 0)), + () => releaseStatements, +); + +const releaseStatements = Effect.sync(() => { + Atomics.store(statementGate, 0, 1); + Atomics.notify(statementGate, 0); +}); + +const holdReaderExits = Effect.acquireRelease( + Effect.sync(() => { + heldExits.on = true; + }), + () => + Effect.sync(() => { + heldExits.on = false; + for (const { worker, code } of heldExits.held.splice(0)) worker.emit("exit", code); + }), +); + +const nextPost = (match: string) => Effect.gen(function* () { - const started = yield* Deferred.make(); - statementStarts.notify = (statement) => { - if (statement.includes("WITH RECURSIVE")) Deferred.doneUnsafe(started, Effect.void); + const posted = yield* Deferred.make(); + const notify = (sql: string, worker: NodeWorkerThreads.Worker) => { + if (!sql.includes(match)) return; + posts.delete(notify); + Deferred.doneUnsafe(posted, Effect.succeed(worker)); }; - const fiber = yield* Effect.forkChild(read(sql.unsafe(slowCount)).pipe(SqliteClient.readOnly), { - startImmediately: true, - }); - yield* Deferred.await(started); - return fiber; + posts.add(notify); + return posted; }); -it.effect("gives the next read a new reader when a read is abandoned mid-statement", () => - withReaderClient((sql) => - Effect.gen(function* () { - const startedBefore = startedWorkers.length; - const referencedPorts = () => - process.getActiveResourcesInfo().filter((resource) => resource === "MessagePort").length; - const referencedBefore = referencedPorts(); - yield* Fiber.interrupt(yield* startSlowRead((slow) => slow, sql)); +const startRead = (read: Effect.Effect, match: string) => + Effect.gen(function* () { + const posted = yield* nextPost(match); + const fiber = yield* Effect.forkChild(read, { startImmediately: true }); + return { fiber, worker: yield* Deferred.await(posted) }; + }); - assert.equal(referencedPorts(), referencedBefore); - assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); - assert.equal(startedWorkers.length, startedBefore + 2); - }), - ), -); +const startReaders = (sql: SqlClient.SqlClient) => + Effect.forEach([0, 1, 2, 3], () => countEntries(sql).pipe(SqliteClient.readOnly), { + concurrency: 4, + }); + +const abandonHeldRead = (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + const { fiber, worker } = yield* startRead(sql.unsafe(held).pipe(SqliteClient.readOnly), held); + yield* Fiber.interrupt(fiber); + return worker; + }); it.effect( - "settles a read-only transaction abandoned mid-statement, then reads on a new reader", + "returns a read queued on a reserved reader after the read ahead of it is abandoned", () => withReaderClient((sql) => Effect.gen(function* () { - const startedBefore = startedWorkers.length; - const transaction = yield* startSlowRead( - (slow) => sql.withTransaction(Effect.andThen(countEntries(sql), slow)), - sql, - ); - yield* Fiber.interrupt(transaction); - - assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(transaction))); - assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); - assert.equal(startedWorkers.length, startedBefore + 2); - }), + yield* holdStatements; + const answer = yield* Effect.gen(function* () { + const connection = yield* sql.reserve; + const first = yield* startRead(connection.executeUnprepared(held, [], undefined), held); + const second = yield* startRead( + connection.executeUnprepared("SELECT 42 AS answer", [], undefined), + "SELECT 42", + ); + yield* Fiber.interrupt(first.fiber); + yield* releaseStatements; + return yield* Fiber.join(second.fiber); + }).pipe(Effect.scoped, SqliteClient.readOnly); + + assert.deepEqual(answer, [{ answer: 42 }]); + }).pipe(Effect.scoped), ), ); -it.effect("keeps an abandoned read on its reader once four readers are still retiring", () => +it.effect("serves the next read on an idle reader while an abandoned statement still runs", () => withReaderClient((sql) => Effect.gen(function* () { - yield* Effect.acquireRelease( - Effect.sync(() => { - heldExits.on = true; - }), - () => - Effect.sync(() => { - heldExits.on = false; - for (const { worker, code } of heldExits.held.splice(0)) worker.emit("exit", code); - }), + yield* holdStatements; + yield* startReaders(sql); + const startedBefore = startedWorkers.length; + const abandoned = yield* abandonHeldRead(sql); + const next = yield* startRead( + countEntries(sql).pipe(SqliteClient.readOnly), + "SELECT COUNT(*)", ); + + assert.notStrictEqual(next.worker, abandoned); + assert.equal(yield* Fiber.join(next.fiber), 1); + assert.equal(startedWorkers.length, startedBefore); + }).pipe(Effect.scoped), + ), +); + +it.effect("starts a new reader once every reader runs only abandoned statements", () => + withReaderClient((sql) => + Effect.gen(function* () { + yield* holdStatements; + yield* holdReaderExits; + yield* startReaders(sql); + const busy = yield* Effect.forEach([0, 1, 2, 3], () => abandonHeldRead(sql)); const startedBefore = startedWorkers.length; - for (let index = 0; index < 5; index++) { - yield* Fiber.interrupt(yield* startSlowRead((slow) => slow, sql)); + const posted = yield* nextPost("SELECT COUNT(*)"); + const next = yield* Effect.forkChild(countEntries(sql).pipe(SqliteClient.readOnly), { + startImmediately: true, + }); + yield* TestClock.adjust("1 second"); + + assert.notInclude(busy, yield* Deferred.await(posted)); + assert.equal(yield* Fiber.join(next), 1); + assert.equal(startedWorkers.length, startedBefore + 1); + }).pipe(Effect.scoped), + ), +); + +it.effect("waits for a reader once four retired readers are still running", () => + withReaderClient((sql) => + Effect.gen(function* () { + yield* holdStatements; + yield* holdReaderExits; + yield* startReaders(sql); + yield* Effect.forEach([0, 1, 2, 3], () => abandonHeldRead(sql)); + const startedBefore = startedWorkers.length; + for (let index = 0; index < 4; index++) { + const posted = yield* nextPost(held); + const read = yield* Effect.forkChild(sql.unsafe(held).pipe(SqliteClient.readOnly), { + startImmediately: true, + }); + yield* TestClock.adjust("1 second"); + yield* Deferred.await(posted); + yield* Fiber.interrupt(read); } + assert.equal(startedWorkers.length, startedBefore + 4); - assert.equal(yield* countEntries(sql).pipe(SqliteClient.readOnly), 1); - assert.equal(startedWorkers.length, startedBefore + 5); + const next = yield* Effect.forkChild(countEntries(sql).pipe(SqliteClient.readOnly), { + startImmediately: true, + }); + yield* TestClock.adjust("1 second"); + yield* releaseStatements; + + assert.equal(yield* Fiber.join(next), 1); + assert.equal(startedWorkers.length, startedBefore + 4); + }).pipe(Effect.scoped), + ), +); + +it.effect("runs the next statement of a read-only transaction after one timed out", () => + withReaderClient((sql) => + Effect.gen(function* () { + yield* holdStatements; + const transaction = yield* startRead( + sql + .withTransaction( + sql + .unsafe(held) + .pipe(Effect.timeout("1 second"), Effect.ignore, Effect.andThen(countEntries(sql))), + ) + .pipe(SqliteClient.readOnly), + held, + ); + yield* TestClock.adjust("1 second"); + yield* releaseStatements; + + assert.equal(yield* Fiber.join(transaction.fiber), 1); }).pipe(Effect.scoped), ), ); +it.effect("closes the client without waiting for an abandoned statement", () => + Effect.gen(function* () { + yield* holdStatements; + yield* holdReaderExits; + yield* withReaderClient((sql) => abandonHeldRead(sql)); + }).pipe(Effect.scoped), +); + it.effect("keeps the reader when a read-only transaction is interrupted between statements", () => withReaderClient((sql) => Effect.gen(function* () { From 136acadb79340dbb5591359648919291a10c2f3a Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 12:08:31 -0800 Subject: [PATCH 5/9] fix(shared): an abandoned read keeps its reader busy instead of retiring it at once An interrupted read released its reader while the statement still ran, so the next read queued behind it. The previous fix retired the reader on every interrupt, which failed live reads on the same reserved connection or transaction and started a worker for most short cancellations. A reader now has three states: idle, live, and abandoned. A read released while its worker still runs requests becomes abandoned and stays occupied until the worker replies, so new reads take idle readers. When no reader is idle, a waiting read replaces a reader whose only work has been abandoned for 250 ms, while fewer than four replaced readers still run; otherwise it waits for the first reader to free up. Live readers are never replaced. Closing the client does not wait for a reader still running abandoned work. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/nodeSqliteClient.ts | 186 +++++++++++++++++------- 1 file changed, 131 insertions(+), 55 deletions(-) diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index ccb210e51b811..311d60b02489b 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -352,8 +352,9 @@ const READER_POOL_SIZE = 4; const READER_STARTUP_TIMEOUT = Duration.seconds(10); const READER_RETRY_DELAY = Duration.seconds(1); const READER_RETRY_MAX_DELAY = Duration.minutes(1); -// node:sqlite cannot interrupt a statement, so an abandoned read keeps its thread and connection -// until the statement returns. Past this many, an abandoned read keeps its reader busy instead. +// node:sqlite cannot interrupt a statement. A waiting read replaces a reader left running abandoned +// work only after this long, and only while fewer than this many replaced readers still run. +const ABANDONED_READER_GRACE_MS = 250; const MAX_RETIRING_READERS = READER_POOL_SIZE; // Bind transactions to one worker; fail after its exit instead of resuming outside the transaction on a replacement. @@ -362,7 +363,7 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { readonly role: "reader" | "writer"; readonly readOnly: boolean; readonly onReply?: () => void; - readonly pool?: { retiring: number }; + readonly onIdle?: () => void; }) { const label = options.role === "reader" ? "Database reader" : "Database writer"; const readOnly = options.readOnly; @@ -371,6 +372,7 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { readonly worker: NodeWorkerThreads.Worker; readonly connection: Connection; readonly started: Promise; + readonly pending: ReadonlyMap; } | undefined; let nextRequestId = 0; @@ -406,7 +408,8 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { stoppedMessage = message; if (options.role === "writer") writerStopped = message; announce({ type: "unavailable", message }); - if (current?.worker === worker) current = undefined; + const wasCurrent = current?.worker === worker; + if (wasCurrent) current = undefined; for (const [id, request] of pending) { request.resume( request.endsTransaction @@ -415,7 +418,7 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { ); } pending.clear(); - worker.unref(); + if (wasCurrent) options.onIdle?.(); }; worker.on("message", (reply: WorkerReply | WorkerStartup) => { if ("type" in reply) { @@ -432,7 +435,10 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { return; } pending.delete(reply.id); - if (pending.size === 0) worker.unref(); + if (pending.size === 0) { + worker.unref(); + if (current?.worker === worker) options.onIdle?.(); + } options.onReply?.(); if ("rows" in reply && request.rows.length > 0) { for (const row of reply.rows) request.rows.push(row); @@ -474,16 +480,6 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { const cached = input.cached && !hasLargeBinding(input.params); // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin. worker.postMessage({ id, safeIntegers, ...input, cached, received }); - const pool = options.pool; - if (pool === undefined) return; - return Effect.sync(() => { - if (!pending.has(id) || pool.retiring >= MAX_RETIRING_READERS) return; - pool.retiring++; - worker.once("exit", () => pool.retiring--); - // terminate() references the worker again, so stop must unref it afterward. - void worker.terminate(); - stop(`${label} abandoned a running statement`); - }); }); // A posted write runs to the end, as it did on the event loop; the caller and its lock // must not move on while the worker is still applying it. Reads stay cancellable. @@ -520,10 +516,21 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { return Stream.die(new UnsupportedNodeSqliteOperationError()); }, }); - current = { worker, connection, started }; + current = { worker, connection, started, pending }; return current; }; + const retire = (worker: NodeWorkerThreads.Worker) => { + if (current?.worker === worker) current = undefined; + return worker.terminate(); + }; + // Termination waits for a running statement, which may run long after its caller left. + const abandon = (worker: NodeWorkerThreads.Worker) => { + const exited = retire(worker); + worker.unref(); + return exited; + }; + yield* Effect.addFinalizer(() => Effect.promise(async () => { const open = current; @@ -536,16 +543,12 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { open.worker.postMessage({ type: "close" }); }); } - await open.worker.terminate(); + if (open.pending.size > 0) void abandon(open.worker); + else await retire(open.worker); }), ); - const retire = (worker: NodeWorkerThreads.Worker) => { - if (current?.worker === worker) current = undefined; - void worker.terminate(); - }; - - return Effect.suspend((): Effect.Effect => { + const acquire = Effect.suspend((): Effect.Effect => { if (current === undefined && writerStopped !== undefined) { return Effect.fail(failedWith({ message: writerStopped }, "execute")); } @@ -574,7 +577,7 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { ? Effect.succeed(entry.connection) : Effect.fail(failedWith({ message: `${label} stopped while starting` }, "open")); } - retire(entry.worker); + void retire(entry.worker); return Effect.fail( failedWith( outcome ?? { @@ -586,6 +589,11 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { }, ); }); + return { + acquire, + busy: () => current !== undefined && current.pending.size > 0, + retire: () => (current === undefined ? Promise.resolve() : abandon(current.worker)), + }; }); const startFailure = (error: SqlError) => { @@ -600,9 +608,11 @@ const startFailure = (error: SqlError) => { // one background retry starts it again. const makeReader = Effect.fnUntraced(function* ( filename: string, - pool: { unavailable: boolean; retiring: number }, + pool: { unavailable: boolean }, + onIdle: () => void, ) { - const acquire = yield* makeWorkerConnection({ filename, role: "reader", readOnly: true, pool }); + const reader = yield* makeWorkerConnection({ filename, role: "reader", readOnly: true, onIdle }); + const acquire = reader.acquire; const scope = yield* Effect.scope; const context = yield* Effect.context(); @@ -629,7 +639,7 @@ const makeReader = Effect.fnUntraced(function* ( }), ); - return Effect.suspend((): Effect.Effect => + const acquireOrFallBack = Effect.suspend((): Effect.Effect => pool.unavailable ? Effect.undefined : acquire.pipe( @@ -651,6 +661,7 @@ const makeReader = Effect.fnUntraced(function* ( }), ), ); + return { ...reader, acquire: acquireOrFallBack }; }); // A checkpoint copies WAL pages into the database and syncs it. On the writer's thread every @@ -913,12 +924,12 @@ const make = Effect.fn("makeWithDatabase")(function* ( const writerWorker = options.writerWorker === true && isFileDatabase; let checkpointAfterWrite: (() => void) | undefined; const writerConnection: Effect.Effect = writerWorker - ? yield* makeWorkerConnection({ + ? (yield* makeWorkerConnection({ filename: options.filename, role: "writer", readOnly: options.readonly ?? false, onReply: () => checkpointAfterWrite?.(), - }) + })).acquire : Effect.succeed(yield* makeConnection); // Opening now fails the layer for a file that is not a database, not its first query. const opened = yield* writerConnection; @@ -933,22 +944,88 @@ const make = Effect.fn("makeWithDatabase")(function* ( ); } } - const readerPool = { unavailable: false, retiring: 0 }; + const readerPool = { unavailable: false }; + // An abandoned reader still runs statements whose callers left, so it cannot take another read. + type ReaderState = + | { readonly name: "idle" } + | { readonly name: "live" } + | { readonly name: "abandoned"; readonly since: number }; + const idle: ReaderState = { name: "idle" }; + const live: ReaderState = { name: "live" }; + const readerWaiters = new Set<() => void>(); + const readersChanged = () => { + for (const wake of Array.from(readerWaiters)) wake(); + }; const readers = options.readerWorker && isFileDatabase ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () => - Effect.map( - Effect.all([makeReader(options.filename, readerPool), Semaphore.make(1)]), - ([acquire, lock]) => ({ - acquire, + Effect.gen(function* () { + const lock = yield* Semaphore.make(1); + const reader = yield* makeReader(options.filename, readerPool, () => { + if (slot.state.name !== "abandoned") return; + slot.state = idle; + readersChanged(); + }); + const slot: typeof reader & { lock: Semaphore.Semaphore; state: ReaderState } = { + ...reader, lock, - claimed: false, - }), - ), + state: idle, + }; + return slot; + }), ) : []; - // One permit per slot, so a queued read waits for any reader, not one it picked while all were busy. - const readerAdmission = yield* Semaphore.make(readers.length); + type Reader = (typeof readers)[number]; + let retiringReaders = 0; + + // Returns the claimed reader, or how long until an abandoned one may be replaced. + const claimReader = (now: number): Reader | number | undefined => { + // The lowest idle reader wins, so idle readers never start a worker. + const idleReader = readers.find((reader) => reader.state.name === "idle"); + if (idleReader !== undefined) { + idleReader.state = live; + return idleReader; + } + if (retiringReaders >= MAX_RETIRING_READERS) return undefined; + let wait: number | undefined; + for (const reader of readers) { + if (reader.state.name !== "abandoned") continue; + const remaining = reader.state.since + ABANDONED_READER_GRACE_MS - now; + if (remaining > 0) { + wait = Math.min(wait ?? remaining, remaining); + continue; + } + retiringReaders++; + void reader.retire().then(() => { + retiringReaders--; + readersChanged(); + }); + reader.state = live; + return reader; + } + return wait; + }; + // A wake hands over nothing, so a waiter interrupted after its wake loses no reader. + const readersChange = Effect.callback((resume) => { + const wake = () => { + readerWaiters.delete(wake); + resume(Effect.void); + }; + readerWaiters.add(wake); + return Effect.sync(() => readerWaiters.delete(wake)); + }); + const waitForReader = (restore: typeof Effect.interruptible) => + Effect.withFiber((fiber) => { + const clock = fiber.getRef(Clock.Clock); + const attempt: Effect.Effect = Effect.suspend(() => { + const claimed = claimReader(clock.currentTimeMillisUnsafe()); + if (typeof claimed === "object") return Effect.succeed(claimed); + const change = + claimed === undefined ? readersChange : Effect.timeoutOption(readersChange, claimed); + return Effect.andThen(restore(change), attempt); + }); + return attempt; + }); interface Target { readonly name: Acquired["connection"]; @@ -971,23 +1048,22 @@ const make = Effect.fn("makeWithDatabase")(function* ( if (readers.length === 0 || readerPool.unavailable || !Context.get(fiber.context, ReadOnly)) { return writer; } - const claim = Effect.andThen( - restore(readerAdmission.take(1)), - Effect.suspend(() => { - // Holding a permit leaves a slot idle; the lowest wins, so idle slots never start a worker. - const reader = readers.find((slot) => !slot.claimed)!; - reader.claimed = true; - const release = Effect.andThen( - Effect.sync(() => { - reader.claimed = false; - }), - readerAdmission.release(1), - ); - return Effect.as(claimed(release), reader); - }), + const claim = Effect.tap(waitForReader(restore), (reader) => + claimed( + Effect.withFiber((releasing) => { + reader.state = reader.busy() + ? { + name: "abandoned", + since: releasing.getRef(Clock.Clock).currentTimeMillisUnsafe(), + } + : idle; + readersChanged(); + return Effect.void; + }), + ), ); return Effect.flatMap( - // A scheduler yield after taking the permit must not precede its release finalizer. + // A scheduler yield after claiming a reader must not precede its release finalizer. Effect.provideService(claim, Scheduler.PreventSchedulerYield, true), (reader) => Effect.flatMap( From 77fb568034fe5637234891a8089cd75b488016c3 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 12:44:20 -0800 Subject: [PATCH 6/9] test(shared): a freed reader wakes one waiting read, and interrupted waiters strand none Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/nodeSqliteClient.test.ts | 136 +++++++++++++++++++ 1 file changed, 136 insertions(+) diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index ccc20859ed548..56580f9b88937 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -754,6 +755,141 @@ it.effect("waits for a reader once four retired readers are still running", () = ), ); +// A read-only transaction that keeps its reader until `release` completes. +const holdReader = (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + const fiber = yield* sql + .withTransaction( + countEntries(sql).pipe( + Effect.andThen(Deferred.succeed(entered, undefined)), + Effect.andThen(Deferred.await(release)), + ), + ) + .pipe(SqliteClient.readOnly, (read) => Effect.forkChild(read, { startImmediately: true })); + return { fiber, entered, release }; + }); + +const holdEveryReader = (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + const holders = yield* Effect.forEach([0, 1, 2, 3], () => holdReader(sql)); + yield* Effect.forEach(holders, (holder) => Deferred.await(holder.entered)); + return holders; + }); + +const finishHeld = (held: Effect.Success>) => + Deferred.succeed(held.release, undefined).pipe(Effect.andThen(Fiber.join(held.fiber))); + +// A read looks at its clock each time it checks for a free reader, so this counts the checks. +const withCheckCount = (effect: Effect.Effect) => + Effect.map(Clock.clockWith(Effect.succeed), (clock) => { + const counted = { checks: 0 }; + const counting: Clock.Clock = { + currentTimeMillisUnsafe: () => { + counted.checks++; + return clock.currentTimeMillisUnsafe(); + }, + currentTimeNanosUnsafe: () => clock.currentTimeNanosUnsafe(), + monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(), + currentTimeMillis: clock.currentTimeMillis, + currentTimeNanos: clock.currentTimeNanos, + monotonicTimeNanos: clock.monotonicTimeNanos, + sleep: (duration) => clock.sleep(duration), + }; + return { counted, read: Effect.provideService(effect, Clock.Clock, counting) }; + }); + +it.effect("wakes one waiting read per reader that frees up, in arrival order", () => + withReaderClient((sql) => + Effect.gen(function* () { + const holders = yield* holdEveryReader(sql); + const waiting = yield* Effect.forEach([0, 1, 2], () => holdReader(sql)); + const last = yield* withCheckCount(countEntries(sql).pipe(SqliteClient.readOnly)); + const lastRead = yield* Effect.forkChild(last.read, { startImmediately: true }); + const checksWhileQueued = last.counted.checks; + yield* Effect.forEach(holders.slice(0, 2), finishHeld); + + yield* Deferred.await(waiting[0]!.entered); + yield* Deferred.await(waiting[1]!.entered); + assert.isFalse(yield* Deferred.isDone(waiting[2]!.entered)); + assert.equal(last.counted.checks, checksWhileQueued); + yield* finishHeld(waiting[0]!); + yield* Deferred.await(waiting[2]!.entered); + yield* Effect.forEach([...holders.slice(2), ...waiting.slice(1)], finishHeld); + assert.equal(yield* Fiber.join(lastRead), 1); + }), + ), +); + +it.effect("serves the reads behind a waiting read that is interrupted", () => + withReaderClient((sql) => + Effect.gen(function* () { + const holders = yield* holdEveryReader(sql); + const waiting = yield* Effect.forEach([0, 1, 2, 3], () => holdReader(sql)); + // The first waiting read is the one a freed reader would go to. + yield* Fiber.interrupt(waiting[0]!.fiber); + yield* Fiber.interrupt(waiting[2]!.fiber); + + yield* finishHeld(holders[0]!); + yield* Deferred.await(waiting[1]!.entered); + yield* finishHeld(holders[1]!); + yield* Deferred.await(waiting[3]!.entered); + yield* Effect.forEach([holders[2]!, holders[3]!, waiting[1]!, waiting[3]!], finishHeld); + }), + ), +); + +it.effect("replaces an abandoned reader for the next waiting read after the first leaves", () => + withReaderClient((sql) => + Effect.gen(function* () { + yield* holdStatements; + yield* holdReaderExits; + const holders = yield* Effect.forEach([0, 1, 2], () => holdReader(sql)); + yield* Effect.forEach(holders, (holder) => Deferred.await(holder.entered)); + yield* abandonHeldRead(sql); + const [first, second] = yield* Effect.forEach([0, 1], () => + Effect.forkChild(countEntries(sql).pipe(SqliteClient.readOnly), { + startImmediately: true, + }), + ); + yield* Fiber.interrupt(first!); + yield* TestClock.adjust("1 second"); + + assert.equal(yield* Fiber.join(second!), 1); + yield* Effect.forEach(holders, finishHeld); + }).pipe(Effect.scoped), + ), +); + +it.effect("replaces two readers abandoned at once for the two reads waiting on them", () => + withReaderClient((sql) => + Effect.gen(function* () { + yield* holdStatements; + yield* holdReaderExits; + const holders = yield* Effect.forEach([0, 1], () => holdReader(sql)); + yield* Effect.forEach(holders, (holder) => Deferred.await(holder.entered)); + // Distinct text, so each read waits for its own post rather than the one before it. + const stuck = yield* Effect.forEach(["1 = 1", "2 = 2"], (where) => { + const statement = `${held} WHERE ${where}`; + return startRead(sql.unsafe(statement).pipe(SqliteClient.readOnly), statement); + }); + const waiting = yield* Effect.forEach([0, 1], () => + Effect.forkChild(countEntries(sql).pipe(SqliteClient.readOnly), { + startImmediately: true, + }), + ); + const startedBefore = startedWorkers.length; + yield* Effect.forEach(stuck, ({ fiber }) => Fiber.interrupt(fiber)); + yield* TestClock.adjust("1 second"); + + assert.deepEqual(yield* Effect.forEach(waiting, Fiber.join), [1, 1]); + assert.equal(startedWorkers.length, startedBefore + 2); + yield* Effect.forEach(holders, finishHeld); + }).pipe(Effect.scoped), + ), +); + it.effect("runs the next statement of a read-only transaction after one timed out", () => withReaderClient((sql) => Effect.gen(function* () { From 672e44fe1adcfea4ec6cf295671893677a8a4131 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 12:51:01 -0800 Subject: [PATCH 7/9] fix(shared): a freed reader wakes one waiting read instead of all of them Waking every waiting read on each pool change made 10,000 reads at 256 concurrent take 2.0 s against main's 0.27 s. A change now wakes the longest-waiting parked read. A read that stops waiting without a reader, or claims one while another reader is claimable or awaits its grace, wakes the next, so no wake is lost. Reads arriving behind waiting reads queue behind them. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/nodeSqliteClient.ts | 104 ++++++++++++++++-------- 1 file changed, 71 insertions(+), 33 deletions(-) diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index 311d60b02489b..f9029eb7ebd06 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -952,9 +952,21 @@ const make = Effect.fn("makeWithDatabase")(function* ( | { readonly name: "abandoned"; readonly since: number }; const idle: ReaderState = { name: "idle" }; const live: ReaderState = { name: "live" }; - const readerWaiters = new Set<() => void>(); + // Waiting reads in arrival order. `resume` is set while one is parked; whoever wakes it clears it. + interface ReaderWaiter { + resume: (() => void) | undefined; + } + const readerWaiters = new Set(); + const wake = (waiter: ReaderWaiter) => { + const resume = waiter.resume; + waiter.resume = undefined; + resume?.(); + }; + // Wakes only the longest-waiting parked read, so a change costs one check, not one per waiter. const readersChanged = () => { - for (const wake of Array.from(readerWaiters)) wake(); + for (const waiter of readerWaiters) { + if (waiter.resume !== undefined) return wake(waiter); + } }; const readers = options.readerWorker && isFileDatabase @@ -978,53 +990,79 @@ const make = Effect.fn("makeWithDatabase")(function* ( type Reader = (typeof readers)[number]; let retiringReaders = 0; - // Returns the claimed reader, or how long until an abandoned one may be replaced. - const claimReader = (now: number): Reader | number | undefined => { + // Returns the reader a read may claim, or how long until an abandoned one may be replaced. + const findReader = (now: number): Reader | number | undefined => { // The lowest idle reader wins, so idle readers never start a worker. const idleReader = readers.find((reader) => reader.state.name === "idle"); - if (idleReader !== undefined) { - idleReader.state = live; - return idleReader; - } + if (idleReader !== undefined) return idleReader; if (retiringReaders >= MAX_RETIRING_READERS) return undefined; let wait: number | undefined; for (const reader of readers) { if (reader.state.name !== "abandoned") continue; const remaining = reader.state.since + ABANDONED_READER_GRACE_MS - now; - if (remaining > 0) { - wait = Math.min(wait ?? remaining, remaining); - continue; - } + if (remaining <= 0) return reader; + wait = Math.min(wait ?? remaining, remaining); + } + return wait; + }; + const claimReader = (reader: Reader) => { + if (reader.state.name === "abandoned") { retiringReaders++; void reader.retire().then(() => { retiringReaders--; readersChanged(); }); - reader.state = live; - return reader; } - return wait; + reader.state = live; + return reader; }; - // A wake hands over nothing, so a waiter interrupted after its wake loses no reader. - const readersChange = Effect.callback((resume) => { - const wake = () => { - readerWaiters.delete(wake); - resume(Effect.void); - }; - readerWaiters.add(wake); - return Effect.sync(() => readerWaiters.delete(wake)); - }); + // A grace deadline wakes only its own waiter; a change wakes the first parked one. + const park = (waiter: ReaderWaiter, delay: number | undefined) => { + const parked = Effect.callback((resume) => { + waiter.resume = () => resume(Effect.void); + return Effect.sync(() => { + waiter.resume = undefined; + }); + }); + if (delay === undefined) return parked; + const deadline = Effect.andThen( + Effect.sleep(delay), + Effect.sync(() => wake(waiter)), + ); + return Effect.flatMap(Effect.forkChild(deadline, { startImmediately: true }), (timer) => + Effect.ensuring(parked, Fiber.interrupt(timer)), + ); + }; + // Every change wakes one parked read. A read that stops waiting without a reader, or claims one + // while another reader is claimable or awaits its grace, wakes the next, so no wake is lost. + // A read arriving behind waiting reads parks behind them; it never takes a reader ahead of them. const waitForReader = (restore: typeof Effect.interruptible) => - Effect.withFiber((fiber) => { + Effect.withFiber((fiber): Effect.Effect => { const clock = fiber.getRef(Clock.Clock); - const attempt: Effect.Effect = Effect.suspend(() => { - const claimed = claimReader(clock.currentTimeMillisUnsafe()); - if (typeof claimed === "object") return Effect.succeed(claimed); - const change = - claimed === undefined ? readersChange : Effect.timeoutOption(readersChange, claimed); - return Effect.andThen(restore(change), attempt); - }); - return attempt; + const found = + readerWaiters.size === 0 ? findReader(clock.currentTimeMillisUnsafe()) : undefined; + if (typeof found === "object") return Effect.succeed(claimReader(found)); + const waiter: ReaderWaiter = { resume: undefined }; + readerWaiters.add(waiter); + const attempt = (found: Reader | number | undefined): Effect.Effect => { + if (typeof found !== "object") { + return Effect.andThen( + restore(park(waiter, found)), + Effect.suspend(() => attempt(findReader(clock.currentTimeMillisUnsafe()))), + ); + } + readerWaiters.delete(waiter); + claimReader(found); + if (readerWaiters.size > 0 && findReader(clock.currentTimeMillisUnsafe()) !== undefined) { + readersChanged(); + } + return Effect.succeed(found); + }; + return Effect.onInterrupt(attempt(found), () => + Effect.sync(() => { + if (readerWaiters.delete(waiter)) readersChanged(); + }), + ); }); interface Target { From 10ba5abf1c30f58dd520e8bd8960ba987f41ca71 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 13:24:06 -0800 Subject: [PATCH 8/9] test(shared): a closed client settles waiting reads, and the grace ignores wall-clock jumps Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/nodeSqliteClient.test.ts | 62 ++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 56580f9b88937..822d302615898 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -890,6 +890,29 @@ it.effect("replaces two readers abandoned at once for the two reads waiting on t ), ); +it.effect("replaces an abandoned reader one grace after the wall clock moves back", () => + withReaderClient((sql) => + Effect.gen(function* () { + yield* holdStatements; + yield* holdReaderExits; + yield* TestClock.adjust("1 minute"); + yield* startReaders(sql); + yield* Effect.forEach([0, 1, 2, 3], () => abandonHeldRead(sql)); + yield* TestClock.setTime(0); + const startedBefore = startedWorkers.length; + const next = yield* Effect.forkChild(countEntries(sql).pipe(SqliteClient.readOnly), { + startImmediately: true, + }); + + yield* TestClock.adjust("249 millis"); + assert.equal(startedWorkers.length, startedBefore); + yield* TestClock.adjust("1 millis"); + assert.equal(startedWorkers.length, startedBefore + 1); + assert.equal(yield* Fiber.join(next), 1); + }).pipe(Effect.scoped), + ), +); + it.effect("runs the next statement of a read-only transaction after one timed out", () => withReaderClient((sql) => Effect.gen(function* () { @@ -920,6 +943,45 @@ it.effect("closes the client without waiting for an abandoned statement", () => }).pipe(Effect.scoped), ); +it.effect("fails a read waiting for a reader when the client closes, and starts none", () => + Effect.gen(function* () { + const startedBefore = startedWorkers.length; + const waiting = yield* Effect.gen(function* () { + yield* holdStatements; + return yield* withReaderClient((sql) => + Effect.gen(function* () { + yield* startReaders(sql); + yield* Effect.forEach([0, 1, 2, 3], () => abandonHeldRead(sql)); + return yield* Effect.forkChild(countEntries(sql).pipe(SqliteClient.readOnly), { + startImmediately: true, + }); + }), + ); + }).pipe(Effect.scoped); + const startedAtClose = startedWorkers.length; + // Settled by the close itself, before its grace runs out. + const error = yield* Effect.flip(Fiber.join(waiting)); + assert.include(String(error.reason.cause), "Database reader closed"); + yield* TestClock.adjust("1 second"); + + assert.equal(startedWorkers.length, startedAtClose); + yield* Effect.promise(() => + Promise.all(startedWorkers.slice(startedBefore).map((worker) => workerExits.get(worker))), + ); + }), +); + +it.effect("fails a read that arrives after the client closes, and starts no reader", () => + Effect.gen(function* () { + const sql = yield* withReaderClient((sql) => Effect.as(startReaders(sql), sql)); + const startedAtClose = startedWorkers.length; + const error = yield* Effect.flip(countEntries(sql).pipe(SqliteClient.readOnly)); + + assert.equal(startedWorkers.length, startedAtClose); + assert.include(String(error.reason.cause), "Database reader closed"); + }), +); + it.effect("keeps the reader when a read-only transaction is interrupted between statements", () => withReaderClient((sql) => Effect.gen(function* () { From e9675b0bd5d0a8d234b0f99411a2dc41f524e013 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 13:28:25 -0800 Subject: [PATCH 9/9] fix(shared): closing the client settles waiting reads, and the grace uses monotonic time Closing marks the reader pool closed before the readers' own finalizers run: parked reads are woken and fail, new reads fail, and nothing claims or replaces a reader or starts a worker. The abandoned-reader grace is measured with the clock's monotonic time, so a wall-clock correction cannot stretch or skip it. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/nodeSqliteClient.test.ts | 8 +++--- packages/shared/src/nodeSqliteClient.ts | 30 +++++++++++++++----- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 822d302615898..b93509ab26b7a 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -786,12 +786,12 @@ const withCheckCount = (effect: Effect.Effect) => Effect.map(Clock.clockWith(Effect.succeed), (clock) => { const counted = { checks: 0 }; const counting: Clock.Clock = { - currentTimeMillisUnsafe: () => { + currentTimeMillisUnsafe: () => clock.currentTimeMillisUnsafe(), + currentTimeNanosUnsafe: () => clock.currentTimeNanosUnsafe(), + monotonicTimeNanosUnsafe: () => { counted.checks++; - return clock.currentTimeMillisUnsafe(); + return clock.monotonicTimeNanosUnsafe(); }, - currentTimeNanosUnsafe: () => clock.currentTimeNanosUnsafe(), - monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(), currentTimeMillis: clock.currentTimeMillis, currentTimeNanos: clock.currentTimeNanos, monotonicTimeNanos: clock.monotonicTimeNanos, diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index f9029eb7ebd06..ded31f2a94c10 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -989,6 +989,18 @@ const make = Effect.fn("makeWithDatabase")(function* ( : []; type Reader = (typeof readers)[number]; let retiringReaders = 0; + // Runs before the readers' own finalizers, so no read claims a slot whose worker already closed. + let closed = false; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + closed = true; + for (const waiter of readerWaiters) wake(waiter); + }), + ); + const readersClosed = Effect.fail(failedWith({ message: "Database reader closed" }, "execute")); + // The grace uses monotonic time, so a wall-clock correction neither stretches nor skips it. + const monotonicMillis = (clock: Clock.Clock) => + Number(clock.monotonicTimeNanosUnsafe() / 1000n) / 1000; // Returns the reader a read may claim, or how long until an abandoned one may be replaced. const findReader = (now: number): Reader | number | undefined => { @@ -1037,23 +1049,27 @@ const make = Effect.fn("makeWithDatabase")(function* ( // while another reader is claimable or awaits its grace, wakes the next, so no wake is lost. // A read arriving behind waiting reads parks behind them; it never takes a reader ahead of them. const waitForReader = (restore: typeof Effect.interruptible) => - Effect.withFiber((fiber): Effect.Effect => { + Effect.withFiber((fiber): Effect.Effect => { + if (closed) return readersClosed; const clock = fiber.getRef(Clock.Clock); - const found = - readerWaiters.size === 0 ? findReader(clock.currentTimeMillisUnsafe()) : undefined; + const found = readerWaiters.size === 0 ? findReader(monotonicMillis(clock)) : undefined; if (typeof found === "object") return Effect.succeed(claimReader(found)); const waiter: ReaderWaiter = { resume: undefined }; readerWaiters.add(waiter); - const attempt = (found: Reader | number | undefined): Effect.Effect => { + const attempt = (found: Reader | number | undefined): Effect.Effect => { + if (closed) { + readerWaiters.delete(waiter); + return readersClosed; + } if (typeof found !== "object") { return Effect.andThen( restore(park(waiter, found)), - Effect.suspend(() => attempt(findReader(clock.currentTimeMillisUnsafe()))), + Effect.suspend(() => attempt(findReader(monotonicMillis(clock)))), ); } readerWaiters.delete(waiter); claimReader(found); - if (readerWaiters.size > 0 && findReader(clock.currentTimeMillisUnsafe()) !== undefined) { + if (readerWaiters.size > 0 && findReader(monotonicMillis(clock)) !== undefined) { readersChanged(); } return Effect.succeed(found); @@ -1092,7 +1108,7 @@ const make = Effect.fn("makeWithDatabase")(function* ( reader.state = reader.busy() ? { name: "abandoned", - since: releasing.getRef(Clock.Clock).currentTimeMillisUnsafe(), + since: monotonicMillis(releasing.getRef(Clock.Clock)), } : idle; readersChanged();