Skip to content

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

perf(filters): load event filter options lazily, per-facet on demand (LFE-10519) (#14617)

Nikita Kabardin13a33263bece
diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.ts
index 4b26e3bc2e..bc7ec0b4c5 100644
--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts
@@ -665,13 +665,15 @@ describe("Clickhouse Events Repository Test", () => {
columns: ["level"],
});
- expect(options.level.map((level) => level.value)).toContain("WARNING");
- expect(options.name).toEqual([]);
- expect(options.traceTags).toEqual([]);
- expect(options.scores_avg).toEqual([]);
- expect(options.score_categories).toEqual([]);
- expect(options.trace_scores_avg).toEqual([]);
- expect(options.trace_score_categories).toEqual([]);
+ expect(options.level?.map((level) => level.value)).toContain("WARNING");
+ // Unrequested columns are absent (not empty arrays), so the client can
+ // distinguish "loaded, no values" from "not requested yet" for lazy loading.
+ expect(options.name).toBeUndefined();
+ expect(options.traceTags).toBeUndefined();
+ expect(options.scores_avg).toBeUndefined();
+ expect(options.score_categories).toBeUndefined();
+ expect(options.trace_scores_avg).toBeUndefined();
+ expect(options.trace_score_categories).toBeUndefined();
});
});
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 998d132012..eeb0c39425 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -190,6 +190,31 @@ export type EventsTableProps = {
sessionId?: string;
};
+// Build the start-time `FilterState` 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 =>
+ range
+ ? [
+ {
+ column: "startTime",
+ type: "datetime",
+ operator: ">=",
+ value: range.from,
+ },
+ ...(range.to
+ ? [
+ {
+ column: "startTime",
+ type: "datetime",
+ operator: "<=",
+ value: range.to,
+ } as const,
+ ]
+ : []),
+ ]
+ : [];
+
export default function ObservationsEventsTable({
projectId,
userId,
@@ -318,6 +343,12 @@ export default function ObservationsEventsTable({
);
const [refreshTick, setRefreshTick] = useState(0);
+ // Facet options are not "live": the auto-refresh tick must keep updating the
+ // table rows without re-fetching facets (their values don't change tick to
+ // tick). They re-anchor only on a real scope change β€” a new time range or an
+ // explicit refresh β€” tracked by this separate tick, which the auto interval
+ // never bumps.
+ const [filterOptionsRefreshTick, setFilterOptionsRefreshTick] = useState(0);
// Auto-increment refresh tick to force date range recalculation
useEffect(() => {
@@ -330,6 +361,9 @@ export default function ObservationsEventsTable({
const handleRefresh = useCallback(() => {
setRefreshTick((t) => t + 1);
+ // An explicit refresh re-anchors the facets too (and invalidate refetches
+ // whatever is already open); the auto interval above does not.
+ setFilterOptionsRefreshTick((t) => t + 1);
Promise.all([
utils.events.all.invalidate(),
utils.events.countAll.invalidate(),
@@ -345,40 +379,45 @@ export default function ObservationsEventsTable({
return toAbsoluteTimeRange(timeRange) ?? undefined;
}, [timeRange, refreshTick]);
+ // Same absolute range, but anchored to scope changes only (NOT the auto tick),
+ // so opening/keeping a facet open never re-fetches on a refresh interval.
+ const filterOptionsTableDateRange = useMemo(() => {
+ filterOptionsRefreshTick;
+ return toAbsoluteTimeRange(timeRange) ?? undefined;
+ }, [timeRange, filterOptionsRefreshTick]);
+
const dateRange = externalDateRange ?? tableDateRange;
+ const filterOptionsDateRange =
+ externalDateRange ?? filterOptionsTableDateRange;
- const dateRangeFilter: FilterState = dateRange
- ? [
- {
- column: "startTime",
- type: "datetime",
- operator: ">=",
- value: dateRange.from,
- },
- ...(dateRange.to
- ? [
- {
- column: "startTime",
- type: "datetime",
- operator: "<=",
- value: dateRange.to,
- } as const,
- ]
- : []),
- ]
- : [];
+ const dateRangeFilter: FilterState = toStartTimeFilterState(dateRange);
- const oldFilterState = inputFilterState.concat(dateRangeFilter);
+ // 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 = inputFilterState.concat(
+ toStartTimeFilterState(filterOptionsDateRange),
+ );
- // Fetch filter options
- const { filterOptions, isFilterOptionsPending } = useEventsFilterOptions({
+ // 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 queryFilterOptions: UseSidebarFilterStateOptions = useMemo(() => {
const baseOptions = {
loading: isFilterOptionsPending,
+ loadingColumns,
implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
};
@@ -402,7 +441,13 @@ export default function ObservationsEventsTable({
stateLocation: "urlAndSessionStorage",
sessionFilterContextId: projectId,
};
- }, [hideControls, isFilterOptionsPending, peekContext, projectId]);
+ }, [
+ hideControls,
+ isFilterOptionsPending,
+ loadingColumns,
+ peekContext,
+ projectId,
+ ]);
const queryFilter = useSidebarFilterState(
eventsFilterConfig,
@@ -410,6 +455,13 @@ export default function ObservationsEventsTable({
queryFilterOptions,
);
+ // Lazy filter-options: load a facet's values when its sidebar section is
+ // expanded (also covers active filters, which auto-expand on mount). The
+ // request set only grows, so re-collapsing never re-fetches.
+ useEffect(() => {
+ requestColumns(queryFilter.expanded);
+ }, [queryFilter.expanded, requestColumns]);
+
// Grammar search bar: an ADDITIONAL editor that coexists with the facet
// sidebar, and the two stay in sync. Generally available on the v4 events
// tables (no longer a per-user Feature Preview opt-in β€” useSearchBarEnabled()
@@ -1498,7 +1550,9 @@ export default function ObservationsEventsTable({
store={searchBarStore}
commit={searchBarCommit}
observed={observedOptions}
+ erroredColumns={erroredColumns}
onApplyFilters={searchBarApplyFilters}
+ onRequestColumns={requestColumns}
aiDataContext={aiDataContext}
/>
)}
diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.ts
index a888ca0525..9a2b8861f6 100644
--- a/web/src/features/events/hooks/useEventsFilterOptions.ts
+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts
@@ -1,15 +1,120 @@
-import { api, type RouterInputs } from "@/src/utils/api";
-import { useMemo } from "react";
+import { api, type RouterInputs, type RouterOutputs } from "@/src/utils/api";
+import { useCallback, useMemo, useState } from "react";
import { type FilterState, type TimeFilter } from "@langfuse/shared";
type EventFilterOptionColumnsInput =
RouterInputs["events"]["filterOptions"]["columns"];
+// Element type of the tRPC `columns` arg β€” keeps the column lists below in sync
+// with the server enum (a typo is a compile error via `satisfies`).
+type EventFilterOptionColumn =
+ NonNullable<EventFilterOptionColumnsInput>[number];
+
+// The filterOptions payload, keyed by column. Every key is optional: the server
+// returns only the columns that were requested (see eventsService.ts), which is
+// what lets lazy loading tell "loaded, no values" ([]) from "not requested yet"
+// (key absent).
+type FilterOptionsData = RouterOutputs["events"]["filterOptions"];
+
+// Every server-enumerable filter-options column. Used to (a) request all options
+// in non-lazy mode and (b) filter caller-supplied columns down to ones the
+// endpoint actually understands (the sidebar/search bar pass raw facet/field ids,
+// some of which β€” metadata, latency, id β€” have no server-side option list).
+const ALL_EVENT_FILTER_OPTION_COLUMNS = [
+ "providedModelName",
+ "modelId",
+ "name",
+ "promptName",
+ "traceTags",
+ "traceName",
+ "type",
+ "userId",
+ "version",
+ "sessionId",
+ "level",
+ "environment",
+ "experimentDatasetId",
+ "experimentId",
+ "experimentName",
+ "isRootObservation",
+ "toolNames",
+ "calledToolNames",
+ "scores_avg",
+ "score_categories",
+ "trace_scores_avg",
+ "trace_score_categories",
+] as const satisfies readonly EventFilterOptionColumn[];
+
+// Columns loaded eagerly on mount in lazy mode: the sidebar's default-expanded
+// facets (environment/name/type/isRootObservation) plus the search-bar empty-stage
+// suggestion fields (level/type/environment/name). The high-cardinality facets
+// (userId/sessionId, model/prompt/experiment/tool) load only when opened or typed.
+//
+// The four score-NAME columns are eager too. They are cheap (just the distinct
+// score names + their categorical buckets, not per-row data) and drive the
+// grammar's score-type routing: `scoreTypeContextFromObserved` must be populated
+// before the bar lowers a `scores.<name>:5` token, or a categorical numeric-label
+// score (e.g. a 1–5 rating) mis-routes to `scores_avg` and silently empties the
+// table. Keeping them eager restores that pre-lazy invariant.
+const EAGER_EVENT_FILTER_OPTION_COLUMNS = [
+ "environment",
+ "name",
+ "type",
+ "level",
+ "isRootObservation",
+ "scores_avg",
+ "score_categories",
+ "trace_scores_avg",
+ "trace_score_categories",
+] as const satisfies readonly EventFilterOptionColumn[];
+
+const EAGER_COLUMN_SET: ReadonlySet<string> = new Set(
+ EAGER_EVENT_FILTER_OPTION_COLUMNS,
+);
+const VALID_FILTER_OPTION_COLUMNS: ReadonlySet<string> = new Set(
+ ALL_EVENT_FILTER_OPTION_COLUMNS,
+);
+
+const isEventFilterOptionColumn = (
+ column: string,
+): column is EventFilterOptionColumn => VALID_FILTER_OPTION_COLUMNS.has(column);
+
+// 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.
+const FILTER_OPTION_QUERY_OPTIONS = {
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ placeholderData: <T>(prev: T) => prev,
+} as const;
+
+type LazyFilterOptionResult = {
+ data: FilterOptionsData | undefined;
+ isFetching: boolean;
+ isError: boolean;
+};
+
type UseEventsFilterOptionsParams = {
projectId: string;
oldFilterState: FilterState;
isRootObservation?: boolean;
+ /**
+ * Explicit column subset to request (non-lazy). Ignored when `lazy` is set.
+ * Omit to request every column (the default bulk behavior).
+ */
columns?: EventFilterOptionColumnsInput;
+ /**
+ * Lazy mode (v4 events table): request only the eagerly-visible columns up
+ * front and load every other facet on demand via the returned `requestColumns`.
+ * Each on-demand facet is its OWN cached query, so opening a new facet fetches
+ * only that column β€” already-loaded facets are served from cache and never
+ * re-fetched. The sidebar/search bar widen the set when a facet is opened or
+ * typed into.
+ */
+ lazy?: boolean;
};
export function useEventsFilterOptions({
@@ -17,6 +122,7 @@ export function useEventsFilterOptions({
oldFilterState,
isRootObservation,
columns,
+ lazy = false,
}: UseEventsFilterOptionsParams) {
// Extract start time filters for filter options query
const startTimeFilters = useMemo(() => {
@@ -27,35 +133,115 @@ export function useEventsFilterOptions({
) as TimeFilter[];
}, [oldFilterState]);
- // Fetch filter options
- const filterOptions = api.events.filterOptions.useQuery(
- {
+ const baseInput = useMemo(
+ () => ({
projectId,
startTimeFilter:
startTimeFilters.length > 0 ? startTimeFilters : undefined,
isRootObservation,
- columns,
+ }),
+ [projectId, startTimeFilters, 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
+ // it β€” and each column gets its own cached query, so toggling sections open and
+ // closed never re-fetches.
+ const [lazyColumnSet, setLazyColumnSet] = useState<
+ ReadonlySet<EventFilterOptionColumn>
+ >(() => new Set());
+
+ const requestColumns = useCallback(
+ (cols: readonly string[]) => {
+ if (!lazy) return;
+ setLazyColumnSet((prev) => {
+ let next: Set<EventFilterOptionColumn> | null = null;
+ for (const col of cols) {
+ if (
+ isEventFilterOptionColumn(col) &&
+ !EAGER_COLUMN_SET.has(col) &&
+ !prev.has(col)
+ ) {
+ next ??= new Set(prev);
+ next.add(col);
+ }
+ }
+ // Stable identity when nothing was added β†’ no new query.
+ return next ?? prev;
+ });
},
+ [lazy],
+ );
+
+ const lazyColumns = useMemo(
+ () => Array.from(lazyColumnSet).sort(),
+ [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;
+ const eagerQuery = api.events.filterOptions.useQuery(
+ { ...baseInput, columns: eagerColumns },
{
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- // Keep showing previous options while fetching new ones to avoid sidebar flicker
- // TODO: maybe remove b/c unnecessary?
- placeholderData: (prev) => prev,
+ 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.
+ const combineLazy = useCallback(
+ (results: readonly LazyFilterOptionResult[]) => {
+ const data: FilterOptionsData = {};
+ const pendingColumns: string[] = [];
+ const erroredColumns: string[] = [];
+ results.forEach((r, i) => {
+ const column = lazyColumns[i];
+ 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 β€”
+ // symmetric with the (combine-free) eager query.
+ if (r.data) {
+ Object.assign(data, r.data);
+ return;
+ }
+ // No data: a terminal error settles this column to empty; an in-flight
+ // fetch is loading. Tracked PER COLUMN so one facet's error (e.g. a
+ // userId approx_top_k timeout) never blocks loading the others.
+ if (r.isError) {
+ erroredColumns.push(column);
+ } else if (r.isFetching) {
+ pendingColumns.push(column);
+ }
+ });
+ return { data, pendingColumns, erroredColumns };
},
+ [lazyColumns],
+ );
+
+ const lazyResult = api.useQueries(
+ (t) =>
+ lazyColumns.map((column) =>
+ t.events.filterOptions(
+ { ...baseInput, columns: [column] },
+ FILTER_OPTION_QUERY_OPTIONS,
+ ),
+ ),
+ { combine: combineLazy },
+ );
+
+ // Merge the eager payload with every loaded on-demand column.
+ const rawData = useMemo<FilterOptionsData>(
+ () => ({ ...eagerQuery.data, ...lazyResult.data }),
+ [eagerQuery.data, lazyResult.data],
);
// Transform filter options for sidebar
const newFilterOptions = useMemo(() => {
const scoreCategories =
- filterOptions.data?.score_categories?.reduce(
+ rawData.score_categories?.reduce(
(acc, score) => {
acc[score.label] = score.values;
return acc;
@@ -63,37 +249,36 @@ export function useEventsFilterOptions({
{} as Record<string, string[]>,
) ?? undefined;
- const scoresNumeric = filterOptions.data?.scores_avg ?? undefined;
+ const scoresNumeric = rawData.scores_avg ?? undefined;
const traceScoreCategories =
- filterOptions.data?.trace_score_categories?.reduce(
+ rawData.trace_score_categories?.reduce(
(acc, score) => {
acc[score.label] = score.values;
return acc;
},
{} as Record<string, string[]>,
) ?? undefined;
- const traceScoresNumeric =
- filterOptions.data?.trace_scores_avg ?? undefined;
+ const traceScoresNumeric = rawData.trace_scores_avg ?? undefined;
return {
- environment: filterOptions.data?.environment ?? undefined,
- name: filterOptions.data?.name ?? undefined,
- type: filterOptions.data?.type ?? undefined,
- level: filterOptions.data?.level ?? undefined,
- providedModelName: filterOptions.data?.providedModelName ?? undefined,
- modelId: filterOptions.data?.modelId ?? undefined,
- promptName: filterOptions.data?.promptName ?? undefined,
- traceTags: filterOptions.data?.traceTags ?? undefined,
- traceName: filterOptions.data?.traceName ?? undefined,
- userId: filterOptions.data?.userId ?? undefined,
- sessionId: filterOptions.data?.sessionId ?? undefined,
- version: filterOptions.data?.version ?? undefined,
- experimentDatasetId: filterOptions.data?.experimentDatasetId ?? undefined,
- experimentId: filterOptions.data?.experimentId ?? undefined,
- experimentName: filterOptions.data?.experimentName ?? undefined,
- isRootObservation: filterOptions.data?.isRootObservation ?? undefined,
- toolNames: filterOptions.data?.toolNames ?? undefined,
- calledToolNames: filterOptions.data?.calledToolNames ?? undefined,
+ environment: rawData.environment ?? undefined,
+ name: rawData.name ?? undefined,
+ type: rawData.type ?? undefined,
+ level: rawData.level ?? undefined,
+ providedModelName: rawData.providedModelName ?? undefined,
+ modelId: rawData.modelId ?? undefined,
+ promptName: rawData.promptName ?? undefined,
+ traceTags: rawData.traceTags ?? undefined,
+ traceName: rawData.traceName ?? undefined,
+ userId: rawData.userId ?? undefined,
+ sessionId: rawData.sessionId ?? undefined,
+ version: rawData.version ?? undefined,
+ experimentDatasetId: rawData.experimentDatasetId ?? undefined,
+ experimentId: rawData.experimentId ?? undefined,
+ experimentName: rawData.experimentName ?? undefined,
+ isRootObservation: rawData.isRootObservation ?? undefined,
+ toolNames: rawData.toolNames ?? undefined,
+ calledToolNames: rawData.calledToolNames ?? undefined,
toolDefinitions: [],
toolCalls: [],
latency: [],
@@ -110,10 +295,53 @@ export function useEventsFilterOptions({
trace_score_categories: traceScoreCategories,
trace_scores_avg: traceScoresNumeric,
};
- }, [filterOptions.data]);
+ }, [rawData]);
+
+ // Lazy mode: the precise set of requested columns whose options have not yet
+ // arrived (so the sidebar shows a skeleton for exactly those facets, and never
+ // for never-enumerated facets like metadata).
+ //
+ // Each entry is gated on an in-flight fetch: a skeleton means "loading", not
+ // "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 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) {
+ if (data[column] === undefined) pending.add(column);
+ }
+ }
+ return pending;
+ }, [lazy, lazyResult.pendingColumns, isEagerFetching, rawData]);
+
+ // Columns whose fetch terminally errored, per column. Consumers settle these to
+ // the empty state (no skeleton, no perpetual loading row β€” there is no
+ // auto-retry) WITHOUT blocking any other column's on-demand load. The eager
+ // bulk is read directly (no combine); if it fails, its columns β€” which are
+ // never lazily re-requestable β€” settle too.
+ const lazyErroredColumns = lazyResult.erroredColumns;
+ const isEagerError = eagerQuery.isError;
+ const erroredColumns = useMemo<ReadonlySet<string>>(() => {
+ const errored = new Set<string>(lazyErroredColumns);
+ if (isEagerError) {
+ for (const column of EAGER_EVENT_FILTER_OPTION_COLUMNS)
+ errored.add(column);
+ }
+ return errored;
+ }, [lazyErroredColumns, isEagerError]);
return {
filterOptions: newFilterOptions,
- isFilterOptionsPending: filterOptions.isPending,
+ isFilterOptionsPending: eagerQuery.isPending,
+ /** Columns whose fetch terminally errored (per column). Consumers settle these
+ * to the empty state; other columns keep loading normally. */
+ erroredColumns,
+ /** Lazy mode only: columns requested but not yet loaded (per-facet skeletons). */
+ loadingColumns,
+ /** Lazy mode only: widen the requested column set (no-op otherwise). */
+ requestColumns,
};
}
diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.ts
index 752b61badf..f765cf2823 100644
--- a/web/src/features/events/server/eventsService.ts
+++ b/web/src/features/events/server/eventsService.ts
@@ -415,13 +415,18 @@ const toEventFilterValueOptions = (
: options;
};
+// Only emit the columns that were actually requested. Returning every column
+// (with `[]` for the unrequested ones) would make a lazily-loaded facet
+// indistinguishable from a loaded-but-empty one on the client, defeating
+// on-demand loading β€” the FE keys "needs loading" on a column key being absent.
const toEventFilterOptionsByColumn = (
items: EventFilterOptionRow[],
-): EventFilterOptionsByColumn =>
- EVENT_FILTER_OPTION_COLUMNS.reduce((acc, column) => {
+ columns: readonly (keyof EventFilterOptionsByColumn)[],
+): Partial<EventFilterOptionsByColumn> =>
+ columns.reduce((acc, column) => {
acc[column] = toEventFilterValueOptions(items, column);
return acc;
- }, {} as EventFilterOptionsByColumn);
+ }, {} as Partial<EventFilterOptionsByColumn>);
const getEventFilterOptionsScope = (
params: GetObservationsFilterOptionsParams,
@@ -622,19 +627,31 @@ export async function getEventFilterOptions(
.map((score) => score.name),
),
);
- const eventFilterOptionsByColumn =
- toEventFilterOptionsByColumn(eventFilterOptions);
+ const eventFilterOptionsByColumn = toEventFilterOptionsByColumn(
+ eventFilterOptions,
+ eventColumns,
+ );
+ // Only include a score key when its column was requested, so an unrequested
+ // (lazily-loadable) score facet stays absent from the payload rather than
+ // arriving as an empty list (which the client cannot tell from "loaded, no
+ // values"). When everything is requested (the default), all keys are present.
+ // Score names come from the observation-/trace-scoped discovery above so each
+ // column only offers names its filter can match (LFE-10596).
return {
...eventFilterOptionsByColumn,
- scores_avg: shouldLoadScoresAvg
- ? numericScoreNames.map((score) => score.name)
- : [],
- score_categories: shouldLoadScoreCategories ? categoricalScoreNames : [],
- trace_scores_avg: shouldLoadTraceScores ? traceNumericScoreNames : [],
- trace_score_categories: shouldLoadTraceScoreCategories
- ? traceCategoricalScoreColumns
- : [],
+ ...(shouldLoadScoresAvg
+ ? { scores_avg: numericScoreNames.map((score) => score.name) }
+ : {}),
+ ...(shouldLoadScoreCategories
+ ? { score_categories: categoricalScoreNames }
+ : {}),
+ ...(shouldLoadTraceScores
+ ? { trace_scores_avg: traceNumericScoreNames }
+ : {}),
+ ...(shouldLoadTraceScoreCategories
+ ? { trace_score_categories: traceCategoricalScoreColumns }
+ : {}),
};
}
diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsx
index 67d66256cd..451728d2ed 100644
--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx
+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx
@@ -345,6 +345,14 @@ type UpdateFilter = (
type BaseUseSidebarFilterStateOptions = {
loading?: boolean;
implicitDefaultConfig?: ManagedEnvironmentPolicyInput;
+ /**
+ * Precise per-facet loading set (lazy filter-options): exactly the columns
+ * whose options have been requested but not yet arrived. When provided it
+ * drives the facet skeleton instead of the coarse `loading` flag, so a facet
+ * shows a skeleton only while its own options stream in β€” and never for
+ * columns that are not server-enumerated (e.g. metadata).
+ */
+ loadingColumns?: ReadonlySet<string>;
};
export type UseSidebarFilterStateOptions =
@@ -432,7 +440,7 @@ export function useSidebarFilterState(
>,
hookOptions: UseSidebarFilterStateOptions = DEFAULT_HOOK_OPTIONS,
) {
- const { loading, implicitDefaultConfig } = hookOptions;
+ const { loading, loadingColumns, implicitDefaultConfig } = hookOptions;
const stateLocationType = hookOptions.stateLocation;
const peekContext =
stateLocationType === "peekContext" ? hookOptions.context : undefined;
@@ -1158,6 +1166,11 @@ export function useSidebarFilterState(
// Helper to determine if a filter should show loading state
// Only filters that depend on options from the query should show loading
const shouldShowLoading = (facetColumn: string): boolean => {
+ // Lazy filter-options: a precise per-facet set is supplied, so a facet
+ // shows a skeleton iff its own column is still in flight. This avoids the
+ // coarse-flag false positive where a never-enumerated facet (metadata,
+ // whose options are always undefined) would skeleton on every refetch.
+ if (loadingColumns) return loadingColumns.has(facetColumn);
if (!loading) return false;
// Only show loading if the filter depends on options and options are not yet available
// Filters that use options: categorical, keyValue, numericKeyValue, stringKeyValue
@@ -1788,6 +1801,7 @@ export function useSidebarFilterState(
config,
options,
loading,
+ loadingColumns,
filterState,
explicitFilterState,
updateFilter,
diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
index b4e2ccd3d0..40b5b9adfe 100644
--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx
+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
@@ -19,6 +19,7 @@ import { type FilterState } from "@langfuse/shared";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { useQueryProject } from "@/src/features/projects/hooks";
import type { ObservedOptions } from "@/src/features/search-bar/lib/observed-options";
+import { AI_GROUNDING_COLUMNS } from "@/src/features/search-bar/lib/ai-context";
import { SearchComposer } from "@/src/features/search-bar/components/SearchComposer";
import { SearchBarAiPrompt } from "@/src/features/search-bar/components/SearchBarAiPrompt";
import { SearchBarStoreProvider } from "@/src/features/search-bar/store/SearchBarStoreProvider";
@@ -29,19 +30,31 @@ export function EventsSearchBarRow({
store,
commit,
observed,
+ erroredColumns,
onApplyFilters,
+ onRequestColumns,
aiDataContext,
}: {
projectId: string;
store: SearchBarStore;
commit: () => string | null;
observed: ObservedOptions | undefined;
+ /** Columns whose lazy fetch terminally errored β€” value-stage loading settles to
+ * empty (per column) instead of pinning, matching the sidebar's settled-error
+ * state, without blocking other columns. */
+ erroredColumns?: ReadonlySet<string>;
/**
* Applies AI-generated filters (apply-immediately); the bar re-derives them.
* Preserves filters the grammar can't represent (no-silent-drop contract) β€”
* comes from `useEventsSearchBar.applyFilters`, not a raw `setFilterState`.
*/
onApplyFilters: (filters: FilterState) => void;
+ /**
+ * Lazy filter-options: widen the requested column set on demand. Threaded to
+ * the composer (request a field's values when typed) and fired on Ask AI open
+ * (request the grounding columns so the prompt sees real values).
+ */
+ onRequestColumns?: (columns: readonly string[]) => void;
/** Project data context (observed values + metadata keys + result count) for
* the AI prompt β€” built by EventsTable from filterOptions + visible rows. */
aiDataContext?: string;
@@ -54,7 +67,12 @@ export function EventsSearchBarRow({
const aiAvailable =
isLangfuseCloud && Boolean(organization?.aiFeaturesEnabled);
- const activateAi = React.useCallback(() => setAiOpen(true), []);
+ const activateAi = React.useCallback(() => {
+ // Ground the model on real project values: lazily request the AI columns so
+ // they are loaded by the time the user submits a prompt.
+ onRequestColumns?.(AI_GROUNDING_COLUMNS);
+ setAiOpen(true);
+ }, [onRequestColumns]);
return (
<div className="min-w-0 px-2 pt-2 pb-1">
@@ -71,7 +89,9 @@ export function EventsSearchBarRow({
<SearchComposer
projectId={projectId}
observed={observed}
+ erroredColumns={erroredColumns}
onActivateAi={aiAvailable ? activateAi : undefined}
+ onRequestColumns={onRequestColumns}
/>
</SearchBarStoreProvider>
)}
diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsx
index 2041dd2a0f..864f3b070a 100644
--- a/web/src/features/search-bar/components/SearchComposer.tsx
+++ b/web/src/features/search-bar/components/SearchComposer.tsx
@@ -286,13 +286,25 @@ function useLatest<T>(value: T) {
export function SearchComposer({
projectId,
observed,
+ erroredColumns,
onActivateAi,
+ onRequestColumns,
}: {
projectId: string;
/** Observed facet values for value suggestions; undefined = loading. */
observed: ObservedOptions | undefined;
+ /** Columns whose lazy fetch terminally errored β€” settle the value-stage
+ * loading row to empty (per column) instead of pinning it (matches the
+ * sidebar), without blocking other columns from loading. */
+ erroredColumns?: ReadonlySet<string>;
/** When set, a clickable "Ask AI" button is shown to build / refine filters. */
onActivateAi?: () => void;
+ /**
+ * Lazy filter-options: request a field's observed values on demand when the
+ * caret enters its value stage (e.g. typing `userId:`). No-op unless lazy
+ * loading is wired by the host table.
+ */
+ onRequestColumns?: (columns: readonly string[]) => void;
}) {
const storeApi = useSearchBarStoreApi();
const commitToFilterState = useSearchBarCommit();
@@ -353,10 +365,20 @@ export function SearchComposer({
input: draft,
caret: Math.min(caret, draft.length),
observed,
+ erroredColumns,
recents,
currentQueryText: draft,
})
: null;
+ // Lazy filter-options: when the current completion stage needs option columns
+ // that have not loaded yet, ask the host table to fetch them. Keyed on the
+ // joined column list so it fires once per distinct need, not every keystroke.
+ const requestColumnsKey = plan?.requestColumns?.join(",") ?? "";
+ React.useEffect(() => {
+ if (!onRequestColumns || requestColumnsKey.length === 0) return;
+ onRequestColumns(requestColumnsKey.split(","));
+ }, [requestColumnsKey, onRequestColumns]);
+
const options = flattenOptions(plan);
// Highlight policy: Enter only picks what typing narrowed. Explicit user
// highlights (arrows/hover) always win; otherwise only plans that completed
diff --git a/web/src/features/search-bar/lib/ai-context.ts b/web/src/features/search-bar/lib/ai-context.ts
index bccddba70f..8c97af752c 100644
--- a/web/src/features/search-bar/lib/ai-context.ts
+++ b/web/src/features/search-bar/lib/ai-context.ts
@@ -27,6 +27,13 @@ const VALUE_COLUMNS: Array<{ col: string; label: string }> = [
{ col: "trace_score_categories", label: "traceScores.<name> (categorical)" },
];
+// Filter-options columns the AI prompt grounds on (lazy mode: requested when
+// Ask AI opens so the model sees real values). Excludes high-cardinality ids by
+// construction β€” `VALUE_COLUMNS` already omits userId/sessionId/id.
+export const AI_GROUNDING_COLUMNS: readonly string[] = VALUE_COLUMNS.map(
+ (c) => c.col,
+);
+
const MAX_VALUES_PER_COL = 25;
const MAX_METADATA_KEYS = 30;
const MAX_VALUE_LEN = 40;
diff --git a/web/src/features/search-bar/lib/completions.clienttest.ts b/web/src/features/search-bar/lib/completions.clienttest.ts
index 11631bbfba..aaf39b85fc 100644
--- a/web/src/features/search-bar/lib/completions.clienttest.ts
+++ b/web/src/features/search-bar/lib/completions.clienttest.ts
@@ -260,7 +260,14 @@ describe("planInputCompletions", () => {
// The parser resolves tracescore./tracescores./trace_scores.; each must also
// produce the score-name dropdown, or that spelling parses but suggests
// nothing. (The singular form was previously missing from PATH_PREFIXES.)
- const observed = { ...OBSERVED, trace_scores_avg: [{ value: "nps" }] };
+ // Both trace score-name columns are requested + returned together, so model
+ // the categorical one as loaded-but-empty (lazy mode keys loading on column
+ // presence, not value count).
+ const observed = {
+ ...OBSERVED,
+ trace_scores_avg: [{ value: "nps" }],
+ trace_score_categories: [],
+ };
for (const prefix of ["tracescore.", "tracescores.", "trace_scores."]) {
const p = plan(prefix, prefix.length, { observed });
const labels = flattenOptions(p).map((o) => o.label);
@@ -546,6 +553,92 @@ describe("planInputCompletions", () => {
expect(p?.loading).toBe(true);
});
+ describe("lazy filter-options (per-field on-demand loading)", () => {
+ // observed is loaded for some columns but the typed field's column is absent
+ // (not yet requested/streamed in). Distinct from observed === undefined.
+ it("requests an option field's column and shows loading when its values are absent", () => {
+ const p = plan("userId:", 7, { observed: OBSERVED });
+ expect(p?.stage).toBe("value");
+ expect(p?.loading).toBe(true);
+ expect(p?.requestColumns).toEqual(["userId"]);
+ expect(flattenOptions(p)).toHaveLength(0);
+ });
+
+ it("shows values (no loading, no request) once the column is present β€” even when empty", () => {
+ const present = plan("userId:", 7, {
+ observed: { ...OBSERVED, userId: [{ value: "u-1" }] },
+ });
+ expect(present?.loading).toBe(false);
+ expect(present?.requestColumns).toBeUndefined();
+ expect(flattenOptions(present).map((o) => o.label)).toContain("u-1");
+
+ // Loaded-but-empty ([] present) is NOT loading β€” it offers no values (a
+ // bare `userId:` with no matches yields no popover at all).
+ const empty = plan("userId:", 7, {
+ observed: { ...OBSERVED, userId: [] },
+ });
+ expect(empty?.loading).not.toBe(true);
+ expect(empty?.requestColumns).toBeUndefined();
+ });
+
+ it("never lazy-loads a textSearch field with no server option list (id)", () => {
+ // `id` is textSearch + suggestObservedValues but has no filter-options
+ // column, so it must not show an endless loading row or request a column.
+ const p = plan("id:abc", 6, { observed: OBSERVED });
+ expect(p?.loading).toBe(false);
+ expect(p?.requestColumns).toBeUndefined();
+ });
+
+ it("requests both score-name columns and shows loading on a score path", () => {
+ const p = plan("scores.", 7, {
+ observed: { level: [{ value: "ERROR" }] },
+ });
+ expect(p?.loading).toBe(true);
+ expect(p?.requestColumns).toEqual(["scores_avg", "score_categories"]);
+ });
+
+ it("requests trace score-name columns while typing a trace score value", () => {
+ const p = plan("traceScores.nps:", 16, {
+ observed: { level: [{ value: "ERROR" }] },
+ });
+ expect(p?.loading).toBe(true);
+ expect(p?.requestColumns).toEqual([
+ "trace_scores_avg",
+ "trace_score_categories",
+ ]);
+ });
+
+ // A column whose fetch terminally errored settles to the empty state (no
+ // loading row, no further request) β€” matching the sidebar β€” since there is no
+ // auto-retry. Threaded per column via `erroredColumns`.
+ it("settles an errored column to empty (no loading, no request)", () => {
+ const field = plan("userId:", 7, {
+ observed: OBSERVED,
+ erroredColumns: new Set(["userId"]),
+ });
+ expect(field?.loading).not.toBe(true);
+ expect(field?.requestColumns).toBeUndefined();
+
+ const score = plan("scores.", 7, {
+ observed: { level: [{ value: "ERROR" }] },
+ erroredColumns: new Set(["scores_avg", "score_categories"]),
+ });
+ expect(score?.loading).not.toBe(true);
+ expect(score?.requestColumns).toBeUndefined();
+ });
+
+ // One column's error must NOT block loading another (per-column, not global):
+ // a userId timeout still lets sessionId load on demand.
+ it("still loads a different column when an unrelated one errored", () => {
+ const p = plan("sessionId:", 10, {
+ observed: OBSERVED,
+ erroredColumns: new Set(["userId"]),
+ });
+ expect(p?.loading).toBe(true);
+ expect(p?.requestColumns).toEqual(["sessionId"]);
+ });
+ });
+
it("never suggests the OR keyword between filters", () => {
const p = plan("O", 1);
const operators = flattenOptions(p).filter((o) => o.kind === "operator");
diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.ts
index 767a7add8a..c1080406f1 100644
--- a/web/src/features/search-bar/lib/completions.ts
+++ b/web/src/features/search-bar/lib/completions.ts
@@ -82,6 +82,13 @@ export type CompletionPlan = {
sections: CompletionSection[];
/** Value stage waiting on observed values (popover shows a loading row). */
loading: boolean;
+ /**
+ * Lazy filter-options: the option columns this stage needs but does not yet
+ * have in `observed`. The composer relays these to the table so it requests
+ * just those facets on demand (e.g. typing `userId:` loads the userId values).
+ * Always valid filter-options column ids; empty/absent when nothing is needed.
+ */
+ requestColumns?: readonly string[];
/** Defaults to false; useful for incomplete grouped value entry. */
keepOpenOnPick?: boolean;
/**
@@ -505,6 +512,9 @@ type ValueStageInput = {
typed: string;
valuePrefix: string;
observed: ObservedOptions | undefined;
+ /** Columns whose lazy fetch terminally errored β€” settle those to empty (not
+ * loading), per column, without blocking others. */
+ erroredColumns?: ReadonlySet<string>;
/** Whole-token span, for rewrites that replace the entire `key:value`. */
tokenSpan: { from: number; to: number };
/** The token carries a leading `-` (a negated filter). Scope rewrites must be
@@ -514,10 +524,31 @@ type ValueStageInput = {
};
/** Sections for the caret-in-value context, or null when free-form entry. */
-function valueStageSections(
- input: ValueStageInput,
-): { sections: CompletionSection[]; loading: boolean } | null {
- const { ref, typed, valuePrefix, observed, tokenSpan, negated } = input;
+function valueStageSections(input: ValueStageInput): {
+ sections: CompletionSection[];
+ loading: boolean;
+ requestColumns?: readonly string[];
+} | null {
+ const {
+ ref,
+ typed,
+ valuePrefix,
+ observed,
+ erroredColumns,
+ tokenSpan,
+ negated,
+ } = input;
+
+ // A loadable option column is "pending" when its key is absent from the
+ // observed map (lazy mode: requested but not yet streamed in). An empty list
+ // ([]) means loaded-but-no-values, which is NOT loading. `observed` itself
+ // being undefined is the initial bulk-load β€” everything is pending.
+ // A column whose fetch terminally errored is never pending: it settles to the
+ // empty state (no loading row, no further request) exactly like the sidebar
+ // facet β€” but PER COLUMN, so a different column can still load on demand.
+ const columnPending = (column: string): boolean =>
+ !erroredColumns?.has(column) &&
+ (observed === undefined || !(column in observed));
// An operator prefix was already typed: the rest is free-form entry.
if (valuePrefix.length > 0) return null;
@@ -560,11 +591,19 @@ function valueStageSections(
}
case "scores": {
- if (observed === undefined) return { sections: [], loading: true };
const numericColumn =
ref.level === "trace" ? "trace_scores_avg" : "scores_avg";
const categoricalColumn =
ref.level === "trace" ? "trace_score_categories" : "score_categories";
+ // Routing a `scores.<name>:` value needs both score-name columns; request
+ // and show a loading row while either is still streaming in.
+ if (columnPending(numericColumn) || columnPending(categoricalColumn)) {
+ return {
+ sections: [],
+ loading: true,
+ requestColumns: [numericColumn, categoricalColumn],
+ };
+ }
// Quoted for the example shown in the compare-op tooltip β€” a spaced score
// name must read as `scores."Rouge Score":>0.8`, not the unparsable bare
// form. (The data lookups above use the unquoted column names.)
@@ -673,6 +712,16 @@ function valueStageSections(
// Observed-value picker: exactOption/arrayOption fields, plus textSearch
// fields flagged `suggestObservedValues` (id/name β€” they search as
// substring but still suggest existing values).
+ // Lazy mode: an option-backed field (exactOption/arrayOption) whose values
+ // have not loaded yet shows a loading row and requests its column. Its `id`
+ // IS the filter-options column id. textSearch fields (id/name) are not
+ // lazily loaded β€” `name` is eager and `id` has no server option list β€” so
+ // they fall through to the picker, which is empty when nothing is observed.
+ const isOptionColumn =
+ f.syncMode === "exactOption" || f.syncMode === "arrayOption";
+ if (isOptionColumn && columnPending(f.id)) {
+ return { sections: [], loading: true, requestColumns: [f.id] };
+ }
if (observed === undefined) return { sections: [], loading: true };
const all = observedValues(observed, f.id).map((o) => ({
id: `value:${o.value}`,
@@ -764,6 +813,14 @@ export type InputCompletionContext = {
caret: number;
/** Observed facet values; undefined = still loading. */
observed: ObservedOptions | undefined;
+ /**
+ * Columns whose lazy filter-options fetch terminally errored. For those the
+ * planner suppresses the "Loading values…" row and the on-demand request, so a
+ * failed fetch settles to the empty state (matching the sidebar's per-column
+ * skeleton) instead of pinning loading forever with no auto-retry β€” but PER
+ * COLUMN, so an unrelated column can still load on demand.
+ */
+ erroredColumns?: ReadonlySet<string>;
recents: string[];
/** Full committed/draft query text (recents identical to it are hidden). */
currentQueryText: string;
@@ -931,6 +988,30 @@ export function planInputCompletions(
// Dot paths (metadata./scores./traceScores.) suggest observed keys.
const path = pathKindOf(keyPart);
if (path !== null) {
+ // Score-name suggestions need both score-name columns; request and show a
+ // loading row while they stream in (lazy mode). Metadata keys are not
+ // server-enumerated, so there is nothing to request there.
+ if (path.kind.canonical !== "metadata.") {
+ const numericColumn =
+ path.kind.level === "trace" ? "trace_scores_avg" : "scores_avg";
+ const categoricalColumn =
+ path.kind.level === "trace"
+ ? "trace_score_categories"
+ : "score_categories";
+ const scorePending = (column: string): boolean =>
+ !ctx.erroredColumns?.has(column) &&
+ (ctx.observed === undefined || !(column in ctx.observed));
+ if (scorePending(numericColumn) || scorePending(categoricalColumn)) {
+ return {
+ stage: "field",
+ from: bodyStart,
+ to,
+ loading: true,
+ sections: [],
+ requestColumns: [numericColumn, categoricalColumn],
+ };
+ }
+ }
const { title, options } = keyPathOptions(
path.kind,
path.typedKey,
@@ -1101,6 +1182,7 @@ export function planInputCompletions(
typed,
valuePrefix,
observed: ctx.observed,
+ erroredColumns: ctx.erroredColumns,
tokenSpan: { from: start, to: term?.to ?? caret },
negated,
});
@@ -1112,6 +1194,9 @@ export function planInputCompletions(
to: segTo,
loading: true,
sections: [],
+ ...(staged.requestColumns
+ ? { requestColumns: staged.requestColumns }
+ : {}),
...groupedPlanAttrs,
};
}