Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/server/src/observability/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
description: "Time for the provider adapter to start a turn, not how long the turn runs.",
});

export const providerThreadUnloadsTotal = Metric.counter("t3_provider_thread_unloads_total", {
description: "Total idle provider thread unload attempts, by mode and outcome.",
});

export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", {
description: "Total canonical provider runtime events processed.",
});
Expand Down
116 changes: 116 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1262,6 +1262,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
terminalEvents,
subagentUpdates,
hasPendingBackgroundWork,
replayState: driver.state,
firstTerminal: Deferred.await(firstTerminal),
until: changes.until,
awaitTerminal: (count: number) => changes.until(() => terminalEvents().length >= count),
Expand Down Expand Up @@ -3882,6 +3883,121 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);

it.effect("archives an eagerly unloaded thread and interrupts its leftover commands", () =>
Effect.gen(function* () {
const exchange = (id: number, method: string, result: unknown, notified: string[]) => [
{
type: "expect_outbound" as const,
label: method,
frame: { id, method, params: { threadId: BG_NATIVE_THREAD } },
},
...notified.map((notifiedMethod) => ({
type: "emit_inbound" as const,
label: notifiedMethod,
frame: { method: notifiedMethod, params: { threadId: BG_NATIVE_THREAD } },
})),
{
type: "emit_inbound" as const,
label: `${method}-result`,
frame: { id, result },
},
];
const transcript = makeCodexReplayTranscript({
scenario: "codex-background-thread-archived",
entries: [
...backgroundExecTranscript.entries.slice(0, -1),
...exchange(4, "thread/archive", {}, ["thread/archived"]),
...exchange(5, "thread/unarchive", { thread: { id: BG_NATIVE_THREAD } }, [
"thread/unarchived",
]),
],
});
const harness = yield* makeCodexReplayHarness(transcript);
yield* harness.runtime.startTurn(
makeCodexTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now: yield* DateTime.now,
attemptId: RunAttemptId.make("attempt-codex-thread-archived"),
text: BG_PROMPT,
}),
);
yield* harness.firstTerminal;
yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread, eager: true });
assert.deepEqual(
harness.events.flatMap((event) =>
event.type === "turn_item.updated" &&
event.turnItem.nativeItemRef?.nativeId === BG_COMMAND_ITEM
? [event.turnItem.status]
: [],
),
["running", "interrupted"],
);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);

it.effect("falls back to unsubscribing when an eager archive fails", () =>
Effect.gen(function* () {
const transcript = makeCodexReplayTranscript({
scenario: "codex-background-thread-archive-failed",
entries: [
...backgroundExecTranscript.entries.slice(0, -1),
{
type: "expect_outbound",
label: "thread/archive",
frame: { id: 4, method: "thread/archive", params: { threadId: BG_NATIVE_THREAD } },
},
{
type: "emit_inbound",
label: "thread/archive-error",
frame: { id: 4, error: { code: -32603, message: "archive failed" } },
},
{
type: "expect_outbound",
label: "thread/unsubscribe",
frame: {
id: 5,
method: "thread/unsubscribe",
params: { threadId: BG_NATIVE_THREAD },
},
},
{
type: "emit_inbound",
label: "thread/unsubscribe-result",
frame: { id: 5, result: { status: "unsubscribed" } },
},
],
});
const harness = yield* makeCodexReplayHarness(transcript);
yield* harness.runtime.startTurn(
makeCodexTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now: yield* DateTime.now,
attemptId: RunAttemptId.make("attempt-codex-thread-archive-failed"),
text: BG_PROMPT,
}),
);
yield* harness.firstTerminal;
yield* harness.runtime.unloadThread!({
providerThread: harness.providerThread,
eager: true,
}).pipe(Effect.flip);
assert.strictEqual((yield* Ref.get(harness.replayState)).cursor, transcript.entries.length);
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
);

const backgroundStopCases = [true, false, "still_running", "thread_unloaded"] as const;
const makeBackgroundStopTranscript = (terminated: (typeof backgroundStopCases)[number]) => {
const stillRunning = terminated === "still_running";
Expand Down
34 changes: 27 additions & 7 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4691,11 +4691,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (

// Unloading an idle thread kills its terminals without completing
// their command items, while the shared provider session stays alive.
yield* client.handleServerNotification("thread/closed", (payload) =>
Effect.gen(function* () {
const interruptClosedThreadCommands = Effect.fn(
"CodexAdapterV2.interruptClosedThreadCommands",
)(
function* (nativeThreadId: string) {
const completedAt = yield* DateTime.now;
for (const context of (yield* Ref.get(settledTurns)).values()) {
if (context.providerThread.nativeThreadRef?.nativeId !== payload.threadId) continue;
if (context.providerThread.nativeThreadRef?.nativeId !== nativeThreadId) continue;
const commands = (yield* Ref.get(runningCommandItemsByTurn)).get(
context.nativeTurnId,
);
Expand All @@ -4715,7 +4717,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
});
yield* releaseSettledTurnIfIdle(context.nativeTurnId);
}
}).pipe(Effect.orDie, turnTerminalizationPermit.withPermits(1)),
},
Effect.orDie,
turnTerminalizationPermit.withPermits(1),
);
yield* client.handleServerNotification("thread/closed", (payload) =>
interruptClosedThreadCommands(payload.threadId),
);

yield* client.handleServerNotification("item/started", (payload) =>
Expand Down Expand Up @@ -7163,13 +7170,26 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
),
),
),
// Dropping this connection's subscription lets the shared app-server
// shut the native thread (and its MCP servers) down once it is idle.
unloadThread: Effect.fn("CodexAdapterV2.unloadThread")(
function* (unloadInput) {
const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread);
sessionApprovals.delete(nativeThreadId);
yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });
if (unloadInput.eager !== true) {
yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });
return;
}
// Codex closes an unsubscribed thread (and its MCP servers) only after a fixed
// 1800 s; archive is the only immediate unload, and it never sends thread/closed.
yield* client.request("thread/archive", { threadId: nativeThreadId }).pipe(
// A failed archive keeps the thread subscribed, so Codex would never close it.
Effect.tapError(() =>
client
.request("thread/unsubscribe", { threadId: nativeThreadId })
.pipe(Effect.ignore),
),
);
yield* interruptClosedThreadCommands(nativeThreadId);
yield* client.raw.request("thread/unarchive", { threadId: nativeThreadId });
},
(effect, unloadInput) =>
effect.pipe(
Expand Down
Loading
Loading