From f5d80b1d16ebaa4613ccc8d752df43c576c2d80f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 29 Jul 2026 20:06:43 +0200 Subject: [PATCH] fix: preserve thread management failure semantics Co-authored-by: codex --- apps/server/src/mcp/OrchestratorMcpService.ts | 56 ++-- .../server/src/mcp/WorktreeMcpService.test.ts | 8 +- .../ThreadManagementService.test.ts | 140 +++++++++- .../ThreadManagementService.ts | 249 ++++++++++++------ ...rchestratorReplayFixtures.contract.test.ts | 24 ++ .../testkit/fixtures/shared.ts | 1 + 6 files changed, 366 insertions(+), 112 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 5149db9346..e4edce171a 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -159,6 +159,23 @@ function failure(code: OrchestratorMcpFailure["code"], message: string): Orchest return new OrchestratorMcpFailure({ code, message }); } +function threadManagementFailure(error: ThreadManagementError): OrchestratorMcpFailure { + switch (error._tag) { + case "ThreadManagementThreadNotFoundError": + return failure("thread_not_found", error.message); + case "ThreadManagementRunNotFoundError": + return failure("run_not_found", error.message); + case "ThreadManagementThreadNotSendableError": + return failure("thread_not_sendable", error.message); + case "ThreadManagementThreadNotInterruptibleError": + return failure("thread_not_interruptible", error.message); + case "ThreadManagementProjectionLoadError": + case "ThreadManagementProjectThreadsListError": + case "ThreadManagementDurableRunProjectionError": + return failure("orchestration_error", error.message); + } +} + function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -639,11 +656,7 @@ const make = Effect.gen(function* () { ): Effect.Effect => threadManagement .getProjectThread({ projectId, threadId }) - .pipe( - Effect.mapError(() => - failure("thread_not_found", `Thread ${threadId} was not found in the calling project.`), - ), - ); + .pipe(Effect.mapError(threadManagementFailure)); const loadScopedThread = (scope: McpInvocationScope, threadId: ThreadId) => Effect.gen(function* () { @@ -1455,10 +1468,12 @@ const make = Effect.gen(function* () { }) .pipe( Effect.mapError((error) => - failure( - "thread_not_sendable", - `Unable to send to thread ${input.threadId}: ${errorMessage(error)}`, - ), + isThreadManagementError(error) + ? threadManagementFailure(error) + : failure( + "orchestration_error", + `Unable to send to thread ${input.threadId}: ${errorMessage(error)}`, + ), ), ); return { @@ -1482,14 +1497,7 @@ const make = Effect.gen(function* () { Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), ), }) - .pipe( - Effect.mapError((error) => - failure( - error.code === "run_not_found" ? "run_not_found" : "orchestration_error", - error.message, - ), - ), - ); + .pipe(Effect.mapError(threadManagementFailure)); return { threadId: input.threadId, runId: result.run?.id ?? null, @@ -1515,14 +1523,12 @@ const make = Effect.gen(function* () { }) .pipe( Effect.mapError((error) => - failure( - isThreadManagementError(error) && error.code === "run_not_found" - ? "run_not_found" - : "thread_not_interruptible", - isThreadManagementError(error) - ? error.message - : `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`, - ), + isThreadManagementError(error) + ? threadManagementFailure(error) + : failure( + "orchestration_error", + `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`, + ), ), ); if (result.type === "no_active_run") { diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index 6adf039731..5a524093f8 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -26,8 +26,8 @@ import { OrchestratorProjectionError, } from "../orchestration-v2/Orchestrator.ts"; import { - ThreadManagementError, ThreadManagementService, + ThreadManagementThreadNotSendableError, type ThreadManagementSendResult, } from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../project/ProjectService.ts"; @@ -177,9 +177,9 @@ const makeHarness = (options: HarnessOptions = {}) => { switch (options.continuation ?? "queued") { case "fails": return Effect.fail( - new ThreadManagementError({ - code: "thread_not_sendable", - message: "simulated send failure", + new ThreadManagementThreadNotSendableError({ + threadId, + reason: { _tag: "Archived" }, }), ); case "dies": diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 96f18d30f0..5e7187d9c3 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -1,15 +1,32 @@ import { expect, it } from "@effect/vitest"; import { CommandId, + MessageId, NodeId, type OrchestrationV2Command, + type OrchestrationV2ThreadProjection, ProjectId, ProviderInstanceId, RunId, ThreadId, } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; -import { existingThreadIdsForCommand, withCreationProvenance } from "./ThreadManagementService.ts"; +import { OrchestratorProjectionError, OrchestratorV2 } from "./Orchestrator.ts"; +import { + existingThreadIdsForCommand, + layer, + ThreadManagementDurableRunProjectionError, + ThreadManagementProjectThreadsListError, + ThreadManagementProjectionLoadError, + ThreadManagementRunNotFoundError, + ThreadManagementService, + ThreadManagementThreadNotFoundError, + ThreadManagementThreadNotInterruptibleError, + ThreadManagementThreadNotSendableError, + withCreationProvenance, +} from "./ThreadManagementService.ts"; it("stamps authoritative provenance on commands that create threads or messages", () => { const command: OrchestrationV2Command = { @@ -161,3 +178,124 @@ it("identifies every existing thread that must be hydrated before dispatch", () }), ).toEqual([parentThreadId, targetThreadId]); }); + +it("derives thread management messages from structural error attributes", () => { + const projectId = ProjectId.make("project:thread-management:errors"); + const threadId = ThreadId.make("thread:thread-management:errors"); + const runId = RunId.make("run:thread-management:errors"); + const messageId = MessageId.make("message:thread-management:errors"); + const infrastructureCause = new Error("private sqlite detail"); + + const threadNotFound = new ThreadManagementThreadNotFoundError({ + projectId, + threadId, + }); + expect(threadNotFound).toMatchObject({ projectId, threadId }); + expect(threadNotFound.message).toBe(`Thread ${threadId} was not found in project ${projectId}.`); + + const runNotFound = new ThreadManagementRunNotFoundError({ threadId, runId }); + expect(runNotFound).toMatchObject({ threadId, runId }); + expect(runNotFound.message).toBe(`Run ${runId} does not belong to thread ${threadId}.`); + + const archived = new ThreadManagementThreadNotSendableError({ + threadId, + reason: { _tag: "Archived" }, + }); + expect(archived).toMatchObject({ threadId, reason: { _tag: "Archived" } }); + expect(archived.message).toBe(`Thread ${threadId} is archived and cannot receive messages.`); + + const notSteerable = new ThreadManagementThreadNotSendableError({ + threadId, + reason: { _tag: "NoSteerableRun", mode: "restart" }, + }); + expect(notSteerable).toMatchObject({ + threadId, + reason: { _tag: "NoSteerableRun", mode: "restart" }, + }); + expect(notSteerable.message).toBe( + `Thread ${threadId} has no running turn that can be restarted.`, + ); + + const notInterruptible = new ThreadManagementThreadNotInterruptibleError({ + threadId, + runId, + }); + expect(notInterruptible).toMatchObject({ threadId, runId }); + expect(notInterruptible.message).toBe(`Run ${runId} is not currently interruptible.`); + + const listFailure = new ThreadManagementProjectThreadsListError({ + projectId, + cause: infrastructureCause, + }); + expect(listFailure).toMatchObject({ projectId, cause: infrastructureCause }); + expect(listFailure.message).toBe(`Unable to list threads in project ${projectId}.`); + expect(listFailure.message).not.toContain(infrastructureCause.message); + + const durableProjectionFailure = new ThreadManagementDurableRunProjectionError({ + threadId, + messageId, + }); + expect(durableProjectionFailure).toMatchObject({ threadId, messageId }); + expect(durableProjectionFailure.message).toBe( + `Message ${messageId} was accepted on thread ${threadId} without a durable run projection.`, + ); +}); + +it.effect("classifies projection infrastructure failures separately from a missing thread", () => { + const projectId = ProjectId.make("project:thread-management:projection-failure"); + const threadId = ThreadId.make("thread:thread-management:projection-failure"); + const infrastructureCause = new Error("sqlite read failed"); + const projectionError = new OrchestratorProjectionError({ + threadId, + cause: infrastructureCause, + }); + const testLayer = layer.pipe( + Layer.provide( + Layer.mock(OrchestratorV2)({ + getThreadProjection: () => Effect.fail(projectionError), + }), + ), + ); + + return Effect.gen(function* () { + const service = yield* ThreadManagementService; + const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId })); + + expect(error).toBeInstanceOf(ThreadManagementProjectionLoadError); + expect(error).toMatchObject({ + projectId, + threadId, + cause: projectionError, + }); + expect(error.message).toBe(`Unable to load thread ${threadId} in project ${projectId}.`); + }).pipe(Effect.provide(testLayer)); +}); + +it.effect("uses thread-not-found only after a projection loads outside the project", () => { + const projectId = ProjectId.make("project:thread-management:requested"); + const otherProjectId = ProjectId.make("project:thread-management:other"); + const threadId = ThreadId.make("thread:thread-management:wrong-project"); + const projection = { + thread: { + id: threadId, + projectId: otherProjectId, + deletedAt: null, + }, + } as OrchestrationV2ThreadProjection; + const testLayer = layer.pipe( + Layer.provide( + Layer.mock(OrchestratorV2)({ + getThreadProjection: () => Effect.succeed(projection), + }), + ), + ); + + return Effect.gen(function* () { + const service = yield* ThreadManagementService; + const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId })); + + expect(error).toBeInstanceOf(ThreadManagementThreadNotFoundError); + expect(error).toMatchObject({ projectId, threadId }); + expect("cause" in error).toBe(false); + }).pipe(Effect.provide(testLayer)); +}); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 43a81cae14..e8b4cd60b9 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1,7 +1,7 @@ import { type ChatAttachment, type CommandId, - type MessageId, + MessageId, type ModelSelection, type OrchestrationV2Actor, type OrchestrationV2Command, @@ -12,9 +12,9 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadShell, type OrchestrationV2TurnItem, - type ProjectId, - type RunId, - type ThreadId, + ProjectId, + RunId, + ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -144,20 +144,113 @@ export type ThreadManagementInterruptResult = readonly run: OrchestrationV2Run & { readonly status: ThreadManagementTerminalRunStatus }; }; -export class ThreadManagementError extends Schema.TaggedErrorClass()( - "ThreadManagementError", +export class ThreadManagementThreadNotFoundError extends Schema.TaggedErrorClass()( + "ThreadManagementThreadNotFoundError", { - code: Schema.Literals([ - "thread_not_found", - "run_not_found", - "thread_not_sendable", - "thread_not_interruptible", - "orchestration_error", - ]), - message: Schema.String, - cause: Schema.optional(Schema.Defect()), + projectId: ProjectId, + threadId: ThreadId, }, -) {} +) { + override get message(): string { + return `Thread ${this.threadId} was not found in project ${this.projectId}.`; + } +} + +export class ThreadManagementRunNotFoundError extends Schema.TaggedErrorClass()( + "ThreadManagementRunNotFoundError", + { + threadId: ThreadId, + runId: RunId, + }, +) { + override get message(): string { + return `Run ${this.runId} does not belong to thread ${this.threadId}.`; + } +} + +const ThreadManagementThreadNotSendableReason = Schema.Union([ + Schema.TaggedStruct("Archived", {}), + Schema.TaggedStruct("NoSteerableRun", { + mode: Schema.Literals(["steer", "restart"]), + }), +]); + +export class ThreadManagementThreadNotSendableError extends Schema.TaggedErrorClass()( + "ThreadManagementThreadNotSendableError", + { + threadId: ThreadId, + reason: ThreadManagementThreadNotSendableReason, + }, +) { + override get message(): string { + switch (this.reason._tag) { + case "Archived": + return `Thread ${this.threadId} is archived and cannot receive messages.`; + case "NoSteerableRun": + return `Thread ${this.threadId} has no running turn that can be ${this.reason.mode === "steer" ? "steered" : "restarted"}.`; + } + } +} + +export class ThreadManagementThreadNotInterruptibleError extends Schema.TaggedErrorClass()( + "ThreadManagementThreadNotInterruptibleError", + { + threadId: ThreadId, + runId: RunId, + }, +) { + override get message(): string { + return `Run ${this.runId} is not currently interruptible.`; + } +} + +export class ThreadManagementProjectionLoadError extends Schema.TaggedErrorClass()( + "ThreadManagementProjectionLoadError", + { + projectId: ProjectId, + threadId: ThreadId, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Unable to load thread ${this.threadId} in project ${this.projectId}.`; + } +} + +export class ThreadManagementProjectThreadsListError extends Schema.TaggedErrorClass()( + "ThreadManagementProjectThreadsListError", + { + projectId: ProjectId, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Unable to list threads in project ${this.projectId}.`; + } +} + +export class ThreadManagementDurableRunProjectionError extends Schema.TaggedErrorClass()( + "ThreadManagementDurableRunProjectionError", + { + threadId: ThreadId, + messageId: MessageId, + }, +) { + override get message(): string { + return `Message ${this.messageId} was accepted on thread ${this.threadId} without a durable run projection.`; + } +} + +export const ThreadManagementError = Schema.Union([ + ThreadManagementThreadNotFoundError, + ThreadManagementRunNotFoundError, + ThreadManagementThreadNotSendableError, + ThreadManagementThreadNotInterruptibleError, + ThreadManagementProjectionLoadError, + ThreadManagementProjectThreadsListError, + ThreadManagementDurableRunProjectionError, +]); +export type ThreadManagementError = typeof ThreadManagementError.Type; type ThreadManagementFailure = ThreadManagementError | OrchestratorV2Error; @@ -254,18 +347,6 @@ export function latestSteerableRun( .toSorted((left, right) => right.ordinal - left.ordinal)[0]; } -function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); -} - -function managementError( - code: ThreadManagementError["code"], - message: string, - cause?: unknown, -): ThreadManagementError { - return new ThreadManagementError({ code, message, ...(cause === undefined ? {} : { cause }) }); -} - const make = Effect.gen(function* () { const orchestrator = yield* OrchestratorV2; const legacyImporter = yield* LegacyV1ThreadImporter; @@ -328,33 +409,34 @@ const make = Effect.gen(function* () { const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) => getThreadProjection(input.threadId).pipe( - Effect.mapError((cause) => - managementError( - "thread_not_found", - `Thread ${input.threadId} was not found in project ${input.projectId}.`, - cause, - ), + Effect.mapError( + (cause) => + new ThreadManagementProjectionLoadError({ + projectId: input.projectId, + threadId: input.threadId, + cause, + }), ), Effect.flatMap((projection) => projection.thread.projectId === input.projectId && projection.thread.deletedAt === null ? Effect.succeed(projection) : Effect.fail( - managementError( - "thread_not_found", - `Thread ${input.threadId} was not found in project ${input.projectId}.`, - ), + new ThreadManagementThreadNotFoundError({ + projectId: input.projectId, + threadId: input.threadId, + }), ), ), ); const listProjectThreads: ThreadManagementServiceShape["listProjectThreads"] = (input) => orchestrator.getShellSnapshot().pipe( - Effect.mapError((cause) => - managementError( - "orchestration_error", - `Unable to list threads in project ${input.projectId}: ${errorMessage(cause)}`, - cause, - ), + Effect.mapError( + (cause) => + new ThreadManagementProjectThreadsListError({ + projectId: input.projectId, + cause, + }), ), Effect.map((snapshot) => snapshot.threads @@ -375,10 +457,10 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const target = yield* getProjectThread(input); if (target.thread.archivedAt !== null) { - return yield* managementError( - "thread_not_sendable", - `Thread ${input.threadId} is archived and cannot receive messages.`, - ); + return yield* new ThreadManagementThreadNotSendableError({ + threadId: input.threadId, + reason: { _tag: "Archived" }, + }); } const steerableRun = latestSteerableRun(target); @@ -388,10 +470,10 @@ const make = Effect.gen(function* () { >["dispatchMode"]; if (input.mode === "steer" || input.mode === "restart") { if (steerableRun === undefined) { - return yield* managementError( - "thread_not_sendable", - `Thread ${input.threadId} has no running turn that can be ${input.mode === "steer" ? "steered" : "restarted"}.`, - ); + return yield* new ThreadManagementThreadNotSendableError({ + threadId: input.threadId, + reason: { _tag: "NoSteerableRun", mode: input.mode }, + }); } dispatchMode = { type: input.mode === "steer" ? "steer_active" : "restart_active", @@ -430,10 +512,10 @@ const make = Effect.gen(function* () { candidate.type === "user_message" && candidate.messageId === input.messageId, ); if (message === undefined || run === undefined || turnItem === undefined) { - return yield* managementError( - "orchestration_error", - `Message ${input.messageId} was accepted without a durable run projection.`, - ); + return yield* new ThreadManagementDurableRunProjectionError({ + threadId: input.threadId, + messageId: input.messageId, + }); } const delivery: ThreadManagementSendResult["delivery"] = turnItem.inputIntent === "turn_start" @@ -454,10 +536,10 @@ const make = Effect.gen(function* () { ? latestRun(target) : target.runs.find((candidate) => candidate.id === input.runId); if (input.runId !== undefined && selectedRun === undefined) { - return yield* managementError( - "run_not_found", - `Run ${input.runId} does not belong to thread ${input.threadId}.`, - ); + return yield* new ThreadManagementRunNotFoundError({ + threadId: input.threadId, + runId: input.runId, + }); } if (selectedRun === undefined) { return { threadId: input.threadId, run: null, timedOut: false }; @@ -471,10 +553,10 @@ const make = Effect.gen(function* () { const current = yield* getProjectThread(input); const run = current.runs.find((candidate) => candidate.id === selectedRun.id); if (run === undefined) { - return yield* managementError( - "run_not_found", - `Run ${selectedRun.id} no longer belongs to thread ${input.threadId}.`, - ); + return yield* new ThreadManagementRunNotFoundError({ + threadId: input.threadId, + runId: selectedRun.id, + }); } if (isTerminalRunStatus(run.status)) return run; yield* Effect.sleep(Duration.millis(Math.max(1, input.pollIntervalMs ?? 250))); @@ -487,10 +569,10 @@ const make = Effect.gen(function* () { const current = yield* getProjectThread(input); const run = current.runs.find((candidate) => candidate.id === selectedRun.id); if (run === undefined) { - return yield* managementError( - "run_not_found", - `Run ${selectedRun.id} no longer belongs to thread ${input.threadId}.`, - ); + return yield* new ThreadManagementRunNotFoundError({ + threadId: input.threadId, + runId: selectedRun.id, + }); } return { threadId: input.threadId, run, timedOut: true }; }); @@ -503,10 +585,10 @@ const make = Effect.gen(function* () { ? undefined : target.runs.find((candidate) => candidate.id === input.runId); if (input.runId !== undefined && explicitRun === undefined) { - return yield* managementError( - "run_not_found", - `Run ${input.runId} does not belong to thread ${input.threadId}.`, - ); + return yield* new ThreadManagementRunNotFoundError({ + threadId: input.threadId, + runId: input.runId, + }); } if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) { return { @@ -517,17 +599,20 @@ const make = Effect.gen(function* () { } as const; } const interruptibleRun = latestActiveRun(target); - if (input.runId === undefined && interruptibleRun === undefined) { - return { type: "no_active_run" } as const; + if (interruptibleRun === undefined) { + if (input.runId === undefined) { + return { type: "no_active_run" } as const; + } + return yield* new ThreadManagementThreadNotInterruptibleError({ + threadId: input.threadId, + runId: input.runId, + }); } - if ( - interruptibleRun === undefined || - (explicitRun !== undefined && interruptibleRun.id !== explicitRun.id) - ) { - return yield* managementError( - "thread_not_interruptible", - `Run ${explicitRun?.id ?? input.runId} is not currently interruptible.`, - ); + if (input.runId !== undefined && interruptibleRun.id !== input.runId) { + return yield* new ThreadManagementThreadNotInterruptibleError({ + threadId: input.threadId, + runId: input.runId, + }); } const dispatch = yield* orchestrator.dispatch({ type: "run.interrupt", diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts index 701b7bdb4c..2c09ef245a 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts @@ -27,6 +27,30 @@ function assertUnique(values: ReadonlyArray, label: string) { } describe("orchestrator replay fixture contract", () => { + it.effect("materializes queued fixture messages as queue-after-active dispatches", () => + Effect.gen(function* () { + const materialized = yield* materializeFixtureInput({ + scenario: "queued-message-dispatch-mode", + fixtureInput: { + steps: [ + { type: "message", text: "active run" }, + { type: "queue_message", text: "queued run" }, + ], + }, + driver: ProviderDriverKind.make("codex"), + modelSelection: CODEX_MODEL_SELECTION, + }); + const queuedCommand = materialized.commands.find( + (command) => command.type === "message.dispatch" && command.text === "queued run", + ); + + assert.isDefined(queuedCommand); + assert.deepInclude(queuedCommand, { + dispatchMode: { type: "queue_after_active" }, + }); + }).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime), + ); + it.effect("keeps message ordinals separate from app run ordinals after steering", () => Effect.gen(function* () { const idAllocator = yield* IdAllocatorV2; diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index 31c177a223..009c916077 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -487,6 +487,7 @@ export function materializeFixtureInput(input: { }), text: step.text, ...(step.attachments === undefined ? {} : { attachments: step.attachments }), + dispatchMode: { type: "queue_after_active" }, }), ); steps.push({ type: "await", key: `run:${runIndex - 1}` });