The Open Framework for Building Agents
Fix session stream hangs for unknown and failed runs (#3403)
e0-gh-vercel-connect[bot]76e907927057
diff --git a/.changeset/fix-session-stream-hangs.md b/.changeset/fix-session-stream-hangs.mdnew file mode 100644index 000000000..af63ea424--- /dev/null+++ b/.changeset/fix-session-stream-hangs.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Return a not-found or transient error before opening an unavailable session stream, and close streams after terminal failures.diff --git a/packages/eve/src/eve-channel/request.stream.test.ts b/packages/eve/src/eve-channel/request.stream.test.tsindex 743e781ed..2326f5742 100644--- a/packages/eve/src/eve-channel/request.stream.test.ts+++ b/packages/eve/src/eve-channel/request.stream.test.ts@@ -16,6 +16,9 @@ function stubSession(events: ReadableStream<unknown>): Session {async getEventStream() {return events;},+ async getStreamTailIndex() {+ return -1;+ },} as Session;}diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.tsindex df9c8f3b8..a2164d04b 100644--- a/packages/eve/src/eve-channel/request.ts+++ b/packages/eve/src/eve-channel/request.ts@@ -9,6 +9,7 @@ import type {import type { Session } from "#channel/session.js";import { parseSessionCallback } from "#channel/session-callback.js";import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";+import { isMissingWorkflowRunError } from "#internal/workflow/is-inactive-workflow-run-error.js";import {EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,@@ -282,7 +283,10 @@ export async function createSessionStreamResponse(const includeTailIndex = parseIncludeTailIndex(request);try {- const tailIndex = includeTailIndex ? await session.getStreamTailIndex() : undefined;+ // The event stream opens its durable source lazily, so an unknown or+ // unreachable session would otherwise answer 200 and then fail mid-body.+ // Resolving the tail first surfaces that before any bytes are committed.+ const tailIndex = await session.getStreamTailIndex();const events = await session.getEventStream({ startIndex });const controlVersion =new URL(request.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY) ===@@ -297,20 +301,24 @@ export async function createSessionStreamResponse([EVE_STREAM_FORMAT_HEADER]: EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION,});- if (tailIndex !== undefined) {+ if (includeTailIndex) {headers.set(EVE_STREAM_TAIL_INDEX_HEADER, String(tailIndex));}return new Response(serializeAsNdjson(events,request.signal,- streamEventLimit(startIndex, tailIndex),+ includeTailIndex ? streamEventLimit(startIndex, tailIndex) : undefined,controlVersion !== undefined,),{ headers },);- } catch {- return Response.json({ error: "Session not found.", ok: false }, { status: 404 });+ } catch (error) {+ const notFound = isMissingWorkflowRunError(error);+ return Response.json(+ { error: notFound ? "Session not found." : "Session stream unavailable.", ok: false },+ { status: notFound ? 404 : 503 },+ );}}diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.tsindex 72f1c2a8c..2038c36cb 100644--- a/packages/eve/src/execution/publish-session-events.ts+++ b/packages/eve/src/execution/publish-session-events.ts@@ -240,7 +240,7 @@ async function publishInSessionScope<T>(* releases it. Events reach the stream through `SessionEventPublisher.emit`.*/export interface SessionEventWriter {- /** Closes the session stream; only a terminal `done` step does this. */+ /** Closes the session stream; only a terminal event (`done`, completion, or failure) does this. */close(): Promise<void>;/** Releases the writer lock so the next step can acquire it. Safe after `close()`. */release(): void;@@ -384,11 +384,12 @@ type TerminalSessionEvent = Extract</*** Publishes a terminal `session.completed` or `session.failed` from outside a* turn as the session's own event, through its channel adapter and- * instrumentation. Stream-event hooks do not run: the ending session may not+ * instrumentation, then closes the session stream so readers following it+ * reach EOF. Stream-event hooks do not run: the ending session may not* restore, and no turn scope remains for authored code. Never throws.*- * When the context cannot be restored, the event is only stamped and written so- * the stream still ends: the one degraded write of a session event.+ * When the context cannot be restored, the event is only stamped, written, and+ * the stream closed: the one degraded write of a session event.*/export async function publishTerminalSessionEvent(input: {readonly errorId?: string;@@ -422,6 +423,7 @@ export async function publishTerminalSessionEvent(input: {// Emitted without its hooks; see above.const publish: HandleEventFn = async (event) => {await publisher.emit(event);+ await publisher.writer.close();};let instrumentation: ReturnType<typeof bindSessionInstrumentation>;try {@@ -460,6 +462,7 @@ async function writeUnroutedSessionEvent(const writer = openSessionEventWriter({ deliveryIds: () => undefined, sessionWritable });try {await writer.write(event);+ await writer.close();} finally {writer.release();}diff --git a/packages/eve/src/execution/terminal-session-stream.integration.test.ts b/packages/eve/src/execution/terminal-session-stream.integration.test.tsnew file mode 100644index 000000000..c2b7cfca8--- /dev/null+++ b/packages/eve/src/execution/terminal-session-stream.integration.test.ts@@ -0,0 +1,80 @@+import { expect, it } from "vitest";++import { publishTerminalSessionEvent } from "#execution/publish-session-events.js";+import { createTestRuntime } from "#internal/testing/app-harness.js";+import { createSessionFailedEvent, type MessageStreamEvent } from "#protocol/message.js";+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";++const serializedContext = {+ "eve.auth": null,+ "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },+ "eve.channel": { kind: "http", state: {} },+ "eve.continuationToken": "test-token",+ "eve.sessionId": "session_xyz",+ "eve.turnDeliveryIds": ["delivery_restored"],+};++function failedEvent() {+ return createSessionFailedEvent({+ code: "WORKFLOW_EXECUTION_FAILED",+ message: "failed",+ sessionId: "session_xyz",+ usage: undefined,+ });+}++/** A session writable that records writes and the close, in order. */+function recordingWritable() {+ const ops: Array<{ kind: "write"; event: MessageStreamEvent } | { kind: "close" }> = [];+ const sessionWritable = new WritableStream<Uint8Array>({+ write(chunk) {+ ops.push({+ kind: "write",+ event: JSON.parse(new TextDecoder().decode(chunk)) as MessageStreamEvent,+ });+ },+ close() {+ ops.push({ kind: "close" });+ },+ });+ return { ops, sessionWritable };+}++it("closes the durable stream after publishing a terminal session.failed", async () => {+ const runtime = await createTestRuntime({ agent: { name: "terminal-session-stream" } });+ const { ops, sessionWritable } = recordingWritable();++ await runtime.run(async () => {+ await publishTerminalSessionEvent({ event: failedEvent(), sessionWritable, serializedContext });+ });++ expect(ops.map((op) => op.kind)).toEqual(["write", "close"]);+ const [written] = ops;+ if (written?.kind !== "write") throw new Error("Expected the terminal event to be written.");+ expect(written.event.type).toBe("session.failed");+ // Only the restored-context publisher stamps the turn's delivery ids; the+ // degraded fallback writes without them, so this pins the restored path.+ expect(written.event.meta.deliveryIds).toEqual(["delivery_restored"]);+});++it("writes the terminal event, then closes, when the context cannot be restored", async () => {+ const { ops, sessionWritable } = recordingWritable();++ await publishTerminalSessionEvent({+ event: failedEvent(),+ sessionWritable,+ serializedContext: {+ "eve.sessionId": "session_xyz",+ "eve.turnDeliveryIds": ["delivery_restored"],+ },+ });++ expect(ops.map((op) => op.kind)).toEqual(["write", "close"]);+ const [written] = ops;+ if (written?.kind !== "write") throw new Error("Expected the terminal event to be written.");+ expect(written.event).toMatchObject({+ type: "session.failed",+ data: { code: "WORKFLOW_EXECUTION_FAILED", sessionId: "session_xyz" },+ });+ expect(written.event.meta.deliveryIds).toBeUndefined();+});diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex ed7696603..5713afb8e 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -1,6 +1,7 @@import type { FilePart, UserContent } from "ai";import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";import { describe, expect, it, vi } from "vitest";+import { WorkflowRunNotFoundError } from "#compiled/@workflow/errors/index.js";import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";@@ -589,14 +590,38 @@ describe("eveChannel — stream cursor", () => {},);- it("omits the tail index by default without paying for the lookup", async () => {+ it("resolves the tail index by default without returning it", async () => {const handler = createEveStreamHandler({ auth: none() });const response = await handler.fetch("https://eve.test/eve/v1/session/test-session-id/stream");expect(response.status).toBe(200);expect(response.headers.get("x-eve-stream-tail-index")).toBeNull();- expect(handler.getStreamTailIndex).not.toHaveBeenCalled();+ expect(handler.getStreamTailIndex).toHaveBeenCalledOnce();+ });++ it("returns 404 for an unknown session in follow mode", async () => {+ const handler = createEveStreamHandler({ auth: none() });+ handler.getStreamTailIndex.mockRejectedValueOnce(+ new WorkflowRunNotFoundError("test-session-id"),+ );++ const response = await handler.fetch("https://eve.test/eve/v1/session/test-session-id/stream");++ expect(response.status).toBe(404);+ expect(await response.json()).toEqual({ error: "Session not found.", ok: false });+ expect(handler.getEventStream).not.toHaveBeenCalled();+ });++ it("returns 503 when the session lookup fails transiently", async () => {+ const handler = createEveStreamHandler({ auth: none() });+ handler.getStreamTailIndex.mockRejectedValueOnce(new Error("stream lookup failed"));++ const response = await handler.fetch("https://eve.test/eve/v1/session/test-session-id/stream");++ expect(response.status).toBe(503);+ expect(await response.json()).toEqual({ error: "Session stream unavailable.", ok: false });+ expect(handler.getEventStream).not.toHaveBeenCalled();});it("reports the durable tail index when the request opts in", async () => {