From 0ebee5e20263563a0f31e936a75f25a6dfa466bf Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 7 Jul 2026 21:04:57 +0000 Subject: [PATCH] Poll on the live clock for out-of-process waits in server tests CursorAdapter.test.ts polled its mock-agent request log with bare Effect.yieldNow loops, and ProviderRegistry.test.ts polled real child-process probe results with TestClock.adjust + yieldNow. Neither gives the child process or libuv any wall-clock time, so on loaded CI hosts the session/cancel log line or the re-probe spawn landed after the ~40 microtask hops and the tests failed on stale data. Add a shared pollUntil test helper that sleeps on the live clock via TestClock.withLive between attempts and dies loudly with the last polled value on timeout, and use it for all cross-process waits in both test files. Also make readJsonLines skip partially written trailing lines while a child process is still appending. Co-authored-by: Theo Browne --- .../src/provider/Layers/CursorAdapter.test.ts | 49 +++++++------ .../provider/Layers/ProviderRegistry.test.ts | 66 ++++++++---------- .../src/provider/testUtils/pollUntil.ts | 69 +++++++++++++++++++ 3 files changed, 123 insertions(+), 61 deletions(-) create mode 100644 apps/server/src/provider/testUtils/pollUntil.ts diff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.ts index 89e9c56eb8..a410dda0b7 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.test.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.test.ts @@ -28,6 +28,7 @@ import { import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import type { CursorAdapterShape } from "../Services/CursorAdapter.ts"; +import { pollUntil } from "../testUtils/pollUntil.ts"; import { makeCursorAdapter } from "./CursorAdapter.ts"; const decodeCursorSettings = Schema.decodeSync(CursorSettings); @@ -97,36 +98,34 @@ async function readJsonLines(filePath: string) { .split("\n") .map((line) => line.trim()) .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as Record); + .flatMap((line) => { + // The mock agent appends lines from a separate process, so a poll may + // observe a partially written trailing line. Skip it; the next poll + // sees the complete line. + try { + return [JSON.parse(line) as Record]; + } catch { + return []; + } + }); } -async function waitForFileContent(filePath: string, attempts = 40) { - for (let attempt = 0; attempt < attempts; attempt += 1) { - try { - const raw = await NodeFSP.readFile(filePath, "utf8"); - if (raw.trim().length > 0) { - return raw; - } - } catch {} - await Effect.runPromise(Effect.yieldNow); - } - throw new Error(`Timed out waiting for file content at ${filePath}`); +function waitForFileContent(filePath: string) { + return pollUntil({ + poll: Effect.promise(() => NodeFSP.readFile(filePath, "utf8").catch(() => "")), + until: (raw) => raw.trim().length > 0, + description: `file content at ${filePath}`, + }); } function waitForJsonLogMatch( filePath: string, predicate: (entry: Record) => boolean, - attempts = 40, ) { - return Effect.gen(function* () { - for (let attempt = 0; attempt < attempts; attempt += 1) { - const requests = yield* Effect.promise(() => readJsonLines(filePath)); - if (requests.some(predicate)) { - return requests; - } - yield* Effect.yieldNow; - } - return yield* Effect.promise(() => readJsonLines(filePath)); + return pollUntil({ + poll: Effect.promise(() => readJsonLines(filePath)), + until: (entries) => entries.some(predicate), + description: `a matching json log entry in ${filePath}`, }); } @@ -353,7 +352,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.stopSession(threadId); - const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath)); + const exitLog = yield* waitForFileContent(exitLogPath); assert.include(exitLog, "SIGTERM"); }), ); @@ -405,7 +404,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { yield* adapter.stopSession(threadId); - const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath)); + const exitLog = yield* waitForFileContent(exitLogPath); assert.equal(exitLog.match(/SIGTERM/g)?.length ?? 0, 2); }), ); @@ -516,7 +515,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { modelSelection, }); - yield* Effect.promise(() => waitForFileContent(requestLogPath)); + yield* waitForFileContent(requestLogPath); const requestsAfterStart = yield* Effect.promise(() => readJsonLines(requestLogPath)); const configIdsAfterStart = requestsAfterStart.flatMap((entry) => diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index b3ab114549..5ee3662295 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -49,6 +49,7 @@ import type { ProviderInstance } from "../ProviderDriver.ts"; import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts"; import * as ProviderRegistry from "../Services/ProviderRegistry.ts"; import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts"; +import { pollUntil } from "../testUtils/pollUntil.ts"; const decodeServerSettings = Schema.decodeSync(ServerSettings); const encodeServerSettings = Schema.encodeSync(ServerSettings); const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS); @@ -1132,17 +1133,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te yield* Effect.gen(function* () { const registry = yield* ProviderRegistry.ProviderRegistry; - let providers = yield* registry.getProviders; - for ( - let attempts = 0; - attempts < 50 && - providers.find((provider) => provider.instanceId === "codex_personal")?.status !== - "error"; - attempts += 1 - ) { - yield* Effect.yieldNow; - providers = yield* registry.getProviders; - } + // The probe spawns a real child process, so its ENOENT arrives on + // the live event loop — poll with real wall-clock pauses. + const providers = yield* pollUntil({ + poll: registry.getProviders, + until: (current) => + current.find((provider) => provider.instanceId === "codex_personal")?.status === + "error", + description: "the codex_personal probe error snapshot to reach the aggregator", + }); const codexPersonal = providers.find( (provider) => provider.instanceId === "codex_personal", ); @@ -1228,19 +1227,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te const registry = yield* ProviderRegistry.ProviderRegistry; // Boot-time probe: the default codex instance is enabled with // `firstMissing`, so the real spawner yields ENOENT and the - // snapshot should be `status: "error"`. - let initialProviders = yield* registry.getProviders; - for ( - let attempts = 0; - attempts < 50 && - initialProviders.find((provider) => provider.instanceId === "codex")?.status !== - "error"; - attempts += 1 - ) { - yield* TestClock.adjust("10 millis"); - yield* Effect.yieldNow; - initialProviders = yield* registry.getProviders; - } + // snapshot should be `status: "error"`. The spawn error arrives + // on the live event loop, so poll with real wall-clock pauses + // while still nudging the virtual clock for any test timers. + const initialProviders = yield* pollUntil({ + poll: TestClock.adjust("10 millis").pipe(Effect.andThen(registry.getProviders)), + until: (providers) => + providers.find((provider) => provider.instanceId === "codex")?.status === "error", + description: "the boot-time codex probe to fail against the first missing binary", + }); const initialCodex = initialProviders.find( (provider) => provider.instanceId === "codex", ); @@ -1264,22 +1259,21 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te // Poll until the injected process boundary observes the new // executable. This verifies the public settings-to-probe behavior - // without depending on timestamps assigned by TestClock. - const refreshed = yield* Effect.gen(function* () { - for (let attempts = 0; attempts < 60; attempts += 1) { - const providers = yield* registry.getProviders; + // without depending on timestamps assigned by TestClock. The + // settings stream, reconcile, and re-probe all hop through real + // fibers and a real child-process spawn, so give them wall-clock + // time between attempts. + const refreshed = yield* pollUntil({ + poll: TestClock.adjust("50 millis").pipe(Effect.andThen(registry.getProviders)), + until: (providers) => { const codex = providers.find((provider) => provider.instanceId === "codex"); - if ( + return ( codex !== undefined && codex.status === "error" && spawnedCommands.includes(secondMissing) - ) { - return providers; - } - yield* TestClock.adjust("50 millis"); - yield* Effect.yieldNow; - } - return yield* registry.getProviders; + ); + }, + description: "the codex re-probe against the second missing binary", }); const reprobedCodex = refreshed.find((provider) => provider.instanceId === "codex"); diff --git a/apps/server/src/provider/testUtils/pollUntil.ts b/apps/server/src/provider/testUtils/pollUntil.ts new file mode 100644 index 0000000000..9e602f72a3 --- /dev/null +++ b/apps/server/src/provider/testUtils/pollUntil.ts @@ -0,0 +1,69 @@ +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as TestClock from "effect/testing/TestClock"; + +const describeValue = (value: unknown) => { + try { + const text = JSON.stringify(value); + if (text === undefined) { + return String(value); + } + return text.length > 2_000 ? `${text.slice(0, 2_000)}…` : text; + } catch { + return String(value); + } +}; + +export interface PollUntilOptions { + /** Effect run on each attempt; its latest result is checked with `until`. */ + readonly poll: Effect.Effect; + /** Predicate on the polled value that ends the wait. */ + readonly until: (value: A) => boolean; + /** Human-readable description of what is being waited for, used in the timeout error. */ + readonly description: string; + /** Wall-clock budget for the whole wait. Defaults to 10 seconds. */ + readonly timeout?: Duration.Input; + /** Wall-clock pause between attempts. Defaults to 25 millis. */ + readonly interval?: Duration.Input; +} + +/** + * Repeatedly runs `poll` until `until` matches, sleeping on the live clock + * between attempts. + * + * Tests running under `@effect/vitest`'s `it.effect` / `it.layer` are on the + * `TestClock`, where `Effect.sleep` only advances via `TestClock.adjust` and + * `Effect.yieldNow` yields no wall-clock time at all. Polling loops built from + * those primitives give out-of-process work — mock agent child processes, + * real `ChildProcessSpawner` probes, libuv I/O callbacks — essentially zero + * real time to complete, which makes them flaky on loaded CI hosts. Sleeping + * via `TestClock.withLive` lets the event loop and child processes make + * progress while the rest of the test stays on the virtual clock. + * + * Dies with a descriptive error (including the last polled value) when the + * budget is exhausted, so a timeout fails loudly instead of letting a later + * assertion fail on stale data. + */ +export const pollUntil = (options: PollUntilOptions) => + Effect.gen(function* () { + const timeoutMillis = Duration.toMillis(options.timeout ?? "10 seconds"); + const interval = options.interval ?? "25 millis"; + const startedAt = yield* TestClock.withLive(Clock.currentTimeMillis); + for (;;) { + const value = yield* options.poll; + if (options.until(value)) { + return value; + } + const now = yield* TestClock.withLive(Clock.currentTimeMillis); + if (now - startedAt >= timeoutMillis) { + return yield* Effect.die( + new Error( + `Timed out after ${timeoutMillis}ms waiting for ${options.description}. ` + + `Last polled value: ${describeValue(value)}`, + ), + ); + } + yield* TestClock.withLive(Effect.sleep(interval)); + } + });