Skip to content
Open
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
6 changes: 6 additions & 0 deletions apps/server/src/orchestration-v2/EffectOutbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
/** Set when the provider process exited under a live server; absent means a server restart. */
cause: Schema.optional(Schema.Literal("provider_exit")),
}),
Schema.Struct({
type: Schema.Literal("queue-hold.retry"),
attempt: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
failedRunId: Schema.optional(RunId),
}),
Schema.Struct({
type: Schema.Literal("provider-session.detach"),
providerSessionId: ProviderSessionId,
Expand Down Expand Up @@ -146,6 +151,7 @@ export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
"provider-session.detach",
"provider-thread.rollback",
"checkpoint.capture",
"queue-hold.retry",
"scheduled-tasks.cleanup",
"terminal.cleanup",
"preview.cleanup",
Expand Down
83 changes: 82 additions & 1 deletion apps/server/src/orchestration-v2/EffectWorker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
ThreadId,
VcsProcessExitError,
type OrchestrationV2ThreadProjection,
type OrchestrationV2Run,
MessageId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
Expand All @@ -33,6 +35,7 @@ import * as TestClock from "effect/testing/TestClock";
import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
import * as CheckpointService from "./CheckpointService.ts";
import * as EffectOutbox from "./EffectOutbox.ts";
import { QUEUE_HOLD_RETRY_DELAYS_MS } from "./QueueHoldResume.ts";
import * as EffectWorker from "./EffectWorker.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as RunFinalizationService from "./RunFinalizationService.ts";
Expand Down Expand Up @@ -93,6 +96,7 @@ function layerExecutorFor(input: {
readonly interrupt?: ProviderTurnControlService.ProviderTurnControlServiceV2Shape["interrupt"];
readonly rollback?: CheckpointRollbackService.CheckpointRollbackServiceV2Shape["execute"];
readonly respond?: RuntimeRequestService.RuntimeRequestServiceV2["Service"]["respond"];
readonly heldQueuedRuns?: ReadonlyArray<OrchestrationV2Run>;
}) {
const record = (event: string) => Ref.update(input.events, (events) => [...events, event]);
const layerDependencies = Layer.mergeAll(
Expand Down Expand Up @@ -175,7 +179,9 @@ function layerExecutorFor(input: {
Layer.mergeAll(
layerDependencies,
Layer.mock(ThreadManagementService.ThreadManagementService)(input.threads ?? {}),
Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getHeldQueuedRuns: () => Effect.succeed(input.heldQueuedRuns ?? []),
}),
ServerSettings.layerTest(
input.continueAfterRestart === true ? { continueThreadsAfterServerUpdate: true } : {},
),
Expand Down Expand Up @@ -839,3 +845,78 @@ it.effect.each([3, 4])(
);
}),
);
const holdRetryEffect = (attempt: number): EffectOutbox.OrchestrationEffectV2 => {
const iso = new Date(0).toISOString();
return {
id: `effect:queue-hold-retry:${threadId}:${attempt}`,
commandId: CommandId.make(`command:queue-hold-retry:${threadId}:${attempt}`),
threadId,
request: { type: "queue-hold.retry", attempt },
status: "running",
attemptCount: 1,
availableAt: iso,
leaseOwner: "test-worker",
createdAt: iso,
updatedAt: iso,
completedAt: null,
lastError: null,
};
};

const holdTest = (name: string, heldCount: number, expect: ReadonlyArray<string>) =>
it.effect(name, () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const instanceId = ProviderInstanceId.make("codex");
const events = yield* Ref.make<ReadonlyArray<string>>([]);
const held: OrchestrationV2Run[] = [
{
id: RunId.make("run:held-queued"),
threadId,
ordinal: 1,
providerInstanceId: instanceId,
modelSelection: { instanceId, model: "model:test" },
providerThreadId,
userMessageId: MessageId.make("message:held-queued"),
rootNodeId: null,
activeAttemptId: null,
status: "queued" as const,
queueHeld: true,
requestedAt: now,
startedAt: null,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
},
];
const layer = layerExecutorFor({
events,
heldQueuedRuns: held.slice(0, heldCount),
threads: {
dispatch: (command) =>
Ref.update(events, (current) => [...current, command.type]).pipe(
Effect.as({ sequence: 1, storedEvents: [] }),
),
},
});
const result = yield* Effect.gen(function* () {
const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
return yield* Effect.exit(
executor.execute(holdRetryEffect(QUEUE_HOLD_RETRY_DELAYS_MS.length)),
);
}).pipe(Effect.provide(layer));
assert.isTrue(Exit.isSuccess(result));
assert.deepEqual(yield* Ref.get(events), expect);
}),
);

holdTest(
"a held-queue retry resumes the queue the way a user's Resume does",
1,
["queue.resume"],
);
holdTest(
"a released hold on the final attempt stays silent",
0,
[],
);
46 changes: 45 additions & 1 deletion apps/server/src/orchestration-v2/EffectWorker.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CommandId, type RunId } from "@t3tools/contracts";
import { CommandId, type ThreadId, type RunId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
Expand All @@ -25,6 +25,7 @@ import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationServic
import * as ThreadManagementService from "./ThreadManagementService.ts";
import * as ServerSettings from "../serverSettings.ts";
import { continueRestartedRun } from "./RestartContinuation.ts";
import type * as Orchestrator from "./Orchestrator.ts";

const isProviderTurnControlError = Schema.is(ProviderTurnControlService.ProviderTurnControlError);

Expand All @@ -39,6 +40,7 @@ export class OrchestrationEffectExecutionError extends Schema.TaggedError<Orches

const isOrchestrationEffectExecutionError = Schema.is(OrchestrationEffectExecutionError);


/**
* Do not apply this to `provider-turn.restart`: that compound effect also runs
* detach and start. Swallowing a start failure that happens to mention
Expand Down Expand Up @@ -147,6 +149,33 @@ export const layerExecutor: Layer.Layer<
),
),
);
// A queue held by a provider failure gets `queue-hold.retry` effects on the
// QUEUE_HOLD_RETRY_DELAYS_MS ladder (enqueued at the hold site in the orchestrator). Each
// retry clears the holds the way a user's Resume does and starts the queue again; the
// next failure re-holds and, past the ladder, waits for a person.
const retryHeldQueueStart = (input: {
readonly threadId: ThreadId;
readonly attempt: number;
readonly failedRunId: RunId | undefined;
}) =>
projectionStore.getHeldQueuedRuns(input.threadId).pipe(
Effect.flatMap((held) =>
held.length > 0
? threads.dispatch({
type: "queue.resume" as const,
commandId: CommandId.make(
`command:system:queue-hold-retry:${input.threadId}:${input.attempt}`,
),
threadId: input.threadId,
})
: // The hold released while this retry waited: a user's Resume or a newer run got
// there first, so there is nothing left to resume and the retry is a no-op.
Effect.succeed<Orchestrator.OrchestratorV2DispatchResult>({
sequence: 0,
storedEvents: [],
}),
),
);
return OrchestrationEffectExecutorV2.of({
execute: Effect.fn("OrchestrationEffectExecutorV2.execute")(function (effect, options) {
const willRetry = options?.willRetry ?? false;
Expand Down Expand Up @@ -240,6 +269,21 @@ export const layerExecutor: Layer.Layer<
}),
),
);
case "queue-hold.retry":
return retryHeldQueueStart({
threadId: effect.threadId,
attempt: effect.request.attempt,
failedRunId: effect.request.failedRunId,
}).pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "provider-turn.interrupt": {
const request = effect.request;
return providerTurnControl
Expand Down
46 changes: 46 additions & 0 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,11 @@ import {
type GuestShareCommand,
} from "./GuestShareDecider.ts";
import * as EffectOutbox from "./EffectOutbox.ts";
import {
QUEUE_HOLD_RETRY_DELAYS_MS,
queueHoldRetryEffect,
queueHoldRetryEffectId,
} from "./QueueHoldResume.ts";
import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
Expand Down Expand Up @@ -2669,6 +2674,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
});
const now = yield* DateTime.now;
// A hold the provider caused gets its own retries before it waits for a person: a
// transient provider error holds a queue that would start fine 30 seconds later. The
// attempt count reads the deterministic effect ids, so a re-hold after a failed retry
// climbs the ladder instead of restarting it; past the ladder the hold is a person's.
const rootFailure =
failedRun && failedRunId !== undefined && failedRun.id === failedRunId
? latestRootProviderFailure(failedRun, projection.turnItems)
: null;
let holdRetries: number | undefined;
if (providerFailed) {
holdRetries = QUEUE_HOLD_RETRY_DELAYS_MS.length + 1;
for (let attempt = 1; attempt <= QUEUE_HOLD_RETRY_DELAYS_MS.length; attempt++) {
const existing = yield* effectOutbox.get(queueHoldRetryEffectId(threadId, attempt));
if (Option.isNone(existing)) {
holdRetries = attempt;
break;
}
}
}
const holdRetryEffect =
providerFailed &&
rootFailure !== null &&
rootFailure.retryable !== false &&
(rootFailure.class === "provider_error" ||
rootFailure.class === "transport_error" ||
rootFailure.class === "unknown") &&
holdRetries !== undefined &&
holdRetries <= QUEUE_HOLD_RETRY_DELAYS_MS.length
? [
queueHoldRetryEffect({
threadId,
failedRunId,
attempt: holdRetries,
now,
commandId: CommandId.make(
`command:system:queue-hold-retry:${threadId}:${holdRetries}`,
),
}),
]
: [];
yield* writeSystemEvents(
projection.runs
.filter((run) => run.status === "queued" && !wakes.some((wake) => wake.id === run.id))
Expand All @@ -2680,6 +2725,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
occurredAt: now,
payload: { ...run, queueHeld: true },
})),
holdRetryEffect,
);
return wakes.length > 0;
}
Expand Down
37 changes: 37 additions & 0 deletions apps/server/src/orchestration-v2/QueueHoldResume.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { CommandId, type RunId, type ThreadId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";

/**
* A provider-failure hold leaves the queue waiting for a person. A held queue after a
* transient provider error waits for nobody: these retries re-attempt the start the way
* `retryContinuationStart` retries a cut continuation, then leave the hold for the user.
*/
export const QUEUE_HOLD_RETRY_DELAYS_MS = [30_000, 120_000, 300_000];

export const queueHoldRetryEffectId = (threadId: ThreadId, attempt: number) =>
`effect:queue-hold-retry:${threadId}:${attempt}`;

/**
* The retry effect for a queue this command just held on a provider failure. The caller
* counts the attempts already spent on this hold (the effect ids are deterministic) and
* passes the next one; past the ladder the hold waits for a person, as designed.
*/
export const queueHoldRetryEffect = (input: {
readonly threadId: ThreadId;
readonly failedRunId: RunId | undefined;
readonly attempt: number;
readonly now: DateTime.Utc;
readonly commandId: CommandId;
}) => ({
id: queueHoldRetryEffectId(input.threadId, input.attempt),
commandId: input.commandId,
threadId: input.threadId,
request: {
type: "queue-hold.retry" as const,
attempt: input.attempt,
...(input.failedRunId === undefined ? {} : { failedRunId: input.failedRunId }),
},
availableAt: DateTime.add(input.now, {
milliseconds: QUEUE_HOLD_RETRY_DELAYS_MS[input.attempt - 1] as number,
}),
});
Loading