@devries-cameron20 / t3code-1 / commits / 7a39060072
Fork 0

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

fix(server): a damaged state database fails startup with its path and how to recover (#35057)

Julius Marminge committed Nov 12, 2026 at 02:30 UTC 7a3906007294c3591b3ebc6afa29bad40037452e
4 files changed +98 -5
apps/server/src/persistence/Sqlite.test.ts
+24
@@ -14,6 +14,7 @@ import * as Effect from "effect/Effect";
14 import * as FileSystem from "effect/FileSystem";
15 import * as Layer from "effect/Layer";
16 import * as SqlClient from "effect/sql/SqlClient";
17 +import * as SqlError from "effect/sql/SqlError";
18 import { vi } from "vite-plus/test";
19
20 import * as ServerConfig from "../config.ts";
@@ -191,6 +192,29 @@ it.effect("drops planner statistics a database already has", () => {
192 );
193 });
194
195 +it.effect("names a database file that is not SQLite", () => {
196 + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-notadb-"));
197 + const dbPath = NodePath.join(tempDir, "state.sqlite");
198 + NodeFS.writeFileSync(dbPath, "not a db\n");
199 +
200 + return Effect.gen(function* () {
201 + const opened = yield* Effect.void.pipe(
202 + Effect.provide(
203 + SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer)),
204 + ),
205 + Effect.result,
206 + );
207 +
208 + assert.equal(opened._tag, "Failure");
209 + if (opened._tag === "Failure") {
210 + assert.isTrue(SqlError.isSqlError(opened.failure));
211 + assert.include(opened.failure.message, dbPath);
212 + }
213 + }).pipe(
214 + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
215 + );
216 +});
217 +
218 const ownT3Home = Effect.fn(function* () {
219 const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig;
220 // An empty home, so no boot service installed on this machine is read.
apps/server/src/persistence/Sqlite.ts
+39
@@ -2,8 +2,10 @@ import * as Effect from "effect/Effect";
2 import * as Layer from "effect/Layer";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 +import * as Predicate from "effect/Predicate";
6 import * as Schema from "effect/Schema";
7 import * as SqlClient from "effect/sql/SqlClient";
8 +import * as SqlError from "effect/sql/SqlError";
9 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
10
11 import { hasPendingMigrations, runMigrations } from "./Migrations.ts";
@@ -22,6 +24,32 @@ export class ServerOwnsDatabaseError extends Schema.TaggedError<ServerOwnsDataba
24 }
25 }
26
27 +// SQLITE_CORRUPT and SQLITE_NOTADB; node:sqlite reports extended codes whose low byte is the primary code.
28 +const DAMAGED_SQLITE_CODES = new Set([11, 26]);
29 +
30 +const isDamagedDatabase = (error: SqlError.SqlError): boolean => {
31 + const seen = new Set<unknown>();
32 + let cause: unknown = error.cause;
33 + while (Predicate.isObject(cause) && !seen.has(cause)) {
34 + seen.add(cause);
35 + if (typeof cause.errcode === "number" && DAMAGED_SQLITE_CODES.has(cause.errcode & 0xff)) {
36 + return true;
37 + }
38 + cause = cause.cause;
39 + }
40 + return false;
41 +};
42 +
43 +// Keeps the SqlError type so callers' error channels do not change; the original stays as the cause.
44 +const damagedDatabaseError = (dbPath: string, cause: SqlError.SqlError) =>
45 + new SqlError.SqlError({
46 + reason: new SqlError.UnknownError({
47 + cause,
48 + operation: "open",
49 + message: `The T3 Code database at ${dbPath} is damaged or is not a SQLite database, so T3 Code cannot start. To recover, quit T3 Code, then move that file and any -wal and -shm files next to it out of the folder, or replace them with a backup. T3 Code creates a new database on the next start.`,
50 + }),
51 + });
52 +
53 // CLI commands open the server's database from another process; migrating behind its owner changes the schema it runs on.
54 const runMigrationsAsOwner = Effect.fn("SqlitePersistence.runMigrationsAsOwner")(function* () {
55 // With nothing pending, runMigrations only validates the recorded history and writes nothing.
@@ -90,6 +118,17 @@ const makeLayerFromPath = <E, R>(setup: Layer.Layer<never, E, R>) =>
118 "service.name": "t3code-server",
119 },
120 }),
121 + ).pipe(
122 + Layer.catchTag("SqlError", (error) =>
123 + Layer.effect(
124 + SqlClient.SqlClient,
125 + Effect.fail(
126 + SqlError.isSqlError(error) && isDamagedDatabase(error)
127 + ? damagedDatabaseError(dbPath, error)
128 + : error,
129 + ),
130 + ),
131 + ),
132 );
133 }, Layer.unwrap);
134
packages/shared/src/nodeSqliteClient.test.ts
+22
@@ -3,11 +3,15 @@ import type * as NodeWorkerThreads from "node:worker_threads";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { assert, it } from "@effect/vitest";
5 import * as Deferred from "effect/Deferred";
6 +import * as Cause from "effect/Cause";
7 import * as Effect from "effect/Effect";
8 +import * as Exit from "effect/Exit";
9 import * as Fiber from "effect/Fiber";
10 import * as FileSystem from "effect/FileSystem";
11 +import * as Layer from "effect/Layer";
12 import * as Path from "effect/Path";
13 import * as SqlClient from "effect/sql/SqlClient";
14 +import * as SqlError from "effect/sql/SqlError";
15 import * as Statement from "effect/sql/Statement";
16 import { ChildProcess, ChildProcessSpawner } from "effect/process";
17 import * as Stream from "effect/Stream";
@@ -408,6 +412,24 @@ it.effect("uses the writer when the reader cannot open the database", () =>
412 ),
413 );
414
415 +it.effect("fails with a typed SqlError when the database file is not SQLite", () =>
416 + Effect.gen(function* () {
417 + const fs = yield* FileSystem.FileSystem;
418 + const path = yield* Path.Path;
419 + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-notadb-" });
420 + const filename = path.join(directory, "state.sqlite");
421 + yield* fs.writeFileString(filename, "not a db\n");
422 +
423 + const exit = yield* Layer.build(SqliteClient.layer({ filename, checkpointWorker: true })).pipe(
424 + Effect.exit,
425 + );
426 +
427 + assert.isTrue(Exit.isFailure(exit));
428 + if (Exit.isFailure(exit)) assert.isTrue(SqlError.isSqlError(Cause.squash(exit.cause)));
429 + if (Exit.isFailure(exit)) assert.isFalse(Cause.hasDies(exit.cause));
430 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
431 +);
432 +
433 it.effect("finishes masked database cleanup after its caller is interrupted", () =>
434 Effect.gen(function* () {
435 const sql = yield* SqlClient.SqlClient;
packages/shared/src/nodeSqliteClient.ts
+13 -5
@@ -630,17 +630,25 @@ const startCheckpointWorker = Effect.fnUntraced(function* (
630 yield* warn("Node SQLite lacks transaction-state or statement-authorizer support");
631 return undefined;
632 }
633 - // These are the writer's first statements, before callers set their own wait.
634 - writer.exec("PRAGMA busy_timeout = 5000;");
635 - const version = String(writer.prepare("SELECT sqlite_version() AS version").get()?.version);
633 + // These are the writer's first statements, before callers set their own wait. A file that is
634 + // not a database first fails here.
635 + const { version, frames, sizeLimit } = yield* Effect.try({
636 + try: () => {
637 + writer.exec("PRAGMA busy_timeout = 5000;");
638 + return {
639 + version: String(writer.prepare("SELECT sqlite_version() AS version").get()?.version),
640 + frames: writer.prepare("PRAGMA wal_checkpoint(NOOP)"),
641 + sizeLimit: writer.prepare("PRAGMA journal_size_limit"),
642 + };
643 + },
644 + catch: (cause) => failed(cause, "Failed to open database", "open"),
645 + });
646 const [major = 0, minor = 0] = version.split(".").map(Number);
647 // Older SQLite treats NOOP as PASSIVE, which would checkpoint on the writer.
648 if (major < 3 || (major === 3 && minor < 51)) {
649 yield* warn(`SQLite ${version} has no NOOP checkpoint`);
650 return undefined;
651 }
642 - const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
643 - const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
652 const started = Result.try(
653 () =>
654 new NodeWorkerThreads.Worker(checkpointWorkerSource, {