🪢 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
fix(trace-timeline): anchor gantt origin to earliest start; stop truncating Timeline label (LFE-10496) (#14539)
Nikita Kabardin331116146357
diff --git a/web/src/components/trace/components/TraceTimeline/index.tsx b/web/src/components/trace/components/TraceTimeline/index.tsxindex 7a7c23d504..f17a23509e 100644--- a/web/src/components/trace/components/TraceTimeline/index.tsx+++ b/web/src/components/trace/components/TraceTimeline/index.tsx@@ -10,7 +10,12 @@ import { useSelection } from "../../contexts/SelectionContext";import { useViewPreferences } from "../../contexts/ViewPreferencesContext";import { useHandlePrefetchObservation } from "../../hooks/useHandlePrefetchObservation";import { flattenTreeWithTimelineMetrics } from "./timeline-flattening";-import { calculateStepSize, SCALE_WIDTH } from "./timeline-calculations";+import {+ calculateStepSize,+ calculateTraceDuration,+ findEarliestStartTime,+ SCALE_WIDTH,+} from "./timeline-calculations";import { TimelineScale } from "./TimelineScale";import { TimelineRow } from "./TimelineRow";@@ -30,19 +35,26 @@ export function TraceTimeline() {const timeIndexRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);- // TODO: Extract aggregation logic to shared utility - duplicated in tree-building.ts and TraceTree.tsx- // Calculate trace duration from roots (max latency across all roots)- const traceDuration = useMemo(() => {- if (roots.length === 0) return 0;- return Math.max(...roots.map((r) => r.latency ?? 0));- }, [roots]);-+ // Timeline origin (the 0s mark): the earliest start time across the WHOLE+ // tree, not just the roots. A child can start before its root (the TRACE+ // wrapper's start is the trace timestamp, which may be later than the first+ // observation), so anchoring to roots alone misplaces the origin past early+ // children. See findEarliestStartTime.const traceStartTime = useMemo(() => {- if (roots.length === 0) return new Date();- // Use earliest start time among roots- return new Date(Math.min(...roots.map((r) => r.startTime.getTime())));+ return findEarliestStartTime(roots) ?? new Date();}, [roots]);+ // TODO: Extract aggregation logic to shared utility - duplicated in tree-building.ts and TraceTree.tsx+ // Total span of the scale, in seconds, measured from the timeline origin+ // (earliest start) to the latest end across the tree, so every bar fits+ // within the scale even when the origin sits before a root's start. The+ // latency fallback (for traces without end times) is anchored to the origin,+ // so a root that starts after an earlier child still fits. See+ // calculateTraceDuration.+ const traceDuration = useMemo(() => {+ return calculateTraceDuration(roots, traceStartTime);+ }, [roots, traceStartTime]);+// Calculate step size for time axisconst stepSize = useMemo(() => {return calculateStepSize(traceDuration, SCALE_WIDTH);diff --git a/web/src/components/trace/components/TraceTimeline/timeline-calculations.clienttest.ts b/web/src/components/trace/components/TraceTimeline/timeline-calculations.clienttest.tsindex 92f16cfca2..7212ec5bf7 100644--- a/web/src/components/trace/components/TraceTimeline/timeline-calculations.clienttest.ts+++ b/web/src/components/trace/components/TraceTimeline/timeline-calculations.clienttest.ts@@ -4,10 +4,40 @@ import {calculateTimelineOffset,calculateTimelineWidth,calculateStepSize,+ calculateTraceDuration,+ findEarliestStartTime,getPredefinedStepSizes,SCALE_WIDTH,PREDEFINED_STEP_SIZES,} from "./timeline-calculations";+import { type TreeNode } from "../../lib/types";++// Minimal TreeNode factory for origin/duration tests (only the fields the+// helpers read). `opts` lets a test set endTime / latency / children.+function makeNode(+ id: string,+ startTime: string,+ opts: {+ children?: TreeNode[];+ endTime?: string | null;+ latency?: number;+ } = {},+): TreeNode {+ const { children = [], endTime = null, latency } = opts;+ return {+ id,+ type: "SPAN",+ name: id,+ startTime: new Date(startTime),+ endTime: endTime === null ? null : new Date(endTime),+ latency,+ children,+ startTimeSinceTrace: 0,+ startTimeSinceParentStart: null,+ depth: 0,+ childrenDepth: 0,+ } as TreeNode;+}describe("timeline-calculations", () => {describe("calculateTimelineOffset", () => {@@ -264,4 +294,143 @@ describe("timeline-calculations", () => {expect(width).toBe(SCALE_WIDTH * 2); // Just calculates proportionally});});++ describe("findEarliestStartTime (timeline origin)", () => {+ it("returns null for an empty tree", () => {+ expect(findEarliestStartTime([])).toBeNull();+ });++ it("returns the root start time when the root starts first", () => {+ const root = makeNode("root", "2024-01-01T00:00:00Z", {+ children: [makeNode("child", "2024-01-01T00:00:02Z")],+ });+ expect(findEarliestStartTime([root])?.toISOString()).toBe(+ "2024-01-01T00:00:00.000Z",+ );+ });++ it("anchors to a child that starts BEFORE the root (the origin bug)", () => {+ // The root (TRACE wrapper) starts at the trace timestamp, but an early+ // observation began before it. The origin must be the child's start.+ const root = makeNode("root", "2024-01-01T00:00:05Z", {+ children: [+ makeNode("early-child", "2024-01-01T00:00:01Z"),+ makeNode("late-child", "2024-01-01T00:00:07Z"),+ ],+ });++ const origin = findEarliestStartTime([root]);+ expect(origin?.toISOString()).toBe("2024-01-01T00:00:01.000Z");++ // And the offset of that early child against the corrected origin is 0,+ // not negative as it would be when anchoring to the root.+ const offset = calculateTimelineOffset(+ new Date("2024-01-01T00:00:01Z"),+ origin!,+ 10,+ );+ expect(offset).toBe(0);+ });++ it("descends into deeply nested children to find the minimum", () => {+ const root = makeNode("root", "2024-01-01T00:00:10Z", {+ children: [+ makeNode("a", "2024-01-01T00:00:08Z", {+ children: [+ makeNode("b", "2024-01-01T00:00:03Z", {+ children: [makeNode("c", "2024-01-01T00:00:02Z")],+ }),+ ],+ }),+ ],+ });+ expect(findEarliestStartTime([root])?.toISOString()).toBe(+ "2024-01-01T00:00:02.000Z",+ );+ });++ it("considers all roots when there are multiple", () => {+ const roots = [+ makeNode("r1", "2024-01-01T00:00:04Z"),+ makeNode("r2", "2024-01-01T00:00:01Z"),+ makeNode("r3", "2024-01-01T00:00:06Z"),+ ];+ expect(findEarliestStartTime(roots)?.toISOString()).toBe(+ "2024-01-01T00:00:01.000Z",+ );+ });+ });++ describe("calculateTraceDuration (timeline scale span)", () => {+ it("returns 0 for an empty tree", () => {+ expect(calculateTraceDuration([], new Date())).toBe(0);+ });++ it("spans from the origin to the latest end when end times exist", () => {+ // Root T0..T+10, child T+2..T+12 → latest end is T+12.+ const origin = new Date("2024-01-01T00:00:00Z");+ const root = makeNode("root", "2024-01-01T00:00:00Z", {+ endTime: "2024-01-01T00:00:10Z",+ children: [+ makeNode("child", "2024-01-01T00:00:02Z", {+ endTime: "2024-01-01T00:00:12Z",+ }),+ ],+ });+ expect(calculateTraceDuration([root], origin)).toBe(12);+ });++ it("measures the latest end relative to an origin BEFORE the root start", () => {+ // Early child anchors the origin at T+0; root runs T+5..T+9. The span+ // must reach the child's end (T+11), not just the root's end.+ const origin = new Date("2024-01-01T00:00:00Z");+ const root = makeNode("root", "2024-01-01T00:00:05Z", {+ endTime: "2024-01-01T00:00:09Z",+ children: [+ makeNode("early-child", "2024-01-01T00:00:00Z", {+ endTime: "2024-01-01T00:00:11Z",+ }),+ ],+ });+ expect(calculateTraceDuration([root], origin)).toBe(11);+ });++ it("offset-aware latency fallback covers a root that starts after the origin (the P2 bug)", () => {+ // No node has an end time, so `endTime ?? startTime` collapses+ // spanFromEnds to the start gap only. An early child anchors the origin+ // at T+0; the root starts at T+3 with latency 10. The root's bar reaches+ // T+13, so the scale MUST be 13 — not the naive max(spanFromEnds=3,+ // latency=10) = 10, which would let the bar overrun the axis.+ const origin = new Date("2024-01-01T00:00:00Z");+ const root = makeNode("root", "2024-01-01T00:00:03Z", {+ latency: 10,+ children: [makeNode("early-child", "2024-01-01T00:00:00Z")],+ });++ const span = calculateTraceDuration([root], origin);+ expect(span).toBe(13);++ // The root bar (offset from origin + width) fits exactly within the axis+ // (modulo floating-point rounding). With the pre-fix scale of 10 it would+ // have reached 1.3 * SCALE_WIDTH and overrun the last tick.+ const offset = calculateTimelineOffset(root.startTime, origin, span);+ const width = calculateTimelineWidth(root.latency!, span);+ expect(offset + width).toBeCloseTo(SCALE_WIDTH, 6);+ });++ it("uses the larger of end-based span and offset-aware latency", () => {+ // Root starts at the origin with latency 10 but a child ends at T+12 →+ // the end-based span (12) wins over the latency span (10).+ const origin = new Date("2024-01-01T00:00:00Z");+ const root = makeNode("root", "2024-01-01T00:00:00Z", {+ latency: 10,+ children: [+ makeNode("child", "2024-01-01T00:00:02Z", {+ endTime: "2024-01-01T00:00:12Z",+ }),+ ],+ });+ expect(calculateTraceDuration([root], origin)).toBe(12);+ });+ });});diff --git a/web/src/components/trace/components/TraceTimeline/timeline-calculations.ts b/web/src/components/trace/components/TraceTimeline/timeline-calculations.tsindex 75066ca3a7..5ff332c460 100644--- a/web/src/components/trace/components/TraceTimeline/timeline-calculations.ts+++ b/web/src/components/trace/components/TraceTimeline/timeline-calculations.ts@@ -3,10 +3,94 @@* These functions handle all timeline positioning and sizing logic*/+import { type TreeNode } from "../../lib/types";+// Fixed widths for timeline stylingexport const SCALE_WIDTH = 900;export const STEP_SIZE = 100;+/**+ * Find the earliest start time across the whole tree (roots + all descendants).+ *+ * This is the timeline origin (the 0s mark). It must be the minimum start time+ * over the entire tree, not just the roots: a child observation can start+ * before its root (the TRACE wrapper's start time is the trace's own timestamp,+ * which may be later than the first observation). Anchoring the origin to the+ * roots alone pushes the 0s mark past such early children, giving them negative+ * offsets and misaligning the whole gantt.+ *+ * @param roots - Root nodes of the trace tree+ * @returns Earliest start time across the tree, or `null` when there are no nodes+ */+export function findEarliestStartTime(roots: TreeNode[]): Date | null {+ if (roots.length === 0) return null;++ let earliest = Infinity;++ // Iterative DFS to avoid stack overflow on deep trees.+ const stack: TreeNode[] = [...roots];+ while (stack.length > 0) {+ const node = stack.pop()!;+ const start = node.startTime.getTime();+ if (start < earliest) earliest = start;+ for (const child of node.children) {+ stack.push(child);+ }+ }++ return new Date(earliest);+}++/**+ * Total span of the timeline scale, in seconds.+ *+ * Measured from the timeline origin (the earliest start across the whole tree,+ * see findEarliestStartTime) to the latest end across the tree, so every bar+ * fits within the scale even when the origin sits before a root's start.+ *+ * When end times are unavailable, `endTime ?? startTime` collapses+ * `spanFromEnds` to the earliest-to-latest start gap. We therefore also+ * consider each root's latency-based span, but measured FROM THE ORIGIN: a+ * root's bar spans `(root.startTime − origin) + latency`, not just `latency`.+ * Anchoring the latency fallback to the origin keeps the root's bar inside the+ * axis when it starts after an earlier child (otherwise the bar overruns the+ * last tick by the dropped `(root.startTime − origin)` offset).+ *+ * @param roots - Root nodes of the trace tree+ * @param origin - Timeline origin (earliest start across the tree)+ * @returns Total scale span in seconds (0 when there are no roots)+ */+export function calculateTraceDuration(+ roots: TreeNode[],+ origin: Date,+): number {+ if (roots.length === 0) return 0;++ const originMs = origin.getTime();+ let latestEndMs = -Infinity;++ // Iterative DFS to avoid stack overflow on deep trees.+ const stack: TreeNode[] = [...roots];+ while (stack.length > 0) {+ const node = stack.pop()!;+ const end = (node.endTime ?? node.startTime).getTime();+ if (end > latestEndMs) latestEndMs = end;+ for (const child of node.children) stack.push(child);+ }++ const spanFromEnds = (latestEndMs - originMs) / 1000;++ // Offset-aware latency fallback: each root's bar reaches+ // (offset from origin, in seconds) + (its latency, in seconds).+ const maxRootLatencySpan = Math.max(+ ...roots.map(+ (r) => (r.startTime.getTime() - originMs) / 1000 + (r.latency ?? 0),+ ),+ );++ return Math.max(spanFromEnds, maxRootLatencySpan);+}+// Predefined step sizes for time axis (in seconds)export const PREDEFINED_STEP_SIZES = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25,diff --git a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsxindex c2fa92cddb..65463de358 100644--- a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx+++ b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx@@ -157,7 +157,7 @@ function TracePanelNavigationHeaderExpanded({onKeyDown={handleSearchKeyDown}/></div>- <div className="flex flex-row items-center gap-0.5">+ <div className="flex shrink-0 flex-row items-center gap-0.5">{/* Expand/Collapse All Button */}<ButtononClick={handleToggleTreeNodes}@@ -198,7 +198,7 @@ function TracePanelNavigationHeaderExpanded({size="sm"onClick={() => setViewMode(isTimelineView ? null : "timeline")}className={cn(- "h-7 px-2 text-xs",+ "h-7 shrink-0 px-2 text-xs",isTimelineView && "bg-primary text-primary-foreground",)}>