TypeScript
fix(server): persist run failures after storage recovers (#19646)
Alb11747801dbf6b84e8
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.tsindex 019bd77bb68..38bc09c25cb 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts@@ -36,6 +36,7 @@ import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";+import * as Logger from "effect/Logger";import * as Option from "effect/Option";import * as Ref from "effect/Ref";import * as Stream from "effect/Stream";@@ -4104,6 +4105,230 @@ it.effect("keeps completed runs completed when pull request refresh fails", () =}),);+it.effect(+ "recovers ingestion failure through typed errors and defects with bounded backoff",+ () => {+ const warnings: Array<unknown> = [];+ const logger = Logger.make(({ message }) => {+ const text = Array.isArray(message) ? message[0] : message;+ if (text === "orchestration V2 run failure finalization retry") warnings.push(text);+ });+ return Effect.gen(function* () {+ const failIngestion = yield* Deferred.make<void>();+ const failedWrite = yield* Deferred.make<void>();+ const writeTimes: Array<number> = [];+ let storageAvailable = false;+ let failedAt = yield* DateTime.now;+ const { finalEvents, observed, written } = yield* captureRootRunTermination({+ key: "recovery-backoff",+ shouldFinalizeRun: () => Effect.succeed(true),+ ingestNormalized: () =>+ Deferred.await(failIngestion).pipe(Effect.andThen(Effect.die("ingestion failed"))),+ beforeTerminalWrite: () =>+ Effect.gen(function* () {+ writeTimes.push(DateTime.toEpochMillis(yield* DateTime.now));+ if (storageAvailable) return true;+ yield* Deferred.succeed(failedWrite, undefined);+ const error = new EventSink.EventSinkWriteError({ eventCount: 5 });+ return yield* writeTimes.length % 2 === 1 ? Effect.fail(error) : Effect.die(error);+ }),+ afterStart: () =>+ Effect.gen(function* () {+ // Separate startup, ingestion failure, and eventual storage recovery.+ yield* TestClock.adjust("5 seconds");+ failedAt = yield* DateTime.now;+ yield* Deferred.succeed(failIngestion, undefined);+ yield* Deferred.await(failedWrite);+ yield* TestClock.adjust("999 millis");+ assert.lengthOf(writeTimes, 1);+ yield* TestClock.adjust("1 millis");+ assert.lengthOf(writeTimes, 2);+ assert.lengthOf(warnings, 1);+ yield* TestClock.adjust("598999 millis");+ const offsets = writeTimes.map((time) => time - DateTime.toEpochMillis(failedAt));+ assert.deepEqual(offsets, [+ 0,+ 1000,+ 3000,+ 7000,+ 15000,+ 31000,+ ...Array.from({ length: 18 }, (_, index) => 61000 + index * 30000),+ ]);+ assert.lengthOf(warnings, 1);+ yield* TestClock.adjust("1001 millis");+ assert.lengthOf(warnings, 2);+ storageAvailable = true;+ yield* TestClock.adjust("30 seconds");+ }),+ });+ assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]);+ assert.lengthOf(warnings, 2);+ assert.sameMembers(+ finalEvents.map((event) => event.type),+ [+ "run-attempt.updated",+ "turn-item.updated",+ "run.updated",+ "node.updated",+ "provider-thread.updated",+ ],+ );+ for (const event of finalEvents) {+ assert.deepEqual(event.occurredAt, failedAt);+ if (+ event.type === "run.updated" ||+ event.type === "run-attempt.updated" ||+ event.type === "node.updated"+ ) {+ assert.equal(event.payload.status, "failed");+ assert.deepEqual(event.payload.completedAt, failedAt);+ }+ if (event.type === "provider-thread.updated")+ assert.deepEqual(event.payload.updatedAt, failedAt);+ }+ assert.lengthOf(written, 1);+ assert.equal(written[0]?.type, "error");+ assert.deepEqual(written[0]?.completedAt, failedAt);+ if (written[0]?.type === "error")+ assert.equal(written[0].failure.message, "Provider turn failed.");+ }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));+ },+);++it.effect("stops recovery when the atomic gate rejects a superseded attempt", () =>+ Effect.gen(function* () {+ const key = "recovery-successor";+ const ids = backgroundScenarioIds(key);+ const failedWrite = yield* Deferred.make<void>();+ let activeAttemptId = ids.attemptId;+ let writes = 0;+ const { finalEvents, observed, written } = yield* captureRootRunTermination({+ key,+ shouldFinalizeRun: () => Effect.succeed(true),+ ingestNormalized: () => Effect.die("ingestion failed"),+ beforeTerminalWrite: (request) =>+ Effect.gen(function* () {+ writes++;+ assert.equal(request.runId, ids.runId);+ assert.equal(request.activeAttemptId, ids.attemptId);+ assert.equal(request.expectedStatus, "running");+ if (writes > 1) return request.activeAttemptId === activeAttemptId;+ yield* Deferred.succeed(failedWrite, undefined);+ return yield* new EventSink.EventSinkWriteError({ eventCount: 5 });+ }),+ afterStart: () =>+ Effect.gen(function* () {+ yield* Deferred.await(failedWrite);+ activeAttemptId = RunAttemptId.make("attempt:successor");+ yield* TestClock.adjust("1 second");+ assert.equal(writes, 2);+ yield* TestClock.adjust("10 minutes");+ assert.equal(writes, 2);+ }),+ });+ assert.deepEqual(finalEvents, []);+ assert.deepEqual(written, []);+ assert.deepEqual(observed, []);+ }),+);++it.effect.each([true, false])(+ "keeps recovery alive after startup cancels its consumer (startup terminal persisted: %s)",+ (startupPersisted) =>+ Effect.gen(function* () {+ const failedWrite = yield* Deferred.make<void>();+ let writes = 0;+ let status: OrchestrationV2Run["status"] = "running";+ const { observed, finalEvents, written } = yield* captureRootRunTermination({+ key: `recovery-startup:${startupPersisted}`,+ shouldFinalizeRun: () => Effect.succeed(true),+ ingestNormalized: () => Effect.die("ingestion failed"),+ beforeTerminalWrite: (request) =>+ Effect.gen(function* () {+ writes++;+ if (writes === 1 || (writes === 2 && !startupPersisted)) {+ yield* Deferred.succeed(failedWrite, undefined);+ return yield* new EventSink.EventSinkWriteError({ eventCount: 5 });+ }+ if (request.expectedStatus !== status) return false;+ status = "failed";+ return true;+ }),+ startTurn: (input) =>+ Deferred.await(failedWrite).pipe(+ Effect.andThen(+ Effect.fail(+ new ProviderAdapter.ProviderAdapterTurnStartError({+ driver,+ threadId: input.threadId,+ providerThreadId: input.providerThread.id,+ runId: input.runId,+ cause: "provider rejected startup",+ }),+ ),+ ),+ ),+ onStartFailure: (error) =>+ Effect.sync(() => {+ assert.isFalse(startupPersisted);+ assert.instanceOf(error, RunExecutionService.RunExecutionStartError);+ }),+ afterStart: (consumerClosed) =>+ Effect.gen(function* () {+ yield* Deferred.await(consumerClosed);+ assert.equal(writes, 2);+ yield* TestClock.adjust("1 second");+ assert.equal(writes, 3);+ yield* TestClock.adjust("10 minutes");+ assert.equal(writes, 3);+ }),+ });+ assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]);+ assert.lengthOf(+ finalEvents.filter(+ (event) => event.type === "run-attempt.updated" && event.payload.status === "failed",+ ),+ 1,+ );+ assert.lengthOf(written, 1);+ assert.equal(written[0]?.type, "error");+ if (written[0]?.type === "error")+ assert.include(+ written[0].failure.message,+ startupPersisted ? "provider could not start this turn" : "Provider turn failed.",+ );+ }),+);++it.effect("stops pending recovery at service shutdown", () =>+ Effect.gen(function* () {+ const failedWrite = yield* Deferred.make<void>();+ let writes = 0;+ const exit = yield* captureRootRunTermination({+ key: "recovery-shutdown",+ shouldFinalizeRun: () => Effect.succeed(true),+ ingestNormalized: () => Effect.die("ingestion failed"),+ beforeTerminalWrite: () =>+ Effect.gen(function* () {+ writes++;+ yield* Deferred.succeed(failedWrite, undefined);+ return yield* new EventSink.EventSinkWriteError({ eventCount: 5 });+ }),+ afterStart: () =>+ Effect.gen(function* () {+ yield* Deferred.await(failedWrite);+ yield* TestClock.adjust("1 second");+ assert.equal(writes, 2);+ return yield* Effect.interrupt;+ }),+ }).pipe(Effect.exit);+ assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause));+ yield* TestClock.adjust("10 minutes");+ assert.equal(writes, 2);+ }),+);+function captureRootRunTermination(input: {readonly key: string;readonly shouldFinalizeRun: () => Effect.Effect<boolean, ProjectionStore.ProjectionStoreV2Error>;@@ -4117,10 +4342,18 @@ function captureRootRunTermination(input: {ProviderAdapter.ProviderAdapterV2Error>;readonly startTurn?: ProviderAdapter.ProviderAdapterV2SessionRuntime["startTurn"];+ readonly onStartFailure?: (+ error: RunExecutionService.RunExecutionServiceV2Error,+ ) => Effect.Effect<void>;readonly refreshAfterTurn?: Effect.Effect<void>;readonly onSubscriptionClose?: Effect.Effect<void>;readonly shouldStartProviderTurn?: RunExecutionService.RunExecutionServiceV2StartRootRunInput["shouldStartProviderTurn"];readonly appContext?: ReturnType<McpAppModelContext.McpAppModelContext["Service"]["forThread"]>;+ readonly ingestNormalized?: ProviderEventIngestor.ProviderEventIngestorV2["Service"]["ingestNormalized"];+ readonly beforeTerminalWrite?: (+ request: Parameters<EventSink.EventSinkV2["Service"]["writeIfRunCurrent"]>[0],+ ) => Effect.Effect<boolean, EventSink.EventSinkV2Error>;+ readonly afterStart?: (closed: Deferred.Deferred<void>) => Effect.Effect<void>;}) {return Effect.gen(function* () {const ids = backgroundScenarioIds(input.key);@@ -4181,7 +4414,11 @@ function captureRootRunTermination(input: {Effect.gen(function* () {const effects = payload.effects ?? [];yield* Ref.update(submittedEffects, (current) => [...current, ...effects]);- if (input.rejectTerminalWrite === true) {+ if (+ input.rejectTerminalWrite === true ||+ (input.beforeTerminalWrite !== undefined &&+ !(yield* input.beforeTerminalWrite(payload)))+ ) {return { committed: false, storedEvents: [] };}yield* Ref.update(committedEffects, (current) => [...current, ...effects]);@@ -4191,7 +4428,7 @@ function captureRootRunTermination(input: {}),IdAllocator.layer,Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({- ingestNormalized: () => Effect.succeed([]),+ ingestNormalized: input.ingestNormalized ?? (() => Effect.succeed([])),}),ServerSettings.layerTest(),Layer.succeed(RunFinalizationService.RunFinalizationObserver, {@@ -4207,7 +4444,7 @@ function captureRootRunTermination(input: {yield* Effect.gen(function* () {const runExecution = yield* RunExecutionService.RunExecutionServiceV2;- yield* runExecution.startRootRun({+ const start = runExecution.startRootRun({commandId: CommandId.make(`command:${input.key}`),appThread: { id: ids.threadId } as OrchestrationV2AppThread,providerSessionId: ProviderSessionId.make(`session:${input.key}`),@@ -4298,9 +4535,13 @@ function captureRootRunTermination(input: {},},});+ yield* start.pipe(+ Effect.catch((error) => input.onStartFailure?.(error) ?? Effect.fail(error)),+ );+ yield* input.afterStart?.(ingestionDone) ?? Effect.void;+ yield* Deferred.await(ingestionDone);}).pipe(Effect.provide(layerTest));- yield* Deferred.await(ingestionDone);return {written: yield* Ref.get(writtenItems),finalEvents: yield* Ref.get(finalEvents),diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex 9dbb141f4d5..e27106d2020 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -27,11 +27,13 @@ import {import * as Context from "effect/Context";import * as Cause from "effect/Cause";import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Ref from "effect/Ref";+import * as Schedule from "effect/Schedule";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";@@ -600,6 +602,7 @@ export const layer: Layer.Layer<> = Layer.effect(RunExecutionServiceV2,Effect.gen(function* () {+ const scope = yield* Effect.scope;const checkpointService = yield* CheckpointService.CheckpointServiceV2;const eventSink = yield* EventSink.EventSinkV2;const idAllocator = yield* IdAllocator.IdAllocatorV2;@@ -620,6 +623,7 @@ export const layer: Layer.Layer<readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;readonly terminal: ProviderTerminalEvent;+ readonly completedAt?: DateTime.Utc;readonly failureItemPersisted: boolean;readonly refreshAfterTurn: Effect.Effect<void>;readonly writeIfRunCurrent?: {@@ -627,7 +631,7 @@ export const layer: Layer.Layer<readonly expectedStatus: OrchestrationV2Run["status"];};}) {- const completedAt = yield* DateTime.now;+ const completedAt = input.completedAt ?? (yield* DateTime.now);const finalizedAttempt: OrchestrationV2RunAttempt | null = {...input.attempt,status: input.terminal.status,@@ -1424,59 +1428,71 @@ export const layer: Layer.Layer<Effect.catchCauseIf((cause) => !Cause.hasInterruptsOnly(cause),(cause) =>- Ref.get(rootRunFinalized).pipe(- Effect.flatMap((finalized) =>- Effect.logWarning("orchestration V2 provider event ingestion failed", {- runId: input.run.id,- cause,- }).pipe(- Effect.andThen(- finalized- ? Effect.void- : Ref.get(latestProviderThread).pipe(- Effect.flatMap((providerThread) =>- Ref.get(latestTurnItemOrdinal).pipe(- Effect.flatMap((latestItemOrdinal) =>- Ref.get(openRunOwnedSubagents).pipe(- Effect.flatMap((openSubagents) =>- writeFinalRunEvents({- run: input.run,- rootNode: input.rootNode,- checkpointScope: input.checkpointScope,- providerThread,- attempt: input.attempt,- writeIfRunCurrent: {- activeAttemptId: input.attempt.id,- expectedStatus: "running",- },- openRunOwnedSubagents: openSubagents,- terminal: makeFailedTerminalEvent(- makeProviderFailure({- cause: Cause.squash(cause),- class: "unknown",- }),- latestItemOrdinal + 1,- ),- failureItemPersisted: false,- refreshAfterTurn,- }),- ),- ),- ),- ),- ),- ),- ),- Effect.mapError(- (writeCause) =>- new RunExecutionIngestError({- runId: input.run.id,- cause: { ingest: cause, write: writeCause },- }),- ),+ Effect.gen(function* () {+ const completedAt = yield* DateTime.now;+ yield* Effect.logWarning("orchestration V2 provider event ingestion failed", {+ runId: input.run.id,+ cause,+ });+ if (yield* Ref.get(rootRunFinalized)) return;+ const providerThread = yield* Ref.get(latestProviderThread);+ const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal);+ const openSubagents = yield* Ref.get(openRunOwnedSubagents);+ let nextRetryWarningAt = completedAt;+ yield* writeFinalRunEvents({+ run: input.run,+ rootNode: input.rootNode,+ checkpointScope: input.checkpointScope,+ providerThread,+ attempt: input.attempt,+ writeIfRunCurrent: {+ activeAttemptId: input.attempt.id,+ expectedStatus: "running",+ },+ openRunOwnedSubagents: openSubagents,+ completedAt,+ terminal: makeFailedTerminalEvent(+ makeProviderFailure({ cause: Cause.squash(cause), class: "unknown" }),+ latestItemOrdinal + 1,),- ),- ),+ failureItemPersisted: false,+ refreshAfterTurn,+ }).pipe(+ // Storage failures can be defects; retry both failure channels.+ Effect.catchCause((writeCause) =>+ Effect.gen(function* () {+ if (Cause.hasInterruptsOnly(writeCause)) {+ return yield* Effect.failCause(writeCause);+ }+ const now = yield* DateTime.now;+ if (DateTime.isGreaterThanOrEqualTo(now, nextRetryWarningAt)) {+ yield* Effect.logWarning(+ "orchestration V2 run failure finalization retry",+ {+ runId: input.run.id,+ attemptId: input.attempt.id,+ cause: writeCause,+ },+ );+ // Persistent storage failures must not flood the same disk.+ nextRetryWarningAt = DateTime.add(now, { minutes: 10 });+ }+ return yield* Effect.fail(writeCause);+ }),+ ),+ Effect.retry({+ schedule: Schedule.exponential("1 second").pipe(+ Schedule.modifyDelay(({ duration }) =>+ Effect.succeed(Duration.min(duration, Duration.seconds(30))),+ ),+ ),+ }),+ // Startup may cancel the consumer and fail its own terminal+ // write. Only service shutdown or the atomic gate ends recovery.+ Effect.forkIn(scope),+ Effect.flatMap(Fiber.join),+ );+ }),),Effect.ensuring(eventSubscription.close),Effect.forkDetach,