TypeScript
fix(server): fail runs whose provider stream ends without a terminal (#19131)
Alb11747e77a48e81a6a
diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.tsindex 62a03c0de2a..55029b4bd32 100644--- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts@@ -1746,7 +1746,7 @@ it.effect("ProviderSessionManagerV2 releases sessions in parallel on server shut}),);-it.effect("ProviderSessionManagerV2 closes event subscriptions normally on server shutdown", () =>+it.effect("ProviderSessionManagerV2 interrupts event subscriptions on server shutdown", () =>Effect.gen(function* () {const state = yield* Ref.make(emptyState);const effect = Effect.gen(function* () {@@ -1781,7 +1781,10 @@ it.effect("ProviderSessionManagerV2 closes event subscriptions normally on serveyield* manager.shutdown;- assert.isEmpty(yield* bufferedSubscription.events.pipe(Stream.runCollect));+ // Buffered events are dropped and the consumer sees an interruption, not+ // a clean end, so it leaves run settlement to restart recovery.+ const exit = yield* bufferedSubscription.events.pipe(Stream.runCollect, Effect.exit);+ assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause));});yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 60_000 })));diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.tsindex cf0afa6b9eb..92eeb91ad23 100644--- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts@@ -593,12 +593,15 @@ export const layerWithOptions = ();});- const closeSubscribers = (entry: LiveSessionEntry) =>+ // Server shutdown interrupts subscribers rather than ending them: a+ // cleanly ended stream without a terminal fails its run, while an+ // interrupted one leaves run settlement to restart recovery.+ const interruptSubscribers = (entry: LiveSessionEntry) =>Effect.gen(function* () {const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());yield* Effect.forEach(subscribers.values(),- (queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.end(queue))),+ (queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.interrupt(queue))),{ discard: true },);});@@ -1078,7 +1081,7 @@ export const layerWithOptions = (if (input.gracefulSubscribers === true) {yield* endSubscribers(entry);} else if (input.reason === "server_shutdown") {- yield* closeSubscribers(entry);+ yield* interruptSubscribers(entry);} else {yield* failSubscribers(entry,@@ -2096,15 +2099,17 @@ export const layerWithOptions = (}).pipe(logReleaseFailure(entry.runtime.providerSessionId));return;}- const cause = Exit.isFailure(exit)- ? exit.cause- : Cause.fail(- new ProviderAdapter.ProviderAdapterEventStreamError({- driver: entry.runtime.driver,- providerSessionId: entry.runtime.providerSessionId,- cause: "Provider event stream ended unexpectedly.",- }),- );+ // Subscribers read an interrupt as server shutdown, so keep it for that.+ const cause =+ Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)+ ? exit.cause+ : Cause.fail(+ new ProviderAdapter.ProviderAdapterEventStreamError({+ driver: entry.runtime.driver,+ providerSessionId: entry.runtime.providerSessionId,+ cause: "Provider event stream ended unexpectedly.",+ }),+ );yield* publishToSubscribers(entry.eventSubscribers, {type: "failure",cause,diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.tsindex d877922a644..592886e0b94 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts@@ -3742,9 +3742,11 @@ it.effect("does not refresh pull requests for auxiliary or stale provider termin{ ...ids, rootProviderTurnId: ProviderTurnId.make("turn:previous") },"interrupted",),+ rootTerminalEvent(ids, "cancelled"),]),});- assert.deepEqual(observed, []);+ // Only the root terminal settles the run and refreshes pull requests.+ assert.deepEqual(observed, ["run:cancelled", "pull-requests-refreshed"]);}),);@@ -3772,6 +3774,58 @@ it.effect("refreshes pull requests after a provider stream exits with an error",}),);+it.effect("fails the run when its event stream ends without a root terminal", () =>+ Effect.gen(function* () {+ const { observed, finalEvents } = yield* captureRootRunTermination({+ key: "stream-end-without-terminal",+ shouldFinalizeRun: () => Effect.succeed(true),+ events: () => Stream.empty,+ });+ assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]);+ assert.equal(+ finalEvents.find((event) => event.type === "provider-thread.updated")?.payload.status,+ "idle",+ );+ }),+);++it.effect("leaves the run to restart recovery when shutdown interrupts its event stream", () =>+ Effect.gen(function* () {+ const { written, observed } = yield* captureRootRunTermination({+ key: "stream-end:shutdown",+ shouldFinalizeRun: () => Effect.succeed(true),+ events: () => Stream.failCause(Cause.interrupt()),+ });+ assert.deepEqual(written, []);+ assert.deepEqual(observed, []);+ }),+);++it.effect("does not start a turn whose run settled during the app context read", () =>+ Effect.gen(function* () {+ const contextReadStarted = yield* Deferred.make<void>();+ const runFailed = yield* Deferred.make<void>();+ const current = yield* Ref.make(true);+ const providerCalls = yield* Ref.make(0);+ const { observed } = yield* captureRootRunTermination({+ key: "stream-end:context-read",+ shouldStartProviderTurn: () => Ref.get(current),+ shouldFinalizeRun: () => Ref.get(current),+ events: () => Stream.unwrap(Deferred.await(contextReadStarted).pipe(Effect.as(Stream.empty))),+ appContext: Deferred.succeed(contextReadStarted, undefined).pipe(+ Effect.andThen(Deferred.await(runFailed)),+ Effect.as([]),+ ),+ refreshAfterTurn: Ref.set(current, false).pipe(+ Effect.andThen(Deferred.succeed(runFailed, undefined)),+ ),+ startTurn: () => Ref.update(providerCalls, (count) => count + 1),+ });+ assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]);+ assert.equal(yield* Ref.get(providerCalls), 0);+ }),+);+it.effect("refreshes pull requests only once when startup failure closes its event stream", () =>Effect.gen(function* () {const ingestionStarted = yield* Deferred.make<void>();@@ -3828,6 +3882,8 @@ function captureRootRunTermination(input: {>;readonly startTurn?: ProviderAdapter.ProviderAdapterV2SessionRuntime["startTurn"];readonly refreshAfterTurn?: Effect.Effect<void>;+ readonly shouldStartProviderTurn?: RunExecutionService.RunExecutionServiceV2StartRootRunInput["shouldStartProviderTurn"];+ readonly appContext?: ReturnType<McpAppModelContext.McpAppModelContext["Service"]["forThread"]>;}) {return Effect.gen(function* () {const ids = backgroundScenarioIds(input.key);@@ -3840,6 +3896,7 @@ function captureRootRunTermination(input: {status: "running",});const writtenItems = yield* Ref.make<ReadonlyArray<OrchestrationV2TurnItem>>([]);+ const finalEvents = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);const observed = yield* Ref.make<ReadonlyArray<string>>([]);const submittedEffects = yield* Ref.make<ReadonlyArray<PendingOrchestrationEffectV2>>([]);const committedEffects = yield* Ref.make<ReadonlyArray<PendingOrchestrationEffectV2>>([]);@@ -3848,6 +3905,7 @@ function captureRootRunTermination(input: {Ref.update(writtenItems, (current) => [...current, payload]);const captureFinalEvents = (events: ReadonlyArray<OrchestrationV2DomainEvent>) =>Effect.gen(function* () {+ yield* Ref.update(finalEvents, (current) => [...current, ...events]);for (const event of events) {if (event.type === "turn-item.updated") {yield* captureTurnItem(event.payload);@@ -3860,7 +3918,9 @@ function captureRootRunTermination(input: {const layerTest = RunExecutionService.layer.pipe(Layer.provide(Layer.mergeAll(- McpAppModelContext.layerEmpty,+ Layer.mock(McpAppModelContext.McpAppModelContext)({+ forThread: () => input.appContext ?? Effect.succeed([]),+ }),Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),Layer.mock(EventSink.EventSinkV2)({write: (payload) =>@@ -3970,6 +4030,9 @@ function captureRootRunTermination(input: {attemptId: ids.attemptId,providerTurnOrdinal: 1,shouldFinalizeRun: input.shouldFinalizeRun,+ ...(input.shouldStartProviderTurn === undefined+ ? {}+ : { shouldStartProviderTurn: input.shouldStartProviderTurn }),...(input.hasUnpairedRunInterruptRequest === undefined? {}: {@@ -4000,6 +4063,7 @@ function captureRootRunTermination(input: {yield* Deferred.await(ingestionDone);return {written: yield* Ref.get(writtenItems),+ finalEvents: yield* Ref.get(finalEvents),observed: yield* Ref.get(observed),submittedEffects: yield* Ref.get(submittedEffects),committedEffects: yield* Ref.get(committedEffects),diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex b2fe77f6cd8..8d9fd792d9b 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -1316,83 +1316,85 @@ export const layer: Layer.Layer<Effect.gen(function* () {const terminal = yield* Ref.get(terminalEvent);if (terminal === null) {- return;+ // A session release interrupts or fails the stream; a clean+ // end without a terminal means the run would never settle.+ return yield* new RunExecutionIngestError({+ runId: input.run.id,+ cause: new ProviderAdapter.ProviderAdapterEventStreamError({+ driver: input.providerThread.driver,+ providerSessionId: input.providerSessionId,+ cause: "Provider event stream ended without a root terminal.",+ }),+ });}yield* finalizeRootRun(terminal);}),),- Effect.catchCause((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,- // The failure may be the ownership- // read itself, so check in the write.- writeIfRunCurrent: {- activeAttemptId: input.attempt.id,- expectedStatus: "running",- },- openRunOwnedSubagents: openSubagents,- terminal: makeFailedTerminalEvent(- makeProviderFailure({- cause: Cause.squash(cause),- class: "unknown",- }),- latestItemOrdinal + 1,- ),- failureItemPersisted: false,- refreshAfterTurn,- }),+ // Server shutdown interrupts the subscription and leaves the run to+ // restart recovery; every other failure fails the run.+ 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,+ // The failure may be the ownership+ // read itself, so check in the write.+ 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.mapError(+ (writeCause) =>+ new RunExecutionIngestError({+ runId: input.run.id,+ cause: { ingest: cause, write: writeCause },+ }),+ ),),),),- ),),Effect.ensuring(eventSubscription.close),Effect.forkDetach,);- // A failed read fails the start below, so the run is recorded as- // failed instead of staying active with no provider turn.- const shouldStart =- input.shouldStartProviderTurn === undefined- ? Exit.succeed(true)- : yield* Effect.exit(input.shouldStartProviderTurn());- if (Exit.isSuccess(shouldStart) && !shouldStart.value) {- yield* Fiber.interrupt(providerEventFiber);- return;- }-// A provider turn is a sign that the session is still alive. Keep// its already-issued MCP credential valid even when the agent goes// a long time between browser-tool calls.@@ -1436,6 +1438,17 @@ export const layer: Layer.Layer<runtimePolicy: input.runtimePolicy,...(appContext.length === 0 ? {} : { appContext }),};+ // Check after the context read: ingestion can settle the run while+ // it awaits. A failed ownership read fails the start below.+ const shouldStart =+ input.shouldStartProviderTurn === undefined+ ? Exit.succeed(true)+ : yield* Effect.exit(input.shouldStartProviderTurn());+ if (Exit.isSuccess(shouldStart) && !shouldStart.value) {+ yield* Fiber.interrupt(providerEventFiber);+ return;+ }+const compact =input.message.attachments.length === 0 &&input.message.text.trim().toLowerCase() === "/compact";