diff --git a/apps/server/src/observability/EventLoopMonitor.ts b/apps/server/src/observability/EventLoopMonitor.ts index 02922cdd3ae6..39711c57e252 100644 --- a/apps/server/src/observability/EventLoopMonitor.ts +++ b/apps/server/src/observability/EventLoopMonitor.ts @@ -3,7 +3,7 @@ import * as NodeOS from "node:os"; import * as NodePerfHooks from "node:perf_hooks"; import type { ServerEventLoopStall } from "@t3tools/contracts"; -import { RotatingFileSink, RotatingFileSinkError } from "@t3tools/shared/logging"; +import { makeAsyncRotatingFileSink } from "@t3tools/shared/logging"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -17,6 +17,7 @@ import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import * as Metrics from "./Metrics.ts"; +import * as StallTraceCapture from "./StallTraceCapture.ts"; // Subtract the histogram's timer resolution; this can undercount stalls by up to RESOLUTION_MS. const RESOLUTION_MS = 1000; @@ -144,26 +145,18 @@ const layerWith = ( EventLoopMonitor, Effect.gen(function* () { const sample = yield* makeSampler; + const stallTraceCapture = yield* StallTraceCapture.StallTraceCapture; + const scope = yield* Effect.scope; // Clients sample on connect as well as the timer, and the sampler resets shared state. const sampling = yield* Semaphore.make(1); const warmedUp = yield* Ref.make(false); const latestNoticeableStall = yield* Ref.make< { readonly stall: ServerEventLoopStall; readonly detectedAtMs: number } | undefined >(undefined); - const stallSink = yield* Effect.try({ - try: () => - new RotatingFileSink({ - filePath: stallLog.filePath, - maxBytes: stallLog.maxBytes, - maxFiles: 1, - throwOnError: true, - }), - catch: (cause) => - new RotatingFileSinkError({ - operation: "initialize", - filePath: stallLog.filePath, - cause, - }), + const stallSink = yield* makeAsyncRotatingFileSink({ + filePath: stallLog.filePath, + maxBytes: stallLog.maxBytes, + maxFiles: 1, }).pipe( Effect.catch(() => Effect.logWarning("event loop stall log unavailable", { @@ -192,6 +185,8 @@ const layerWith = ( }, }); } + const windowMs = Math.max(readings.elapsedMs, 30_000); + const stallTrace = stallTraceCapture.attribute({ detectedAt: now, delayMaxMs, windowMs }); const attributes = { delayMaxMs, utilization: Math.round(utilization * 100) / 100, @@ -201,23 +196,30 @@ const layerWith = ( minorPageFaults: usage.minorPageFault, involuntaryContextSwitches: usage.involuntaryContextSwitches, rssMb: Math.round(rssBytes / 1024 / 1024), + ...(stallTrace.activeSpans.length > 0 ? { activeSpans: stallTrace.activeSpans } : {}), + ...(stallTrace.slowSpans.length > 0 ? { slowSpans: stallTrace.slowSpans } : {}), }; yield* Effect.logWarning(`event loop stalled for ${delayMaxMs} ms`).pipe( Effect.withSpan("server.eventLoop.stall", { root: true, level: "Warn", attributes }), ); - if (stallSink !== undefined) { - yield* encodeStallLine({ time: detectedAt, ...attributes }).pipe( - Effect.flatMap((line) => - Effect.try({ - try: () => stallSink.write(`${line}\n`), - catch: (cause) => - new RotatingFileSinkError({ - operation: "write", - filePath: stallLog.filePath, - cause, + // Preserve the trace window in the monitor's scope so reconnecting clients never block or cancel it. + yield* Effect.forkIn( + stallTraceCapture.saveSnapshot({ detectedAt: now, delayMaxMs, windowMs }).pipe( + Effect.flatMap((traceSnapshotPath) => + traceSnapshotPath === undefined + ? Effect.void + : Effect.logInfo("Preserved event-loop stall trace snapshot", { + detectedAt, + delayMaxMs, + traceSnapshotPath, }), - }), ), + ), + scope, + ); + if (stallSink !== undefined) { + yield* encodeStallLine({ time: detectedAt, ...attributes }).pipe( + Effect.flatMap((line) => stallSink.write(`${line}\n`)), Effect.catch(() => Effect.logWarning("event loop stall log write failed", { filePath: stallLog.filePath, @@ -225,7 +227,11 @@ const layerWith = ( ), ); } - }).pipe(sampling.withPermits(1)); + }).pipe( + // Resetting the histogram consumes the sample, so finish recording even if a client disconnects. + Effect.uninterruptible, + sampling.withPermits(1), + ); const wait = Effect.sleep(SAMPLE_INTERVAL); // The first sample includes migrations and bootstrap; skip expected startup stalls. yield* wait.pipe( diff --git a/apps/server/src/observability/Observability.ts b/apps/server/src/observability/Observability.ts index 1b0414e43b8a..2b8c51b45bbf 100644 --- a/apps/server/src/observability/Observability.ts +++ b/apps/server/src/observability/Observability.ts @@ -5,6 +5,7 @@ import * as SharedObservability from "@t3tools/shared/observability"; import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as References from "effect/References"; import * as Tracer from "effect/Tracer"; import * as OtlpExporter from "effect/observability/OtlpExporter"; @@ -18,6 +19,7 @@ import * as ServerLogger from "../serverLogger.ts"; import * as BrowserTraceCollector from "./BrowserTraceCollector.ts"; import * as HeapAttribution from "./HeapAttribution.ts"; import * as OtlpExportFailures from "./OtlpExportFailures.ts"; +import * as StallTraceCapture from "./StallTraceCapture.ts"; export const layer = Layer.unwrap( Effect.gen(function* () { @@ -73,11 +75,19 @@ export const layer = Layer.unwrap( ...(delegate ? { delegate } : {}), }); + const path = yield* Path.Path; const heapAttribution = yield* HeapAttribution.make(tracer); yield* heapAttribution.run; + const stallTraceCapture = yield* StallTraceCapture.make({ + tracer: heapAttribution.tracer, + sink, + snapshotDir: path.join(config.logsDir, "event-loop-stall-traces"), + }); + return Layer.mergeAll( - Layer.succeed(Tracer.Tracer, heapAttribution.tracer), + Layer.succeed(Tracer.Tracer, stallTraceCapture.tracer), + Layer.succeed(StallTraceCapture.StallTraceCapture, stallTraceCapture.service), BrowserTraceCollector.layer(sink), ); }), diff --git a/apps/server/src/observability/StallTraceCapture.test.ts b/apps/server/src/observability/StallTraceCapture.test.ts new file mode 100644 index 000000000000..73f1a0b0d456 --- /dev/null +++ b/apps/server/src/observability/StallTraceCapture.test.ts @@ -0,0 +1,187 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Tracer from "effect/Tracer"; + +import * as StallTraceCapture from "./StallTraceCapture.ts"; + +const msToNs = (ms: number) => BigInt(ms) * 1_000_000n; + +describe("StallTraceCapture", () => { + it.effect("attributes active and slow spans and preserves trace lines across rotation", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "stall-trace-capture-" }); + const tracePath = path.join(dir, "server.trace.ndjson"); + const snapshotDir = path.join(dir, "event-loop-stall-traces"); + + const baseMs = Date.parse("2026-11-25T06:00:00.000Z"); + // Older record outside the 60s capture window (must be excluded). + const oldLine = JSON.stringify({ + type: "effect-span", + name: "old.span", + endTimeUnixNano: String(msToNs(baseMs - 120_000)), + durationMs: 12, + }); + // Record inside the capture window that already rotated into `.1`. + const rotatedLine = JSON.stringify({ + type: "effect-span", + name: "rotated.inWindow", + endTimeUnixNano: String(msToNs(baseMs - 40_000)), + durationMs: 85, + }); + yield* fs.writeFileString(`${tracePath}.1`, `${oldLine}\n${rotatedLine}\n`); + + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 1024 * 1024, + maxFiles: 2, + batchWindowMs: 60_000, + }); + const fileTracer = yield* makeLocalFileTracer({ + filePath: tracePath, + maxBytes: 1024 * 1024, + maxFiles: 2, + batchWindowMs: 60_000, + sink, + }); + const capture = yield* StallTraceCapture.make({ + tracer: fileTracer, + sink, + snapshotDir, + minWindowMs: 60_000, + cooldownMs: 30_000, + }); + + const startSpan = (name: string, startMs: number) => + capture.tracer.span({ + name, + parent: Option.none(), + annotations: Context.empty(), + links: [], + startTime: msToNs(startMs), + kind: "internal", + root: false, + sampled: true, + }); + + // Long-lived idle subscription opened 10 minutes earlier should not be blamed. + const idleSubscription = startSpan("ws.subscribeShell", baseMs - 600_000); + // Fast span (<50ms) should stay out of slowSpans. + const fast = startSpan("sqlite.fast", baseMs - 5_000); + fast.end(msToNs(baseMs - 4_995), Exit.void); + // Slow span in window should appear in slowSpans and in the preserved snapshot. + const slow = startSpan("ProjectionStore.heavyRead", baseMs - 4_000); + slow.end(msToNs(baseMs - 2_800), Exit.void); + // Active span still open when the stall sample fires. + const active = startSpan("AntigravityUsage.scan", baseMs - 2_500); + + const detectedAt = DateTime.makeUnsafe(baseMs); + const attribution = capture.service.attribute({ + detectedAt, + delayMaxMs: 2_500, + windowMs: 30_000, + }); + const snapshotPath = yield* capture.service.saveSnapshot({ + detectedAt, + delayMaxMs: 2_500, + windowMs: 30_000, + }); + + assert.deepStrictEqual(attribution.activeSpans, ["AntigravityUsage.scan (2500ms)"]); + assert.deepStrictEqual(attribution.slowSpans, ["ProjectionStore.heavyRead (1200ms)"]); + assert.isDefined(snapshotPath); + + const savedText = yield* fs.readFileString(snapshotPath!); + assert.notInclude(savedText, "old.span"); + assert.include(savedText, "rotated.inWindow"); + assert.include(savedText, "ProjectionStore.heavyRead"); + + // A second snapshot within cooldown skips writing another file while attribution stays live. + const duringCooldownAt = DateTime.makeUnsafe(baseMs + 5_000); + const duringCooldownPath = yield* capture.service.saveSnapshot({ + detectedAt: duringCooldownAt, + delayMaxMs: 2_100, + windowMs: 30_000, + }); + const duringCooldownAttr = capture.service.attribute({ + detectedAt: duringCooldownAt, + delayMaxMs: 2_100, + windowMs: 30_000, + }); + assert.isUndefined(duringCooldownPath); + assert.deepStrictEqual(duringCooldownAttr.activeSpans, ["AntigravityUsage.scan (7500ms)"]); + + active.end(msToNs(baseMs + 6_000), Exit.void); + idleSubscription.end(msToNs(baseMs + 6_000), Exit.void); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect( + "bounds snapshot size to newest lines and prunes snapshots beyond maxSnapshotFiles", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "stall-trace-prune-" }); + const tracePath = path.join(dir, "server.trace.ndjson"); + const snapshotDir = path.join(dir, "event-loop-stall-traces"); + + const baseMs = Date.parse("2026-11-25T06:10:00.000Z"); + const line1 = JSON.stringify({ + name: "first-trimmed", + endTimeUnixNano: String(msToNs(baseMs - 2_000)), + pad: "a".repeat(80), + }); + const line2 = JSON.stringify({ + name: "second-kept", + endTimeUnixNano: String(msToNs(baseMs - 1_000)), + pad: "b".repeat(80), + }); + yield* fs.writeFileString(tracePath, `${line1}\n${line2}\n`); + + const inner = Tracer.make({ span: (options) => new Tracer.NativeSpan(options) }); + const capture = yield* StallTraceCapture.make({ + tracer: inner, + sink: { filePath: tracePath, flush: Effect.void }, + snapshotDir, + maxSnapshotBytes: Buffer.byteLength(line2) + 10, + maxSnapshotFiles: 2, + cooldownMs: 0, + }); + + const snap1 = yield* capture.service.saveSnapshot({ + detectedAt: DateTime.makeUnsafe(baseMs), + delayMaxMs: 2_100, + windowMs: 30_000, + }); + assert.isDefined(snap1); + const text = yield* fs.readFileString(snap1!); + assert.notInclude(text, "first-trimmed"); + assert.include(text, "second-kept"); + + yield* capture.service.saveSnapshot({ + detectedAt: DateTime.makeUnsafe(baseMs + 1_000), + delayMaxMs: 2_100, + windowMs: 30_000, + }); + yield* capture.service.saveSnapshot({ + detectedAt: DateTime.makeUnsafe(baseMs + 2_000), + delayMaxMs: 2_100, + windowMs: 30_000, + }); + + const files = (yield* fs.readDirectory(snapshotDir)).toSorted(); + assert.strictEqual(files.length, 2); + assert.notInclude(files, path.basename(snap1!)); + }).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/observability/StallTraceCapture.ts b/apps/server/src/observability/StallTraceCapture.ts new file mode 100644 index 000000000000..5d692f2deb96 --- /dev/null +++ b/apps/server/src/observability/StallTraceCapture.ts @@ -0,0 +1,267 @@ +import type { TraceSink } from "@t3tools/shared/observability"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Semaphore from "effect/Semaphore"; +import * as Stream from "effect/Stream"; +import * as Tracer from "effect/Tracer"; + +const NOTABLE_SPAN_MS = 50; +const MAX_RECENT_SPANS = 128; +const REPORTED_SPANS = 8; +const ACTIVE_SPAN_MAX_AGE_NS = BigInt(5 * 60_000) * 1_000_000n; +const DEFAULT_MIN_WINDOW_MS = 60_000; +const DEFAULT_MAX_SNAPSHOT_BYTES = 4 * 1024 * 1024; +const DEFAULT_MAX_SNAPSHOT_FILES = 10; +const DEFAULT_COOLDOWN_MS = 30_000; +const STALL_SNAPSHOT_PREFIX = "stall-"; +const STALL_SNAPSHOT_SUFFIX = ".trace.ndjson"; +const END_TIME_NANO_PATTERN = /"endTimeUnixNano":"(\d+)"/; + +interface StallSpanAttribution { + readonly activeSpans: ReadonlyArray; + readonly slowSpans: ReadonlyArray; +} + +interface RecentSpan { + readonly name: string; + readonly durationMs: number; + readonly endTimeNs: bigint; +} + +interface StallTraceCaptureInput { + readonly detectedAt: DateTime.Utc; + readonly delayMaxMs: number; + readonly windowMs: number; +} + +interface StallTraceCaptureService { + readonly attribute: (input: StallTraceCaptureInput) => StallSpanAttribution; + readonly saveSnapshot: (input: StallTraceCaptureInput) => Effect.Effect; +} + +export class StallTraceCapture extends Context.Reference( + "t3/observability/StallTraceCapture", + { + defaultValue: () => ({ + attribute: () => ({ + activeSpans: [], + slowSpans: [], + }), + saveSnapshot: () => Effect.undefined, + }), + }, +) {} + +const extractEndTimeNs = (line: string): bigint | undefined => { + const match = END_TIME_NANO_PATTERN.exec(line); + if (match?.[1] === undefined) return undefined; + try { + return BigInt(match[1]); + } catch { + return undefined; + } +}; + +const isStallSnapshotName = (name: string) => + name.startsWith(STALL_SNAPSHOT_PREFIX) && name.endsWith(STALL_SNAPSHOT_SUFFIX); + +/** + * Tracks active and slow spans and preserves a bounded slice of `server.trace.ndjson` + * whenever `EventLoopMonitor` records a stall, so stall traces survive fast rotation. + */ +export const make = Effect.fn("StallTraceCapture.make")(function* (options: { + readonly tracer: Tracer.Tracer; + readonly sink: Pick; + readonly snapshotDir: string; + readonly maxSnapshotBytes?: number; + readonly maxSnapshotFiles?: number; + readonly minWindowMs?: number; + readonly cooldownMs?: number; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const maxSnapshotBytes = options.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES; + const maxSnapshotFiles = options.maxSnapshotFiles ?? DEFAULT_MAX_SNAPSHOT_FILES; + const minWindowMs = options.minWindowMs ?? DEFAULT_MIN_WINDOW_MS; + const cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS; + + const open = new Map(); + const recent: Array = []; + const snapshotLock = yield* Semaphore.make(1); + let lastSnapshotAtMs: number | undefined; + + const wrapped = Tracer.make({ + ...(options.tracer.context === undefined ? {} : { context: options.tracer.context }), + span(spanOptions) { + const span = options.tracer.span(spanOptions); + open.set(span, { name: spanOptions.name, startTimeNs: spanOptions.startTime }); + const end = span.end.bind(span); + span.end = (endTime, exit) => { + open.delete(span); + const durationMs = Number(endTime - spanOptions.startTime) / 1_000_000; + if (durationMs >= NOTABLE_SPAN_MS) { + recent.push({ name: spanOptions.name, durationMs, endTimeNs: endTime }); + if (recent.length > MAX_RECENT_SPANS) recent.shift(); + } + end(endTime, exit); + }; + return span; + }, + }); + + // Untraced: runs inside the stall snapshot path with tracing disabled. + const writeSnapshot = Effect.fnUntraced(function* ( + detectedAt: DateTime.Utc, + detectedAtMs: number, + windowStartNs: bigint, + ) { + if (lastSnapshotAtMs !== undefined && detectedAtMs - lastSnapshotAtMs < cooldownMs) { + return undefined; + } + yield* options.sink.flush.pipe(Effect.ignore); + + const readWindow = Effect.fnUntraced(function* () { + const kept: Array<{ readonly line: string; readonly bytes: number }> = []; + let head = 0; + let keptBytes = 0; + + const pushLine = (line: string) => { + if (line.length === 0) return; + const endTimeNs = extractEndTimeNs(line); + if (endTimeNs === undefined || endTimeNs < windowStartNs) return; + const bytes = Buffer.byteLength(line) + 1; + if (bytes > maxSnapshotBytes) return; + kept.push({ line, bytes }); + keptBytes += bytes; + while (keptBytes > maxSnapshotBytes && head < kept.length) { + keptBytes -= kept[head]!.bytes; + head += 1; + } + if (head > 1024 && head * 2 >= kept.length) { + kept.splice(0, head); + head = 0; + } + }; + + const sourceFiles = [`${options.sink.filePath}.1`, options.sink.filePath]; + for (const sourcePath of sourceFiles) { + yield* fs.stream(sourcePath).pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.runForEachArray((lines) => + Effect.sync(() => { + for (const line of lines) pushLine(line); + }), + ), + Effect.ignore, + ); + } + return head === 0 ? kept : kept.slice(head); + }); + + const statActive = () => + fs.stat(options.sink.filePath).pipe( + Effect.map((info) => ({ ino: Option.getOrUndefined(info.ino), size: info.size })), + Effect.orElseSucceed(() => undefined), + ); + const activeBefore = yield* statActive(); + let retained = yield* readWindow(); + const activeAfter = yield* statActive(); + // Retry once if the active file rotated into `.1` while `.1` was streaming. + const rotatedDuringRead = + activeBefore !== undefined && + activeAfter !== undefined && + (activeBefore.ino !== activeAfter.ino || activeAfter.size < activeBefore.size); + if (rotatedDuringRead) { + retained = yield* readWindow(); + } + if (retained.length === 0) return undefined; + + yield* fs.makeDirectory(options.snapshotDir, { recursive: true }); + const fileName = `${STALL_SNAPSHOT_PREFIX}${DateTime.formatIso(detectedAt).replaceAll(":", "-")}${STALL_SNAPSHOT_SUFFIX}`; + const snapshotPath = path.join(options.snapshotDir, fileName); + const pendingPath = `${snapshotPath}.tmp`; + yield* fs + .writeFileString(pendingPath, `${retained.map((entry) => entry.line).join("\n")}\n`) + .pipe( + Effect.andThen(fs.rename(pendingPath, snapshotPath)), + Effect.tapError(() => fs.remove(pendingPath, { force: true }).pipe(Effect.ignore)), + ); + lastSnapshotAtMs = detectedAtMs; + + const entries = (yield* fs.readDirectory(options.snapshotDir)) + .filter(isStallSnapshotName) + .toSorted(); + const excess = entries.length - maxSnapshotFiles; + for (let index = 0; index < excess; index++) { + yield* fs + .remove(path.join(options.snapshotDir, entries[index]!), { force: true }) + .pipe(Effect.ignore); + } + + return snapshotPath; + }); + + const windowStartNanos = ({ detectedAt, delayMaxMs, windowMs }: StallTraceCaptureInput) => { + const detectedAtMs = DateTime.toEpochMillis(detectedAt); + const detectedAtNs = BigInt(detectedAtMs) * 1_000_000n; + const captureWindowMs = Math.max(windowMs, delayMaxMs + 30_000, minWindowMs); + return { + detectedAtMs, + detectedAtNs, + windowStartNs: detectedAtNs - BigInt(Math.round(captureWindowMs)) * 1_000_000n, + }; + }; + + const attribute: StallTraceCaptureService["attribute"] = (input) => { + const { detectedAtNs, windowStartNs } = windowStartNanos(input); + + const activeSpans = [...open.values()] + .filter( + ({ startTimeNs }) => + detectedAtNs >= startTimeNs && detectedAtNs - startTimeNs <= ACTIVE_SPAN_MAX_AGE_NS, + ) + .map(({ name, startTimeNs }) => ({ + name, + elapsedMs: Number(detectedAtNs - startTimeNs) / 1_000_000, + })) + .toSorted((left, right) => right.elapsedMs - left.elapsedMs) + .slice(0, REPORTED_SPANS) + .map(({ name, elapsedMs }) => `${name} (${Math.round(elapsedMs)}ms)`); + + const slowSpans = recent + .filter(({ endTimeNs }) => endTimeNs >= windowStartNs) + .toSorted((left, right) => right.durationMs - left.durationMs) + .slice(0, REPORTED_SPANS) + .map(({ name, durationMs }) => `${name} (${Math.round(durationMs)}ms)`); + + return { activeSpans, slowSpans }; + }; + + const saveSnapshot: StallTraceCaptureService["saveSnapshot"] = Effect.fnUntraced(function* ( + input: StallTraceCaptureInput, + ) { + const { detectedAtMs, windowStartNs } = windowStartNanos(input); + return yield* snapshotLock + .withPermits(1)(writeSnapshot(input.detectedAt, detectedAtMs, windowStartNs)) + .pipe( + Effect.uninterruptible, + Effect.withTracerEnabled(false), + Effect.catch((cause) => + Effect.logWarning("Failed to preserve event-loop stall trace snapshot", { + snapshotDir: options.snapshotDir, + cause, + }).pipe(Effect.as(undefined)), + ), + ); + }); + + return { + tracer: wrapped, + service: { attribute, saveSnapshot } satisfies StallTraceCaptureService, + }; +}); diff --git a/apps/server/src/persistence/Sqlite.test.ts b/apps/server/src/persistence/Sqlite.test.ts index b413f02d83f6..647d312693f9 100644 --- a/apps/server/src/persistence/Sqlite.test.ts +++ b/apps/server/src/persistence/Sqlite.test.ts @@ -152,6 +152,7 @@ it.effect("upgrades an existing database on a read-write worker connection", () requireWal: false, allowExtension: false, prepareCacheSize: 200, + busyTimeoutMs: 5000, }); }).pipe( Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))), diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index b9029b8746b4..6e005bf4ae2c 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -1,5 +1,4 @@ import * as NodeOS from "node:os"; -import * as NodeSqlite from "node:sqlite"; import * as NodeZlib from "node:zlib"; import { @@ -27,11 +26,13 @@ import * as Path from "effect/Path"; import * as Pull from "effect/Pull"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; +import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { isBareGitConfig, parseOriginUrlFromGitConfig } from "@t3tools/shared/git"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -1585,33 +1586,37 @@ export const make = Effect.gen(function* () { ) { const rootsByThread = new Map>(); const databasePath = path.join(homePath, CODEX_STATE_DATABASE); - return yield* Effect.try({ - try: () => { - const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); - try { - database.exec("PRAGMA busy_timeout = 100"); - const rows = database - .prepare( - `SELECT threads.id AS id, project_roots.path AS path - FROM threads JOIN project_roots ON project_roots.project_id = threads.project_id - ORDER BY threads.rowid DESC, project_roots.position LIMIT ?`, - ) - .all(MAX_CODEX_PROJECT_ROOT_ROWS); - for (const { id, path: root } of rows) { - if (typeof id !== "string" || typeof root !== "string" || root.trim().length === 0) { - continue; - } - const roots = rootsByThread.get(id); - if (roots === undefined) rootsByThread.set(id, [root]); - else roots.push(root); - } - return rootsByThread; - } finally { - database.close(); + if (!(yield* fileSystem.exists(databasePath).pipe(Effect.orElseSucceed(() => false)))) { + return rootsByThread; + } + return yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ readonly id: unknown; readonly path: unknown }>` + SELECT threads.id AS id, project_roots.path AS path + FROM threads JOIN project_roots ON project_roots.project_id = threads.project_id + ORDER BY threads.rowid DESC, project_roots.position LIMIT ${MAX_CODEX_PROJECT_ROOT_ROWS} + `; + for (const { id, path: root } of rows) { + if (typeof id !== "string" || typeof root !== "string" || root.trim().length === 0) { + continue; } - }, - catch: (cause) => new CodexStateReadError({ databasePath, cause }), - }).pipe(Effect.orElseSucceed((): ReadonlyMap> => new Map())); + const roots = rootsByThread.get(id); + if (roots === undefined) rootsByThread.set(id, [root]); + else roots.push(root); + } + return rootsByThread; + }).pipe( + Effect.provide( + NodeSqliteClient.layer({ + filename: databasePath, + readonly: true, + writerWorker: true, + busyTimeoutMs: 100, + }), + ), + Effect.mapError((cause) => new CodexStateReadError({ databasePath, cause })), + Effect.orElseSucceed((): ReadonlyMap> => new Map()), + ); }); // Only chats left in an excluded folder, such as Codex's scratch folder, take their project's root. diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index 1829cf475333..076d4b01cc15 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -824,4 +824,25 @@ describe("readAntigravityUsage", () => { ); }).pipe(Effect.provide(NodeServices.layer)), ); + + it.effect("recovers its reader worker after a corrupt database and still reads later files", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* tempDir; + yield* fs.writeFileString(path.join(dir, "01-corrupt.db"), "not-a-sqlite-file"); + yield* seedDatabase(path.join(dir, "02-valid.db"), (db) => + Effect.gen(function* () { + yield* createTables(db); + yield* db.run("INSERT INTO steps VALUES (?, ?)", [0, stepUsage("after-corrupt")]); + }), + ); + const result = yield* readAntigravityUsage(dir, 0); + assert.strictEqual(result.errors.length, 1); + assert.deepStrictEqual( + records(result).map((record) => record.dedupeKey), + ["antigravity:11:after-corrupt"], + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 62cd3e5831ff..6758318fdae6 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -1,15 +1,14 @@ -// @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's File.Info has no ctime, which the cache fingerprint needs. +// @effect-diagnostics nodeBuiltinImport:off -- Effect's File.Info has no ctime, and worker threads keep SQLite off the event loop. import * as NodeFSP from "node:fs/promises"; +import * as NodeWorkerThreads from "node:worker_threads"; import { pipe } from "effect/Function"; import type { UsageRecord } from "@t3tools/provider-core/server/usage"; -import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; -import * as SqlClient from "effect/sql/SqlClient"; type FieldValue = number | bigint | Uint8Array; type Fields = Map; @@ -255,25 +254,182 @@ class AntigravityDatabaseDecodeError extends Schema.TaggedError { + if (db === undefined) return; + const current = db; + db = undefined; + try { current.exec("COMMIT"); } catch {} + try { current.close(); } catch {} +}; +parentPort.on("message", (request) => { + if (request.type === "shutdown") { + closeDb(); + parentPort.close(); + return; + } + const { id } = request; + try { + if (request.type === "open") { + closeDb(); + const next = new DatabaseSync(request.filename, { readOnly: true, allowExtension: false }); + try { + next.exec("PRAGMA busy_timeout = 100"); + next.exec("BEGIN"); + } catch (error) { + try { next.close(); } catch {} + throw error; + } + db = next; + parentPort.postMessage({ id, rows: [] }); + return; + } + if (request.type === "close") { + closeDb(); + parentPort.postMessage({ id, rows: [] }); + return; + } + if (request.type === "all") { + if (db === undefined) throw new Error("SQLite reader has no open database"); + const rows = db.prepare(request.sql).all(...(request.params ?? [])); + parentPort.postMessage({ id, rows }); + return; + } + throw new Error("Unsupported SQLite reader request"); + } catch (error) { + parentPort.postMessage({ id, error: String(error && error.message ? error.message : error) }); + } +}); +`; + +interface SqliteReaderWorker { + readonly open: (filename: string) => Effect.Effect; + readonly all: ( + filename: string, + sql: string, + params?: ReadonlyArray, + ) => Effect.Effect, AntigravityDatabaseDecodeError>; + readonly close: (filename: string) => Effect.Effect; +} + +interface ActiveWorker { + readonly worker: NodeWorkerThreads.Worker; + readonly pending: Map< + number, + { + readonly resolve: (rows: ReadonlyArray) => void; + readonly reject: (error: Error) => void; + } + >; +} + +const makeSqliteReaderWorker = Effect.gen(function* () { + let current: ActiveWorker | undefined; + let nextId = 0; + + const ensureWorker = (): ActiveWorker => { + if (current !== undefined) return current; + const worker = new NodeWorkerThreads.Worker(sqliteReaderWorkerSource, { eval: true }); + const entry: ActiveWorker = { worker, pending: new Map() }; + const fail = (message: string) => { + if (current === entry) current = undefined; + for (const request of entry.pending.values()) request.reject(new Error(message)); + entry.pending.clear(); + }; + worker.unref(); + worker.on( + "message", + (reply: { + readonly id: number; + readonly rows?: ReadonlyArray; + readonly error?: string; + }) => { + const request = entry.pending.get(reply.id); + if (request === undefined) return; + entry.pending.delete(reply.id); + if (entry.pending.size === 0) worker.unref(); + if (reply.error !== undefined) request.reject(new Error(reply.error)); + else request.resolve(reply.rows ?? []); + }, + ); + worker.on("error", (cause) => { + fail(`Antigravity SQLite reader failed: ${cause.message}`); + void worker.terminate(); + }); + worker.on("exit", (code) => { + fail(`Antigravity SQLite reader exited with code ${code}`); + }); + current = entry; + return entry; + }; + + yield* Effect.addFinalizer(() => + Effect.promise(async () => { + const active = current; + current = undefined; + if (active === undefined) return; + try { + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin. + active.worker.postMessage({ type: "shutdown" }); + } catch {} + await active.worker.terminate(); + }), + ); + + const send = (filename: string, payload: Record) => + Effect.tryPromise({ + try: () => + new Promise>((resolve, reject) => { + const active = ensureWorker(); + const id = ++nextId; + active.pending.set(id, { resolve, reject }); + if (active.pending.size === 1) active.worker.ref(); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node workers do not accept a target origin. + active.worker.postMessage({ id, ...payload }); + }), + catch: (cause) => new AntigravityDatabaseDecodeError({ path: filename, cause }), + }); + + return { + open: (filename) => send(filename, { type: "open", filename }).pipe(Effect.asVoid), + all: (filename: string, sql: string, params: ReadonlyArray = []) => + send(filename, { type: "all", sql, params }) as Effect.Effect< + ReadonlyArray, + AntigravityDatabaseDecodeError + >, + close: (filename) => + Effect.suspend(() => + current === undefined + ? Effect.void + : send(filename, { type: "close" }).pipe(Effect.asVoid, Effect.ignore), + ), + } satisfies SqliteReaderWorker; +}); + const readDatabase = Effect.fn("readDatabase")(function* ( + reader: SqliteReaderWorker, path: string, sessionId: string, fallbackTimestamp: number, ) { - const sql = yield* SqlClient.SqlClient; const decode = (evaluate: () => A) => Effect.try({ try: evaluate, catch: (cause) => new AntigravityDatabaseDecodeError({ path, cause }), }); - yield* sql.unsafe("PRAGMA busy_timeout = 100"); + yield* reader.open(path); return yield* Effect.gen(function* () { const tables = new Set( - (yield* sql.unsafe<{ readonly name: unknown }>( + (yield* reader.all<{ readonly name: unknown }>( + path, "SELECT name FROM sqlite_master WHERE type = 'table'", )).map((row) => row.name), ); @@ -288,13 +444,11 @@ const readDatabase = Effect.fn("readDatabase")(function* ( const entries: Array<{ idx: number; entry: Metadata }> = []; let after = -Infinity; while (true) { - const rows = yield* sql - .unsafe<{ - readonly row_id: number; - readonly idx: unknown; - readonly data: unknown; - }>(query, [after, pageRows]) - .pipe(Effect.withTracerEnabled(false)); + const rows = yield* reader.all<{ + readonly row_id: number; + readonly idx: unknown; + readonly data: unknown; + }>(path, query, [after, pageRows]); for (const row of rows) { // Filter outside SQL to bound scans to one page, including rows without metadata. if (step && row.data === null) continue; @@ -319,7 +473,8 @@ const readDatabase = Effect.fn("readDatabase")(function* ( : []; let trajectoryTimestamp: number | null = null; if (tables.has("trajectory_metadata_blob")) { - for (const row of yield* sql.unsafe<{ readonly data: unknown }>( + for (const row of yield* reader.all<{ readonly data: unknown }>( + path, "SELECT data FROM trajectory_metadata_blob", )) { trajectoryTimestamp ??= yield* decode(() => @@ -351,7 +506,7 @@ const readDatabase = Effect.fn("readDatabase")(function* ( models, }; }); - }).pipe(sql.withTransaction); + }).pipe(Effect.ensuring(reader.close(path))); }); function usageCandidates( @@ -511,6 +666,7 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* } }; const visited = new Set(); + const reader = yield* makeSqliteReaderWorker; const readFile = Effect.fn("readAntigravityUsage.readFile")(function* (path: string) { const canonical = yield* fileSystem.realPath(path); if (visited.has(canonical)) return null; @@ -527,9 +683,7 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* const fingerprint = `${part}/${wal._tag === "Some" ? wal.value.part : "-"}`; const cached = cache?.get(canonical); if (cached?.fingerprint === fingerprint) return cached.data; - const data = yield* readDatabase(path, pathService.basename(path, ".db"), stat.mtimeMs).pipe( - Effect.provide(NodeSqliteClient.layer({ filename: path, readonly: true })), - ); + const data = yield* readDatabase(reader, path, pathService.basename(path, ".db"), stat.mtimeMs); cache?.set(canonical, { fingerprint, data }); return data; }); @@ -608,4 +762,4 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* } } return { files, errors }; -}); +}, Effect.scoped); diff --git a/packages/provider-opencode/src/server/usage.test.ts b/packages/provider-opencode/src/server/usage.test.ts index 882eaea613a4..8bde96afbefd 100644 --- a/packages/provider-opencode/src/server/usage.test.ts +++ b/packages/provider-opencode/src/server/usage.test.ts @@ -22,25 +22,36 @@ import { } from "./usage.fixture.ts"; import { openCodeUsageReader, readOpenCodeUsage } from "./usage.ts"; -const readerWorkers = vi.hoisted(() => ({ started: 0, enabled: false })); +const workerSpy = vi.hoisted(() => ({ + started: 0, + workerData: [] as Array, + onStatement: undefined as ((sql: string) => void) | undefined, + onRows: undefined as ((rows: ReadonlyArray>) => void) | undefined, +})); -// Statement spies only see the main thread, so reader workers fail to start unless a test enables them. vi.mock("node:worker_threads", async (importOriginal) => { const actual = await importOriginal(); - class ReaderWorker extends actual.Worker { + class RecordedWorker extends actual.Worker { constructor(...args: ConstructorParameters) { - super( - ...((readerWorkers.enabled - ? args - : [ - "throw new Error('reader workers disabled');", - { eval: true }, - ]) as ConstructorParameters), - ); - readerWorkers.started++; + super(...args); + workerSpy.started++; + workerSpy.workerData.push(args[1]?.workerData); + this.prependListener("message", (reply: { readonly rows?: unknown }) => { + if (Array.isArray(reply?.rows)) { + workerSpy.onRows?.(reply.rows as ReadonlyArray>); + } + }); + } + override postMessage(...args: Parameters) { + const value = args[0]; + if (typeof value === "object" && value !== null && "sql" in value) { + const sql = (value as { readonly sql?: unknown }).sql; + if (typeof sql === "string") workerSpy.onStatement?.(sql); + } + return super.postMessage(...args); } } - return { ...actual, Worker: ReaderWorker }; + return { ...actual, Worker: RecordedWorker }; }); const openDatabase = (filename: string) => @@ -148,14 +159,9 @@ describe("readOpenCodeUsage", () => { ); let changed = false; let largestRawResult = 0; - const originalAll = NodeSqlite.StatementSync.prototype.all; yield* Effect.acquireRelease( - Effect.sync(() => - vi.spyOn(NodeSqlite.StatementSync.prototype, "all").mockImplementation(function ( - this: NodeSqlite.StatementSync, - ...params - ) { - const rows = originalAll.apply(this, params); + Effect.sync(() => { + workerSpy.onRows = (rows) => { const rawSize = rows.reduce( (size, row) => size + (typeof row.data === "string" ? row.data.length : 0), 0, @@ -167,10 +173,12 @@ describe("readOpenCodeUsage", () => { .prepare("UPDATE message SET data = ? WHERE id = ?") .run(JSON.stringify({ ...message, tokens: { input: 900, output: 20 } }), "msg-129"); } - return rows; + }; + }), + () => + Effect.sync(() => { + workerSpy.onRows = undefined; }), - ), - (spy) => Effect.sync(() => spy.mockRestore()), ); const result = yield* readOpenCodeUsage(dir, sinceMs); assert.isFalse(result.error); @@ -223,19 +231,28 @@ describe("readOpenCodeUsage", () => { } let statements = 0; let bodyReads = 0; + let mainThreadReads = 0; + const workersBefore = workerSpy.started; const originalAll = NodeSqlite.StatementSync.prototype.all; yield* Effect.acquireRelease( - Effect.sync(() => - vi.spyOn(NodeSqlite.StatementSync.prototype, "all").mockImplementation(function ( + Effect.sync(() => { + workerSpy.onStatement = (sql) => { + statements++; + if (sql.includes("data ->")) bodyReads++; + }; + return vi.spyOn(NodeSqlite.StatementSync.prototype, "all").mockImplementation(function ( this: NodeSqlite.StatementSync, ...params ) { - statements++; - if (this.sourceSQL.includes("data ->")) bodyReads++; + mainThreadReads++; return originalAll.apply(this, params); + }); + }), + (spy) => + Effect.sync(() => { + workerSpy.onStatement = undefined; + spy.mockRestore(); }), - ), - (spy) => Effect.sync(() => spy.mockRestore()), ); const result = yield* readOpenCodeUsage(dir, sinceMs); assert.isFalse(result.error); @@ -244,6 +261,9 @@ describe("readOpenCodeUsage", () => { ["opencode:a", "opencode:b", "opencode:c"], ); assert.isBelow(statements, 10); + // Even a non-WAL database runs its open and scan off the event loop. + assert.isAbove(workerSpy.started, workersBefore); + assert.strictEqual(mainThreadReads, 0); bodyReads = 0; const repeated = yield* readOpenCodeUsage(dir, sinceMs); @@ -316,13 +336,7 @@ describe("readOpenCodeUsage", () => { const legacy = path.join(dir, "storage", "message", message.sessionID); yield* fileSystem.makeDirectory(legacy, { recursive: true }); yield* fileSystem.writeFileString(path.join(legacy, "msg-1.json"), JSON.stringify(message)); - yield* Effect.acquireRelease( - Effect.sync(() => { - readerWorkers.enabled = true; - readerWorkers.started = 0; - }), - () => Effect.sync(() => (readerWorkers.enabled = false)), - ); + const workersBefore = workerSpy.started; let mainThreadBodyReads = 0; const originalAll = NodeSqlite.StatementSync.prototype.all; yield* Effect.acquireRelease( @@ -362,7 +376,15 @@ describe("readOpenCodeUsage", () => { ); assert.isAbove(Number((yield* fileSystem.stat(path.join(dir, "opencode.db-wal"))).size), 0); // A large database must not be read on the server's event loop. - assert.isAbove(readerWorkers.started, 0); + assert.isAbove(workerSpy.started, workersBefore); + assert.deepInclude(workerSpy.workerData.slice(workersBefore), { + filename: path.join(dir, "opencode.db"), + readOnly: true, + requireWal: false, + allowExtension: false, + prepareCacheSize: 200, + busyTimeoutMs: 100, + }); assert.strictEqual(mainThreadBodyReads, 0); }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/packages/provider-opencode/src/server/usage.ts b/packages/provider-opencode/src/server/usage.ts index 9878742ce882..d5beba6611ca 100644 --- a/packages/provider-opencode/src/server/usage.ts +++ b/packages/provider-opencode/src/server/usage.ts @@ -196,8 +196,6 @@ export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* ( }); yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - // Fail promptly on live-writer locks instead of stalling the server. - yield* sql.unsafe("PRAGMA busy_timeout = 100"); const tables = new Set( (yield* sql.unsafe<{ readonly name: unknown }>( "SELECT name FROM sqlite_master WHERE type = 'table'", @@ -374,10 +372,15 @@ export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* ( } }).pipe( (read) => Effect.flatMap(SqlClient.SqlClient, (sql) => sql.withTransaction(read)), - // Run the scan on a reader worker so large databases do not block the server's event loop. - NodeSqliteClient.readOnly, + // Run open, queries, and close off the event loop for both WAL and non-WAL databases, + // failing promptly on live-writer locks instead of stalling the server. Effect.provide( - NodeSqliteClient.layer({ filename: file.path, readonly: true, readerWorker: true }), + NodeSqliteClient.layer({ + filename: file.path, + readonly: true, + writerWorker: true, + busyTimeoutMs: 100, + }), ), Effect.catchTags({ SqlError: () => { diff --git a/packages/provider-opencode/src/server/usageLimits.ts b/packages/provider-opencode/src/server/usageLimits.ts index 03488e515a79..f23c2eb61788 100644 --- a/packages/provider-opencode/src/server/usageLimits.ts +++ b/packages/provider-opencode/src/server/usageLimits.ts @@ -1,5 +1,3 @@ -import * as NodeSqlite from "node:sqlite"; - import type { ServerProviderUsageWindow } from "@t3tools/contracts"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; @@ -8,6 +6,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; import * as Hex from "effect/encoding/Hex"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; @@ -19,6 +18,7 @@ import { makeUsageLimits, } from "@t3tools/provider-core/server/usageLimits"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknown) }); const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String }); @@ -52,36 +52,58 @@ class OpenCodeCredentialReadError extends Schema.TaggedError - Effect.try({ - try: () => { - const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); - try { - database.exec("PRAGMA busy_timeout = 100"); - const row = database - .prepare( - `SELECT value FROM credential - WHERE integration_id = ? AND active IS NOT 0 - ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`, - ) - .get(integrationId); - const stored = - typeof row?.value === "string" - ? Option.getOrUndefined(decodeStoredKey(row.value)) - : undefined; - const server = stored?.metadata?.server; - if (typeof server === "string") { - const url = new URL(server); - if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console") - return undefined; - } - return stored?.key.trim(); - } finally { - database.close(); +const isConsoleServerUrl = (server: string): boolean => { + try { + const url = new URL(server); + return `${url.origin}${url.pathname.replace(/\/+$/, "")}` === "https://opencode.ai/console"; + } catch { + return false; + } +}; + +const readStoredApiKeys = Effect.fn("readStoredApiKeys")(function* ( + databasePath: string, + integrationIds: ReadonlyArray<"opencode" | "opencode-go">, +) { + const fs = yield* FileSystem.FileSystem; + if (!(yield* fs.exists(databasePath).pipe(Effect.orElseSucceed(() => false)))) { + return []; + } + return yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const keys: Array = []; + for (const integrationId of integrationIds) { + const rows = yield* sql<{ readonly value: unknown }>` + SELECT value FROM credential + WHERE integration_id = ${integrationId} AND active IS NOT 0 + ORDER BY active DESC, time_created DESC, id DESC LIMIT 1 + `; + const row = rows[0]; + const stored = + typeof row?.value === "string" + ? Option.getOrUndefined(decodeStoredKey(row.value)) + : undefined; + const server = stored?.metadata?.server; + if (typeof server === "string" && !isConsoleServerUrl(server)) { + keys.push(undefined); + continue; } - }, - catch: (cause) => new OpenCodeCredentialReadError({ databasePath, cause }), - }).pipe(Effect.orElseSucceed(() => undefined)); + keys.push(stored?.key.trim()); + } + return keys; + }).pipe( + Effect.provide( + NodeSqliteClient.layer({ + filename: databasePath, + readonly: true, + writerWorker: true, + busyTimeoutMs: 100, + }), + ), + Effect.mapError((cause) => new OpenCodeCredentialReadError({ databasePath, cause })), + Effect.orElseSucceed((): Array => []), + ); +}); /** External OpenCode servers own their credentials; never read the host's account for them. */ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: { @@ -124,11 +146,8 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")( const storedKeys = env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:" ? [] - : [ - yield* readStoredApiKey(databasePath, "opencode"), - // OpenCode 2 imports auth.json once, so a replaced Go key only exists here. - yield* readStoredApiKey(databasePath, "opencode-go"), - ]; + : // OpenCode 2 imports auth.json once, so a replaced Go key only exists in opencode-go. + yield* readStoredApiKeys(databasePath, ["opencode", "opencode-go"]); const keys = [...new Set([...storedKeys, goKey].filter((key): key is string => Boolean(key)))]; let apiKey = keys[0]; if (!apiKey) return unsupported; diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 71a9897b841f..a2be0004832c 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -337,6 +337,34 @@ it.effect("commits on the worker writer after a returning write timed out on a l }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.effect("applies busyTimeoutMs to writer and reader workers at startup", () => + Effect.gen(function* () { + const { filename, other } = yield* makeTempDatabase; + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + assert.deepEqual(yield* sql`PRAGMA busy_timeout`.values, [[123]]); + assert.deepEqual(yield* sql`PRAGMA busy_timeout`.values.pipe(SqliteClient.readOnly), [[123]]); + }).pipe( + Effect.provide( + SqliteClient.layer({ + filename, + writerWorker: true, + readerWorker: true, + busyTimeoutMs: 123, + }), + ), + ); + + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* Effect.sync(() => other.exec("BEGIN IMMEDIATE")); + const error = yield* sql`UPDATE counters SET value = 1 WHERE id = 1`.pipe(Effect.flip); + assert.equal(error.reason._tag, "LockTimeoutError"); + yield* Effect.sync(() => other.exec("COMMIT")); + }).pipe(Effect.provide(SqliteClient.layer({ filename, writerWorker: true, busyTimeoutMs: 0 }))); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("keeps another connection from committing between a transaction's read and write", () => Effect.gen(function* () { const { filename, other } = yield* makeTempDatabase; diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index bb00de745981..ca05dc49ecfe 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -37,6 +37,8 @@ export interface SqliteClientConfig { readonly readerWorker?: boolean | undefined; /** Runs the writer and WAL checkpoints off the event loop. Ignored for in-memory databases. */ readonly writerWorker?: boolean | undefined; + /** Worker startup `PRAGMA busy_timeout` in milliseconds (default 5000). */ + readonly busyTimeoutMs?: number | undefined; } // SqlClient masks transaction acquisition, so readOnly carries the caller's interruption policy. @@ -213,7 +215,7 @@ try { readOnly: workerData.readOnly, allowExtension: workerData.allowExtension, }); - next.exec("PRAGMA busy_timeout = 5000;"); + next.exec("PRAGMA busy_timeout = " + workerData.busyTimeoutMs + ";"); // Reads the header, so a file that is not a database fails here rather than on first use. const mode = String(next.prepare("PRAGMA journal_mode").get().journal_mode).toLowerCase(); // Without WAL a reader's shared lock blocks the writer's commits, so refuse. @@ -362,6 +364,7 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { readonly filename: string; readonly role: "reader" | "writer"; readonly readOnly: boolean; + readonly busyTimeoutMs: number; readonly onReply?: () => void; }) { const label = options.role === "reader" ? "Database reader" : "Database writer"; @@ -388,6 +391,7 @@ const makeWorkerConnection = Effect.fnUntraced(function* (options: { requireWal: options.role === "reader", allowExtension: false, prepareCacheSize: 200, + busyTimeoutMs: options.busyTimeoutMs, }, }); let announce: (startup: WorkerStartup) => void = () => {}; @@ -614,8 +618,17 @@ 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, + busyTimeoutMs: number, + pool: { unavailable: boolean }, +) { + const acquire = yield* makeWorkerConnection({ + filename, + role: "reader", + readOnly: true, + busyTimeoutMs, + }); const scope = yield* Effect.scope; const context = yield* Effect.context(); @@ -926,6 +939,10 @@ const make = Effect.fn("makeWithDatabase")(function* ( }); }); + const busyTimeoutMs = + options.busyTimeoutMs !== undefined && Number.isFinite(options.busyTimeoutMs) + ? Math.max(0, Math.floor(options.busyTimeoutMs)) + : 5000; const semaphore = yield* Semaphore.make(1); const writerWorker = options.writerWorker === true && isFileDatabase; let checkpointAfterWrite: (() => void) | undefined; @@ -934,6 +951,7 @@ const make = Effect.fn("makeWithDatabase")(function* ( filename: options.filename, role: "writer", readOnly: options.readonly ?? false, + busyTimeoutMs, onReply: () => checkpointAfterWrite?.(), }) : Effect.succeed(yield* makeConnection); @@ -955,7 +973,10 @@ const make = Effect.fn("makeWithDatabase")(function* ( options.readerWorker && isFileDatabase ? yield* Effect.forEach(Array.from({ length: READER_POOL_SIZE }), () => Effect.map( - Effect.all([makeReader(options.filename, readerPool), Semaphore.make(1)]), + Effect.all([ + makeReader(options.filename, busyTimeoutMs, readerPool), + Semaphore.make(1), + ]), ([acquire, lock]) => ({ acquire, lock, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 4ec3f6a74b81..ea4a62d4a537 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -1533,6 +1533,37 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { }).pipe(Effect.provideService(CommandResolutionCache, new Map())), ); + it.effect("awaits and deduplicates concurrent asynchronous Xcode git lookups", () => + Effect.gen(function* () { + let releaseLookup: ((value: string | undefined) => void) | undefined; + let calls = 0; + const lookupPromise = new Promise((resolve) => { + releaseLookup = resolve; + }); + const files = new Set(["/usr/bin/git", XCODE_GIT]); + const resolve = resolveSpawnCommand("git", ["status"], { + env: { PATH: "/fake/bin" }, + }).pipe( + Effect.map((resolved) => resolved.command), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(SpawnExecutableResolution, (command) => + command === "git" ? "/usr/bin/git" : files.has(command) ? command : undefined, + ), + Effect.provideService(XcodeGitLocation, () => { + calls += 1; + return lookupPromise; + }), + ); + const first = yield* Effect.forkChild(resolve); + const second = yield* Effect.forkChild(resolve); + yield* Effect.yieldNow; + releaseLookup!(XCODE_GIT); + expect(yield* Fiber.join(first)).toBe(XCODE_GIT); + expect(yield* Fiber.join(second)).toBe(XCODE_GIT); + expect(calls).toBe(1); + }).pipe(Effect.provideService(CommandResolutionCache, new Map())), + ); + it.effect("keeps git when PATH has another git or the host is not macOS", () => Effect.gen(function* () { const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT }); diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index c23492c4863c..9101651eba86 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -1024,23 +1024,41 @@ export function npmShimExecutable( return isFile(executable) ? executable : undefined; } -export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined; +export type XcodeGitLocator = ( + env: NodeJS.ProcessEnv, +) => string | undefined | Promise; // xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does. -function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined { - try { - const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], { - encoding: "utf8", - env, - timeout: 5_000, - stdio: ["ignore", "pipe", "ignore"], - }).trim(); - return NodePath.isAbsolute(located) ? located : undefined; - } catch { - return undefined; - } +function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): Promise { + return new Promise((resolve) => { + try { + NodeChildProcess.execFile( + "/usr/bin/xcrun", + ["--find", "git"], + { + encoding: "utf8", + env, + timeout: 5_000, + windowsHide: true, + }, + (error, stdout) => { + if (error) { + resolve(undefined); + return; + } + const located = stdout.trim(); + resolve(NodePath.isAbsolute(located) ? located : undefined); + }, + ); + } catch { + resolve(undefined); + } + }); } +// Deduplicate concurrent cold/expired xcrun lookups so N simultaneous git spawns launch one xcrun. +const inFlightXcodeGitLookups = new Map>(); + export const XcodeGitLocation = Context.Reference( "@t3tools/shared/shell/XcodeGitLocation", { defaultValue: () => locateXcodeGitWithXcrun }, @@ -1083,7 +1101,23 @@ const resolveMacosGit = Effect.fnUntraced(function* ( } } const pathGit = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); - const located = pathGit === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const located = + pathGit === MACOS_GIT_SHIM + ? yield* Effect.promise(() => { + const existing = inFlightXcodeGitLookups.get(cacheKey); + if (existing !== undefined) return existing; + const lookup = Promise.resolve() + .then(() => locateXcodeGit(env)) + .catch(() => undefined) + .finally(() => { + if (inFlightXcodeGitLookups.get(cacheKey) === lookup) { + inFlightXcodeGitLookups.delete(cacheKey); + } + }); + inFlightXcodeGitLookups.set(cacheKey, lookup); + return lookup; + }) + : undefined; const realGit = located !== undefined && (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined