The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 04:15 UTC
fix(opencode): retry shared database locks during startup (#17922)
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
luke committed
Oct 18, 2026 at 20:21 UTC
b058babb1694da9fa4b46b489dec2b76523dc218
2 files changed
+163
-3
packages/provider-opencode/src/server/OpenCodeRuntime.environment.test.ts
+117
@@ -234,3 +234,120 @@ server.listen(0, "127.0.0.1", () => {
234
10_000,
235
);
236
});
237
+
238
+describe("OpenCode database lock startup", () => {
239
+ effectIt.live.each([
240
+ { mode: "transient", keepPipesOpen: false },
241
+ { mode: "permanent", keepPipesOpen: false },
242
+ { mode: "configuration", keepPipesOpen: false },
243
+ { mode: "unrelated", keepPipesOpen: false },
244
+ { mode: "transient", keepPipesOpen: true },
245
+ { mode: "permanent", keepPipesOpen: true },
246
+ { mode: "configuration", keepPipesOpen: true },
247
+ { mode: "unrelated", keepPipesOpen: true },
248
+ ] as const)(
249
+ "handles $mode startup failures with bounded process ownership (open pipes: $keepPipesOpen)",
250
+ ({ mode, keepPipesOpen }) =>
251
+ Effect.gen(function* () {
252
+ const fs = yield* FileSystem.FileSystem;
253
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-lock-" });
254
+ const platform = yield* HostProcess.Platform;
255
+ const executablePath = yield* HostProcess.ExecutablePath;
256
+ const environment = yield* HostProcess.Environment;
257
+ const scriptPath = `${root}/fake.mjs`;
258
+ const attemptsPath = `${root}/attempts`;
259
+ yield* Effect.addFinalizer(() =>
260
+ fs.readFileString(`${attemptsPath}.descendants`).pipe(
261
+ Effect.orElseSucceed(() => ""),
262
+ Effect.flatMap((pids) =>
263
+ Effect.sync(() => {
264
+ for (const pid of pids.trim().split("\n").filter(Boolean)) {
265
+ try {
266
+ process.kill(Number(pid), "SIGKILL");
267
+ } catch {
268
+ // The fixture descendant may already have exited.
269
+ }
270
+ }
271
+ }),
272
+ ),
273
+ ),
274
+ );
275
+ yield* fs.writeFileString(
276
+ scriptPath,
277
+ `
278
+import { readFileSync, writeFileSync, writeSync } from "node:fs";
279
+import { createServer } from "node:http";
280
+import { spawn } from "node:child_process";
281
+const path = process.env.T3_TEST_ATTEMPTS;
282
+let attempt = 0;
283
+try { attempt = Number(readFileSync(path, "utf8")); } catch {}
284
+writeFileSync(path, String(++attempt));
285
+if (${JSON.stringify(mode)} !== "transient" || attempt < 3) {
286
+ // Inherited pipes remain open after the direct child exits.
287
+ if (${keepPipesOpen}) {
288
+ const descendant = spawn(process.execPath, ["-e", "setTimeout(() => {}, 10000)"], {
289
+ detached: true,
290
+ stdio: ["ignore", "inherit", "inherit"],
291
+ });
292
+ writeFileSync(path + ".descendants", descendant.pid + "\\n", { flag: "a" });
293
+ descendant.unref();
294
+ }
295
+ // A lock mentioned outside the startup diagnostic is not a lock failure.
296
+ if (${JSON.stringify(mode)} === "unrelated") writeSync(1, "note: database is locked was seen earlier\\n");
297
+ writeSync(2, ${JSON.stringify(mode === "configuration" || mode === "unrelated" ? "Invalid configuration" : "SQLiteError: database is locked (SQLITE_BUSY)")} + "\\n");
298
+ process.exit(1);
299
+}
300
+const server = createServer((req, res) => res.end("ok"));
301
+server.listen(0, "127.0.0.1", () => console.log("opencode server listening on http://127.0.0.1:" + server.address().port));
302
+`,
303
+ );
304
+ const binaryPath = `${root}/opencode${platform === "win32" ? ".cmd" : ""}`;
305
+ yield* fs.writeFileString(
306
+ binaryPath,
307
+ platform === "win32"
308
+ ? '@echo off\n"%T3_TEST_NODE_BINARY%" "%T3_TEST_OPENCODE_SCRIPT%" %*\n'
309
+ : '#!/bin/sh\nexec "$T3_TEST_NODE_BINARY" "$T3_TEST_OPENCODE_SCRIPT" "$@"\n',
310
+ );
311
+ if (platform !== "win32") yield* fs.chmod(binaryPath, 0o700);
312
+ const runtime = yield* OpenCodeRuntime.OpenCodeRuntime;
313
+ const result = yield* Effect.result(
314
+ runtime.startOpenCodeServerProcess({
315
+ binaryPath,
316
+ directory: root,
317
+ port: 0,
318
+ timeoutMs: 2_000,
319
+ environment: {
320
+ ...environment,
321
+ T3_TEST_NODE_BINARY: executablePath,
322
+ T3_TEST_OPENCODE_SCRIPT: scriptPath,
323
+ T3_TEST_ATTEMPTS: attemptsPath,
324
+ },
325
+ verify: () => Effect.succeed("1.14.19"),
326
+ }),
327
+ );
328
+ expect(result._tag).toBe(mode === "transient" ? "Success" : "Failure");
329
+ expect(Number(yield* fs.readFileString(attemptsPath))).toBe(
330
+ mode === "transient" ? 3 : mode === "permanent" ? 4 : 1,
331
+ );
332
+ if (result._tag === "Failure") {
333
+ expect(result.failure.reason).toBe(mode === "permanent" ? "databaseLocked" : undefined);
334
+ const stderr =
335
+ mode === "permanent"
336
+ ? "SQLiteError: database is locked (SQLITE_BUSY)"
337
+ : "Invalid configuration";
338
+ expect(result.failure.detail).toContain(`stderr:\n${stderr}`);
339
+ expect(result.failure.cause).toMatchObject({ exitCode: 1, stderr: `${stderr}\n` });
340
+ }
341
+ }).pipe(
342
+ Effect.scoped,
343
+ Effect.provide([
344
+ OpenCodeRuntime.layer.pipe(
345
+ Layer.provide(OpenCodeServerLedger.layerTest),
346
+ Layer.provideMerge(NodeServices.layer),
347
+ ),
348
+ FetchHttpClient.layer,
349
+ ]),
350
+ ),
351
+ 15_000,
352
+ );
353
+});
packages/provider-opencode/src/server/OpenCodeRuntime.ts
+46
-3
@@ -27,6 +27,7 @@ import * as Ref from "effect/Ref";
27
import * as Result from "effect/Result";
28
import * as Scope from "effect/Scope";
29
import * as Schema from "effect/Schema";
30
+import * as Schedule from "effect/Schedule";
31
import * as Stream from "effect/Stream";
32
import * as ChildProcess from "effect/process/ChildProcess";
33
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
@@ -85,6 +86,7 @@ export function resolveOpenCodeServerPassword(
86
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000;
87
const DEFAULT_HOSTNAME = "127.0.0.1";
88
const OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS = 64 * 1024;
89
+const OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT = "500 millis";
90
const OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
91
export interface OpenCodeServerProcess {
92
readonly url: string;
@@ -107,8 +109,17 @@ export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERRO
109
readonly operation: string;
110
readonly cause?: unknown;
111
readonly detail: string;
112
+ readonly reason?: OpenCodeStartupFailureReason;
113
}> {}
114
115
+export type OpenCodeStartupFailureReason = "databaseLocked";
116
+
117
+// OpenCode reports a held opencode.db lock on stderr. Classify it once where the
118
+// exit is captured so callers branch on the category, not on diagnostic text.
119
+function classifyStartupExit(stderr: string): OpenCodeStartupFailureReason | undefined {
120
+ return /SQLITE_BUSY|database is locked/i.test(stderr) ? "databaseLocked" : undefined;
121
+}
122
+
123
export const isOpenCodeRuntimeError = (u: unknown): u is OpenCodeRuntimeError =>
124
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
125
@@ -657,9 +668,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
668
throwOnError: true,
669
});
670
660
- const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (
661
- input,
662
- ) =>
671
+ const startServerAttempt: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (input) =>
672
Effect.gen(function* () {
673
const runtimeScope = yield* Scope.Scope;
674
@@ -782,13 +791,22 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
791
const exitFiber = yield* child.exitCode.pipe(
792
Effect.flatMap((code) =>
793
Effect.gen(function* () {
794
+ // Allow trailing diagnostics to drain, but descendants can keep pipes open.
795
+ const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe(
796
+ Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT),
797
+ );
798
+ if (Option.isNone(drained)) {
799
+ yield* Fiber.interruptAll([stdoutFiber, stderrFiber]);
800
+ }
801
const stdout = (yield* Ref.get(stdoutRef)) ?? "";
802
const stderr = (yield* Ref.get(stderrRef)) ?? "";
803
const exitCode = Number(code);
804
+ const reason = classifyStartupExit(stderr);
805
yield* Deferred.fail(
806
readyDeferred,
807
new OpenCodeRuntimeError({
808
operation: "startOpenCodeServerProcess",
809
+ ...(reason ? { reason } : {}),
810
detail: [
811
`OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
812
stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
@@ -860,6 +878,31 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
878
} satisfies OpenCodeServerProcess;
879
});
880
881
+ const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = (
882
+ input,
883
+ ) =>
884
+ Effect.gen(function* () {
885
+ const ownerScope = yield* Scope.Scope;
886
+ const attempt = Effect.gen(function* () {
887
+ const attemptScope = yield* Scope.fork(ownerScope);
888
+ return yield* startServerAttempt(input).pipe(
889
+ Effect.provideService(Scope.Scope, attemptScope),
890
+ Effect.onExit((exit) =>
891
+ Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void,
892
+ ),
893
+ );
894
+ });
895
+ // OpenCode instances share opencode.db. Migration/WAL locks are transient;
896
+ // configuration and executable errors are not helped by launching again.
897
+ return yield* attempt.pipe(
898
+ Effect.retry({
899
+ times: 3,
900
+ schedule: Schedule.spaced("250 millis"),
901
+ while: (error) => error.reason === "databaseLocked",
902
+ }),
903
+ );
904
+ });
905
+
906
const connectToOpenCodeServer: OpenCodeRuntime["Service"]["connectToOpenCodeServer"] = (
907
input,
908
) => {