Skip to content

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

fix(sessions): bound trace-card I/O in the session detail view (LFE-10958) (#15124)

Nikita Kabardin5ab8d48e75bd
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
index 7f0e4c0b05..2c30850fc0 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
@@ -5,6 +5,62 @@ import {
EventsQueryBuilder,
} from "./event-query-builder";
+describe("EventsQueryBuilder.selectIOWithSizeCap", () => {
+ const build = () =>
+ new EventsQueryBuilder({ projectId: "test-project" })
+ .selectFieldSet("base", "calculated", "metadata")
+ .selectIOWithSizeCap(300_000, 4_000)
+ .whereRaw("e.trace_id = {traceId: String}", { traceId: "trace-1" })
+ .buildWithParams();
+
+ it("returns full fields under the cap and a preview head above it", () => {
+ const { query } = build();
+
+ // lengthUTF8() is computed in the query on purpose: the materialized
+ // input_length/output_length columns cannot be assumed present on every
+ // deployment's events_full, and the full column is read here anyway.
+ expect(query).toContain(
+ "if(lengthUTF8(e.input) <= 300000, e.input, leftUTF8(e.input, 4000)) as input",
+ );
+ expect(query).toContain(
+ "if(lengthUTF8(e.output) <= 300000, e.output, leftUTF8(e.output, 4000)) as output",
+ );
+ });
+
+ it("exposes the true lengths so callers can detect previews", () => {
+ const { query } = build();
+
+ expect(query).toContain("lengthUTF8(e.input) as input_length");
+ expect(query).toContain("lengthUTF8(e.output) as output_length");
+ });
+
+ it("caps metadata values with the same policy and flags truncation", () => {
+ const { query } = build();
+
+ expect(query).toContain(
+ "arrayMap(v -> if(lengthUTF8(v) <= 300000, v, leftUTF8(v, 4000)), arrayReverse(e.metadata_values))",
+ );
+ // The flag only fires for a key's winning value (a shadowed duplicate
+ // must not raise it), and the shipped weight counts every capped value.
+ expect(query).toContain(
+ "arrayExists((v, i) -> lengthUTF8(v) > 300000 AND arrayFirstIndex(n -> n = e.metadata_names[i], e.metadata_names) = i, e.metadata_values, arrayEnumerate(e.metadata_values)) as metadata_truncated",
+ );
+ expect(query).toContain(
+ "arraySum(arrayMap(v -> if(lengthUTF8(v) <= 300000, lengthUTF8(v), 4000), e.metadata_values)) as metadata_length",
+ );
+ // The default full-value metadata expression must not also be present.
+ expect(query).not.toContain(
+ "mapFromArrays(arrayReverse(e.metadata_names), arrayReverse(e.metadata_values)) as metadata",
+ );
+ });
+
+ it("reads events_full (true lengths + full under-cap values)", () => {
+ const { query } = build();
+
+ expect(query).toContain("FROM events_full");
+ });
+});
+
describe("buildEventsFullTableSplitQuery", () => {
const buildBase = () =>
new EventsQueryBuilder({ projectId: "test-project" })
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
index 4d25fc8cc2..9d7522b3cb 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
@@ -1002,7 +1002,11 @@ abstract class BaseEventsQueryBuilder<
export class EventsQueryBuilder extends BaseEventsQueryBuilder<
typeof EVENTS_FIELDS
> {
- private ioFields: { truncated: boolean; charLimit?: number } | null = null;
+ private ioFields:
+ | { mode: "full" }
+ | { mode: "truncated"; charLimit?: number }
+ | { mode: "sizeCapped"; inlineChars: number; previewChars: number }
+ | null = null;
// Metadata expansion config: null = use truncated (default), string[] = expand specific keys, empty array = expand all
private metadataExpansionKeys: string[] | null = null;
private shouldForceFullTable = false;
@@ -1071,7 +1075,22 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
* Add IO fields with optional truncation
*/
selectIO(truncated = false, charLimit?: number): this {
- this.ioFields = { truncated, charLimit };
+ this.ioFields = truncated
+ ? { mode: "truncated", charLimit }
+ : { mode: "full" };
+ return this;
+ }
+
+ /**
+ * Add IO fields with a per-field size cap: fields whose full length is
+ * within `inlineChars` come back whole; larger fields come back as a
+ * `previewChars` head. True lengths are exposed as `input_length` /
+ * `output_length` so callers can tell a preview from full content.
+ * Metadata values are capped with the same policy. Reads events_full
+ * (true lengths + full under-cap values).
+ */
+ selectIOWithSizeCap(inlineChars: number, previewChars: number): this {
+ this.ioFields = { mode: "sizeCapped", inlineChars, previewChars };
return this;
}
@@ -1100,6 +1119,10 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
) {
fieldsToExclude.push("metadata");
}
+ // Size-capped I/O caps metadata values too (custom SELECT expression below)
+ if (this.ioFields?.mode === "sizeCapped") {
+ fieldsToExclude.push("metadata");
+ }
const fieldsToProcess = [...this.selectFields].filter(
(f) => !fieldsToExclude.includes(f),
@@ -1113,15 +1136,53 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
// Add I/O fields if configured
// Note: needsFullTable() is responsible for choosing events_core/events_full (truncated vs full I/O)
if (this.ioFields) {
- if (this.ioFields.truncated && this.ioFields.charLimit !== undefined) {
+ if (
+ this.ioFields.mode === "truncated" &&
+ this.ioFields.charLimit !== undefined
+ ) {
fieldExpressions.push(
`leftUTF8(input, ${this.ioFields.charLimit}) as input, leftUTF8(output, ${this.ioFields.charLimit}) as output`,
);
+ } else if (this.ioFields.mode === "sizeCapped") {
+ const { inlineChars, previewChars } = this.ioFields;
+ // lengthUTF8() is computed inline instead of reading the materialized
+ // input_length/output_length columns: the full value is read by this
+ // select anyway, and not every deployment's events_full is guaranteed
+ // to carry the materialized columns.
+ fieldExpressions.push(
+ `if(lengthUTF8(e.input) <= ${inlineChars}, e.input, leftUTF8(e.input, ${previewChars})) as input`,
+ `if(lengthUTF8(e.output) <= ${inlineChars}, e.output, leftUTF8(e.output, ${previewChars})) as output`,
+ `lengthUTF8(e.input) as input_length`,
+ `lengthUTF8(e.output) as output_length`,
+ );
} else {
fieldExpressions.push("input, output");
}
}
+ // Size-capped metadata: same per-value policy as I/O, plus a truncation
+ // flag and the shipped size so callers can budget and surface capping.
+ // Mirrors the arrayReverse shape of the default metadata expression.
+ if (
+ this.ioFields?.mode === "sizeCapped" &&
+ this.selectFields.has("metadata")
+ ) {
+ const { inlineChars, previewChars } = this.ioFields;
+ fieldExpressions.push(
+ `mapFromArrays(arrayReverse(e.metadata_names), arrayMap(v -> if(lengthUTF8(v) <= ${inlineChars}, v, leftUTF8(v, ${previewChars})), arrayReverse(e.metadata_values))) as metadata`,
+ // The flag checks only each key's WINNING value. A duplicate key ships
+ // both entries in the Map's JSON, and the client's JSON.parse keeps the
+ // last textual duplicate β€” with the arrayReverse above that resolves to
+ // the FIRST occurrence in the original arrays. A capped value that is
+ // shadowed by a small winner must not raise the flag (verified against
+ // ClickHouse + JSON.parse semantics).
+ `arrayExists((v, i) -> lengthUTF8(v) > ${inlineChars} AND arrayFirstIndex(n -> n = e.metadata_names[i], e.metadata_names) = i, e.metadata_values, arrayEnumerate(e.metadata_values)) as metadata_truncated`,
+ // Shipped metadata weight: every (capped) value counts, duplicates
+ // included, because duplicates are physically in the response.
+ `arraySum(arrayMap(v -> if(lengthUTF8(v) <= ${inlineChars}, lengthUTF8(v), ${previewChars}), e.metadata_values)) as metadata_length`,
+ );
+ }
+
// Add metadata field with expansion if configured
// Note: needsFullTable() is responsible for choosing events_core/events_full
// Metadata expansion is handled by querying events_full directly for full values.
@@ -1158,8 +1219,10 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
* - events_full: full I/O and metadata (when full data is needed)
*/
private needsFullTable(): boolean {
- // Need full I/O? (truncated = false means we need full data)
- const needsFullIO = this.ioFields !== null && !this.ioFields.truncated;
+ // Need full I/O? (anything but the truncated mode needs full data;
+ // sizeCapped needs true lengths + full under-cap values)
+ const needsFullIO =
+ this.ioFields !== null && this.ioFields.mode !== "truncated";
// Need full metadata? (any expansion requested β€” specific keys or all)
const needsFullMetadata =
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index f74201cdc9..51d66df8ac 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -1,6 +1,7 @@
export {
type FullObservations,
type FullObservationsWithScores,
+ type FullEventsObservation,
type FullEventsObservations,
type ObservationPriceFields,
} from "./createGenerationsQuery";
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index b88be20df9..43cc2721a3 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -33,6 +33,7 @@ import {
DateTimeFilter,
type Filter,
FilterList,
+ type FullEventsObservation,
FullEventsObservations,
buildEventsObservationRowSelection,
extractTimeFilter,
@@ -169,11 +170,43 @@ type ObservationsTableQueryResultWitouhtTraceFields = Omit<
"trace_tags" | "trace_name" | "trace_user_id"
>;
+/**
+ * Extra row fields present when the query ran with an `ioSizeCap`
+ * (EventsQueryBuilder.selectIOWithSizeCap). ClickHouse returns UInt64 as
+ * string and the exists-flag as 0/1.
+ */
+type IOSizeCapRowFields = {
+ input_length: string;
+ output_length: string;
+ metadata_truncated: 0 | 1;
+ metadata_length: string;
+};
+
+/**
+ * Caller-facing truncation summary attached to observations fetched with an
+ * `ioSizeCap`: true field lengths (UTF-8 code points) plus flags telling a
+ * preview head apart from full content.
+ */
+export type ObservationIOSizeFields = {
+ inputLength: number;
+ outputLength: number;
+ inputTruncated: boolean;
+ outputTruncated: boolean;
+ metadataTruncated: boolean;
+ /** Shipped (capped) metadata weight in chars β€” for response budgeting. */
+ metadataLength: number;
+};
+
/**
* Internal helper: enrich observations with model pricing data
* Uses events-specific converter to include userId and sessionId
* Supports both V1 (complete observations) and V2 (partial observations with field groups)
*
+ * CONTRACT: a 1:1 order-preserving map over observationRecords β€” never
+ * filter, deduplicate, or reorder here. The ioSizeCap path in
+ * getObservationsWithModelDataFromEventsTable zips row-extra columns back on
+ * by index and asserts the row count.
+ *
* @param observationRecords - Raw observation records from ClickHouse
* @param projectId - Project ID for model lookup
* @param parseIoAsJson - Whether to parse input/output as JSON
@@ -278,6 +311,12 @@ async function enrichObservationsWithModelData(
});
}
+/**
+ * CONTRACT: a 1:1 order-preserving map β€” never filter, deduplicate, or
+ * reorder here. The ioSizeCap path in
+ * getObservationsWithModelDataFromEventsTable zips row-extra columns back on
+ * by index and asserts the row count.
+ */
async function enrichObservationsWithTraceFields(
observationRecords: Array<EventsObservation & ObservationPriceFields>,
): Promise<FullEventsObservations> {
@@ -465,16 +504,23 @@ export const getObservationsCountsFromEventsTable = async (
};
};
-export const getObservationsWithModelDataFromEventsTable = async (
+export async function getObservationsWithModelDataFromEventsTable(
+ opts: ObservationTableQuery & {
+ ioSizeCap: NonNullable<ObservationTableQuery["ioSizeCap"]>;
+ },
+): Promise<Array<FullEventsObservation & ObservationIOSizeFields>>;
+export async function getObservationsWithModelDataFromEventsTable(
opts: ObservationTableQuery,
-): Promise<FullEventsObservations> => {
- const observationRecords =
- await getObservationsFromEventsTableInternal<ObservationsTableQueryResultWitouhtTraceFields>(
- {
- ...opts,
- select: "rows",
- },
- );
+): Promise<FullEventsObservations>;
+export async function getObservationsWithModelDataFromEventsTable(
+ opts: ObservationTableQuery,
+): Promise<FullEventsObservations> {
+ const observationRecords = await getObservationsFromEventsTableInternal<
+ ObservationsTableQueryResultWitouhtTraceFields & Partial<IOSizeCapRowFields>
+ >({
+ ...opts,
+ select: "rows",
+ });
const withModelData: Array<EventsObservation & ObservationPriceFields> =
await enrichObservationsWithModelData(
@@ -484,8 +530,36 @@ export const getObservationsWithModelDataFromEventsTable = async (
null, // V1 path: always enrich all fields
);
- return enrichObservationsWithTraceFields(withModelData);
-};
+ const enriched = await enrichObservationsWithTraceFields(withModelData);
+
+ if (!opts.ioSizeCap) return enriched;
+
+ // Zip the size fields back on BY ROW ORDER: both enrichers above are 1:1
+ // order-preserving maps over the records (a documented contract on each).
+ // Never zip by id β€” un-merged ReplacingMergeTree versions of one span
+ // return multiple rows sharing an id, and an id-keyed lookup would attach
+ // one version's lengths to another version's payload.
+ if (enriched.length !== observationRecords.length) {
+ throw new Error(
+ "getObservationsWithModelDataFromEventsTable: enrichment changed the row count; the ioSizeCap zip requires 1:1 order-preserving enrichers",
+ );
+ }
+ const { inlineChars } = opts.ioSizeCap;
+ return enriched.map((observation, index) => {
+ const record = observationRecords[index];
+ const inputLength = Number(record.input_length ?? 0);
+ const outputLength = Number(record.output_length ?? 0);
+ return {
+ ...observation,
+ inputLength,
+ outputLength,
+ inputTruncated: inputLength > inlineChars,
+ outputTruncated: outputLength > inlineChars,
+ metadataTruncated: Boolean(Number(record.metadata_truncated ?? 0)),
+ metadataLength: Number(record.metadata_length ?? 0),
+ };
+ });
+}
export const getTraceDeleteCursorPageFromEvents = async (props: {
projectId: string;
@@ -605,12 +679,21 @@ async function getObservationsFromEventsTableInternal<T>(
"calculated",
);
if (selectIOAndMetadata) {
- queryBuilder
- .selectIO(
- renderingProps.truncated,
- env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT,
- )
- .selectFieldSet("metadata");
+ if (opts.ioSizeCap) {
+ queryBuilder
+ .selectIOWithSizeCap(
+ opts.ioSizeCap.inlineChars,
+ opts.ioSizeCap.previewChars,
+ )
+ .selectFieldSet("metadata");
+ } else {
+ queryBuilder
+ .selectIO(
+ renderingProps.truncated,
+ env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT,
+ )
+ .selectFieldSet("metadata");
+ }
}
}
@@ -667,8 +750,23 @@ async function getObservationsFromEventsTableInternal<T>(
.when(isTraceDeleteCursorSelect, (b) =>
applyOrderByForObservationsQuery(b).limitBy("e.trace_id", "e.project_id"),
)
- .when(!isTraceDeleteCursorSelect && orderByEntries.length > 0, (b) =>
- b.orderByColumns(orderByEntries),
+ .when(
+ !isTraceDeleteCursorSelect &&
+ (orderByEntries.length > 0 || Boolean(opts.dedupeBySpanId)),
+ (b) =>
+ b.orderByColumns(
+ opts.dedupeBySpanId
+ ? // event_ts DESC within the caller's order so LIMIT 1 BY keeps
+ // the newest version of each span.
+ [
+ ...orderByEntries,
+ { column: "e.event_ts", direction: "DESC" as const },
+ ]
+ : orderByEntries,
+ ),
+ )
+ .when(!isTraceDeleteCursorSelect && Boolean(opts.dedupeBySpanId), (b) =>
+ b.limitBy("e.span_id", "e.project_id"),
)
.limit(limit, isTraceDeleteCursorSelect ? undefined : offset);
@@ -2370,6 +2468,82 @@ export const getObservationsBatchIOFromEventsTable = async <
})) as Array<EventBatchIOResult<TIncludeExperiment, TIncludeToolCalls>>;
};
+/**
+ * Full raw I/O + metadata for ONE observation, scoped to a session (the
+ * session-detail download fallback for payloads too large to render inline,
+ * LFE-10958). Callers are session-authorized (public sessions included), so
+ * the session_id predicate is part of the authorization: the query itself
+ * guarantees the observation belongs to that session β€” never widen it.
+ */
+export const getObservationFullIOForSessionFromEventsTable = async (opts: {
+ projectId: string;
+ sessionId: string;
+ traceId: string;
+ observationId: string;
+ /** The observation's startTime; bounds the read for primary-key pruning. */
+ startTime: Date;
+}): Promise<{
+ id: string;
+ input: string | null;
+ output: string | null;
+ metadata: MetadataDomain;
+} | null> => {
+ // Β±1s around start_time prunes on the primary key
+ // (project_id, toStartOfMinute(start_time), xxHash32(trace_id)).
+ const minTimestamp = new Date(opts.startTime.getTime() - 1000);
+ const maxTimestamp = new Date(opts.startTime.getTime() + 1000);
+
+ const query = `
+ SELECT
+ e.span_id as id,
+ e.input as input,
+ e.output as output,
+ mapFromArrays(arrayReverse(e.metadata_names), arrayReverse(e.metadata_values)) as metadata
+ FROM events_full e
+ WHERE e.project_id = {projectId: String}
+ AND e.session_id = {sessionId: String}
+ AND xxHash32(e.trace_id) = xxHash32({traceId: 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)}
+ ORDER BY e.event_ts DESC
+ LIMIT 1
+ `;
+
+ const rows = await queryClickhouse<{
+ id: string;
+ input: string | null;
+ output: string | null;
+ metadata: Record<string, string>;
+ }>({
+ query,
+ params: {
+ projectId: opts.projectId,
+ sessionId: opts.sessionId,
+ traceId: opts.traceId,
+ observationId: opts.observationId,
+ minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
+ maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ },
+ tags: { projectId: opts.projectId },
+ preferredClickhouseService: "EventsReadOnly",
+ });
+
+ const row = rows[0];
+ if (!row) return null;
+
+ return {
+ id: row.id,
+ input: applyBatchIOStringRendering(row.input),
+ output: applyBatchIOStringRendering(row.output),
+ metadata:
+ row.metadata !== undefined
+ ? parseMetadataCHRecordToDomain(row.metadata)
+ : {},
+ };
+};
+
/**
* Discouraged: Avoid using this function for new code.
*
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 98a62c5dd9..7bc37ad8a3 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -526,6 +526,20 @@ export type ObservationTableQuery = {
offset?: number;
selectIOAndMetadata?: boolean;
renderingProps?: RenderingProps;
+ /**
+ * Per-field I/O size cap (events table only): fields whose full length is
+ * within `inlineChars` come back whole, larger fields come back as a
+ * `previewChars` head plus true lengths and truncation flags. Takes
+ * precedence over `renderingProps.truncated` for the I/O select.
+ */
+ ioSizeCap?: { inlineChars: number; previewChars: number };
+ /**
+ * Events table only: collapse un-merged ReplacingMergeTree row versions to
+ * one row per span (`ORDER BY ..., event_ts DESC` + `LIMIT 1 BY span_id`),
+ * so row counts equal distinct observations and the newest version wins.
+ * Required by callers whose limits/paging count observations.
+ */
+ dedupeBySpanId?: boolean;
clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;
};
diff --git a/web/src/__tests__/server/sessions-observations-io-cap.servertest.ts b/web/src/__tests__/server/sessions-observations-io-cap.servertest.ts
new file mode 100644
index 0000000000..626a0d9cca
--- /dev/null
+++ b/web/src/__tests__/server/sessions-observations-io-cap.servertest.ts
@@ -0,0 +1,440 @@
+/**
+ * Bounded I/O contract of the session-detail card queries (LFE-10958).
+ *
+ * Session cards are previews: `sessions.observationsForTraceFromEvents` must
+ * never return unbounded payloads. Fields within the inline limit come back
+ * whole (cards render exactly as before); larger fields come back as a
+ * preview head plus their true length and a truncated flag, with the trace
+ * peek / `sessions.observationFullIOFromEvents` as the full-reading surfaces.
+ */
+import type { Session } from "next-auth";
+import { prisma } from "@langfuse/shared/src/db";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { createEvent, createEventsCh } from "@langfuse/shared/src/server";
+import waitForExpect from "wait-for-expect";
+import { randomUUID } from "crypto";
+
+// The events_full table is created only by the ClickHouse dev-tables setup,
+// which runs in the default deploy-mode where .env.dev.example enables the v4
+// preview opt-in. The -azure and -redis-cluster CI runs skip that setup, so
+// the events table is absent there. Mirrors sessions-trpc-events-only gating.
+const eventsTableAvailable =
+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";
+const maybe = eventsTableAvailable ? describe : describe.skip;
+
+// At least one always-running test so the file does not hang on the redis
+// connections opened by the tRPC caller imports when the suite is skipped.
+describe("sessions observations io cap liveness", () => {
+ it("should not hang redis when the events table is unavailable", () => {});
+});
+
+// Keep in sync with the constants in web/src/server/api/routers/sessions.ts.
+const INLINE_LIMIT = 300_000;
+const PREVIEW_LIMIT = 4_000;
+const PER_TRACE_LIMIT = 50;
+
+maybe("sessions observations bounded I/O (events)", () => {
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: "user-1",
+ canCreateOrganizations: true,
+ name: "Demo User",
+ organizations: [
+ {
+ id: "seed-org-id",
+ name: "Test Organization",
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ aiFeaturesEnabled: false,
+ aiTelemetryEnabled: true,
+ projects: [
+ {
+ id: projectId,
+ role: "ADMIN",
+ retentionDays: 30,
+ deletedAt: null,
+ name: "Test Project",
+ hasTraces: false,
+ metadata: {},
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ searchBar: false,
+ v4BetaToggleVisible: false,
+ observationEvals: false,
+ experimentsV4Enabled: false,
+ },
+ admin: true,
+ },
+ environment: {} as any,
+ };
+
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+ const caller = appRouter.createCaller({ ...ctx, prisma });
+
+ const seedObservations = async (
+ events: Array<{
+ input?: string;
+ output?: string;
+ metadataValues?: string[];
+ metadataNames?: string[];
+ }>,
+ ) => {
+ const sessionId = randomUUID();
+ const traceId = randomUUID();
+ const baseTime = Date.now();
+
+ await createEventsCh(
+ events.map((event, index) =>
+ createEvent({
+ span_id: `${traceId}-o${index}`,
+ id: `${traceId}-o${index}`,
+ trace_id: traceId,
+ project_id: projectId,
+ parent_span_id: index === 0 ? "" : `${traceId}-o0`,
+ type: "GENERATION",
+ session_id: sessionId,
+ user_id: "user-a",
+ start_time: (baseTime + index * 100) * 1000,
+ input: event.input ?? "small input",
+ output: event.output ?? "small output",
+ ...(event.metadataValues
+ ? {
+ metadata_names:
+ event.metadataNames ??
+ event.metadataValues.map((_, i) => `key-${i}`),
+ metadata_values: event.metadataValues,
+ }
+ : {}),
+ }),
+ ),
+ );
+
+ await waitForExpect(async () => {
+ const result = await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+ expect(result.observations.length).toBeGreaterThanOrEqual(
+ Math.min(events.length, PER_TRACE_LIMIT),
+ );
+ });
+
+ return { sessionId, traceId, baseTime };
+ };
+
+ it("returns under-cap fields whole and over-cap fields as preview heads with true lengths", async () => {
+ const bigInput = "a".repeat(INLINE_LIMIT + 100);
+ const { sessionId, traceId } = await seedObservations([
+ { input: "hello", output: "world" },
+ { input: bigInput, output: "small" },
+ ]);
+
+ const { observations, hasMoreObservations } =
+ await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ expect(hasMoreObservations).toBe(false);
+
+ const small = observations.find((o) => o.id === `${traceId}-o0`);
+ expect(small?.input).toBe("hello");
+ expect(small?.inputTruncated).toBe(false);
+ expect(small?.inputLength).toBe(5);
+ expect(small?.outputTruncated).toBe(false);
+
+ const large = observations.find((o) => o.id === `${traceId}-o1`);
+ expect(large?.inputTruncated).toBe(true);
+ expect(large?.inputLength).toBe(INLINE_LIMIT + 100);
+ expect(typeof large?.input).toBe("string");
+ expect((large?.input as string).length).toBe(PREVIEW_LIMIT);
+ expect(large?.outputTruncated).toBe(false);
+ expect(large?.output).toBe("small");
+ });
+
+ it("caps metadata values and flags metadataTruncated", async () => {
+ const bigValue = "m".repeat(INLINE_LIMIT + 50);
+ const { sessionId, traceId } = await seedObservations([
+ { metadataValues: [bigValue, "tiny"], metadataNames: ["big", "small"] },
+ ]);
+
+ const { observations } =
+ await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ const observation = observations[0];
+ expect(observation.metadataTruncated).toBe(true);
+ const metadata = observation.metadata as Record<string, unknown>;
+ expect(String(metadata.big).length).toBe(PREVIEW_LIMIT);
+ expect(metadata.small).toBe("tiny");
+ });
+
+ it("caps observations per card and reports more exist", async () => {
+ const { sessionId, traceId } = await seedObservations(
+ Array.from({ length: PER_TRACE_LIMIT + 2 }, () => ({})),
+ );
+
+ const { observations, hasMoreObservations } =
+ await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ expect(observations.length).toBe(PER_TRACE_LIMIT);
+ expect(hasMoreObservations).toBe(true);
+ });
+
+ it("trims to preview heads once the cumulative I/O budget is exhausted (valid-JSON payloads)", async () => {
+ // 8 x ~290K VALID-JSON inputs: each under the inline cap, cumulatively
+ // over the 2M budget from the 8th observation on (budget checked before
+ // adding). Valid JSON is the realistic LLM shape and guards the budget
+ // against ever depending on the value's parse state.
+ const nearCap = JSON.stringify({
+ messages: [{ role: "user", content: "b".repeat(289_000) }],
+ });
+ const { sessionId, traceId } = await seedObservations(
+ Array.from({ length: 8 }, () => ({ input: nearCap, output: "ok" })),
+ );
+
+ const { observations } =
+ await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ const first = observations[0];
+ expect(first.inputTruncated).toBe(false);
+ // I/O on this path is returned as the raw string; the client parses.
+ expect(typeof first.input).toBe("string");
+ expect((first.input as string).length).toBe(nearCap.length);
+
+ const last = observations[observations.length - 1];
+ expect(last.inputTruncated).toBe(true);
+ expect((last.input as string).length).toBe(PREVIEW_LIMIT);
+ // The true length survives the trim so the UI can show the real size.
+ expect(last.inputLength).toBe(nearCap.length);
+ });
+
+ it("does not let the synthetic trace row consume a card slot or trip hasMore", async () => {
+ // 50 real observations + the synthetic trace-level row (id `t-<traceId>`,
+ // the shape handleEventPropagationJob writes): all 50 real observations
+ // must come back alongside the synthetic row, and hasMoreObservations
+ // must stay false β€” the synthetic row is trace metadata, not observation
+ // number 51.
+ const { sessionId, traceId, baseTime } = await seedObservations(
+ Array.from({ length: PER_TRACE_LIMIT }, () => ({})),
+ );
+ await createEventsCh([
+ createEvent({
+ span_id: `t-${traceId}`,
+ id: `t-${traceId}`,
+ trace_id: traceId,
+ project_id: projectId,
+ parent_span_id: "",
+ type: "SPAN",
+ session_id: sessionId,
+ user_id: "user-a",
+ start_time: (baseTime - 50) * 1000,
+ input: "trace level input",
+ output: "trace level output",
+ }),
+ ]);
+
+ await waitForExpect(async () => {
+ const result = await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+ expect(result.observations.length).toBe(PER_TRACE_LIMIT + 1);
+ });
+
+ const { observations, hasMoreObservations } =
+ await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ expect(observations.some((o) => o.id === `t-${traceId}`)).toBe(true);
+ expect(observations.filter((o) => o.id !== `t-${traceId}`).length).toBe(
+ PER_TRACE_LIMIT,
+ );
+ expect(hasMoreObservations).toBe(false);
+ });
+
+ it("collapses un-merged span versions to one observation (newest wins)", async () => {
+ const sessionId = randomUUID();
+ const traceId = randomUUID();
+ const spanId = `${traceId}-o0`;
+ const baseTime = Date.now();
+
+ // Create + update pair for ONE span: two ReplacingMergeTree row versions
+ // sharing span_id, distinguished by event_ts. Until the background merge
+ // runs, both rows are physically present β€” the card's row counting must
+ // see one observation, with the newest version's payload.
+ const shared = {
+ span_id: spanId,
+ id: spanId,
+ trace_id: traceId,
+ project_id: projectId,
+ parent_span_id: "",
+ type: "GENERATION",
+ session_id: sessionId,
+ user_id: "user-a",
+ start_time: baseTime * 1000,
+ } as const;
+ await createEventsCh([
+ createEvent({
+ ...shared,
+ input: "prompt",
+ output: "",
+ event_ts: baseTime * 1000,
+ }),
+ createEvent({
+ ...shared,
+ input: "prompt",
+ output: "completed answer",
+ event_ts: (baseTime + 5000) * 1000,
+ }),
+ ]);
+
+ await waitForExpect(async () => {
+ const result = await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+ expect(result.observations.length).toBeGreaterThanOrEqual(1);
+ });
+
+ const { observations, hasMoreObservations } =
+ await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ expect(observations.length).toBe(1);
+ expect(hasMoreObservations).toBe(false);
+ expect(observations[0].output).toBe("completed answer");
+ });
+
+ it("does not flag metadata truncation when a capped value is shadowed by a small winner", async () => {
+ // Duplicate metadata key where the client-visible winner (first original
+ // occurrence) is small and an oversized duplicate is shadowed: the flag
+ // must stay false β€” the reader can see everything the card shows.
+ const bigValue = "m".repeat(INLINE_LIMIT + 50);
+ const { sessionId, traceId } = await seedObservations([
+ {
+ metadataNames: ["k", "k"],
+ metadataValues: ["small-winner", bigValue],
+ },
+ ]);
+
+ const { observations } =
+ await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ const observation = observations[0];
+ expect((observation.metadata as Record<string, unknown>).k).toBe(
+ "small-winner",
+ );
+ expect(observation.metadataTruncated).toBe(false);
+ });
+
+ it("counts metadata toward the cumulative budget and drops it past the ceiling", async () => {
+ // Tiny I/O but ~290K of metadata per observation: 8 observations exceed
+ // the 2M budget on metadata weight alone; past the ceiling metadata is
+ // dropped and flagged instead of shipped.
+ const bigMeta = "m".repeat(290_000);
+ const { sessionId, traceId } = await seedObservations(
+ Array.from({ length: 8 }, () => ({
+ input: "in",
+ output: "out",
+ metadataNames: ["payload"],
+ metadataValues: [bigMeta],
+ })),
+ );
+
+ const { observations } =
+ await caller.sessions.observationsForTraceFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ filter: [],
+ });
+
+ const first = observations[0];
+ expect(first.metadataTruncated).toBe(false);
+ expect(
+ String((first.metadata as Record<string, unknown>).payload).length,
+ ).toBe(290_000);
+
+ const last = observations[observations.length - 1];
+ expect(last.metadataTruncated).toBe(true);
+ expect(last.metadata).toEqual({});
+ });
+
+ it("serves full I/O for one observation via observationFullIOFromEvents, scoped to the session", async () => {
+ const bigInput = "c".repeat(INLINE_LIMIT + 100);
+ const { sessionId, traceId, baseTime } = await seedObservations([
+ { input: bigInput, output: "full output" },
+ ]);
+
+ const full = await caller.sessions.observationFullIOFromEvents({
+ projectId,
+ sessionId,
+ traceId,
+ observationId: `${traceId}-o0`,
+ startTime: new Date(baseTime),
+ });
+
+ expect(full.input).toBe(bigInput);
+ expect(full.output).toBe("full output");
+
+ // A different session must not grant access to the same observation:
+ // the sessionId predicate is part of the authorization.
+ await expect(
+ caller.sessions.observationFullIOFromEvents({
+ projectId,
+ sessionId: randomUUID(),
+ traceId,
+ observationId: `${traceId}-o0`,
+ startTime: new Date(baseTime),
+ }),
+ ).rejects.toThrow("Observation not found in session");
+ });
+});
diff --git a/web/src/components/session/SessionObservationIO.clienttest.tsx b/web/src/components/session/SessionObservationIO.clienttest.tsx
new file mode 100644
index 0000000000..243ef78595
--- /dev/null
+++ b/web/src/components/session/SessionObservationIO.clienttest.tsx
@@ -0,0 +1,176 @@
+/**
+ * Session cards must stay bounded (LFE-10958): observations whose I/O fits
+ * the server's inline limit render through IOPreview exactly as before, while
+ * server-truncated observations render a bounded preview with escape hatches
+ * (trace view, raw download) instead of the full payload.
+ */
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+const fullIOQuery = vi.fn();
+const downloadJsonFile = vi.fn();
+const capture = vi.fn();
+
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ useUtils: () => ({
+ client: {
+ sessions: {
+ observationFullIOFromEvents: { query: fullIOQuery },
+ },
+ },
+ }),
+ },
+}));
+
+vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
+ usePostHogClientCapture: () => capture,
+}));
+
+vi.mock("@/src/components/trace/components/IOPreview/IOPreview", () => ({
+ IOPreview: () => <div data-testid="io-preview" />,
+}));
+
+vi.mock("@/src/components/session/actions/downloadSessionAsJson", () => ({
+ downloadJsonFile: (args: unknown) => downloadJsonFile(args),
+}));
+
+import {
+ SessionObservationIO,
+ type SessionTraceObservation,
+} from "./SessionObservationIO";
+
+const baseObservation = {
+ id: "obs-1",
+ name: "gpt-4o-completion",
+ startTime: new Date("2026-07-15T10:00:00Z"),
+ input: '{"messages":[{"role":"user","content":"hi"}]}',
+ output: "hello",
+ metadata: {},
+ inputLength: 45,
+ outputLength: 5,
+ inputTruncated: false,
+ outputTruncated: false,
+ metadataTruncated: false,
+} as unknown as SessionTraceObservation;
+
+const renderComponent = (
+ observation: SessionTraceObservation,
+ onOpenInTraceView = vi.fn(),
+) => {
+ render(
+ <SessionObservationIO
+ observation={observation}
+ projectId="p1"
+ sessionId="s1"
+ traceId="t1"
+ showCorrections={false}
+ onOpenInTraceView={onOpenInTraceView}
+ />,
+ );
+ return { onOpenInTraceView };
+};
+
+describe("SessionObservationIO", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("renders untruncated observations through IOPreview, unchanged", () => {
+ renderComponent(baseObservation);
+
+ expect(screen.getByTestId("io-preview")).toBeInTheDocument();
+ expect(screen.queryByText(/too large/i)).not.toBeInTheDocument();
+ });
+
+ it("renders a bounded preview instead of IOPreview when the server truncated I/O", () => {
+ renderComponent({
+ ...baseObservation,
+ input: "x".repeat(4000),
+ inputLength: 2_500_000,
+ inputTruncated: true,
+ } as SessionTraceObservation);
+
+ expect(screen.queryByTestId("io-preview")).not.toBeInTheDocument();
+ expect(
+ screen.getByText(/too large to display in the session view/i),
+ ).toBeInTheDocument();
+ // True size is surfaced so users know what they are dealing with.
+ expect(screen.getByText(/2\.5M characters/i)).toBeInTheDocument();
+ });
+
+ it("opens the trace view at the observation", () => {
+ const { onOpenInTraceView } = renderComponent({
+ ...baseObservation,
+ inputTruncated: true,
+ } as SessionTraceObservation);
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /open in trace view/i }),
+ );
+
+ expect(onOpenInTraceView).toHaveBeenCalledWith("obs-1");
+ expect(capture).toHaveBeenCalledWith(
+ "session_detail:truncated_observation_open_trace_click",
+ );
+ });
+
+ it("downloads the full raw I/O without rendering it", async () => {
+ fullIOQuery.mockResolvedValue({
+ id: "obs-1",
+ input: "full-input",
+ output: "full-output",
+ metadata: {},
+ });
+ renderComponent({
+ ...baseObservation,
+ outputTruncated: true,
+ } as SessionTraceObservation);
+
+ fireEvent.click(screen.getByRole("button", { name: /download i\/o/i }));
+
+ await waitFor(() => expect(downloadJsonFile).toHaveBeenCalledTimes(1));
+ expect(fullIOQuery).toHaveBeenCalledWith({
+ projectId: "p1",
+ sessionId: "s1",
+ traceId: "t1",
+ observationId: "obs-1",
+ startTime: baseObservation.startTime,
+ });
+ expect(downloadJsonFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fileName: "observation-obs-1.json",
+ data: expect.objectContaining({ input: "full-input" }),
+ }),
+ );
+ });
+
+ it("keeps metadata visible alongside truncated I/O", () => {
+ renderComponent({
+ ...baseObservation,
+ inputTruncated: true,
+ metadata: { key: "value" },
+ metadataLength: 15,
+ metadataTruncated: false,
+ } as SessionTraceObservation);
+
+ expect(screen.getByText("Metadata")).toBeInTheDocument();
+ expect(screen.getByText(/"key":"value"/)).toBeInTheDocument();
+ });
+
+ it("keeps IOPreview but points to the trace view when only metadata was truncated", () => {
+ const { onOpenInTraceView } = renderComponent({
+ ...baseObservation,
+ metadataTruncated: true,
+ } as SessionTraceObservation);
+
+ expect(screen.getByTestId("io-preview")).toBeInTheDocument();
+ expect(
+ screen.getByText(/metadata values are too large/i),
+ ).toBeInTheDocument();
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /open in trace view/i }),
+ );
+ expect(onOpenInTraceView).toHaveBeenCalledWith("obs-1");
+ });
+});
diff --git a/web/src/components/session/SessionObservationIO.tsx b/web/src/components/session/SessionObservationIO.tsx
new file mode 100644
index 0000000000..d771e3931d
--- /dev/null
+++ b/web/src/components/session/SessionObservationIO.tsx
@@ -0,0 +1,218 @@
+import React from "react";
+import { Download, ExternalLinkIcon, Loader2 } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import { IOPreview } from "@/src/components/trace/components/IOPreview/IOPreview";
+import { api, type RouterOutputs } from "@/src/utils/api";
+import { downloadJsonFile } from "@/src/components/session/actions/downloadSessionAsJson";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { compactNumberFormatter } from "@/src/utils/numbers";
+
+export type SessionTraceObservation =
+ RouterOutputs["sessions"]["observationsForTraceFromEvents"]["observations"][number];
+
+/** Display cap of a preview section β€” matches the server's preview head. */
+const PREVIEW_DISPLAY_CHARS = 4_000;
+
+/**
+ * One field of an over-limit observation: a bounded, non-interactive preview
+ * head. Never grows with payload size β€” the display is capped even when the
+ * shipped value is larger (an under-cap sibling field, or capped metadata);
+ * the trace view and the download are the full-reading surfaces (LFE-10958).
+ */
+const TruncatedIOSection = ({
+ label,
+ value,
+ fullLength,
+ truncated,
+}: {
+ label: string;
+ value: unknown;
+ fullLength: number;
+ truncated: boolean;
+}) => {
+ if (value === null || value === undefined || value === "") return null;
+ const text = typeof value === "string" ? value : JSON.stringify(value);
+ const shown =
+ text.length > PREVIEW_DISPLAY_CHARS
+ ? text.slice(0, PREVIEW_DISPLAY_CHARS)
+ : text;
+
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">
+ <span className="font-medium">{label}</span>
+ {(truncated || shown.length < text.length) && (
+ <span>
+ {compactNumberFormatter(Math.max(fullLength, text.length), 1)}{" "}
+ characters β€” showing the first{" "}
+ {compactNumberFormatter(shown.length, 1)}
+ </span>
+ )}
+ </div>
+ <pre className="bg-muted/50 max-h-40 overflow-hidden rounded-md border p-2 font-mono text-xs break-all whitespace-pre-wrap">
+ {shown}
+ </pre>
+ </div>
+ );
+};
+
+/**
+ * Renders one observation's I/O inside a session-detail trace card.
+ *
+ * Observations whose I/O fits the server's inline limit render exactly as
+ * before (IOPreview, pretty chat view included). Observations the server
+ * truncated render as a bounded preview with the true size and two escape
+ * hatches: the trace view (full machinery: worker parse, virtualized JSON
+ * viewer) and a download that saves the raw payload without rendering it.
+ */
+export const SessionObservationIO = ({
+ observation,
+ projectId,
+ sessionId,
+ traceId,
+ environment,
+ showCorrections,
+ onOpenInTraceView,
+}: {
+ observation: SessionTraceObservation;
+ projectId: string;
+ sessionId: string;
+ traceId: string;
+ environment?: string;
+ showCorrections: boolean;
+ onOpenInTraceView: (observationId: string) => void;
+}) => {
+ const capture = usePostHogClientCapture();
+ const utils = api.useUtils();
+ const [isDownloading, setIsDownloading] = React.useState(false);
+
+ const isIOTruncated = Boolean(
+ observation.inputTruncated || observation.outputTruncated,
+ );
+
+ const onDownload = async () => {
+ capture("session_detail:truncated_observation_download_click");
+ setIsDownloading(true);
+ try {
+ // Plain client call (no React Query cache): the full payload is saved
+ // to a file and must not be retained in memory afterwards.
+ const full =
+ await utils.client.sessions.observationFullIOFromEvents.query({
+ projectId,
+ sessionId,
+ traceId,
+ observationId: observation.id,
+ startTime: observation.startTime,
+ });
+ // I/O stays embedded as raw strings: parsing multi-megabyte JSON just
+ // to pretty-print it risks the same freeze this card exists to avoid.
+ downloadJsonFile({
+ data: {
+ observationId: observation.id,
+ traceId,
+ input: full.input,
+ output: full.output,
+ metadata: full.metadata,
+ },
+ fileName: `observation-${observation.id}.json`,
+ });
+ } catch {
+ showErrorToast(
+ "Download failed",
+ "Could not fetch the observation's full I/O. Please try again.",
+ );
+ } finally {
+ setIsDownloading(false);
+ }
+ };
+
+ const openInTraceView = () => {
+ capture("session_detail:truncated_observation_open_trace_click");
+ onOpenInTraceView(observation.id);
+ };
+
+ if (!isIOTruncated) {
+ return (
+ <>
+ <IOPreview
+ input={observation.input ?? undefined}
+ output={observation.output ?? undefined}
+ metadata={observation.metadata ?? undefined}
+ observationName={observation.name ?? undefined}
+ hideIfNull
+ projectId={projectId}
+ traceId={traceId}
+ observationId={observation.id}
+ environment={environment}
+ showCorrections={showCorrections}
+ />
+ {observation.metadataTruncated && (
+ <p className="text-muted-foreground text-xs">
+ Some metadata values are too large to show here.{" "}
+ <button
+ type="button"
+ onClick={openInTraceView}
+ className="text-primary underline underline-offset-2 hover:no-underline"
+ >
+ Open in trace view
+ </button>{" "}
+ for full metadata.
+ </p>
+ )}
+ </>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-2 rounded-md border border-dashed p-3">
+ <p className="text-muted-foreground text-xs">
+ This observation&apos;s input/output is too large to display in the
+ session view.
+ </p>
+ <TruncatedIOSection
+ label="Input"
+ value={observation.input}
+ fullLength={observation.inputLength}
+ truncated={observation.inputTruncated}
+ />
+ <TruncatedIOSection
+ label="Output"
+ value={observation.output}
+ fullLength={observation.outputLength}
+ truncated={observation.outputTruncated}
+ />
+ {/* Metadata stays visible when I/O is truncated β€” it shipped with the
+ observation and was always shown alongside I/O before the cap. */}
+ {observation.metadata !== null &&
+ typeof observation.metadata === "object" &&
+ Object.keys(observation.metadata).length > 0 && (
+ <TruncatedIOSection
+ label="Metadata"
+ value={observation.metadata}
+ fullLength={observation.metadataLength}
+ truncated={observation.metadataTruncated}
+ />
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button variant="outline" size="sm" onClick={openInTraceView}>
+ <ExternalLinkIcon className="mr-1 h-3.5 w-3.5" />
+ Open in trace view
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onDownload}
+ disabled={isDownloading}
+ >
+ {isDownloading ? (
+ <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Download className="mr-1 h-3.5 w-3.5" />
+ )}
+ Download I/O
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/web/src/components/session/TraceEventsRow.tsx b/web/src/components/session/TraceEventsRow.tsx
index 01e638470c..628f2a89e6 100644
--- a/web/src/components/session/TraceEventsRow.tsx
+++ b/web/src/components/session/TraceEventsRow.tsx
@@ -11,12 +11,16 @@ import { ItemBadge } from "@/src/components/ItemBadge";
import { NewDatasetItemFromTraceId } from "@/src/components/session/NewDatasetItemFromTrace";
import { type FilterState } from "@langfuse/shared";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
-import { IOPreview } from "@/src/components/trace/components/IOPreview/IOPreview";
+import { SessionObservationIO } from "@/src/components/session/SessionObservationIO";
import { api } from "@/src/utils/api";
import { FilterX } from "lucide-react";
import isEqual from "lodash/isEqual";
import { SESSION_DETAIL_VIEW_TRIGGER_ID } from "@/src/components/session/session-detail-presets";
+// Display copy for the per-card observation cap; the authoritative limit is
+// SESSION_OBSERVATIONS_PER_TRACE_LIMIT in the sessions router (LFE-10958).
+const SESSION_CARD_OBSERVATIONS_NOTICE_COUNT = 50;
+
const hasContent = (value: unknown): boolean =>
value !== null &&
value !== undefined &&
@@ -153,7 +157,20 @@ export const TraceEventsRow = React.memo(
// trace-level I/O that no observation shows (a v3-migrated trace can set
// trace I/O apart from any observation; dropping it would lose content and
// blind the annotation queue, which hides the trace panel).
- const observations = observationsQuery.data;
+ const observations = observationsQuery.data?.observations;
+ const hasMoreObservations = Boolean(
+ observationsQuery.data?.hasMoreObservations,
+ );
+
+ // Opens the trace peek AT the observation (the session page's peek config
+ // mirrors row.observationId into the ?observation= param; the annotation
+ // queue's openPeek opens the trace page in a new tab instead).
+ const openObservationInTraceView = React.useCallback(
+ (observationId: string) => {
+ openPeek(trace.id, { ...trace, observationId });
+ },
+ [openPeek, trace],
+ );
const visibleObservations = React.useMemo(() => {
if (!observations) return undefined;
const syntheticTraceRowId = `t-${trace.id}`;
@@ -163,15 +180,20 @@ export const TraceEventsRow = React.memo(
const realObservations = observations.filter(
(observation) => observation.id !== syntheticTraceRowId,
);
+ // I/O can be server-truncated to a preview head (LFE-10958), so equal
+ // heads alone don't prove equal payloads β€” the true lengths must match
+ // too (equal head + equal full length β‰ˆ identical content).
const syntheticRowIsRedundant =
!syntheticRow ||
!observationHasIO(syntheticRow) ||
realObservations.some(
(observation) =>
(hasContent(syntheticRow.input) &&
- isEqual(observation.input, syntheticRow.input)) ||
+ isEqual(observation.input, syntheticRow.input) &&
+ observation.inputLength === syntheticRow.inputLength) ||
(hasContent(syntheticRow.output) &&
- isEqual(observation.output, syntheticRow.output)),
+ isEqual(observation.output, syntheticRow.output) &&
+ observation.outputLength === syntheticRow.outputLength),
);
if (!syntheticRowIsRedundant) return observations;
return realObservations.length > 0 ? realObservations : observations;
@@ -198,7 +220,11 @@ export const TraceEventsRow = React.memo(
{visibleObservations.map((observation) => (
<div key={observation.id} className="flex flex-col gap-2">
<div className="text-muted-foreground flex flex-wrap items-center gap-2 text-xs">
- <span>{observation.name ?? "Observation"}</span>
+ {/* min-w-0 + wrap-break-word: unbroken long names must
+ wrap inside the card, not escape it */}
+ <span className="min-w-0 wrap-break-word">
+ {observation.name ?? "Observation"}
+ </span>
<span className="-mr-1">β€’</span>
<span className="inline-flex items-center gap-1">
<ItemBadge
@@ -215,24 +241,35 @@ export const TraceEventsRow = React.memo(
<span>β€’</span>
<span>{observation.startTime.toLocaleString()}</span>
</div>
- <IOPreview
- input={observation.input ?? undefined}
- output={observation.output ?? undefined}
- metadata={observation.metadata ?? undefined}
- observationName={observation.name ?? undefined}
- hideIfNull
+ <SessionObservationIO
+ observation={observation}
projectId={projectId}
+ sessionId={sessionId}
traceId={trace.id}
- observationId={observation.id}
environment={
observation.environment ??
trace.environment ??
undefined
}
showCorrections={showCorrections}
+ onOpenInTraceView={openObservationInTraceView}
/>
</div>
))}
+ {hasMoreObservations && (
+ <p className="text-muted-foreground text-xs">
+ Only the first {SESSION_CARD_OBSERVATIONS_NOTICE_COUNT}{" "}
+ observations are shown here.{" "}
+ <button
+ type="button"
+ onClick={() => openPeek(trace.id, trace)}
+ className="text-primary underline underline-offset-2 hover:no-underline"
+ >
+ Open the trace
+ </button>{" "}
+ to see all of them.
+ </p>
+ )}
</div>
) : observations &&
observations.length === 0 &&
@@ -263,8 +300,10 @@ export const TraceEventsRow = React.memo(
}}
>
<ItemBadge type="TRACE" isSmall />
- <div className="flex flex-col">
- <span className="text-xs font-medium">
+ {/* min-w-0 + wrap-break-word: an unbroken long trace
+ name must wrap inside the panel, not escape the card */}
+ <div className="flex min-w-0 flex-col">
+ <span className="text-xs font-medium wrap-break-word">
{trace.name ?? "Trace"} ({trace.id})&nbsp;β†—
</span>
<span className="text-muted-foreground text-xs">
diff --git a/web/src/components/session/TraceRow.tsx b/web/src/components/session/TraceRow.tsx
index 4d1a62d7eb..9d63818344 100644
--- a/web/src/components/session/TraceRow.tsx
+++ b/web/src/components/session/TraceRow.tsx
@@ -81,8 +81,10 @@ const TraceRow = React.memo(
}}
>
<ItemBadge type="TRACE" isSmall />
- <div className="flex flex-col">
- <span className="text-xs font-medium">
+ {/* min-w-0 + wrap-break-word: an unbroken long trace name
+ must wrap inside the panel, not escape the card */}
+ <div className="flex min-w-0 flex-col">
+ <span className="text-xs font-medium wrap-break-word">
{trace.name} ({trace.id})&nbsp;β†—
</span>
<span className="text-muted-foreground text-xs">
diff --git a/web/src/components/session/actions/downloadSessionAsJson.ts b/web/src/components/session/actions/downloadSessionAsJson.ts
index 0c9e4b0998..c5af9fa7b7 100644
--- a/web/src/components/session/actions/downloadSessionAsJson.ts
+++ b/web/src/components/session/actions/downloadSessionAsJson.ts
@@ -44,7 +44,7 @@ export function buildSessionExportData({
};
}
-function downloadJsonFile({
+export function downloadJsonFile({
data,
fileName,
}: {
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index cfafad5805..de7d679e3f 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -702,8 +702,11 @@ const LoadedSessionEventsPage: React.FC<{
basePath: `/project/${projectId}/traces`,
},
queryParams: ["observation", "display", "timestamp"],
+ // observationId: set by a card's "Open in trace view" on a truncated
+ // observation so the peek opens AT that observation (LFE-10958).
extractParamsValuesFromRow: (row: any) => ({
timestamp: row.timestamp.toISOString(),
+ ...(row.observationId ? { observation: row.observationId } : {}),
}),
}),
[projectId],
diff --git a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
index f222e73fce..a0149e408c 100644
--- a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
@@ -98,8 +98,16 @@ export const SessionAnnotationProcessor: React.FC<
// Stable callback to avoid creating new function reference on every render (defeats React.memo)
const openPeek = useCallback(
- (traceId: string) => {
- window.open(`/project/${projectId}/traces/${traceId}`, "_blank");
+ (traceId: string, row?: { observationId?: string }) => {
+ // observationId: a truncated observation's "Open in trace view" deep-links
+ // to that observation (LFE-10958).
+ const observationParam = row?.observationId
+ ? `?observation=${encodeURIComponent(row.observationId)}`
+ : "";
+ window.open(
+ `/project/${projectId}/traces/${traceId}${observationParam}`,
+ "_blank",
+ );
},
[projectId],
);
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 13103179da..6f621e7c52 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -112,6 +112,8 @@ export const events = {
"publish_button_click",
"download_button_click",
"copy_session_id_click",
+ "truncated_observation_open_trace_click",
+ "truncated_observation_download_click",
],
eval_config: [
"new_form_submit",
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index ac9338b749..45dd4edc88 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -32,6 +32,7 @@ import {
getSessionMetricsFromEvents,
getSessionTracesFromEvents,
getObservationsWithModelDataFromEventsTable,
+ getObservationFullIOForSessionFromEventsTable,
getTracesGroupedByTags,
getTracesIdentifierForSession,
getScoresForTraces,
@@ -70,6 +71,26 @@ const SessionTraceObservationsInput = z.object({
filter: z.array(singleFilter).nullable(),
});
+/**
+ * Bounded I/O contract for session-detail trace cards (LFE-10958). Cards are
+ * previews: every observation field whose full length fits the inline limit
+ * renders exactly as before; anything larger ships only a preview head plus
+ * its true length, and the trace peek / download are the full-reading
+ * surfaces. The inline limit matches the pretty view's client-side parse cap
+ * (deepParseJson maxSize) so under-cap cards are behavior-identical.
+ */
+const SESSION_OBSERVATION_INLINE_IO_CHAR_LIMIT = 300_000;
+const SESSION_OBSERVATION_PREVIEW_IO_CHAR_LIMIT = 4_000;
+/** Cards show at most this many observations; the peek shows the rest. */
+const SESSION_OBSERVATIONS_PER_TRACE_LIMIT = 50;
+/**
+ * Cumulative per-card I/O budget: once the summed returned I/O passes this,
+ * later observations collapse to preview heads even when each field is under
+ * the inline limit β€” many just-under-cap observations must not add up to an
+ * unbounded response.
+ */
+const SESSION_TRACE_TOTAL_IO_CHAR_BUDGET = 2_000_000;
+
const handleGetSessionById = async (input: {
sessionId: string;
projectId: string;
@@ -814,7 +835,10 @@ export const sessionRouter = createTRPCRouter({
];
let orderBy: OrderByState = { column: "startTime", order: "ASC" };
- let limit: number | undefined;
+ // One extra row detects "more observations than the card shows", and
+ // one more because the synthetic trace-level row (id `t-<traceId>`)
+ // may sit in the fetched window without consuming a card slot.
+ let limit: number = SESSION_OBSERVATIONS_PER_TRACE_LIMIT + 2;
let offset: number | undefined;
if (positionFilter) {
@@ -832,7 +856,10 @@ export const sessionRouter = createTRPCRouter({
limit = 1;
}
- const observations = await getObservationsWithModelDataFromEventsTable({
+ // No renderingProps: ioSizeCap owns the I/O select, and this path's
+ // conversion always returns I/O as raw strings (the V1 enricher
+ // hardcodes parseIoAsJson=false) β€” the client parses.
+ const fetched = await getObservationsWithModelDataFromEventsTable({
projectId: input.projectId,
filter: filterState,
searchQuery: undefined,
@@ -841,10 +868,132 @@ export const sessionRouter = createTRPCRouter({
limit,
offset,
selectIOAndMetadata: true,
- renderingProps: { truncated: false, shouldJsonParse: true },
+ ioSizeCap: {
+ inlineChars: SESSION_OBSERVATION_INLINE_IO_CHAR_LIMIT,
+ previewChars: SESSION_OBSERVATION_PREVIEW_IO_CHAR_LIMIT,
+ },
+ // Un-merged ReplacingMergeTree row versions of one span must not
+ // count as separate observations: the 50-row page, the hasMore
+ // detection, and the budget below all count rows.
+ dedupeBySpanId: true,
+ });
+
+ // The synthetic trace-level row is metadata about the trace, not one of
+ // its observations: it must neither consume one of the card's slots
+ // (displacing a real observation) nor count toward hasMore. The client
+ // decides whether to show or drop it (redundancy dedupe).
+ const syntheticTraceRowId = `t-${input.traceId}`;
+ const realFetchedCount = fetched.filter(
+ (observation) => observation.id !== syntheticTraceRowId,
+ ).length;
+ const hasMoreObservations =
+ !positionFilter &&
+ realFetchedCount > SESSION_OBSERVATIONS_PER_TRACE_LIMIT;
+ let realTaken = 0;
+ const page: typeof fetched = [];
+ for (const observation of fetched) {
+ if (observation.id === syntheticTraceRowId) {
+ page.push(observation);
+ continue;
+ }
+ if (realTaken >= SESSION_OBSERVATIONS_PER_TRACE_LIMIT) continue;
+ page.push(observation);
+ realTaken++;
+ }
+
+ // Preview head of a value regardless of parse state: I/O is a raw
+ // string on this path, but if conversion ever starts returning parsed
+ // objects the budget must keep holding β€” hence the stringify branch.
+ // The cut is surrogate-safe: plain .slice can split an astral-plane
+ // character (emoji/CJK) and leave a corrupted lone surrogate β€” the SQL
+ // side avoids this via leftUTF8, so the JS fallback must too.
+ const toPreviewHead = (value: unknown): unknown => {
+ const text =
+ typeof value === "string" ? value : (JSON.stringify(value) ?? "");
+ if (text.length <= SESSION_OBSERVATION_PREVIEW_IO_CHAR_LIMIT)
+ return value;
+ const head = text.slice(0, SESSION_OBSERVATION_PREVIEW_IO_CHAR_LIMIT);
+ const lastCode = head.charCodeAt(head.length - 1);
+ return lastCode >= 0xd800 && lastCode <= 0xdbff
+ ? head.slice(0, -1)
+ : head;
+ };
+
+ // Cumulative budget: rows are order-stable (startTime ASC + span-dedup),
+ // so the trim is deterministic. The check runs before adding the row's
+ // own size, so the first observation always keeps whatever the per-field
+ // cap allowed. Sizes come from the server-computed lengths + flags β€”
+ // including the shipped metadata weight β€” NOT from the returned values,
+ // so the accounting is independent of value shape.
+ let cumulativeIOChars = 0;
+ const observations = page.map((observation) => {
+ const returnedIOChars =
+ (observation.inputTruncated
+ ? SESSION_OBSERVATION_PREVIEW_IO_CHAR_LIMIT
+ : observation.inputLength) +
+ (observation.outputTruncated
+ ? SESSION_OBSERVATION_PREVIEW_IO_CHAR_LIMIT
+ : observation.outputLength) +
+ observation.metadataLength;
+ const withinBudget =
+ cumulativeIOChars <= SESSION_TRACE_TOTAL_IO_CHAR_BUDGET;
+ cumulativeIOChars += returnedIOChars;
+ if (withinBudget) return observation;
+
+ const input = toPreviewHead(observation.input);
+ const output = toPreviewHead(observation.output);
+ return {
+ ...observation,
+ input,
+ output,
+ // Past the budget, metadata is dropped rather than shipped β€” the
+ // flag routes readers to the trace view for the full values.
+ metadata: {},
+ metadataTruncated:
+ observation.metadataTruncated || observation.metadataLength > 0,
+ inputTruncated:
+ observation.inputTruncated || input !== observation.input,
+ outputTruncated:
+ observation.outputTruncated || output !== observation.output,
+ };
+ });
+
+ return { observations, hasMoreObservations };
+ }),
+ /**
+ * Full raw I/O for one observation, for the session card's download
+ * fallback (LFE-10958). Session-authorized (public sessions included); the
+ * repository query scopes by sessionId so a session grant cannot read
+ * observations outside that session. Returns raw strings β€” the client
+ * saves them to a file and never renders them.
+ */
+ observationFullIOFromEvents: protectedGetSessionProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ sessionId: z.string(),
+ traceId: z.string(),
+ observationId: z.string(),
+ startTime: z.date(),
+ }),
+ )
+ .query(async ({ input }) => {
+ const observation = await getObservationFullIOForSessionFromEventsTable({
+ projectId: input.projectId,
+ sessionId: input.sessionId,
+ traceId: input.traceId,
+ observationId: input.observationId,
+ startTime: input.startTime,
});
- return observations;
+ if (!observation) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Observation not found in session",
+ });
+ }
+
+ return observation;
}),
bookmark: protectedProjectProcedure
.input(