TypeScript
fix(server): make the remaining flaky server tests deterministic (#22559)
Julius Marminge31dcc7c51309
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.tsindex ae06aba0355..6dcfde2ee33 100644--- a/apps/server/scripts/acp-mock-agent.ts+++ b/apps/server/scripts/acp-mock-agent.ts@@ -1466,9 +1466,9 @@ const program = Effect.gen(function* () {},});if (exitAfterRunningCommandLaunch) {+ // The test sends `_test/exit` once T3 has recorded the published processes.yield* Effect.promise(() => runningCommandPublished);- yield* Effect.sleep("100 millis");- return yield* Effect.sync(() => process.exit(0));+ return yield* Effect.never;}while (!cancelledSessions.has(requestedSessionId)) {yield* Effect.sleep("25 millis");@@ -2448,8 +2448,14 @@ const program = Effect.gen(function* () {return Effect.succeed({});});- yield* agent.handleUnknownExtNotification((method) =>- method === "_test/exit" ? Effect.sync(() => process.exit(19)) : Effect.void,+ yield* agent.handleUnknownExtNotification((method, params) =>+ method === "_test/exit"+ ? Effect.sync(() => {+ const code =+ typeof params === "object" && params !== null ? Reflect.get(params, "code") : undefined;+ process.exit(typeof code === "number" ? code : 19);+ })+ : Effect.void,);return yield* Effect.never;diff --git a/apps/server/scripts/acp-replay-agent.ts b/apps/server/scripts/acp-replay-agent.tsindex 351cfa131e2..950c6909d01 100644--- a/apps/server/scripts/acp-replay-agent.ts+++ b/apps/server/scripts/acp-replay-agent.ts@@ -56,9 +56,12 @@ let nextAgentRequestId = 1;const pendingClientRequestIds = new Map<string, string | number>();const pendingAgentRequestMethods = new Map<string, string>();+// The test reads status while this agent may still be running; rename makes each+// write atomic so a reader never sees a truncated file.function writeStatus(failure?: unknown): void {+ const temporaryStatusPath = `${replayStatusPath}.${process.pid}.tmp`;NodeFS.writeFileSync(- replayStatusPath,+ temporaryStatusPath,JSON.stringify({scenario: transcript.scenario,cursor,@@ -67,6 +70,7 @@ function writeStatus(failure?: unknown): void {}),"utf8",);+ NodeFS.renameSync(temporaryStatusPath, replayStatusPath);}function stableStringify(value: unknown): string {diff --git a/apps/server/src/auth/ServerSecretStore.ts b/apps/server/src/auth/ServerSecretStore.tsindex a3bab12d8b5..020413ee8cd 100644--- a/apps/server/src/auth/ServerSecretStore.ts+++ b/apps/server/src/auth/ServerSecretStore.ts@@ -223,26 +223,41 @@ export const make = Effect.gen(function* () {);};+ // `link` publishes the fully written temp file under the final name, or fails with+ // AlreadyExists, so a concurrent reader never observes a partially written secret.const create: ServerSecretStore["Service"]["create"] = (name, value) => {const secretPath = resolveSecretPath(name);- return Effect.scoped(- Effect.gen(function* () {- const file = yield* fileSystem.open(secretPath, {- flag: "wx",- mode: 0o600,- });- yield* file.writeAll(value);- yield* file.sync;- yield* fileSystem.chmod(secretPath, 0o600);- }),- ).pipe(+ return crypto.randomUUIDv4().pipe(Effect.mapError((cause) =>- new SecretStorePersistError({+ new SecretStoreTemporaryPathError({resource: `secret ${name}`,cause,}),),+ Effect.flatMap((uuid) => {+ const tempPath = `${secretPath}.${uuid}.tmp`;+ return Effect.gen(function* () {+ yield* Effect.scoped(+ Effect.gen(function* () {+ const file = yield* fileSystem.open(tempPath, { flag: "wx", mode: 0o600 });+ yield* file.writeAll(value);+ yield* file.sync;+ }),+ );+ yield* fileSystem.chmod(tempPath, 0o600);+ yield* fileSystem.link(tempPath, secretPath);+ }).pipe(+ Effect.ensuring(fileSystem.remove(tempPath).pipe(Effect.ignore)),+ Effect.mapError(+ (cause) =>+ new SecretStorePersistError({+ resource: `secret ${name}`,+ cause,+ }),+ ),+ );+ }),);};diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.tsindex 0ec6920620d..fab0020b7e0 100644--- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts@@ -467,7 +467,19 @@ describe("AcpRegistryAdapterV2", () => {readonly storedModePick?: string;readonly turnModels?: ReadonlyArray<string>;}) {- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ // Scope release gives the replay agent at most a second to exit, so the status+ // read below waits for the agent itself instead of racing its last write.+ const agentExits: Array<Effect.Effect<void>> = [];+ const childProcessSpawner = ChildProcessSpawner.make((command) =>+ spawner+ .spawn(command)+ .pipe(+ Effect.tap((handle) =>+ Effect.sync(() => agentExits.push(Effect.ignore(handle.exitCode))),+ ),+ ),+ );const fileSystem = yield* FileSystem.FileSystem;const path = yield* Path.Path;const replayDir = yield* fileSystem.makeTempDirectoryScoped({@@ -592,6 +604,7 @@ describe("AcpRegistryAdapterV2", () => {current = target;}}).pipe(Effect.scoped);+ yield* Effect.all(agentExits, { discard: true });yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);return { configurations };});diff --git a/packages/effect-acp/src/errors.test.ts b/packages/effect-acp/src/errors.test.tsindex 345c63070f7..8b2587ff650 100644--- a/packages/effect-acp/src/errors.test.ts+++ b/packages/effect-acp/src/errors.test.ts@@ -53,6 +53,19 @@ describe("effect-acp errors", () => {});});+ it("includes the authored detail but not the cause in the transport message", () => {+ const cause = new Error("connection refused at a private endpoint");+ const error = new AcpError.AcpTransportError({+ detail: "ACP replay did not consume all frames",+ cause,+ });++ expect(error.message).toBe(+ "ACP transport operation failed: ACP replay did not consume all frames.",+ );+ expect(error.cause).toBe(cause);+ });+it("preserves structured extension handler failures behind stable request errors", () => {const cause = new AcpError.AcpTransportError({operation: "read-input-stream",diff --git a/packages/effect-acp/src/errors.ts b/packages/effect-acp/src/errors.tsindex ef1c38d9267..d0fa81ccdd8 100644--- a/packages/effect-acp/src/errors.ts+++ b/packages/effect-acp/src/errors.ts@@ -244,10 +244,11 @@ export class AcpTransportError extends Schema.TaggedError<AcpTransportError>()(},) {override get message() {+ const operation = this.operation ? ` ${this.operation}` : "";const method = this.method ? ` for method ${this.method}` : "";- return this.operation- ? `ACP transport operation ${this.operation} failed${method}.`- : "ACP transport operation failed.";+ // Callers often pass a sentence; strip its period so the message ends with exactly one.+ const detail = this.detail ? `: ${this.detail.replace(/\.$/, "")}` : "";+ return `ACP transport operation${operation} failed${method}${detail}.`;}}diff --git a/packages/provider-opencode/src/server/OpenCodeServerLedger.test.ts b/packages/provider-opencode/src/server/OpenCodeServerLedger.test.tsindex 90c72cf4913..5ea1943a1cb 100644--- a/packages/provider-opencode/src/server/OpenCodeServerLedger.test.ts+++ b/packages/provider-opencode/src/server/OpenCodeServerLedger.test.ts@@ -1,5 +1,6 @@// @effect-diagnostics nodeBuiltinImport:offimport * as NodeChildProcess from "node:child_process";+import * as NodeReadline from "node:readline";import * as NodeServices from "@effect/platform-node/NodeServices";import { describe, expect, it } from "@effect/vitest";@@ -38,20 +39,68 @@ const killGroup = (pgid: number) =>}});+// libuv ignores a failed setsid(), which happens when the new pid equals the id of a group+// that still has members (such as a sleep orphaned by an earlier test). The child would then+// share the test worker's group, so the script first confirms it leads its own group and exits+// with 97 before starting anything if it does not.+const groupLeaderGuard = `pgid="$(ps -o pgid= -p $$ 2>&1 | tr -d ' ')"; [ "$pgid" = "$$" ] || { echo "ungrouped:$pgid"; exit 97; }; echo grouped; `;++// Yields the group, or a description of why this shell cannot be used as one.+const spawnGroupLeader = (args: ReadonlyArray<string>, script: string) =>+ Effect.gen(function* () {+ const child = NodeChildProcess.spawn("/bin/sh", ["-c", groupLeaderGuard + script, ...args], {+ detached: true,+ stdio: ["ignore", "pipe", "ignore"],+ });+ const pid = child.pid;+ if (pid === undefined) return yield* Effect.die("spawn failed");+ const grouped = yield* Deferred.make<true | string>();+ const exited = yield* Deferred.make<NodeJS.Signals | null>();+ const printed = yield* Deferred.make<void>();+ child.once("exit", (_code, signal) => Deferred.doneUnsafe(exited, Effect.succeed(signal)));+ // "close" fires after stdout drains, so a guard line always lands first. It only fires before+ // "grouped" when the shell died without starting the script, such as from a signal.+ child.once("close", (code, signal) =>+ Deferred.doneUnsafe(+ grouped,+ Effect.succeed(+ `shell ${pid} exited (code ${code}, signal ${signal}) before its group check`,+ ),+ ),+ );+ NodeReadline.createInterface({ input: child.stdout }).on("line", (line) => {+ if (line === "grouped") Deferred.doneUnsafe(grouped, Effect.succeed(true));+ if (line.startsWith("ungrouped:")) {+ const output = line.slice("ungrouped:".length);+ Deferred.doneUnsafe(+ grouped,+ Effect.succeed(`\`ps -o pgid= -p ${pid}\` printed ${JSON.stringify(output)}`),+ );+ }+ if (line === "ready") Deferred.doneUnsafe(printed, Effect.void);+ });+ const result = yield* Deferred.await(grouped);+ return result === true+ ? { pid, exited: Deferred.await(exited), printed: Deferred.await(printed) }+ : result;+ });++// A pid colliding with a live group id is rare, so a few retries clear it. Repeated failures+// mean the guard itself is broken (for example a missing or BusyBox `ps`).+const GROUP_LEADER_ATTEMPTS = 5;+const spawnGroup = (args: ReadonlyArray<string>, script = "sleep 600 & wait") =>Effect.acquireRelease(Effect.gen(function* () {- const child = NodeChildProcess.spawn("/bin/sh", ["-c", script, ...args], {- detached: true,- stdio: ["ignore", "pipe", "ignore"],- });- const exited = yield* Deferred.make<NodeJS.Signals | null>();- const printed = yield* Deferred.make<void>();- child.once("exit", (_code, signal) => Deferred.doneUnsafe(exited, Effect.succeed(signal)));- child.stdout.once("data", () => Deferred.doneUnsafe(printed, Effect.void));- const pid = child.pid;- if (pid === undefined) return yield* Effect.die("spawn failed");- return { pid, exited: Deferred.await(exited), printed: Deferred.await(printed) };+ let failure = "";+ for (let attempt = 0; attempt < GROUP_LEADER_ATTEMPTS; attempt++) {+ const group = yield* spawnGroupLeader(args, script);+ if (typeof group !== "string") return group;+ failure = group;+ }+ return yield* Effect.die(+ `no shell led its own process group after ${GROUP_LEADER_ATTEMPTS} attempts; last: ${failure}`,+ );}),({ pid }) => killGroup(pid),);@@ -64,7 +113,7 @@ const recordFromDeadServer = (stateDir: string, server: { readonly pid: number }ownerPid: previousServer.pid,});yield* Effect.asVoid(previousLedger.track({ pid: server.pid, port: 4096, args: SERVE_ARGS }));- process.kill(-previousServer.pid, "SIGKILL");+ yield* killGroup(previousServer.pid);yield* previousServer.exited;});