πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(trace): show subtree wall-clock duration on observations (LFE-10475) (#14537)
Nikita Kabardinefdde0ffa2d4
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.mdindex eb100e3f35..cdb978fc09 100644--- a/.agents/skills/seed-test-data/SKILL.md+++ b/.agents/skills/seed-test-data/SKILL.md@@ -29,18 +29,19 @@ this.## Need β command-| I need... | Command |-| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| A very complex observation tree (v3) | `pnpm run seed -- trace-tree --observations 5000 --depth 12 --breadth 500` |-| The same tree readable in the v4 events UI | add `--v4` (writes `events_full`; `events_core` fills via MV) |-| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` |-| Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` |-| Scores with spaces in the name (filter/grammar testing) | `pnpm run seed -- scored-traces --traces 24 --v4` |-| Varied human-annotation queues (annotate UI / keyboard testing) | `pnpm run seed -- annotation-queue --core-items 12` (creates a "core types" queue covering every score-field render path + an "edge cases" queue with archived/stale/partial scores and observation/session/deleted/completed items) |-| Huge/malformed/unicode payloads | `pnpm run seed -- trace-tree --payload-bytes 1000000 --payload-style malformed` (styles: json, text, malformed, unicode, bignum) |-| Big integers beyond 2^53-1 (number-precision testing) | `pnpm run seed -- trace-tree --observations 1 --payload-style bignum` |-| See all scenarios and flags | `pnpm run seed -- list --json` |-| Predict without writing | add `--dry-run` |+| I need... | Command |+| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| A very complex observation tree (v3) | `pnpm run seed -- trace-tree --observations 5000 --depth 12 --breadth 500` |+| The same tree readable in the v4 events UI | add `--v4` (writes `events_full`; `events_core` fills via MV) |+| Async parents whose subtree outlives their own span (subtree wall-clock duration badge) | add `--async-parents` to `trace-tree` (root + hub end immediately while children keep running) |+| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` |+| Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` |+| Scores with spaces in the name (filter/grammar testing) | `pnpm run seed -- scored-traces --traces 24 --v4` |+| Varied human-annotation queues (annotate UI / keyboard testing) | `pnpm run seed -- annotation-queue --core-items 12` (creates a "core types" queue covering every score-field render path + an "edge cases" queue with archived/stale/partial scores and observation/session/deleted/completed items) |+| Huge/malformed/unicode payloads | `pnpm run seed -- trace-tree --payload-bytes 1000000 --payload-style malformed` (styles: json, text, malformed, unicode, bignum) |+| Big integers beyond 2^53-1 (number-precision testing) | `pnpm run seed -- trace-tree --observations 1 --payload-style bignum` |+| See all scenarios and flags | `pnpm run seed -- list --json` |+| Predict without writing | add `--dry-run` |## Contractdiff --git a/packages/shared/scripts/seeder/scenarios/trace-tree.ts b/packages/shared/scripts/seeder/scenarios/trace-tree.tsindex 5cf977dd01..2ccd1279e7 100644--- a/packages/shared/scripts/seeder/scenarios/trace-tree.ts+++ b/packages/shared/scripts/seeder/scenarios/trace-tree.ts@@ -122,6 +122,7 @@ const run = async (const payloadBytes = params["payload-bytes"] as number;const payloadStyle = params["payload-style"] as PayloadStyle;const withV4 = params["v4"] as boolean;+ const asyncParents = params["async-parents"] as boolean;if (!PAYLOAD_STYLES.includes(payloadStyle)) {throw new SeedError(@@ -259,10 +260,27 @@ const run = async (}}+ // LFE-10475 demo (opt-in via --async-parents): the root dispatcher and the+ // hub node behave like fire-and-forget async work β their OWN span ends almost+ // immediately while their subtree keeps running. We only shorten the written+ // end_time of these nodes (subtree offsets and ancestors are untouched), so+ // their own-span duration badly understates the subtree's wall-clock duration.+ // This is exactly the shape that surfaces the subtree-duration badge.+ const ASYNC_OWN_DURATION_MS = 40;+ const hubIndex = Math.min(2, depth - 1);+ const asyncParentIndexes = asyncParents+ ? new Set<number>([0, hubIndex])+ : new Set<number>();+let retryNodeUsed = false;const observations: ObservationRecordInsertType[] = shape.map((node) => {const isGeneration = node.kind === "GENERATION";const startTime = traceTimestamp + startOffsets[node.index];+ // Async parents (opt-in): own span ends right after start, while the+ // subtree keeps running off the (untouched) child offsets.+ const endOffset = asyncParentIndexes.has(node.index)+ ? startOffsets[node.index] + ASYNC_OWN_DURATION_MS+ : endOffsets[node.index];const missingEndTime = node.index > 0 && node.index % 19 === 0;const isError = node.index % 29 === 7;const isFailedToolRetryPair =@@ -313,7 +331,7 @@ const run = async (: `${ctx.idPrefix}-obs-${node.parentIndex}`,name,start_time: startTime,- end_time: missingEndTime ? null : traceTimestamp + endOffsets[node.index],+ end_time: missingEndTime ? null : traceTimestamp + endOffset,completion_start_time: isGeneration ? startTime + rng.int(80, 400) : null,level:isError || isFailedToolRetryPair@@ -608,6 +626,13 @@ export const traceTreeScenario: ScenarioDefinition = {default: false,description: "also mirror the tree into v4 events_full/events_core",},+ {+ flag: "async-parents",+ type: "boolean",+ default: false,+ description:+ "root + hub nodes end immediately while their subtree keeps running (async/fire-and-forget shape; surfaces the subtree wall-clock duration badge)",+ },],run,};diff --git a/web/src/components/trace/components/SpanContent.tsx b/web/src/components/trace/components/SpanContent.tsxindex b3fe069b3e..ea8f4a70d6 100644--- a/web/src/components/trace/components/SpanContent.tsx+++ b/web/src/components/trace/components/SpanContent.tsx@@ -24,7 +24,10 @@ import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";import { cn } from "@/src/utils/tailwind";import { formatIntervalSeconds } from "@/src/utils/dates";import { usdFormatter, formatTokenCounts } from "@/src/utils/numbers";-import { heatMapTextColor } from "@/src/components/trace/lib/helpers";+import {+ heatMapTextColor,+ getSubtreeDurationOverflowMs,+} from "@/src/components/trace/lib/helpers";import { useViewPreferences } from "../contexts/ViewPreferencesContext";import { useTraceData } from "../contexts/TraceDataContext";import type Decimal from "decimal.js";@@ -70,6 +73,18 @@ export function SpanContent({const shouldRenderDuration =showDuration && Boolean(duration || node.latency);+ // Wall-clock duration of the whole subtree, surfaced as a second badge beside+ // the own-span badge when async descendants outlive the parent span (so the+ // own-span duration above understates the real elapsed time). See LFE-10475.+ // It only complements the own-span badge β never renders alone β so a node+ // with no own-span duration (e.g. an in-flight/crashed observation with no+ // endTime) shows nothing rather than an orphaned "β" with no anchor.+ const subtreeWallClockOverflowMs = showDuration+ ? getSubtreeDurationOverflowMs(duration, node.subtreeWallClockDurationMs)+ : null;+ const shouldRenderSubtreeDuration =+ shouldRenderDuration && subtreeWallClockOverflowMs != null;+const shouldRenderCostTokens =showCostTokens &&Boolean(@@ -143,13 +158,13 @@ export function SpanContent({{/* Metrics row */}{shouldRenderAnyMetrics && (<div className="flex flex-wrap gap-x-2">- {/* Duration */}+ {/* Duration (own span) */}{shouldRenderDuration && (duration || node.latency) ? (<spantitle={- node.children.length > 0 || node.type === "TRACE"- ? "Aggregated duration of all child observations"- : undefined+ node.type === "TRACE"+ ? "Total trace duration"+ : "Own span duration"}className={cn("text-muted-foreground text-xs",@@ -168,6 +183,17 @@ export function SpanContent({</span>) : null}+ {/* Subtree wall-clock duration β async descendants outlive the parent span */}+ {shouldRenderSubtreeDuration ? (+ <span+ title="Subtree wall-clock duration (first start β last end)"+ className="text-muted-foreground text-xs"+ >+ {"β "}+ {formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}+ </span>+ ) : null}+{/* Token counts */}{shouldRenderCostTokens &&(node.inputUsage || node.outputUsage || node.totalUsage) ? (diff --git a/web/src/components/trace/components/TraceTimeline/TimelineBar.tsx b/web/src/components/trace/components/TraceTimeline/TimelineBar.tsxindex 9b5f2b6a40..32543c877d 100644--- a/web/src/components/trace/components/TraceTimeline/TimelineBar.tsx+++ b/web/src/components/trace/components/TraceTimeline/TimelineBar.tsx@@ -10,9 +10,15 @@ import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import { formatIntervalSeconds } from "@/src/utils/dates";import { usdFormatter } from "@/src/utils/numbers";-import { heatMapTextColor } from "@/src/components/trace/lib/helpers";+import {+ heatMapTextColor,+ getSubtreeDurationOverflowMs,+} from "@/src/components/trace/lib/helpers";import { isPresent } from "@langfuse/shared";+const SUBTREE_DURATION_TITLE =+ "Subtree wall-clock duration (first start β last end)";+export function TimelineBar({node,metrics,@@ -33,6 +39,19 @@ export function TimelineBar({const duration = latency ? latency * 1000 : undefined;const hasChildren = node.children.length > 0;+ // Wall-clock duration of the whole subtree, surfaced only when async+ // descendants outlive this node's own span (LFE-10475). Own-span basis+ // mirrors SpanContent: fall back to node.latency when there's no endTime+ // (e.g. the synthetic v4 trace-root span) so the tree and timeline agree.+ const ownDurationMs =+ duration ?? (node.latency ? node.latency * 1000 : undefined);+ const subtreeWallClockOverflowMs = showDuration+ ? getSubtreeDurationOverflowMs(+ ownDurationMs,+ node.subtreeWallClockDurationMs,+ )+ : null;+// Render split bar for streaming LLMs (first token time)if (firstTokenTimeOffset) {const firstTokenWidth = firstTokenTimeOffset - startOffset;@@ -79,22 +98,31 @@ export function TimelineBar({{showComments && commentCount ? (<CommentCountIcon count={commentCount} />) : null}- {showDuration && isPresent(latency) && (+ {showDuration && isPresent(ownDurationMs) && (<spanclassName={cn("text-muted-foreground text-xs",parentTotalDuration &&colorCodeMetrics &&- duration &&heatMapTextColor({max: parentTotalDuration,- value: duration,+ value: ownDurationMs,}),)}>- {formatIntervalSeconds(latency)}+ {formatIntervalSeconds(ownDurationMs / 1000)}</span>)}+ {isPresent(ownDurationMs) &&+ subtreeWallClockOverflowMs != null && (+ <span+ title={SUBTREE_DURATION_TITLE}+ className="text-muted-foreground text-xs whitespace-nowrap"+ >+ {"β "}+ {formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}+ </span>+ )}{showCostTokens && node.totalCost && (<spanclassName={cn(@@ -153,20 +181,28 @@ export function TimelineBar({{showComments && commentCount ? (<CommentCountIcon count={commentCount} />) : null}- {showDuration && isPresent(latency) && (+ {showDuration && isPresent(ownDurationMs) && (<spanclassName={cn("text-muted-foreground text-xs",parentTotalDuration &&colorCodeMetrics &&- duration &&heatMapTextColor({max: parentTotalDuration,- value: duration,+ value: ownDurationMs,}),)}>- {formatIntervalSeconds(latency)}+ {formatIntervalSeconds(ownDurationMs / 1000)}+ </span>+ )}+ {isPresent(ownDurationMs) && subtreeWallClockOverflowMs != null && (+ <span+ title={SUBTREE_DURATION_TITLE}+ className="text-muted-foreground text-xs whitespace-nowrap"+ >+ {"β "}+ {formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}</span>)}{showCostTokens && node.totalCost && (diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.tsindex 114adc3717..a07de65b34 100644--- a/web/src/components/trace/lib/helpers.ts+++ b/web/src/components/trace/lib/helpers.ts@@ -1,6 +1,7 @@import { type NestedObservation } from "@/src/utils/types";import { type TreeNode, type TraceSearchListItem } from "./types";import { type ObservationReturnType } from "@/src/server/api/routers/traces";+import { formatIntervalSeconds } from "@/src/utils/dates";import Decimal from "decimal.js";import {type ObservationLevelType,@@ -184,6 +185,41 @@ export const heatMapTextColor = (p: {return "";};+/**+ * Decides whether a node's subtree wall-clock duration should be shown as a+ * distinct badge alongside its own-span duration (LFE-10475), and returns that+ * duration (ms) when it should.+ *+ * Async children can outlive their parent span, so a parent's own+ * (endTime β startTime) can understate the real elapsed time of its subtree.+ * The subtree always contains the own span, so it can only be β₯ own. We surface+ * the badge on any difference that is visible at the rendered precision β i.e.+ * when the subtree would display a different value than the own span. This shows+ * every difference the user can actually see (down to the formatter's 0.01s+ * resolution) while never rendering two identical-looking numbers. Users who+ * don't want durations at all can hide them via the "show duration" toggle.+ *+ * A missing own-span duration is treated as 0 so that nodes without a recorded+ * end still surface a meaningful subtree duration.+ *+ * @param ownDurationMs - the node's own span duration (endTime β startTime), ms+ * @param subtreeWallClockDurationMs - max(end) β min(start) across the subtree, ms+ */+export function getSubtreeDurationOverflowMs(+ ownDurationMs: number | undefined | null,+ subtreeWallClockDurationMs: number | undefined | null,+): number | null {+ if (subtreeWallClockDurationMs == null) return null;+ const own = ownDurationMs ?? 0;+ if (subtreeWallClockDurationMs <= own) return null;+ if (+ formatIntervalSeconds(subtreeWallClockDurationMs / 1000) ===+ formatIntervalSeconds(own / 1000)+ )+ return null;+ return subtreeWallClockDurationMs;+}+// Helper function to unnest observations for cost calculationexport const unnestObservation = (nestedObservation: NestedObservation) => {const unnestedObservations = [];diff --git a/web/src/components/trace/lib/tree-building.clienttest.ts b/web/src/components/trace/lib/tree-building.clienttest.tsindex a978cb5846..528b50a21b 100644--- a/web/src/components/trace/lib/tree-building.clienttest.ts+++ b/web/src/components/trace/lib/tree-building.clienttest.ts@@ -9,6 +9,7 @@ import {removeHiddenNodes,getObservationLevels,} from "./tree-building";+import { getSubtreeDurationOverflowMs } from "./helpers";import { type TreeNode } from "./types";import { type ObservationReturnType } from "@/src/server/api/routers/traces";import Decimal from "decimal.js";@@ -802,6 +803,216 @@ describe("buildTraceUiData", () => {});});+ describe("Subtree Wall-Clock Duration Aggregation", () => {+ it("leaf node subtree duration equals its own span", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "leaf",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const leaf = result.nodeMap.get("leaf");+ expect(leaf?.subtreeWallClockDurationMs).toBe(1000);+ });++ it("async child outliving parent: subtree spans last end β first start", () => {+ // Parent span ends after 40ms, but kicks off an async child that finishes+ // ~12s later. The parent's own duration (40ms) badly understates elapsed time.+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:00.040Z"),+ }),+ createMockObservation({+ id: "async-child",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:00.030Z"),+ endTime: new Date("2024-01-01T00:00:12.030Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const parent = result.nodeMap.get("parent");+ const child = result.nodeMap.get("async-child");+ // Own span = 40ms, subtree wall-clock = 12.030s β 0 = 12030ms+ expect(parent?.subtreeWallClockDurationMs).toBe(12030);+ // Child is a leaf: subtree == own span (12000ms)+ expect(child?.subtreeWallClockDurationMs).toBe(12000);+ });++ it("aggregates wall-clock through deep nesting (3 levels)", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "grandparent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:00.100Z"),+ }),+ createMockObservation({+ id: "parent",+ parentObservationId: "grandparent",+ startTime: new Date("2024-01-01T00:00:00.050Z"),+ endTime: new Date("2024-01-01T00:00:00.200Z"),+ }),+ createMockObservation({+ id: "child",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:00.150Z"),+ endTime: new Date("2024-01-01T00:00:05.000Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(result.nodeMap.get("child")?.subtreeWallClockDurationMs).toBe(+ 4850,+ ); // 5.000 β 0.150+ expect(result.nodeMap.get("parent")?.subtreeWallClockDurationMs).toBe(+ 4950,+ ); // 5.000 β 0.050+ expect(+ result.nodeMap.get("grandparent")?.subtreeWallClockDurationMs,+ ).toBe(5000); // 5.000 β 0.000+ });++ it("spans the latest-ending sibling across multiple children", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:00.500Z"),+ }),+ createMockObservation({+ id: "child-a",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:00.100Z"),+ endTime: new Date("2024-01-01T00:00:03.000Z"),+ }),+ createMockObservation({+ id: "child-b",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:00.200Z"),+ endTime: new Date("2024-01-01T00:00:08.000Z"), // latest end+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // 8.000 (latest child end) β 0.000 (parent start) = 8000ms+ expect(result.nodeMap.get("parent")?.subtreeWallClockDurationMs).toBe(+ 8000,+ );+ });++ it("synchronous subtree contained within parent span equals own span", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:10.000Z"),+ }),+ createMockObservation({+ id: "child",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ endTime: new Date("2024-01-01T00:00:09.000Z"), // fully inside parent+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Subtree wall-clock equals the parent's own span (10000ms)+ expect(result.nodeMap.get("parent")?.subtreeWallClockDurationMs).toBe(+ 10000,+ );+ });++ it("falls back to start time when a node has no endTime", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: null, // no recorded end+ }),+ createMockObservation({+ id: "child",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:00.100Z"),+ endTime: new Date("2024-01-01T00:00:05.100Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Parent end falls back to its start (0); child extends to 5.100s β 5100ms+ expect(result.nodeMap.get("parent")?.subtreeWallClockDurationMs).toBe(+ 5100,+ );+ });++ it("leaf with no endTime has zero subtree duration", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "leaf",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(result.nodeMap.get("leaf")?.subtreeWallClockDurationMs).toBe(0);+ });++ it("computes subtree duration for events-based root observations", () => {+ const trace = createMockTrace({+ id: "trace-1",+ rootObservationType: "SPAN",+ rootObservationId: "root-obs",+ latency: 6,+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "root-obs",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:00.040Z"), // short own span+ }),+ createMockObservation({+ id: "async-child",+ parentObservationId: "root-obs",+ startTime: new Date("2024-01-01T00:00:00.030Z"),+ endTime: new Date("2024-01-01T00:00:06.000Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(result.roots[0].id).toBe("root-obs");+ // Own span 40ms but subtree extends to 6s+ expect(result.roots[0].subtreeWallClockDurationMs).toBe(6000);+ });+ });+describe.skip("Performance Tests", () => {// Helper to generate observations at scaleconst generateObservations = (@@ -1931,3 +2142,43 @@ describe("getObservationLevels", () => {expect(levels).toEqual(expected);});});++describe("getSubtreeDurationOverflowMs", () => {+ it("returns null when there is no subtree duration", () => {+ expect(getSubtreeDurationOverflowMs(1000, undefined)).toBeNull();+ expect(getSubtreeDurationOverflowMs(1000, null)).toBeNull();+ });++ it("does not flag leaf nodes whose subtree equals their own span", () => {+ expect(getSubtreeDurationOverflowMs(1000, 1000)).toBeNull();+ });++ it("returns null when the difference is below the rendered 0.01s precision", () => {+ // 1.000s vs 1.004s both render as "1.00s" β no visible difference+ expect(getSubtreeDurationOverflowMs(1000, 1004)).toBeNull();+ });++ it("returns the subtree duration on any difference visible at 0.01s precision", () => {+ // 10ms is visible: "1.00s" vs "1.01s"+ expect(getSubtreeDurationOverflowMs(1000, 1010)).toBe(1010);+ // small absolute diffs that the old 250ms/10% margin would have hidden+ expect(getSubtreeDurationOverflowMs(1000, 1200)).toBe(1200);+ expect(getSubtreeDurationOverflowMs(10000, 10300)).toBe(10300);+ // the async-parent case: tiny own span, large subtree+ expect(getSubtreeDurationOverflowMs(40, 12030)).toBe(12030);+ });++ it("treats a missing own-span duration as zero", () => {+ // own = 0 β "0.00s"; any visibly non-zero subtree is shown+ expect(getSubtreeDurationOverflowMs(undefined, 300)).toBe(300);+ // sub-precision subtree (< 0.005s) rounds to "0.00s" β hidden+ expect(getSubtreeDurationOverflowMs(undefined, 4)).toBeNull();+ });++ it("compares at the formatter's coarser resolution for minute-scale durations", () => {+ // both render as "1m 04s" (sub-second diff invisible at this scale)+ expect(getSubtreeDurationOverflowMs(64_000, 64_400)).toBeNull();+ // a full second is visible: "1m 04s" vs "1m 05s"+ expect(getSubtreeDurationOverflowMs(64_000, 65_000)).toBe(65_000);+ });+});diff --git a/web/src/components/trace/lib/tree-building.ts b/web/src/components/trace/lib/tree-building.tsindex 4a5975e952..8317ae9667 100644--- a/web/src/components/trace/lib/tree-building.ts+++ b/web/src/components/trace/lib/tree-building.ts@@ -51,6 +51,10 @@ interface ProcessingNode {inDegree: number; // Number of unprocessed children (for topological sort)depth: number; // Tree depth (calculated during graph building)treeNode?: TreeNode; // Set when node is processed+ // Earliest start / latest end (epoch ms) across this node and all descendants.+ // Tracked bottom-up to derive subtreeWallClockDurationMs (mirrors cost aggregation).+ subtreeMinStartMs?: number;+ subtreeMaxEndMs?: number;}/**@@ -240,6 +244,30 @@ function buildTreeNodesBottomUp(? nodeCost.plus(childrenTotalCost): nodeCost || childrenTotalCost;+ // Aggregate subtree wall-clock bounds bottom-up: earliest start and latest+ // end across this node and every descendant. Children are already processed,+ // so their bounds are available on the ProcessingNode registry.+ // A missing endTime contributes only its start (zero-length interval).+ let subtreeMinStartMs = obs.startTime.getTime();+ let subtreeMaxEndMs = obs.endTime+ ? obs.endTime.getTime()+ : obs.startTime.getTime();+ for (const childId of currentNode.childrenIds) {+ const childNode = nodeRegistry.get(childId);+ if (childNode?.subtreeMinStartMs != null) {+ subtreeMinStartMs = Math.min(+ subtreeMinStartMs,+ childNode.subtreeMinStartMs,+ );+ }+ if (childNode?.subtreeMaxEndMs != null) {+ subtreeMaxEndMs = Math.max(subtreeMaxEndMs, childNode.subtreeMaxEndMs);+ }+ }+ currentNode.subtreeMinStartMs = subtreeMinStartMs;+ currentNode.subtreeMaxEndMs = subtreeMaxEndMs;+ const subtreeWallClockDurationMs = subtreeMaxEndMs - subtreeMinStartMs;+// Calculate temporal and structural propertiesconst startTimeSinceTrace =obs.startTime.getTime() - traceStartTime.getTime();@@ -283,6 +311,7 @@ function buildTreeNodesBottomUp(parentObservationId: obs.parentObservationId,traceId: obs.traceId,totalCost,+ subtreeWallClockDurationMs,startTimeSinceTrace,startTimeSinceParentStart,depth,diff --git a/web/src/components/trace/lib/types.ts b/web/src/components/trace/lib/types.tsindex 6aeb35ba07..48acb3b65f 100644--- a/web/src/components/trace/lib/types.ts+++ b/web/src/components/trace/lib/types.ts@@ -33,6 +33,13 @@ export type TreeNode = {totalCost?: Decimal;// Duration in seconds. Set on TRACE wrapper nodes (v3) or root observation nodes (v4 events-based traces).latency?: number;+ // Wall-clock duration of this node's subtree, in milliseconds:+ // max(end time) β min(start time) across this node and ALL its descendants.+ // Calculated bottom-up during tree construction (mirrors totalCost). Lets the UI+ // surface async children that outlive their parent span, whose own+ // (endTime β startTime) badge would otherwise understate the real elapsed time.+ // Undefined on TRACE wrapper nodes (which already render trace-level latency).+ subtreeWallClockDurationMs?: number;// Observation-specific properties (when type !== 'TRACE')parentObservationId?: string | null;traceId?: string;