Skip to content

Commit f48b868

Browse files
Mika Hertlerclaude
andcommitted
fix(server): Stop reaches kept sessions after a newer start fails
When a newer account's start fails before it accepts a provider turn, the failed run has no turn of its own to interrupt. `thread.stop` then fell back to marking and holding the thread, and dropped the interrupts it had already validated for the older kept sessions, so they stayed busy. A holding interrupt of the latest settled run now still sends those interrupts when the run has no provider turn, and marks the run and holds the queue as before. A plain `run.interrupt` of such a run, of an older run, or of a run still starting is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5414cfd commit f48b868

2 files changed

Lines changed: 209 additions & 1 deletion

File tree

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12171,6 +12171,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1217112171
};
1217212172
}
1217312173

12174+
// A newer account's start can fail before it accepts a turn. Stop still owes the older
12175+
// kept sessions their interrupts, and marks and holds the thread like its fallback.
12176+
if (
12177+
providerTurn === undefined &&
12178+
command.holdQueue === true &&
12179+
hasBackgroundWork &&
12180+
otherProviderInterrupts.length > 0
12181+
) {
12182+
yield* emitEvent({
12183+
type: "turn-item.updated",
12184+
threadId: command.threadId,
12185+
runId: run.id,
12186+
nodeId: rootNode.id,
12187+
providerInstanceId: run.providerInstanceId,
12188+
occurredAt: now,
12189+
payload: interruptRequestItem,
12190+
});
12191+
yield* stopRemainingWork();
12192+
yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]);
12193+
return undefined;
12194+
}
1217412195
if (providerTurn === undefined) {
1217512196
return yield* new OrchestratorDispatchError({
1217612197
commandId: command.commandId,

‎apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts‎

Lines changed: 188 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,12 +118,17 @@ function makeTestAdapter(input: {
118118
readonly cancelledRunOrdinals?: ReadonlySet<number>;
119119
readonly holdRunOrdinal?: number;
120120
readonly pendingBackgroundWork?: Ref.Ref<boolean>;
121+
// Codex-like: adapter-only work of the named provider threads, probed per thread.
122+
readonly busyProviderThreads?: Ref.Ref<ReadonlyArray<string>>;
121123
readonly subagentOnlyBackgroundWork?: boolean;
122124
readonly holdFirstTurn?: Deferred.Deferred<void>;
123125
readonly releaseFirstTurn?: Deferred.Deferred<void>;
124126
readonly backgroundWork?: Ref.Ref<boolean>;
125127
readonly bufferedWake?: Ref.Ref<boolean>;
126128
readonly closedSessions?: Ref.Ref<ReadonlyArray<string>>;
129+
readonly onInterrupt?: (
130+
input: ProviderAdapter.ProviderAdapterV2InterruptInput,
131+
) => Effect.Effect<void>;
127132
}): ProviderAdapter.ProviderAdapterV2["Service"] {
128133
return {
129134
instanceId: input.instanceId,
@@ -167,6 +172,17 @@ function makeTestAdapter(input: {
167172
? Effect.succeed(false)
168173
: Ref.get(input.pendingBackgroundWork!),
169174
}),
175+
...(input.busyProviderThreads === undefined
176+
? {}
177+
: {
178+
hasPendingBackgroundWork: Ref.get(input.busyProviderThreads).pipe(
179+
Effect.map((ids) => ids.length > 0),
180+
),
181+
hasPendingBackgroundWorkForThread: (thread) =>
182+
Ref.get(input.busyProviderThreads!).pipe(
183+
Effect.map((ids) => ids.includes(thread.id)),
184+
),
185+
}),
170186
...(input.getModelContextWindow === undefined
171187
? {}
172188
: { getModelContextWindow: input.getModelContextWindow }),
@@ -404,7 +420,7 @@ function makeTestAdapter(input: {
404420
}
405421
}),
406422
steerTurn: () => Effect.void,
407-
interruptTurn: () => Effect.void,
423+
interruptTurn: (interrupt) => input.onInterrupt?.(interrupt) ?? Effect.void,
408424
respondToRuntimeRequest: () => Effect.void,
409425
readThreadSnapshot: () =>
410426
unimplemented(input.driver, "readThreadSnapshot unused in provider switch test"),
@@ -3055,6 +3071,177 @@ describe("orchestration v2 provider switching", () => {
30553071
),
30563072
);
30573073

3074+
it.live(
3075+
"lets Stop reach older kept sessions when a newer account fails before its first turn",
3076+
() =>
3077+
Effect.scoped(
3078+
Effect.gen(function* () {
3079+
const cwd = yield* checkpointWorkspace("stop-after-failed-switch-start");
3080+
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
3081+
// Provider threads with work only their adapter sees; a restart interrupt ends it.
3082+
const busy = yield* Ref.make<ReadonlyArray<string>>([]);
3083+
const interrupts = yield* Ref.make<
3084+
ReadonlyArray<ProviderAdapter.ProviderAdapterV2InterruptInput>
3085+
>([]);
3086+
const failThirdStart = yield* Ref.make(true);
3087+
const selections = ["first", "second", "third"].map((account): ModelSelection => ({
3088+
...CODEX_MODEL_SELECTION,
3089+
instanceId: ProviderInstanceId.make(`codex-${account}-account`),
3090+
}));
3091+
const adapters = selections.map((modelSelection, index) =>
3092+
makeTestAdapter({
3093+
instanceId: modelSelection.instanceId,
3094+
driver: CODEX_DRIVER,
3095+
capabilities: CodexProviderCapabilitiesV2,
3096+
modelSelection,
3097+
responseByRunOrdinal: {},
3098+
capturedTurns,
3099+
busyProviderThreads: busy,
3100+
...(index === 2 ? { failStartOnce: failThirdStart } : {}),
3101+
onInterrupt: (interrupt) =>
3102+
Ref.update(interrupts, (current) => [...current, interrupt]).pipe(
3103+
Effect.andThen(
3104+
interrupt.requestRuntimeRestart === true
3105+
? Ref.update(busy, (ids) =>
3106+
ids.filter((id) => id !== interrupt.providerThread.id),
3107+
)
3108+
: Effect.void,
3109+
),
3110+
),
3111+
}),
3112+
);
3113+
const threadId = ThreadId.make("thread:stop-after-failed-switch-start");
3114+
const unrelatedThreadId = ThreadId.make(
3115+
"thread:stop-after-failed-switch-start:unrelated",
3116+
);
3117+
yield* Effect.gen(function* () {
3118+
const orchestrator = yield* Orchestrator.OrchestratorV2;
3119+
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3120+
const create = (id: ThreadId) =>
3121+
orchestrator.dispatch({
3122+
type: "thread.create",
3123+
createdBy: "user",
3124+
creationSource: "web",
3125+
commandId: CommandId.make(`command:create:${id}`),
3126+
threadId: id,
3127+
projectId: ProjectId.make("project:stop-after-failed-switch-start"),
3128+
title: "Stop after a failed switch start",
3129+
modelSelection: selections[0]!,
3130+
runtimeMode: "full-access",
3131+
interactionMode: "default",
3132+
branch: null,
3133+
worktreePath: cwd,
3134+
});
3135+
const send = (id: ThreadId, ordinal: number, modelSelection: ModelSelection) =>
3136+
orchestrator.dispatch({
3137+
type: "message.dispatch",
3138+
createdBy: "user",
3139+
creationSource: "web",
3140+
commandId: CommandId.make(`command:send:${id}:${ordinal}`),
3141+
threadId: id,
3142+
messageId: MessageId.make(`message:${id}:${ordinal}`),
3143+
text: `Prompt ${ordinal}`,
3144+
attachments: [],
3145+
modelSelection,
3146+
dispatchMode: { type: "start_immediately" },
3147+
});
3148+
yield* create(threadId);
3149+
yield* create(unrelatedThreadId);
3150+
// Another app thread shares the first account's runtime; Stop must leave its work.
3151+
yield* send(unrelatedThreadId, 1, selections[0]!);
3152+
yield* worker.drain();
3153+
const unrelated = yield* waitForIdle(unrelatedThreadId);
3154+
const unrelatedProviderThreadId = unrelated.thread.activeProviderThreadId!;
3155+
yield* Ref.update(busy, (ids) => [...ids, unrelatedProviderThreadId]);
3156+
3157+
// Each account completes its run and keeps adapter-only work after the next takes over.
3158+
for (const index of [0, 1]) {
3159+
yield* send(threadId, index + 1, selections[index]!);
3160+
yield* worker.drain();
3161+
const idle = yield* waitForIdle(threadId);
3162+
assert.strictEqual(idle.runs.at(-1)?.status, "completed");
3163+
yield* Ref.update(busy, (ids) => [...ids, idle.thread.activeProviderThreadId!]);
3164+
}
3165+
// The third account fails before accepting any provider turn.
3166+
yield* send(threadId, 3, selections[2]!);
3167+
yield* worker.drain();
3168+
const failed = yield* waitForIdle(threadId);
3169+
assert.deepStrictEqual(
3170+
failed.runs.map((run) => [run.providerInstanceId, run.status]),
3171+
[
3172+
[selections[0]!.instanceId, "completed"],
3173+
[selections[1]!.instanceId, "completed"],
3174+
[selections[2]!.instanceId, "failed"],
3175+
],
3176+
);
3177+
const kept = failed.providerThreads.filter(
3178+
(thread) => thread.providerInstanceId !== selections[2]!.instanceId,
3179+
);
3180+
assert.lengthOf(kept, 2);
3181+
assert.strictEqual(
3182+
kept.find((thread) => thread.providerInstanceId === selections[0]!.instanceId)
3183+
?.providerSessionId,
3184+
unrelated.providerThreads[0]?.providerSessionId,
3185+
"the unrelated thread shares the first account's runtime",
3186+
);
3187+
3188+
// A plain interrupt of the failed run still has no turn to interrupt.
3189+
const plain = yield* orchestrator
3190+
.dispatch({
3191+
type: "run.interrupt",
3192+
commandId: CommandId.make("command:stop-after-failed-switch-start:interrupt"),
3193+
threadId,
3194+
runId: failed.runs[2]!.id,
3195+
})
3196+
.pipe(Effect.exit);
3197+
assert.isTrue(plain._tag === "Failure");
3198+
yield* worker.drain();
3199+
assert.deepStrictEqual(yield* Ref.get(interrupts), []);
3200+
3201+
yield* orchestrator.dispatch({
3202+
type: "thread.stop",
3203+
commandId: CommandId.make("command:stop-after-failed-switch-start:stop"),
3204+
threadId,
3205+
});
3206+
yield* worker.drain();
3207+
const sent = yield* Ref.get(interrupts);
3208+
assert.sameMembers(
3209+
sent.map((interrupt) => interrupt.providerThread.id),
3210+
kept.map((thread) => thread.id),
3211+
"Stop never reached the older kept sessions",
3212+
);
3213+
assert.isTrue(sent.every((interrupt) => interrupt.requestRuntimeRestart === true));
3214+
assert.deepStrictEqual(yield* Ref.get(busy), [unrelatedProviderThreadId]);
3215+
const stopped = yield* orchestrator.getThreadProjection(threadId);
3216+
assert.isTrue(
3217+
stopped.turnItems.some(
3218+
(item) =>
3219+
item.runId === failed.runs[2]!.id && item.type === "run_interrupt_request",
3220+
),
3221+
);
3222+
}).pipe(
3223+
Effect.provide(
3224+
ProviderReplayHarness.layerWithRegistry(
3225+
{
3226+
name: "stop-after-failed-switch-start",
3227+
runtimePolicyOverride: {
3228+
cwd,
3229+
approvalPolicy: "never",
3230+
sandboxPolicy: {
3231+
type: "readOnly",
3232+
access: { type: "fullAccess" },
3233+
networkAccess: false,
3234+
},
3235+
},
3236+
},
3237+
ProviderAdapterRegistry.layerFromAdapters(adapters),
3238+
),
3239+
),
3240+
);
3241+
}),
3242+
),
3243+
);
3244+
30583245
it.live.each(["immediately", "behind a running turn"] as const)(
30593246
"starts a fresh provider session %s and never hands earlier runs to a later provider",
30603247
(variant) =>

0 commit comments

Comments
 (0)