diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index b495293bc2228..e32562e09626f 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -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, @@ -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", diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 60c6fdd94784f..03894cb722a84 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -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"; @@ -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"; @@ -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; }) { const record = (event: string) => Ref.update(input.events, (events) => [...events, event]); const layerDependencies = Layer.mergeAll( @@ -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 } : {}, ), @@ -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) => + it.effect(name, () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const instanceId = ProviderInstanceId.make("codex"); + const events = yield* Ref.make>([]); + 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, + [], +); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 340e322f3e0a2..34f6e258aaf86 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -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"; @@ -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); @@ -39,6 +40,7 @@ export class OrchestrationEffectExecutionError extends Schema.TaggedError + 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({ + sequence: 0, + storedEvents: [], + }), + ), + ); return OrchestrationEffectExecutorV2.of({ execute: Effect.fn("OrchestrationEffectExecutorV2.execute")(function (effect, options) { const willRetry = options?.willRetry ?? false; @@ -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 diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c280fae6dbc2f..069ec9441a054 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -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"; @@ -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)) @@ -2680,6 +2725,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: { ...run, queueHeld: true }, })), + holdRetryEffect, ); return wakes.length > 0; } diff --git a/apps/server/src/orchestration-v2/QueueHoldResume.ts b/apps/server/src/orchestration-v2/QueueHoldResume.ts new file mode 100644 index 0000000000000..087b701958e12 --- /dev/null +++ b/apps/server/src/orchestration-v2/QueueHoldResume.ts @@ -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, + }), +});