πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(trace-batching): add versioned input storage (#19102)
marliessophie01b88c70b54e
diff --git a/.env.dev.example b/.env.dev.exampleindex eab3db383b..4fd32efcfb 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -95,6 +95,10 @@ NEXTAUTH_SECRET="secret"# LANGFUSE_TRACE_BATCH_DISPATCHER_ENABLED=true# QUEUE_CONSUMER_TRACE_BATCH_QUEUE_IS_ENABLED=true# LANGFUSE_TRACE_BATCH_READ_ENABLED=true+# Optional input capture; configure matching bucket retention before enabling.+# LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED=false+# Per-request S3 deadline for input capture; a stalled request releases the Topics slot.+# LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_REQUEST_TIMEOUT_MS=10000# ClickHouse socket idle timeout during streaming, including summary backpressure.# LANGFUSE_TRACE_BATCH_REQUEST_TIMEOUT_MS=40000# Queued input/output/metadata bytes; excludes current trace and object overhead.diff --git a/.env.prod.example b/.env.prod.exampleindex c7d9b3e880..32697bc620 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -624,3 +624,7 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# LANGFUSE_TRACE_BATCH_REQUEST_TIMEOUT_MS=40000# Queued input/output/metadata bytes; excludes current trace and object overhead.# LANGFUSE_TRACE_BATCH_MAX_PENDING_SUMMARY_BYTES=104857600+# Optional cloud trace-batch input capture; requires matching bucket retention.+# LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED=false+# Per-request S3 deadline for input capture; a stalled request releases the Topics slot.+# LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_REQUEST_TIMEOUT_MS=10000diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.mdindex e4ed4aece7..e4d5d878f8 100644--- a/packages/shared/AGENTS.md+++ b/packages/shared/AGENTS.md@@ -152,6 +152,26 @@`orderObservations`, then pass the enriched result and optional`{ maxCharacters?, onTimings? }` to `assembleTranscript`.The optional cap bounds `JSON.stringify(result).length`; see its README.+ `schema.ts` owns the current transcript shape; `types.ts` infers its output+ types. Message/part types come from `src/utils/normalized-io/schema.ts`.++- `src/server/traceBatch`: versioned input storage through the server barrel.+ `createTraceBatchInputStorage()` returns the `TraceBatchInputStorage` interface+ with `put` and `get`, sharing a project/trace/revision key in the event bucket+ and one lazily initialized provider client across factory calls. Consumers+ receive the storage object. The writer takes `TraceBatchInputData` with transcript+ and required `traceContext`; session ID and trace name are nullable. The reader+ requires and returns both. Context timestamps+ stay ISO strings. The writer skips envelopes over 1,000,000 UTF-16+ units; the reader validates the stored version and restores message dates, and+ throws `UnsupportedTraceBatchInputVersionError` for a newer version, which+ callers treat as retryable. Same-revision PUTs may overwrite.+ `src/server/traceBatch/versions/v1.ts` freezes the complete envelope, including+ transcript and trace context, without importing live schemas; `serialization.ts` owns the typed+ transcript adapters and `storage-schema.ts` only probes the version. Compatible+ optional additions may extend V1; anything else starts a new version module+ with its own adapters. Schema versions and readiness revisions are independent;+ see the trace-batch README.- `@langfuse/shared` via `src/index.ts`: default shared surface forcross-runtime types, zod schemas, table definitions, domain models, promptdiff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 7736a34bb6..d08ea8611a 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -331,6 +331,11 @@ const EnvSchema = z.object({.default(3),LANGFUSE_S3_EVENT_UPLOAD_BUCKET: z.string(), // Langfuse requires a bucket name for S3 Event Uploads.LANGFUSE_S3_EVENT_UPLOAD_PREFIX: z.string().default(""),+ LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_REQUEST_TIMEOUT_MS: z.coerce+ .number()+ .int()+ .positive()+ .default(10_000), // 10 secondsLANGFUSE_S3_EVENT_UPLOAD_REGION: z.string().optional(),LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: z.string().optional(),LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: z.string().optional(),diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex d0d367e57e..5fc71e3b6e 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -99,6 +99,7 @@ export * from "../server/ingestion/validateAndInflateScore";export * from "./ingestion/extractToolsBackend";export * from "./normalized-io";export * from "./transcript";+export * from "./traceBatch";export * from "../server/queries/public-api-filter-builder";export * from "../server/pricing-tiers";export * from "./redis/redis";diff --git a/packages/shared/src/server/s3/index.ts b/packages/shared/src/server/s3/index.tsindex c50ccb14cb..92245abc7b 100644--- a/packages/shared/src/server/s3/index.ts+++ b/packages/shared/src/server/s3/index.ts@@ -45,11 +45,12 @@ export const getS3MediaStorageClient = (bucketName: string): StorageService => {* configuration and keep their own instance.** SlowDown is logged as a warning. Ingestion and OTEL jobs escalate to an- * error once their BullMQ attempts are spent.+ * error once their BullMQ attempts are spent. `s3RequestTimeoutMs` bounds each+ * S3 HTTP request for callers that hold a shared resource while uploading.*/export function createEventUploadStorageService(bucketName: string,- options?: { maxAttempts?: number },+ options?: { maxAttempts?: number; s3RequestTimeoutMs?: number },): StorageService {return StorageServiceFactory.getInstance({bucketName,@@ -62,6 +63,7 @@ export function createEventUploadStorageService(awsSseKmsKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_SSE_KMS_KEY_ID,logSlowDownAsWarning: true,maxAttempts: options?.maxAttempts,+ s3RequestTimeoutMs: options?.s3RequestTimeoutMs,});}diff --git a/packages/shared/src/server/traceBatch/README.md b/packages/shared/src/server/traceBatch/README.mdnew file mode 100644index 0000000000..cb67336422--- /dev/null+++ b/packages/shared/src/server/traceBatch/README.md@@ -0,0 +1,36 @@+# Trace-batch input storage++`createTraceBatchInputStorage()` provides `put` and `get` for versioned inputs,+using a project/trace/revision reference and one lazily initialized provider+client shared across factory calls. The live inputs contain a nullable transcript+and required trace context. Session ID and trace name are nullable; context+timestamps stay ISO strings.++## Stored format and versioning++`versions/v1.ts` owns the complete V1 envelope: `schemaVersion`, `transcript`, and+`traceContext`. It freezes the transcript and normalized message schemas with+message dates as ISO strings, importing no live schema. Its compile-time JSON+constraint rejects non-JSON fields. `serialization.ts` owns the typed+`toStoredTranscriptV1` / `fromStoredTranscriptV1` adapters between the live+transcript and V1. `storage-schema.ts` only probes the version before validation+against a supported envelope schema.++Live schema changes do not change V1. When the adapters stop compiling or the+fixture round trip fails, decide: a compatible optional field may be added to V1+if absent values are safe for old readers; anything else starts `versions/v2.ts`+with its own adapters and a read dispatch on the envelope's `schemaVersion`.+Historical versions never import changing current schemas. Deploy readers+accepting both versions before enabling new writers; a reader that meets an+unknown version throws `UnsupportedTraceBatchInputVersionError`, which callers+must treat as retryable. Retries can resolve temporary deployment skew once a+compatible reader is available. Retain old-version readers until old objects+have expired; no rewrite of existing objects is required. Schema versions and+trace-readiness revisions are independent.++The serialization suite round-trips the live transcript fixtures through V1.+The storage suite retains a literal V1 JSON fixture to pin the saved format:++```bash+pnpm --filter @langfuse/shared run test src/server/traceBatch+```diff --git a/packages/shared/src/server/traceBatch/fixtures/inputs-v1.json b/packages/shared/src/server/traceBatch/fixtures/inputs-v1.jsonnew file mode 100644index 0000000000..5f3a473e55--- /dev/null+++ b/packages/shared/src/server/traceBatch/fixtures/inputs-v1.json@@ -0,0 +1,31 @@+{+ "schemaVersion": 1,+ "traceContext": {+ "sessionId": null,+ "traceName": null,+ "traceTimestamp": "2026-10-20T10:00:00.123Z",+ "environment": "production"+ },+ "transcript": {+ "threads": [+ {+ "conversationHistory": [],+ "currentTurn": {+ "nestingLevel": 0,+ "observations": [{ "id": "span", "traceId": "trace" }],+ "messages": [+ {+ "role": "assistant",+ "source": "output",+ "parts": [{ "type": "text", "text": "Hello π" }],+ "observationId": "span",+ "traceId": "trace",+ "startTime": "2026-10-20T10:00:00.123Z",+ "endTime": null+ }+ ]+ }+ }+ ]+ }+}diff --git a/packages/shared/src/server/traceBatch/index.ts b/packages/shared/src/server/traceBatch/index.tsnew file mode 100644index 0000000000..471af5ee79--- /dev/null+++ b/packages/shared/src/server/traceBatch/index.ts@@ -0,0 +1,8 @@+export {+ createTraceBatchInputStorage,+ TRACE_BATCH_INPUT_MAX_CHARACTERS,+ UnsupportedTraceBatchInputVersionError,+ type TraceBatchInputReference,+ type TraceBatchInputData,+ type TraceBatchInputStorage,+} from "./storage";diff --git a/packages/shared/src/server/traceBatch/serialization.test.ts b/packages/shared/src/server/traceBatch/serialization.test.tsnew file mode 100644index 0000000000..21805fcbda--- /dev/null+++ b/packages/shared/src/server/traceBatch/serialization.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vitest";+import { transcriptFixtures } from "../transcript/fixtures";+import { createObservation } from "../test-utils";+import { convertObservation } from "../repositories/observations_converters";+import { orderObservations } from "../transcript/ordering";+import { assembleTranscript } from "../transcript/transcript";+import { toStoredTranscriptV1, fromStoredTranscriptV1 } from "./serialization";+import { traceBatchInputsV1Schema } from "./versions/v1";++describe("trace batch input serialization", () => {+ it.each(transcriptFixtures)("round trips $name", (fixture) => {+ const observations = fixture.observations.map((observation) =>+ convertObservation(createObservation(observation)),+ );+ const transcript = assembleTranscript(orderObservations(observations));+ const stored = JSON.parse(+ JSON.stringify({+ schemaVersion: 1,+ transcript:+ transcript === null ? null : toStoredTranscriptV1(transcript),+ traceContext: {+ sessionId: null,+ traceName: null,+ traceTimestamp: "2026-10-20T10:00:00.123Z",+ environment: "production",+ },+ }),+ );+ const parsed = traceBatchInputsV1Schema.parse(stored);++ expect(+ parsed.transcript === null+ ? null+ : fromStoredTranscriptV1(parsed.transcript),+ ).toEqual(transcript);+ });+});diff --git a/packages/shared/src/server/traceBatch/serialization.ts b/packages/shared/src/server/traceBatch/serialization.tsnew file mode 100644index 0000000000..a83e2df867--- /dev/null+++ b/packages/shared/src/server/traceBatch/serialization.ts@@ -0,0 +1,42 @@+import type { Transcript } from "../transcript/types";+import type { StoredTranscriptV1 } from "./versions/v1";++/**+ * Encode the live transcript as stored V1. Only message dates need conversion;+ * when this stops compiling, the live schema has diverged from V1 and the+ * change needs either a compatible V1 addition or a new version.+ */+export function toStoredTranscriptV1(value: Transcript): StoredTranscriptV1 {+ return {+ ...value,+ threads: value.threads.map((thread) => ({+ ...thread,+ currentTurn: {+ ...thread.currentTurn,+ messages: thread.currentTurn.messages.map((message) => ({+ ...message,+ startTime: message.startTime.toISOString(),+ endTime: message.endTime?.toISOString() ?? null,+ })),+ },+ })),+ };+}++/** Decode an already validated V1 payload into the current transcript representation. */+export function fromStoredTranscriptV1(value: StoredTranscriptV1): Transcript {+ return {+ ...value,+ threads: value.threads.map((thread) => ({+ ...thread,+ currentTurn: {+ ...thread.currentTurn,+ messages: thread.currentTurn.messages.map((message) => ({+ ...message,+ startTime: new Date(message.startTime),+ endTime: message.endTime === null ? null : new Date(message.endTime),+ })),+ },+ })),+ };+}diff --git a/packages/shared/src/server/traceBatch/storage-schema.ts b/packages/shared/src/server/traceBatch/storage-schema.tsnew file mode 100644index 0000000000..a2bfd3c57e--- /dev/null+++ b/packages/shared/src/server/traceBatch/storage-schema.ts@@ -0,0 +1,6 @@+import { z } from "zod";++/** Read before the full schema so a newer version is distinguishable from invalid data. */+export const traceBatchInputsVersionSchema = z.object({+ schemaVersion: z.number(),+});diff --git a/packages/shared/src/server/traceBatch/storage.test.ts b/packages/shared/src/server/traceBatch/storage.test.tsnew file mode 100644index 0000000000..9a90b37142--- /dev/null+++ b/packages/shared/src/server/traceBatch/storage.test.ts@@ -0,0 +1,217 @@+import { Readable } from "node:stream";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { StorageService } from "../services/StorageService";+import type { Transcript } from "../transcript/types";+import storedV1 from "./fixtures/inputs-v1.json";+import { createEventUploadStorageService } from "../s3";+import { createTraceBatchInputStorage } from "./storage";++const storage = vi.hoisted(() => ({+ uploadFile: vi.fn<StorageService["uploadFile"]>(),+ download: vi.fn<StorageService["download"]>(),+}));+vi.mock("../s3", () => ({+ createEventUploadStorageService: vi.fn(() => storage),+}));+vi.mock("../../env", () => ({+ env: {+ LANGFUSE_S3_EVENT_UPLOAD_BUCKET: "events",+ LANGFUSE_S3_EVENT_UPLOAD_PREFIX: "test/",+ LANGFUSE_S3_EVENT_KEY_MAX_SEGMENT_BYTES: 200,+ LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_REQUEST_TIMEOUT_MS: 10_000,+ },+}));++const inputStorage = createTraceBatchInputStorage();++const reference = {+ projectId: "project",+ traceId: "trace",+ revision: "revision",+};++const traceContext = {+ sessionId: null,+ traceName: null,+ traceTimestamp: "2026-10-20T10:00:00.123Z",+ environment: "production",+};++beforeEach(() => {+ storage.uploadFile.mockReset().mockResolvedValue(undefined);+ storage.download.mockReset().mockResolvedValue(JSON.stringify(storedV1));+});++describe("trace batch input storage", () => {+ it("initializes the provider lazily and reuses it across storage instances", async () => {+ vi.resetModules();+ vi.mocked(createEventUploadStorageService).mockClear();+ const { createTraceBatchInputStorage } = await import("./storage.js");+ const first = createTraceBatchInputStorage();+ const second = createTraceBatchInputStorage();+ expect(createEventUploadStorageService).not.toHaveBeenCalled();++ await first.get(reference);+ await second.put(reference, { transcript: null, traceContext });++ expect(createEventUploadStorageService).toHaveBeenCalledExactlyOnceWith(+ "events",+ { s3RequestTimeoutMs: 10_000 },+ );+ });++ it.each([+ { sessionId: "session", traceName: "agent" },+ { sessionId: null, traceName: null },+ ])("round trips nested trace context with %j", async (nullableFields) => {+ const inputs = {+ transcript: transcript(),+ traceContext: {+ ...traceContext,+ ...nullableFields,+ },+ };+ await inputStorage.put(reference, inputs);+ let json = "";+ for await (const chunk of storage.uploadFile.mock.calls[0][0].data)+ json += chunk;+ expect(JSON.parse(json)).toEqual({+ ...storedV1,+ traceContext: inputs.traceContext,+ });+ storage.download.mockResolvedValueOnce(json);+ expect(await inputStorage.get(reference)).toEqual(inputs);+ });++ it("reads the saved v1 format and writes it at the deterministic revision key", async () => {+ const value = transcript();+ const key = "test/trace-batch/trace/ecb/project/trace/revision.json";+ expect(await inputStorage.get(reference)).toEqual({+ transcript: value,+ traceContext,+ });+ expect(storage.download).toHaveBeenCalledWith(key);++ await inputStorage.put(reference, { transcript: value, traceContext });+ const upload = storage.uploadFile.mock.calls[0][0];+ expect(upload).toMatchObject({+ fileName: key,+ fileType: "application/json",+ });+ expect(upload.data).toBeInstanceOf(Readable);+ let json = "";+ for await (const chunk of upload.data) json += chunk;+ expect(JSON.parse(json)).toEqual(storedV1);+ });++ it("reads an explicitly stored null transcript", async () => {+ storage.download.mockResolvedValueOnce(+ JSON.stringify({ schemaVersion: 1, transcript: null, traceContext }),+ );+ expect(await inputStorage.get(reference)).toEqual({+ transcript: null,+ traceContext,+ });+ });++ it.each([1_000_000, 1_000_001])(+ "applies the limit to the complete envelope of length %i",+ async (size) => {+ const value = transcript("");+ const overhead = JSON.stringify({+ schemaVersion: 1,+ transcript: value,+ traceContext,+ }).length;+ value.threads[0].currentTurn.messages[0].parts = [+ { type: "text", text: "x".repeat(size - overhead) },+ ];+ expect(+ await inputStorage.put(reference, {+ transcript: value,+ traceContext,+ }),+ ).toEqual({+ outcome: size > 1_000_000 ? "too_large" : "stored",+ jsonLength: size,+ });+ expect(storage.uploadFile).toHaveBeenCalledTimes(+ size > 1_000_000 ? 0 : 1,+ );+ },+ );++ it("propagates upload and download failures", async () => {+ storage.download.mockRejectedValueOnce(new Error("NoSuchKey"));+ await expect(inputStorage.get(reference)).rejects.toThrow("NoSuchKey");+ storage.uploadFile.mockRejectedValueOnce(new Error("SlowDown"));+ await expect(+ inputStorage.put(reference, { transcript: null, traceContext }),+ ).rejects.toThrow("SlowDown");+ });++ it.each([+ ["invalid JSON", "{"],+ ["missing trace context", '{"schemaVersion":1,"transcript":null}'],+ [+ "unsupported version",+ JSON.stringify({ schemaVersion: 2, transcript: null, traceContext }),+ ],+ [+ "invalid transcript",+ JSON.stringify({+ schemaVersion: 1,+ transcript: { threads: "bad" },+ traceContext,+ }),+ ],+ ...["sessionId", "traceName", "environment", "traceTimestamp"].map(+ (field) => [+ `missing trace context ${field}`,+ JSON.stringify({+ schemaVersion: 1,+ transcript: null,+ traceContext: Object.fromEntries(+ Object.entries(traceContext).filter(([key]) => key !== field),+ ),+ }),+ ],+ ),+ [+ "invalid trace timestamp",+ JSON.stringify({+ schemaVersion: 1,+ transcript: null,+ traceContext: { ...traceContext, traceTimestamp: "not a date" },+ }),+ ],+ ])("rejects %s", async (_label, json) => {+ storage.download.mockResolvedValueOnce(json);+ await expect(inputStorage.get(reference)).rejects.toThrow();+ });+});++function transcript(text = "Hello π"): Transcript {+ return {+ threads: [+ {+ conversationHistory: [],+ currentTurn: {+ nestingLevel: 0,+ observations: [{ id: "span", traceId: "trace" }],+ messages: [+ {+ role: "assistant",+ source: "output",+ parts: [{ type: "text", text }],+ observationId: "span",+ traceId: "trace",+ startTime: new Date("2026-10-20T10:00:00.123Z"),+ endTime: null,+ },+ ],+ },+ },+ ],+ };+}diff --git a/packages/shared/src/server/traceBatch/storage.ts b/packages/shared/src/server/traceBatch/storage.tsnew file mode 100644index 0000000000..91767c1eba--- /dev/null+++ b/packages/shared/src/server/traceBatch/storage.ts@@ -0,0 +1,130 @@+import { Readable } from "node:stream";+import { env } from "../../env";+import { createEventUploadStorageService } from "../s3";+import type { StorageService } from "../services/StorageService";+import {+ safeBlobFilenameStem,+ safeBlobKeySegment,+} from "../services/safeBlobKeySegment";+import type { Transcript } from "../transcript/types";+import { createW3CTraceId } from "../utils/traceId";+import { toStoredTranscriptV1, fromStoredTranscriptV1 } from "./serialization";+import { traceBatchInputsVersionSchema } from "./storage-schema";+import {+ traceBatchInputsV1Schema,+ type TraceBatchInputsV1,+} from "./versions/v1";++export type TraceBatchInputReference = {+ projectId: string;+ traceId: string;+ revision: string;+};++export type TraceBatchInputData = {+ transcript: Transcript | null;+ traceContext: TraceBatchInputsV1["traceContext"];+};++export interface TraceBatchInputStorage {+ /** Ordinary PUT: retries using the same revision can replace the saved input. */+ put(+ reference: TraceBatchInputReference,+ inputs: TraceBatchInputData,+ ): Promise<{ outcome: "stored" | "too_large"; jsonLength: number }>;+ /**+ * Missing objects and invalid JSON propagate to the caller. A newer+ * `schemaVersion` throws `UnsupportedTraceBatchInputVersionError`, which+ * callers must treat as retryable: a later attempt can run on an updated reader.+ */+ get(reference: TraceBatchInputReference): Promise<TraceBatchInputData>;+}++/** The object was written by a newer schema than this reader knows. */+export class UnsupportedTraceBatchInputVersionError extends Error {+ constructor(readonly schemaVersion: number) {+ super(+ `Trace batch input schema version ${schemaVersion} is not supported by this reader.`,+ );+ this.name = "UnsupportedTraceBatchInputVersionError";+ }+}++// UTF-16 length of the complete JSON envelope, not a UTF-8 byte limit.+export const TRACE_BATCH_INPUT_MAX_CHARACTERS = 1_000_000;++let storage: StorageService | undefined;++/** Storage dependencies share one lazily initialized provider client. */+export function createTraceBatchInputStorage(): TraceBatchInputStorage {+ return {+ async put(reference, { transcript, traceContext }) {+ const inputs: TraceBatchInputsV1 = {+ schemaVersion: 1,+ transcript:+ transcript === null ? null : toStoredTranscriptV1(transcript),+ traceContext,+ };+ const json = JSON.stringify(inputs);+ const jsonLength = json.length;+ if (jsonLength > TRACE_BATCH_INPUT_MAX_CHARACTERS)+ return { outcome: "too_large", jsonLength };++ await getStorage().uploadFile({+ fileName: getTraceBatchInputsKey(reference),+ fileType: "application/json",+ // Stream the serialized text so providers handle its UTF-8 byte length.+ data: Readable.from([json]),+ });+ return { outcome: "stored", jsonLength };+ },+ async get(reference) {+ const json = await getStorage().download(+ getTraceBatchInputsKey(reference),+ );+ const stored: unknown = JSON.parse(json);+ const envelope = traceBatchInputsVersionSchema.safeParse(stored);+ if (envelope.success && envelope.data.schemaVersion !== 1)+ throw new UnsupportedTraceBatchInputVersionError(+ envelope.data.schemaVersion,+ );+ const inputs = traceBatchInputsV1Schema.parse(stored);+ return {+ transcript:+ inputs.transcript === null+ ? null+ : fromStoredTranscriptV1(inputs.transcript),+ traceContext: inputs.traceContext,+ };+ },+ };+}++/** Each S3 request is bounded so a stalled upload cannot hold a Topics slot indefinitely. */+function getStorage(): StorageService {+ if (!storage)+ storage = createEventUploadStorageService(+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ {+ // This timeout applies only to S3; Azure, GCS, and OCI retain their provider defaults.+ s3RequestTimeoutMs:+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_REQUEST_TIMEOUT_MS,+ },+ );+ return storage;+}++function getTraceBatchInputsKey({+ projectId,+ traceId,+ revision,+}: TraceBatchInputReference): string {+ const safeProjectId = safeBlobKeySegment(projectId);+ const safeTraceId = safeBlobKeySegment(traceId);+ const safeRevision = safeBlobFilenameStem(revision, ".json");+ const hash = createW3CTraceId(JSON.stringify([projectId, traceId])).slice(+ 0,+ 3,+ );+ return `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}trace-batch/trace/${hash}/${safeProjectId}/${safeTraceId}/${safeRevision}.json`;+}diff --git a/packages/shared/src/server/traceBatch/versions/v1.ts b/packages/shared/src/server/traceBatch/versions/v1.tsnew file mode 100644index 0000000000..caeeea78f4--- /dev/null+++ b/packages/shared/src/server/traceBatch/versions/v1.ts@@ -0,0 +1,172 @@+import { z } from "zod";+import type { JsonValue } from "../../../utils/normalized-io/types";++/**+ * Trace-batch input format V1: a frozen envelope and copy of the transcript+ * and normalized message schemas, with message dates as ISO strings. This file+ * imports no live schema, so the live shape can change without changing what V1+ * accepts. V1 may only gain optional fields whose+ * absence is safe for old readers; anything else starts `v2.ts`.+ */++const jsonValue: z.ZodType<JsonValue, JsonValue> = z.json();++/** ISO 8601 timestamp as produced by `Date.prototype.toISOString`. */+const isoTimestampSchema = z.iso.datetime();++const partBase = z.object({+ providerMetadata: z.record(z.string(), jsonValue).optional(),+});++const textPart = partBase.extend({+ type: z.literal("text"),+ text: z.string(),+ refusal: z.literal(true).optional(),+});++const reasoningPart = partBase.extend({+ type: z.literal("reasoning"),+ content: z.discriminatedUnion("kind", [+ z.object({+ kind: z.literal("text"),+ text: z.string(),+ signature: z.string().optional(),+ }),+ z.object({ kind: z.literal("redacted"), data: z.string() }),+ z.object({ kind: z.literal("encrypted"), data: z.string() }),+ z.object({ kind: z.literal("data"), value: jsonValue }),+ ]),+});++const filePart = partBase.extend({+ type: z.literal("file"),+ mediaType: z.string().optional(),+ filename: z.string().optional(),+ reasoning: z.literal(true).optional(),+ content: z.discriminatedUnion("kind", [+ z.object({ kind: z.literal("url"), url: z.string() }),+ z.object({ kind: z.literal("base64"), data: z.string() }),+ z.object({ kind: z.literal("reference"), id: z.string() }),+ ]),+});++const dataPart = partBase.extend({+ type: z.literal("data"),+ name: z.string().optional(),+ value: jsonValue,+});++const customPart = partBase.extend({+ type: z.literal("custom"),+ kind: z.string(),+ value: jsonValue,+});++const toolCallPart = partBase.extend({+ type: z.literal("tool-call"),+ toolCallId: z.string().nullable(),+ toolName: z.string(),+ input: jsonValue,+ toolType: z.string().optional(),+ providerExecuted: z.boolean().optional(),+ invalid: z.literal(true).optional(),+});++const toolResultContentPart = z.discriminatedUnion("type", [+ textPart,+ reasoningPart,+ filePart,+ dataPart,+ customPart,+]);++const toolResultOutput = z.discriminatedUnion("type", [+ z.object({ type: z.literal("text"), value: z.string() }),+ z.object({ type: z.literal("json"), value: jsonValue }),+ z.object({+ type: z.literal("content"),+ value: z.array(toolResultContentPart),+ }),+]);++const toolResultPart = partBase.extend({+ type: z.literal("tool-result"),+ toolCallId: z.string().nullable(),+ toolName: z.string().optional(),+ isError: z.boolean().optional(),+ output: toolResultOutput,+});++const messagePart = z.discriminatedUnion("type", [+ textPart,+ reasoningPart,+ toolCallPart,+ toolResultPart,+ filePart,+ dataPart,+ customPart,+]);++const finishReason = z.object({+ type: z.enum([+ "stop",+ "length",+ "tool-calls",+ "content-filter",+ "error",+ "other",+ "unknown",+ ]),+ raw: z.string(),+});++const message = z.object({+ id: z.string().optional(),+ role: z.enum(["system", "user", "assistant", "tool"]),+ senderName: z.string().optional(),+ parts: z.array(messagePart),+ finishReason: finishReason.optional(),+ source: z.enum(["input", "output"]),+});++const threadMessage = message.extend({+ observationId: z.string(),+ traceId: z.string(),+ startTime: isoTimestampSchema,+ endTime: isoTimestampSchema.nullable(),+});++const turn = z.object({+ nestingLevel: z.number().int().nonnegative(),+ messages: z.array(threadMessage),+ observations: z.array(z.object({ id: z.string(), traceId: z.string() })),+});++const thread = z.object({+ conversationHistory: z.array(message),+ currentTurn: turn,+});++/** The stored V1 transcript; the JSON constraint rejects any non-JSON field. */+const storedTranscriptV1Schema = z.object({+ threads: z.array(thread),+ truncated: z.literal(true).optional(),+}) satisfies z.ZodType<JsonValue>;++export type StoredTranscriptV1 = z.infer<typeof storedTranscriptV1Schema>;++// Add breaking versions alongside v1; deploy readers before enabling new writers.+export const traceBatchInputsV1Schema = z.object({+ schemaVersion: z.literal(1),+ transcript: storedTranscriptV1Schema.nullable(),+ // Mirrors the event observation domain fields without importing the domain+ // schema; the writer's typed assignment keeps both compatible.+ traceContext: z.object({+ sessionId: z.string().nullable(),+ traceTimestamp: isoTimestampSchema,+ environment: z.string(),+ traceName: z.string().nullable(),+ }),+}) satisfies z.ZodType<JsonValue>;++export type TraceBatchInputsV1 = z.infer<typeof traceBatchInputsV1Schema>;diff --git a/packages/shared/src/server/transcript/README.md b/packages/shared/src/server/transcript/README.mdindex 089fc5ae6e..dce55f6acd 100644--- a/packages/shared/src/server/transcript/README.md+++ b/packages/shared/src/server/transcript/README.md@@ -82,6 +82,19 @@ remove that second input. Such an extension should keep conversation assemblyand trace-level facts distinct, so root I/O and operation metadata do not becomeduplicate conversation messages.+## Schema++`schema.ts` owns the current transcript shape and composes the message/part schemas+from `utils/normalized-io/schema.ts`. `types.ts` infers the output types from those+schemas; assembly inputs and options remain separate. Assembly does not parse+each intermediate object at runtime.++Persisted trace-batch inputs have their own frozen schemas and serialization+adapters under [`../traceBatch`](../traceBatch/README.md). They version the+complete storage envelope, including the transcript and trace context.+The transcript fixture suite validates the current assembled shape independently+of that storage format.+## Character limit`assembleTranscript(observations, { maxCharacters: 10_000 })` guarantees@@ -279,7 +292,8 @@ transcript/βββ replay.ts createMessageDeduplicatorβββ threads.ts thread selection and message appendingβββ tool-calls.ts tool matching and response association-βββ types.ts Transcript, Thread, Turn, ThreadMessage+βββ schema.ts current transcript shape, composing normalized message schemas+βββ types.ts inferred output types, assembly inputs and optionsβββ fixtures/βββ fixture-types.ts TranscriptFixtureβββ index.ts registry of fixturesdiff --git a/packages/shared/src/server/transcript/fixtures/fixtures.test.ts b/packages/shared/src/server/transcript/fixtures/fixtures.test.tsindex 2cab58cf5b..6e33e806cc 100644--- a/packages/shared/src/server/transcript/fixtures/fixtures.test.ts+++ b/packages/shared/src/server/transcript/fixtures/fixtures.test.ts@@ -4,6 +4,8 @@ import { createObservation } from "../../test-utils";import { convertObservation } from "../../repositories/observations_converters";import { orderObservations } from "../ordering";import { assembleTranscript } from "../transcript";+import { transcriptSchema } from "../schema";+describe("transcript fixtures", () => {const traceId = "trace";const generation = (id: string, input: string[], output: string[]) => ({@@ -473,9 +475,9 @@ describe("transcript fixtures", () => {convertObservation(createObservation(observation)),);const snapshot = structuredClone(observations);- expect(assembleTranscript(orderObservations(observations))).toEqual(- fixture.expected,- );+ const transcript = assembleTranscript(orderObservations(observations));+ expect(transcript).toEqual(fixture.expected);+ expect(transcriptSchema.nullable().parse(transcript)).toEqual(transcript);expect(observations).toEqual(snapshot);});});diff --git a/packages/shared/src/server/transcript/schema.ts b/packages/shared/src/server/transcript/schema.tsnew file mode 100644index 0000000000..a0f5babf55--- /dev/null+++ b/packages/shared/src/server/transcript/schema.ts@@ -0,0 +1,35 @@+import { z } from "zod";+import { normalizedMessageSchema } from "../../utils/normalized-io/schema";++export const threadMessageSchema = normalizedMessageSchema.extend({+ /** Observation that first emitted this message. */+ observationId: z.string(),+ /** Trace of the emitting observation, including transcripts spanning several traces. */+ traceId: z.string(),+ /** Source observation start time, not the individual message time. */+ startTime: z.date(),+ /** Source observation end time; null while unavailable. */+ endTime: z.date().nullable(),+});++/** Messages of one turn with the observations that emitted them. */+export const turnSchema = z.object({+ /** Tree depth of the first contributing generation; fetched roots are level 0. */+ nestingLevel: z.number().int().nonnegative(),+ messages: z.array(threadMessageSchema),+ /** Observations that contributed to this turn, in contribution order. */+ observations: z.array(z.object({ id: z.string(), traceId: z.string() })),+});++export const threadSchema = z.object({+ /** Messages replayed from earlier turns, in replay order, without provenance. */+ conversationHistory: z.array(normalizedMessageSchema),+ /** Messages the supplied observations added to the conversation. */+ currentTurn: turnSchema,+});++export const transcriptSchema = z.object({+ threads: z.array(threadSchema),+ /** The character limit shortened text or omitted messages. */+ truncated: z.literal(true).optional(),+});diff --git a/packages/shared/src/server/transcript/types.ts b/packages/shared/src/server/transcript/types.tsindex 8a2b4a162c..67042b7ee6 100644--- a/packages/shared/src/server/transcript/types.ts+++ b/packages/shared/src/server/transcript/types.ts@@ -1,4 +1,10 @@-import type { NormalizedMessage } from "../../utils/normalized-io/types";+import type { z } from "zod";+import type {+ threadMessageSchema,+ turnSchema,+ threadSchema,+ transcriptSchema,+} from "./schema";import type { Observation } from "../../domain";export type TranscriptOptions = {@@ -26,36 +32,7 @@ export type TranscriptObservation = Pick<| "metadata">;-export type ThreadMessage = NormalizedMessage & {- /** Observation that first emitted this message. */- observationId: string;- /** Trace the emitting observation belongs to. Helpful when the transcript- * spans several traces, for example one session. */- traceId: string;- /** Start time of the source observation, not the individual message. */- startTime: Date;- /** End time of the source observation; null while unavailable. */- endTime: Date | null;-};--/** Messages of one turn with the observations that emitted them. */-export type Turn = {- /** Tree depth of the first contributing generation; fetched roots are level 0. */- nestingLevel: number;- messages: ThreadMessage[];- /** Observations that contributed to this turn, in contribution order. */- observations: { id: string; traceId: string }[];-};--export type Thread = {- /** Messages replayed from earlier turns, in replay order, without provenance. */- conversationHistory: NormalizedMessage[];- /** Messages the supplied observations added to the conversation. */- currentTurn: Turn;-};--export type Transcript = {- threads: Thread[];- /** The character limit shortened text or omitted messages. */- truncated?: true;-};+export type ThreadMessage = z.infer<typeof threadMessageSchema>;+export type Turn = z.infer<typeof turnSchema>;+export type Thread = z.infer<typeof threadSchema>;+export type Transcript = z.infer<typeof transcriptSchema>;diff --git a/packages/shared/src/utils/normalized-io/README.md b/packages/shared/src/utils/normalized-io/README.mdindex 4245bdbcf4..8cf4f74335 100644--- a/packages/shared/src/utils/normalized-io/README.md+++ b/packages/shared/src/utils/normalized-io/README.md@@ -36,6 +36,11 @@ Known fields become the normalized shape. Anything else is kept in## Interface+`schema.ts` owns the canonical message and content-part shapes. Their public+TypeScript types in `types.ts` are inferred from Zod; type-only imports keep runtime+schemas out of consumers that only need types. Raw `SpanIO`, assembly-independent+tool definitions and compatibility-column types remain separate.+```tsnormalizeIO(source: NormalizeIOSource): NormalizedIOdiff --git a/packages/shared/src/utils/normalized-io/conventions/providers/anthropic/anthropic.test.ts b/packages/shared/src/utils/normalized-io/conventions/providers/anthropic/anthropic.test.tsindex 4dcc8a469c..fd889456ba 100644--- a/packages/shared/src/utils/normalized-io/conventions/providers/anthropic/anthropic.test.ts+++ b/packages/shared/src/utils/normalized-io/conventions/providers/anthropic/anthropic.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import { normalizeSpanIO } from "../../../parser";+import { normalizedMessageSchema } from "../../../schema";import {anthropicMessagesRawServerToolsAndMediaFixture,anthropicMessagesRichContentFixture,@@ -15,9 +16,13 @@ describe("Anthropic normalized I/O", () => {anthropicMessagesRawServerToolsAndMediaFixture,anthropicMessagesRichContentFixture,])("$name", ({ spanIO, expected }) => {- expect(normalizeSpanIO(spanIO)).toEqual({+ const actual = normalizeSpanIO(spanIO);+ expect(actual).toEqual({...expected,span: spanIO,});+ expect(normalizedMessageSchema.array().parse(actual.messages)).toEqual(+ actual.messages,+ );});});diff --git a/packages/shared/src/utils/normalized-io/conventions/providers/openai/openai.test.ts b/packages/shared/src/utils/normalized-io/conventions/providers/openai/openai.test.tsindex c0454d6f22..689b2bf5bf 100644--- a/packages/shared/src/utils/normalized-io/conventions/providers/openai/openai.test.ts+++ b/packages/shared/src/utils/normalized-io/conventions/providers/openai/openai.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import { normalizeSpanIO } from "../../../parser";+import { normalizedMessageSchema } from "../../../schema";import {capturedTraceFixtures,customerFixtures,@@ -23,9 +24,13 @@ describe("OpenAI normalized I/O", () => {openAiResponsesBuiltInToolsAndMediaFixture,openAiResponsesReasoningWithParallelCallsFixture,])("$name", ({ spanIO, expected }) => {- expect(normalizeSpanIO(spanIO)).toEqual({+ const actual = normalizeSpanIO(spanIO);+ expect(actual).toEqual({...expected,span: spanIO,});+ expect(normalizedMessageSchema.array().parse(actual.messages)).toEqual(+ actual.messages,+ );});});diff --git a/packages/shared/src/utils/normalized-io/schema.ts b/packages/shared/src/utils/normalized-io/schema.tsnew file mode 100644index 0000000000..d26b75028b--- /dev/null+++ b/packages/shared/src/utils/normalized-io/schema.ts@@ -0,0 +1,187 @@+import { z } from "zod";+import type { JsonValue } from "./types";++// Pins inferred and emitted types to the public JSON type instead of Zod's+// internal JSONType, on both the input and the output side.+const jsonValueSchema: z.ZodType<JsonValue, JsonValue> = z.json();++/**+ * Semantics the parser computes are typed fields on their parts (for example+ * `refusal`, `reasoning`, `invalid`). `providerMetadata` preserves every raw+ * provider field the canonical part did not consume, plus parser-derived+ * provider payloads such as unified citations. New provider concepts start in+ * `providerMetadata` and are promoted to a typed field once they are+ * cross-provider semantics that consumers filter on.+ */+export const normalizedPartBaseSchema = z.object({+ /** Raw provider fields the canonical part did not consume, plus derived payloads such as citations. */+ providerMetadata: z.record(z.string(), jsonValueSchema).optional(),+});++export const textPartSchema = normalizedPartBaseSchema.extend({+ type: z.literal("text"),+ text: z.string(),+ /**+ * Model refusal text (OpenAI refusal parts, `message.refusal`). Stays in the+ * conversation stream and is filterable for evals.+ */+ refusal: z.literal(true).optional(),+});++/**+ * One reasoning part with a discriminated payload instead of per-provider part+ * types, mirroring file content:+ * - `text`: visible chain-of-thought or summaries; Anthropic's integrity+ * `signature` rides along because it certifies exactly that text.+ * - `redacted`: a blob the provider withheld (Anthropic redacted_thinking).+ * - `encrypted`: a blob the provider returns for replay (OpenAI Responses+ * encrypted_content).+ * - `data`: structured or unrecognized reasoning payloads.+ * Opaque blobs are first-class stream elements rather than providerMetadata+ * piggybacks so replay and audit consumers can find them.+ */+export const reasoningPartSchema = normalizedPartBaseSchema.extend({+ type: z.literal("reasoning"),+ content: z.discriminatedUnion("kind", [+ z.object({+ kind: z.literal("text"),+ text: z.string(),+ signature: z.string().optional(),+ }),+ z.object({ kind: z.literal("redacted"), data: z.string() }),+ z.object({ kind: z.literal("encrypted"), data: z.string() }),+ z.object({ kind: z.literal("data"), value: jsonValueSchema }),+ ]),+});++export const filePartSchema = normalizedPartBaseSchema.extend({+ type: z.literal("file"),+ /**+ * IANA media type when the source declares one (data-URI prefix, Langfuse+ * media reference token, explicit format field). A modality wildcard such as+ * `image/*` when only the part kind reveals the modality. Absent when the+ * source gives no signal, for example an opaque file id.+ */+ mediaType: z.string().optional(),+ filename: z.string().optional(),+ /** File produced as reasoning output (for example AI SDK reasoning-file). */+ reasoning: z.literal(true).optional(),+ content: z.discriminatedUnion("kind", [+ z.object({ kind: z.literal("url"), url: z.string() }),+ z.object({ kind: z.literal("base64"), data: z.string() }),+ z.object({ kind: z.literal("reference"), id: z.string() }),+ ]),+});++export const dataPartSchema = normalizedPartBaseSchema.extend({+ type: z.literal("data"),+ name: z.string().optional(),+ value: jsonValueSchema,+});++export const customPartSchema = normalizedPartBaseSchema.extend({+ type: z.literal("custom"),+ kind: z.string(),+ value: jsonValueSchema,+});++export const toolCallPartSchema = normalizedPartBaseSchema.extend({+ type: z.literal("tool-call"),+ toolCallId: z.string().nullable(),+ toolName: z.string(),+ input: jsonValueSchema,+ /**+ * Raw source type used by compatibility projections, for example `function`,+ * `custom`, or a provider-specific built-in kind.+ */+ toolType: z.string().optional(),+ providerExecuted: z.boolean().optional(),+ /**+ * Attempt the model made whose arguments could not be parsed (for example+ * LangChain invalid_tool_calls). Visible in the stream and filterable for+ * evals; excluded from the tool columns, which count executable calls.+ */+ invalid: z.literal(true).optional(),+});++/** Content belonging to one execution; nested calls/results are not content. */+export const toolResultContentPartSchema = z.discriminatedUnion("type", [+ textPartSchema,+ reasoningPartSchema,+ filePartSchema,+ dataPartSchema,+ customPartSchema,+]);++export const toolResultOutputSchema = z.discriminatedUnion("type", [+ z.object({ type: z.literal("text"), value: z.string() }),+ z.object({ type: z.literal("json"), value: jsonValueSchema }),+ z.object({+ type: z.literal("content"),+ value: z.array(toolResultContentPartSchema),+ }),+]);++export const toolResultPartSchema = normalizedPartBaseSchema.extend({+ type: z.literal("tool-result"),+ toolCallId: z.string().nullable(),+ toolName: z.string().optional(),+ isError: z.boolean().optional(),+ output: toolResultOutputSchema,+});++export const normalizedMessagePartSchema = z.discriminatedUnion("type", [+ textPartSchema,+ reasoningPartSchema,+ toolCallPartSchema,+ toolResultPartSchema,+ filePartSchema,+ dataPartSchema,+ customPartSchema,+]);++export const normalizedMessageRoleSchema = z.enum([+ "system",+ "user",+ "assistant",+ "tool",+]);++/**+ * How the model's turn ended, canonicalized across providers so consumers+ * filter one vocabulary (for example "all length-truncated observations").+ * `raw` keeps the provider's verbatim value, so canonicalization loses nothing+ * (`{ type: "stop", raw: "stop_sequence" }` versus natural completion).+ */+export const finishReasonSchema = z.object({+ type: z.enum([+ "stop",+ "length",+ "tool-calls",+ "content-filter",+ "error",+ "other",+ "unknown",+ ]),+ raw: z.string(),+});++export const normalizedMessageSchema = z.object({+ id: z.string().optional(),+ role: normalizedMessageRoleSchema,+ /**+ * Sender identity beyond the canonical role: an explicit participant name+ * (OpenAI/LangChain `name`, for example `alice` or `example_user`) or the raw+ * declared role when it is not a recognized role, as multi-agent frameworks+ * do when they put the agent name in the role field.+ */+ senderName: z.string().optional(),+ parts: z.array(normalizedMessagePartSchema),+ /**+ * Turn metadata, not conversation content: a message field rather than a part+ * so text extraction, rendering and tool-column paths stay untouched.+ */+ finishReason: finishReasonSchema.optional(),+ /** Preserves the observation input/output boundary in one ordered stream. */+ source: z.enum(["input", "output"]),+});diff --git a/packages/shared/src/utils/normalized-io/types.ts b/packages/shared/src/utils/normalized-io/types.tsindex ded2325bb1..9630549b18 100644--- a/packages/shared/src/utils/normalized-io/types.ts+++ b/packages/shared/src/utils/normalized-io/types.ts@@ -1,3 +1,21 @@+import type { z } from "zod";+import type {+ normalizedPartBaseSchema,+ textPartSchema,+ reasoningPartSchema,+ toolCallPartSchema,+ toolResultContentPartSchema,+ toolResultOutputSchema,+ toolResultPartSchema,+ filePartSchema,+ dataPartSchema,+ customPartSchema,+ normalizedMessagePartSchema,+ normalizedMessageRoleSchema,+ finishReasonSchema,+ normalizedMessageSchema,+} from "./schema";+/*** The transport-independent observation I/O boundary.*@@ -17,160 +35,28 @@ export type JsonObject = { [key: string]: JsonValue };export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];-/**- * Semantics the parser computes are typed fields on their parts (e.g.- * `refusal`, `reasoning`, `invalid`); `providerMetadata` preserves every raw- * provider field that the canonical part did not consume, plus parser-derived- * provider payloads such as unified citations.- * Part types encode what a consumer can do with a part; new provider- * concepts start as providerMetadata and get promoted to a typed field once- * they are cross-provider semantics we compute and consumers filter on.- */-export type NormalizedPartBase = {- providerMetadata?: JsonObject;-};--export type TextPart = NormalizedPartBase & {- type: "text";- /** Model refusal text (OpenAI refusal parts / `message.refusal`) β stays- * in the conversation stream, filterable for evals. */- refusal?: true;- text: string;-};--/**- * One reasoning part type with a discriminated payload instead of- * per-provider part types (mirrors FilePart.content):- * - `text` β visible chain-of-thought or summaries; Anthropic's integrity- * `signature` rides on it since it certifies exactly that text.- * - `redacted` β a blob the provider withheld (Anthropic redacted_thinking).- * - `encrypted` β a blob the provider returns for replay (OpenAI Responses- * encrypted_content).- * - `data` β structured/unrecognized reasoning payloads.- * Opaque blobs are first-class stream elements rather than providerMetadata- * piggybacks so replay and audit consumers can find them.- */-export type ReasoningPart = NormalizedPartBase & {- type: "reasoning";- content:- | { kind: "text"; text: string; signature?: string }- | { kind: "redacted"; data: string }- | { kind: "encrypted"; data: string }- | { kind: "data"; value: JsonValue };-};--export type ToolCallPart = NormalizedPartBase & {- type: "tool-call";- toolCallId: string | null;- toolName: string;- input: JsonValue;- /** Raw source type used by compatibility projections (for example- * `function`, `custom`, or a provider-specific built-in kind). */- toolType?: string;- providerExecuted?: boolean;- /** Attempt the model made whose arguments could not be parsed (e.g.- * LangChain invalid_tool_calls). Visible in the stream, filterable for- * evals; excluded from the tool columns, which count executable calls. */- invalid?: true;-};+// Part and message types are inferred from `schema.ts`, which carries the field+// documentation; hovering a field shows it. Type-level rationale lives on the+// schema constants.+/** Shared by every part; `providerMetadata` holds what the canonical part did not consume. */+export type NormalizedPartBase = z.infer<typeof normalizedPartBaseSchema>;+export type TextPart = z.infer<typeof textPartSchema>;+/** Reasoning with a discriminated payload (`text`, `redacted`, `encrypted`, `data`). */+export type ReasoningPart = z.infer<typeof reasoningPartSchema>;+export type ToolCallPart = z.infer<typeof toolCallPartSchema>;/** Content belonging to one execution; nested calls/results are not content. */-export type ToolResultContentPart =- | TextPart- | DataPart- | FilePart- | ReasoningPart- | CustomPart;--export type ToolResultOutput =- | { type: "text"; value: string }- | { type: "json"; value: JsonValue }- | { type: "content"; value: ToolResultContentPart[] };--export type ToolResultPart = NormalizedPartBase & {- type: "tool-result";- toolCallId: string | null;- toolName?: string;- output: ToolResultOutput;- isError?: boolean;-};--export type FilePart = NormalizedPartBase & {- type: "file";- /**- * IANA media type when the source declares one (data-URI prefix, Langfuse- * media reference token, explicit format field). Modality wildcards like- * `image/*` / `audio/*` when only the part kind reveals the modality;- * absent when the source gives no signal (e.g. an opaque file id).- */- mediaType?: string;- filename?: string;- /** File was produced as reasoning output (e.g. AI SDK reasoning-file). */- reasoning?: true;- content:- | { kind: "url"; url: string }- | { kind: "base64"; data: string }- | { kind: "reference"; id: string };-};--export type DataPart = NormalizedPartBase & {- type: "data";- name?: string;- value: JsonValue;-};--export type CustomPart = NormalizedPartBase & {- type: "custom";- kind: string;- value: JsonValue;-};--export type NormalizedMessagePart =- | TextPart- | ReasoningPart- | ToolCallPart- | ToolResultPart- | FilePart- | DataPart- | CustomPart;--export type NormalizedMessageRole = "system" | "user" | "assistant" | "tool";--/**- * How the model's turn ended, canonicalized across providers so consumers- * filter one vocabulary (e.g. "all length-truncated observations"). `raw`- * keeps the provider's verbatim value, so canonicalization loses nothing- * (e.g. { type: "stop", raw: "stop_sequence" } vs natural completion).- */-export type FinishReason = {- type:- | "stop"- | "length"- | "tool-calls"- | "content-filter"- | "error"- | "other"- | "unknown";- raw: string;-};--export type NormalizedMessage = {- id?: string;- role: NormalizedMessageRole;- /**- * Sender identity beyond the canonical role: an explicit participant name- * (OpenAI/LangChain `name`, e.g. `alice` or `example_user`) or the raw- * declared role when it is not a recognized role (e.g. multi-agent frameworks- * putting the agent name in the role field)- */- senderName?: string;- parts: NormalizedMessagePart[];- // Turn metadata, not conversation content β a message field rather than a- // part so text extraction, rendering, and tool-column paths stay untouched.- finishReason?: FinishReason;- // Preserves the observation input/output boundary in one ordered stream.- source: "input" | "output";-};+export type ToolResultContentPart = z.infer<typeof toolResultContentPartSchema>;+export type ToolResultOutput = z.infer<typeof toolResultOutputSchema>;+export type ToolResultPart = z.infer<typeof toolResultPartSchema>;+export type FilePart = z.infer<typeof filePartSchema>;+export type DataPart = z.infer<typeof dataPartSchema>;+export type CustomPart = z.infer<typeof customPartSchema>;+export type NormalizedMessagePart = z.infer<typeof normalizedMessagePartSchema>;+export type NormalizedMessageRole = z.infer<typeof normalizedMessageRoleSchema>;+/** Canonical finish reason with the provider's verbatim value in `raw`. */+export type FinishReason = z.infer<typeof finishReasonSchema>;+export type NormalizedMessage = z.infer<typeof normalizedMessageSchema>;export type ToolDefinition = {name: string;diff --git a/worker/AGENTS.md b/worker/AGENTS.mdindex 1f9d585813..385bc3260f 100644--- a/worker/AGENTS.md+++ b/worker/AGENTS.md@@ -86,6 +86,18 @@metrics. Token estimates run sequentially;tool-response size uses comparable character counts over message parts.Allowlisted projects are then summarized from that assembled transcript.+ Optional `src/features/traceBatching/storeInputs.ts` capture runs after Topics+ eligibility/sampling, within the same concurrency limit, using the queued+ revision. The queue creates `createTraceBatchInputStorage()` once and injects+ its `TraceBatchInputStorage` object into `storeInputs`. Store+ `{ transcript, traceContext }` using the same metadata selection+ as Topics; preserve nullable session ID/name in storage and apply the Topics+ name fallback only at its call site. The shared orchestration checks the latest+ event's environment before capture or Topics; internal eval environments skip both.+ `LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED` defaults off; each S3 upload+ request is bounded by `LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_REQUEST_TIMEOUT_MS`.+ Oversized inputs and exhausted storage errors leave in-memory Topics running;+ file-dependent consumers must require successful storage before scheduling.Allow one pending tokenization promise per batch whilebuffering completed traces behind the serial summary chain. Pause reads onlyabove the configured queued-payload threshold, then resume as soon as completeddiff --git a/worker/src/env.ts b/worker/src/env.tsindex 8bdf3c5ad7..09f87e93fa 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -158,6 +158,9 @@ const EnvSchema = z.object({.enum(["true", "false"]).default("false"),LANGFUSE_TRACE_BATCH_READ_ENABLED: z.enum(["true", "false"]).default("false"),+ LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED: z+ .enum(["true", "false"])+ .default("false"),LANGFUSE_TRACE_BATCH_TRANSCRIPT_METRICS_ENABLED: z.enum(["true", "false"]).default("false"),diff --git a/worker/src/features/traceBatching/README.md b/worker/src/features/traceBatching/README.mdindex 37f8feb7ac..b90e58c1c2 100644--- a/worker/src/features/traceBatching/README.md+++ b/worker/src/features/traceBatching/README.md@@ -293,6 +293,132 @@ rather than accepting partial results. Beyond the dispatcher's weight budgetsand trace exclusion, this does not cap observation count, query memory ordispatcher snapshot memory.+## Optional input storage++`LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED=false` controls writes only.+When enabled, `storeInputs.ts` captures the assembled transcript for traces that+pass the internal-environment exclusion, Topics settings and rule sampling gate.+The latest event's environment determines eligibility for both capture and Topics.+It runs inside the+Topics concurrency limit alongside in-memory summarization. Both operations must+settle before releasing the slot, including when summarization fails. Each S3+request is bounded by `LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_REQUEST_TIMEOUT_MS`+(default 10 seconds) so a stalled request cannot hold a slot indefinitely; the+SDK attempt budget stays at its default. It does not capture every trace admitted+by experimental batching.++The shared `server/traceBatch` module uses the event-upload bucket and credentials:++```text+<prefix>trace-batch/trace/<hash>/<projectId>/<safeTraceId>/<revision>.json+```++`hash` is the first three hex characters of SHA-256 over+`JSON.stringify([projectId, traceId])`. Identifiers use the shared blob-key+escaping helpers. The revision comes from the queued readiness entry; a new+revision uses another key, while an ordinary PUT of the same revision can replace+its object. A reader needs all three identifiers; no latest-revision lookup or+durable job reference is stored.++Objects contain a versioned envelope:++```ts+{+ schemaVersion: 1,+ transcript: StoredTranscriptV1 | null,+ traceContext: {+ sessionId: string | null,+ traceTimestamp: string, // ISO timestamp+ environment: string,+ traceName: string | null,+ },+}+```++The queue creates `inputStorage` with `createTraceBatchInputStorage()` and passes+it into `storeInputs`. The factory returns the `TraceBatchInputStorage` interface+with `put` and `get`; all instances share one lazily initialized provider client.+Feature gating, instrumentation and tolerated failures remain in `storeInputs`.++`inputStorage.put(reference, { transcript, traceContext })` requires all context+fields, with null for an absent session ID or name. Context fields mirror the+event-domain field shapes without importing the domain schema; the writer's typed+assignment keeps them compatible. Context uses the existing Topics selection: earliest observation start,+newest nonempty session ID, newest-event environment and first observation name.+The transcript alone cannot reconstruct this context. The original job enqueue+time remains execution state rather than trace context.++The trace-batch module freezes the complete stored V1 envelope in+`traceBatch/versions/v1.ts`, including trace context and copies of the transcript+and normalized message schemas without importing live schemas. Its serialization+module owns the typed adapters between the live transcript and V1. Message dates are+serialized as ISO strings. `inputStorage.get(reference)` returns+`{ transcript, traceContext }`, validates nested content and restores message+dates; `traceContext.traceTimestamp` remains an ISO string. Missing context,+invalid JSON and download errors propagate; an explicitly stored null transcript+returns `transcript: null`. A `schemaVersion` the reader does not know throws+`UnsupportedTraceBatchInputVersionError`, distinct from invalid data. Schema+version and readiness revision are independent.++Mixed versions happen: rolling deploys, and self-hosters updating web and worker+at different times. A reader that meets an unknown `schemaVersion` must fail with+the retryable `UnsupportedTraceBatchInputVersionError`, never discard the job or+treat the object as missing. Consumers read inside retried jobs whose backoff+spans a deploy, so the retry lands on an updated reader. Deploy readers for a new+version before enabling its writer; if a writer ships first, the retries cover the+gap. Compatible optional fields may be added to V1 when absent values are safe for+old readers. A breaking change adds `versions/v2.ts`, its adapters and a read+dispatch on `schemaVersion`; existing objects are never rewritten.++Serialize the full envelope once. Skip the entire upload if `json.length` exceeds+1,000,000; do not truncate. This measures UTF-16 code units, not UTF-8 bytes, and+does not bound assembly or serialization memory. Size skips emit an info log with identifiers,+actual length and limit. StorageService owns upload retries and logs: SlowDown at+warning level, other failures including request timeouts at error level. Exhausted+failures mark the `trace-batch-store-inputs` span as failed. Neither outcome stops+Topics. The span records outcome and JSON length without transcript content;+there are no additional outcome counters.++Deploy with writes disabled. Before enabling, configure and verify an enabled+bucket lifecycle rule for the full `<prefix>trace-batch/trace/` path, matching+span-eval retention, including noncurrent versions where applicable. A rule for+`evals/` alone does not cover this path. Enable on a small worker rollout and+check storage spans, size-skip logs, S3 failures and Topics latency. Roll back by+disabling writes. Existing Topics processing continues to use in-memory inputs;+future consumers that require files must schedule only after a successful PUT.++Like temporary span-eval inputs, these objects have no ingestion deletion+references. Trace/project deletion and per-project retention do not immediately+remove them; bucket expiry is the accepted cleanup mechanism, and the deletion+paths are intentionally not extended. The lifecycle rule above remains the+precondition for enabling writes.++### Storage portability++Keep producers and consumers behind the `TraceBatchInputStorage` interface.+`createTraceBatchInputStorage()` wires the production implementation; consumers+receive the storage object so tests or another backend can supply the same contract.+`TraceBatchInputData` is the application contract; the S3 key layout, client,+serialization and physical retention belong to the storage implementation.+The logical identity `(projectId, traceId, revision)` must remain stable across+storage backends. A ClickHouse implementation can return the same transcript+and trace context without exposing its table layout to callers.++When adding file-dependent consumers, persist a backend-aware input reference+on the execution record and carry it in the queue job. For S3 this reference+must retain the exact object key. Only the storage module should interpret the+backend and locator. During a migration, keep readers for both backends until+queued references have drained or expired; changing the writer backend must+not redirect reads of existing references.++Replacing S3 also requires preserving behavior: report `stored` only after the+input is durable and available to the consumer's read path; retain the size+limit and define retry/same-revision replacement semantics explicitly. ClickHouse+needs batched or safely acknowledged async inserts rather than one synchronous+insert per trace, and its retention/deletion policy must be configured separately.+These are requirements for a future backend, not a second implementation in this+optional-capture stage.+## Per-trace transcriptsThe reader orders only by project ID and trace ID. The worker keeps@@ -300,7 +426,8 @@ one trace's observations, assembles it when the pair changes, and flushes the latrace only after a successful end of stream. A stream error discards the currentpartial trace; earlier completed traces have already emitted samples. Each traceuses the shared depth-first ordering and transcript assembler. Transcripts are-ephemeral: neither logs nor job results contain their content.+ephemeral unless optional input capture is enabled. Neither logs nor job results+contain their content.Completion means all rows returned for that pair's query window, not that no lateevents can arrive. Event versions follow the current ClickHouse merge state;diff --git a/worker/src/features/traceBatching/storeInputs.ts b/worker/src/features/traceBatching/storeInputs.tsnew file mode 100644index 0000000000..d539e8437e--- /dev/null+++ b/worker/src/features/traceBatching/storeInputs.ts@@ -0,0 +1,48 @@+import {+ instrumentAsync,+ logger,+ TRACE_BATCH_INPUT_MAX_CHARACTERS,+ traceException,+ type TraceBatchInputReference,+ type TraceBatchInputData,+ type TraceBatchInputStorage,+} from "@langfuse/shared/src/server";+import { env } from "../../env";++/** Optional capture; storage failures must not stop in-memory Topics processing. */+export async function storeInputs(+ reference: TraceBatchInputReference,+ inputs: TraceBatchInputData,+ inputStorage: TraceBatchInputStorage,+): Promise<void> {+ if (env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED !== "true") return;++ await instrumentAsync({ name: "trace-batch-store-inputs" }, async (span) => {+ span.setAttributes({+ "langfuse.project.id": reference.projectId,+ "langfuse.trace.id": reference.traceId,+ "langfuse.trace_batch.revision": reference.revision,+ });+ try {+ const result = await inputStorage.put(reference, inputs);+ span.setAttributes({+ "langfuse.trace_batch.input_storage.outcome": result.outcome,+ "langfuse.trace_batch.input_storage.json_characters": result.jsonLength,+ });+ if (result.outcome === "too_large")+ logger.info("Trace batch input storage skipped", {+ ...reference,+ reason: "input_too_large",+ jsonLength: result.jsonLength,+ limit: TRACE_BATCH_INPUT_MAX_CHARACTERS,+ });+ } catch (error) {+ // StorageService owns SDK retries and failure logs, including SlowDown warnings.+ span.setAttribute(+ "langfuse.trace_batch.input_storage.outcome",+ "upload_failed",+ );+ traceException(error, span);+ }+ });+}diff --git a/worker/src/queues/__tests__/traceBatchQueue.test.ts b/worker/src/queues/__tests__/traceBatchQueue.test.tsindex 5b3b8f41a6..d2da6a6c32 100644--- a/worker/src/queues/__tests__/traceBatchQueue.test.ts+++ b/worker/src/queues/__tests__/traceBatchQueue.test.ts@@ -23,6 +23,7 @@ import {recordDistribution,recordGauge,recordIncrement,+ type TraceBatchInputStorage,type TQueueJobTypes,} from "@langfuse/shared/src/server";import { env } from "../../env";@@ -52,6 +53,11 @@ import {traceBatchQueueProcessor,} from "../traceBatchQueue";+const inputStorage = vi.hoisted(() => ({+ put: vi.fn<TraceBatchInputStorage["put"]>(),+ get: vi.fn<TraceBatchInputStorage["get"]>(),+}));+vi.mock("@langfuse/shared/src/server", async (importOriginal) => ({...(await importOriginal<typeof import("@langfuse/shared/src/server")>()),getTraceBatchEventStream: vi.fn(),@@ -59,6 +65,7 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => ({recordDistribution: vi.fn(),recordGauge: vi.fn(),recordIncrement: vi.fn(),+ createTraceBatchInputStorage: () => inputStorage,}));vi.mock("../../features/topics/summarizeAssembledTrace", () => ({@@ -93,6 +100,8 @@ vi.mock("../../features/tokenisation/async-usage", () => ({const originalReadEnabled = env.LANGFUSE_TRACE_BATCH_READ_ENABLED;const originalTranscriptMetricsEnabled =env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_METRICS_ENABLED;+const originalTranscriptStorageEnabled =+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED;const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;const originalExperimentId = env.LANGFUSE_TRACE_BATCH_EXPERIMENT_ID;const processingSpan = trace.wrapSpanContext({@@ -115,6 +124,11 @@ afterAll(async () => {beforeEach(() => {exporter.reset();env.LANGFUSE_TRACE_BATCH_READ_ENABLED = "true";+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED = "false";+ inputStorage.put.mockResolvedValue({+ outcome: "stored",+ jsonLength: 100,+ });env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";vi.mocked(getCurrentSpan).mockReturnValue(processingSpan);vi.spyOn(processingSpan, "setAttributes");@@ -123,6 +137,8 @@ afterEach(() => {env.LANGFUSE_TRACE_BATCH_READ_ENABLED = originalReadEnabled;env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_METRICS_ENABLED =originalTranscriptMetricsEnabled;+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED =+ originalTranscriptStorageEnabled;env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;env.LANGFUSE_TRACE_BATCH_EXPERIMENT_ID = originalExperimentId;vi.restoreAllMocks();@@ -983,7 +999,198 @@ describe("trace batch queue", () => {}));});+ it.each(["disabled", "stored", "too_large", "upload_failed"] as const)(+ "preserves Topics processing when optional input storage is %s",+ async (outcome) => {+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED =+ outcome === "disabled" ? "false" : "true";+ const info = vi.spyOn(logger, "info");+ if (outcome === "upload_failed")+ inputStorage.put.mockRejectedValueOnce(+ new Error("Failed to upload file to S3"),+ );+ if (outcome === "too_large")+ inputStorage.put.mockResolvedValueOnce({+ outcome,+ jsonLength: 1_000_001,+ });+ vi.mocked(getTraceBatchEventStream).mockImplementation(+ async function* () {+ yield {+ project_id: "project",+ trace_id: "trace",+ environment: "default",+ span_id: "span",+ parent_span_id: null,+ start_time: "2026-09-11 00:00:00.000000",+ event_ts: "2026-09-11 00:00:00.000000",+ type: "GENERATION",+ name: "generation",+ input: JSON.stringify([{ role: "user", content: "private input" }]),+ output: JSON.stringify({+ role: "assistant",+ content: "private output",+ }),+ metadata: {},+ level: "DEFAULT",+ status_message: null,+ tool_definitions: {},+ tool_calls: [],+ tool_call_names: [],+ };+ },+ );+ const job = {+ data: {+ id: "storage",+ name: QueueJobs.TraceBatch,+ timestamp: new Date(),+ payload: {+ traces: [+ {+ projectId: "project",+ traceId: "trace",+ minStart: 0,+ maxStart: 1,+ revision: "queued-revision",+ },+ ],+ },+ },+ } as Job<TQueueJobTypes[QueueName.TraceBatch]>;++ await expect(+ traceBatchQueueProcessor(job, undefined),+ ).resolves.toBeDefined();+ expect(summarizeAssembledTrace).toHaveBeenCalledTimes(1);+ expect(+ vi.mocked(summarizeAssembledTrace).mock.calls[0][0].transcript?.threads,+ ).toHaveLength(1);+ expect(inputStorage.put).toHaveBeenCalledTimes(+ outcome === "disabled" ? 0 : 1,+ );+ if (outcome !== "disabled") {+ expect(inputStorage.put).toHaveBeenCalledWith(+ {+ projectId: "project",+ traceId: "trace",+ revision: "queued-revision",+ },+ {+ transcript: vi.mocked(summarizeAssembledTrace).mock.calls[0][0]+ .transcript,+ traceContext: {+ sessionId: null,+ traceTimestamp: "2026-09-11T00:00:00.000Z",+ environment: "default",+ traceName: "generation",+ },+ },+ );+ const storageSpan = exporter+ .getFinishedSpans()+ .find((span) => span.name === "trace-batch-store-inputs");+ expect(+ storageSpan?.attributes["langfuse.trace_batch.input_storage.outcome"],+ ).toBe(outcome);+ if (outcome === "upload_failed")+ expect(storageSpan?.status.code).toBe(SpanStatusCode.ERROR);+ }+ if (outcome === "too_large") {+ expect(info).toHaveBeenCalledWith("Trace batch input storage skipped", {+ projectId: "project",+ traceId: "trace",+ revision: "queued-revision",+ reason: "input_too_large",+ jsonLength: 1_000_001,+ limit: 1_000_000,+ });+ expect(JSON.stringify(info.mock.calls)).not.toContain("private input");+ expect(JSON.stringify(info.mock.calls)).not.toContain("private output");+ }+ },+ );++ it.each([false, true])(+ "runs Topics alongside capture and holds the slot until both settle (Topics rejects: %s)",+ async (summaryRejects) => {+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED = "true";+ const originalConcurrency = env.LANGFUSE_TOPICS_TRACE_CONCURRENCY;+ env.LANGFUSE_TOPICS_TRACE_CONCURRENCY = 1;+ let finishUpload!: () => void;+ inputStorage.put.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishUpload = () =>+ resolve({ outcome: "stored", jsonLength: 100 });+ }),+ );+ vi.mocked(summarizeAssembledTrace).mockImplementationOnce(async () => {+ if (summaryRejects) throw new Error("summary failed");+ return { outcome: "unchanged", rows: [] };+ });+ vi.mocked(getTraceBatchEventStream).mockImplementation(+ async function* () {+ for (const traceId of ["a", "b"])+ yield {+ project_id: "project",+ trace_id: traceId,+ environment: "default",+ span_id: "span",+ parent_span_id: null,+ start_time: "2026-09-11 00:00:00.000000",+ event_ts: "2026-09-11 00:00:00.000000",+ type: "GENERATION",+ name: "generation",+ input: JSON.stringify([{ role: "user", content: "hello" }]),+ output: JSON.stringify({ role: "assistant", content: "answer" }),+ metadata: {},+ level: "DEFAULT",+ status_message: null,+ tool_definitions: {},+ tool_calls: [],+ tool_call_names: [],+ };+ },+ );+ const job = {+ data: {+ id: "concurrent-storage",+ name: QueueJobs.TraceBatch,+ timestamp: new Date(),+ payload: {+ traces: ["a", "b"].map((traceId) => ({+ projectId: "project",+ traceId,+ minStart: 0,+ maxStart: 1,+ revision: "revision",+ })),+ },+ },+ } as Job<TQueueJobTypes[QueueName.TraceBatch]>;+ const processing = traceBatchQueueProcessor(job, undefined);+ try {+ await vi.waitFor(() =>+ expect(summarizeAssembledTrace).toHaveBeenCalledTimes(1),+ );+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(inputStorage.put).toHaveBeenCalledTimes(1);+ expect(summarizeAssembledTrace).toHaveBeenCalledTimes(1);+ finishUpload();+ await processing;+ expect(inputStorage.put).toHaveBeenCalledTimes(2);+ expect(summarizeAssembledTrace).toHaveBeenCalledTimes(2);+ } finally {+ finishUpload?.();+ await processing;+ env.LANGFUSE_TOPICS_TRACE_CONCURRENCY = originalConcurrency;+ }+ },+ );+it("summarizes only the saved rule's facets and skips traces outside its sampling", async () => {+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED = "true";vi.mocked(getTraceBatchEventStream).mockImplementation(async function* () {for (const projectId of ["picked", "sampled-out"])yield {@@ -1028,7 +1235,7 @@ describe("trace batch queue", () => {traceId: "trace",minStart: 0,maxStart: 1,- revision: "r",+ revision: `revision-${projectId}`,})),},},@@ -1044,11 +1251,19 @@ describe("trace batch queue", () => {input.facets.map(({ id }) => id),]),).toEqual([["picked", ["issues"]]]);+ expect(inputStorage.put).toHaveBeenCalledTimes(1);+ expect(inputStorage.put).toHaveBeenCalledWith(+ { projectId: "picked", traceId: "trace", revision: "revision-picked" },+ expect.objectContaining({+ transcript: expect.objectContaining({ threads: expect.any(Array) }),+ }),+ );vi.mocked(listTopicFacets).mockResolvedValue([]);vi.mocked(listTopicRules).mockResolvedValue([]);});it("passes the session of the newest event that has one, breaking timestamp ties by span ID", async () => {+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED = "true";vi.mocked(getTraceBatchEventStream).mockImplementation(async function* () {for (const [span, eventTs, sessionId] of [["a", "2026-09-11 00:00:01.000000", "session-old"],@@ -1060,13 +1275,13 @@ describe("trace batch queue", () => {project_id: "project",trace_id: "trace",session_id: sessionId,- environment: "default",+ environment: `env-${span}`,span_id: span,parent_span_id: null,- start_time: "2026-09-11 00:00:00.000000",+ start_time: `2026-09-11 00:00:0${span === "d" ? "0" : "1"}.000000`,event_ts: eventTs,type: "GENERATION",- name: "generation",+ name: `generation-${span}`,input: JSON.stringify([{ role: "user", content: span }]),output: JSON.stringify({ role: "assistant", content: "answer" }),metadata: {},@@ -1106,12 +1321,30 @@ describe("trace batch queue", () => {expect(vi.mocked(summarizeAssembledTrace).mock.calls.at(-1)?.[0],- ).toMatchObject({ traceId: "trace", sessionId: "session-tie" });+ ).toMatchObject({+ traceId: "trace",+ sessionId: "session-tie",+ traceTimestamp: "2026-09-11T00:00:00.000Z",+ environment: "env-c",+ traceName: "generation-a",+ });+ expect(inputStorage.put).toHaveBeenCalledWith(+ { projectId: "project", traceId: "trace", revision: "r" },+ expect.objectContaining({+ traceContext: {+ sessionId: "session-tie",+ traceTimestamp: "2026-09-11T00:00:00.000Z",+ environment: "env-c",+ traceName: "generation-a",+ },+ }),+ );vi.mocked(listTopicFacets).mockResolvedValue([]);vi.mocked(listTopicRules).mockResolvedValue([]);});it("skips projects without enabled Topics models and pauses a project whose connection is rejected", async () => {+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED = "true";const rows = [["off", "trace-1"],["on", "trace-1"],@@ -1180,6 +1413,12 @@ describe("trace batch queue", () => {"on",]);expect(listTopicFacets).toHaveBeenCalledExactlyOnceWith("on");+ expect(inputStorage.put.mock.calls.map(([reference]) => reference)).toEqual(+ [+ { projectId: "on", traceId: "trace-1", revision: "r" },+ { projectId: "on", traceId: "trace-2", revision: "r" },+ ],+ );expect(vi.mocked(summarizeAssembledTrace)@@ -1207,7 +1446,8 @@ describe("trace batch queue", () => {}));});- it("assembles each tenant's trace with its latest environment at the boundary and EOF", async () => {+ it("uses the latest environment to exclude internal traces from Topics and storage", async () => {+ env.LANGFUSE_TRACE_BATCH_TRANSCRIPT_STORAGE_ENABLED = "true";const userMessage = { role: "user", content: "first question" };const answer = { role: "assistant", content: "first answer" };const row = {@@ -1283,10 +1523,10 @@ describe("trace batch queue", () => {projectId: input.projectId,environment: input.environment,})),- ).toEqual([- { projectId: "a", environment: "langfuse-topics" },- { projectId: "b", environment: "production" },- ]);+ ).toEqual([{ projectId: "b", environment: "production" }]);+ expect(inputStorage.put.mock.calls.map(([reference]) => reference)).toEqual(+ [{ projectId: "b", traceId: "shared-trace", revision: "r" }],+ );const estimates = vi.mocked(tokenCountAsync).mock.calls;expect(estimates).toHaveLength(5);const serializedTranscript = JSON.stringify(estimates[0][0].text);@@ -1298,7 +1538,9 @@ describe("trace batch queue", () => {]) {expect(serializedTranscript.split(content)).toHaveLength(2);}- const spans = exporter.getFinishedSpans();+ const spans = exporter+ .getFinishedSpans()+ .filter((span) => span.name === "trace-batch-transcript");expect(spans).toHaveLength(2);for (const [index, projectId] of ["a", "b"].entries()) {const span = spans[index];diff --git a/worker/src/queues/traceBatchQueue.ts b/worker/src/queues/traceBatchQueue.tsindex 43786635aa..59313c0d32 100644--- a/worker/src/queues/traceBatchQueue.ts+++ b/worker/src/queues/traceBatchQueue.ts@@ -5,8 +5,10 @@ import { randomUUID } from "node:crypto";import { type Observation } from "@langfuse/shared";import {convertObservation,+ createTraceBatchInputStorage,getCurrentSpan,getTraceBatchEventStream,+ isInternalEvalEnvironment,logger,recordDistribution,recordGauge,@@ -15,6 +17,7 @@ import {type QueueName,type TQueueJobTypes,type Transcript,+ type TraceBatchInputReference,} from "@langfuse/shared/src/server";import {getEnabledTopicsModels,@@ -41,6 +44,9 @@ import { isRetryableClickhouseInsertError } from "../services/ClickhouseWriter";import { summarizeAssembledTrace } from "../features/topics/summarizeAssembledTrace";import { enqueueTopicsAutomation } from "../features/topics/topicsAutomation";import { recordTraceBatchTranscript } from "../features/traceBatching/traceBatchTranscript";+import { storeInputs } from "../features/traceBatching/storeInputs";++const inputStorage = createTraceBatchInputStorage();type TraceBatchObservation = Observation & {eventTimestamp: string;@@ -53,6 +59,10 @@ type TraceOutcome = (| { outcome: "failed"; reason: string }) & { rows: TopicSummary[] };+/** Identity of one trace within a batch; a batch spans projects. */+const traceKey = (projectId: string, traceId: string) =>+ JSON.stringify([projectId, traceId]);+/*** Topics settings of one batch, loaded with one query while the read starts.* A project paused mid-batch is skipped for the rest of the batch.@@ -135,6 +145,7 @@ async function summarizeTraceBatch(transcript: Transcript | null,topics: TopicsBatchProjects,jobEnqueuedAt: Date,+ revisions: ReadonlyMap<string, string>,): Promise<TraceOutcome> {const first = observations[0];const traceId = first?.traceId;@@ -148,12 +159,25 @@ async function summarizeTraceBatch(throw new Error("Trace batch observations crossed a project or trace boundary.",);+ // Match manual processing and discovery, preserving event_ts microseconds.+ const latest = newestEvent(observations)!;+ if (isInternalEvalEnvironment(latest.environment))+ return { outcome: "disabled", rows: [] };+ const revision = revisions.get(traceKey(first.projectId, traceId));+ const inputReference: TraceBatchInputReference | undefined =+ revision === undefined+ ? undefined+ : { projectId: first.projectId, traceId, revision };const traceTimestamp = new Date(Math.min(...observations.map((row) => row.startTime.getTime())),).toISOString();- // Match manual processing and discovery, preserving event_ts microseconds.- const latest = newestEvent(observations)!;const sessionId = newestSessionId(observations);+ const traceContext = {+ sessionId,+ traceTimestamp,+ environment: latest.environment,+ traceName: first.name,+ };let rows: TopicSummary[] = [];try {const project = await topics.get(first.projectId);@@ -165,18 +189,28 @@ async function summarizeTraceBatch(}))return { outcome: "disabled", rows };- const result = await summarizeAssembledTrace({- projectId: first.projectId,- traceId,- sessionId,- traceTimestamp,- jobEnqueuedAt,- environment: latest.environment,- traceName: first.name ?? "",- transcript,- models: project.models,- facets: project.facets,- });+ // Capture reports its own failures; drain both before releasing the Topics slot.+ const [summary] = await Promise.allSettled([+ summarizeAssembledTrace({+ projectId: first.projectId,+ traceId,+ ...traceContext,+ jobEnqueuedAt,+ traceName: traceContext.traceName ?? "",+ transcript,+ models: project.models,+ facets: project.facets,+ }),+ inputReference+ ? storeInputs(+ inputReference,+ { transcript, traceContext },+ inputStorage,+ )+ : Promise.resolve(),+ ]);+ if (summary.status === "rejected") throw summary.reason;+ const result = summary.value;rows = result.rows;if (result.failure === undefined) return { outcome: result.outcome, rows };throw result.failure;@@ -324,6 +358,12 @@ export const traceBatchQueueProcessor: Processor<return { discarded: "expired" };}const batch = event.payload;+ const revisions = new Map(+ batch.traces.map((trace) => [+ traceKey(trace.projectId, trace.traceId),+ trace.revision,+ ]),+ );const topicsOutcomes: TraceOutcome[] = [];let droppedRows = new Set<TopicSummary>();const topics = new TopicsBatchProjects(@@ -424,6 +464,7 @@ export const traceBatchQueueProcessor: Processor<assembled.transcript,topics,event.timestamp,+ revisions,),);});@@ -445,7 +486,7 @@ export const traceBatchQueueProcessor: Processor<let traceBytes = 0;for await (const event of getTraceBatchEventStream(batch, queryOptions)) {observationCount++;- foundTraces.add(JSON.stringify([event.project_id, event.trace_id]));+ foundTraces.add(traceKey(event.project_id, event.trace_id));foundProjects.add(event.project_id);// Logical UTF-8 payload size, excluding JSON transport and compression.const eventInputBytes = Buffer.byteLength(event.input);