Skip to content

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

fix(table): clear stale rows when switching filter scope (#17692)

Nikita Kabardin816e69d4e21f
diff --git a/web/src/components/table/hooks/usePaginationWindowPin.clienttest.ts b/web/src/components/table/hooks/usePaginationWindowPin.clienttest.ts
index a06f056f08..312f92f770 100644
--- a/web/src/components/table/hooks/usePaginationWindowPin.clienttest.ts
+++ b/web/src/components/table/hooks/usePaginationWindowPin.clienttest.ts
@@ -86,6 +86,20 @@ describe("usePaginationWindowPin", () => {
expect(closed.result.current.range).toBe(absolute);
});
+ it("releases the previous view's pin before the page reset reaches the URL", () => {
+ const { result, rerender } = renderHook(
+ ({ pageIndex }) => usePaginationWindowPin(LIVE, pageIndex),
+ { initialProps: { pageIndex: 2 } },
+ );
+ expect(result.current.range?.to).toEqual(START);
+ act(() => result.current.resetPin());
+ expect(result.current.range?.to).toBeUndefined();
+ rerender({ pageIndex: 0 });
+ act(() => result.current.pinOnLeavingFirstPage(1, NEWEST_ON_PAGE_1));
+ rerender({ pageIndex: 1 });
+ expect(result.current.range?.to).toEqual(NEWEST_ON_PAGE_1);
+ });
+
it("does not pin a live window when the sort has no live tail", () => {
const { result, rerender } = renderHook(
({ pageIndex }: { pageIndex: number }) =>
diff --git a/web/src/components/table/hooks/usePaginationWindowPin.ts b/web/src/components/table/hooks/usePaginationWindowPin.ts
index bfd8ebcf83..3d5d5ddf67 100644
--- a/web/src/components/table/hooks/usePaginationWindowPin.ts
+++ b/web/src/components/table/hooks/usePaginationWindowPin.ts
@@ -80,5 +80,9 @@ export function usePaginationWindowPin(
[enabled],
);
- return { range: pinnedRange, pinOnLeavingFirstPage };
+ return {
+ range: pinnedRange,
+ pinOnLeavingFirstPage,
+ resetPin: () => setPinnedAt(null),
+ };
}
diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
index 9c45fefc8b..e10cb8303b 100644
--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
@@ -71,6 +71,8 @@ interface UseTableStateProps {
allowBackendSystemPresets?: boolean;
/** Called after an application even when the validated state is unchanged. */
onViewApplied?: (state: TableViewPresetState) => void;
+ /** Reset transient table state on selection; preserve bookmarked pagination. */
+ onViewSelected?: () => void;
}
const isViewApplicableToTable = (
@@ -113,6 +115,7 @@ export function useTableViewManager({
disabled = false,
allowBackendSystemPresets = false,
onViewApplied,
+ onViewSelected,
}: UseTableStateProps) {
const router = useRouter();
const isRouterReady = router.isReady;
@@ -209,6 +212,7 @@ export function useTableViewManager({
const setSearchQueryRef = useRef(setSearchQuery);
const setExpandedFiltersRef = useRef(setExpandedFilters);
const onViewAppliedRef = useRef(onViewApplied);
+ const onViewSelectedRef = useRef(onViewSelected);
// Update refs immediately on every render
setFiltersRef.current = setFilters;
@@ -216,6 +220,7 @@ export function useTableViewManager({
setSearchQueryRef.current = setSearchQuery;
setExpandedFiltersRef.current = setExpandedFilters;
onViewAppliedRef.current = onViewApplied;
+ onViewSelectedRef.current = onViewSelected;
// Extract primitive for effect dep (rerender-dependencies: avoid object deps)
const defaultViewId = resolvedDefault?.viewId;
@@ -319,6 +324,13 @@ export function useTableViewManager({
(viewData: TableViewPresetState, meta?: SavedViewApplyMeta) => {
// lock table
setIsLoading(true);
+ if (
+ meta?.trigger === "select" ||
+ meta?.trigger === "system_preset" ||
+ meta?.trigger === "system_preset_cleared"
+ ) {
+ onViewSelectedRef.current?.();
+ }
/**
* Validate orderBy and filters
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 65043cd39d..843886367f 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -62,6 +62,7 @@ import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-
import { EmptyValue } from "@/src/components/design-system/table/components/EmptyValue/EmptyValue";
import { ConnectedIOTableCell } from "@/src/components/table/ConnectedIOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
+import { tablePlaceholderOptions } from "@/src/components/table/utils/tablePlaceholder";
import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateContext";
import {
toAbsoluteTimeRange,
@@ -627,10 +628,26 @@ export default function ObservationsTable({
orderBy,
};
+ const placeholderOptions = tablePlaceholderOptions({
+ projectId,
+ filter:
+ externalFilterState ??
+ queryFilter.effectiveFilterState.concat(
+ promptNameFilter,
+ promptVersionFilter,
+ modelIdFilter,
+ ),
+ searchQuery,
+ searchType,
+ timeRange: externalDateRange ?? timeRange,
+ });
+
const generations = api.generations.all.useQuery(getAllPayload, {
+ ...placeholderOptions,
refetchOnWindowFocus: true,
});
const totalCountQuery = api.generations.countAll.useQuery(getCountPayload, {
+ ...placeholderOptions,
refetchOnWindowFocus: true,
});
const totalCount = totalCountQuery.data?.totalCount ?? null;
@@ -1228,6 +1245,10 @@ export default function ObservationsTable({
currentFilterState: queryFilter.explicitFilterState,
currentExpandedFilters: queryFilter.expanded,
disabled: hideControls,
+ onViewSelected: () => {
+ setPaginationState({ ...paginationState, pageIndex: 0 });
+ observationsTableStore.getState().actions.clearSelection();
+ },
});
viewControllersRef.current = viewControllers;
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 6e0c433b04..e26df9a53c 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -64,6 +64,7 @@ import {
usePaginationWindowPin,
} from "@/src/components/table/hooks/usePaginationWindowPin";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
+import { tablePlaceholderOptions } from "@/src/components/table/utils/tablePlaceholder";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
import { BreakdownTooltip } from "@/src/features/traces/components/BreakdownTooltip";
@@ -287,12 +288,15 @@ function TracesTableInternal({
// upper bound pinned, so that offset paging does not repeat or skip rows while
// the window keeps taking in newly ingested ones.
const dateRangeFilter: FilterState = toTimestampFilter(dateRange);
- const { range: rowsDateRange, pinOnLeavingFirstPage } =
- usePaginationWindowPin(
- dateRange,
- limitRows ? 0 : paginationState.pageIndex,
- { enabled: isLiveTailTimeSort(orderByState, "timestamp") },
- );
+ const {
+ range: rowsDateRange,
+ pinOnLeavingFirstPage,
+ resetPin,
+ } = usePaginationWindowPin(
+ dateRange,
+ limitRows ? 0 : paginationState.pageIndex,
+ { enabled: isLiveTailTimeSort(orderByState, "timestamp") },
+ );
const rowsDateRangeFilter: FilterState = toTimestampFilter(rowsDateRange);
const userIdFilter: FilterState = userId
? [
@@ -486,11 +490,18 @@ function TracesTableInternal({
orderBy: null,
};
- // Deliberately NOT placeholder-backed, unlike the row query: its key only
- // changes when the filter does, and keeping the previous value would pair rows
- // for the new filter with a count for the old one. It reports as loading
- // instead until it catches up.
+ const placeholderOptions = tablePlaceholderOptions({
+ projectId,
+ filter:
+ externalFilterState ??
+ queryFilter.effectiveFilterState.concat(userIdFilter),
+ searchQuery,
+ searchType,
+ timeRange: externalDateRange ?? timeRange,
+ });
+
const totalCountQuery = api.traces.countAll.useQuery(tracesAllCountFilter, {
+ ...placeholderOptions,
enabled: environmentFilterOptions.data !== undefined,
});
@@ -503,14 +514,11 @@ function TracesTableInternal({
orderBy: orderByState,
};
- // A filter/page/sort change (or a re-anchored window) is a new query key:
- // keep the rows that are on screen until the new ones land, so only a genuine
- // cold load renders skeletons.
const traces = api.traces.all.useQuery(tracesAllQueryFilter, {
+ ...placeholderOptions,
enabled: environmentFilterOptions.data !== undefined,
refetchOnMount: false,
refetchOnWindowFocus: true,
- placeholderData: (prev) => prev,
});
const traceMetrics = api.traces.metrics.useQuery(
{
@@ -519,10 +527,10 @@ function TracesTableInternal({
traceIds: traces.data?.traces.map((t) => t.id) ?? [],
},
{
+ ...placeholderOptions,
enabled: traces.data !== undefined,
refetchOnMount: false,
refetchOnWindowFocus: true,
- placeholderData: (prev) => prev,
},
);
@@ -1287,6 +1295,12 @@ function TracesTableInternal({
currentFilterState: queryFilter.explicitFilterState,
currentExpandedFilters: queryFilter.expanded,
disabled: hideControls,
+ onViewSelected: () => {
+ resetPin();
+ setPaginationState({ ...paginationState, pageIndex: 0 });
+ setSelectedRows({});
+ setSelectAll(false);
+ },
});
viewControllersRef.current = viewControllers;
diff --git a/web/src/components/table/utils/tablePlaceholder.clienttest.ts b/web/src/components/table/utils/tablePlaceholder.clienttest.ts
new file mode 100644
index 0000000000..3755cc4385
--- /dev/null
+++ b/web/src/components/table/utils/tablePlaceholder.clienttest.ts
@@ -0,0 +1,122 @@
+// @vitest-environment node
+
+import { QueryClient, QueryObserver } from "@tanstack/react-query";
+import {
+ tablePlaceholderOptions,
+ type TableDataScope,
+} from "./tablePlaceholder";
+
+const scope = {
+ projectId: "project-a",
+ filter: [{ column: "name", type: "string", operator: "=", value: "A" }],
+ searchQuery: "test",
+ searchType: ["id"],
+ timeRange: { range: "last1Day" },
+} satisfies TableDataScope;
+
+const queryOptions = (identity: TableDataScope, input: unknown) => ({
+ queryKey: ["rows", input],
+ queryFn: () => new Promise<string[]>(() => {}),
+ ...tablePlaceholderOptions(identity),
+});
+
+describe("table placeholders", () => {
+ it("drops rows when their project, filters, search, or chosen time range changes", () => {
+ const changes: TableDataScope[] = [
+ { ...scope, projectId: "project-b" },
+ { ...scope, filter: [{ ...scope.filter[0]!, value: "B" }] },
+ { ...scope, searchQuery: "other" },
+ { ...scope, searchType: ["content"] },
+ { ...scope, timeRange: { range: "last7Days" } },
+ {
+ ...scope,
+ filter: [
+ ...scope.filter,
+ {
+ column: "startTime",
+ type: "datetime",
+ operator: ">=",
+ value: new Date("2026-01-01T00:00:00Z"),
+ },
+ ],
+ },
+ ];
+
+ for (const next of changes) {
+ const client = new QueryClient();
+ const initial = queryOptions(scope, "A");
+ client.setQueryData(initial.queryKey, ["A"]);
+ const observer = new QueryObserver(client, initial);
+ observer.setOptions(queryOptions(next, "B"));
+
+ expect(observer.getCurrentResult().isPending).toBe(true);
+ expect(observer.getCurrentResult().data).toBeUndefined();
+ observer.destroy();
+ client.clear();
+ }
+ });
+
+ it("does not revive A while switching from pending B to pending C", () => {
+ const client = new QueryClient();
+ const initial = queryOptions(scope, "A");
+ client.setQueryData(initial.queryKey, ["A"]);
+ const observer = new QueryObserver(client, initial);
+
+ for (const name of ["B", "C"]) {
+ observer.setOptions(
+ queryOptions(
+ { ...scope, filter: [{ ...scope.filter[0]!, value: name }] },
+ name,
+ ),
+ );
+ expect(observer.getCurrentResult().data).toBeUndefined();
+ expect(observer.getCurrentResult().isPending).toBe(true);
+ }
+
+ observer.destroy();
+ client.clear();
+ });
+
+ it("keeps rows across page, sort and resolved-window changes in the same scope", () => {
+ const client = new QueryClient();
+ const initial = queryOptions(scope, { page: 1 });
+ client.setQueryData(initial.queryKey, ["A"]);
+ const observer = new QueryObserver(client, initial);
+
+ for (const input of [
+ { page: 2 },
+ { page: 2, orderBy: { column: "name", order: "ASC" } },
+ { page: 2, from: new Date("2026-01-02T00:00:00Z") },
+ ]) {
+ observer.setOptions(queryOptions({ ...scope }, input));
+ expect(observer.getCurrentResult().data).toEqual(["A"]);
+ expect(observer.getCurrentResult().isPlaceholderData).toBe(true);
+ }
+
+ observer.destroy();
+ client.clear();
+ });
+
+ it("keeps a disabled dependent query from relabeling the last populated batch", () => {
+ const client = new QueryClient();
+ const initial = queryOptions(scope, { ids: ["A"] });
+ client.setQueryData(initial.queryKey, ["A input"]);
+ const observer = new QueryObserver(client, initial);
+ const nextScope = { ...scope, searchQuery: "other" };
+
+ observer.setOptions({
+ ...queryOptions(nextScope, null),
+ enabled: false,
+ });
+ expect(observer.getCurrentResult().data).toBeUndefined();
+ expect(
+ client.getQueryCache().find({ queryKey: initial.queryKey })?.meta,
+ ).toEqual({ tableDataScope: scope });
+
+ observer.setOptions(queryOptions(nextScope, { ids: ["B"] }));
+ expect(observer.getCurrentResult().data).toBeUndefined();
+
+ observer.destroy();
+ client.clear();
+ });
+});
diff --git a/web/src/components/table/utils/tablePlaceholder.ts b/web/src/components/table/utils/tablePlaceholder.ts
new file mode 100644
index 0000000000..df947e18ab
--- /dev/null
+++ b/web/src/components/table/utils/tablePlaceholder.ts
@@ -0,0 +1,28 @@
+import { type FilterState, type TracingSearchType } from "@langfuse/shared";
+import {
+ type TableDateRange,
+ type TimeRange,
+} from "@/src/utils/date-range-utils";
+import isEqual from "lodash/isEqual";
+
+// Keep user intent here; paging, sort and generated window bounds are not scope.
+export type TableDataScope = {
+ projectId: string;
+ filter: FilterState;
+ searchQuery?: string | null;
+ searchType?: TracingSearchType[];
+ timeRange: TimeRange | TableDateRange | undefined;
+};
+
+export function tablePlaceholderOptions(scope: TableDataScope) {
+ return {
+ meta: { tableDataScope: scope },
+ placeholderData: <T>(
+ previousData: T | undefined,
+ previousQuery: { meta?: Record<string, unknown> } | undefined,
+ ): T | undefined =>
+ isEqual(previousQuery?.meta?.tableDataScope, scope)
+ ? previousData
+ : undefined,
+ };
+}
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 15d28d3570..648518fcdb 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -506,12 +506,15 @@ export default function ObservationsEventsTable({
// Facets describe the whole window (see facetStartTimeFilter below); the paged
// row/count queries take the pinned upper bound instead, so offset paging does
// not repeat or skip rows while the window keeps taking in newly ingested ones.
- const { range: rowsDateRange, pinOnLeavingFirstPage } =
- usePaginationWindowPin(
- dateRange,
- limitRows ? 0 : paginationState.page - 1,
- { enabled: isLiveTailTimeSort(orderByState, "startTime") },
- );
+ const {
+ range: rowsDateRange,
+ pinOnLeavingFirstPage,
+ resetPin,
+ } = usePaginationWindowPin(
+ dateRange,
+ limitRows ? 0 : paginationState.page - 1,
+ { enabled: isLiveTailTimeSort(orderByState, "startTime") },
+ );
const dateRangeFilter: FilterState = toStartTimeFilterState(rowsDateRange);
const appRootDefault = useAppRootDefault({
@@ -908,6 +911,15 @@ export default function ObservationsEventsTable({
} = useEventsTableData({
projectId,
filterState,
+ tableDataScope: {
+ projectId,
+ filter:
+ externalFilterState ??
+ queryFilter.effectiveFilterState.concat(embedScopeFilterState),
+ searchQuery,
+ searchType,
+ timeRange: externalDateRange ?? timeRange,
+ },
paginationState: limitRows
? { page: 1, limit: limitRows }
: paginationState,
@@ -1658,6 +1670,12 @@ export default function ObservationsEventsTable({
currentExpandedFilters: queryFilter.expanded,
disabled: tableStatePolicy.disableSavedViews,
allowBackendSystemPresets: true,
+ onViewSelected: () => {
+ resetPin();
+ setPaginationState({ ...paginationState, page: 1 });
+ setSelectedRows({});
+ setSelectAll(false);
+ },
onViewApplied: (viewState) =>
resetSearchBarDraft({
filters: projectFiltersForSearchBar(viewState.filters),
diff --git a/web/src/features/events/hooks/useEventsFilterOptions.clienttest.ts b/web/src/features/events/hooks/useEventsFilterOptions.clienttest.ts
index 575ca17457..a678c44030 100644
--- a/web/src/features/events/hooks/useEventsFilterOptions.clienttest.ts
+++ b/web/src/features/events/hooks/useEventsFilterOptions.clienttest.ts
@@ -1,5 +1,10 @@
import { act, renderHook } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ QueryClient,
+ QueryObserver,
+ type QueryObserverOptions,
+} from "@tanstack/react-query";
import type { FilterState, TimeFilter } from "@langfuse/shared";
@@ -7,6 +12,9 @@ const mocks = vi.hoisted(() => ({
bulkInputs: [] as any[],
perColumnInputs: [] as any[],
perColumnData: {} as Record<string, Record<string, unknown>>,
+ bulkData: {} as Record<string, unknown>,
+ bulkClient: null as QueryClient | null,
+ bulkObserver: null as QueryObserver<Record<string, unknown>> | null,
}));
// Capture the tRPC inputs the hook builds, to assert the plan is wired through
@@ -15,11 +23,39 @@ vi.mock("@/src/utils/api", () => ({
api: {
events: {
filterOptions: {
- useQuery: (input: any) => {
+ useQuery: (
+ input: any,
+ options: Omit<
+ QueryObserverOptions<Record<string, unknown>>,
+ "queryKey" | "queryFn"
+ >,
+ ) => {
mocks.bulkInputs.push(input);
+ if (mocks.bulkClient) {
+ const queryOptions = {
+ queryKey: ["events.filterOptions", input],
+ queryFn: () => new Promise<Record<string, unknown>>(() => {}),
+ ...options,
+ };
+ if (!mocks.bulkObserver) {
+ mocks.bulkClient.setQueryData(
+ queryOptions.queryKey,
+ mocks.bulkData,
+ );
+ mocks.bulkObserver = new QueryObserver(
+ mocks.bulkClient,
+ queryOptions,
+ );
+ mocks.bulkObserver.subscribe(() => {});
+ } else {
+ mocks.bulkObserver.setOptions(queryOptions);
+ }
+ return mocks.bulkObserver.getCurrentResult();
+ }
return {
- data: {},
+ data: mocks.bulkData,
isFetching: false,
+ isPlaceholderData: false,
isError: false,
isPending: false,
};
@@ -89,6 +125,69 @@ describe("useEventsFilterOptions filtered facet counts (LFE-14489)", () => {
mocks.bulkInputs = [];
mocks.perColumnInputs = [];
mocks.perColumnData = {};
+ mocks.bulkData = {};
+ mocks.bulkClient = null;
+ mocks.bulkObserver = null;
+ });
+
+ afterEach(() => {
+ mocks.bulkObserver?.destroy();
+ mocks.bulkClient?.clear();
+ });
+
+ it("retains counts across column changes and only clears counts across scope changes", () => {
+ const environment = [{ value: "production", count: 120 }];
+ mocks.bulkData = {
+ environment,
+ approxTotalCount: 120,
+ approxTotalCountIsPartial: true,
+ };
+ mocks.bulkClient = new QueryClient();
+ const initial: Parameters<typeof useEventsFilterOptions>[0] = {
+ projectId: "p",
+ startTimeFilter: [START_TIME],
+ includeApproxCount: true,
+ lazy: true,
+ };
+ const { result, rerender } = renderHook(
+ (props) => useEventsFilterOptions(props),
+ { initialProps: initial },
+ );
+ expect(result.current.approxTotalCount).toBe(120);
+
+ rerender({ ...initial, lazy: false, columns: ["environment", "name"] });
+ expect(mocks.bulkObserver?.getCurrentResult().isPlaceholderData).toBe(true);
+ expect(result.current.approxTotalCount).toBe(120);
+ expect(result.current.isApproxTotalCountLoading).toBe(false);
+ expect(result.current.approxTotalCountIsPartialScope).toBe(true);
+
+ for (const change of [
+ { refiningFilter: [LEVEL_ERROR] },
+ { startTimeFilter: [{ ...START_TIME, value: new Date("2026-02-01") }] },
+ { refiningFilter: [{ ...START_TIME, value: new Date("2026-02-01") }] },
+ { projectId: "another-project" },
+ { isRootObservation: true },
+ ]) {
+ rerender({ ...initial, ...change });
+ expect(result.current.approxTotalCount).toBeNull();
+ expect(result.current.isApproxTotalCountLoading).toBe(true);
+ expect(result.current.approxTotalCountIsPartialScope).toBe(false);
+ expect(result.current.filterOptions.environment).toEqual(environment);
+ }
+
+ const finalProps = { ...initial, isRootObservation: true, lazy: false };
+ rerender(finalProps);
+ expect(result.current.approxTotalCount).toBeNull();
+ mocks.bulkClient.setQueryData(
+ mocks.bulkObserver!.getCurrentQuery().queryKey,
+ {
+ approxTotalCount: 7,
+ approxTotalCountIsPartial: false,
+ },
+ );
+ rerender(finalProps);
+ expect(result.current.approxTotalCount).toBe(7);
+ expect(result.current.isApproxTotalCountLoading).toBe(false);
});
it("sends only the start-time scope and no refining filter when idle", () => {
diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.ts
index 5cf1ba7182..4ad8b464b5 100644
--- a/web/src/features/events/hooks/useEventsFilterOptions.ts
+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts
@@ -7,6 +7,7 @@ import {
splitFacetFilter,
} from "@/src/features/events/lib/facet-query-plan";
import { sortOptionValues } from "@/src/features/filters";
+import { tablePlaceholderOptions } from "@/src/components/table/utils/tablePlaceholder";
type EventFilterOptionColumnsInput =
RouterInputs["events"]["filterOptions"]["columns"];
@@ -235,6 +236,24 @@ export function useEventsFilterOptions({
[splitFilter.refiningFilter, lazy, columns, lazyColumns],
);
+ const countPlaceholderOptions = tablePlaceholderOptions({
+ projectId,
+ filter: (plan.bulk.filter ?? []).concat(
+ baseInput.startTimeFilter ?? [],
+ isRootObservation === undefined
+ ? []
+ : [
+ {
+ column: "isRootObservation",
+ type: "boolean",
+ operator: "=",
+ value: isRootObservation,
+ },
+ ],
+ ),
+ timeRange: undefined,
+ });
+
// Eager bulk query: one ClickHouse scan for the plan's shared columns. Only
// this query carries includeApproxCount, so the approximate total ("Total ≈
// X") is computed once here (riding this scan), not per lazy per-column facet.
@@ -249,6 +268,17 @@ export function useEventsFilterOptions({
enabled,
trpc: { context: { skipBatch: true } },
...FILTER_OPTION_QUERY_OPTIONS,
+ meta: countPlaceholderOptions.meta,
+ // Facets remain visible across scopes; counts also require matching scope.
+ placeholderData: (previousData, previousQuery) =>
+ countPlaceholderOptions.placeholderData(previousData, previousQuery) ??
+ (previousData
+ ? {
+ ...previousData,
+ approxTotalCount: null,
+ approxTotalCountIsPartial: false,
+ }
+ : undefined),
},
);
diff --git a/web/src/features/events/hooks/useEventsTableData.clienttest.tsx b/web/src/features/events/hooks/useEventsTableData.clienttest.tsx
new file mode 100644
index 0000000000..77d2013dd0
--- /dev/null
+++ b/web/src/features/events/hooks/useEventsTableData.clienttest.tsx
@@ -0,0 +1,110 @@
+import { renderHook } from "@testing-library/react";
+import {
+ QueryClient,
+ QueryClientProvider,
+ type UseQueryOptions,
+ type useQuery,
+} from "@tanstack/react-query";
+import { type ReactNode } from "react";
+import { type TableDataScope } from "@/src/components/table/utils/tablePlaceholder";
+import { useEventsTableData } from "./useEventsTableData";
+
+vi.mock("@/src/features/notifications", () => ({
+ showSuccessToast: vi.fn(),
+}));
+
+vi.mock("@/src/utils/api", async () => {
+ const { useQuery: useActualQuery } = await vi.importActual<{
+ useQuery: typeof useQuery;
+ }>("@tanstack/react-query");
+ const query = (name: string) => ({
+ useQuery: (
+ input: unknown,
+ options: Omit<UseQueryOptions, "queryKey" | "queryFn">,
+ ) =>
+ useActualQuery({
+ queryKey: [name, input],
+ queryFn: () => new Promise<never>(() => {}),
+ ...options,
+ }),
+ });
+ return {
+ sendAsPostOption: {},
+ api: {
+ events: {
+ all: query("events.all"),
+ batchIO: query("events.batchIO"),
+ countAll: query("events.countAll"),
+ },
+ annotationQueueItems: { createMany: { useMutation: () => ({}) } },
+ },
+ };
+});
+
+it("does not relabel cached non-root rows when the disabled fallback observes them", () => {
+ const client = new QueryClient();
+ const scope: TableDataScope = {
+ projectId: "project-a",
+ filter: [],
+ timeRange: { range: "last1Day" },
+ };
+ client.setQueryData(
+ [
+ "events.all",
+ {
+ projectId: scope.projectId,
+ filter: [],
+ searchQuery: null,
+ searchType: ["id", "content"],
+ orderBy: null,
+ page: 1,
+ limit: 50,
+ },
+ ],
+ {
+ observations: [{ id: "non-root" }],
+ hasMore: false,
+ },
+ );
+
+ const { result, rerender, unmount } = renderHook(
+ ({ tableDataScope }: { tableDataScope: TableDataScope }) =>
+ useEventsTableData({
+ projectId: scope.projectId,
+ filterState: tableDataScope.filter,
+ tableDataScope,
+ paginationState: { page: 1, limit: 50 },
+ orderByState: null,
+ selectedRows: {},
+ selectAll: false,
+ setSelectedRows: () => {},
+ }),
+ {
+ initialProps: { tableDataScope: scope },
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ },
+ );
+ expect(result.current.observations.rows).toEqual([{ id: "non-root" }]);
+
+ const rootScope: TableDataScope = {
+ ...scope,
+ filter: [
+ {
+ column: "isRootObservation",
+ type: "boolean",
+ operator: "=",
+ value: true,
+ },
+ ],
+ };
+ rerender({ tableDataScope: rootScope });
+ // The fallback observer updates shared query metadata after the first render.
+ rerender({ tableDataScope: rootScope });
+ expect(result.current.observations.status).toBe("loading");
+ expect(result.current.observations.rows).toBeUndefined();
+
+ unmount();
+ client.clear();
+});
diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.ts
index 340e3fc83f..e459b43acf 100644
--- a/web/src/features/events/hooks/useEventsTableData.ts
+++ b/web/src/features/events/hooks/useEventsTableData.ts
@@ -10,6 +10,10 @@ import { type FullEventsObservations } from "@langfuse/shared/src/server";
import { showSuccessToast } from "@/src/features/notifications";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { usePendingRowIds } from "@/src/components/table/hooks/usePendingRowIds";
+import {
+ tablePlaceholderOptions,
+ type TableDataScope,
+} from "@/src/components/table/utils/tablePlaceholder";
import { type EventBatchIOOutput } from "@/src/features/events/server/eventsRouter";
import {
removeAppRootDefaultFilter,
@@ -24,6 +28,7 @@ type FullEventsObservation = FullEventsObservations[number] & {
type UseEventsTableDataParams = {
projectId: string;
filterState: FilterState;
+ tableDataScope: TableDataScope;
paginationState: {
page: number;
limit: number;
@@ -54,6 +59,7 @@ type UseEventsTableDataParams = {
export function useEventsTableData({
projectId,
filterState,
+ tableDataScope,
paginationState,
orderByState,
searchQuery,
@@ -93,12 +99,14 @@ export function useEventsTableData({
);
const silentHttpCodes = [422];
+ const placeholderOptions = tablePlaceholderOptions(tableDataScope);
const observations = api.events.all.useQuery(getAllPayload, {
+ ...placeholderOptions,
enabled: rowsEnabled,
refetchOnWindowFocus: true,
- placeholderData: (prev) => prev,
meta: {
+ ...placeholderOptions.meta,
silentHttpCodes, // Turns off red bubble
},
});
@@ -125,7 +133,13 @@ export function useEventsTableData({
refetchOnWindowFocus: false,
staleTime: Infinity,
retry: false,
- meta: { silentHttpCodes },
+ meta: {
+ tableDataScope: {
+ ...tableDataScope,
+ filter: removeAppRootDefaultFilter(tableDataScope.filter),
+ },
+ silentHttpCodes,
+ },
});
const activeObservations =
shouldRunAppRootFallback && !appRootFallbackQuery.isError
@@ -175,11 +189,11 @@ export function useEventsTableData({
// Fetch I/O data
const ioDataQuery = api.events.batchIO.useQuery(batchIOPayload!, {
...sendAsPostOption,
+ ...placeholderOptions,
enabled:
rowsEnabled && activeObservations.isSuccess && batchIOPayload !== null,
refetchOnWindowFocus: false,
staleTime: 0,
- placeholderData: (prev) => prev,
});
// I/O lands one query behind the rows.
@@ -198,9 +212,8 @@ export function useEventsTableData({
// Memoize joined data to prevent infinite re-renders
// Handle loading, error, and success states
const joinedData = useMemo(() => {
- // Placeholder data is the previous key's rows: report them as loaded so a
- // filter/page/sort change keeps them on screen. "loading" now means the
- // table has nothing to show at all.
+ // Same-scope placeholders keep paging and refreshes loaded; scope changes
+ // have no placeholder and show the cold-load state.
if (activeObservations.isPending) {
return { status: "loading" as const, rows: undefined };
}
@@ -228,9 +241,9 @@ export function useEventsTableData({
// Fetch the exact count only after the user selects all matching rows.
const totalCountQuery = api.events.countAll.useQuery(getCountPayload, {
+ ...placeholderOptions,
enabled: selectAll,
refetchOnWindowFocus: true,
- placeholderData: (prev) => prev,
});
const totalCount = selectAll
diff --git a/web/src/features/filters/viewStateHistoryWrites.clienttest.tsx b/web/src/features/filters/viewStateHistoryWrites.clienttest.tsx
index 2514c83a76..6aaadd7d84 100644
--- a/web/src/features/filters/viewStateHistoryWrites.clienttest.tsx
+++ b/web/src/features/filters/viewStateHistoryWrites.clienttest.tsx
@@ -26,6 +26,7 @@ const mockUseRouter = vi.fn();
const mockCapture = vi.fn();
const mockGetDefaultUseQuery = vi.fn();
const mockGetByIdUseQuery = vi.fn();
+const mockViewSelected = vi.fn();
const queryParamStore = new Map<string, unknown>();
@@ -143,20 +144,22 @@ function ViewManagerHarness({
tableName?: TableViewPresetTableName;
}) {
const [appliedFilters, setAppliedFilters] = useState<FilterState>([]);
- const { selectedViewId, handleSetViewId } = useTableViewManager({
- tableName,
- projectId: "project-1",
- stateUpdaters: {
- setFilters: setAppliedFilters,
- setColumnOrder: () => {},
- setColumnVisibility: () => {},
- },
- validationContext: {
- columns: [],
- filterColumnDefinition: TEST_FILTER_CONFIG.columnDefinitions,
- },
- currentFilterState: appliedFilters,
- });
+ const { selectedViewId, handleSetViewId, applyViewState } =
+ useTableViewManager({
+ tableName,
+ projectId: "project-1",
+ stateUpdaters: {
+ setFilters: setAppliedFilters,
+ setColumnOrder: () => {},
+ setColumnVisibility: () => {},
+ },
+ validationContext: {
+ columns: [],
+ filterColumnDefinition: TEST_FILTER_CONFIG.columnDefinitions,
+ },
+ currentFilterState: appliedFilters,
+ onViewSelected: mockViewSelected,
+ });
return (
<div>
@@ -168,6 +171,21 @@ function ViewManagerHarness({
set-view-replace
</button>
<button onClick={() => handleSetViewId("view-1")}>set-view</button>
+ <button
+ onClick={() =>
+ applyViewState(
+ {
+ filters: TEST_FILTERS,
+ orderBy: null,
+ columnOrder: [],
+ columnVisibility: {},
+ },
+ { trigger: "select", viewId: "view-1" },
+ )
+ }
+ >
+ apply-view
+ </button>
</div>
);
}
@@ -225,6 +243,14 @@ describe("view-state URL writes and browser history (LFE-10715)", () => {
});
});
+ it("resets table state for an explicit view selection, including reapplication", () => {
+ render(<ViewManagerHarness />);
+ expect(mockViewSelected).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByText("apply-view"));
+ fireEvent.click(screen.getByText("apply-view"));
+ expect(mockViewSelected).toHaveBeenCalledTimes(2);
+ });
+
it("strips a stale frontend system-preset viewId with a replace, not a push", async () => {
queryParamStore.set("viewId", "__langfuse_with_io__");
mockUseRouter.mockReturnValue({
@@ -346,6 +372,7 @@ describe("view-state URL writes and browser history (LFE-10715)", () => {
expect(screen.getByTestId("selected-view-id").textContent).toBe("view-1");
expect(screen.getByTestId("applied-filter-count").textContent).toBe("1");
});
+ expect(mockViewSelected).not.toHaveBeenCalled();
const viewIdWrites = urlParamWrites.filter(
(write) => write.key === "viewId",
diff --git a/web/src/features/sessions/SessionsTable.tsx b/web/src/features/sessions/SessionsTable.tsx
index 17f1020c5e..8d6ed6fdcc 100644
--- a/web/src/features/sessions/SessionsTable.tsx
+++ b/web/src/features/sessions/SessionsTable.tsx
@@ -48,6 +48,7 @@ import type Decimal from "decimal.js";
import { useEffect, useState, useMemo, useRef, useCallback } from "react";
import { usePaginationState } from "@/src/hooks/usePaginationState";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
+import { tablePlaceholderOptions } from "@/src/components/table/utils/tablePlaceholder";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
import { joinSessionCoreAndMetrics } from "@/src/features/sessions/session-row-data";
import TagList from "@/src/features/tag/components/TagList";
@@ -342,23 +343,33 @@ export default function SessionsTable({
limit: paginationState.pageSize,
};
+ const placeholderOptions = tablePlaceholderOptions({
+ projectId,
+ filter: queryFilter.effectiveFilterState.concat(userIdFilter),
+ timeRange,
+ });
+
const sessionsV3 = api.sessions.all.useQuery(payloadGetAll, {
+ ...placeholderOptions,
enabled: !isV4,
refetchOnWindowFocus: true,
});
const sessionsV4 = api.sessions.allFromEvents.useQuery(payloadGetAll, {
+ ...placeholderOptions,
enabled: isV4,
refetchOnWindowFocus: true,
});
const sessions = isV4 ? sessionsV4 : sessionsV3;
const sessionCountQueryV3 = api.sessions.countAll.useQuery(payloadCount, {
+ ...placeholderOptions,
enabled: !isV4,
refetchOnWindowFocus: true,
});
const sessionCountQueryV4 = api.sessions.countAllFromEvents.useQuery(
payloadCount,
{
+ ...placeholderOptions,
enabled: isV4,
refetchOnWindowFocus: true,
},
@@ -392,6 +403,7 @@ export default function SessionsTable({
sessionIds: sessionsV3.data?.sessions.map((s) => s.id) ?? [],
},
{
+ ...placeholderOptions,
enabled: sessionsV3.data !== undefined && !isV4,
refetchOnWindowFocus: true,
},
@@ -404,6 +416,7 @@ export default function SessionsTable({
queryFromTimestamp: dateRange?.from ?? null,
},
{
+ ...placeholderOptions,
enabled: sessionsV4.data !== undefined && isV4,
refetchOnWindowFocus: true,
},
@@ -753,6 +766,11 @@ export default function SessionsTable({
},
currentFilterState: queryFilter.explicitFilterState,
currentExpandedFilters: queryFilter.expanded,
+ onViewSelected: () => {
+ setPaginationState({ ...paginationState, pageIndex: 0 });
+ setSelectedRows({});
+ setSelectAll(false);
+ },
});
viewControllersRef.current = viewControllers;