Skip to content

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

feat(trace): tell the truth about observations past the load cap (LFE-14993) (#16033)

Nikita Kabardind4979001e51d
diff --git a/web/src/components/table/peek/peek-experiment-item-detail.tsx b/web/src/components/table/peek/peek-experiment-item-detail.tsx
index e7a3e23964..f799c9b4d3 100644
--- a/web/src/components/table/peek/peek-experiment-item-detail.tsx
+++ b/web/src/components/table/peek/peek-experiment-item-detail.tsx
@@ -31,7 +31,12 @@ const PeekViewExperimentItemDetail = ({ projectId }: { projectId: string }) => {
}
return (
- <TraceDetailBody trace={trace.data} context="peek" keySuffix={peekId} />
+ <TraceDetailBody
+ trace={trace.data}
+ context="peek"
+ keySuffix={peekId}
+ truncatedAtObservations={trace.truncatedAtObservations}
+ />
);
};
diff --git a/web/src/components/table/peek/peek-observation-detail.tsx b/web/src/components/table/peek/peek-observation-detail.tsx
index 840ce6ba78..28a647a744 100644
--- a/web/src/components/table/peek/peek-observation-detail.tsx
+++ b/web/src/components/table/peek/peek-observation-detail.tsx
@@ -87,6 +87,7 @@ export const TablePeekViewObservationDetail = (
trace={trace.data}
context="peek"
keySuffix={peekObservationId}
+ truncatedAtObservations={trace.truncatedAtObservations}
/>
</TablePeekView>
);
diff --git a/web/src/components/table/peek/peek-trace-detail.tsx b/web/src/components/table/peek/peek-trace-detail.tsx
index b5ee265db9..fb48a55139 100644
--- a/web/src/components/table/peek/peek-trace-detail.tsx
+++ b/web/src/components/table/peek/peek-trace-detail.tsx
@@ -77,7 +77,11 @@ export const TablePeekViewTraceDetail = (
) : undefined
}
>
- <TraceDetailBody trace={trace.data} context="peek" />
+ <TraceDetailBody
+ trace={trace.data}
+ context="peek"
+ truncatedAtObservations={trace.truncatedAtObservations}
+ />
</TablePeekView>
);
};
diff --git a/web/src/features/events/hooks/useEventsTraceData.ts b/web/src/features/events/hooks/useEventsTraceData.ts
index a51426e382..f1bc28344e 100644
--- a/web/src/features/events/hooks/useEventsTraceData.ts
+++ b/web/src/features/events/hooks/useEventsTraceData.ts
@@ -34,7 +34,12 @@ interface UseEventsTraceDataResult {
| undefined;
isLoading: boolean;
error: unknown;
- cutoffObservationsAfterMaxCount: boolean;
+ /**
+ * The observation cap this trace was loaded under, set ONLY when the trace hit
+ * it (so the list is missing its chronological tail). The number comes from the
+ * server response β€” never a client-side copy of the constant.
+ */
+ truncatedAtObservations: number | undefined;
}
/**
@@ -173,13 +178,12 @@ export function useEventsTraceData(
};
}, [observations, traceId, rootIOQuery.data, scoresQuery.data]);
- const cutoffObservationsAfterMaxCount =
- eventsQuery.data?.cutoffObservationsAfterMaxCount ?? false;
-
return {
data: transformed ?? undefined,
isLoading: eventsQuery.isLoading || scoresQuery.isLoading,
error: eventsQuery.error || scoresQuery.error,
- cutoffObservationsAfterMaxCount,
+ truncatedAtObservations: eventsQuery.data?.cutoffObservationsAfterMaxCount
+ ? eventsQuery.data.maxObservationsPerTrace
+ : undefined,
};
}
diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.ts
index e643cda8f7..fa3855f3bc 100644
--- a/web/src/features/events/server/eventsRouter.ts
+++ b/web/src/features/events/server/eventsRouter.ts
@@ -334,6 +334,9 @@ export const eventsRouter = createTRPCRouter({
observations: toDomainArrayWithStringifiedMetadata(observations),
cutoffObservationsAfterMaxCount:
totalCount > MAX_OBSERVATIONS_PER_TRACE,
+ // The cap the client was served under, so UI copy states the number
+ // actually applied instead of keeping its own copy of it.
+ maxObservationsPerTrace: MAX_OBSERVATIONS_PER_TRACE,
};
},
);
diff --git a/web/src/features/traces/TracePage.tsx b/web/src/features/traces/TracePage.tsx
index 75d4343e37..72360135b0 100644
--- a/web/src/features/traces/TracePage.tsx
+++ b/web/src/features/traces/TracePage.tsx
@@ -12,8 +12,6 @@ import { Button } from "@/src/components/ui/button";
import Link from "next/link";
import { stripBasePath } from "@/src/utils/redirect";
import { Badge } from "@/src/components/ui/badge";
-import { showErrorToast } from "@/src/features/notifications/showErrorToast";
-import { useEffect } from "react";
export function TracePage({
traceId,
@@ -38,16 +36,6 @@ export function TracePage({
projectIdForAccessCheck,
);
- useEffect(() => {
- if (trace.cutoffObservationsAfterMaxCount) {
- showErrorToast(
- "Trace truncated",
- "This trace has too many observations for the detail view. Only a subset is shown.",
- "WARNING",
- );
- }
- }, [trace.cutoffObservationsAfterMaxCount]);
-
if (trace.isUnauthorized)
return <ErrorPage message="You do not have access to this trace." />;
@@ -175,6 +163,7 @@ export function TracePage({
<TraceDetailBody
trace={trace.data}
context={router.query.peek !== undefined ? "peek" : "fullscreen"}
+ truncatedAtObservations={trace.truncatedAtObservations}
/>
</div>
</Page>
diff --git a/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
index bdfd3498e3..500018f943 100644
--- a/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx
@@ -87,8 +87,14 @@ export function ObservationDetailView({
// V4 beta mode and observations for log tab
const { isBetaEnabled: isV4Enabled } = useV4Beta();
- const { observations, roots, nodeMap, traceLevelScoreOwnerIds } =
- useTraceData();
+ const {
+ observations,
+ roots,
+ nodeMap,
+ traceLevelScoreOwnerIds,
+ detachedObservationId,
+ detachedObservationIsMisplaced,
+ } = useTraceData();
const isLogViewVirtualized =
observations.length >= TRACE_VIEW_CONFIG.logView.virtualizationThreshold;
@@ -115,9 +121,15 @@ export function ObservationDetailView({
// Uses the tree's roots array which handles orphans correctly.
// Both stay absent/false for an observation outside the loaded (capped) list:
// subtree metrics and root-only chrome are tree facts we genuinely don't have,
- // so they are omitted rather than guessed.
+ // so they are omitted rather than guessed. A merged-in row whose parent is also
+ // past the cap sits AMONG the roots without being one β€” root chrome there would
+ // assert a position we don't know.
const treeNode = nodeMap.get(observation.id);
- const isRoot = roots.some((root) => root.id === observation.id);
+ const isRoot =
+ roots.some((root) => root.id === observation.id) &&
+ !(
+ detachedObservationIsMisplaced && observation.id === detachedObservationId
+ );
// Without a TRACE row (v4) this span stands in for the trace, so its badge and
// its Scores tab both cover the trace-level scores.
diff --git a/web/src/features/traces/components/Trace.tsx b/web/src/features/traces/components/Trace.tsx
index f98cff7f07..4b7a04c193 100644
--- a/web/src/features/traces/components/Trace.tsx
+++ b/web/src/features/traces/components/Trace.tsx
@@ -4,7 +4,11 @@ import { type ScoreDomain } from "@langfuse/shared";
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
import { TraceDataProvider } from "@/src/features/traces/contexts/TraceDataContext";
import { ViewPreferencesProvider } from "@/src/features/traces/contexts/ViewPreferencesContext";
-import { SelectionProvider } from "@/src/features/traces/contexts/SelectionContext";
+import {
+ SelectionProvider,
+ useSelection,
+} from "@/src/features/traces/contexts/SelectionContext";
+import { useSelectedObservation } from "@/src/features/traces/hooks/useSelectedObservation";
import { SearchProvider } from "@/src/features/traces/contexts/SearchContext";
import { JsonExpansionProvider } from "@/src/features/traces/contexts/JsonExpansionContext";
import { PlayheadProvider } from "@/src/features/traces/contexts/PlayheadContext";
@@ -34,16 +38,35 @@ export type TraceProps = {
corrections: ScoreDomain[];
projectId: string;
context?: "fullscreen" | "peek" | "annotation";
+ /** Observation cap this trace was loaded under, when it hit it. */
+ truncatedAtObservations?: number;
};
-export function Trace({
+/**
+ * SelectionProvider sits ABOVE the trace data so the selected observation can be
+ * resolved before the tree is built: past the observation cap the selected row is
+ * missing from the loaded list and has to be fetched and merged in.
+ */
+export function Trace({ context, ...props }: TraceProps) {
+ return (
+ <ViewPreferencesProvider traceContext={context}>
+ <SelectionProvider>
+ <TraceWithSelection {...props} />
+ </SelectionProvider>
+ </ViewPreferencesProvider>
+ );
+}
+
+function TraceWithSelection({
trace,
- observations,
+ observations: loadedObservations,
scores,
corrections,
projectId,
- context,
-}: TraceProps) {
+ truncatedAtObservations,
+}: Omit<TraceProps, "context">) {
+ const { selectedNodeId } = useSelection();
+
// Fetch comment counts using existing hook
const { observationCommentCounts, traceCommentCount } = useTraceComments({
projectId,
@@ -59,32 +82,63 @@ export function Trace({
return map;
}, [observationCommentCounts, traceCommentCount, trace.id]);
+ // A selected observation outside the loaded list joins the tree instead of
+ // being invisible in it.
+ const selected = useSelectedObservation({
+ selectedNodeId,
+ traceId: trace.id,
+ projectId,
+ observations: loadedObservations,
+ });
+ const detachedObservation =
+ selected.kind === "observation" && selected.isOutsideLoadedList
+ ? selected.observation
+ : null;
+
+ // treeBuilding nulls a parentObservationId it cannot resolve, so a row whose
+ // parent ALSO fell past the cap renders at root level without being a root β€”
+ // the one case the UI has to qualify. A row with a loaded parent nests
+ // correctly, and a row with no parent at all genuinely is a root; neither is
+ // misplaced.
+ const detachedIsMisplaced = useMemo(() => {
+ const parentId = detachedObservation?.parentObservationId;
+ if (!parentId) return false;
+ return !loadedObservations.some((obs) => obs.id === parentId);
+ }, [detachedObservation, loadedObservations]);
+
+ const observations = useMemo(
+ () =>
+ detachedObservation
+ ? [...loadedObservations, detachedObservation]
+ : loadedObservations,
+ [loadedObservations, detachedObservation],
+ );
+
return (
- <ViewPreferencesProvider traceContext={context}>
- <TraceDataProvider
- trace={trace}
+ <TraceDataProvider
+ trace={trace}
+ observations={observations}
+ serverScores={scores}
+ corrections={corrections}
+ comments={commentsMap}
+ detachedObservationId={detachedObservation?.id ?? null}
+ detachedObservationIsMisplaced={detachedIsMisplaced}
+ truncatedAtObservations={truncatedAtObservations}
+ >
+ <TraceGraphDataProvider
+ projectId={trace.projectId}
+ traceId={trace.id}
observations={observations}
- serverScores={scores}
- corrections={corrections}
- comments={commentsMap}
>
- <TraceGraphDataProvider
- projectId={trace.projectId}
- traceId={trace.id}
- observations={observations}
- >
- <SelectionProvider>
- <SearchProvider>
- <JsonExpansionProvider>
- <PlayheadProvider>
- <TraceContent />
- </PlayheadProvider>
- </JsonExpansionProvider>
- </SearchProvider>
- </SelectionProvider>
- </TraceGraphDataProvider>
- </TraceDataProvider>
- </ViewPreferencesProvider>
+ <SearchProvider>
+ <JsonExpansionProvider>
+ <PlayheadProvider>
+ <TraceContent />
+ </PlayheadProvider>
+ </JsonExpansionProvider>
+ </SearchProvider>
+ </TraceGraphDataProvider>
+ </TraceDataProvider>
);
}
diff --git a/web/src/features/traces/components/TraceDetailBody.tsx b/web/src/features/traces/components/TraceDetailBody.tsx
index 84f5e37610..a9c7a028df 100644
--- a/web/src/features/traces/components/TraceDetailBody.tsx
+++ b/web/src/features/traces/components/TraceDetailBody.tsx
@@ -16,10 +16,13 @@ export function TraceDetailBody({
trace,
context,
keySuffix,
+ truncatedAtObservations,
}: {
trace: TraceDetailData | undefined;
context: "peek" | "fullscreen" | "annotation";
keySuffix?: string;
+ /** Observation cap this trace was loaded under, when it hit it. */
+ truncatedAtObservations?: number;
}) {
if (!trace) return <Skeleton className="h-full w-full rounded-none" />;
return (
@@ -31,6 +34,7 @@ export function TraceDetailBody({
projectId={trace.projectId}
observations={trace.observations}
context={context}
+ truncatedAtObservations={truncatedAtObservations}
/>
);
}
diff --git a/web/src/features/traces/components/TraceLayoutMobile.tsx b/web/src/features/traces/components/TraceLayoutMobile.tsx
index d268aa8c04..7f29afa8bb 100644
--- a/web/src/features/traces/components/TraceLayoutMobile.tsx
+++ b/web/src/features/traces/components/TraceLayoutMobile.tsx
@@ -38,6 +38,7 @@ import {
TabsBarTrigger,
} from "@/src/components/ui/tabs-bar";
import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
+import { TraceTruncationNotice } from "./TraceTruncationNotice";
export type MobileTraceTab = "tree" | "timeline" | "graph" | "info";
const VALID_TABS: MobileTraceTab[] = ["tree", "timeline", "graph", "info"];
@@ -135,6 +136,10 @@ export function TraceLayoutMobile({
<TabsBarTrigger value="info">Data</TabsBarTrigger>
</TabsBarList>
+ {/* Above the tab bodies, not inside one: the truncation applies to every
+ tab, and the navigators own their own scroll containers. */}
+ <TraceTruncationNotice />
+
{/* Inactive tabs unmount (Radix default). On memory-constrained mobile
that keeps a single heavy subtree live at a time (two virtualizers,
the elk graph layout, and the detail JSON never all mount at once);
diff --git a/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx b/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx
index cb9ea3e823..f99b8353e9 100644
--- a/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx
+++ b/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx
@@ -4,7 +4,7 @@
* Responsibility:
* - Wrap navigation content with header and collapsible layout structure
* - Handle panel collapse/expand state for desktop
- * - Position TracePanelNavigationHiddenNotice above content
+ * - Position the truncation + hidden-observation notices above content
* - Render graph view panel below tree/timeline when enabled
* - Own the graph panel's collapse state: drag the divider down (or click the
* "Graph" bar) to collapse it to a slim bar; persisted per-project. Traces
@@ -34,6 +34,7 @@ import { useTraceGraphData } from "@/src/features/traces/contexts/TraceGraphData
import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
import { TracePanelNavigationHeader } from "../TracePanelNavigationHeader/TracePanelNavigationHeader";
import { TracePanelNavigationHiddenNotice } from "./components/TracePanelNavigationHiddenNotice";
+import { TraceTruncationNotice } from "@/src/features/traces/components/TraceTruncationNotice";
// Height of the "Graph" bar β€” the panel's collapsed form. Must match the bar's
// h-7 so a collapsed panel shows exactly the bar and nothing else.
@@ -168,6 +169,7 @@ export function TracePanelNavigationLayoutDesktop({
/>
{!isNavigationPanelCollapsed && (
<>
+ <TraceTruncationNotice />
<TracePanelNavigationHiddenNotice />
{secondaryContent ? (
<ResizablePanelGroup
diff --git a/web/src/features/traces/components/TraceTruncationNotice.clienttest.tsx b/web/src/features/traces/components/TraceTruncationNotice.clienttest.tsx
new file mode 100644
index 0000000000..2097b0f4d6
--- /dev/null
+++ b/web/src/features/traces/components/TraceTruncationNotice.clienttest.tsx
@@ -0,0 +1,109 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { TraceTruncationNotice } from "@/src/features/traces/components/TraceTruncationNotice";
+
+const { mockUseTraceData } = vi.hoisted(() => ({ mockUseTraceData: vi.fn() }));
+
+vi.mock("@/src/features/traces/contexts/TraceDataContext", () => ({
+ useTraceData: () => mockUseTraceData(),
+}));
+
+const traceData = (
+ overrides: {
+ truncatedAtObservations?: number;
+ detachedObservationId?: string | null;
+ detachedObservationIsMisplaced?: boolean;
+ } = {},
+) =>
+ mockUseTraceData.mockReturnValue({
+ truncatedAtObservations: 10_000,
+ detachedObservationId: null,
+ detachedObservationIsMisplaced: false,
+ ...overrides,
+ });
+
+const dismiss = () => fireEvent.click(screen.getByLabelText("Dismiss"));
+const isVisible = () => !!screen.queryByText(/Showing the first/);
+
+describe("TraceTruncationNotice", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("states the cap the server actually applied", () => {
+ // Never a hard-coded 10,000: the cap is server-owned and will change.
+ traceData({ truncatedAtObservations: 25_000 });
+
+ render(<TraceTruncationNotice />);
+
+ expect(
+ screen.getByText(/Showing the first 25,000 observations/),
+ ).toBeInTheDocument();
+ // An overflow flag is not a count β€” the copy must not promise a total.
+ expect(screen.queryByText(/of 25,001|total/)).not.toBeInTheDocument();
+ });
+
+ it.each([
+ // The row carries no marker of its own, so this copy is the only thing
+ // between a misplaced observation and a tree implying it is top-level.
+ { misplaced: true, claimsPosition: true },
+ // A row that nests correctly, or a genuine root, gets no position claim.
+ { misplaced: false, claimsPosition: false },
+ ])(
+ "claims a wrong position only when there is one (misplaced=$misplaced)",
+ ({ misplaced, claimsPosition }) => {
+ traceData({
+ detachedObservationId: "obs-past-cap",
+ detachedObservationIsMisplaced: misplaced,
+ });
+
+ render(<TraceTruncationNotice />);
+
+ expect(screen.getByText(/loaded separately/)).toBeInTheDocument();
+ expect(!!screen.queryByText(/appears at the top level/)).toBe(
+ claimsPosition,
+ );
+ },
+ );
+
+ it("re-shows only for a message that says more, never on the way back", () => {
+ traceData();
+ const { rerender } = render(<TraceTruncationNotice />);
+ dismiss();
+ expect(isVisible()).toBe(false);
+
+ // A re-render with the same message must not bring it back...
+ rerender(<TraceTruncationNotice />);
+ expect(isVisible()).toBe(false);
+
+ // ...but opening an observation outside the loaded list adds a sentence, and
+ // that is new information rather than the same notice nagging again.
+ traceData({ detachedObservationId: "obs-past-cap" });
+ rerender(<TraceTruncationNotice />);
+ expect(screen.getByText(/loaded separately/)).toBeInTheDocument();
+
+ // Dismiss that one and select a normal row again: selection flips the
+ // message BACK, and it must stay gone instead of re-appearing on every
+ // click across that boundary.
+ dismiss();
+ traceData();
+ rerender(<TraceTruncationNotice />);
+ expect(isVisible()).toBe(false);
+
+ // But the out-of-position caveat says strictly more than what was
+ // dismissed, and it is the only warning that row gets β€” so it still shows.
+ traceData({
+ detachedObservationId: "obs-past-cap",
+ detachedObservationIsMisplaced: true,
+ });
+ rerender(<TraceTruncationNotice />);
+ expect(screen.getByText(/appears at the top level/)).toBeInTheDocument();
+ });
+
+ it("renders nothing for a trace under the cap", () => {
+ traceData({ truncatedAtObservations: undefined });
+
+ const { container } = render(<TraceTruncationNotice />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/web/src/features/traces/components/TraceTruncationNotice.tsx b/web/src/features/traces/components/TraceTruncationNotice.tsx
new file mode 100644
index 0000000000..1cc587cbb5
--- /dev/null
+++ b/web/src/features/traces/components/TraceTruncationNotice.tsx
@@ -0,0 +1,77 @@
+/**
+ * Inline notice above the tree/timeline/search list when the trace has more
+ * observations than the detail view loads.
+ *
+ * It sits in the navigation pane on purpose: the missing observations are a fact
+ * about the picture drawn there, not an error that happened. It also renders in
+ * the peek, which previously said nothing at all about truncation.
+ *
+ * The count comes from the server response, never a client copy of the cap β€” the
+ * limit is server-owned and can change without this file.
+ */
+
+import { useState } from "react";
+import { TriangleAlert, X } from "lucide-react";
+import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
+
+export function TraceTruncationNotice() {
+ const {
+ truncatedAtObservations,
+ detachedObservationId,
+ detachedObservationIsMisplaced,
+ } = useTraceData();
+
+ // Per trace view: dismissing frees the space for this visit, and the notice is
+ // back on the next trace/reload rather than silently gone for good. Stored as
+ // the RANK that was dismissed, because selection moves in and out of the
+ // detached row and so the message changes both ways.
+ const [dismissedRank, setDismissedRank] = useState(-1);
+
+ if (!truncatedAtObservations) return null;
+
+ // The detached row carries no marker of its own (deliberately β€” a per-row label
+ // is noise on every scroll), so this sentence is the ONLY place that can say
+ // the tree is showing it out of position.
+ const detachedNote = !detachedObservationId
+ ? null
+ : detachedObservationIsMisplaced
+ ? " The one you opened is loaded separately, and appears at the top level because its parent is missing too."
+ : " The one you opened is loaded separately.";
+
+ // Ranked by how much the message says. Dismissing hides that message and
+ // everything it already covered, but never a later one that says MORE β€” so
+ // dismissing the short detached note cannot swallow the out-of-position
+ // caveat, which is the only warning that row gets.
+ const rank =
+ detachedObservationId && detachedObservationIsMisplaced
+ ? 2
+ : detachedObservationId
+ ? 1
+ : 0;
+ if (rank <= dismissedRank) return null;
+
+ return (
+ <div className="text-muted-foreground border-border bg-muted/40 flex shrink-0 items-start gap-2 border-b py-1.5 pr-1 pl-2 text-xs">
+ <TriangleAlert className="text-foreground-tertiary mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <p className="min-w-0 flex-1">
+ {/* No total: the server stops counting at the cap, so we know "more than
+ this", never how many. */}
+ <span className="font-bold">
+ Showing the first {truncatedAtObservations.toLocaleString()}{" "}
+ observations
+ </span>{" "}
+ by start time. Later ones are missing here β€” find them in the
+ observations table.
+ {detachedNote}
+ </p>
+ <button
+ type="button"
+ aria-label="Dismiss"
+ onClick={() => setDismissedRank(rank)}
+ className="hover:bg-muted-foreground/10 hover:text-foreground shrink-0 rounded p-0.5"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ );
+}
diff --git a/web/src/features/traces/contexts/TraceDataContext.tsx b/web/src/features/traces/contexts/TraceDataContext.tsx
index 56ffa6a4a4..e152a82bbd 100644
--- a/web/src/features/traces/contexts/TraceDataContext.tsx
+++ b/web/src/features/traces/contexts/TraceDataContext.tsx
@@ -57,6 +57,24 @@ interface TraceDataContextValue {
nodeMap: Map<string, TreeNode>;
searchItems: TraceSearchListItem[];
hiddenObservationsCount: number;
+ /**
+ * Observation that was merged in from a by-id fetch because it sits outside the
+ * loaded (capped) list. Its ancestors are unknown, so treeBuilding places it at
+ * root level β€” the views MUST mark it, or a deeply nested observation silently
+ * reads as top-level.
+ */
+ detachedObservationId: string | null;
+ /**
+ * True when that observation renders at root level WITHOUT being a root: its
+ * own parent fell past the cap too, so treeBuilding could not resolve the
+ * reference and nulled it. The three cases collapse to this one question β€”
+ * a loaded parent nests correctly, and a genuinely parentless row IS a root β€”
+ * but they must not be conflated: reading "no parent" as "parent is loaded"
+ * is what made the UI claim a position it did not have.
+ */
+ detachedObservationIsMisplaced: boolean;
+ /** Observation cap this trace was loaded under, when it hit it. */
+ truncatedAtObservations?: number;
comments: Map<string, number>;
/** Timeline origin (the 0s mark): earliest start across the whole tree. The
* single owner of the temporal frame β€” timeline, playhead, and graph all
@@ -82,6 +100,9 @@ interface TraceDataProviderProps {
serverScores: WithStringifiedMetadata<ScoreDomain>[];
corrections: ScoreDomain[];
comments: Map<string, number>;
+ detachedObservationId?: string | null;
+ detachedObservationIsMisplaced?: boolean;
+ truncatedAtObservations?: number;
children: ReactNode;
}
@@ -95,6 +116,9 @@ export function TraceDataProvider({
serverScores,
corrections,
comments,
+ detachedObservationId = null,
+ detachedObservationIsMisplaced = false,
+ truncatedAtObservations,
children,
}: TraceDataProviderProps) {
const { minObservationLevel } = useViewPreferences();
@@ -156,8 +180,14 @@ export function TraceDataProvider({
);
const traceLevelScoreOwnerIdSet = useMemo(
- () => traceLevelScoreOwnerIds(uiData.roots),
- [uiData.roots],
+ () =>
+ traceLevelScoreOwnerIds(
+ uiData.roots,
+ // Only a misplaced row is an impostor among the roots; a genuine root
+ // that happened to fall past the cap is still a root.
+ detachedObservationIsMisplaced ? detachedObservationId : null,
+ ),
+ [uiData.roots, detachedObservationId, detachedObservationIsMisplaced],
);
// Merge scores with optimistic cache
@@ -182,6 +212,9 @@ export function TraceDataProvider({
nodeMap: uiData.nodeMap,
searchItems: filteredSearchItems,
hiddenObservationsCount,
+ detachedObservationId,
+ detachedObservationIsMisplaced,
+ truncatedAtObservations,
comments,
traceStartTime,
traceDuration,
@@ -196,6 +229,9 @@ export function TraceDataProvider({
traceLevelScoreOwnerIdSet,
filteredSearchItems,
hiddenObservationsCount,
+ detachedObservationId,
+ detachedObservationIsMisplaced,
+ truncatedAtObservations,
uiData.nodeMap,
comments,
traceStartTime,
diff --git a/web/src/features/traces/fns/nodeScores.clienttest.ts b/web/src/features/traces/fns/nodeScores.clienttest.ts
index 0b37591de4..2fd4a8926e 100644
--- a/web/src/features/traces/fns/nodeScores.clienttest.ts
+++ b/web/src/features/traces/fns/nodeScores.clienttest.ts
@@ -27,6 +27,25 @@ describe("traceLevelScoreOwnerIds", () => {
]).toEqual(["root", "orphan"]);
});
+ it("does not hand ownership to a row that only LOOKS top-level", () => {
+ // An observation merged in from outside the loaded list, whose parent is
+ // missing too, sits among the roots without being one. In v4 (no TRACE row)
+ // the roots stand in for the trace, so leaving it in would give it the
+ // trace's scores and root-only chrome.
+ const rootsWithImpostor = roots(
+ { id: "root", type: "SPAN" },
+ { id: "detached", type: "SPAN" },
+ );
+
+ expect([...traceLevelScoreOwnerIds(rootsWithImpostor, "detached")]).toEqual(
+ ["root"],
+ );
+ // A genuine root that merely fell past the cap keeps root semantics.
+ expect(
+ traceLevelScoreOwnerIds(rootsWithImpostor, null).has("detached"),
+ ).toBe(true);
+ });
+
it("is input-sensitive: level-filtered roots would hand ownership to a promoted child", () => {
// A level filter that hides "root" promotes "child" to the top of the
// rendered tree. Ownership must come from the structural roots, or a
diff --git a/web/src/features/traces/fns/nodeScores.ts b/web/src/features/traces/fns/nodeScores.ts
index 50d17b8a33..69101f7ee4 100644
--- a/web/src/features/traces/fns/nodeScores.ts
+++ b/web/src/features/traces/fns/nodeScores.ts
@@ -18,12 +18,22 @@ type LeveledScore = { observationId: string | null };
* Pass the STRUCTURAL roots, never the level-filtered ones: hiding a root
* promotes its children to the top of the rendered tree, and a promoted child is
* not a stand-in for the trace. TraceDataContext owns the one call site.
+ *
+ * `excludeId` covers the same class of impostor from the other direction: an
+ * observation merged in from outside the loaded list whose parent is also missing
+ * lands among the roots because its parent reference could not be resolved, not
+ * because it is top-level. Without excluding it, a v4 trace (no TRACE row) hands
+ * it the trace's scores and its root-only chrome.
*/
export function traceLevelScoreOwnerIds(
roots: Pick<TreeNode, "id" | "type">[],
+ excludeId?: string | null,
): Set<string> {
- const traceNodes = roots.filter((root) => root.type === "TRACE");
- const owners = traceNodes.length > 0 ? traceNodes : roots;
+ const structural = excludeId
+ ? roots.filter((root) => root.id !== excludeId)
+ : roots;
+ const traceNodes = structural.filter((root) => root.type === "TRACE");
+ const owners = traceNodes.length > 0 ? traceNodes : structural;
return new Set(owners.map((owner) => owner.id));
}
diff --git a/web/src/features/traces/fns/treeBuilding.clienttest.ts b/web/src/features/traces/fns/treeBuilding.clienttest.ts
index 3710987d7a..00bc479918 100644
--- a/web/src/features/traces/fns/treeBuilding.clienttest.ts
+++ b/web/src/features/traces/fns/treeBuilding.clienttest.ts
@@ -292,6 +292,34 @@ describe("buildTraceUiData", () => {
expect(result.roots[0].name).toBe("Generation");
});
+ it("places an observation whose parent is not in the list at root level", () => {
+ // The contract the detached-observation injection relies on: a row merged
+ // in from outside the capped list has an unloaded parent, so it lands as a
+ // root β€” which is why the truncation notice has to qualify its position.
+ const trace = createMockTrace({
+ id: "trace-1",
+ rootObservationType: "SPAN",
+ });
+ const observations: ObservationReturnType[] = [
+ createMockObservation({ id: "loaded-root", startTime: new Date(1000) }),
+ createMockObservation({
+ id: "detached",
+ parentObservationId: "never-loaded",
+ startTime: new Date(2000),
+ }),
+ ];
+
+ const result = buildTraceUiData(trace, observations);
+
+ expect(result.roots.map((r) => r.id)).toEqual([
+ "loaded-root",
+ "detached",
+ ]);
+ expect(result.nodeMap.get("detached")?.parentObservationId).toBeNull();
+ // It must still participate in search / the temporal frame.
+ expect(result.searchItems.map((i) => i.node.id)).toContain("detached");
+ });
+
it("propagates trace.latency to primary root observation node", () => {
const trace = createMockTrace({
id: "trace-1",
diff --git a/web/src/features/traces/hooks/useTraceDetailData.clienttest.tsx b/web/src/features/traces/hooks/useTraceDetailData.clienttest.tsx
index 0c87fd973a..b4e58806ee 100644
--- a/web/src/features/traces/hooks/useTraceDetailData.clienttest.tsx
+++ b/web/src/features/traces/hooks/useTraceDetailData.clienttest.tsx
@@ -72,7 +72,7 @@ describe("useTraceDetailData (beta / events path)", () => {
data: undefined,
isLoading: false,
error: { data: { code: "UNAUTHORIZED" } },
- cutoffObservationsAfterMaxCount: false,
+ truncatedAtObservations: undefined,
});
const r = render();
expect(r.isUnauthorized).toBe(true);
@@ -86,7 +86,7 @@ describe("useTraceDetailData (beta / events path)", () => {
data: undefined,
isLoading: false,
error: { data: { code: "INTERNAL_SERVER_ERROR" } },
- cutoffObservationsAfterMaxCount: false,
+ truncatedAtObservations: undefined,
});
const r = render();
// A transient server error is neither "not found" nor "unauthorized".
@@ -100,7 +100,7 @@ describe("useTraceDetailData (beta / events path)", () => {
data: undefined,
isLoading: false,
error: null,
- cutoffObservationsAfterMaxCount: false,
+ truncatedAtObservations: undefined,
});
const r = render();
expect(r.isNotFound).toBe(true);
@@ -126,7 +126,7 @@ describe("useTraceDetailData endpoint routing", () => {
data: undefined,
isLoading: false,
error: null,
- cutoffObservationsAfterMaxCount: false,
+ truncatedAtObservations: undefined,
});
});
diff --git a/web/src/features/traces/hooks/useTraceDetailData.ts b/web/src/features/traces/hooks/useTraceDetailData.ts
index af542b7455..d3f4e914d6 100644
--- a/web/src/features/traces/hooks/useTraceDetailData.ts
+++ b/web/src/features/traces/hooks/useTraceDetailData.ts
@@ -76,7 +76,7 @@ export function useTraceDetailData({
isError: false,
isNotFound: false,
isUnauthorized: false,
- cutoffObservationsAfterMaxCount: false,
+ truncatedAtObservations: undefined,
};
}
@@ -100,8 +100,7 @@ export function useTraceDetailData({
isNotFound:
!eventsData.isLoading && !eventsData.data && !eventsData.error,
isUnauthorized,
- cutoffObservationsAfterMaxCount:
- eventsData.cutoffObservationsAfterMaxCount,
+ truncatedAtObservations: eventsData.truncatedAtObservations,
};
}
@@ -112,6 +111,7 @@ export function useTraceDetailData({
isError: tracesQuery.isError,
isNotFound: tracesQuery.error?.data?.code === "NOT_FOUND",
isUnauthorized: tracesQuery.error?.data?.code === "UNAUTHORIZED",
- cutoffObservationsAfterMaxCount: false,
+ // The traces-table read path has no row cap.
+ truncatedAtObservations: undefined,
};
}