Skip to content

Commit 6009ad0

Browse files
rileyjshawclaude
andcommitted
fix(server): keep the Codex event forwarder alive while the runtime closes
The adapter handed its session scope to the runtime, and `runtime.close` closes that scope before ending its event stream. That interrupted the forwarder running in the same scope, so `session/closed` was still lost and the drain wait in `stopSessionInternal` joined an interrupted fiber, which interrupted the stop itself. - Give the runtime a child of the session scope, so closing it stops the app-server without touching the forwarder. - Wait for the forwarder with `Fiber.await` instead of `Fiber.join`. - The fake runtime now closes its supplied scope like the real one, and the drain test runs on the live clock so a lost exit fails in 2s. - Add a registry test that removes a live Codex instance (real adapter, real runtime, mock app-server) and expects `session.exited`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent d77541f commit 6009ad0

3 files changed

Lines changed: 73 additions & 13 deletions

File tree

‎apps/server/src/provider/Layers/CodexAdapter.test.ts‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,11 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape {
124124
public closeEmitsSessionClosed = false;
125125

126126
readonly options: CodexSessionRuntimeOptions;
127+
private readonly scope: Scope.Scope | undefined;
127128

128-
constructor(options: CodexSessionRuntimeOptions) {
129+
constructor(options: CodexSessionRuntimeOptions, scope?: Scope.Scope) {
129130
this.options = options;
131+
this.scope = scope;
130132
}
131133

132134
start() {
@@ -180,7 +182,9 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape {
180182
})
181183
: Effect.void,
182184
),
183-
// The real runtime ends (not shuts down) its event queue on close.
185+
// Like the real runtime: close the supplied scope, then end (not shut
186+
// down) the event queue.
187+
Effect.andThen(() => (this.scope ? Scope.close(this.scope, Exit.void) : Effect.void)),
184188
Effect.andThen(() => Queue.end(this.eventQueue)),
185189
Effect.asVoid,
186190
);
@@ -193,11 +197,13 @@ class FakeCodexRuntime implements CodexSessionRuntimeShape {
193197

194198
function makeRuntimeFactory() {
195199
const runtimes: Array<FakeCodexRuntime> = [];
196-
const factory = vi.fn((options: CodexSessionRuntimeOptions) => {
197-
const runtime = new FakeCodexRuntime(options);
198-
runtimes.push(runtime);
199-
return Effect.succeed(runtime);
200-
});
200+
const factory = vi.fn((options: CodexSessionRuntimeOptions) =>
201+
Effect.gen(function* () {
202+
const runtime = new FakeCodexRuntime(options, yield* Scope.Scope);
203+
runtimes.push(runtime);
204+
return runtime;
205+
}),
206+
);
201207

202208
return {
203209
factory,
@@ -213,7 +219,7 @@ function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolea
213219

214220
const factory = vi.fn((runtimeOptions: CodexSessionRuntimeOptions) =>
215221
Effect.gen(function* () {
216-
yield* Scope.Scope;
222+
const scope = yield* Scope.Scope;
217223
yield* Effect.addFinalizer(() =>
218224
Effect.sync(() => {
219225
releasedThreadIds.push(runtimeOptions.threadId);
@@ -227,7 +233,7 @@ function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolea
227233
});
228234
}
229235

230-
const runtime = new FakeCodexRuntime(runtimeOptions);
236+
const runtime = new FakeCodexRuntime(runtimeOptions, scope);
231237
runtimes.push(runtime);
232238
return runtime;
233239
}),
@@ -1836,14 +1842,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
18361842
// the exit the runtime emits on close, or the thread stays "running".
18371843
yield* adapter.stopSession(threadId);
18381844

1839-
const exited = yield* Fiber.join(exitedFiber);
1845+
const exited = yield* Fiber.join(exitedFiber).pipe(Effect.timeout("2 seconds"));
18401846
NodeAssert.equal(exited._tag, "Some");
18411847
if (exited._tag !== "Some" || exited.value.type !== "session.exited") {
18421848
return;
18431849
}
18441850
NodeAssert.equal(exited.value.payload.exitKind, "graceful");
18451851
NodeAssert.equal(yield* adapter.hasSession(threadId), false);
1846-
}),
1852+
// Live clock so a lost exit fails at the timeout instead of hanging.
1853+
}).pipe(TestClock.withLive),
18471854
);
18481855

18491856
it.effect("maps retryable Codex error notifications to runtime.warning", () =>

‎apps/server/src/provider/Layers/CodexAdapter.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2348,8 +2348,12 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
23482348
// it and read it when a turn fails on the limit.
23492349
let rateLimits: CodexRateLimitSnapshot | undefined;
23502350
const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime;
2351+
// `runtime.close` closes the scope it was given before ending its event
2352+
// stream. A child scope keeps that from interrupting the forwarder
2353+
// below, which must stay alive to deliver the final `session/closed`.
2354+
const runtimeScope = yield* Scope.fork(sessionScope, "sequential");
23512355
const runtime = yield* createRuntime(runtimeInput).pipe(
2352-
Effect.provideService(Scope.Scope, sessionScope),
2356+
Effect.provideService(Scope.Scope, runtimeScope),
23532357
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
23542358
Effect.provideService(Crypto.Crypto, crypto),
23552359
Effect.mapError(
@@ -2766,7 +2770,8 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
27662770
// `close` ends the runtime event stream after emitting `session/closed`.
27672771
// Let the forwarder drain it before its scope is closed, so the exit
27682772
// reaches the orchestrator and the thread does not stay "running".
2769-
yield* Fiber.join(session.eventFiber).pipe(Effect.timeoutOption("5 seconds"), Effect.ignore);
2773+
// `await`, not `join`: an interrupted forwarder must not interrupt the stop.
2774+
yield* Fiber.await(session.eventFiber).pipe(Effect.timeoutOption("5 seconds"));
27702775
yield* Effect.ignore(Scope.close(session.scope, Exit.void));
27712776
yield* Fiber.interrupt(session.eventFiber).pipe(Effect.ignore);
27722777
});

‎apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,15 @@ import {
3737
ProviderDriverKind,
3838
type ProviderInstanceConfigMap,
3939
ProviderInstanceId,
40+
ThreadId,
4041
} from "@t3tools/contracts";
4142
import { HostProcessPlatform, isHostWindows } from "@t3tools/shared/hostProcess";
4243
import * as DateTime from "effect/DateTime";
4344
import * as Effect from "effect/Effect";
45+
import * as Fiber from "effect/Fiber";
4446
import * as FileSystem from "effect/FileSystem";
4547
import * as Layer from "effect/Layer";
48+
import * as Option from "effect/Option";
4649
import * as Path from "effect/Path";
4750
import * as Schema from "effect/Schema";
4851
import * as Stream from "effect/Stream";
@@ -467,6 +470,51 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
467470
}).pipe(Effect.provide(testLayer)),
468471
);
469472

473+
it.live("reports the exit of a live Codex session when its instance is removed", () =>
474+
Effect.gen(function* () {
475+
if (yield* isHostWindows) return;
476+
const fixtures = yield* makeTildeProviderFixtures();
477+
const codexId = ProviderInstanceId.make("codex_removed_live");
478+
const threadId = ThreadId.make("thread-instance-removed");
479+
const { registry, mutator } = yield* makeProviderInstanceRegistry({
480+
drivers: [CodexDriver],
481+
configMap: {
482+
[codexId]: {
483+
driver: ProviderDriverKind.make("codex"),
484+
enabled: true,
485+
environment: [
486+
{ name: "T3_CODEX_COLLAB_SCRIPT", value: fixtures.codexScriptPath, sensitive: false },
487+
],
488+
config: makeCodexConfig({ enabled: true, binaryPath: fixtures.codexBinaryPath }),
489+
},
490+
},
491+
});
492+
const codex = yield* registry.getInstance(codexId);
493+
expect(codex).toBeDefined();
494+
const adapter = codex!.adapter;
495+
const exitedFiber = yield* adapter.streamEvents.pipe(
496+
Stream.filter((event) => event.type === "session.exited" && event.threadId === threadId),
497+
Stream.runHead,
498+
Effect.forkChild,
499+
);
500+
yield* adapter.startSession({
501+
provider: ProviderDriverKind.make("codex"),
502+
threadId,
503+
runtimeMode: "full-access",
504+
});
505+
506+
// A settings edit that drops the instance. The real adapter and runtime
507+
// must report the exit, or the thread's turn stays "running" forever.
508+
yield* mutator.reconcile({});
509+
510+
const exited = yield* Fiber.join(exitedFiber).pipe(Effect.timeout("10 seconds"));
511+
expect(Option.isSome(exited)).toBe(true);
512+
if (Option.isNone(exited) || exited.value.type !== "session.exited") return;
513+
expect(exited.value.payload.exitKind).toBe("graceful");
514+
expect(yield* registry.listInstances).toEqual([]);
515+
}).pipe(Effect.provide(testLayer)),
516+
);
517+
470518
const redeemClaudeReset = (claim: { result: string; usageFailsAfterClaim: boolean }) =>
471519
Effect.gen(function* () {
472520
const fs = yield* FileSystem.FileSystem;

0 commit comments

Comments
 (0)