From 371b40e014f9f5c1edd5cd21dc60ecf89d850f0e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 29 Jul 2026 05:24:06 +0200 Subject: [PATCH] fix(orchestrator): close cancellation edge cases Co-authored-by: codex --- .../src/orchestration-v2/EffectWorker.test.ts | 69 +++++++++++++++++++ .../src/orchestration-v2/EffectWorker.ts | 10 ++- .../src/provider/acp/XAiAcpExtension.test.ts | 4 +- .../src/provider/acp/XAiAcpExtension.ts | 6 +- 4 files changed, 81 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index baa74c883e..6fab8a9576 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -10,6 +10,7 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; @@ -251,6 +252,74 @@ it.effect("requeues a claim when a pre-execution worker check fails", () => }), ); +it.effect("arms cancellation before the durable pre-execution check", () => + Effect.gen(function* () { + const now = DateTime.formatIso(yield* DateTime.now); + const effectId = "effect:worker-cancellation-registration-race"; + const workerId = "worker-cancellation-registration-race"; + const claimedEffect: OrchestrationEffectV2 = { + id: effectId, + commandId: CommandId.make("command:worker-cancellation-registration-race"), + threadId: ThreadId.make("thread:worker-cancellation-registration-race"), + request: { type: "terminal.cleanup" }, + status: "running", + attemptCount: 1, + availableAt: now, + leaseOwner: workerId, + leaseExpiresAt: now, + createdAt: now, + updatedAt: now, + completedAt: null, + lastError: null, + }; + const signal = yield* Deferred.make(); + let cancellationArmed = false; + const executionCount = yield* Ref.make(0); + const settlementCount = yield* Ref.make(0); + const outboxLayer = Layer.mock(EffectOutboxV2)({ + claimNext: () => Effect.succeed(Option.some(claimedEffect)), + awaitCancellation: () => { + cancellationArmed = true; + return Deferred.await(signal); + }, + get: () => + Effect.gen(function* () { + // Model a cancellation commit immediately after this durable read + // took its snapshot. Its process-local signal is only delivered when + // the worker registered the waiter before starting the read. + if (cancellationArmed) { + yield* Deferred.succeed(signal, undefined); + } + return Option.some(claimedEffect); + }), + clearCancellation: () => Effect.void, + succeed: () => Ref.update(settlementCount, (count) => count + 1).pipe(Effect.as(true)), + }); + const executorLayer = Layer.succeed( + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2.of({ + execute: () => + Effect.yieldNow.pipe(Effect.andThen(Ref.update(executionCount, (count) => count + 1))), + }), + ); + const workerLayer = effectWorkerLayerWithOptions({ workerId }).pipe( + Layer.provide(Layer.merge(outboxLayer, executorLayer)), + ); + + const exit = yield* OrchestrationEffectWorkerV2.pipe( + Effect.flatMap((worker) => worker.runOnce), + Effect.provide(workerLayer), + Effect.exit, + ); + + if (Exit.isFailure(exit)) { + assert.fail(Cause.pretty(exit.cause)); + } + assert.equal(yield* Ref.get(executionCount), 0); + assert.equal(yield* Ref.get(settlementCount), 0); + }), +); + it.effect("terminalizes a process-bound claim when success settlement fails", () => Effect.gen(function* () { const now = DateTime.formatIso(yield* DateTime.now); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index fd932da03b..b6d4c7c4ae 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -442,6 +442,13 @@ export const layerWithOptions = ( return false; } const effect = claimed.value; + // Arm the process-local cancellation signal before re-reading durable + // state. A cancellation that commits after the row read has begun can + // then still win the execution race instead of falling into the gap + // between the read and signal registration. + const cancellation = outbox + .awaitCancellation(effect.id) + .pipe(Effect.as("cancelled" as const)); const cancelledBeforeExecution = yield* Effect.gen(function* () { const claimedAt = DateTime.toEpochMillis(yield* DateTime.now); const eligibleAt = Math.max( @@ -468,9 +475,6 @@ export const layerWithOptions = ( if (cancelledBeforeExecution) return true; const execution = executor.execute(effect).pipe(Effect.as("executed" as const)); - const cancellation = outbox - .awaitCancellation(effect.id) - .pipe(Effect.as("cancelled" as const)); const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe( Effect.ensuring(outbox.clearCancellation(effect.id)), ); diff --git a/apps/server/src/provider/acp/XAiAcpExtension.test.ts b/apps/server/src/provider/acp/XAiAcpExtension.test.ts index 77ed674147..00efee078d 100644 --- a/apps/server/src/provider/acp/XAiAcpExtension.test.ts +++ b/apps/server/src/provider/acp/XAiAcpExtension.test.ts @@ -725,7 +725,7 @@ describe("XAiAcpExtension", () => { ]); }); - it("tombstones tasks the model kills via kill_command_or_subagent", () => { + it("tombstones confirmed kills and ignores failed kill calls", () => { expect( extractXAiKilledBackgroundTasks({ toolCallId: "call-kill-1", @@ -750,7 +750,7 @@ describe("XAiAcpExtension", () => { status: "failed", data: { rawInput: { variant: "kill", task_id: "call-bg-3" } }, }), - ).toEqual([{ taskId: "call-bg-3", status: "completed", appendOutput: "" }]); + ).toEqual([]); // In-flight kill calls and unrelated tools contribute nothing. expect( extractXAiKilledBackgroundTasks({ diff --git a/apps/server/src/provider/acp/XAiAcpExtension.ts b/apps/server/src/provider/acp/XAiAcpExtension.ts index 1e05248b22..ae2ab7b277 100644 --- a/apps/server/src/provider/acp/XAiAcpExtension.ts +++ b/apps/server/src/provider/acp/XAiAcpExtension.ts @@ -334,8 +334,8 @@ export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState): /** * A finished kill_command_or_subagent call is the genuine end signal for every * task id it names: the Grok CLI emits no `x.ai/task_completed` for a killed - * task. A failed kill usually means the task was already gone, so it ends the - * id too (failing open to a continuation beats pinning the running set). + * task. A failed kill is not proof the target stopped, so leave the existing + * task state unchanged until a genuine terminal signal arrives. */ export function extractXAiKilledBackgroundTasks(toolCall: AcpToolCallState): ReadonlyArray<{ readonly taskId: string; @@ -346,7 +346,7 @@ export function extractXAiKilledBackgroundTasks(toolCall: AcpToolCallState): Rea const rawInput = unknownRecord(toolCall.data.rawInput); const variant = nonEmptyString(rawInput?.variant)?.toLowerCase(); if (!title.includes("kill_command_or_subagent") && variant !== "kill") return []; - if (toolCall.status !== "completed" && toolCall.status !== "failed") return []; + if (toolCall.status !== "completed") return []; const taskIds: string[] = []; const push = (value: unknown) => { const id = nonEmptyString(value);