fix: preserve thread management failure semantics

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-08-15 16:50:19 +02:00
1 parent e77b08358d
commit f5d80b1d16
6 files changed
+366 -112

No files matched your search

+31 -25
View File
@@ -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<OrchestrationV2ThreadProjection, OrchestratorMcpFailure> =>
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") {
@@ -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":
@@ -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));
});
@@ -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>()(
"ThreadManagementError",
export class ThreadManagementThreadNotFoundError extends Schema.TaggedErrorClass<ThreadManagementThreadNotFoundError>()(
"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>()(
"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>()(
"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>()(
"ThreadManagementThreadNotInterruptibleError",
{
threadId: ThreadId,
runId: RunId,
},
) {
override get message(): string {
return `Run ${this.runId} is not currently interruptible.`;
}
}
export class ThreadManagementProjectionLoadError extends Schema.TaggedErrorClass<ThreadManagementProjectionLoadError>()(
"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>()(
"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>()(
"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",
@@ -27,6 +27,30 @@ function assertUnique(values: ReadonlyArray<string>, 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;
@@ -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}` });