From 24de5760ccb019c7e2157f40ecc50ac7766337e4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 18:58:51 +0000 Subject: [PATCH] fix(server): a shared T3 home no longer hides that the server runs on another machine With one T3 home on a shared filesystem, a second machine judged the server's runtime record by a local PID probe. `t3 pair` reported "No running T3 Code server found", and `t3 serve` told the user to stop a server that is not on their machine. The runtime record now carries the hostname of the machine its PID belongs to. The ownership lock stays the authority: when it refuses a start, the rejection reads the holder's record and names the other machine instead of advising to stop it, for `t3`, `t3 serve`, the background service's child and `t3 doctor --fix` alike. `t3 pair` names the machine too, and still pairs when the recorded server answers locally as this home's environment (a hostname that changed under a running server). The manual launch preflight leaves another machine's record to the lock rather than probing its PID here. Co-authored-by: Phon Co-Authored-By: Claude Fable 5.2 --- apps/server/src/cli/config.test.ts | 5 +- apps/server/src/cli/config.ts | 10 +++- apps/server/src/cli/doctor.test.ts | 11 ++++ apps/server/src/cli/doctor.ts | 13 +++-- apps/server/src/cli/pair.test.ts | 57 +++++++++++++++++++ apps/server/src/cli/pair.ts | 44 ++++++++++++-- .../src/persistence/DatabaseMaintenance.ts | 4 ++ apps/server/src/serverOwnership.ts | 32 +++++++++-- apps/server/src/serverRuntimeState.test.ts | 12 ++++ apps/server/src/serverRuntimeState.ts | 30 ++++++++-- 10 files changed, 196 insertions(+), 22 deletions(-) diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 5e09dda2c164..9f83ab2f47eb 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -128,11 +128,13 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-" }); const child = yield* liveProcess; assert(child.pid !== undefined); - for (const [name, pid, mode, rejectRunningServer] of [ + for (const [name, pid, mode, rejectRunningServer, hostname] of [ ["stale", 2_147_483_647, "web", true], ["own-pid", process.pid, "web", true], ["desktop", child.pid, "desktop", true], ["serve", child.pid, "web", false], + // Another machine's PID that happens to be alive here; the ownership lock decides. + ["other-machine", child.pid, "web", true, "other-machine"], ] as const) { const baseDir = path.join(root, name); const stateDir = path.join(baseDir, "userdata"); @@ -142,6 +144,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { yield* encodeUnknownJson({ version: 1, pid, + hostname, port: 3773, origin: "http://127.0.0.1:3773", startedAt: "2026-10-01T00:00:00.000Z", diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index a7b9584d1a7e..b57dd6b550cf 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -26,7 +26,11 @@ import { readBootstrapEnvelope } from "../bootstrap.ts"; import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; import { expandHomePath, resolveBaseDir } from "../os-jank.ts"; -import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { + isProcessAlive, + readPersistedServerRuntimeState, + runtimeStateOtherMachine, +} from "../serverRuntimeState.ts"; const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe( Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."), @@ -348,11 +352,13 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct // and supervisor handoff are separate; this preflight cannot arbitrate two starts. if (options?.rejectRunningServer && mode === "web") { const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath); - // A killed container can leave a record with the new server's own PID. + // A killed container can leave a record with the new server's own PID. Another machine's + // PID says nothing here; the ownership lock refuses that start and names the machine. if ( Option.isSome(runtime) && runtime.value.pid > 0 && runtime.value.pid !== process.pid && + (yield* runtimeStateOtherMachine(runtime.value)) === undefined && isProcessAlive(runtime.value.pid) ) { return yield* new CliError.UserError({ diff --git a/apps/server/src/cli/doctor.test.ts b/apps/server/src/cli/doctor.test.ts index aec121749498..98f54164420b 100644 --- a/apps/server/src/cli/doctor.test.ts +++ b/apps/server/src/cli/doctor.test.ts @@ -114,6 +114,17 @@ it.effect( `Stop T3 Code server process ${state.pid}, which the background service did not start, before repairing the database.`, ); assert.deepEqual(calls, ["pause", "resume"]); + + const refusedElsewhere = yield* Effect.scoped( + acquireServerOwnership(serverRuntimeStatePath).pipe( + Effect.tap((owner) => owner.publish({ ...state, hostname: "other-machine" })), + Effect.andThen(doctor(false)), + ), + ).pipe(Effect.flip); + assert.equal( + refusedElsewhere.message, + "A T3 Code server on another machine (other-machine) has this database open. Stop it on other-machine before repairing the database.", + ); }).pipe(Effect.provide(layerHost)), ); diff --git a/apps/server/src/cli/doctor.ts b/apps/server/src/cli/doctor.ts index a0bda9935164..1a7352fa7746 100644 --- a/apps/server/src/cli/doctor.ts +++ b/apps/server/src/cli/doctor.ts @@ -41,13 +41,18 @@ const lockServerHome = Effect.fn("runDoctor.lockServerHome")(function* (paths: { yield* ServerOwnership.holdServerOwnershipLock(paths.serverRuntimeStatePath).pipe( Effect.catchTags({ ServerAlreadyRunningError: Effect.fn("runDoctor.nameServerHolder")(function* (cause) { - const owner = yield* readPersistedServerRuntimeState(paths.serverRuntimeStatePath).pipe( - Effect.map(Option.filter((state) => isProcessAlive(state.pid))), - Effect.orElseSucceed(() => Option.none()), - ); + // Another machine's PID is not a process to stop here. + const owner = + cause.otherMachine === undefined + ? yield* readPersistedServerRuntimeState(paths.serverRuntimeStatePath).pipe( + Effect.map(Option.filter((state) => isProcessAlive(state.pid))), + Effect.orElseSucceed(() => Option.none()), + ) + : Option.none(); return yield* new DatabaseMaintenance.DatabaseInUseError({ path: paths.dbPath, cause, + ...(cause.otherMachine !== undefined && { otherMachine: cause.otherMachine }), ...(Option.isSome(owner) && { pid: owner.value.pid, serviceManaged: owner.value.serviceManaged === true, diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts index 9619030be2fa..266bce636b20 100644 --- a/apps/server/src/cli/pair.test.ts +++ b/apps/server/src/cli/pair.test.ts @@ -429,6 +429,63 @@ describe("t3 pair", () => { ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect( + "names the other machine for a shared home, unless the server answers as this home", + () => + withDescriptorServer((origin) => + Effect.gen(function* () { + const baseDir = NodeFS.mkdtempSync( + NodePath.join(NodeOS.tmpdir(), "t3-pair-shared-home-"), + ); + const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json"); + // The worst case: the other machine's PID is alive here and its port answers as a T3 server. + yield* persistServerRuntimeState({ + path: statePath, + state: { + ...(yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: Number(new URL(origin).port), + })), + hostname: "other-machine", + }, + }); + + const error = yield* provideCliTestLayers( + runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip), + ); + const rendered = String( + typeof error === "object" && error !== null && "cause" in error ? error.cause : error, + ); + assert.include(rendered, "runs on another machine (other-machine)"); + assert.include(rendered, statePath); + assert.notInclude(rendered, "No running T3 Code server found."); + + // A hostname that changed under a running server: it still serves this home's environment. + NodeFS.writeFileSync( + NodePath.join(baseDir, "userdata", "environment-id"), + `${testDescriptor.environmentId}\n`, + ); + const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir])); + assert.include(output, `Pairing URL: ${origin}/pair#token=`); + }), + ).pipe( + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + Effect.provideService(HostProcess.Environment, { + ...process.env, + [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({ + protocol: SERVICE_LAUNCHER_PROTOCOL, + childVersion: packageJson.version, + }), + }), + Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, { + connected: false, + send: () => false, + on: () => undefined, + off: () => undefined, + }), + ), + ); + // regression: #10516 minting opens the target database with this checkout's // migrations, so a worktree must never fall back to the live install. it.effect("does not fall back to the shared home from a linked worktree", () => diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts index 622b47f91a65..e92869edbbb6 100644 --- a/apps/server/src/cli/pair.ts +++ b/apps/server/src/cli/pair.ts @@ -23,6 +23,7 @@ import * as Console from "effect/Console"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as References from "effect/References"; @@ -39,6 +40,7 @@ import { type PersistedServerRuntimeState, isProcessAlive, readPersistedServerRuntimeState, + runtimeStateOtherMachine, } from "../serverRuntimeState.ts"; import { buildPairingUrl, @@ -82,6 +84,18 @@ export class NoRunningServerError extends Schema.TaggedError()( + "ServerOnAnotherMachineError", + { otherMachine: Schema.String, statePath: Schema.String }, +) { + override get message(): string { + return [ + `The T3 Code server recorded in ${this.statePath} runs on another machine (${this.otherMachine}), so it cannot be paired from this one.`, + `Run \`t3 pair\` on ${this.otherMachine}. To run a server on this machine, use a separate T3 home (\`--base-dir\`).`, + ].join("\n"); + } +} + export class IncompatibleServerProtocolError extends Schema.TaggedError()( "IncompatibleServerProtocolError", { @@ -249,6 +263,14 @@ const probeEnvironmentDescriptor: ( Effect.catch((outcome) => Effect.succeed(outcome)), ); +const readEnvironmentId = Effect.fn("pair.readEnvironmentId")(function* (path: string) { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readFileString(path).pipe( + Effect.map((raw) => raw.trim()), + Effect.orElseSucceed(() => undefined), + ); +}); + interface DiscoveredPairTarget { readonly baseDir: string; readonly variant: PairStateVariant; @@ -280,6 +302,7 @@ const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* ( } const checkedStatePaths: Array = []; + let serverElsewhere: ServerOnAnotherMachineError | undefined; for (const baseDir of new Set(bases)) { for (const variant of ["userdata", "dev"] as const) { const derivedPaths = yield* ServerConfig.deriveServerPaths( @@ -293,12 +316,22 @@ const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* ( if (Option.isNone(state)) { continue; } + const otherMachine = yield* runtimeStateOtherMachine(state.value); // A dead server's port may be reused; do not mint tokens in its old database for another server. - if (!isProcessAlive(state.value.pid)) { - continue; - } - const probed = yield* probeEnvironmentDescriptor(state.value.origin); - if (probed._tag !== "descriptor") { + const probed = isProcessAlive(state.value.pid) + ? yield* probeEnvironmentDescriptor(state.value.origin) + : undefined; + // Another machine's PID and origin can match an unrelated local server. Only one + // serving this home's environment is the recorded server, under a changed hostname. + if ( + probed?._tag !== "descriptor" || + (otherMachine !== undefined && + probed.descriptor.environmentId !== + (yield* readEnvironmentId(derivedPaths.environmentIdPath))) + ) { + if (otherMachine !== undefined) { + serverElsewhere ??= new ServerOnAnotherMachineError({ otherMachine, statePath }); + } continue; } return { @@ -309,6 +342,7 @@ const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* ( } satisfies DiscoveredPairTarget; } } + if (serverElsewhere !== undefined) return yield* serverElsewhere; const baseDirArgs = hasExplicitBaseDir ? ["--base-dir", explicitBaseDir] : []; return yield* new NoRunningServerError({ checkedStatePaths, diff --git a/apps/server/src/persistence/DatabaseMaintenance.ts b/apps/server/src/persistence/DatabaseMaintenance.ts index 07f2bdeecec6..76e40e6ec247 100644 --- a/apps/server/src/persistence/DatabaseMaintenance.ts +++ b/apps/server/src/persistence/DatabaseMaintenance.ts @@ -33,9 +33,13 @@ export class DatabaseInUseError extends Schema.TaggedError() cause: Schema.Defect(), pid: Schema.optional(Schema.Int), serviceManaged: Schema.optional(Schema.Boolean), + otherMachine: Schema.optional(Schema.String), }, ) { override get message() { + if (this.otherMachine !== undefined) { + return `A T3 Code server on another machine (${this.otherMachine}) has this database open. Stop it on ${this.otherMachine} before repairing the database.`; + } if (this.pid !== undefined) { return `Stop T3 Code server process ${this.pid}${this.serviceManaged ? "" : ", which the background service did not start,"} before repairing the database.`; } diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts index 193233fa8abe..41b3ee97bc2f 100644 --- a/apps/server/src/serverOwnership.ts +++ b/apps/server/src/serverOwnership.ts @@ -37,17 +37,25 @@ import { isProcessAlive, persistServerRuntimeState, readPersistedServerRuntimeState, + runtimeStateOtherMachine, type PersistedServerRuntimeState, } from "./serverRuntimeState.ts"; export class ServerAlreadyRunningError extends Schema.TaggedError()( "ServerAlreadyRunningError", - { stateDir: Schema.String }, + { + stateDir: Schema.String, + // Set when the owner's runtime record names a machine other than this one. + otherMachine: Schema.optional(Schema.String), + }, ) { // Distinct exit codes let supervisors stop restarting an already-owned server. override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED; override get message(): string { + if (this.otherMachine !== undefined) { + return `A T3 Code server on another machine (${this.otherMachine}) already owns ${this.stateDir}. To pair with it, run \`t3 pair\` on ${this.otherMachine}. To run a server on this machine, use a separate T3 home (\`--base-dir\`). No server was stopped. server-owner.sqlite is the ownership lock; do not delete it while a server is running.`; + } return `A T3 Code server already owns ${this.stateDir}. Stop that server, or use a separate T3 home and pair with it, then retry. No server was stopped. server-owner.sqlite is the ownership lock; do not delete it while a server is running.`; } } @@ -207,13 +215,27 @@ const openOwnershipLock = (stateDir: string) => : new ServerOwnershipError({ stateDir, cause }), }); +// The lock decides ownership; the holder's runtime record only says which machine to name. +const lockOwnership = (statePath: string) => + openOwnershipLock(NodePath.dirname(statePath)).pipe( + Effect.catchTags({ + ServerAlreadyRunningError: Effect.fn("lockOwnership.nameOtherMachine")(function* (error) { + const owner = yield* readPersistedServerRuntimeState(statePath); + const otherMachine = Option.isSome(owner) + ? yield* runtimeStateOtherMachine(owner.value) + : undefined; + return yield* otherMachine === undefined + ? error + : new ServerAlreadyRunningError({ stateDir: error.stateDir, otherMachine }); + }), + }), + ); + /** Hold only the ownership lock until the scope closes, without claiming the runtime state. */ export const holdServerOwnershipLock = Effect.fn("holdServerOwnershipLock")(function* ( statePath: string, ) { - yield* Effect.acquireRelease(openOwnershipLock(NodePath.dirname(statePath)), ({ db }) => - Effect.sync(() => db.close()), - ); + yield* Effect.acquireRelease(lockOwnership(statePath), ({ db }) => Effect.sync(() => db.close())); }); /** Hold an exclusive lock on the state directory until the scope closes. */ @@ -226,7 +248,7 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi .uuidV4() .pipe(Effect.mapError((cause) => new ServerOwnershipError({ stateDir, cause }))); const lockPath = ownershipLockPath(stateDir); - const lock = yield* Effect.acquireRelease(openOwnershipLock(stateDir), ({ db }) => + const lock = yield* Effect.acquireRelease(lockOwnership(statePath), ({ db }) => readPersistedServerRuntimeState(statePath).pipe( Effect.flatMap((state) => Option.isSome(state) && state.value.ownerId === ownerId diff --git a/apps/server/src/serverRuntimeState.test.ts b/apps/server/src/serverRuntimeState.test.ts index 5a14cf139577..b02c9bf9b7a5 100644 --- a/apps/server/src/serverRuntimeState.test.ts +++ b/apps/server/src/serverRuntimeState.test.ts @@ -188,6 +188,18 @@ describe("server ownership", () => { ); assert.equal(refused._tag, "ServerAlreadyRunningError"); assert.include(refused.message, "do not delete it while a server is running"); + assert.notInclude(refused.message, "another machine"); + // The same T3 home, read from a second machine over a shared filesystem. + const refusedElsewhere = yield* ServerOwnership.acquireServerOwnership(statePath).pipe( + Effect.provideService(HostProcess.Hostname, "second-machine"), + Effect.flip, + ); + assert.equal(refusedElsewhere._tag, "ServerAlreadyRunningError"); + assert.include( + refusedElsewhere.message, + `on another machine (${HostProcess.Hostname.defaultValue()})`, + ); + assert.notInclude(refusedElsewhere.message, "Stop that server"); assert.equal(yield* fs.readFileString(statePath), before); }), ); diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts index fc5c85a2a9c1..5aa616cf9223 100644 --- a/apps/server/src/serverRuntimeState.ts +++ b/apps/server/src/serverRuntimeState.ts @@ -5,6 +5,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification"; import packageJson from "../package.json" with { type: "json" }; import type * as ServerConfig from "./config.ts"; @@ -12,6 +13,8 @@ import type * as ServerConfig from "./config.ts"; export const PersistedServerRuntimeState = Schema.Struct({ version: Schema.Literal(1), pid: Schema.Int, + // The machine `pid` belongs to; a T3 home on a shared filesystem is read by others. Absent from older servers. + hostname: Schema.optional(Schema.String), ownerId: Schema.optional(Schema.String), host: Schema.optional(Schema.String), privateNetworkOnly: Schema.optional(Schema.Boolean), @@ -61,7 +64,9 @@ const runtimeOriginForConfig = ( return `http://${hostname}:${port}`; }; -export const makePersistedServerRuntimeState = (input: { +export const makePersistedServerRuntimeState = Effect.fn( + "serverRuntimeState.makePersistedServerRuntimeState", +)(function* (input: { readonly config: Pick< ServerConfig.ServerConfig["Service"], "host" | "privateNetworkOnly" | "devUrl" @@ -69,10 +74,12 @@ export const makePersistedServerRuntimeState = (input: { readonly port: number; readonly serviceManaged?: boolean; readonly managedPolicy?: PersistedServerRuntimeState["managedPolicy"]; -}): Effect.Effect => - Effect.map(DateTime.now, (now) => ({ - version: 1, +}) { + const now = yield* DateTime.now; + return { + version: 1 as const, pid: process.pid, + hostname: yield* HostProcess.Hostname, ...(input.config.host ? { host: input.config.host } : {}), ...(input.config.privateNetworkOnly ? { privateNetworkOnly: true } : {}), port: input.port, @@ -82,7 +89,8 @@ export const makePersistedServerRuntimeState = (input: { ...(input.serviceManaged ? { serviceManaged: true } : {}), serverVersion: packageJson.version, ...(input.managedPolicy === undefined ? {} : { managedPolicy: input.managedPolicy }), - })); + } satisfies PersistedServerRuntimeState; +}); export const persistServerRuntimeState = (input: { readonly path: string; @@ -139,6 +147,18 @@ export const isProcessAlive = (pid: number): boolean => { } }; +/** + * The recorded machine when it is not this one. Its PID and loopback origin mean nothing + * here. A hostname can also change under a running server, so this alone does not prove + * the server is elsewhere. + */ +export const runtimeStateOtherMachine = Effect.fn("serverRuntimeState.runtimeStateOtherMachine")( + function* (state: Pick) { + const hostname = yield* HostProcess.Hostname; + return state.hostname !== undefined && state.hostname !== hostname ? state.hostname : undefined; + }, +); + export const readPersistedServerRuntimeState = Effect.fn( "serverRuntimeState.readPersistedServerRuntimeState", )(