@devries-cameron20 / t3code-1 / commits / 616819ac17
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(shared): checkpoint WAL without blocking the event loop (#21799)

Co-authored-by: Yannic Charlon <52761674+JustYannicc@users.noreply.github.com>

Julius Marminge committed Oct 19, 2026 at 19:53 UTC 616819ac170dc20750bb8bff5c100f0b9a3d4967
2 files changed +1186 -137
packages/shared/src/nodeSqliteClient.test.ts
+718 -6
@@ -9,6 +9,8 @@ import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 import * as Logger from "effect/Logger";
11 import * as Path from "effect/Path";
12 +import * as Scheduler from "effect/Scheduler";
13 +import type * as Scope from "effect/Scope";
14 import * as SqlClient from "effect/sql/SqlClient";
15 import * as Statement from "effect/sql/Statement";
16 import * as TestClock from "effect/testing/TestClock";
@@ -758,7 +760,8 @@ const withCheckpointClient = <A, E>(
760 use: (
761 sql: SqlClient.SqlClient,
762 filename: string,
761 - ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem>,
763 + ) => Effect.Effect<A, E, SqlClient.SqlClient | FileSystem.FileSystem | Scope.Scope>,
764 + options: { readonly readerWorker?: boolean } = {},
765 ) =>
766 Effect.gen(function* () {
767 const fs = yield* FileSystem.FileSystem;
@@ -769,15 +772,31 @@ const withCheckpointClient = <A, E>(
772 const sql = yield* SqlClient.SqlClient;
773 yield* sql`PRAGMA journal_mode = WAL`;
774 return yield* use(sql, filename);
772 - }).pipe(Effect.provide(SqliteClient.layer({ filename, checkpointWorker: true })));
775 + }).pipe(Effect.provide(SqliteClient.layer({ filename, checkpointWorker: true, ...options })));
776 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
777
778 +const supportsNoopCheckpoint = (() => {
779 + const db = new NodeSqlite.DatabaseSync(":memory:");
780 + const version = String(db.prepare("SELECT sqlite_version() AS version").get()?.version);
781 + db.close();
782 + const [major = 0, minor = 0] = version.split(".").map(Number);
783 + return major > 3 || (major === 3 && minor >= 51);
784 +})();
785 +
786 const checkpointWorkerReply = (worker: NodeWorkerThreads.Worker) =>
787 Effect.promise(
788 () =>
789 new Promise<void>((resolve) => {
790 + let replies = 0;
791 const onReply = (reply: unknown) => {
792 if (reply !== "barrier") return;
793 + if (++replies < 2) {
794 + // One checkpoint response may queue a coalesced follow-up behind the first barrier.
795 + // A second barrier observes that follow-up and makes the helper deterministic.
796 + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
797 + worker.postMessage("barrier");
798 + return;
799 + }
800 worker.off("message", onReply);
801 resolve();
802 };
@@ -787,18 +806,218 @@ const checkpointWorkerReply = (worker: NodeWorkerThreads.Worker) =>
806 }),
807 );
808
809 +const waitForCheckpointMessage = (worker: NodeWorkerThreads.Worker, id: unknown) =>
810 + new Promise<Record<string, unknown>>((resolve) => {
811 + const onMessage = (message: unknown) => {
812 + if (
813 + typeof message === "object" &&
814 + message !== null &&
815 + "type" in message &&
816 + message.type === "checkpoint" &&
817 + "id" in message &&
818 + message.id === id
819 + ) {
820 + worker.off("message", onMessage);
821 + resolve(message as Record<string, unknown>);
822 + }
823 + };
824 + worker.on("message", onMessage);
825 + });
826 +
827 +const waitForTruncateCompletion = (worker: NodeWorkerThreads.Worker) =>
828 + new Promise<Record<string, unknown>>((resolve) => {
829 + const onMessage = (message: unknown) => {
830 + if (
831 + typeof message === "object" &&
832 + message !== null &&
833 + "type" in message &&
834 + message.type === "checkpoint" &&
835 + "truncateId" in message &&
836 + typeof message.truncateId === "number"
837 + ) {
838 + worker.off("message", onMessage);
839 + resolve(message as Record<string, unknown>);
840 + }
841 + };
842 + worker.on("message", onMessage);
843 + });
844 +
845 +const holdWorkerMessage = (worker: NodeWorkerThreads.Worker, type: string) => {
846 + const emit = worker.emit.bind(worker) as (
847 + eventName: string | symbol,
848 + ...args: unknown[]
849 + ) => boolean;
850 + let held: unknown;
851 + let resolve: (message: unknown) => void = () => {};
852 + const ready = new Promise<unknown>((done) => {
853 + resolve = done;
854 + });
855 + const spy = vi.spyOn(worker, "emit").mockImplementation((eventName, ...args) => {
856 + const message = args[0];
857 + if (
858 + eventName === "message" &&
859 + held === undefined &&
860 + typeof message === "object" &&
861 + message !== null &&
862 + "type" in message &&
863 + message.type === type
864 + ) {
865 + held = message;
866 + resolve(message);
867 + return true;
868 + }
869 + return emit(eventName, ...args);
870 + });
871 + return {
872 + ready,
873 + deliver() {
874 + spy.mockRestore();
875 + if (held !== undefined) emit("message", held);
876 + },
877 + release() {
878 + spy.mockRestore();
879 + if (held !== undefined) emit("message", held);
880 + },
881 + };
882 +};
883 +
884 +const schedulerHoldingDispatch = (afterResume = false) => {
885 + let resuming = false;
886 + let yielded = false;
887 + let resolveContinuation = () => {};
888 + const continuation = new Promise<void>((resolve) => {
889 + resolveContinuation = resolve;
890 + });
891 + let holdNext = false;
892 + let heldTask: (() => void) | undefined;
893 + let resolvePaused: () => void = () => {};
894 + const paused = new Promise<void>((resolve) => {
895 + resolvePaused = resolve;
896 + });
897 + const mixed = new Scheduler.MixedScheduler("async", (task) => {
898 + if (holdNext) {
899 + holdNext = false;
900 + heldTask = task;
901 + if (resuming) resolveContinuation();
902 + else resolvePaused();
903 + return () => {
904 + if (heldTask === task) heldTask = undefined;
905 + };
906 + }
907 + const immediate = setImmediate(task);
908 + return () => clearImmediate(immediate);
909 + });
910 + const scheduler: Scheduler.Scheduler = {
911 + executionMode: mixed.executionMode,
912 + makeDispatcher: () => mixed.makeDispatcher(),
913 + shouldYield: () => {
914 + if (resuming && afterResume && !yielded) {
915 + yielded = true;
916 + holdNext = true;
917 + return true;
918 + }
919 + return false;
920 + },
921 + };
922 + return {
923 + scheduler,
924 + paused,
925 + continuation,
926 + arm() {
927 + holdNext = true;
928 + },
929 + resume() {
930 + const task = heldTask;
931 + heldTask = undefined;
932 + if (task !== undefined)
933 + setImmediate(() => {
934 + resuming = true;
935 + task();
936 + resuming = false;
937 + });
938 + },
939 + };
940 +};
941 +
942 +const pauseCheckpointRequests = (worker: NodeWorkerThreads.Worker) => {
943 + const queued: Array<Parameters<typeof worker.postMessage>> = [];
944 + const send = worker.postMessage.bind(worker);
945 + const spy = vi.spyOn(worker, "postMessage").mockImplementation((...args) => {
946 + queued.push(args);
947 + });
948 + let restored = false;
949 + return {
950 + queued,
951 + sendNext() {
952 + const args = queued.shift();
953 + if (args !== undefined) send(...args);
954 + return args?.[0];
955 + },
956 + release() {
957 + if (restored) return;
958 + restored = true;
959 + spy.mockRestore();
960 + for (const args of queued.splice(0)) send(...args);
961 + },
962 + };
963 +};
964 +
965 +const blockCheckpointBehindReader = (
966 + sql: SqlClient.SqlClient,
967 + filename: string,
968 + worker: NodeWorkerThreads.Worker,
969 +) =>
970 + Effect.gen(function* () {
971 + yield* sql.unsafe("PRAGMA journal_size_limit = 1").unprepared;
972 + yield* sql.unsafe("CREATE TABLE entries(value INTEGER PRIMARY KEY)").unprepared;
973 + yield* sql.unsafe("CREATE TABLE pages(payload BLOB)").unprepared;
974 + const reader = yield* Effect.acquireRelease(
975 + Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
976 + (database) => Effect.sync(() => database.close()),
977 + );
978 + reader.exec("BEGIN");
979 + reader.prepare("SELECT COUNT(*) AS count FROM entries").get();
980 +
981 + const checkpointRequests = pauseCheckpointRequests(worker);
982 + yield* Effect.addFinalizer(() => Effect.sync(checkpointRequests.release));
983 + yield* sql.unsafe(`
984 + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1200)
985 + INSERT INTO pages(payload) SELECT randomblob(4000) FROM n
986 + `).unprepared;
987 +
988 + const request = checkpointRequests.queued[0]?.[0];
989 + assert(typeof request === "object" && request !== null && "id" in request);
990 + const blocked = waitForCheckpointMessage(worker, (request as { readonly id: unknown }).id);
991 + checkpointRequests.sendNext();
992 + const state = yield* Effect.promise(() => blocked);
993 + assert.isTrue(state.blocked as boolean);
994 + assert.isAbove(state.log as number, 0);
995 + return { reader, checkpointRequests };
996 + });
997 +
998 +const readCheckpointState = (db: NodeSqlite.DatabaseSync) => {
999 + const state = db.prepare("PRAGMA wal_checkpoint(NOOP)").get();
1000 + if (typeof state?.log !== "number" || typeof state.checkpointed !== "number") {
1001 + throw new Error("SQLite returned invalid WAL checkpoint frame counts");
1002 + }
1003 + return { log: state.log, checkpointed: state.checkpointed };
1004 +};
1005 +
1006 it.effect("checkpoints the WAL on the worker instead of the writer", () =>
1007 withCheckpointClient((sql, filename) =>
1008 Effect.gen(function* () {
1009 const fs = yield* FileSystem.FileSystem;
1010 const walSize = Effect.map(fs.stat(`${filename}-wal`), (info) => Number(info.size));
1011 const worker = startedWorkers.at(-1)!;
1012 + const checkpointRequests = pauseCheckpointRequests(worker);
1013 + yield* Effect.addFinalizer(() => Effect.sync(checkpointRequests.release));
1014 const limit = 1024 * 1024;
1015 yield* sql.unsafe(`PRAGMA journal_size_limit = ${limit}`);
1016 const autocheckpoint = yield* sql<{
1017 readonly wal_autocheckpoint: number;
1018 }>`PRAGMA wal_autocheckpoint`;
801 - assert.equal(autocheckpoint[0]?.wal_autocheckpoint, 10_000);
1019 + assert.equal(autocheckpoint[0]?.wal_autocheckpoint, 0);
1020 + assert.deepEqual(yield* sql`PRAGMA synchronous`, [{ synchronous: 2 }]);
1021
1022 // About 1200 frames, past the 1000 that start a checkpoint.
1023 yield* sql`CREATE TABLE pages(payload BLOB)`;
@@ -806,21 +1025,78 @@ it.effect("checkpoints the WAL on the worker instead of the writer", () =>
1025 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1200)
1026 INSERT INTO pages(payload) SELECT randomblob(4000) FROM n
1027 `;
1028 + const pending = yield* sql<{
1029 + readonly log: number;
1030 + readonly checkpointed: number;
1031 + }>`PRAGMA wal_checkpoint(NOOP)`;
1032 + assert.isAbove(pending[0]!.log, 1000);
1033 + assert.isBelow(pending[0]!.checkpointed, pending[0]!.log);
1034 + checkpointRequests.release();
1035 yield* checkpointWorkerReply(worker);
1036 const wal = yield* sql<{
1037 readonly log: number;
1038 readonly checkpointed: number;
1039 }>`PRAGMA wal_checkpoint(NOOP)`;
814 - assert.isAbove(wal[0]!.log, 1000);
815 - assert.equal(wal[0]!.checkpointed, wal[0]!.log);
1040 + assert.isAtMost(wal[0]!.log - wal[0]!.checkpointed, 1000);
1041
817 - assert.isAbove(yield* walSize, limit);
1042 + assert.isAtMost(yield* walSize, limit);
1043 yield* sql`INSERT INTO pages(payload) VALUES (x'00')`;
1044 assert.isAtMost(yield* walSize, limit);
1045 }),
1046 ),
1047 );
1048
1049 +it.effect.skipIf(!supportsNoopCheckpoint)(
1050 + "answers checks received while the worker waits for truncation acknowledgement",
1051 + () =>
1052 + withCheckpointClient((sql) =>
1053 + Effect.gen(function* () {
1054 + const worker = startedWorkers.at(-1)!;
1055 + const send = worker.postMessage.bind(worker);
1056 + const truncateRequest = holdWorkerMessage(worker, "truncate-request");
1057 + yield* Effect.addFinalizer(() => Effect.sync(truncateRequest.release));
1058 + const checkpointRequests = pauseCheckpointRequests(worker);
1059 + yield* Effect.addFinalizer(() => Effect.sync(checkpointRequests.release));
1060 + const replies: Array<unknown> = [];
1061 + const onMessage = (message: unknown) => replies.push(message);
1062 + worker.on("message", onMessage);
1063 + yield* Effect.addFinalizer(() => Effect.sync(() => worker.off("message", onMessage)));
1064 +
1065 + yield* sql.unsafe("PRAGMA journal_size_limit = 1").unprepared;
1066 + yield* sql.unsafe("CREATE TABLE pages(payload BLOB)").unprepared;
1067 + yield* sql.unsafe(`
1068 + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1200)
1069 + INSERT INTO pages(payload) SELECT randomblob(4000) FROM n
1070 + `).unprepared;
1071 + checkpointRequests.sendNext();
1072 + const pending = yield* Effect.promise(() => truncateRequest.ready);
1073 + assert(typeof pending === "object" && pending !== null && "generation" in pending);
1074 + assert.equal(typeof pending.generation, "number");
1075 +
1076 + // Queue a newer check before allowing the main thread to acknowledge truncation.
1077 + send({ type: "check", id: "during-truncate", generation: Number(pending.generation) + 1 });
1078 + truncateRequest.deliver();
1079 + checkpointRequests.release();
1080 + yield* checkpointWorkerReply(worker);
1081 + const reply = replies.find(
1082 + (message) =>
1083 + typeof message === "object" &&
1084 + message !== null &&
1085 + "id" in message &&
1086 + message.id === "during-truncate",
1087 + );
1088 + assert.include(reply, {
1089 + type: "checkpoint",
1090 + id: "during-truncate",
1091 + generation: pending.generation,
1092 + blocked: true,
1093 + });
1094 + yield* sql.unsafe("INSERT INTO pages(payload) VALUES (x'00')").unprepared;
1095 + assert.deepEqual(yield* sql`SELECT COUNT(*) AS count FROM pages`, [{ count: 1201 }]);
1096 + }),
1097 + ),
1098 +);
1099 +
1100 it.effect("hands checkpoints back to the writer when the worker stops", () =>
1101 withCheckpointClient((sql) =>
1102 Effect.gen(function* () {
@@ -1004,3 +1280,439 @@ it.effect.each([
1280 );
1281 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
1282 );
1283 +
1284 +const openDatabase = (filename: string) =>
1285 + Effect.acquireRelease(
1286 + Effect.sync(() => new NodeSqlite.DatabaseSync(filename)),
1287 + (db) => Effect.sync(() => db.close()),
1288 + );
1289 +
1290 +it.effect.each([false, true])(
1291 + "bounds a busy truncate without gating a reset WAL (resetDuringHandoff=%s)",
1292 + (resetDuringHandoff) =>
1293 + withCheckpointClient((sql, filename) =>
1294 + Effect.gen(function* () {
1295 + const fs = yield* FileSystem.FileSystem;
1296 + const worker = startedWorkers.at(-1)!;
1297 + const reader = yield* openDatabase(filename);
1298 + const observer = yield* openDatabase(filename);
1299 + const limit = 1024 * 1024;
1300 + const requests = pauseCheckpointRequests(worker);
1301 + yield* Effect.addFinalizer(() => Effect.sync(requests.release));
1302 + const truncation = holdWorkerMessage(worker, "truncate-request");
1303 + yield* Effect.addFinalizer(() => Effect.sync(truncation.release));
1304 + yield* sql.unsafe(`PRAGMA journal_size_limit = ${limit}`).unprepared;
1305 + yield* sql`CREATE TABLE pages(payload BLOB)`;
1306 + yield* sql`
1307 + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1200)
1308 + INSERT INTO pages(payload) SELECT zeroblob(4000) FROM n
1309 + `;
1310 + // Reading before PASSIVE pins the last WAL frame even when every frame is copied.
1311 + reader.exec("BEGIN");
1312 + assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM pages").get()?.count, 1200);
1313 + requests.sendNext();
1314 + yield* Effect.promise(() => truncation.ready);
1315 + const copied = readCheckpointState(observer);
1316 + assert.equal(copied.checkpointed, copied.log);
1317 + assert.isAbove(copied.log, 1000);
1318 + assert.isBelow(copied.log, 10_000);
1319 + assert.isAbove(Number((yield* fs.stat(`${filename}-wal`)).size), limit);
1320 +
1321 + if (resetDuringHandoff) {
1322 + // Another connection can reset the WAL before the main thread acknowledges truncation.
1323 + reader.exec("ROLLBACK");
1324 + assert.equal(observer.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()?.busy, 0);
1325 + observer.exec("INSERT INTO pages VALUES (x'01')");
1326 + reader.exec("BEGIN");
1327 + assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM pages").get()?.count, 1201);
1328 + assert.isAbove(readCheckpointState(observer).log, 0);
1329 + assert.isBelow(readCheckpointState(observer).log, 10_000);
1330 + assert.isAtMost(Number((yield* fs.stat(`${filename}-wal`)).size), limit);
1331 + }
1332 +
1333 + const completed = waitForTruncateCompletion(worker);
1334 + requests.release();
1335 + const started = performance.now();
1336 + truncation.deliver();
1337 + const write = yield* Effect.forkChild(sql`INSERT INTO pages VALUES (x'02')`, {
1338 + startImmediately: true,
1339 + });
1340 + const reply = yield* Effect.promise(() => completed);
1341 + const elapsed = performance.now() - started;
1342 + assert.equal(reply.log, reply.checkpointed);
1343 + if (resetDuringHandoff) {
1344 + yield* Fiber.join(write);
1345 + assert.deepEqual(yield* sql`SELECT COUNT(*) AS count FROM pages`, [{ count: 1202 }]);
1346 + assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM pages").get()?.count, 1201);
1347 + } else {
1348 + yield* eventLoopTurn;
1349 + assert.isUndefined(write.pollUnsafe(), "the physical size limit must still gate writes");
1350 + assert.equal(reader.prepare("SELECT COUNT(*) AS count FROM pages").get()?.count, 1200);
1351 + }
1352 + reader.exec("ROLLBACK");
1353 + yield* checkpointWorkerReply(worker);
1354 + yield* Fiber.join(write);
1355 + yield* sql`INSERT INTO pages VALUES (x'03')`;
1356 + assert.deepEqual(yield* sql`SELECT COUNT(*) AS count FROM pages`, [
1357 + { count: resetDuringHandoff ? 1203 : 1202 },
1358 + ]);
1359 + assert.isAtMost(Number((yield* fs.stat(`${filename}-wal`)).size), limit);
1360 + assert.equal(reply.blocked, !resetDuringHandoff);
1361 + // Both implementations eventually reply; only a bound distinguishes SQLite's 5s busy wait.
1362 + assert.isBelow(elapsed, 1000, "TRUNCATE must return promptly while the reader stays open");
1363 + }),
1364 + ),
1365 + { skip: !supportsNoopCheckpoint, timeout: 15_000 },
1366 +);
1367 +
1368 +it.effect.each(["statement", "commit", "rollback", "partial failure", "worker failure"] as const)(
1369 + "bounds a real WAL backlog and resumes writes (%s)",
1370 + (mode) =>
1371 + withCheckpointClient(
1372 + (sql, filename) =>
1373 + Effect.gen(function* () {
1374 + const worker = startedWorkers.at(-1)!;
1375 + yield* sql`PRAGMA journal_size_limit = 1048576`;
1376 + yield* sql`CREATE TABLE pages(id INTEGER PRIMARY KEY, payload BLOB)`;
1377 + yield* sql`INSERT INTO pages VALUES (12001, x'00')`;
1378 + yield* checkpointWorkerReply(worker);
1379 + const reader = yield* openDatabase(filename);
1380 + const observer = yield* openDatabase(filename);
1381 + reader.exec("BEGIN");
1382 + reader.prepare("SELECT COUNT(*) FROM pages").get();
1383 + const requests = pauseCheckpointRequests(worker);
1384 + yield* Effect.addFinalizer(() => Effect.sync(requests.release));
1385 + const insert = sql.unsafe(`
1386 + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ${mode === "partial failure" ? 12001 : 12000})
1387 + INSERT OR FAIL INTO pages SELECT i, zeroblob(4000) FROM n ORDER BY i
1388 + `).unprepared;
1389 + if (mode === "commit" || mode === "rollback") {
1390 + const result = yield* sql
1391 + .withTransaction(
1392 + Effect.gen(function* () {
1393 + yield* insert;
1394 + // Admission must not prevent an active transaction from finishing.
1395 + yield* sql`INSERT INTO pages VALUES (12002, x'00')`;
1396 + assert.deepEqual(yield* sql`SELECT COUNT(*) AS count FROM pages`, [
1397 + { count: 12002 },
1398 + ]);
1399 + if (mode === "rollback") return yield* Effect.fail("rollback");
1400 + }),
1401 + )
1402 + .pipe(Effect.exit);
1403 + assert.equal(result._tag, mode === "rollback" ? "Failure" : "Success");
1404 + } else if (mode === "partial failure") {
1405 + const error = yield* insert.pipe(Effect.flip);
1406 + assert.equal(error.reason._tag, "ConstraintError");
1407 + } else yield* insert;
1408 +
1409 + if (mode !== "rollback") {
1410 + assert.isAbove(
1411 + readCheckpointState(observer).log - readCheckpointState(observer).checkpointed,
1412 + 10_000,
1413 + );
1414 + }
1415 + const finished = yield* Deferred.make<void>();
1416 + const write = yield* Effect.forkChild(
1417 + sql`INSERT INTO pages VALUES (12003, x'00')`.pipe(
1418 + Effect.andThen(Deferred.succeed(finished, undefined)),
1419 + ),
1420 + { startImmediately: true },
1421 + );
1422 + yield* eventLoopTurn;
1423 + const expected = mode === "rollback" ? 1 : mode === "commit" ? 12002 : 12001;
1424 + if (mode !== "rollback") {
1425 + assert.isFalse(yield* Deferred.isDone(finished));
1426 + const before = Number(
1427 + (yield* (yield* FileSystem.FileSystem).stat(`${filename}-wal`)).size,
1428 + );
1429 + assert.deepEqual(
1430 + yield* sql`SELECT COUNT(*) AS count FROM pages`.pipe(SqliteClient.readOnly),
1431 + [{ count: expected }],
1432 + );
1433 + yield* eventLoopTurn;
1434 + assert.isFalse(yield* Deferred.isDone(finished));
1435 + assert.equal(
1436 + Number((yield* (yield* FileSystem.FileSystem).stat(`${filename}-wal`)).size),
1437 + before,
1438 + );
1439 + }
1440 + if (mode === "worker failure") {
1441 + yield* Effect.promise(() => worker.terminate());
1442 + yield* Fiber.join(write);
1443 + assert.deepEqual(yield* sql`PRAGMA wal_autocheckpoint`, [{ wal_autocheckpoint: 1000 }]);
1444 + reader.exec("ROLLBACK");
1445 + } else {
1446 + reader.exec("ROLLBACK");
1447 + requests.release();
1448 + yield* Fiber.join(write);
1449 + yield* checkpointWorkerReply(worker);
1450 + if (mode !== "rollback")
1451 + assert.isAtMost(
1452 + Number((yield* (yield* FileSystem.FileSystem).stat(`${filename}-wal`)).size),
1453 + 1048576,
1454 + );
1455 + }
1456 + assert.deepEqual(yield* sql`SELECT COUNT(*) AS count FROM pages`, [
1457 + { count: expected + 1 },
1458 + ]);
1459 + yield* sql.withTransaction(sql`INSERT INTO pages VALUES (12004, x'00')`);
1460 + }),
1461 + { readerWorker: true },
1462 + ),
1463 + { skip: !supportsNoopCheckpoint },
1464 +);
1465 +
1466 +it.effect.each([
1467 + { reserved: false, stage: "queued" },
1468 + { reserved: true, stage: "queued" },
1469 + { reserved: false, stage: "elected" },
1470 + { reserved: true, stage: "elected" },
1471 + { reserved: false, stage: "resumed" },
1472 + { reserved: true, stage: "resumed" },
1473 +] as const)(
1474 + "hands cancellation to the next writer (reserved=$reserved, stage=$stage)",
1475 + ({ reserved, stage }) =>
1476 + withCheckpointClient((sql, filename) =>
1477 + Effect.gen(function* () {
1478 + const worker = startedWorkers.at(-1)!;
1479 + const { reader, checkpointRequests } = yield* blockCheckpointBehindReader(
1480 + sql,
1481 + filename,
1482 + worker,
1483 + );
1484 + yield* Effect.scoped(
1485 + Effect.gen(function* () {
1486 + const connection = reserved ? yield* sql.reserve : undefined;
1487 + const insert = (value: number) =>
1488 + connection
1489 + ? connection.executeUnprepared("INSERT INTO entries VALUES (?)", [value], undefined)
1490 + : sql`INSERT INTO entries VALUES (${value})`;
1491 + const scheduled = schedulerHoldingDispatch(stage === "resumed");
1492 + yield* Effect.addFinalizer(() => Effect.sync(scheduled.resume));
1493 + const first = yield* Effect.forkChild(
1494 + insert(1).pipe(Effect.provideService(Scheduler.Scheduler, scheduled.scheduler)),
1495 + { startImmediately: true },
1496 + );
1497 + const second = yield* Effect.forkChild(insert(2), { startImmediately: true });
1498 + yield* eventLoopTurn;
1499 + assert.isUndefined(first.pollUnsafe());
1500 + assert.isUndefined(second.pollUnsafe());
1501 + if (stage !== "queued") {
1502 + scheduled.arm();
1503 + const truncated = waitForTruncateCompletion(worker);
1504 + checkpointRequests.release();
1505 + reader.exec("ROLLBACK");
1506 + yield* Effect.promise(() => truncated);
1507 + yield* Effect.promise(() => scheduled.paused);
1508 + if (stage === "resumed") {
1509 + scheduled.resume();
1510 + yield* Effect.promise(() => scheduled.continuation);
1511 + }
1512 + }
1513 + yield* Fiber.interrupt(first);
1514 + scheduled.resume();
1515 + if (stage === "queued") {
1516 + reader.exec("ROLLBACK");
1517 + checkpointRequests.release();
1518 + yield* checkpointWorkerReply(worker);
1519 + }
1520 + yield* eventLoopTurn;
1521 + assert.isDefined(
1522 + second.pollUnsafe(),
1523 + "cancellation must hand off without waiting for a later checkpoint",
1524 + );
1525 + yield* Fiber.join(second);
1526 + }),
1527 + );
1528 + yield* sql.withTransaction(sql`INSERT INTO entries VALUES (3)`);
1529 + assert.deepEqual(yield* sql`SELECT value FROM entries ORDER BY value`.values, [[2], [3]]);
1530 + }),
1531 + ),
1532 + { skip: !supportsNoopCheckpoint },
1533 +);
1534 +
1535 +it.effect.each([false, true])(
1536 + "keeps masked cleanup waiting at the checkpoint gate (transaction=%s)",
1537 + (transaction) =>
1538 + withCheckpointClient((sql, filename) =>
1539 + Effect.gen(function* () {
1540 + const worker = startedWorkers.at(-1)!;
1541 + const { reader, checkpointRequests } = yield* blockCheckpointBehindReader(
1542 + sql,
1543 + filename,
1544 + worker,
1545 + );
1546 + const entered = yield* Deferred.make<void>();
1547 + const cleanupEntered = yield* Deferred.make<void>();
1548 + const work = yield* Effect.forkChild(
1549 + Deferred.succeed(entered, undefined).pipe(
1550 + Effect.andThen(Effect.never),
1551 + Effect.onInterrupt(() =>
1552 + Effect.gen(function* () {
1553 + yield* Deferred.succeed(cleanupEntered, undefined);
1554 + const insert = sql.unsafe("INSERT INTO entries VALUES (1)").unprepared;
1555 + yield* transaction ? sql.withTransaction(insert) : insert;
1556 + }),
1557 + ),
1558 + ),
1559 + { startImmediately: true },
1560 + );
1561 + yield* Deferred.await(entered);
1562 + const interrupt = yield* Effect.forkChild(Fiber.interrupt(work), {
1563 + startImmediately: true,
1564 + });
1565 + yield* Deferred.await(cleanupEntered);
1566 + yield* Effect.yieldNow;
1567 + assert.isUndefined(work.pollUnsafe());
1568 +
1569 + const truncateFinished = waitForTruncateCompletion(worker);
1570 + checkpointRequests.release();
1571 + reader.exec("ROLLBACK");
1572 + yield* Effect.promise(() => truncateFinished);
1573 + yield* Fiber.join(interrupt);
1574 + assert.deepEqual(yield* sql.unsafe("SELECT value FROM entries").unprepared, [{ value: 1 }]);
1575 + }),
1576 + ),
1577 + { skip: !supportsNoopCheckpoint },
1578 +);
1579 +
1580 +it.effect.each(["PRAGMA incremental_vacuum(1)", "PRAGMA user_version = 42"])(
1581 + "admits maintenance mutations through the checkpoint gate (%s)",
1582 + (operation) =>
1583 + withCheckpointClient((sql, filename) =>
1584 + Effect.gen(function* () {
1585 + const worker = startedWorkers.at(-1)!;
1586 + yield* sql`PRAGMA auto_vacuum = INCREMENTAL`;
1587 + yield* sql`VACUUM`;
1588 + yield* sql`CREATE TABLE reclaim(payload BLOB)`;
1589 + yield* sql`INSERT INTO reclaim VALUES (zeroblob(8000000))`;
1590 + yield* sql`DELETE FROM reclaim`;
1591 + yield* checkpointWorkerReply(worker);
1592 + const { reader, checkpointRequests } = yield* blockCheckpointBehindReader(
1593 + sql,
1594 + filename,
1595 + worker,
1596 + );
1597 + const before = (yield* sql<{ freelist_count: number }>`PRAGMA freelist_count`)[0]!
1598 + .freelist_count;
1599 + assert.isAbove(before, 0);
1600 + const mutation = yield* Effect.forkChild(sql.unsafe(operation).unprepared, {
1601 + startImmediately: true,
1602 + });
1603 + yield* eventLoopTurn;
1604 + assert.isUndefined(mutation.pollUnsafe());
1605 + assert.equal(reader.prepare("PRAGMA user_version").get()?.user_version, 0);
1606 + reader.exec("ROLLBACK");
1607 + checkpointRequests.release();
1608 + yield* Fiber.join(mutation);
1609 + if (operation.includes("incremental_vacuum")) {
1610 + assert.isBelow(
1611 + (yield* sql<{ freelist_count: number }>`PRAGMA freelist_count`)[0]!.freelist_count,
1612 + before,
1613 + );
1614 + } else assert.deepEqual(yield* sql`PRAGMA user_version`, [{ user_version: 42 }]);
1615 + yield* sql.withTransaction(sql`INSERT INTO entries VALUES (1)`);
1616 + }),
1617 + ),
1618 + { skip: !supportsNoopCheckpoint },
1619 +);
1620 +
1621 +it.effect("keeps automatic checkpoints when mutation classification is unavailable", () =>
1622 + Effect.acquireUseRelease(
1623 + Effect.sync(() => {
1624 + const descriptor = Object.getOwnPropertyDescriptor(
1625 + NodeSqlite.DatabaseSync.prototype,
1626 + "setAuthorizer",
1627 + )!;
1628 + Object.defineProperty(NodeSqlite.DatabaseSync.prototype, "setAuthorizer", {
1629 + configurable: true,
1630 + value: undefined,
1631 + });
1632 + return descriptor;
1633 + }),
1634 + () =>
1635 + withCheckpointClient((sql) =>
1636 + Effect.gen(function* () {
1637 + assert.deepEqual(yield* sql`PRAGMA wal_autocheckpoint`, [{ wal_autocheckpoint: 1000 }]);
1638 + assert.deepEqual(yield* sql`PRAGMA synchronous`, [{ synchronous: 2 }]);
1639 + yield* sql`CREATE TABLE fallback(value INTEGER)`;
1640 + yield* sql.withTransaction(sql`INSERT INTO fallback VALUES (1)`);
1641 + assert.deepEqual(yield* sql`SELECT value FROM fallback`, [{ value: 1 }]);
1642 + }),
1643 + ),
1644 + (descriptor) =>
1645 + Effect.sync(() =>
1646 + Object.defineProperty(NodeSqlite.DatabaseSync.prototype, "setAuthorizer", descriptor),
1647 + ),
1648 + ),
1649 +);
1650 +
1651 +it.effect.each(["successful", "failed"] as const)(
1652 + "lets the event loop run while draining queued writes (%s)",
1653 + (outcome) =>
1654 + withCheckpointClient((sql, filename) =>
1655 + Effect.gen(function* () {
1656 + const worker = startedWorkers.at(-1)!;
1657 + const { reader, checkpointRequests } = yield* blockCheckpointBehindReader(
1658 + sql,
1659 + filename,
1660 + worker,
1661 + );
1662 + let completed = 0;
1663 + let resolveHeartbeat = (_completed: number) => {};
1664 + const heartbeat = new Promise<number>((resolve) => {
1665 + resolveHeartbeat = resolve;
1666 + });
1667 + const scheduler = new Scheduler.MixedScheduler("async", (task) => {
1668 + const handle = setImmediate(task);
1669 + return () => clearImmediate(handle);
1670 + });
1671 + const writeScheduler: Scheduler.Scheduler = {
1672 + executionMode: scheduler.executionMode,
1673 + makeDispatcher: () => scheduler.makeDispatcher(),
1674 + shouldYield: () => false,
1675 + };
1676 + const writes = [];
1677 + for (let value = 0; value < 20; value++) {
1678 + writes.push(
1679 + yield* Effect.forkChild(
1680 + sql`INSERT INTO entries VALUES (${outcome === "failed" ? "invalid" : value})`.pipe(
1681 + Effect.match({
1682 + onSuccess: () => assert.equal(outcome, "successful"),
1683 + onFailure: (error) => {
1684 + assert.equal(outcome, "failed");
1685 + assert.equal(error._tag, "SqlError");
1686 + assert.equal(error.reason.operation, "execute");
1687 + assert.include(String(error.reason.cause), "datatype mismatch");
1688 + },
1689 + }),
1690 + Effect.tap(() =>
1691 + Effect.sync(() => {
1692 + if (++completed === 1) setImmediate(() => resolveHeartbeat(completed));
1693 + }),
1694 + ),
1695 + Effect.provideService(Scheduler.Scheduler, writeScheduler),
1696 + ),
1697 + { startImmediately: true },
1698 + ),
1699 + );
1700 + }
1701 + yield* eventLoopTurn;
1702 + assert.equal(completed, 0);
1703 + reader.exec("ROLLBACK");
1704 + checkpointRequests.release();
1705 + const completedAtHeartbeat = yield* Effect.promise(() => heartbeat);
1706 + for (const write of writes) yield* Fiber.join(write);
1707 + assert.equal(completed, writes.length);
1708 + assert.deepEqual(
1709 + yield* sql`SELECT value FROM entries ORDER BY value`,
1710 + outcome === "failed"
1711 + ? []
1712 + : Array.from({ length: writes.length }, (_, value) => ({ value })),
1713 + );
1714 + assert.isBelow(completedAtHeartbeat, writes.length);
1715 + }),
1716 + ),
1717 + { skip: !supportsNoopCheckpoint },
1718 +);
packages/shared/src/nodeSqliteClient.ts
+468 -131
@@ -468,43 +468,134 @@ const makeReader = Effect.fnUntraced(function* (options: SqliteClientConfig) {
468 });
469
470 const CHECKPOINT_FRAMES = 1000;
471 -// While the worker runs, the writer still checkpoints a WAL this long. Writes
472 -// with no pause leave the worker behind, and the WAL can only restart once
473 -// every frame is checkpointed, so this keeps the file from growing forever.
474 -const WRITER_BACKSTOP_FRAMES = 10 * CHECKPOINT_FRAMES;
471 const CHECKPOINT_IDLE_MS = 100;
472 +const CHECKPOINT_BACKPRESSURE_FRAMES = 10 * CHECKPOINT_FRAMES;
473
477 -// SQLite before 3.51 reads NOOP as PASSIVE and would checkpoint on every
478 -// request, so the worker refuses to start there and the writer keeps
479 -// checkpointing.
474 +const readSafeSqliteInteger = (value: unknown) => {
475 + const number = typeof value === "bigint" ? Number(value) : value;
476 + return typeof number === "number" && Number.isSafeInteger(number) ? number : undefined;
477 +};
478 +
479 +// Evaluated source also works in bundles and single-executable builds.
480 const checkpointWorkerSource = `
481 const { parentPort, workerData } = require("node:worker_threads");
482 const { DatabaseSync } = require("node:sqlite");
483 -const db = new DatabaseSync(workerData.filename);
484 -const version = db.prepare("SELECT sqlite_version() AS version").get().version;
485 -const [major, minor] = version.split(".").map(Number);
486 -if (major < 3 || (major === 3 && minor < 51)) throw new Error("SQLite " + version + " has no NOOP checkpoint");
487 -// macOS fsync() does not flush the drive cache; F_FULLFSYNC does. Other platforms ignore this.
488 -db.exec("PRAGMA checkpoint_fullfsync = ON;");
489 -const frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
490 -const checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
491 -const finish = () => {
492 - const { log, checkpointed } = frames.get();
493 - if (log >= workerData.frames && checkpointed < log) checkpoint.get();
494 -};
483 +const { statSync } = require("node:fs");
484 +let db;
485 +let frames;
486 +let checkpoint;
487 +let truncate;
488 +let journalSizeLimit = -1;
489 +let generation = 0;
490 +let nextTruncateId = 0;
491 +let pendingTruncate;
492 +let pendingBarriers = 0;
493 let idle;
494 +const initialize = () => {
495 + if (db !== undefined) return;
496 + // The writer switches to WAL after constructing the client.
497 + db = new DatabaseSync(workerData.filename);
498 + db.exec("PRAGMA busy_timeout = 5000;");
499 + const mode = String(db.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase();
500 + if (mode !== "wal") throw new Error("database uses journal_mode " + mode + ", not wal");
501 + // macOS requires F_FULLFSYNC to flush the drive cache.
502 + db.exec("PRAGMA checkpoint_fullfsync = ON;");
503 + frames = db.prepare("PRAGMA wal_checkpoint(NOOP)");
504 + checkpoint = db.prepare("PRAGMA wal_checkpoint(PASSIVE)");
505 + truncate = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)");
506 +};
507 +const atCeiling = (state) => state.log >= workerData.backpressureFrames;
508 +const exceedsSizeLimit = () =>
509 + journalSizeLimit >= 0 && statSync(workerData.filename + "-wal").size > journalSizeLimit;
510 +const schedule = (state, blocked) => {
511 + if (blocked || state.log - state.checkpointed >= workerData.frames) {
512 + idle = setTimeout(() => check(undefined, undefined, true), workerData.idleMs);
513 + }
514 +};
515 +const check = (id, nextJournalSizeLimit, force, nextGeneration = generation) => {
516 + initialize();
517 + if (Number.isSafeInteger(nextGeneration)) generation = Math.max(generation, nextGeneration);
518 + if (Number.isSafeInteger(nextJournalSizeLimit)) journalSizeLimit = nextJournalSizeLimit;
519 + let state = frames.get();
520 + const oversized = exceedsSizeLimit();
521 + if (force || state.log - state.checkpointed >= workerData.frames || oversized) {
522 + checkpoint.get();
523 + state = frames.get();
524 + }
525 + if (state.checkpointed === state.log && (atCeiling(state) || oversized)) {
526 + pendingTruncate = { truncateId: ++nextTruncateId, checkId: id, generation, state };
527 + parentPort.postMessage({
528 + type: "truncate-request",
529 + truncateId: pendingTruncate.truncateId,
530 + checkId: id,
531 + generation,
532 + ...state,
533 + });
534 + return;
535 + }
536 + const blocked = (atCeiling(state) || oversized) && state.checkpointed < state.log;
537 + parentPort.postMessage({ type: "checkpoint", id, generation, ...state, blocked });
538 + schedule(state, blocked);
539 +};
540 +const finishTruncate = (truncateId) => {
541 + if (pendingTruncate === undefined || pendingTruncate.truncateId !== truncateId) return;
542 + const pending = pendingTruncate;
543 + parentPort.postMessage({ type: "truncate-start", truncateId });
544 + let busy;
545 + // Admission is paused here; a pinned reader must not make truncation wait.
546 + db.exec("PRAGMA busy_timeout = 0;");
547 + try {
548 + busy = truncate.get().busy !== 0;
549 + } finally {
550 + db.exec("PRAGMA busy_timeout = 5000;");
551 + }
552 + const state = frames.get();
553 + const blocked = (atCeiling(state) && (busy || state.checkpointed < state.log)) || exceedsSizeLimit();
554 + pendingTruncate = undefined;
555 + parentPort.postMessage({
556 + type: "checkpoint",
557 + id: pending.checkId,
558 + generation: pending.generation,
559 + truncateId,
560 + ...state,
561 + blocked,
562 + });
563 + while (pendingBarriers > 0) {
564 + pendingBarriers--;
565 + parentPort.postMessage("barrier");
566 + }
567 + schedule(state, blocked);
568 +};
569 parentPort.on("message", (request) => {
497 - const { log, checkpointed } = frames.get();
498 - if (log - checkpointed >= workerData.frames) checkpoint.get();
570 clearTimeout(idle);
500 - idle = setTimeout(finish, workerData.idleMs);
501 - parentPort.postMessage(request);
571 + if (request && request.type === "truncate") {
572 + finishTruncate(request.truncateId);
573 + return;
574 + }
575 + const isBarrier = request === "barrier";
576 + if (pendingTruncate !== undefined) {
577 + if (isBarrier) pendingBarriers++;
578 + else if (request && request.type === "check") {
579 + // Retire the request without labeling the pending snapshot with a newer generation.
580 + parentPort.postMessage({
581 + type: "checkpoint",
582 + id: request.id,
583 + generation: pendingTruncate.generation,
584 + ...pendingTruncate.state,
585 + blocked: true,
586 + });
587 + }
588 + return;
589 + }
590 + const input = request && typeof request === "object" ? request : {};
591 + check(input.id, input.journalSizeLimit, input.force, input.generation);
592 + if (isBarrier) {
593 + if (pendingTruncate !== undefined) pendingBarriers++;
594 + else parentPort.postMessage("barrier");
595 + }
596 });
597 `;
598
505 -/**
506 - * Call the returned function after each statement on the writer.
507 - */
599 const startCheckpointWorker = Effect.fnUntraced(function* (
600 filename: string,
601 writer: NodeSqlite.DatabaseSync,
@@ -514,60 +605,227 @@ const startCheckpointWorker = Effect.fnUntraced(function* (
605 "SQLite checkpoint worker unavailable; checkpoints run on the main connection",
606 { reason },
607 );
608 + if (typeof writer.isTransaction !== "boolean" || typeof writer.setAuthorizer !== "function") {
609 + yield* warn("Node SQLite lacks transaction-state or statement-authorizer support");
610 + return undefined;
611 + }
612 + const version = String(writer.prepare("SELECT sqlite_version() AS version").get()?.version);
613 + const [major = 0, minor = 0] = version.split(".").map(Number);
614 + // Older SQLite treats NOOP as PASSIVE, which would checkpoint on the writer.
615 + if (major < 3 || (major === 3 && minor < 51)) {
616 + yield* warn(`SQLite ${version} has no NOOP checkpoint`);
617 + return undefined;
618 + }
619 + const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
620 + const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
621 let worker: NodeWorkerThreads.Worker;
622 try {
623 worker = new NodeWorkerThreads.Worker(checkpointWorkerSource, {
624 eval: true,
521 - workerData: { filename, frames: CHECKPOINT_FRAMES, idleMs: CHECKPOINT_IDLE_MS },
625 + workerData: {
626 + filename,
627 + frames: CHECKPOINT_FRAMES,
628 + backpressureFrames: CHECKPOINT_BACKPRESSURE_FRAMES,
629 + idleMs: CHECKPOINT_IDLE_MS,
630 + },
631 });
632 } catch (cause) {
633 yield* warn(String(cause));
634 return undefined;
635 }
527 - writer.exec(`PRAGMA wal_autocheckpoint = ${WRITER_BACKSTOP_FRAMES};`);
636 const runFork = Effect.runForkWith(yield* Effect.context<never>());
637 let stopped = false;
530 - let checking = false;
638 + let generation = 0;
639 + let nextId = 0;
640 + let inFlight: number | undefined;
641 let checkAgain = false;
642 + let blocked = false;
643 + let log = 0;
644 + let checkpointed = 0;
645 + let unknown = false;
646 + let truncate: { id: number; acknowledged: boolean } | undefined;
647 + type Waiter = { resume: () => void; cancelled: boolean };
648 + const waiters: Array<Waiter> = [];
649 + let elected: Waiter | undefined;
650 + const gated = () =>
651 + !stopped &&
652 + !writer.isTransaction &&
653 + (unknown || blocked || truncate !== undefined || log >= CHECKPOINT_BACKPRESSURE_FRAMES);
654 + const wake = () => {
655 + if (!gated() && elected === undefined) {
656 + elected = waiters.shift();
657 + elected?.resume();
658 + }
659 + if (waiters.length === 0 && elected === undefined) worker.unref();
660 + };
661 + const release = (waiter: Waiter) => {
662 + waiter.cancelled = true;
663 + const index = waiters.indexOf(waiter);
664 + if (index !== -1) waiters.splice(index, 1);
665 + if (elected === waiter) elected = undefined;
666 + wake();
667 + };
668 const handBack = (reason: string) => {
669 if (stopped) return;
670 stopped = true;
671 + truncate = undefined;
672 try {
673 writer.exec(`PRAGMA wal_autocheckpoint = ${CHECKPOINT_FRAMES};`);
674 } catch {}
675 + wake();
676 runFork(warn(reason));
677 };
678 + const send = (message: unknown) => {
679 + try {
680 + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
681 + worker.postMessage(message);
682 + } catch (cause) {
683 + handBack(String(cause));
684 + }
685 + };
686 + const acknowledge = () => {
687 + if (truncate === undefined || truncate.acknowledged || stopped || writer.isTransaction) return;
688 + truncate.acknowledged = true;
689 + send({ type: "truncate", truncateId: truncate.id });
690 + };
691 + const observe = () => {
692 + try {
693 + const state = frames.get();
694 + const nextLog = readSafeSqliteInteger(state?.log);
695 + const nextCheckpointed = readSafeSqliteInteger(state?.checkpointed);
696 + if (nextLog === undefined || nextCheckpointed === undefined)
697 + throw new Error("Invalid WAL frame counts");
698 + log = nextLog;
699 + checkpointed = nextCheckpointed;
700 + unknown = false;
701 + } catch {
702 + unknown = true;
703 + }
704 + };
705 + const request = (force = false) => {
706 + if (stopped || writer.isTransaction) return;
707 + if (truncate !== undefined) {
708 + acknowledge();
709 + return;
710 + }
711 + if (inFlight !== undefined) {
712 + checkAgain = true;
713 + return;
714 + }
715 + if (!force && !gated() && log - checkpointed < CHECKPOINT_FRAMES) return;
716 + inFlight = ++nextId;
717 + try {
718 + send({
719 + type: "check",
720 + id: inFlight,
721 + generation,
722 + journalSizeLimit: readSafeSqliteInteger(sizeLimit.get()?.journal_size_limit),
723 + force: force || gated(),
724 + });
725 + } catch (cause) {
726 + handBack(String(cause));
727 + }
728 + };
729 + const check = () => {
730 + if (stopped || writer.isTransaction) return;
731 + generation++;
732 + observe();
733 + request();
734 + wake();
735 + };
736 worker.on("error", (cause) => handBack(cause.message));
737 worker.on("exit", (code) => handBack(`exited with code ${code}`));
738 + worker.on("message", (message: unknown) => {
739 + if (stopped || typeof message !== "object" || message === null || !("type" in message)) return;
740 + if (
741 + message.type === "truncate-request" &&
742 + "truncateId" in message &&
743 + typeof message.truncateId === "number"
744 + ) {
745 + truncate = { id: message.truncateId, acknowledged: false };
746 + blocked = true;
747 + acknowledge();
748 + return;
749 + }
750 + if (message.type !== "checkpoint") return;
751 + const completedTruncate =
752 + truncate !== undefined && "truncateId" in message && message.truncateId === truncate.id;
753 + if (completedTruncate) truncate = undefined;
754 + // An acknowledged truncate excludes new writer mutations, so its result is current.
755 + if (
756 + (completedTruncate || ("generation" in message && message.generation === generation)) &&
757 + "log" in message &&
758 + typeof message.log === "number" &&
759 + "checkpointed" in message &&
760 + typeof message.checkpointed === "number" &&
761 + "blocked" in message &&
762 + typeof message.blocked === "boolean"
763 + ) {
764 + log = message.log;
765 + checkpointed = message.checkpointed;
766 + blocked = message.blocked;
767 + unknown = false;
768 + }
769 + // Even a stale snapshot must retire its request so a newer check can run.
770 + if ("id" in message && message.id === inFlight) inFlight = undefined;
771 + if (checkAgain && inFlight === undefined) {
772 + checkAgain = false;
773 + request(true);
774 + }
775 + wake();
776 + });
777 yield* Effect.addFinalizer(() =>
778 Effect.promise(() => {
779 stopped = true;
780 + truncate = undefined;
781 + wake();
782 return worker.terminate();
783 }),
784 );
548 -
549 - // At most one request is in flight. A statement that runs during it asks for
550 - // one more check, so the frames of a last commit before idle still get one.
551 - const check = () => {
552 - if (stopped) return;
553 - if (checking) {
554 - checkAgain = true;
555 - return;
556 - }
557 - checking = true;
558 - // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin.
559 - worker.postMessage(null);
560 - };
561 - worker.on("message", () => {
562 - checking = false;
563 - if (checkAgain) {
564 - checkAgain = false;
565 - check();
566 - }
567 - });
568 - // After the listeners: adding a "message" listener refs the worker again.
785 + writer.exec("PRAGMA wal_autocheckpoint = 0;");
786 + observe();
787 worker.unref();
570 - return check;
788 +
789 + const runWithAdmission = <A, E>(
790 + execute: () => Exit.Exit<A, E>,
791 + admitted?: Waiter,
792 + ): Effect.Effect<A, E> =>
793 + Effect.suspend(() => {
794 + if (!gated()) {
795 + // Release the election after executing; its successor must see the new WAL state.
796 + try {
797 + return execute();
798 + } finally {
799 + if (admitted !== undefined) release(admitted);
800 + }
801 + }
802 + if (admitted !== undefined) release(admitted);
803 + const waiter: Waiter = { resume: () => {}, cancelled: false };
804 + const wait = Effect.uninterruptibleMask((restore) =>
805 + Effect.withFiber((fiber) =>
806 + (fiber.getRef(TransactionAcquire)?.restore ?? restore)(
807 + Effect.callback<void>(function (this: Scheduler.Scheduler, resume) {
808 + const dispatcher = this.makeDispatcher();
809 + waiter.resume = () => {
810 + dispatcher.scheduleTask(() => {
811 + if (!waiter.cancelled) resume(Effect.void);
812 + }, 0);
813 + };
814 + waiters.push(waiter);
815 + worker.ref();
816 + request(true);
817 + wake();
818 + return Effect.sync(() => release(waiter));
819 + }),
820 + ),
821 + ),
822 + );
823 + return wait.pipe(
824 + Effect.flatMap(() => runWithAdmission(execute, waiter)),
825 + Effect.onInterrupt(() => Effect.sync(() => release(waiter))),
826 + );
827 + });
828 + return { check, runWithAdmission };
829 });
830
831 const make = Effect.fn("makeWithDatabase")(function* (
@@ -611,6 +869,71 @@ const make = Effect.fn("makeWithDatabase")(function* (
869 : undefined;
870
871 const statementReaderCache = new WeakMap<NodeSqlite.StatementSync, boolean>();
872 + interface CheckpointClassification {
873 + backpressure: boolean;
874 + check: boolean;
875 + }
876 + const checkpointClassifications = new WeakMap<
877 + NodeSqlite.StatementSync,
878 + CheckpointClassification
879 + >();
880 + const mutatingPragmasWithValues = new Set([
881 + "application_id",
882 + "auto_vacuum",
883 + "journal_mode",
884 + "schema_version",
885 + "user_version",
886 + ]);
887 + const mutatesPragma = (name: string | null, value: string | null) => {
888 + const pragma = name?.toLowerCase();
889 + if (pragma === undefined) return false;
890 + if (pragma === "incremental_vacuum" || pragma === "optimize") return true;
891 + if (pragma === "wal_checkpoint") return value?.toLowerCase() !== "noop";
892 + return value !== null && mutatingPragmasWithValues.has(pragma);
893 + };
894 + let activeClassification: CheckpointClassification | undefined;
895 + const withClassification = <A>(
896 + classification: CheckpointClassification | undefined,
897 + f: () => A,
898 + ): A => {
899 + if (classification === undefined) return f();
900 + const previous = activeClassification;
901 + activeClassification = classification;
902 + try {
903 + return f();
904 + } finally {
905 + activeClassification = previous;
906 + }
907 + };
908 + if (checkpoint !== undefined) {
909 + // SQLite may reprepare an expired statement while it executes. Keep this
910 + // callback installed and collect only around that statement's prepare/run.
911 + db.setAuthorizer((actionCode, action, argument) => {
912 + const classification = activeClassification;
913 + if (classification === undefined) return NodeSqlite.constants.SQLITE_OK;
914 + const constants = NodeSqlite.constants;
915 + if (actionCode === constants.SQLITE_TRANSACTION) {
916 + classification.backpressure ||= action === "BEGIN";
917 + classification.check ||= action === "COMMIT" || action === "ROLLBACK";
918 + } else if (actionCode === constants.SQLITE_SAVEPOINT) {
919 + classification.backpressure ||= action === "BEGIN";
920 + classification.check = true;
921 + } else if (actionCode === constants.SQLITE_PRAGMA && mutatesPragma(action, argument)) {
922 + classification.backpressure = true;
923 + classification.check = true;
924 + } else if (
925 + actionCode !== constants.SQLITE_READ &&
926 + actionCode !== constants.SQLITE_SELECT &&
927 + actionCode !== constants.SQLITE_FUNCTION &&
928 + actionCode !== constants.SQLITE_RECURSIVE &&
929 + actionCode !== constants.SQLITE_PRAGMA
930 + ) {
931 + classification.backpressure = true;
932 + classification.check = true;
933 + }
934 + return constants.SQLITE_OK;
935 + });
936 + }
937 const hasRows = (statement: NodeSqlite.StatementSync): boolean => {
938 const cached = statementReaderCache.get(statement);
939 if (cached !== undefined) {
@@ -623,7 +946,12 @@ const make = Effect.fn("makeWithDatabase")(function* (
946
947 const prepare = (sql: string) =>
948 Effect.try({
626 - try: () => db.prepare(sql),
949 + try: () => {
950 + const classification = { backpressure: false, check: false };
951 + const statement = withClassification(classification, () => db.prepare(sql));
952 + if (checkpoint !== undefined) checkpointClassifications.set(statement, classification);
953 + return statement;
954 + },
955 catch: (cause) =>
956 new SqlError({
957 reason: classifyError(cause, "Failed to prepare statement", "prepare"),
@@ -643,81 +971,64 @@ const make = Effect.fn("makeWithDatabase")(function* (
971 const runStatement = (
972 statement: NodeSqlite.StatementSync,
973 params: ReadonlyArray<unknown>,
646 - raw: boolean,
974 + mode: "rows" | "raw" | "values" = "rows",
975 ) =>
976 Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
649 - try {
650 - statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
651 - if (hasRows(statement)) {
652 - const rows = statement.all(...(params as any));
653 - checkpoint?.();
654 - return Effect.succeed(rows);
655 - }
656 - const result = statement.run(...(params as any));
657 - checkpoint?.();
658 - return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
659 - } catch (cause) {
660 - return Effect.fail(
661 - new SqlError({
662 - reason: classifyError(cause, "Failed to execute statement", "execute"),
663 - }),
664 - );
665 - }
666 - });
667 -
668 - const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
669 - Effect.flatMap(statementFor(sql, params), (s) => runStatement(s, params, raw));
670 -
671 - const runStatementValues = (
672 - statement: NodeSqlite.StatementSync,
673 - params: ReadonlyArray<unknown>,
674 - ) =>
675 - Effect.acquireUseRelease(
676 - Effect.succeed(statement),
677 - (statement) =>
678 - Effect.try({
679 - try: () => {
680 - statement.setReadBigInts(
681 - Boolean(Context.get(Fiber.getCurrent()!.context, Client.SafeIntegers)),
682 - );
977 + const classification = checkpointClassifications.get(statement);
978 + const execute = () => {
979 + let arrays = false;
980 + let result: Exit.Exit<ReadonlyArray<unknown>, SqlError>;
981 + try {
982 + const value = withClassification(classification, () => {
983 + statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
984 if (hasRows(statement)) {
684 - statement.setReturnArrays(true);
685 - const rows = statement.all(...(params as any)) as unknown as ReadonlyArray<
686 - ReadonlyArray<unknown>
687 - >;
688 - checkpoint?.();
689 - return rows;
985 + arrays = mode === "values";
986 + if (arrays) statement.setReturnArrays(true);
987 + return statement.all(...(params as any));
988 }
691 - statement.run(...(params as any));
692 - checkpoint?.();
693 - return [];
694 - },
695 - catch: (cause) =>
989 + const result = statement.run(...(params as any));
990 + return mode === "raw" ? (result as unknown as ReadonlyArray<unknown>) : [];
991 + });
992 + result = Exit.succeed(value);
993 + } catch (cause) {
994 + result = Exit.fail(
995 new SqlError({
996 reason: classifyError(cause, "Failed to execute statement", "execute"),
997 }),
699 - }),
700 - (statement) =>
701 - Effect.try({
702 - try: () => {
703 - if (hasRows(statement)) {
704 - statement.setReturnArrays(false);
705 - }
706 - },
707 - catch: (cause) =>
708 - new SqlError({
709 - reason: classifyError(
710 - cause,
711 - "Failed to reset statement result mode",
712 - "resetResultMode",
713 - ),
714 - }),
715 - }).pipe(Effect.orDie),
716 - );
998 + );
999 + } finally {
1000 + // OR FAIL may have committed earlier rows even when execution throws.
1001 + if (classification?.check) checkpoint?.check();
1002 + }
1003 + if (arrays) {
1004 + try {
1005 + statement.setReturnArrays(false);
1006 + } catch (cause) {
1007 + return Exit.die(
1008 + new SqlError({
1009 + reason: classifyError(
1010 + cause,
1011 + "Failed to reset statement result mode",
1012 + "resetResultMode",
1013 + ),
1014 + }),
1015 + );
1016 + }
1017 + }
1018 + return result;
1019 + };
1020 + return checkpoint !== undefined && classification?.backpressure
1021 + ? checkpoint.runWithAdmission(execute)
1022 + : execute();
1023 + });
1024
1025 + const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
1026 + Effect.flatMap(statementFor(sql, params), (statement) =>
1027 + runStatement(statement, params, raw ? "raw" : "rows"),
1028 + );
1029 const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
1030 Effect.flatMap(statementFor(sql, params), (statement) =>
720 - runStatementValues(statement, params),
1031 + runStatement(statement, params, "values"),
1032 );
1033
1034 return identity<Connection>({
@@ -732,12 +1043,12 @@ const make = Effect.fn("makeWithDatabase")(function* (
1043 },
1044 executeValuesUnprepared(sql, params) {
1045 return Effect.flatMap(prepare(sql), (statement) =>
735 - runStatementValues(statement, params ?? []),
1046 + runStatement(statement, params ?? [], "values"),
1047 );
1048 },
1049 executeUnprepared(sql, params, rowTransform) {
1050 const effect = prepare(sql).pipe(
740 - Effect.flatMap((statement) => runStatement(statement, params ?? [], false)),
1051 + Effect.flatMap((statement) => runStatement(statement, params ?? [])),
1052 );
1053 return rowTransform ? Effect.map(effect, rowTransform) : effect;
1054 },
@@ -773,23 +1084,49 @@ const make = Effect.fn("makeWithDatabase")(function* (
1084 lockWaitMs: Number((clock.monotonicTimeNanosUnsafe() - start) / 1000n) / 1000,
1085 });
1086
1087 + const writerBorrowBatchSize = 16;
1088 + let writerBorrowsSinceYield = 0;
1089 const borrower: Borrower = (use) =>
1090 Effect.flatMap(route, (target) =>
1091 Effect.withFiber((fiber) => {
779 - const effect = Effect.suspend(() => use(target.connection));
780 - if (
781 - !fiber.getRef(References.TracerEnabled) ||
782 - !fiber.getRef(Statement.SpanPropagationEnabled)
783 - ) {
784 - return target.lock.withPermits(1)(effect);
785 - }
1092 const clock = fiber.getRef(Clock.Clock);
1093 const start = clock.monotonicTimeNanosUnsafe();
788 - return target.lock.withPermits(1)(
789 - Effect.andThen(
790 - Effect.sync(() => annotateAcquired(fiber, acquired(target, clock, start))),
791 - effect,
792 - ),
1094 + const useConnection = Effect.suspend(() => {
1095 + if (
1096 + fiber.getRef(References.TracerEnabled) &&
1097 + fiber.getRef(Statement.SpanPropagationEnabled)
1098 + ) {
1099 + annotateAcquired(fiber, acquired(target, clock, start));
1100 + }
1101 + return use(target.connection);
1102 + });
1103 + if (!options.checkpointWorker || target.name !== "writer") {
1104 + return target.lock.withPermits(1)(useConnection);
1105 + }
1106 + const writerUse = Effect.onExit(useConnection, (exit) =>
1107 + Effect.sync(() => {
1108 + writerBorrowsSinceYield = Exit.hasInterrupts(exit)
1109 + ? 0
1110 + : Math.min(writerBorrowsSinceYield + 1, writerBorrowBatchSize);
1111 + }),
1112 + );
1113 + return Effect.flatMap(target.lock.withPermitsIfAvailable(1)(writerUse), (result) =>
1114 + Option.isSome(result)
1115 + ? Effect.succeed(result.value)
1116 + : target.lock.withPermits(1)(
1117 + Effect.andThen(
1118 + // Failed SQL also consumes the batch; cancellation hands off immediately.
1119 + Effect.suspend(() => {
1120 + if (writerBorrowsSinceYield < writerBorrowBatchSize) return Effect.void;
1121 + writerBorrowsSinceYield = 0;
1122 + return Effect.callback<void>((resume) => {
1123 + const immediate = setImmediate(() => resume(Effect.void));
1124 + return Effect.sync(() => clearImmediate(immediate));
1125 + });
1126 + }),
1127 + writerUse,
1128 + ),
1129 + ),
1130 );
1131 }),
1132 );