Skip to content

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

feat(filters): refine event facet counts from the row query's filter state (LFE-14489) (#15466)

Nikita Kabardince10eb5be66e
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index f3f96e099e..c5ba418908 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -1019,7 +1019,7 @@ const LoadedSessionEventsPage: React.FC<{
const { filterOptions, isFilterOptionsPending } = useEventsFilterOptions({
projectId,
- oldFilterState: timeFiltersForOptions,
+ startTimeFilter: timeFiltersForOptions,
});
const typedFilterOptions = filterOptions as EventFilterOptions;
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 3b37cf1fb1..a9ab08c7d4 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -6,11 +6,11 @@ import {
} from "@/src/components/table/data-table-controls";
import { ResizableFilterLayout } from "@/src/components/table/resizable-filter-layout";
import { useEffect, useMemo, useState, useRef, useCallback } from "react";
-import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { usePaginationState } from "@/src/hooks/usePaginationState";
import {
type UseSidebarFilterStateOptions,
- useSidebarFilterState,
+ useSidebarFilterPresentation,
+ useSidebarFilterStateCore,
} from "@/src/features/filters/hooks/useSidebarFilterState";
import {
getEventsColumnName,
@@ -28,6 +28,7 @@ import {
BatchActionType,
ActionId,
RESOURCE_LIMIT_ERROR_MESSAGE,
+ type TimeFilter,
type TracingSearchType,
type ScoreAggregate,
} from "@langfuse/shared";
@@ -78,7 +79,6 @@ import {
useDetailPageLists,
} from "@/src/features/navigate-detail-pages/context";
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
-import { useRouter } from "next/router";
import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";
import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";
import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";
@@ -240,10 +240,10 @@ export type EventsTableProps = {
isolateTableState?: boolean;
};
-// Build the start-time `FilterState` for an absolute date range (lower bound
+// Build the start-time filters for an absolute date range (lower bound
// always, upper bound when present). Shared by the live table-rows range and the
// tick-decoupled facet-options range.
-const toStartTimeFilterState = (range?: TableDateRange): FilterState =>
+const toStartTimeFilterState = (range?: TableDateRange): TimeFilter[] =>
range
? [
{
@@ -281,8 +281,6 @@ export default function ObservationsEventsTable({
isolateTableState = false,
}: EventsTableProps) {
const peekContext = usePeekTableState();
- const router = useRouter();
- const { viewId } = router.query;
const eventsFilterConfig = useMemo(
() => getObservationEventsFilterConfig(omittedFilter),
[omittedFilter],
@@ -327,31 +325,6 @@ export default function ObservationsEventsTable({
"s",
);
- const [inputFilterState] = useQueryFilterState(
- // Default type filter - exclude SPAN and EVENT types
- !viewId
- ? [
- {
- column: "type",
- type: "stringOptions",
- operator: "any of",
- value: [
- "GENERATION",
- "AGENT",
- "TOOL",
- "CHAIN",
- "RETRIEVER",
- "EVALUATOR",
- "EMBEDDING",
- "GUARDRAIL",
- ],
- },
- ]
- : [],
- "generations", // Use "generations" table name for compatibility
- projectId,
- );
-
const [orderByState, setOrderByState] = useOrderByState({
column: "startTime",
order: "DESC",
@@ -508,40 +481,16 @@ export default function ObservationsEventsTable({
const dateRangeFilter: FilterState = toStartTimeFilterState(dateRange);
- // Facet options are scoped only by the time window (the facet hook reads just
- // the start-time filters); use the tick-decoupled range so the auto refresh
- // leaves them alone.
- const oldFilterState = (isolateTableState ? [] : inputFilterState).concat(
- toStartTimeFilterState(filterOptionsDateRange),
- );
-
- // Fetch filter options. Lazy: start with the eagerly-visible facets and load
- // the rest (high-cardinality userId/sessionId, model/prompt/score facets) only
- // when a sidebar section is opened or a field is typed into the search bar.
- const {
- filterOptions,
- isFilterOptionsPending,
- erroredColumns,
- loadingColumns,
- requestColumns,
- } = useEventsFilterOptions({
- projectId,
- oldFilterState,
- lazy: true,
- });
-
const appRootDefault = useAppRootDefault({
enabled: enableAppRootDefault,
projectId,
});
- const queryFilterOptions: UseSidebarFilterStateOptions = useMemo(() => {
+ // Route-state half of the sidebar filters, ahead of the facet-options query
+ // so the same state that scopes the rows can refine the counts (LFE-14489).
+ const filterStateOptions: UseSidebarFilterStateOptions = useMemo(() => {
const baseOptions = {
- loading: isFilterOptionsPending,
- loadingColumns,
implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
- // v4 fast-mode surface β€” drives `isV4` on filters:* analytics (LFE-10781).
- isV4: true,
defaultExplicitFilterState: appRootDefault.defaultExplicitFilterState,
onExplicitFilterStateChange: appRootDefault.onExplicitFilterStateChange,
};
@@ -568,18 +517,104 @@ export default function ObservationsEventsTable({
};
}, [
tableStatePolicy.filterStateLocation,
- isFilterOptionsPending,
- loadingColumns,
peekContext,
projectId,
appRootDefault.defaultExplicitFilterState,
appRootDefault.onExplicitFilterStateChange,
]);
- const queryFilter = useSidebarFilterState(
+ const filterCore = useSidebarFilterStateCore(
+ eventsFilterConfig,
+ filterStateOptions,
+ );
+
+ // Embed scoping (user/session detail tabs, prompt linked generations): these
+ // conditions bound the row query, so they refine the facet counts too.
+ const embedScopeFilterState: FilterState = useMemo(
+ () => [
+ ...(userId
+ ? [
+ {
+ column: "User ID",
+ type: "string" as const,
+ operator: "=" as const,
+ value: userId,
+ },
+ ]
+ : []),
+ ...(sessionId
+ ? [
+ {
+ column: "Session ID",
+ type: "string" as const,
+ operator: "=" as const,
+ value: sessionId,
+ },
+ ]
+ : []),
+ ...(promptName
+ ? [
+ {
+ column: "promptName",
+ type: "string" as const,
+ operator: "=" as const,
+ value: promptName,
+ },
+ ]
+ : []),
+ ...(promptVersion
+ ? [
+ {
+ column: "promptVersion",
+ type: "number" as const,
+ operator: "=" as const,
+ value: promptVersion,
+ },
+ ]
+ : []),
+ ],
+ [userId, sessionId, promptName, promptVersion],
+ );
+
+ // The time window travels separately, on the tick-decoupled range so the
+ // auto refresh leaves the facets alone.
+ const facetRefiningFilter = useMemo(
+ () =>
+ externalFilterState ??
+ filterCore.filterState.concat(embedScopeFilterState),
+ [externalFilterState, filterCore.filterState, embedScopeFilterState],
+ );
+ const facetStartTimeFilter = useMemo(
+ () => toStartTimeFilterState(filterOptionsDateRange),
+ [filterOptionsDateRange],
+ );
+
+ // Fetch filter options. Lazy: start with the eagerly-visible facets and load
+ // the rest (high-cardinality userId/sessionId, model/prompt/score facets) only
+ // when a sidebar section is opened or a field is typed into the search bar.
+ const {
+ filterOptions,
+ isFilterOptionsPending,
+ erroredColumns,
+ loadingColumns,
+ requestColumns,
+ } = useEventsFilterOptions({
+ projectId,
+ startTimeFilter: facetStartTimeFilter,
+ refiningFilter: facetRefiningFilter,
+ lazy: true,
+ });
+
+ const queryFilter = useSidebarFilterPresentation(
+ filterCore,
eventsFilterConfig,
filterOptions,
- queryFilterOptions,
+ {
+ loading: isFilterOptionsPending,
+ loadingColumns,
+ // v4 fast-mode surface β€” drives `isV4` on filters:* analytics (LFE-10781).
+ isV4: true,
+ },
);
// Lazy filter-options: load a facet's values when its sidebar section is
@@ -694,59 +729,12 @@ export default function ObservationsEventsTable({
// ]
// : [];
- // Create user ID filter if userId is provided
- const userIdFilter: FilterState = userId
- ? [
- {
- column: "User ID",
- type: "string",
- operator: "=",
- value: userId,
- },
- ]
- : [];
-
- const sessionIdFilter: FilterState = sessionId
- ? [
- {
- column: "Session ID",
- type: "string",
- operator: "=",
- value: sessionId,
- },
- ]
- : [];
-
- const promptNameFilter: FilterState = promptName
- ? [
- {
- column: "promptName",
- type: "string",
- operator: "=",
- value: promptName,
- },
- ]
- : [];
-
- const promptVersionFilter: FilterState = promptVersion
- ? [
- {
- column: "promptVersion",
- type: "number",
- operator: "=",
- value: promptVersion,
- },
- ]
- : [];
-
// The sidebar's effective filter state is the single source of truth in both
- // modes β€” the search bar syncs into it rather than replacing it.
+ // modes β€” the search bar syncs into it, and the facet counts above refine
+ // from the same state + embed scoping (LFE-14489).
const combinedFilterState = queryFilter.effectiveFilterState
.concat(dateRangeFilter)
- .concat(userIdFilter)
- .concat(sessionIdFilter)
- .concat(promptNameFilter)
- .concat(promptVersionFilter);
+ .concat(embedScopeFilterState);
// Use external filter state if provided, otherwise use combined filter
// state. Even with an external filter, still apply the date-range bound so
diff --git a/web/src/features/events/hooks/useEventsFilterOptions.clienttest.ts b/web/src/features/events/hooks/useEventsFilterOptions.clienttest.ts
new file mode 100644
index 0000000000..fcff62b259
--- /dev/null
+++ b/web/src/features/events/hooks/useEventsFilterOptions.clienttest.ts
@@ -0,0 +1,132 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { FilterState, TimeFilter } from "@langfuse/shared";
+
+const mocks = vi.hoisted(() => ({
+ bulkInputs: [] as any[],
+ perColumnInputs: [] as any[],
+}));
+
+// Capture the tRPC inputs the hook builds, to assert the plan is wired through
+// to the server contract. Plan SEMANTICS live in the planner's own tests.
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ events: {
+ filterOptions: {
+ useQuery: (input: any) => {
+ mocks.bulkInputs.push(input);
+ return {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ };
+ },
+ },
+ },
+ useQueries: (
+ build: (t: any) => unknown[],
+ opts: { combine: (results: any[]) => unknown },
+ ) => {
+ const descriptors = build({
+ events: {
+ filterOptions: (input: any) => {
+ mocks.perColumnInputs.push(input);
+ return { input };
+ },
+ },
+ });
+ const results = descriptors.map(() => ({
+ data: {},
+ isFetching: false,
+ isError: false,
+ }));
+ return opts.combine(results);
+ },
+ },
+}));
+
+import { useEventsFilterOptions } from "@/src/features/events/hooks/useEventsFilterOptions";
+
+const START_TIME: TimeFilter = {
+ column: "startTime",
+ type: "datetime",
+ operator: ">=",
+ value: new Date("2026-01-01T00:00:00.000Z"),
+};
+const LEVEL_ERROR: FilterState[number] = {
+ column: "level",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["ERROR"],
+};
+const ENV_PROD: FilterState[number] = {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production"],
+};
+
+function run(refiningFilter: FilterState) {
+ renderHook(() =>
+ useEventsFilterOptions({
+ projectId: "p",
+ startTimeFilter: [START_TIME],
+ refiningFilter,
+ lazy: true,
+ }),
+ );
+ return {
+ bulk: mocks.bulkInputs.at(-1),
+ perColumn: mocks.perColumnInputs,
+ };
+}
+
+describe("useEventsFilterOptions filtered facet counts (LFE-14489)", () => {
+ beforeEach(() => {
+ mocks.bulkInputs = [];
+ mocks.perColumnInputs = [];
+ });
+
+ it("sends only the start-time scope and no refining filter when idle", () => {
+ const { bulk, perColumn } = run([]);
+ expect(bulk.startTimeFilter).toEqual([START_TIME]);
+ expect(bulk.filter).toBeUndefined();
+ expect(bulk.columns).toContain("name");
+ expect(bulk.columns).toContain("scores_avg");
+ expect(perColumn).toHaveLength(0);
+ });
+
+ it("re-routes user-authored start-time conditions into startTimeFilter", () => {
+ // A search-bar `startTime:>…` narrows the rows; the server ignores it in
+ // `filter`, so it must reach the queries via the authoritative channel.
+ const userStartTime: FilterState[number] = {
+ column: "startTime",
+ type: "datetime",
+ operator: ">",
+ value: new Date("2026-02-01T00:00:00.000Z"),
+ };
+ const { bulk } = run([userStartTime, LEVEL_ERROR]);
+ expect(bulk.startTimeFilter).toEqual([START_TIME, userStartTime]);
+ expect(bulk.filter).toEqual([LEVEL_ERROR]);
+ });
+
+ it("executes the query plan: refined bulk + self-excluded per-column queries", () => {
+ const { bulk, perColumn } = run([ENV_PROD, LEVEL_ERROR]);
+
+ // The self-filtered facets leave the bulk; the rest refine by everything.
+ expect(bulk.columns).not.toContain("environment");
+ expect(bulk.columns).not.toContain("level");
+ expect(bulk.columns).toContain("name");
+ expect(bulk.filter).toEqual([ENV_PROD, LEVEL_ERROR]);
+
+ // Each pulled-out facet gets its own query carrying the OTHER conditions,
+ // and the shared start-time scope.
+ const envQuery = perColumn.find((q) => q.columns?.[0] === "environment");
+ const levelQuery = perColumn.find((q) => q.columns?.[0] === "level");
+ expect(envQuery.filter).toEqual([LEVEL_ERROR]);
+ expect(levelQuery.filter).toEqual([ENV_PROD]);
+ expect(envQuery.startTimeFilter).toEqual([START_TIME]);
+ });
+});
diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.ts
index 3e30d2ea58..0c0e376007 100644
--- a/web/src/features/events/hooks/useEventsFilterOptions.ts
+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts
@@ -1,6 +1,10 @@
import { api, type RouterInputs, type RouterOutputs } from "@/src/utils/api";
import { useCallback, useMemo, useState } from "react";
import { type FilterState, type TimeFilter } from "@langfuse/shared";
+import {
+ planEventFacetQueries,
+ splitFacetFilter,
+} from "@/src/features/events/lib/facet-query-plan";
type EventFilterOptionColumnsInput =
RouterInputs["events"]["filterOptions"]["columns"];
@@ -85,8 +89,8 @@ const isEventFilterOptionColumn = (
// Shared react-query options: filter options change slowly and are never live β€”
// fetch once and keep (no refetch on mount/focus/reconnect, infinite stale time),
-// and keep prior values on screen while a key changes (time-range move) so the
-// sidebar/bar never flicker.
+// and keep prior values on screen while a key changes (time-range move or filter
+// edit) so the sidebar/bar never flicker.
const FILTER_OPTION_QUERY_OPTIONS = {
refetchOnMount: false,
refetchOnWindowFocus: false,
@@ -101,14 +105,20 @@ type LazyFilterOptionResult = {
isError: boolean;
};
+const EMPTY_FILTER_STATE: FilterState = [];
+
type UseEventsFilterOptionsParams = {
projectId: string;
- oldFilterState: FilterState;
+ /** Time scope for the bounded facet scan. Separate from `refiningFilter`, so
+ * a window move re-keys every query but a filter edit only the refined ones. */
+ startTimeFilter?: TimeFilter[];
+ /** Active filters the counts refine against (LFE-14489). Pass the SAME state
+ * that scopes the row query; each facet self-excludes its own column via the
+ * query plan. Start-time conditions are re-routed into `startTimeFilter`. */
+ refiningFilter?: FilterState;
isRootObservation?: boolean;
- /**
- * Explicit column subset to request (non-lazy). Ignored when `lazy` is set.
- * Omit to request every column (the default bulk behavior).
- */
+ /** Explicit column subset (non-lazy; ignored when `lazy`). Omit to request
+ * all β€” request-all cannot self-exclude, so only valid unfiltered. */
columns?: EventFilterOptionColumnsInput;
/**
* Lazy mode (v4 events table): request only the eagerly-visible columns up
@@ -123,29 +133,36 @@ type UseEventsFilterOptionsParams = {
export function useEventsFilterOptions({
projectId,
- oldFilterState,
+ startTimeFilter,
+ refiningFilter = EMPTY_FILTER_STATE,
isRootObservation,
columns,
lazy = false,
}: UseEventsFilterOptionsParams) {
- // Extract start time filters for filter options query
- const startTimeFilters = useMemo(() => {
- return oldFilterState.filter(
- (f) =>
- (f.column === "Start Time" || f.column === "startTime") &&
- f.type === "datetime",
- ) as TimeFilter[];
- }, [oldFilterState]);
+ // User-authored start-time conditions (search-bar `startTime:>…`) merge into
+ // the authoritative startTimeFilter channel β€” the server ignores them in
+ // `filter`, so counts would otherwise silently ignore that narrowing.
+ const splitFilter = useMemo(
+ () => splitFacetFilter(refiningFilter),
+ [refiningFilter],
+ );
- const baseInput = useMemo(
- () => ({
+ const baseInput = useMemo(() => {
+ const mergedStartTime = [
+ ...(startTimeFilter ?? []),
+ ...splitFilter.startTimeFilter,
+ ];
+ return {
projectId,
- startTimeFilter:
- startTimeFilters.length > 0 ? startTimeFilters : undefined,
+ startTimeFilter: mergedStartTime.length > 0 ? mergedStartTime : undefined,
isRootObservation,
- }),
- [projectId, startTimeFilters, isRootObservation],
- );
+ };
+ }, [
+ projectId,
+ startTimeFilter,
+ splitFilter.startTimeFilter,
+ isRootObservation,
+ ]);
// Lazy mode owns a monotonically-growing set of on-demand columns (everything
// beyond the eager set). It only grows β€” re-collapsing a facet does not narrow
@@ -182,27 +199,43 @@ export function useEventsFilterOptions({
[lazyColumnSet],
);
- // Eager bulk query: one ClickHouse scan for the always-visible columns (lazy
- // mode) β€” or the explicit/all columns in non-lazy mode (unchanged behavior).
- const eagerColumns = lazy ? [...EAGER_EVENT_FILTER_OPTION_COLUMNS] : columns;
+ // All refinement semantics (self-exclusion, score catalog, id/label
+ // canonicalization) live in the pure plan module.
+ const plan = useMemo(
+ () =>
+ planEventFacetQueries<EventFilterOptionColumn>({
+ refiningFilter: splitFilter.refiningFilter,
+ eagerColumns: lazy ? EAGER_EVENT_FILTER_OPTION_COLUMNS : columns,
+ lazyColumns,
+ }),
+ [splitFilter.refiningFilter, lazy, columns, lazyColumns],
+ );
+
+ // Eager bulk query: one ClickHouse scan for the plan's shared columns.
const eagerQuery = api.events.filterOptions.useQuery(
- { ...baseInput, columns: eagerColumns },
+ {
+ ...baseInput,
+ filter: plan.bulk.filter,
+ columns: plan.bulk.columns,
+ },
{
trpc: { context: { skipBatch: true } },
...FILTER_OPTION_QUERY_OPTIONS,
},
);
- // One independently-cached query per on-demand column. `combine` merges them
- // into a single payload + derives which columns are still loading / errored,
- // and react-query memoizes the result so identity is stable between changes.
+ // One independently-cached query per plan.perColumn entry. `combine` merges
+ // them into a single payload + derives which columns are still loading /
+ // errored, and react-query memoizes the result so identity is stable between
+ // changes.
+ const perColumnPlan = plan.perColumn;
const combineLazy = useCallback(
(results: readonly LazyFilterOptionResult[]) => {
const data: FilterOptionsData = {};
const pendingColumns: string[] = [];
const erroredColumns: string[] = [];
results.forEach((r, i) => {
- const column = lazyColumns[i];
+ const column = perColumnPlan[i]?.column;
if (column === undefined) return;
// Publish data first: a post-success refetch error keeps placeholderData,
// so an already-loaded facet retains its values instead of blanking out β€”
@@ -222,14 +255,14 @@ export function useEventsFilterOptions({
});
return { data, pendingColumns, erroredColumns };
},
- [lazyColumns],
+ [perColumnPlan],
);
const lazyResult = api.useQueries(
(t) =>
- lazyColumns.map((column) =>
+ perColumnPlan.map(({ column, filter }) =>
t.events.filterOptions(
- { ...baseInput, columns: [column] },
+ { ...baseInput, filter, columns: [column] },
FILTER_OPTION_QUERY_OPTIONS,
),
),
@@ -318,17 +351,20 @@ export function useEventsFilterOptions({
// "no data". On a terminal error the column is dropped (no auto-retry, so the
// facet renders its empty state instead of skeletoning forever).
const isEagerFetching = eagerQuery.isFetching;
+ const bulkColumns = plan.bulk.columns;
const loadingColumns = useMemo<ReadonlySet<string> | undefined>(() => {
if (!lazy) return undefined;
const pending = new Set<string>(lazyResult.pendingColumns);
if (isEagerFetching) {
const data = rawData as Record<string, unknown>;
- for (const column of EAGER_EVENT_FILTER_OPTION_COLUMNS) {
+ // Only the columns actually in the bulk query β€” the self-excluded ones
+ // report through lazyResult.pendingColumns instead.
+ for (const column of bulkColumns ?? []) {
if (data[column] === undefined) pending.add(column);
}
}
return pending;
- }, [lazy, lazyResult.pendingColumns, isEagerFetching, rawData]);
+ }, [lazy, lazyResult.pendingColumns, isEagerFetching, rawData, bulkColumns]);
// Columns whose fetch terminally errored, per column. Consumers settle these to
// the empty state (no skeleton, no perpetual loading row β€” there is no
@@ -340,11 +376,11 @@ export function useEventsFilterOptions({
const erroredColumns = useMemo<ReadonlySet<string>>(() => {
const errored = new Set<string>(lazyErroredColumns);
if (isEagerError) {
- for (const column of EAGER_EVENT_FILTER_OPTION_COLUMNS)
+ for (const column of bulkColumns ?? EAGER_EVENT_FILTER_OPTION_COLUMNS)
errored.add(column);
}
return errored;
- }, [lazyErroredColumns, isEagerError]);
+ }, [lazyErroredColumns, isEagerError, bulkColumns]);
return {
filterOptions: newFilterOptions,
diff --git a/web/src/features/events/lib/facet-query-plan.clienttest.ts b/web/src/features/events/lib/facet-query-plan.clienttest.ts
new file mode 100644
index 0000000000..674bc44253
--- /dev/null
+++ b/web/src/features/events/lib/facet-query-plan.clienttest.ts
@@ -0,0 +1,176 @@
+import { describe, expect, it } from "vitest";
+
+import type { FilterState } from "@langfuse/shared";
+
+import {
+ planEventFacetQueries,
+ resolveEventFacetColumnId,
+ splitFacetFilter,
+} from "@/src/features/events/lib/facet-query-plan";
+
+const START_TIME: FilterState[number] = {
+ column: "startTime",
+ type: "datetime",
+ operator: ">=",
+ value: new Date("2026-01-01T00:00:00.000Z"),
+};
+const LEVEL_ERROR: FilterState[number] = {
+ column: "level",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["ERROR"],
+};
+const ENV_PROD: FilterState[number] = {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production"],
+};
+const SCORE_QUALITY: FilterState[number] = {
+ column: "scores_avg",
+ type: "numberObject",
+ key: "quality",
+ operator: ">",
+ value: 0.5,
+};
+// Display-name keyed conditions: the search bar's lowering and the embed-scope
+// filters (user/session detail pages) produce these instead of column ids.
+const ENV_PROD_BY_LABEL: FilterState[number] = {
+ column: "Environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production"],
+};
+const USER_SCOPE_BY_LABEL: FilterState[number] = {
+ column: "User ID",
+ type: "string",
+ operator: "=",
+ value: "user-1",
+};
+
+const EAGER = ["environment", "level", "name", "scores_avg"] as const;
+
+describe("splitFacetFilter", () => {
+ it("routes start-time conditions (id and display name) into startTimeFilter", () => {
+ const startTimeByLabel = { ...START_TIME, column: "Start Time" };
+ expect(
+ splitFacetFilter([START_TIME, startTimeByLabel, LEVEL_ERROR]),
+ ).toEqual({
+ startTimeFilter: [START_TIME, startTimeByLabel],
+ refiningFilter: [LEVEL_ERROR],
+ });
+ });
+});
+
+describe("resolveEventFacetColumnId", () => {
+ it("maps display names to column ids and passes ids/unknowns through", () => {
+ expect(resolveEventFacetColumnId("Environment")).toBe("environment");
+ expect(resolveEventFacetColumnId("User ID")).toBe("userId");
+ expect(resolveEventFacetColumnId("environment")).toBe("environment");
+ expect(resolveEventFacetColumnId("not-a-column")).toBe("not-a-column");
+ });
+});
+
+describe("planEventFacetQueries", () => {
+ it("keeps everything in one unrefined bulk when no filter is active", () => {
+ const plan = planEventFacetQueries({
+ refiningFilter: [],
+ eagerColumns: EAGER,
+ lazyColumns: [],
+ });
+ expect(plan.bulk.columns).toEqual([...EAGER]);
+ expect(plan.bulk.filter).toBeUndefined();
+ expect(plan.perColumn).toEqual([]);
+ });
+
+ it("pulls a self-filtered facet out of the bulk and self-excludes it", () => {
+ const plan = planEventFacetQueries({
+ refiningFilter: [LEVEL_ERROR],
+ eagerColumns: EAGER,
+ lazyColumns: [],
+ });
+ // `level` would self-collapse under its own condition β†’ own query...
+ expect(plan.bulk.columns).not.toContain("level");
+ expect(plan.bulk.columns).toContain("name");
+ // ...while the remaining bulk facets are refined by it.
+ expect(plan.bulk.filter).toEqual([LEVEL_ERROR]);
+ expect(plan.perColumn).toEqual([{ column: "level", filter: undefined }]);
+ });
+
+ it("cross-refines self-excluded facets against each other", () => {
+ const plan = planEventFacetQueries({
+ refiningFilter: [ENV_PROD, LEVEL_ERROR],
+ eagerColumns: EAGER,
+ lazyColumns: [],
+ });
+ expect(plan.bulk.columns).toEqual(["name", "scores_avg"]);
+ expect(plan.bulk.filter).toEqual([ENV_PROD, LEVEL_ERROR]);
+ // environment sees level's condition but not its own β€” and vice versa.
+ expect(plan.perColumn).toEqual([
+ { column: "environment", filter: [LEVEL_ERROR] },
+ { column: "level", filter: [ENV_PROD] },
+ ]);
+ });
+
+ it("never evicts the score catalog from the bulk", () => {
+ const plan = planEventFacetQueries({
+ refiningFilter: [SCORE_QUALITY],
+ eagerColumns: EAGER,
+ lazyColumns: [],
+ });
+ // The server ignores the filter for the catalog; the score condition still
+ // refines the value facets sharing the bulk.
+ expect(plan.bulk.columns).toEqual([...EAGER]);
+ expect(plan.bulk.filter).toEqual([SCORE_QUALITY]);
+ expect(plan.perColumn).toEqual([]);
+ });
+
+ it("matches display-name keyed conditions to their facet ids", () => {
+ const plan = planEventFacetQueries({
+ refiningFilter: [ENV_PROD_BY_LABEL],
+ eagerColumns: EAGER,
+ lazyColumns: [],
+ });
+ expect(plan.bulk.columns).not.toContain("environment");
+ expect(plan.perColumn).toEqual([
+ { column: "environment", filter: undefined },
+ ]);
+ });
+
+ it("refines every facet by an embed-scope condition without evicting the unrequested column", () => {
+ // The user page scopes by `User ID` but omits the userId facet; the
+ // condition refines all requested facets and evicts none of them.
+ const plan = planEventFacetQueries({
+ refiningFilter: [USER_SCOPE_BY_LABEL],
+ eagerColumns: EAGER,
+ lazyColumns: [],
+ });
+ expect(plan.bulk.columns).toEqual([...EAGER]);
+ expect(plan.bulk.filter).toEqual([USER_SCOPE_BY_LABEL]);
+ expect(plan.perColumn).toEqual([]);
+ });
+
+ it("gives lazy columns their own self-excluded queries alongside dirty eager facets", () => {
+ const plan = planEventFacetQueries({
+ refiningFilter: [ENV_PROD],
+ eagerColumns: EAGER,
+ lazyColumns: ["userId", "environment"],
+ });
+ // Deduped + sorted: the dirty eager facet and both lazy columns.
+ expect(plan.perColumn).toEqual([
+ { column: "environment", filter: undefined },
+ { column: "userId", filter: [ENV_PROD] },
+ ]);
+ });
+
+ it("supports request-all mode (columns undefined) for unfiltered callers", () => {
+ const plan = planEventFacetQueries({
+ refiningFilter: [],
+ eagerColumns: undefined,
+ lazyColumns: [],
+ });
+ expect(plan.bulk.columns).toBeUndefined();
+ expect(plan.bulk.filter).toBeUndefined();
+ expect(plan.perColumn).toEqual([]);
+ });
+});
diff --git a/web/src/features/events/lib/facet-query-plan.ts b/web/src/features/events/lib/facet-query-plan.ts
new file mode 100644
index 0000000000..1249dada65
--- /dev/null
+++ b/web/src/features/events/lib/facet-query-plan.ts
@@ -0,0 +1,112 @@
+import {
+ eventsTableCols,
+ type FilterState,
+ type TimeFilter,
+} from "@langfuse/shared";
+
+// Pure query planning for the events filter options (LFE-14489): which facet
+// columns share one bulk query, which need a self-excluded per-column query,
+// and the refining filter each carries. useEventsFilterOptions executes the plan.
+
+// Score-catalog columns (score names, not per-value counts) always stay in the
+// bulk: the server never refines them, and the search-bar grammar's score-type
+// routing + AI score-name validation must see the full catalog (LFE-10596).
+const UNREFINED_SCORE_CATALOG_COLUMNS: ReadonlySet<string> = new Set([
+ "scores_avg",
+ "score_categories",
+ "score_booleans",
+ "trace_scores_avg",
+ "trace_score_categories",
+ "trace_score_booleans",
+]);
+
+// Filters can be keyed by column id ("environment") or display name ("User ID",
+// as the embed-scope filters are). Facet columns are always ids β€” a label that
+// slipped past self-exclusion would self-collapse its facet.
+const FACET_COLUMN_ID_BY_NAME_OR_ID: ReadonlyMap<string, string> = new Map(
+ eventsTableCols.flatMap((c) => [
+ [c.id, c.id],
+ [c.name, c.id],
+ ]),
+);
+
+export const resolveEventFacetColumnId = (column: string): string =>
+ FACET_COLUMN_ID_BY_NAME_OR_ID.get(column) ?? column;
+
+const isStartTimeCondition = (f: FilterState[number]): f is TimeFilter =>
+ f.type === "datetime" &&
+ (f.column === "startTime" || f.column === "Start Time");
+
+/**
+ * Split user-authored start-time conditions (e.g. a search-bar `startTime:>…`)
+ * from the refining rest. They must travel via the authoritative
+ * `startTimeFilter` channel β€” the server drops start-time entries from the
+ * participating filter, so leaving them here would silently un-scope the counts.
+ * Non-participating columns (input/output/comment*, positionInTrace) pass
+ * through verbatim; the server omits all counts while one is active.
+ */
+export const splitFacetFilter = (
+ filter: FilterState,
+): { startTimeFilter: TimeFilter[]; refiningFilter: FilterState } => ({
+ startTimeFilter: filter.filter(isStartTimeCondition),
+ refiningFilter: filter.filter((f) => !isStartTimeCondition(f)),
+});
+
+export type FacetQueryPlan<Column extends string = string> = {
+ /** Shared bulk query: clean facets + score catalog, refined by the full
+ * filter. `columns` undefined = request-all (only valid unfiltered). */
+ bulk: {
+ columns: Column[] | undefined;
+ filter: FilterState | undefined;
+ };
+ /** One query per self-excluded facet β€” its own condition removed, so its full
+ * option list survives and the `none of` complement stays computable β€” plus
+ * each lazily-requested column. */
+ perColumn: { column: Column; filter: FilterState | undefined }[];
+};
+
+/**
+ * Partition the requested columns into the bulk and per-column queries, with
+ * each query's refining filter. `refiningFilter` must be start-time-free (see
+ * `splitFacetFilter`); lazy columns are always per-column (own cache entry each).
+ */
+export function planEventFacetQueries<Column extends string>(params: {
+ refiningFilter: FilterState;
+ eagerColumns: readonly Column[] | undefined;
+ lazyColumns: readonly Column[];
+}): FacetQueryPlan<Column> {
+ const { refiningFilter, eagerColumns, lazyColumns } = params;
+
+ const filterFor = (column: Column): FilterState | undefined => {
+ const refined = refiningFilter.filter(
+ (f) => resolveEventFacetColumnId(f.column) !== column,
+ );
+ return refined.length > 0 ? refined : undefined;
+ };
+
+ // Only facets carrying their own condition would self-collapse in the bulk;
+ // a score condition never evicts its (unrefined) catalog column.
+ const selfFilteredColumns = new Set(
+ refiningFilter
+ .map((f) => resolveEventFacetColumnId(f.column))
+ .filter((c) => !UNREFINED_SCORE_CATALOG_COLUMNS.has(c)),
+ );
+
+ const bulkColumns = eagerColumns?.filter((c) => !selfFilteredColumns.has(c));
+ const dirtyEagerColumns =
+ eagerColumns?.filter((c) => selfFilteredColumns.has(c)) ?? [];
+
+ const perColumn = Array.from(
+ new Set<Column>([...lazyColumns, ...dirtyEagerColumns]),
+ )
+ .sort()
+ .map((column) => ({ column, filter: filterFor(column) }));
+
+ return {
+ bulk: {
+ columns: bulkColumns,
+ filter: refiningFilter.length > 0 ? refiningFilter : undefined,
+ },
+ perColumn,
+ };
+}
diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsx
index 0056f0e9e9..dda2076840 100644
--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx
+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx
@@ -470,22 +470,17 @@ const DEFAULT_HOOK_OPTIONS: UseSidebarFilterStateOptions = {
const toUrlFilterQuery = (encoded: string): string =>
encoded.length > MAX_URL_FILTER_QUERY_LENGTH ? "" : encoded;
-export function useSidebarFilterState(
+/**
+ * State half of the sidebar filters: owns the applied FilterState
+ * (URL/session/memory/peek decode + defaults + managed-env policy) and its
+ * writer. Independent of the filter-OPTIONS payload, so a view can read its
+ * applied filters BEFORE fetching options (events facet counts, LFE-14489).
+ */
+export function useSidebarFilterStateCore(
config: FilterConfig,
- options: Record<
- string,
- (string | SingleValueOption)[] | Record<string, string[]> | undefined
- >,
hookOptions: UseSidebarFilterStateOptions = DEFAULT_HOOK_OPTIONS,
) {
- const {
- loading,
- loadingColumns,
- implicitDefaultConfig,
- onExplicitFilterStateChange,
- } = hookOptions;
- const isV4Surface = hookOptions.isV4 ?? false;
- const capture = usePostHogClientCapture();
+ const { implicitDefaultConfig, onExplicitFilterStateChange } = hookOptions;
const stateLocationType = hookOptions.stateLocation;
const peekContext =
stateLocationType === "peekContext" ? hookOptions.context : undefined;
@@ -703,29 +698,6 @@ export function useSidebarFilterState(
const managedEnvironmentColumn =
managedEnvironmentPolicyConfig.managedEnvironmentColumn;
- // Context the pure facet-action functions (lib/sidebar-filter-actions)
- // read: facet/column metadata, the option lists, and β€” only while the
- // managed-environment policy is active β€” the managed column, which gates
- // its explicit enable-all-environments override.
- const actionContext: SidebarFilterActionContext = useMemo(
- () => ({
- facets: config.facets,
- columnDefinitions: config.columnDefinitions,
- options,
- managedEnvironmentColumn:
- managedEnvironmentPolicyConfig.hiddenEnvironments.length > 0
- ? managedEnvironmentColumn
- : undefined,
- }),
- [
- config.facets,
- config.columnDefinitions,
- options,
- managedEnvironmentColumn,
- managedEnvironmentPolicyConfig.hiddenEnvironments,
- ],
- );
-
const effectiveEnvironmentFilterState: FilterState = useMemo(
() =>
buildEffectiveEnvironmentFilter({
@@ -919,6 +891,76 @@ export function useSidebarFilterState(
setStoredFiltersQuery,
]);
+ return {
+ /** Effective applied filters: explicit + defaults + managed-env policy. */
+ filterState,
+ explicitFilterState,
+ setFilterState,
+ expandedState,
+ onExpandedChange,
+ managedEnvironmentColumn,
+ managedEnvironmentPolicyConfig,
+ };
+}
+
+export type SidebarFilterStateCore = ReturnType<
+ typeof useSidebarFilterStateCore
+>;
+
+export type SidebarFilterPresentationOptions = Pick<
+ BaseUseSidebarFilterStateOptions,
+ "loading" | "loadingColumns" | "isV4"
+>;
+
+/**
+ * Presentation half over a core instance: option-aware facet actions,
+ * analytics, and the UIFilter list.
+ */
+export function useSidebarFilterPresentation(
+ core: SidebarFilterStateCore,
+ config: FilterConfig,
+ options: Record<
+ string,
+ (string | SingleValueOption)[] | Record<string, string[]> | undefined
+ >,
+ presentationOptions: SidebarFilterPresentationOptions = {},
+) {
+ const { loading, loadingColumns } = presentationOptions;
+ const isV4Surface = presentationOptions.isV4 ?? false;
+ const capture = usePostHogClientCapture();
+ const {
+ filterState,
+ explicitFilterState,
+ setFilterState,
+ expandedState,
+ onExpandedChange,
+ managedEnvironmentColumn,
+ managedEnvironmentPolicyConfig,
+ } = core;
+
+ // Context the pure facet-action functions (lib/sidebar-filter-actions)
+ // read: facet/column metadata, the option lists, and β€” only while the
+ // managed-environment policy is active β€” the managed column, which gates
+ // its explicit enable-all-environments override.
+ const actionContext: SidebarFilterActionContext = useMemo(
+ () => ({
+ facets: config.facets,
+ columnDefinitions: config.columnDefinitions,
+ options,
+ managedEnvironmentColumn:
+ managedEnvironmentPolicyConfig.hiddenEnvironments.length > 0
+ ? managedEnvironmentColumn
+ : undefined,
+ }),
+ [
+ config.facets,
+ config.columnDefinitions,
+ options,
+ managedEnvironmentColumn,
+ managedEnvironmentPolicyConfig.hiddenEnvironments,
+ ],
+ );
+
// When true, the applied-filter capture inside `updateFilter` is suppressed β€”
// set by `updateOperator`, which funnels through `updateFilter` but must emit
// `filters:facet_operator_toggled` instead of a duplicate `filters:applied`.
@@ -1863,3 +1905,19 @@ export function useSidebarFilterState(
isV4: isV4Surface,
};
}
+
+/**
+ * Core + presentation in one call. Views that need the applied filter state
+ * before fetching options compose the two hooks directly (see EventsTable).
+ */
+export function useSidebarFilterState(
+ config: FilterConfig,
+ options: Record<
+ string,
+ (string | SingleValueOption)[] | Record<string, string[]> | undefined
+ >,
+ hookOptions: UseSidebarFilterStateOptions = DEFAULT_HOOK_OPTIONS,
+) {
+ const core = useSidebarFilterStateCore(config, hookOptions);
+ return useSidebarFilterPresentation(core, config, options, hookOptions);
+}