Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(api): stream trace observation IO as bytes (LFE-11081) (#15239)

Nikita Kabardine6624c293dc1
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index c3569a470e..a9944c97b3 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -2577,6 +2577,145 @@ export const getObservationsBatchIOFromEventsTable = async <
})) as Array<EventBatchIOResult<TIncludeExperiment, TIncludeToolCalls>>;
};
+/**
+ * The single observation IO fields the stream/length helpers below can serve.
+ * `input`/`output` are raw `String` columns streamed as-is β€” note they may be a
+ * bare, unquoted string (not JSON) for plain-text prompts/completions, so the
+ * route serves them as opaque bytes, not `application/json`. `metadata` is
+ * reconstructed from the `metadata_names`/`metadata_values` `Map(String,String)`
+ * columns, so **every metadata value is emitted JSON-string-encoded** (a nested
+ * object comes out as an escaped string). Consumers must unwrap one level, exactly
+ * as the existing metadata read path does (`parseMetadataCHRecordToDomain`).
+ */
+export const OBSERVATION_IO_STREAM_FIELDS = [
+ "input",
+ "output",
+ "metadata",
+] as const;
+
+export type ObservationIoStreamField =
+ (typeof OBSERVATION_IO_STREAM_FIELDS)[number];
+
+// Closed set of SQL expressions keyed by the validated `field` enum β€” never
+// string-interpolated user input. The length pre-query and the byte stream share
+// this map + the WHERE/params below so they can never drift; a mismatch would
+// make the route's Content-Length integrity check wrong.
+const OBSERVATION_IO_FIELD_SELECT: Record<ObservationIoStreamField, string> = {
+ input: "e.input",
+ output: "e.output",
+ metadata:
+ "toJSONString(mapFromArrays(arrayReverse(e.metadata_names), arrayReverse(e.metadata_values)))",
+};
+
+// The Β±1s window around `startTime` only prunes the primary key
+// (project_id, toStartOfMinute(start_time), xxHash32(trace_id)); it is a
+// performance hint, never an authorization control.
+const OBSERVATION_IO_WHERE = `
+ WHERE e.project_id = {projectId: String}
+ AND e.trace_id = {traceId: String}
+ AND e.span_id = {observationId: String}
+ AND e.start_time >= {minTimestamp: DateTime64(3)}
+ AND e.start_time <= {maxTimestamp: DateTime64(3)}`;
+
+interface ObservationIOReadOpts {
+ projectId: string;
+ traceId: string;
+ observationId: string;
+ field: ObservationIoStreamField;
+ /** The observation's startTime; bounds the read for primary-key pruning. */
+ startTime: Date;
+}
+
+function observationIOReadParams(opts: ObservationIOReadOpts) {
+ return {
+ projectId: opts.projectId,
+ traceId: opts.traceId,
+ observationId: opts.observationId,
+ minTimestamp: convertDateToClickhouseDateTime(
+ new Date(opts.startTime.getTime() - 1000),
+ ),
+ maxTimestamp: convertDateToClickhouseDateTime(
+ new Date(opts.startTime.getTime() + 1000),
+ ),
+ };
+}
+
+/**
+ * Byte length of one observation IO field β€” a cheap pre-query the streaming
+ * route runs BEFORE committing headers. It does two jobs the raw stream can't:
+ * - distinguishes "not found" (no row β†’ `null` β†’ the route 404s) from "present
+ * but empty" (row with 0 β†’ empty 200), so a stale/skewed `startTime` yields a
+ * diagnosable 404 rather than a misleading empty body; and
+ * - gives the exact byte count for a `Content-Length` header, so a mid-stream
+ * ClickHouse failure (truncated body) is detectable at the HTTP layer on ANY
+ * ClickHouse version β€” independent of the `x-clickhouse-exception-tag` header
+ * that raw-passthrough failure detection needs (β‰₯25.11 only).
+ * Uses the SAME field expression + WHERE as the stream, so the length matches the
+ * bytes streamed. `length()` on a ClickHouse `String` is its byte count.
+ */
+export const getObservationIOFieldByteLengthFromEventsTable = async (
+ opts: ObservationIOReadOpts,
+): Promise<number | null> => {
+ const query = `
+ SELECT length(${OBSERVATION_IO_FIELD_SELECT[opts.field]}) AS len
+ FROM events_full e
+ ${OBSERVATION_IO_WHERE}
+ ORDER BY e.event_ts DESC
+ LIMIT 1
+ `;
+ const rows = await queryClickhouse<{ len: string }>({
+ query,
+ params: observationIOReadParams(opts),
+ tags: { projectId: opts.projectId, route: "observation-io-stream-length" },
+ preferredClickhouseService: "EventsReadOnly",
+ });
+ const first = rows[0];
+ return first ? Number(first.len) : null;
+};
+
+/**
+ * Stream ONE observation's single IO field (input | output | metadata) straight
+ * from ClickHouse to the caller as raw bytes, WITHOUT materializing the whole
+ * value in the Node process. Uses `FORMAT RawBLOB`, so ClickHouse emits exactly
+ * the field's bytes (no JSONEachRow envelope) and {@link queryClickhouseExecRaw}
+ * hands back the live HTTP body as a `Readable` for the caller to pipe onward.
+ * This is the transport primitive behind the lazy/streaming large-JSON viewer
+ * (LFE-11081): the browser can fetch a multi-hundred-MB field as a byte stream
+ * instead of forcing the server to buffer + JSON-serialize it in one shot.
+ *
+ * SECURITY: strictly tenant-scoped. The read is pinned to a single
+ * (project_id, trace_id, span_id) via parameterized predicates, so it can only
+ * ever return bytes for that one observation inside that one project β€” a wrong
+ * projectId yields zero rows (zero bytes). `field` is NOT interpolated user
+ * input: it selects from a fixed, closed set of SQL expressions. Callers MUST
+ * still authorize the (projectId, traceId) pair before calling β€” this function
+ * performs data isolation, not request authorization.
+ */
+export const streamObservationIOFieldFromEventsTable = (
+ opts: ObservationIOReadOpts,
+) => {
+ const query = `
+ SELECT ${OBSERVATION_IO_FIELD_SELECT[opts.field]} AS field
+ FROM events_full e
+ ${OBSERVATION_IO_WHERE}
+ ORDER BY e.event_ts DESC
+ LIMIT 1
+ `;
+
+ // FORMAT RawBLOB emits the selected String column's bytes with no escaping or
+ // delimiters; with LIMIT 1 that is exactly this observation's field value.
+ return queryClickhouseExecRaw({
+ query,
+ format: "RawBLOB",
+ params: observationIOReadParams(opts),
+ tags: {
+ projectId: opts.projectId,
+ route: "observation-io-stream",
+ },
+ preferredClickhouseService: "EventsReadOnly",
+ });
+};
+
/**
* Full raw I/O + metadata for ONE observation, scoped to a session (the
* session-detail download fallback for payloads too large to render inline,
diff --git a/web/src/__tests__/server/repositories/stream-observation-io-repository.servertest.ts b/web/src/__tests__/server/repositories/stream-observation-io-repository.servertest.ts
new file mode 100644
index 0000000000..52caa34443
--- /dev/null
+++ b/web/src/__tests__/server/repositories/stream-observation-io-repository.servertest.ts
@@ -0,0 +1,149 @@
+import { randomUUID } from "crypto";
+import { describe, expect } from "vitest";
+import {
+ createEvent,
+ createEventsCh,
+ getObservationIOFieldByteLengthFromEventsTable,
+ streamObservationIOFieldFromEventsTable,
+} from "@langfuse/shared/src/server";
+import { env } from "@/src/env.mjs";
+
+// Reads the v4 events table (events_full), so gate on the same preview opt-in as
+// the rest of the events-repository suite.
+const maybe =
+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"
+ ? describe
+ : describe.skip;
+
+async function collectStream(stream: NodeJS.ReadableStream): Promise<string> {
+ const chunks: Buffer[] = [];
+ for await (const chunk of stream) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
+ }
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+maybe("streamObservationIOFieldFromEventsTable", () => {
+ it("streams each raw IO field for the scoped observation", async () => {
+ const projectId = randomUUID();
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const startMs = Date.now();
+
+ const input = JSON.stringify({ prompt: "hello 🌍", n: 42 });
+ const output = JSON.stringify([{ role: "assistant", content: "hi" }]);
+
+ await createEventsCh([
+ createEvent({
+ id: observationId,
+ span_id: observationId,
+ project_id: projectId,
+ trace_id: traceId,
+ input,
+ output,
+ metadata_names: ["k1", "k2"],
+ metadata_values: ["v1", "v2"],
+ start_time: startMs * 1000, // micros
+ }),
+ ]);
+
+ const startTime = new Date(startMs);
+
+ const inputText = await streamObservationIOFieldFromEventsTable({
+ projectId,
+ traceId,
+ observationId,
+ field: "input",
+ startTime,
+ }).then((r) => collectStream(r.stream));
+ expect(inputText).toBe(input);
+
+ const outputText = await streamObservationIOFieldFromEventsTable({
+ projectId,
+ traceId,
+ observationId,
+ field: "output",
+ startTime,
+ }).then((r) => collectStream(r.stream));
+ expect(outputText).toBe(output);
+
+ const metadataText = await streamObservationIOFieldFromEventsTable({
+ projectId,
+ traceId,
+ observationId,
+ field: "metadata",
+ startTime,
+ }).then((r) => collectStream(r.stream));
+ expect(JSON.parse(metadataText)).toMatchObject({ k1: "v1", k2: "v2" });
+ });
+
+ it("returns zero bytes for a different project (tenant isolation)", async () => {
+ const projectId = randomUUID();
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const startMs = Date.now();
+
+ await createEventsCh([
+ createEvent({
+ id: observationId,
+ span_id: observationId,
+ project_id: projectId,
+ trace_id: traceId,
+ input: "secret tenant data",
+ start_time: startMs * 1000,
+ }),
+ ]);
+
+ // Same trace/observation ids, but a foreign projectId must never match.
+ const crossProject = await streamObservationIOFieldFromEventsTable({
+ projectId: randomUUID(),
+ traceId,
+ observationId,
+ field: "input",
+ startTime: new Date(startMs),
+ }).then((r) => collectStream(r.stream));
+
+ expect(crossProject).toBe("");
+ });
+
+ it("byte length is the field's UTF-8 byte count, and null for a foreign project", async () => {
+ const projectId = randomUUID();
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const startMs = Date.now();
+ // Contains a 4-byte emoji, so byte length > character length: verifies
+ // ClickHouse `length()` counts bytes (what Content-Length needs).
+ const input = JSON.stringify({ prompt: "hello 🌍", n: 42 });
+
+ await createEventsCh([
+ createEvent({
+ id: observationId,
+ span_id: observationId,
+ project_id: projectId,
+ trace_id: traceId,
+ input,
+ start_time: startMs * 1000,
+ }),
+ ]);
+ const startTime = new Date(startMs);
+
+ const len = await getObservationIOFieldByteLengthFromEventsTable({
+ projectId,
+ traceId,
+ observationId,
+ field: "input",
+ startTime,
+ });
+ expect(len).toBe(Buffer.byteLength(input, "utf8"));
+
+ // No matching row β†’ null (the route turns this into a 404, not empty 200).
+ const missing = await getObservationIOFieldByteLengthFromEventsTable({
+ projectId: randomUUID(),
+ traceId,
+ observationId,
+ field: "input",
+ startTime,
+ });
+ expect(missing).toBeNull();
+ });
+});
diff --git a/web/src/__tests__/server/stream-observation-io-api.servertest.ts b/web/src/__tests__/server/stream-observation-io-api.servertest.ts
new file mode 100644
index 0000000000..d778d3ac11
--- /dev/null
+++ b/web/src/__tests__/server/stream-observation-io-api.servertest.ts
@@ -0,0 +1,215 @@
+/** @vitest-environment node */
+import type { NextApiRequest, NextApiResponse } from "next";
+import { Readable } from "stream";
+import { createMocks } from "node-mocks-http";
+import { LangfuseNotFoundError, UnauthorizedError } from "@langfuse/shared";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import handler from "../../pages/api/traces/[traceId]/observations/[observationId]/io/[field]";
+
+const {
+ mockGetServerAuthSession,
+ mockGetAuthorizedTrace,
+ mockStreamIOField,
+ mockByteLength,
+} = vi.hoisted(() => ({
+ mockGetServerAuthSession: vi.fn(),
+ mockGetAuthorizedTrace: vi.fn(),
+ mockStreamIOField: vi.fn(),
+ mockByteLength: vi.fn(),
+}));
+
+vi.mock("../../server/auth", () => ({
+ getServerAuthSession: (...args: unknown[]) =>
+ mockGetServerAuthSession(...args),
+}));
+
+// Override only the trace authorizer; keep the rest of the module real.
+vi.mock("../../features/traces/server/buildTraceExport", async () => ({
+ ...(await vi.importActual("../../features/traces/server/buildTraceExport")),
+ getAuthorizedTrace: (...args: unknown[]) => mockGetAuthorizedTrace(...args),
+}));
+
+// Override only the ClickHouse streaming read; keep logger, the field enum, and
+// everything withMiddlewares needs from the barrel intact.
+vi.mock("@langfuse/shared/src/server", async () => ({
+ ...(await vi.importActual("@langfuse/shared/src/server")),
+ getObservationIOFieldByteLengthFromEventsTable: (...args: unknown[]) =>
+ mockByteLength(...args),
+ streamObservationIOFieldFromEventsTable: (...args: unknown[]) =>
+ mockStreamIOField(...args),
+}));
+
+const projectId = "project-1";
+const traceId = "trace-1";
+const observationId = "obs-1";
+const startTime = "2024-06-15T12:00:00.000Z";
+
+const createGetMocks = (query: Record<string, string | string[] | undefined>) =>
+ createMocks<NextApiRequest, NextApiResponse>({ method: "GET", query });
+
+const validQuery = {
+ traceId,
+ observationId,
+ field: "input",
+ projectId,
+ startTime,
+};
+
+describe("GET /api/traces/[traceId]/observations/[observationId]/io/[field]", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetServerAuthSession.mockResolvedValue({
+ user: {
+ email: "[email protected]",
+ admin: false,
+ organizations: [{ projects: [{ id: projectId }] }],
+ },
+ });
+ mockGetAuthorizedTrace.mockResolvedValue({
+ id: traceId,
+ timestamp: new Date(startTime),
+ });
+ // Byte length matches the streamed body ('{"hello":"world"}' = 17 bytes).
+ mockByteLength.mockResolvedValue(17);
+ mockStreamIOField.mockResolvedValue({
+ stream: Readable.from(['{"hello":', '"world"}']),
+ });
+ });
+
+ it("streams the field as opaque bytes for an authorized member", async () => {
+ const { req, res } = createGetMocks(validQuery);
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(200);
+ // Opaque bytes, not application/json (input/output may be a bare string).
+ expect(res.getHeader("Content-Type")).toBe("application/octet-stream");
+ // No Content-Length: the body streams chunked, so its size is never derived
+ // from a second read that could diverge from it.
+ expect(res.getHeader("Content-Length")).toBeUndefined();
+ expect(res.getHeader("Cache-Control")).toBe("private, no-store");
+ expect(res.getHeader("Accept-Ranges")).toBe("none");
+ expect(res._getData()).toBe('{"hello":"world"}');
+
+ // The ClickHouse read is pinned to exactly this tenant/trace/observation.
+ expect(mockStreamIOField).toHaveBeenCalledWith({
+ projectId,
+ traceId,
+ observationId,
+ field: "input",
+ startTime: new Date(startTime),
+ });
+ });
+
+ it("returns 404 (not a misleading empty 200) when the field/observation is not found", async () => {
+ // No matching row (e.g. a stale/skewed startTime) β†’ the length pre-query
+ // returns null β†’ clean 404, and the stream is never opened.
+ mockByteLength.mockResolvedValue(null);
+ const { req, res } = createGetMocks(validQuery);
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(404);
+ expect(mockStreamIOField).not.toHaveBeenCalled();
+ });
+
+ it("serves a genuinely empty field (length 0, row exists) as an empty 200", async () => {
+ mockByteLength.mockResolvedValue(0);
+ mockStreamIOField.mockResolvedValue({ stream: Readable.from([]) });
+ const { req, res } = createGetMocks(validQuery);
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(200);
+ expect(res._getData()).toBe("");
+ });
+
+ it("serves each supported field", async () => {
+ for (const field of ["input", "output", "metadata"] as const) {
+ vi.clearAllMocks();
+ mockGetServerAuthSession.mockResolvedValue({
+ user: {
+ email: "[email protected]",
+ admin: false,
+ organizations: [{ projects: [{ id: projectId }] }],
+ },
+ });
+ mockGetAuthorizedTrace.mockResolvedValue({ id: traceId });
+ mockByteLength.mockResolvedValue(1);
+ mockStreamIOField.mockResolvedValue({ stream: Readable.from(["x"]) });
+
+ const { req, res } = createGetMocks({ ...validQuery, field });
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(200);
+ expect(mockStreamIOField).toHaveBeenCalledWith(
+ expect.objectContaining({ field }),
+ );
+ }
+ });
+
+ it("returns 401 and never reads IO when the caller is not authorized (cross-project/tenant)", async () => {
+ // A user from another project: getAuthorizedTrace rejects for a
+ // non-public trace they cannot access.
+ mockGetAuthorizedTrace.mockRejectedValue(
+ new UnauthorizedError(
+ "User is not a member of this project and this trace is not public",
+ ),
+ );
+ const { req, res } = createGetMocks(validQuery);
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(401);
+ // Authorization gates data access: the ClickHouse read is never issued.
+ expect(mockStreamIOField).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 when the trace does not exist", async () => {
+ mockGetAuthorizedTrace.mockRejectedValue(
+ new LangfuseNotFoundError("Trace not found"),
+ );
+ const { req, res } = createGetMocks(validQuery);
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(404);
+ expect(mockStreamIOField).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 for an unsupported field", async () => {
+ const { req, res } = createGetMocks({ ...validQuery, field: "secrets" });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(mockGetAuthorizedTrace).not.toHaveBeenCalled();
+ expect(mockStreamIOField).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when projectId is missing", async () => {
+ const { req, res } = createGetMocks({
+ traceId,
+ observationId,
+ field: "input",
+ startTime,
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(mockGetAuthorizedTrace).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 for an unparsable startTime", async () => {
+ const { req, res } = createGetMocks({
+ ...validQuery,
+ startTime: "not-a-date",
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(mockStreamIOField).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/features/traces/server/buildTraceExport.ts b/web/src/features/traces/server/buildTraceExport.ts
index 453a5eeb7a..846c96696a 100644
--- a/web/src/features/traces/server/buildTraceExport.ts
+++ b/web/src/features/traces/server/buildTraceExport.ts
@@ -92,7 +92,16 @@ const getObservationRecordCountForTrace = async (params: {
});
};
-async function getAuthorizedTrace(params: {
+/**
+ * Canonical trace read-authorization used by the session-authed trace download
+ * routes: grants access when the trace (or its session) is public, the user is
+ * an admin, or the user is a member of the project β€” and fires the admin-access
+ * webhook for admins. Reused by the observation IO streaming route (LFE-11081)
+ * so authorization stays in one place rather than being re-derived per route.
+ * Returns the authorized trace (its `timestamp` bounds downstream ClickHouse
+ * reads); throws `LangfuseNotFoundError` / `UnauthorizedError` otherwise.
+ */
+export async function getAuthorizedTrace(params: {
traceId: string;
projectId: string;
session: TraceExportAccessSession;
diff --git a/web/src/pages/api/traces/[traceId]/observations/[observationId]/io/[field].ts b/web/src/pages/api/traces/[traceId]/observations/[observationId]/io/[field].ts
new file mode 100644
index 0000000000..bde17c2bb8
--- /dev/null
+++ b/web/src/pages/api/traces/[traceId]/observations/[observationId]/io/[field].ts
@@ -0,0 +1,194 @@
+import { once } from "node:events";
+import { z } from "zod";
+import {
+ InvalidRequestError,
+ LangfuseNotFoundError,
+ UnauthorizedError,
+} from "@langfuse/shared";
+import {
+ getObservationIOFieldByteLengthFromEventsTable,
+ logger,
+ OBSERVATION_IO_STREAM_FIELDS,
+ streamObservationIOFieldFromEventsTable,
+} from "@langfuse/shared/src/server";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ getAuthorizedTrace,
+ type TraceExportAccessSession,
+} from "@/src/features/traces/server/buildTraceExport";
+import { getServerAuthSession } from "@/src/server/auth";
+
+/**
+ * GET /api/traces/:traceId/observations/:observationId/io/:field
+ * ?projectId=...&startTime=<ISO-8601>
+ *
+ * Streams ONE observation's raw IO field (input | output | metadata) as bytes,
+ * piping the ClickHouse response body straight to the client without buffering
+ * the whole value in the Node process. This is the transport enabler for the
+ * lazy/streaming large-JSON viewer (LFE-11081, seeded by LFE-10847 / LFE-10152:
+ * huge single-field payloads crash the browser when fetched+parsed in one shot).
+ *
+ * SECURITY: session-authed and strictly project-scoped. Authorization reuses the
+ * canonical `getAuthorizedTrace` (project membership, public trace/session, or
+ * admin) β€” identical to the trace download route β€” and the underlying query is
+ * pinned to (projectId, traceId, observationId), so a caller can never read
+ * another project's or trace's observation IO.
+ *
+ * v4/events-only: reads `events_full`, matching the events.batchIO read path.
+ */
+
+// traceId / observationId / field are path segments; projectId / startTime are
+// query-string params. All are validated before any data access.
+const querySchema = z.object({
+ traceId: z.string().min(1),
+ observationId: z.string().min(1),
+ field: z.enum(OBSERVATION_IO_STREAM_FIELDS),
+ projectId: z.string().min(1),
+ // The observation's startTime (ISO-8601). Prunes the ClickHouse primary key;
+ // not a security control β€” the tenant scoping above is.
+ startTime: z.coerce.date(),
+});
+
+/**
+ * Shape the NextAuth session into the access-session `getAuthorizedTrace`
+ * expects. Mirrors the trace download route (`/api/traces/[traceId]/download`):
+ * a missing session stays `null` (only public traces are then readable); a
+ * malformed session is rejected.
+ */
+function toTraceAccessSession(
+ session: Awaited<ReturnType<typeof getServerAuthSession>>,
+): TraceExportAccessSession {
+ if (!session) {
+ return null;
+ }
+
+ const { user } = session;
+ if (
+ !user ||
+ typeof user.email !== "string" ||
+ !Array.isArray(user.organizations)
+ ) {
+ throw new UnauthorizedError("Unauthorized");
+ }
+
+ return {
+ user: {
+ email: user.email,
+ admin: user.admin,
+ organizations: user.organizations,
+ },
+ };
+}
+
+export default withMiddlewares({
+ GET: async (req, res) => {
+ // --- Everything that can fail cleanly happens BEFORE any bytes are sent,
+ // so withMiddlewares can still translate errors into a JSON response. ---
+
+ const parsed = querySchema.safeParse({
+ traceId: req.query.traceId,
+ observationId: req.query.observationId,
+ field: req.query.field,
+ projectId: req.query.projectId,
+ startTime: req.query.startTime,
+ });
+ if (!parsed.success) {
+ throw new InvalidRequestError(parsed.error.message);
+ }
+ const { traceId, observationId, field, projectId, startTime } = parsed.data;
+
+ // Authorize the (projectId, traceId) pair. Throws 401/404 before we stream.
+ const session = toTraceAccessSession(
+ await getServerAuthSession({ req, res }),
+ );
+ await getAuthorizedTrace({ traceId, projectId, session });
+
+ // Cheap existence pre-query BEFORE any bytes: a null (no matching row, e.g.
+ // a stale/skewed startTime) becomes a clean 404 instead of a misleading
+ // empty 200. We deliberately do NOT derive a Content-Length from it: the
+ // body is streamed from a *separate* read, and a new event landing between
+ // the two would make a length-vs-body mismatch (truncation is instead
+ // signaled by aborting the socket in the catch below β€” see there).
+ const byteLength = await getObservationIOFieldByteLengthFromEventsTable({
+ projectId,
+ traceId,
+ observationId,
+ field,
+ startTime,
+ });
+ if (byteLength === null) {
+ throw new LangfuseNotFoundError(
+ "Observation IO field not found for the given trace/observation/startTime",
+ );
+ }
+
+ // Resolves once ClickHouse has returned response headers; an immediate query
+ // failure rejects here (pre-headers) and is handled by withMiddlewares.
+ const { stream } = await streamObservationIOFieldFromEventsTable({
+ projectId,
+ traceId,
+ observationId,
+ field,
+ startTime,
+ });
+
+ // --- Headers committed below; from here we must not throw into
+ // withMiddlewares (headers are already sent). ---
+ // Opaque field bytes: input/output may be a bare (unquoted) string rather
+ // than JSON, so we do NOT claim application/json. The consumer knows it is an
+ // IO field and parses accordingly.
+ res.setHeader("Content-Type", "application/octet-stream");
+ // No Content-Length: the exact size would have to come from a second,
+ // independent read that can diverge from the body under concurrent
+ // ingestion. Streamed with chunked transfer-encoding instead; a truncated
+ // body is signaled by a socket abort (catch below), which fails the
+ // client's fetch β€” no false "clean" short read.
+ // Tenant data: never cache in shared/proxy caches.
+ res.setHeader("Cache-Control", "private, no-store");
+ res.setHeader("X-Content-Type-Options", "nosniff");
+ // Range paging is a documented follow-up (see PR); advertise it as
+ // unsupported for now rather than silently ignoring a Range header.
+ res.setHeader("Accept-Ranges", "none");
+ res.status(200);
+
+ // Tear down the ClickHouse read if the client disconnects (mirrors
+ // execute-query-stream.ts). Without this, a disconnect under backpressure
+ // would hang the handler forever and leak the CH connection.
+ let clientClosed = false;
+ const closed = once(res, "close");
+ req.on("close", () => {
+ clientClosed = true;
+ stream.destroy();
+ });
+
+ try {
+ // One chunk at a time (source backpressure); honor sink backpressure via
+ // drain β€” but race drain against `close`, or a disconnect mid-drain would
+ // never settle (`once(res,"drain")` alone hangs on socket close).
+ for await (const chunk of stream) {
+ if (clientClosed) break;
+ if (res.write(chunk) === false) {
+ await Promise.race([once(res, "drain"), closed]);
+ if (clientClosed) break;
+ }
+ }
+ if (!clientClosed) res.end();
+ } catch (error) {
+ // Mid-stream ClickHouse/transport failure after headers were sent. Abort
+ // the socket (res.destroy, not a clean res.end) so the client's fetch
+ // rejects with a connection error instead of seeing a clean 200 whose
+ // body was silently truncated. Do not rethrow (headers already sent).
+ logger.error("[stream-observation-io] mid-stream failure", {
+ error: error instanceof Error ? error.message : String(error),
+ projectId,
+ traceId,
+ observationId,
+ field,
+ });
+ stream.destroy();
+ if (!res.writableEnded && !clientClosed) {
+ res.destroy(error instanceof Error ? error : new Error(String(error)));
+ }
+ }
+ },
+});