diff --git a/apps/server/src/cli/auth.ts b/apps/server/src/cli/auth.ts index 1533cdda7d..d688c9dd61 100644 --- a/apps/server/src/cli/auth.ts +++ b/apps/server/src/cli/auth.ts @@ -210,7 +210,16 @@ const pairingUrlCommand = Command.make("url", { ? flags : { ...flags, baseDir: Option.some(worktreeBaseDir) }; const config = yield* resolveCliAuthConfig(resolvedFlags, logLevel); - const live = yield* findLiveServerRuntimeState(config); + // Quieted here rather than only around the issuing layer below: probing + // reads both state directories, and a corrupt file in the one *not* in + // use logs a Warn to stdout — ahead of the payload, breaking `--json` + // for any consumer piping it. The warning is about a file the command + // then ignores, so under --json it is noise either way. + const live = yield* findLiveServerRuntimeState(config).pipe( + Effect.provide( + Layer.succeed(References.MinimumLogLevel, flags.json ? "Error" : config.logLevel), + ), + ); if (Option.isNone(live)) { return yield* new NoRunningServerError({ baseDir: config.baseDir }); diff --git a/apps/server/src/serverRuntimeState.test.ts b/apps/server/src/serverRuntimeState.test.ts index 8450ed7832..db44018d7f 100644 --- a/apps/server/src/serverRuntimeState.test.ts +++ b/apps/server/src/serverRuntimeState.test.ts @@ -70,6 +70,30 @@ describe("serverRuntimeState", () => { ); }), ); + + // `process.kill` reads non-positive pids as signal-group targets rather + // than process lookups — 0 is the caller's own group, -1 every permitted + // process — so neither throws, and a probe that only catches would call + // both "live" no matter what wrote the file. + for (const pid of [0, -1]) { + it.effect(`reports pid ${String(pid)} as dead rather than signalling a group`, () => + Effect.gen(function* () { + assert.isFalse( + yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(pid)), + ); + }), + ); + } + + // Out of range for a pid: process.kill throws a TypeError with no errno, + // which the EPERM check must not assume the shape of. + it.effect("reports an out-of-range pid as dead", () => + Effect.gen(function* () { + assert.isFalse( + yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(2 ** 40)), + ); + }), + ); }); it.effect("treats a missing runtime state file as absent", () => diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts index b4d75bad7a..69a98f0777 100644 --- a/apps/server/src/serverRuntimeState.ts +++ b/apps/server/src/serverRuntimeState.ts @@ -10,7 +10,11 @@ import { formatHostForUrl, isWildcardHost } from "./startupAccess.ts"; export const PersistedServerRuntimeState = Schema.Struct({ version: Schema.Literal(1), - pid: Schema.Int, + /** + * Positive: `process.kill` reads 0 and negatives as signal-group targets, so + * a liveness probe on one reports "live" for a process that never existed. + */ + pid: Schema.Int.check(Schema.isGreaterThan(0)), host: Schema.optional(Schema.String), port: Schema.Int, origin: Schema.String, @@ -107,6 +111,13 @@ export const clearPersistedServerRuntimeState = (path: string) => ); }); +/** + * `process.kill` rejects an out-of-range pid with a TypeError rather than an + * errno, so the catch below cannot assume either shape. + */ +const isErrnoException = (cause: unknown): cause is NodeJS.ErrnoException => + typeof cause === "object" && cause !== null && "code" in cause; + /** * Whether the process that wrote a runtime-state file is still alive. * @@ -123,12 +134,20 @@ export const isPersistedServerRuntimeStateLive = ( state: PersistedServerRuntimeState, ): Effect.Effect => Effect.sync(() => { + // `process.kill` reads non-positive pids as signal-group targets rather + // than process lookups: 0 signals the caller's own group and -1 every + // permitted process, so neither throws and both would report "live" + // unconditionally. A server never records one; a corrupt or truncated file + // can, and that file would then be believed forever. + if (!Number.isSafeInteger(state.pid) || state.pid <= 0) { + return false; + } try { process.kill(state.pid, 0); return true; } catch (cause) { // EPERM means the process exists but belongs to another user. - return (cause as NodeJS.ErrnoException).code === "EPERM"; + return isErrnoException(cause) && cause.code === "EPERM"; } }); diff --git a/scripts/dev-seed.ts b/scripts/dev-seed.ts index e6e8c2d146..bab89506aa 100644 --- a/scripts/dev-seed.ts +++ b/scripts/dev-seed.ts @@ -28,7 +28,13 @@ const MAX_THREAD_LIMIT = 32_766; class DevSeedTargetError extends Schema.TaggedErrorClass()( "DevSeedTargetError", { - reason: Schema.Literals(["shared-home", "missing-target", "not-a-worktree", "server-running"]), + reason: Schema.Literals([ + "shared-home", + "missing-target", + "not-a-worktree", + "server-running", + "same-source", + ]), detail: Schema.String, }, ) { @@ -56,6 +62,13 @@ class DevSeedTargetError extends Schema.TaggedErrorClass()( "which leaves the running server's in-memory read model describing rows that no longer exist.", "Stop it, run the seed, then start it again.", ].join("\n"); + case "same-source": + return [ + `Refusing to seed ${this.detail} from itself.`, + "The copy would restore what the delete removed, but the event log and the", + "projector cursors are cleared either way — so the directory loses its history", + "and keeps only whatever the thread and activity caps selected.", + ].join("\n"); } } } @@ -167,13 +180,21 @@ const devSeedCli = Command.make("dev-seed", { // The whole point is to keep dev data off the real home; overwriting it // here would be the exact accident this command exists to avoid. - const [canonicalTarget, canonicalShared] = yield* Effect.all([ + const [canonicalTarget, canonicalSource, canonicalShared] = yield* Effect.all([ fileSystem.realPath(targetBaseDir).pipe(Effect.orElseSucceed(() => targetBaseDir)), + fileSystem.realPath(sourceBaseDir).pipe(Effect.orElseSucceed(() => sourceBaseDir)), fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)), ]); if (canonicalTarget === canonicalShared) { return yield* new DevSeedTargetError({ reason: "shared-home", detail: targetBaseDir }); } + // Seeding a directory from itself is not the data loss it looks like — + // the source reads a pre-transaction snapshot, so the copy puts the rows + // back. What does not come back is the event log and the cursors, and + // anything outside the caps. Nobody means to ask for that. + if (canonicalTarget === canonicalSource) { + return yield* new DevSeedTargetError({ reason: "same-source", detail: targetBaseDir }); + } const targetDbPath = stateDbPath(path, targetBaseDir); if (!(yield* fileSystem.exists(targetDbPath))) { diff --git a/scripts/lib/dev-seed.test.ts b/scripts/lib/dev-seed.test.ts index a85fd42137..4acc5d9f8e 100644 --- a/scripts/lib/dev-seed.test.ts +++ b/scripts/lib/dev-seed.test.ts @@ -101,8 +101,10 @@ function makeSource( } // The newest thread is left mid-turn, as a copy taken while an agent is // working would be: a running turn with no completion, and a message still - // streaming into it. + // streaming into it. The one before it is left "pending" — a user message + // accepted but whose provider turn never started. const midFlight = index === threadCount - 1; + const queued = index === threadCount - 2; database .prepare( `INSERT INTO projection_turns (thread_id, turn_id, state, requested_at, completed_at, checkpoint_files_json) @@ -111,9 +113,9 @@ function makeSource( .run( threadId, `turn-${threadId}`, - midFlight ? "running" : "completed", + midFlight ? "running" : queued ? "pending" : "completed", at, - midFlight ? null : at, + midFlight || queued ? null : at, ); database .prepare(`INSERT INTO projection_thread_sessions VALUES (?,'running','claude',?,'boom',?)`) @@ -297,10 +299,11 @@ describe("seedDevDatabase", () => { }); }); - // A copied running turn has no agent left to finish it. The session override - // alone does not cover this: the turn is read independently, and an unsettled - // one keeps the thread spinning and its timeline unfoldable forever. - it("settles turns copied mid-flight", () => { + // A copied turn has no agent left to finish it, whether it was already + // running or still queued behind a "pending" row. The session override alone + // does not cover either: the turn is read independently, and an unsettled one + // keeps the thread spinning and its timeline unfoldable forever. + it("settles turns copied before they finished", () => { withDatabases(({ source, target }) => { seedDevDatabase({ sourceDbPath: source, @@ -314,9 +317,11 @@ describe("seedDevDatabase", () => { target, "SELECT state, completed_at FROM projection_turns", ); + // The fixture puts one running turn and one pending turn in this range. assert.isAbove(turns.length, 0); for (const turn of turns) { assert.notEqual(turn.state, "running"); + assert.notEqual(turn.state, "pending"); assert.isNotNull(turn.completed_at); } }); diff --git a/scripts/lib/dev-seed.ts b/scripts/lib/dev-seed.ts index bd48990be0..26e9990663 100644 --- a/scripts/lib/dev-seed.ts +++ b/scripts/lib/dev-seed.ts @@ -216,6 +216,16 @@ function copyRows(input: { return { copied, skipped }; } +/** + * Turn states that describe work an agent still owes: "running" for a turn in + * flight, "pending" for one whose user message was accepted but whose provider + * turn had not started yet (`insertPendingProjectionTurn` in + * apps/server/src/persistence/Layers/ProjectionTurns.ts). Neither can make + * progress in a copy, and only the thread's own next message would clear a + * pending one. + */ +const UNSETTLED_TURN_STATES = ["running", "pending"] as const; + /** * Settles turns copied mid-flight, matching what the server does to a turn * whose session leaves "running": `settledTurnStateForSessionStatus` in @@ -223,26 +233,28 @@ function copyRows(input: { * status the sessions are copied with to "interrupted". * * An UPDATE rather than a copy override, because only the rows that were - * actually running should change; the rest keep their real recorded state. + * actually unsettled should change; the rest keep their real recorded state. */ -function settleRunningTurns( +function settleUnfinishedTurns( target: NodeSqlite.DatabaseSync, threadIds: ReadonlyArray, ): void { if (threadIds.length === 0 || !hasColumn(target, "projection_turns", "state")) { return; } - // completed_at is what marks a turn settled alongside its state; a running - // turn has none, and leaving it null keeps the thread unsettled regardless. + // completed_at is what marks a turn settled alongside its state; an + // unfinished turn has none, and leaving it null keeps the thread unsettled + // regardless of the state written here. const setCompletedAt = hasColumn(target, "projection_turns", "completed_at") ? `, completed_at = COALESCE(completed_at, requested_at)` : ""; target .prepare( `UPDATE projection_turns SET state = 'interrupted'${setCompletedAt} - WHERE state = 'running' AND thread_id IN (${placeholders(threadIds.length)})`, + WHERE state IN (${placeholders(UNSETTLED_TURN_STATES.length)}) + AND thread_id IN (${placeholders(threadIds.length)})`, ) - .run(...threadIds); + .run(...UNSETTLED_TURN_STATES, ...threadIds); } export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary { @@ -267,6 +279,22 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary { ); } + // The source is normally the *live* installed app's database — only the + // target is guarded against a running server, because reading is harmless. + // Reading it across a dozen separate implicit transactions is not: the app + // can delete a project between the query that picks it up and the copy that + // reads its row, leaving a copied thread whose project no longer exists (no + // foreign keys are declared, so nothing catches it). One deferred read + // transaction pins every query below to a single snapshot. + let sourceTransactionOpen = false; + try { + source.exec("BEGIN"); + sourceTransactionOpen = true; + } catch { + // A concurrent writer can leave the connection unable to start one. The + // copy is still worth doing — it just loses snapshot isolation. + } + try { // Threads the user actually touched most recently. Mirrors the sidebar's own // ordering (packages/client-runtime/src/state/threadSort.ts). Both recency @@ -376,11 +404,11 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary { }), ); // A thread copied mid-turn has no agent to finish it. The session status is - // forced to "stopped" below, but the turn is read independently: a - // `state = 'running'` turn keeps the thread unsettled and unfoldable - // forever (deriveUnsettledTurnId in MessagesTimeline.logic.ts). Interrupted - // is what the server itself settles an abandoned turn to. - settleRunningTurns(target, threadIds); + // forced to "stopped" below, but the turn is read independently: an + // unfinished turn keeps the thread unsettled and unfoldable forever + // (deriveUnsettledTurnId in MessagesTimeline.logic.ts). Interrupted is what + // the server itself settles an abandoned turn to. + settleUnfinishedTurns(target, threadIds); const messages = record( copyRows({ source, @@ -475,6 +503,15 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary { ? cause : new DevSeedError(`could not seed the dev database: ${String(cause)}`); } finally { + if (sourceTransactionOpen) { + try { + // Read-only, so there is nothing to commit; end it before closing so + // the snapshot is released explicitly rather than by teardown. + source.exec("ROLLBACK"); + } catch { + // Already ended, which is equally fine for a read-only transaction. + } + } source.close(); target.close(); } diff --git a/scripts/lib/server-runtime-probe.test.ts b/scripts/lib/server-runtime-probe.test.ts index 18981daeab..49be5108bf 100644 --- a/scripts/lib/server-runtime-probe.test.ts +++ b/scripts/lib/server-runtime-probe.test.ts @@ -86,6 +86,20 @@ describe("findRunningServerPid", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + // `process.kill` reads these as signal-group targets, not process lookups, so + // neither throws — a naive probe calls both "live" and blocks seeding forever + // on a file no server ever wrote. + for (const pid of [0, -1]) { + it.effect(`ignores a state file recording pid ${String(pid)}`, () => + Effect.gen(function* () { + const baseDir = yield* makeBaseDir(); + yield* writeRuntimeState({ baseDir, stateDir: "dev", contents: runtimeStateJson(pid) }); + + assert.isTrue(Option.isNone(yield* findRunningServerPid(baseDir))); + }).pipe(Effect.provide(NodeServices.layer)), + ); + } + it.effect("reports nothing when no state files exist", () => Effect.gen(function* () { const baseDir = yield* makeBaseDir(); diff --git a/scripts/lib/server-runtime-probe.ts b/scripts/lib/server-runtime-probe.ts index b4c9238cea..3a6b1fbed9 100644 --- a/scripts/lib/server-runtime-probe.ts +++ b/scripts/lib/server-runtime-probe.ts @@ -16,7 +16,8 @@ import * as Schema from "effect/Schema"; const STATE_DIRS = ["dev", "userdata"] as const; const RuntimeStateProbe = Schema.Struct({ - pid: Schema.Int, + /** Positive, for the reason `isPidLive` explains. */ + pid: Schema.Int.check(Schema.isGreaterThan(0)), }); const decodeRuntimeStateProbe = Schema.decodeUnknownEffect( @@ -34,12 +35,23 @@ const decodeRuntimeStateProbe = Schema.decodeUnknownEffect( * case is being told to stop a server that is already stopped. */ const isPidLive = (pid: number): boolean => { + // `process.kill` reads non-positive pids as signal-group targets rather than + // process lookups — 0 signals the caller's own group, -1 every permitted + // process — so neither throws and both would report "live" unconditionally. + // The schema rejects those, and this repeats the check so the invariant + // travels with the code that depends on it. + if (!Number.isSafeInteger(pid) || pid <= 0) { + return false; + } try { process.kill(pid, 0); return true; } catch (cause) { - // EPERM means the process exists but belongs to another user. - return (cause as NodeJS.ErrnoException).code === "EPERM"; + // EPERM means the process exists but belongs to another user. An + // out-of-range pid throws a TypeError instead, which has no errno. + return typeof cause === "object" && cause !== null && "code" in cause + ? cause.code === "EPERM" + : false; } };