From 34629c2a50464debd45038f7ce01edd44e762de1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 10 Jun 2026 16:12:51 -0700 Subject: [PATCH] fix codex provider startup probing Co-authored-by: codex --- .../provider/Layers/ProviderRegistry.test.ts | 110 ++++++++++++++++-- .../src/provider/Layers/ProviderRegistry.ts | 47 ++++---- .../makeManagedServerProvider.test.ts | 1 + .../src/provider/makeManagedServerProvider.ts | 6 +- .../src/client.test.ts | 37 ++++++ .../effect-codex-app-server/src/client.ts | 21 ++-- .../fixtures/codex-app-server-mock-peer.ts | 12 ++ 7 files changed, 189 insertions(+), 45 deletions(-) diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 273cf22f31..56b80f6c4a 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -594,6 +594,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T ]); }); + it.effect("does not run provider probes during layer construction", () => + Effect.gen(function* () { + const codexDriver = ProviderDriverKind.make("codex"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const initialProvider = { + instanceId: codexInstanceId, + driver: codexDriver, + status: "warning", + enabled: true, + installed: false, + auth: { status: "unknown" }, + checkedAt: "2026-06-10T00:00:00.000Z", + version: null, + message: "Checking Codex provider status.", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const refreshCalls = yield* Ref.make(0); + const instance = { + instanceId: codexInstanceId, + driverKind: codexDriver, + continuationIdentity: { + driverKind: codexDriver, + continuationKey: "codex:instance:codex", + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: codexDriver, + packageName: null, + }), + getSnapshot: Effect.succeed(initialProvider), + refresh: Ref.update(refreshCalls, (count) => count + 1).pipe( + Effect.andThen(Effect.never), + ), + streamChanges: Stream.empty, + }, + adapter: {} as ProviderInstance["adapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(instanceId === codexInstanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), PubSub.subscribe), + }); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistryLive.pipe( + Layer.provideMerge(instanceRegistryLayer), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-background-refresh-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]); + assert.strictEqual(yield* Ref.get(refreshCalls), 0); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + it("persists merged provider snapshots for the providers that were refreshed", () => { const previousProviders = [ { @@ -1042,7 +1113,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T yield* Effect.gen(function* () { const registry = yield* ProviderRegistry; - const providers = yield* registry.getProviders; + 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; + } const codexPersonal = providers.find( (provider) => provider.instanceId === "codex_personal", ); @@ -1072,9 +1153,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T // instance and rebuild it so a fresh probe runs with the new binary. // This test drives the real settings stream → registry reconcile → // aggregator sync pipeline and asserts that `getProviders` reflects - // the new probe's outcome. If `syncLiveSources` stops awaiting the - // rebuilt instance's refresh (previous bug mode), the aggregator - // keeps the old snapshot and this test fails. + // the new background probe's outcome. // it.effect("re-probes when settings change the codex binaryPath", () => Effect.gen(function* () { @@ -1124,7 +1203,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T // the two probe runs is `checkedAt` — each probe stamps a // fresh DateTime, so we capture it and assert it advances // after the settings mutation. - const initialProviders = yield* registry.getProviders; + 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; + } const initialCodex = initialProviders.find( (provider) => provider.instanceId === "codex", ); @@ -1144,8 +1234,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T // envelope changed because `binaryPath` differs → `entryEqual` // is false). The registry's `Stream.runForEach( // instanceRegistry.streamChanges, () => syncLiveSources)` - // fires `syncLiveSources`, which subscribes + awaits a fresh - // refresh on the rebuilt instance. + // fires `syncLiveSources`, which subscribes and launches a fresh + // background refresh on the rebuilt instance. yield* serverSettings.updateSettings({ providers: { codex: { enabled: true, binaryPath: secondMissing }, @@ -1158,7 +1248,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T for (let attempts = 0; attempts < 60; attempts += 1) { const providers = yield* registry.getProviders; const codex = providers.find((provider) => provider.instanceId === "codex"); - if (codex !== undefined && codex.checkedAt !== initialCheckedAt) { + if ( + codex !== undefined && + codex.status === "error" && + codex.checkedAt !== initialCheckedAt + ) { return providers; } yield* TestClock.adjust("50 millis"); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index 22a120f0a5..2df63e5383 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -492,16 +492,15 @@ export const ProviderRegistryLive = Layer.effect( * - subscribe to each newly-added or rebuilt instance's * `streamChanges` (so periodic + enrichment refreshes land in * `providersRef`); - * - force-refresh each newly-added/rebuilt instance and feed the - * result directly into `providersRef`, bypassing the PubSub - * attachment race that otherwise drops the initial probe; + * - read each newly-added/rebuilt instance's current snapshot after + * subscribing, closing the race with its independently-running + * background startup probe; * - prune `providersRef` of instances that no longer exist. * - * Initial refreshes are awaited in parallel rather than forked, so - * callers (layer build; `streamChanges` watcher) see fully-probed - * state on return. This matters for layer build in particular: - * consumers reading `getProviders` immediately after layer build - * expect the probe to have already landed. + * Provider refreshes are owned by each managed provider and never run + * on this layer's construction path. Consumers see cached or pending + * snapshots immediately, then receive live probe results through the + * already-attached change stream. * * Per-instance subscription fibers are not tracked explicitly. When * a rebuilt instance's old child scope closes, its PubSub shuts @@ -543,27 +542,31 @@ export const ProviderRegistryLive = Layer.effect( } // Fork long-lived subscriptions to each new/rebuilt instance's - // change stream BEFORE kicking off refreshes — if the driver's - // own initial probe (line 140 in `makeManagedServerProvider`) - // wins the refreshSemaphore race, its PubSub publish must land - // in an active subscriber or the result is dropped. + // change stream before reading its current snapshot. If the + // driver's own initial probe finishes during this sync, either + // the current read or the active subscriber observes the result. for (const [, instance] of newlyAdded) { const source = buildSnapshotSource(instance); yield* Stream.runForEach(source.streamChanges, (provider) => correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)), ).pipe(Effect.forkScoped); } + yield* Effect.yieldNow; - // Force-refresh every new/rebuilt instance in parallel and wait - // for them all to complete. The refresh's result is piped - // directly into `syncProvider`, so `providersRef` is populated - // deterministically by the time this block returns — regardless - // of PubSub subscription timing. Failures are logged and - // swallowed so one bad driver can't wedge the whole registry. + // Snapshot current state without starting a probe. Managed providers + // launch their startup refresh independently, so this closes the + // subscription race without putting external work on the registry + // or HTTP server construction path. yield* Effect.forEach( newlyAdded, ([, instance]) => - refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })), + Effect.gen(function* () { + const source = buildSnapshotSource(instance); + const provider = yield* source.getSnapshot; + yield* correlateSnapshotWithSource(source, provider).pipe( + Effect.flatMap(syncProvider), + ); + }).pipe(Effect.ignoreCause({ log: true })), { concurrency: "unbounded", discard: true }, ); yield* upsertProviders(unavailableProviders, { @@ -654,9 +657,9 @@ export const ProviderRegistryLive = Layer.effect( // was dropped, which made any settings change that replaced an // instance never propagate to the aggregator's `providersRef`.) const instanceChanges = yield* instanceRegistry.subscribeChanges; - // Initial sync: subscribe + kick off refreshes for every instance - // present at boot. Run synchronously so consumers pulling immediately - // after the layer build see the correct aggregator state. + // Initial sync attaches subscriptions and snapshots current state for + // every instance present at boot. Provider probes are already running in + // their managed background fibers and never block this layer. yield* syncLiveSources; // React to registry mutations — instance added / removed / rebuilt. // `Stream.fromSubscription` builds a stream over the pre-acquired diff --git a/apps/server/src/provider/makeManagedServerProvider.test.ts b/apps/server/src/provider/makeManagedServerProvider.test.ts index 1f3ebeab08..ba1f01fe2b 100644 --- a/apps/server/src/provider/makeManagedServerProvider.test.ts +++ b/apps/server/src/provider/makeManagedServerProvider.test.ts @@ -129,6 +129,7 @@ describe("makeManagedServerProvider", () => { Effect.forkChild, ); yield* Effect.yieldNow; + assert.strictEqual(yield* Ref.get(checkCalls), 1); yield* Deferred.succeed(releaseCheck, undefined); diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.ts index 2f07c5d508..88547fb3af 100644 --- a/apps/server/src/provider/makeManagedServerProvider.ts +++ b/apps/server/src/provider/makeManagedServerProvider.ts @@ -152,11 +152,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( return { maintenanceCapabilities: input.maintenanceCapabilities, - getSnapshot: input.getSettings.pipe( - Effect.flatMap(applySnapshot), - Effect.tapError(Effect.logError), - Effect.orDie, - ), + getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)), refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie), get streamChanges() { return Stream.fromPubSub(changesPubSub); diff --git a/packages/effect-codex-app-server/src/client.test.ts b/packages/effect-codex-app-server/src/client.test.ts index 77b5a16355..8d301742a5 100644 --- a/packages/effect-codex-app-server/src/client.test.ts +++ b/packages/effect-codex-app-server/src/client.test.ts @@ -152,4 +152,41 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => { assert.equal(initialized.userAgent, "mock-codex-app-server"); }), ); + + it.effect("drains command stderr so large diagnostics cannot block protocol responses", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const scope = yield* Scope.make(); + const clientLayer = CodexClient.layerCommand({ + command: "node", + args: mockPeerArgs(yield* mockPeerPath), + cwd: path.join(import.meta.dirname, ".."), + env: { + CODEX_APP_SERVER_TEST_STDERR_BYTES: String(512 * 1024), + }, + }); + const context = yield* Layer.buildWithScope(clientLayer, scope); + + const initialized = yield* Effect.gen(function* () { + const client = yield* CodexClient.CodexAppServerClient; + return yield* client.request("initialize", { + clientInfo: { + name: "effect-codex-app-server-test", + title: "Effect Codex App Server Test", + version: "0.0.0", + }, + capabilities: { + experimentalApi: true, + optOutNotificationMethods: null, + }, + }); + }).pipe( + Effect.timeout("5 seconds"), + Effect.provide(context), + Effect.ensuring(Scope.close(scope, Exit.void)), + ); + + assert.equal(initialized.userAgent, "mock-codex-app-server"); + }), + ); }); diff --git a/packages/effect-codex-app-server/src/client.ts b/packages/effect-codex-app-server/src/client.ts index 7d409fce77..edc7d8b6cf 100644 --- a/packages/effect-codex-app-server/src/client.ts +++ b/packages/effect-codex-app-server/src/client.ts @@ -4,6 +4,7 @@ import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stdio from "effect/Stdio"; +import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import * as CodexRpc from "./_generated/meta.gen.ts"; @@ -253,11 +254,15 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make export const layerChildProcess = ( handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions = {}, -): Layer.Layer => { - const stdio = makeChildStdio(handle); - const terminationError = makeTerminationError(handle); - return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError)); -}; +): Layer.Layer => + Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options)); + +const makeChildProcessClient = Effect.fn( + "effect-codex-app-server/CodexAppServerClient.makeChildProcessClient", +)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) { + yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped); + return yield* make(makeChildStdio(handle), options, makeTerminationError(handle)); +}); export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions { readonly command: string; @@ -292,9 +297,5 @@ export const layerCommand = ( }), ), ); - }).pipe( - Effect.flatMap((handle) => - make(makeChildStdio(handle), options, makeTerminationError(handle)), - ), - ), + }).pipe(Effect.flatMap((handle) => makeChildProcessClient(handle, options))), ); diff --git a/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts b/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts index 51668b5e24..f04f43dd70 100644 --- a/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts +++ b/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts @@ -34,6 +34,18 @@ const handleMethod = (message: Record) => { switch (method) { case "initialize": { + const stderrBytes = Number(process.env.CODEX_APP_SERVER_TEST_STDERR_BYTES ?? 0); + if (Number.isFinite(stderrBytes) && stderrBytes > 0) { + process.stderr.write("x".repeat(stderrBytes), () => { + respond(message.id as number | string, { + userAgent: "mock-codex-app-server", + codexHome: process.cwd(), + platformFamily: process.platform === "win32" ? "windows" : "unix", + platformOs: process.platform === "darwin" ? "macos" : process.platform, + }); + }); + return; + } respond(message.id as number | string, { userAgent: "mock-codex-app-server", codexHome: process.cwd(),