Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: parse livekit attributes on otel spans (#10771)

Jannik Maierhöfer2a8b063832cf
diff --git a/packages/shared/src/server/otel/ObservationTypeMapper.ts b/packages/shared/src/server/otel/ObservationTypeMapper.ts
index d7572816f1..2d0f8e5d96 100644
--- a/packages/shared/src/server/otel/ObservationTypeMapper.ts
+++ b/packages/shared/src/server/otel/ObservationTypeMapper.ts
@@ -10,11 +10,13 @@ interface ObservationTypeMapper {
attributes: Record<string, unknown>,
resourceAttributes?: Record<string, unknown>,
scopeData?: Record<string, unknown>,
+ spanName?: string,
): boolean;
mapToObservationType(
attributes: Record<string, unknown>,
resourceAttributes?: Record<string, unknown>,
scopeData?: Record<string, unknown>,
+ spanName?: string,
): LangfuseObservationType | null;
}
@@ -30,6 +32,7 @@ class SimpleAttributeMapper implements ObservationTypeMapper {
attributes: Record<string, unknown>,
_resourceAttributes?: Record<string, unknown>,
_scopeData?: Record<string, unknown>,
+ _spanName?: string,
): boolean {
return (
this.attributeKey in attributes &&
@@ -41,6 +44,7 @@ class SimpleAttributeMapper implements ObservationTypeMapper {
attributes: Record<string, unknown>,
_resourceAttributes?: Record<string, unknown>,
_scopeData?: Record<string, unknown>,
+ _spanName?: string,
): LangfuseObservationType | null {
const value = attributes[this.attributeKey] as string;
const mappedType = this.mappings[value];
@@ -67,11 +71,13 @@ class CustomAttributeMapper implements ObservationTypeMapper {
attributes: Record<string, unknown>,
resourceAttributes?: Record<string, unknown>,
scopeData?: Record<string, unknown>,
+ spanName?: string,
) => boolean,
private readonly mapFn: (
attributes: Record<string, unknown>,
resourceAttributes?: Record<string, unknown>,
scopeData?: Record<string, unknown>,
+ spanName?: string,
) => LangfuseObservationType | null,
) {}
@@ -79,16 +85,23 @@ class CustomAttributeMapper implements ObservationTypeMapper {
attributes: Record<string, unknown>,
resourceAttributes?: Record<string, unknown>,
scopeData?: Record<string, unknown>,
+ spanName?: string,
): boolean {
- return this.canMapFn(attributes, resourceAttributes, scopeData);
+ return this.canMapFn(attributes, resourceAttributes, scopeData, spanName);
}
mapToObservationType(
attributes: Record<string, unknown>,
resourceAttributes?: Record<string, unknown>,
scopeData?: Record<string, unknown>,
+ spanName?: string,
): LangfuseObservationType | null {
- const result = this.mapFn(attributes, resourceAttributes, scopeData);
+ const result = this.mapFn(
+ attributes,
+ resourceAttributes,
+ scopeData,
+ spanName,
+ );
if (
result &&
@@ -381,9 +394,30 @@ export class ObservationTypeMapperRegistry {
() => "TOOL",
),
+ // LiveKit spans: use span name to determine observation type
new CustomAttributeMapper(
- "ModelBased",
+ "LiveKit_SpanName",
7,
+ (_attributes, _resourceAttributes, scopeData, spanName) => {
+ if (scopeData?.name !== "livekit-agents") return false;
+
+ return (
+ spanName === "agent_turn" ||
+ spanName === "start_agent_activity" ||
+ spanName === "function_tool"
+ );
+ },
+ (_attributes, _resourceAttributes, _scopeData, spanName) => {
+ if (spanName === "agent_turn" || spanName === "start_agent_activity")
+ return "AGENT";
+ if (spanName === "function_tool") return "TOOL";
+ return null;
+ },
+ ),
+
+ new CustomAttributeMapper(
+ "ModelBased",
+ 8,
(attributes, _resourceAttributes, _scopeData) => {
const modelKeys = [
LangfuseOtelSpanAttributes.OBSERVATION_MODEL,
@@ -413,14 +447,16 @@ export class ObservationTypeMapperRegistry {
attributes: Record<string, unknown>,
resourceAttributes?: Record<string, unknown>,
scopeData?: Record<string, unknown>,
+ spanName?: string,
): LangfuseObservationType {
const sortedMappers = this.getSortedMappers();
for (const mapper of sortedMappers) {
- if (mapper.canMap(attributes, resourceAttributes, scopeData)) {
+ if (mapper.canMap(attributes, resourceAttributes, scopeData, spanName)) {
const result = mapper.mapToObservationType(
attributes,
resourceAttributes,
scopeData,
+ spanName,
);
if (result) {
return result;
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
index 9c3e0b9ff2..2942e07f0e 100644
--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
@@ -121,6 +121,24 @@ const observationTypeMapper = new ObservationTypeMapperRegistry();
* Manages trace deduplication internally and provides a clean interface
* for converting OTEL spans to Langfuse events.
*/
+const LIVEKIT_DEBUG_SPAN_NAMES = new Set([
+ "user_speaking",
+ "eou_detection",
+ "llm_request_run",
+ "tts_node",
+ "tts_request",
+ "tts_request_run",
+ "tts_stream_adapter",
+ "agent_speaking",
+ "drain_agent_activity",
+ "on_exit",
+ "on_enter",
+ "llm_fallback_adapter",
+ "tts_fallback_adapter",
+ "start_agent_activity",
+ "on_enter",
+]);
+
export class OtelIngestionProcessor {
private static readonly OTEL_CONVERSION_FAILURE_METRIC =
"langfuse.ingestion.otel.conversion_failure";
@@ -346,6 +364,7 @@ export class OtelIngestionProcessor {
spanAttributes,
resourceAttributes,
scopeSpan?.scope,
+ span.name,
),
environment: this.extractEnvironment(
spanAttributes,
@@ -365,7 +384,10 @@ export class OtelIngestionProcessor {
] ??
(span.status?.code === 2
? ObservationLevel.ERROR
- : ObservationLevel.DEFAULT),
+ : scopeSpan?.scope?.name === "livekit-agents" &&
+ LIVEKIT_DEBUG_SPAN_NAMES.has(span.name)
+ ? ObservationLevel.DEBUG
+ : ObservationLevel.DEFAULT),
statusMessage:
spanAttributes[
LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE
@@ -943,7 +965,10 @@ export class OtelIngestionProcessor {
attributes[LangfuseOtelSpanAttributes.OBSERVATION_LEVEL] ??
(span.status?.code === 2
? ObservationLevel.ERROR
- : ObservationLevel.DEFAULT),
+ : scopeSpan?.scope?.name === "livekit-agents" &&
+ LIVEKIT_DEBUG_SPAN_NAMES.has(span.name)
+ ? ObservationLevel.DEBUG
+ : ObservationLevel.DEFAULT),
statusMessage:
attributes[LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE] ??
span.status?.message ??
@@ -980,6 +1005,7 @@ export class OtelIngestionProcessor {
attributes,
resourceAttributes,
scopeSpan?.scope,
+ span.name,
);
const observationType =
mappedObservationType && typeof mappedObservationType === "string"
@@ -1206,6 +1232,9 @@ export class OtelIngestionProcessor {
"events",
// LiveKit
"lk.input_text",
+ "lk.user_transcript",
+ "lk.chat_ctx",
+ "lk.user_input",
"lk.function_tool.output",
"lk.response.text",
// MLFlow
@@ -1437,7 +1466,10 @@ export class OtelIngestionProcessor {
}
// LiveKit
- input = attributes["lk.input_text"];
+ input =
+ attributes["lk.input_text"] ??
+ attributes["lk.user_transcript"] ??
+ attributes["lk.chat_ctx"];
output =
attributes["lk.function_tool.output"] || attributes["lk.response.text"];
if (input || output) {
diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
index b92403d59e..a8eb41b4e3 100644
--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
@@ -1380,6 +1380,160 @@ describe("OTel Resource Span Mapping", () => {
expect(toolObservation?.body.name).toBe("correct_tool_name");
});
+ const livekitTraceId = "abcdef1234567890abcdef1234567890";
+
+ const createLivekitSpan = (params: {
+ name: string;
+ attributes?: Array<{ key: string; value: { stringValue: string } }>;
+ statusCode?: number;
+ scopeName?: string;
+ }) => ({
+ resource: {
+ attributes: [
+ {
+ key: "telemetry.sdk.language",
+ value: { stringValue: "python" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ ...(params.scopeName ? { scope: { name: params.scopeName } } : {}),
+ spans: [
+ {
+ traceId: Buffer.from(livekitTraceId, "hex"),
+ spanId: Buffer.from("1234567890abcdef", "hex"),
+ name: params.name,
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1000000,
+ high: 406528574,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 2000000,
+ high: 406528574,
+ unsigned: true,
+ },
+ attributes: params.attributes ?? [],
+ events: [],
+ status: { code: params.statusCode ?? 1 },
+ },
+ ],
+ },
+ ],
+ });
+
+ const findObservationCreateEvent = (events: any[]) =>
+ events.find(
+ (e) => e.type !== "trace-create" && e.type.endsWith("-create"),
+ );
+
+ it.each([
+ {
+ spanName: "agent_turn",
+ expectedType: "agent-create",
+ attributes: [
+ {
+ key: "lk.input_text",
+ value: { stringValue: "What is the weather today?" },
+ },
+ {
+ key: "lk.response.text",
+ value: { stringValue: "The weather is sunny." },
+ },
+ ],
+ },
+ {
+ spanName: "function_tool",
+ expectedType: "tool-create",
+ attributes: [
+ {
+ key: "lk.function_tool.output",
+ value: { stringValue: '{"temperature": 75, "condition": "sunny"}' },
+ },
+ ],
+ },
+ {
+ spanName: "start_agent_activity",
+ expectedType: "agent-create",
+ },
+ ])(
+ "should map LiveKit $spanName span to $expectedType observation type",
+ async ({ spanName, expectedType, attributes }) => {
+ const events = await convertOtelSpanToIngestionEvent(
+ createLivekitSpan({
+ name: spanName,
+ attributes,
+ scopeName: "livekit-agents",
+ }),
+ new Set([livekitTraceId]),
+ );
+
+ const observation = events.find((e) => e.type === expectedType);
+ expect(observation).toBeDefined();
+ expect(observation?.type).toBe(expectedType);
+ expect(observation?.body.name).toBe(spanName);
+ },
+ );
+
+ it("should not map LiveKit span names without livekit-agents scope", async () => {
+ const events = await convertOtelSpanToIngestionEvent(
+ createLivekitSpan({
+ name: "agent_turn",
+ }),
+ new Set([livekitTraceId]),
+ );
+
+ const observation = events.find(
+ (e) => e.type !== "trace-create" && e.type.endsWith("-create"),
+ );
+ expect(observation).toBeDefined();
+ expect(observation?.type).toBe("span-create");
+ });
+
+ it.each([
+ {
+ spanName: "tts_fallback_adapter",
+ statusCode: 1,
+ expectedLevel: "DEBUG",
+ },
+ {
+ spanName: "tts_fallback_adapter",
+ statusCode: 2,
+ expectedLevel: "ERROR",
+ },
+ { spanName: "user_speaking", statusCode: 1, expectedLevel: "DEBUG" },
+ { spanName: "eou_detection", statusCode: 1, expectedLevel: "DEBUG" },
+ { spanName: "llm_request_run", statusCode: 1, expectedLevel: "DEBUG" },
+ { spanName: "tts_node", statusCode: 1, expectedLevel: "DEBUG" },
+ { spanName: "tts_request_run", statusCode: 1, expectedLevel: "DEBUG" },
+ { spanName: "tts_stream_adapter", statusCode: 1, expectedLevel: "DEBUG" },
+ { spanName: "agent_speaking", statusCode: 1, expectedLevel: "DEBUG" },
+ {
+ spanName: "drain_agent_activity",
+ statusCode: 1,
+ expectedLevel: "DEBUG",
+ },
+ { spanName: "on_exit", statusCode: 1, expectedLevel: "DEBUG" },
+ ])(
+ "should set level to $expectedLevel for LiveKit span named $spanName",
+ async ({ spanName, statusCode, expectedLevel }) => {
+ const events = await convertOtelSpanToIngestionEvent(
+ createLivekitSpan({
+ name: spanName,
+ scopeName: "livekit-agents",
+ statusCode,
+ }),
+ new Set([livekitTraceId]),
+ );
+
+ const observation = findObservationCreateEvent(events);
+ expect(observation).toBeDefined();
+ expect(observation?.body.level).toBe(expectedLevel);
+ },
+ );
+
it("should map Pydantic AI agent root span with final_result as output and pydantic_ai.all_messages as input", async () => {
const traceId = "abcdef1234567890abcdef1234567890";
@@ -2640,6 +2794,56 @@ describe("OTel Resource Span Mapping", () => {
entityAttributeValue: "What is the weather today?",
},
],
+ [
+ "should map lk.user_transcript to input",
+ {
+ entity: "observation",
+ otelAttributeKey: "lk.user_transcript",
+ otelAttributeValue: {
+ stringValue: "Hey there. What's the weather?",
+ },
+ entityAttributeKey: "input",
+ entityAttributeValue: "Hey there. What's the weather?",
+ },
+ ],
+ [
+ "should map lk.chat_ctx to input",
+ {
+ entity: "observation",
+ otelAttributeKey: "lk.chat_ctx",
+ otelAttributeValue: {
+ stringValue: JSON.stringify({
+ items: [
+ {
+ id: "lk.agent_task.instructions",
+ type: "message",
+ role: "system",
+ content: ["Your name is Kelly."],
+ interrupted: false,
+ extra: {},
+ metrics: {},
+ created_at: 1764240453.4831302,
+ },
+ ],
+ }),
+ },
+ entityAttributeKey: "input",
+ entityAttributeValue: JSON.stringify({
+ items: [
+ {
+ id: "lk.agent_task.instructions",
+ type: "message",
+ role: "system",
+ content: ["Your name is Kelly."],
+ interrupted: false,
+ extra: {},
+ metrics: {},
+ created_at: 1764240453.4831302,
+ },
+ ],
+ }),
+ },
+ ],
[
"should map lk.response.text to output",
{
diff --git a/web/src/components/trace2/contexts/TraceDataContext.tsx b/web/src/components/trace2/contexts/TraceDataContext.tsx
index cee65ee44d..1de4527d48 100644
--- a/web/src/components/trace2/contexts/TraceDataContext.tsx
+++ b/web/src/components/trace2/contexts/TraceDataContext.tsx
@@ -12,11 +12,19 @@
*/
import { createContext, useContext, useMemo, type ReactNode } from "react";
-import { type TraceDomain, type ScoreDomain } from "@langfuse/shared";
+import {
+ type TraceDomain,
+ type ScoreDomain,
+ ObservationLevel,
+} from "@langfuse/shared";
import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
import { type TreeNode, type TraceSearchListItem } from "../lib/types";
-import { buildTraceUiData } from "../lib/tree-building";
+import {
+ buildTraceUiData,
+ getObservationLevels,
+ removeHiddenNodes,
+} from "../lib/tree-building";
import { useViewPreferences } from "./ViewPreferencesContext";
import { useMergedScores } from "@/src/features/scores/lib/useMergedScores";
@@ -74,9 +82,38 @@ export function TraceDataProvider({
}: TraceDataProviderProps) {
const { minObservationLevel } = useViewPreferences();
+ // Build full tree (no level filtering) — only rebuilds when data changes
const uiData = useMemo(() => {
- return buildTraceUiData(trace, observations, minObservationLevel);
- }, [trace, observations, minObservationLevel]);
+ return buildTraceUiData(trace, observations);
+ }, [trace, observations]);
+
+ // Apply level filtering as a cheap post-processing step
+ const { filteredRoots, filteredSearchItems, hiddenObservationsCount } =
+ useMemo(() => {
+ const allowedLevels = getObservationLevels(minObservationLevel);
+ const isAllLevels = allowedLevels.includes(ObservationLevel.DEBUG);
+
+ if (isAllLevels) {
+ return {
+ filteredRoots: uiData.roots,
+ filteredSearchItems: uiData.searchItems,
+ hiddenObservationsCount: 0,
+ };
+ }
+
+ const allowedSet = new Set<string>(allowedLevels);
+ const isHidden = (node: TreeNode) =>
+ node.type !== "TRACE" && !!node.level && !allowedSet.has(node.level);
+
+ const filteredRoots = removeHiddenNodes(uiData.roots, isHidden);
+ const filteredSearchItems = uiData.searchItems.filter(
+ (item) => !isHidden(item.node),
+ );
+ const hiddenObservationsCount =
+ uiData.searchItems.length - filteredSearchItems.length;
+
+ return { filteredRoots, filteredSearchItems, hiddenObservationsCount };
+ }, [uiData, minObservationLevel]);
// Merge scores with optimistic cache
const mergedScores = useMergedScores(
@@ -95,10 +132,10 @@ export function TraceDataProvider({
serverScores: serverScores,
mergedScores,
corrections,
- roots: uiData.roots,
+ roots: filteredRoots,
nodeMap: uiData.nodeMap,
- searchItems: uiData.searchItems,
- hiddenObservationsCount: uiData.hiddenObservationsCount,
+ searchItems: filteredSearchItems,
+ hiddenObservationsCount,
comments,
}),
[
@@ -107,7 +144,10 @@ export function TraceDataProvider({
serverScores,
mergedScores,
corrections,
- uiData,
+ filteredRoots,
+ filteredSearchItems,
+ hiddenObservationsCount,
+ uiData.nodeMap,
comments,
],
);
diff --git a/web/src/components/trace2/lib/tree-building.clienttest.ts b/web/src/components/trace2/lib/tree-building.clienttest.ts
index f735cf640e..e068147e7c 100644
--- a/web/src/components/trace2/lib/tree-building.clienttest.ts
+++ b/web/src/components/trace2/lib/tree-building.clienttest.ts
@@ -4,7 +4,12 @@
* Run with: pnpm test-client --testPathPattern="tree-building"
*/
-import { buildTraceUiData } from "./tree-building";
+import {
+ buildTraceUiData,
+ removeHiddenNodes,
+ getObservationLevels,
+} from "./tree-building";
+import { type TreeNode } from "./types";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import Decimal from "decimal.js";
@@ -209,7 +214,6 @@ describe("buildTraceUiData", () => {
expect(result.roots).toHaveLength(1);
expect(result.roots[0].children).toHaveLength(0);
expect(result.searchItems).toHaveLength(1); // Just the trace
- expect(result.hiddenObservationsCount).toBe(0);
});
it("sorts children by startTime", () => {
@@ -1660,3 +1664,239 @@ describe("buildTraceUiData", () => {
});
});
});
+
+describe("removeHiddenNodes", () => {
+ const makeNode = (
+ overrides: Partial<TreeNode> & { id: string },
+ ): TreeNode => ({
+ type: "SPAN",
+ name: overrides.id,
+ startTime: new Date("2024-01-01T00:00:00Z"),
+ endTime: new Date("2024-01-01T00:00:01Z"),
+ level: "DEFAULT",
+ children: [],
+ startTimeSinceTrace: 0,
+ startTimeSinceParentStart: null,
+ depth: 0,
+ childrenDepth: 0,
+ ...overrides,
+ });
+
+ const flattenIds = (nodes: TreeNode[]): Array<[string, string[]]> => {
+ const out: Array<[string, string[]]> = [];
+ const stack = [...nodes].reverse();
+
+ while (stack.length > 0) {
+ const node = stack.pop()!;
+ out.push([node.id, node.children.map((c) => c.id)]);
+ for (let i = node.children.length - 1; i >= 0; i--) {
+ stack.push(node.children[i]!);
+ }
+ }
+
+ return out;
+ };
+
+ it.each([
+ {
+ name: "keeps nodes unchanged when none are hidden",
+ roots: [
+ makeNode({
+ id: "A",
+ children: [makeNode({ id: "B" }), makeNode({ id: "C" })],
+ }),
+ ],
+ expected: [
+ ["A", ["B", "C"]],
+ ["B", []],
+ ["C", []],
+ ],
+ predicate: () => false,
+ },
+ {
+ name: "promotes children of hidden intermediate nodes",
+ roots: [
+ makeNode({
+ id: "A",
+ children: [
+ makeNode({
+ id: "B",
+ level: "DEBUG",
+ children: [makeNode({ id: "C" })],
+ }),
+ ],
+ }),
+ ],
+ expected: [
+ ["A", ["C"]],
+ ["C", []],
+ ],
+ predicate: (n: TreeNode) => n.level === "DEBUG",
+ },
+ {
+ name: "promotes children of hidden root nodes",
+ roots: [
+ makeNode({
+ id: "A",
+ level: "DEBUG",
+ children: [makeNode({ id: "B" }), makeNode({ id: "C" })],
+ }),
+ ],
+ expected: [
+ ["B", []],
+ ["C", []],
+ ],
+ predicate: (n: TreeNode) => n.level === "DEBUG",
+ },
+ {
+ name: "handles consecutive hidden ancestors",
+ roots: [
+ makeNode({
+ id: "A",
+ children: [
+ makeNode({
+ id: "B",
+ level: "DEBUG",
+ children: [
+ makeNode({
+ id: "C",
+ level: "DEBUG",
+ children: [makeNode({ id: "D" })],
+ }),
+ ],
+ }),
+ ],
+ }),
+ ],
+ expected: [
+ ["A", ["D"]],
+ ["D", []],
+ ],
+ predicate: (n: TreeNode) => n.level === "DEBUG",
+ },
+ {
+ name: "merges promoted children with existing siblings",
+ roots: [
+ makeNode({
+ id: "A",
+ children: [
+ makeNode({
+ id: "B",
+ level: "DEBUG",
+ children: [makeNode({ id: "B1" }), makeNode({ id: "B2" })],
+ }),
+ makeNode({ id: "C" }),
+ ],
+ }),
+ ],
+ expected: [
+ ["A", ["B1", "B2", "C"]],
+ ["B1", []],
+ ["B2", []],
+ ["C", []],
+ ],
+ predicate: (n: TreeNode) => n.level === "DEBUG",
+ },
+ {
+ name: "removes hidden leaf nodes",
+ roots: [
+ makeNode({
+ id: "A",
+ children: [
+ makeNode({ id: "B", level: "DEBUG" }),
+ makeNode({ id: "C" }),
+ ],
+ }),
+ ],
+ expected: [
+ ["A", ["C"]],
+ ["C", []],
+ ],
+ predicate: (n: TreeNode) => n.level === "DEBUG",
+ },
+ ])("$name", ({ roots, expected, predicate }) => {
+ const result = removeHiddenNodes(roots, predicate);
+ expect(flattenIds(result)).toEqual(expected);
+ });
+
+ it("does not modify the original tree", () => {
+ const child = makeNode({ id: "C" });
+ const hidden = makeNode({
+ id: "B",
+ level: "DEBUG",
+ children: [child],
+ });
+ const root = makeNode({ id: "A", children: [hidden] });
+
+ removeHiddenNodes([root], (n) => n.level === "DEBUG");
+
+ // Original tree is untouched
+ expect(root.children).toHaveLength(1);
+ expect(root.children[0].id).toBe("B");
+ expect(root.children[0].children).toHaveLength(1);
+ });
+
+ it("preserves TRACE nodes even if predicate matches", () => {
+ const roots = [
+ makeNode({
+ id: "trace-1",
+ type: "TRACE",
+ level: "DEBUG",
+ children: [makeNode({ id: "obs-1" })],
+ }),
+ ];
+
+ const result = removeHiddenNodes(
+ roots,
+ (n) => n.type !== "TRACE" && n.level === "DEBUG",
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe("trace-1");
+ expect(result[0].children).toHaveLength(1);
+ });
+
+ it("handles deeply nested trees without stack overflow", () => {
+ const depth = 15_000;
+ const root = makeNode({ id: "node-0" });
+ let current = root;
+
+ for (let i = 1; i < depth; i++) {
+ const child = makeNode({ id: `node-${i}` });
+ current.children = [child];
+ current = child;
+ }
+
+ const result = removeHiddenNodes([root], () => false);
+
+ expect(result).toHaveLength(1);
+ let count = 0;
+ let cursor: TreeNode | undefined = result[0];
+ while (cursor) {
+ count++;
+ cursor = cursor.children[0];
+ }
+
+ expect(count).toBe(depth);
+ });
+});
+
+describe("getObservationLevels", () => {
+ it.each([
+ {
+ minLevel: undefined,
+ expected: ["DEBUG", "DEFAULT", "WARNING", "ERROR"],
+ },
+ {
+ minLevel: "DEFAULT" as const,
+ expected: ["DEFAULT", "WARNING", "ERROR"],
+ },
+ {
+ minLevel: "ERROR" as const,
+ expected: ["ERROR"],
+ },
+ ])("returns levels at/above $minLevel", ({ minLevel, expected }) => {
+ const levels = getObservationLevels(minLevel);
+ expect(levels).toEqual(expected);
+ });
+});
diff --git a/web/src/components/trace2/lib/tree-building.ts b/web/src/components/trace2/lib/tree-building.ts
index a3a2e02c12..a4465812b6 100644
--- a/web/src/components/trace2/lib/tree-building.ts
+++ b/web/src/components/trace2/lib/tree-building.ts
@@ -5,12 +5,15 @@
* Uses fully iterative algorithms (no recursion) to avoid stack overflow on deep trees (10k+ depth).
*
* Algorithm Overview:
- * 1. Filter observations by level threshold and sort by startTime
+ * 1. Sort observations by startTime
* 2. Build dependency graph: Map-based parent-child relationships (O(N))
* 3. Topological sort: Process nodes bottom-up (leaves first) using queue with index-based traversal
* 4. Cost aggregation: Compute bottom-up during tree construction (children before parents)
* 5. Flatten to searchItems: Iterative pre-order traversal using explicit stack
*
+ * Level filtering (hiding DEBUG observations etc.) is NOT done here — it's applied
+ * as a post-processing step via removeHiddenNodes() in the display layer (TraceDataContext).
+ *
* Complexity: O(N) time, O(N) space - handles unlimited depth without stack overflow.
*
* Main export: buildTraceUiData() - builds tree, nodeMap, and searchItems from trace + observations.
@@ -53,7 +56,9 @@ interface ProcessingNode {
/**
* Returns observation levels at or above the minimum level.
*/
-function getObservationLevels(minLevel: ObservationLevelType | undefined) {
+export function getObservationLevels(
+ minLevel: ObservationLevelType | undefined,
+) {
const ascendingLevels = [
ObservationLevel.DEBUG,
ObservationLevel.DEFAULT,
@@ -68,37 +73,24 @@ function getObservationLevels(minLevel: ObservationLevelType | undefined) {
}
/**
- * Filters and prepares observations for tree building.
- * Filters by minimum observation level, cleans orphaned parents, and sorts by startTime.
+ * Prepares observations for tree building.
+ * Cleans orphaned parent references and sorts by startTime.
* Returns flat array (nesting happens in buildDependencyGraph).
*/
-function filterAndPrepareObservations(
- list: ObservationReturnType[],
- minLevel?: ObservationLevelType,
-): {
+function prepareObservations(list: ObservationReturnType[]): {
sortedObservations: ObservationReturnType[];
- hiddenObservationsCount: number;
} {
- if (list.length === 0)
- return { sortedObservations: [], hiddenObservationsCount: 0 };
-
- // Filter for observations with minimum level
- const mutableList = list.filter((o) =>
- getObservationLevels(minLevel).includes(o.level),
- );
- const hiddenObservationsCount = list.length - mutableList.length;
+ if (list.length === 0) return { sortedObservations: [] };
// Build a Set of all observation IDs for O(1) lookup
const observationIds = new Set(list.map((o) => o.id));
- // Remove parentObservationId if parent doesn't exist
- mutableList.forEach((observation) => {
- if (
- observation.parentObservationId &&
- !observationIds.has(observation.parentObservationId)
- ) {
- observation.parentObservationId = null;
+ // Remove parentObservationId if parent doesn't exist in the list
+ const mutableList = list.map((o) => {
+ if (o.parentObservationId && !observationIds.has(o.parentObservationId)) {
+ return { ...o, parentObservationId: null };
}
+ return o;
});
// Sort by start time
@@ -106,10 +98,7 @@ function filterAndPrepareObservations(
(a, b) => a.startTime.getTime() - b.startTime.getTime(),
);
- return {
- sortedObservations,
- hiddenObservationsCount,
- };
+ return { sortedObservations };
}
/**
@@ -170,7 +159,7 @@ function buildDependencyGraph(sortedObservations: ObservationReturnType[]): {
// Fourth pass: calculate in-degrees and identify leaf nodes
// Note: Children are already in correct order because observations are pre-sorted
- // by startTime in filterAndPrepareObservations, and children are added in iteration order.
+ // by startTime in prepareObservations, and children are added in iteration order.
const leafIds: string[] = [];
for (const [id, node] of nodeRegistry) {
// Set in-degree to children count (for topological sort)
@@ -334,21 +323,18 @@ function buildTreeNodesBottomUp(
function buildTraceTree(
trace: TraceType,
observations: ObservationReturnType[],
- minLevel?: ObservationLevelType,
): {
roots: TreeNode[];
- hiddenObservationsCount: number;
nodeMap: Map<string, TreeNode>;
} {
- // Phase 1: Filter and prepare observations
- const { sortedObservations, hiddenObservationsCount } =
- filterAndPrepareObservations(observations, minLevel);
+ // Phase 1: Prepare observations (sort, clean orphaned parents)
+ const { sortedObservations } = prepareObservations(observations);
// Handle empty case
if (sortedObservations.length === 0) {
// For events-based traces with no observations, return empty roots
if (trace.rootObservationType) {
- return { roots: [], hiddenObservationsCount, nodeMap: new Map() };
+ return { roots: [], nodeMap: new Map() };
}
// Traditional traces: return TRACE node with no children
@@ -369,7 +355,7 @@ function buildTraceTree(
};
const nodeMap = new Map<string, TreeNode>();
nodeMap.set(emptyTree.id, emptyTree);
- return { roots: [emptyTree], hiddenObservationsCount, nodeMap };
+ return { roots: [emptyTree], nodeMap };
}
// Phase 2: Build dependency graph
@@ -398,7 +384,7 @@ function buildTraceTree(
// Events-based traces (rootObservationType set): return observations as roots directly
if (trace.rootObservationType) {
- return { roots: rootTreeNodes, hiddenObservationsCount, nodeMap };
+ return { roots: rootTreeNodes, nodeMap };
}
// Traditional traces: wrap in TRACE node
@@ -437,37 +423,33 @@ function buildTraceTree(
nodeMap.set(traceNode.id, traceNode);
- return { roots: [traceNode], hiddenObservationsCount, nodeMap };
+ return { roots: [traceNode], nodeMap };
}
/**
* Main entry point: builds complete UI data from trace and observations.
*
+ * Level filtering (hiding DEBUG observations etc.) is NOT done here.
+ * Use removeHiddenNodes() on the returned roots to filter by level in the display layer.
+ *
* Returns:
* - roots: Array of root TreeNodes (single TRACE root for traditional, multiple obs roots for events-based)
* - nodeMap: Map<id, TreeNode> for O(1) lookup
* - searchItems: Flattened list for search/virtualized rendering
- * - hiddenObservationsCount: Number filtered by minLevel
*/
export function buildTraceUiData(
trace: TraceType,
observations: ObservationReturnType[],
- minLevel?: ObservationLevelType,
): {
roots: TreeNode[];
- hiddenObservationsCount: number;
searchItems: TraceSearchListItem[];
nodeMap: Map<string, TreeNode>;
} {
- const { roots, hiddenObservationsCount, nodeMap } = buildTraceTree(
- trace,
- observations,
- minLevel,
- );
+ const { roots, nodeMap } = buildTraceTree(trace, observations);
// Handle empty roots case
if (roots.length === 0) {
- return { roots, hiddenObservationsCount, searchItems: [], nodeMap };
+ return { roots, searchItems: [], nodeMap };
}
// TODO: Extract aggregation logic to shared utility - duplicated in TraceTree.tsx and TraceTimeline/index.tsx
@@ -513,5 +495,52 @@ export function buildTraceUiData(
}
}
- return { roots, hiddenObservationsCount, searchItems, nodeMap };
+ return { roots, searchItems, nodeMap };
+}
+
+/**
+ * Removes nodes matching a predicate from a tree, promoting their children
+ * to the parent level. Useful for hiding observations by level (e.g. DEBUG)
+ * without breaking the tree structure.
+ *
+ * This is applied as a display-layer post-processing step, keeping the
+ * tree-building data layer clean and free of level-filtering concerns.
+ *
+ * Implemented iteratively to avoid call stack overflows on deeply nested traces.
+ * Uses a single-pass stack algorithm to keep complexity linear in node count.
+ */
+export function removeHiddenNodes(
+ nodes: TreeNode[],
+ isHidden: (node: TreeNode) => boolean,
+): TreeNode[] {
+ if (nodes.length === 0) return [];
+
+ const result: TreeNode[] = [];
+
+ // Each stack entry carries the output array where this node should be attached.
+ // Hidden nodes are skipped and their children are redirected to the same target.
+ const stack: Array<{ node: TreeNode; target: TreeNode[] }> = [];
+ for (let i = nodes.length - 1; i >= 0; i--) {
+ stack.push({ node: nodes[i]!, target: result });
+ }
+
+ while (stack.length > 0) {
+ const { node, target } = stack.pop()!;
+
+ if (isHidden(node)) {
+ for (let i = node.children.length - 1; i >= 0; i--) {
+ stack.push({ node: node.children[i]!, target });
+ }
+ continue;
+ }
+
+ const clone: TreeNode = { ...node, children: [] };
+ target.push(clone);
+
+ for (let i = node.children.length - 1; i >= 0; i--) {
+ stack.push({ node: node.children[i]!, target: clone.children });
+ }
+ }
+
+ return result;
}