πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(traces): show approximate row count in the traces table (LFE-11057) (#15517)
Nikita Kabardinf1a691835f68
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-filter-options.ts b/packages/shared/src/server/queries/clickhouse-sql/event-filter-options.tsindex f32d3193ff..239f507b8a 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-filter-options.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-filter-options.ts@@ -12,6 +12,10 @@ import { buildEventsObservationRowSelection } from "./events-observation-row-selimport { createFilterFromFilterState } from "./factory";export const EVENTS_FILTER_OPTION_TOP_N = 1000;++// Sentinel "column" carrying the approx total observation count in the facet result.+export const EVENTS_APPROX_TOTAL_COUNT_MARKER = "__approxTotalCount__";+const EVENTS_FILTER_OPTION_TOP_K_MAX_N = 65_536;type EventFilterOptionSort = "countDesc" | "alpha" | "booleanAsc";@@ -358,6 +362,8 @@ export const buildEventsFilterOptionsForColumnsQuery = (params: {columns: readonly EventFilterOptionColumn[];limit: number;scope?: EventFilterOptionScope;+ // approx total = uniq(span_id) over the bulk scan's full-filter WHERE; re-verify if the scan ever drops predicates+ includeApproxCount?: boolean;}): { query: string; params: Record<string, unknown> } | null => {const columns = uniqueEventFilterOptionColumns(params.columns);if (columns.length === 0 || params.limit <= 0) {@@ -371,8 +377,11 @@ export const buildEventsFilterOptionsForColumnsQuery = (params: {filter: params.filter,});+ const includeApproxTotal = params.includeApproxCount === true;+aggregatedOptionsBuilder.selectRaw(...columns.map(optionTopKSelectExpression),+ ...(includeApproxTotal ? ["uniq(e.span_id) AS approx_total_count"] : []),);if (params.scope) {@@ -384,6 +393,11 @@ export const buildEventsFilterOptionsForColumnsQuery = (params: {const { query: aggregatedOptionsQuery, params: aggregatedOptionsParams } =aggregatedOptionsBuilder.buildWithParams();+ // Approx total rides one extra sentinel row so the result shape stays {column, value, count}.+ const approxTotalCountRow = includeApproxTotal+ ? `,\n [tuple('${EVENTS_APPROX_TOTAL_COUNT_MARKER}', '', toUInt64(approx_total_count), toInt64(0))]`+ : "";+const query = `WITH aggregated_options AS (${aggregatedOptionsQuery}@@ -391,7 +405,7 @@ ${aggregatedOptionsQuery}option_rows AS (SELECTarrayJoin(arrayConcat(- ${columns.map(optionRowsArrayExpression).join(",\n ")}+ ${columns.map(optionRowsArrayExpression).join(",\n ")}${approxTotalCountRow})) AS optionFROM aggregated_options)diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex 1852adc6e1..0d1909905a 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -75,6 +75,7 @@ export {buildEventsFilterOptionColumnQuery,buildEventsFilterOptionsForColumnsQuery,EVENTS_FILTER_OPTION_TOP_N,+ EVENTS_APPROX_TOTAL_COUNT_MARKER,normalizeEventFilterOptionColumn,type EventFilterOptionRow,type EventFilterOptionColumn,diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex d16a814a68..7a5fe16b28 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -2029,6 +2029,7 @@ const queryEventsFilterOptionsForColumns = async (params: {columns: readonly EventFilterOptionColumn[];limit: number;scope?: EventFilterOptionScope;+ includeApproxCount?: boolean;}) => {const queryWithParams = buildEventsFilterOptionsForColumnsQuery({projectId: params.projectId,@@ -2036,6 +2037,7 @@ const queryEventsFilterOptionsForColumns = async (params: {columns: params.columns,limit: params.limit,scope: params.scope,+ includeApproxCount: params.includeApproxCount,});if (!queryWithParams) {@@ -2075,6 +2077,7 @@ export const getEventsFilterOptionsForColumns = async (params: {columns: readonly EventFilterOptionColumn[];topN?: number;scope?: EventFilterOptionScope;+ includeApproxCount?: boolean;}) =>queryEventsFilterOptionsForColumns({...params,diff --git a/web/src/components/table/data-table-pagination.tsx b/web/src/components/table/data-table-pagination.tsxindex 5ce62c3d91..2497d929db 100644--- a/web/src/components/table/data-table-pagination.tsx+++ b/web/src/components/table/data-table-pagination.tsx@@ -17,6 +17,13 @@ import {import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import Spinner from "@/src/components/design-system/Spinner/Spinner";import { Input } from "@/src/components/ui/input";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { compactNumberFormatter } from "@/src/utils/numbers";import { useEffect, useState } from "react";interface DataTablePaginationProps<TData> {@@ -25,6 +32,13 @@ interface DataTablePaginationProps<TData> {paginationOptions?: number[];hideTotalCount?: boolean;canJumpPages?: boolean; // if we need a cursor (last_item_id), we can't jump pages+ // Approx count for the "Total" footer; undefined = no footer (opt-in).+ approxTotalCount?: number | null;+ isApproxTotalCountLoading?: boolean;+ /** The estimate over-counts (non-native filters dropped) β mark it partial. */+ approxTotalCountIsPartialScope?: boolean;+ /** Cursor pagination: whether another page exists after the current one. */+ hasNextPage?: boolean;}export function DataTablePagination<TData>({@@ -33,9 +47,28 @@ export function DataTablePagination<TData>({paginationOptions = [10, 20, 30, 40, 50],hideTotalCount = false,canJumpPages = true,+ approxTotalCount,+ isApproxTotalCountLoading = false,+ approxTotalCountIsPartialScope = false,+ hasNextPage,}: DataTablePaginationProps<TData>) {const capture = usePostHogClientCapture();+ // Last page shows the exact loaded-row total; multi-page shows "Total β X".+ const totalFooterEnabled =+ approxTotalCount !== undefined || isApproxTotalCountLoading;+ const paginationState = table.getState().pagination;+ const loadedRowCount = table.getRowModel().rows.length;+ const isInitialTotalLoading = isLoading && loadedRowCount === 0;+ // hasNextPage is authoritative for cursor tables; fall back to the table's signal.+ const morePagesExist =+ (hasNextPage ?? table.getCanNextPage()) && !isInitialTotalLoading;+ const exactTotal =+ paginationState.pageIndex * paginationState.pageSize + loadedRowCount;+ const showApproxTotal = totalFooterEnabled && morePagesExist;+ const showExactTotal =+ totalFooterEnabled && !morePagesExist && !isInitialTotalLoading;+const currentPage = table.getState().pagination.pageIndex + 1;const [inputState, setInputState] = useState<number | string>(currentPage);@@ -81,6 +114,52 @@ export function DataTablePagination<TData>({{table.getFilteredRowModel().rows.length} row(s) selected. */}</div><div className="flex flex-wrap items-center space-x-6 lg:space-x-8">+ {showExactTotal ? (+ // Result fits on the loaded page(s) β the total is exact, no estimate.+ <span className="text-muted-foreground hidden text-sm font-normal whitespace-nowrap md:inline-flex md:items-center">+ Total {compactNumberFormatter(exactTotal)}+ </span>+ ) : showApproxTotal ? (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="text-muted-foreground hidden text-sm font-normal whitespace-nowrap md:inline-flex md:items-center">+ Total β + {approxTotalCount != null ? (+ compactNumberFormatter(approxTotalCount)+ ) : (+ <span className="inline-flex align-middle">+ <Spinner size="xxs" variant="muted" display="inline" />+ </span>+ )}+ {approxTotalCountIsPartialScope &&+ approxTotalCount != null && (+ // Marks that the estimate ignores some filters (can exceed row count).+ <span className="text-muted-foreground/70 ml-0.5 align-super text-[0.65rem] leading-none">+ *+ </span>+ )}+ </span>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs font-normal">+ {approxTotalCountIsPartialScope ? (+ <>+ Approximate count over the active column filters and time+ range only. It excludes full-text search, score, and comment+ filters, so it can be noticeably higher than the number of+ matching rows.+ </>+ ) : (+ <>+ Approximate number of matching rows for the active filters+ and time range, estimated with ClickHouse's HyperLogLog+ (typically within a few percent of the true count).+ </>+ )}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ ) : null}<div className="flex items-center space-x-2"><p className="text-sm font-bold whitespace-nowrap md:hidden">Rows</p><p className="hidden text-sm font-bold whitespace-nowrap md:block">diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsxindex bc7da6a4d0..b2945319bd 100644--- a/web/src/components/table/data-table.tsx+++ b/web/src/components/table/data-table.tsx@@ -68,6 +68,22 @@ interface DataTableProps<TData, TValue> {options?: number[];hideTotalCount?: boolean;canJumpPages?: boolean;+ /**+ * Approximate row/entity count matching the active filters. Rendered near+ * the pagination controls, but ONLY when the result set spans more than one+ * page: a single (last) page shows the EXACT total derived from the loaded+ * rows instead (no "β"). Distinct from `totalCount` (which drives page-count+ * math): a cheap estimate shown for context only. `null` while loading.+ */+ approxTotalCount?: number | null;+ isApproxTotalCountLoading?: boolean;+ /**+ * True when the approximate count dropped non-native filters (score/comment/+ * input-output/full-text search) and so over-counts vs the visible rows.+ * The footer then marks the estimate partial-scope and drops the+ * "within a few percent" tooltip.+ */+ approxTotalCountIsPartialScope?: boolean;};rowSelection?: RowSelectionState;setRowSelection?: OnChangeFn<RowSelectionState>;@@ -585,6 +601,12 @@ export function DataTable<TData extends object, TValue>({paginationOptions={pagination.options}hideTotalCount={pagination.hideTotalCount}canJumpPages={pagination.canJumpPages}+ approxTotalCount={pagination.approxTotalCount}+ isApproxTotalCountLoading={pagination.isApproxTotalCountLoading}+ approxTotalCountIsPartialScope={+ pagination.approxTotalCountIsPartialScope+ }+ hasNextPage={pagination.hasNextPage}/></div>) : null}diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 855ffd1989..f7424f3bb6 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -415,6 +415,8 @@ export default function ObservationsEventsTable({Promise.all([utils.events.all.invalidate(),utils.events.countAll.invalidate(),+ // Invalidate filterOptions too so the "Total β X" count refreshes on the auto tick (re-anchors facets as a side effect).+ utils.events.filterOptions.invalidate(),utils.dashboard.executeQuery.invalidate(),]);}, [utils]);@@ -432,8 +434,7 @@ export default function ObservationsEventsTable({]);}, [utils]);- // Auto-refresh runs the tick-safe set (rows + chart), NOT the facet- // re-anchor β otherwise every tick re-issues facet queries for open columns.+ // Auto-refresh runs handleAutoRefresh (rows + chart + the "Total β X" filter-options scan).useEffect(() => {if (!refreshInterval) return;const id = setInterval(() => {@@ -615,6 +616,9 @@ export default function ObservationsEventsTable({const {filterOptions,isFilterOptionsPending,+ approxTotalCount,+ isApproxTotalCountLoading,+ approxTotalCountIsPartialScope,erroredColumns,loadingColumns,requestColumns,@@ -622,9 +626,16 @@ export default function ObservationsEventsTable({projectId,startTimeFilter: facetStartTimeFilter,refiningFilter: facetRefiningFilter,+ // "Total β X" rides the facet scan (uniq(span_id) over facetRefiningFilter); skip for embedded/preview tables.+ includeApproxCount: !limitRows,lazy: true,});+ // Partial scope (over-counts) when the server dropped filters (input/output/comment) or a full-text search is active.+ const approxTotalCountIsPartial =+ approxTotalCountIsPartialScope ||+ Boolean(searchQuery && searchQuery.trim().length > 0);+const queryFilter = useSidebarFilterPresentation(filterCore,eventsFilterConfig,@@ -770,15 +781,7 @@ export default function ObservationsEventsTable({// rest as "not applied" (see chartFilterExclusions below).const chartEnabled = !hideControls && !userId && !sessionId;- // The outlier strip additionally hides on prompt-version-scoped tables:- // `promptVersion` is a page-scope prop the aggregate query cannot express- // (number filter, not a forwardable dimension), and unlike sidebar facets it- // has no "not applied" affordance β the strip would silently aggregate- // across ALL versions while the table shows one. (`promptName` forwards.)- // External state pins also disqualify it: the strip's drill-in writes the- // URL range, which a table on externalDateRange would ignore β chart and- // table would silently diverge. (No current surface combines these with- // chartEnabled; this encodes the invariant for future mounts.)+ // Hide the strip where it would silently diverge from the table: prompt-version scope (not forwardable, no "not applied" affordance) or external date/filter pins.const outlierStripEnabled =chartEnabled &&promptVersion === undefined &&@@ -932,6 +935,8 @@ export default function ObservationsEventsTable({onSettled: () => {utils.events.all.invalidate();utils.events.countAll.invalidate();+ // Refresh filterOptions so the "Total β X" count updates after a delete.+ utils.events.filterOptions.invalidate();utils.traces.all.invalidate();},});@@ -2298,6 +2303,11 @@ export default function ObservationsEventsTable({hasNextPage: hasMore,hideTotalCount: true,canJumpPages: false,+ // Approx observation count ("Total β X"), rides the filter-options scan (async).+ approxTotalCount,+ isApproxTotalCountLoading,+ approxTotalCountIsPartialScope:+ approxTotalCountIsPartial,onChange: (updater) => {const newState =typeof updater === "function"diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.tsindex ce75a90bbf..dd1b21c963 100644--- a/web/src/features/events/hooks/useEventsFilterOptions.ts+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts@@ -117,6 +117,13 @@ type UseEventsFilterOptionsParams = {* 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;+ /**+ * When true, the eager bulk query also returns `approxTotalCount` β the+ * approximate observation count matching the refined filter, via `uniq(span_id)`+ * riding the SAME bulk facet scan (its WHERE already applies `refiningFilter`+ * post-LFE-14489). Set only on the count-bearing table, not per-column.+ */+ includeApproxCount?: boolean;isRootObservation?: boolean;/** Explicit column subset (non-lazy; ignored when `lazy`). Omit to request* all β request-all cannot self-exclude, so only valid unfiltered. */@@ -136,6 +143,7 @@ export function useEventsFilterOptions({projectId,startTimeFilter,refiningFilter = EMPTY_FILTER_STATE,+ includeApproxCount = false,isRootObservation,columns,lazy = false,@@ -212,12 +220,15 @@ export function useEventsFilterOptions({[splitFilter.refiningFilter, lazy, columns, lazyColumns],);- // Eager bulk query: one ClickHouse scan for the plan's shared columns.+ // 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.const eagerQuery = api.events.filterOptions.useQuery({...baseInput,filter: plan.bulk.filter,columns: plan.bulk.columns,+ includeApproxCount,},{trpc: { context: { skipBatch: true } },@@ -232,7 +243,12 @@ export function useEventsFilterOptions({const perColumnPlan = plan.perColumn;const combineLazy = useCallback((results: readonly LazyFilterOptionResult[]) => {- const data: FilterOptionsData = {};+ // approxTotalCount / partial-scope are read from the eager query only;+ // lazy responses carry defaults and this accumulator never surfaces them.+ const data: FilterOptionsData = {+ approxTotalCount: null,+ approxTotalCountIsPartial: false,+ };const pendingColumns: string[] = [];const erroredColumns: string[] = [];results.forEach((r, i) => {@@ -384,9 +400,29 @@ export function useEventsFilterOptions({return errored;}, [lazyErroredColumns, isEagerError, bulkColumns]);+ // Approximate total observation count ("Total β X"). Read from the eager+ // query only β lazy per-column responses omit the count and must not clobber+ // it. `null` until the first bulk response resolves.+ const approxTotalCount = eagerQuery.data?.approxTotalCount ?? null;+ const isApproxTotalCountLoading =+ includeApproxCount && approxTotalCount === null && eagerQuery.isFetching;+ // The bulk scan honours the refining filter (incl. scores) but the server+ // omits input/output/comment filters, so the count over-counts when one is+ // active. Full-text search isn't part of this query β callers OR in their+ // own searchQuery signal.+ const approxTotalCountIsPartialScope =+ eagerQuery.data?.approxTotalCountIsPartial ?? false;+return {filterOptions: newFilterOptions,isFilterOptionsPending: eagerQuery.isPending,+ /** Approximate total observation count matching the refined filter, or null. */+ approxTotalCount,+ /** True while the first approximate-count value is still loading. */+ isApproxTotalCountLoading,+ /** True when the count omitted input/output/comment filters and therefore+ * over-counts. Does NOT include full-text search. */+ approxTotalCountIsPartialScope,/** Columns whose fetch terminally errored (per column). Consumers settle these* to the empty state; other columns keep loading normally. */erroredColumns,diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex 14428feefa..565388c65c 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -64,6 +64,10 @@ const GetEventFilterOptionsInput = zodSchema.object({columns: zodSchema.array(zodSchema.enum(EVENT_FILTER_OPTIONS_COLUMNS)).optional(),+ // When true, the response also carries the approximate total observation+ // count ("Total β X") β uniq(span_id) over the same bulk facet scan, matching+ // `filter`. Sent only on the eager bulk request.+ includeApproxCount: zodSchema.boolean().optional(),});export type GetEventFilterOptionsInput = z.infer<@@ -184,6 +188,7 @@ export const eventsRouter = createTRPCRouter({? !input.hasParentObservation: undefined), // backward compat for legacy hasParentObservation filterOptioncolumns: input.columns,+ includeApproxCount: input.includeApproxCount,});},);diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsindex 6a91438b32..81b9266a69 100644--- a/web/src/features/events/server/eventsService.ts+++ b/web/src/features/events/server/eventsService.ts@@ -20,6 +20,7 @@ import {getScoresForTraces,logger,traceException,+ EVENTS_APPROX_TOTAL_COUNT_MARKER,type EventBatchIOResult,type EventFilterOptionColumn,} from "@langfuse/shared/src/server";@@ -106,6 +107,15 @@ interface GetEventFilterOptionsParams extends GetObservationsFilterOptionsParams* that scan for filter options is prohibitively expensive.*/filter?: FilterState;+ /**+ * When true, the bulk facet query also returns the approximate total+ * observation count matching `filter` (`uniq(span_id)` over the same facet+ * scan) for the traces-table footer "Total β X". The scan honors `filter`+ * (incl. score filters) but not input/output/comment (dropped upstream, so+ * `omitCounts` β the count is flagged partial) nor full-text search. Set only+ * on the eager bulk request so the count is computed once.+ */+ includeApproxCount?: boolean;}type EventFilterValueOption = {@@ -707,6 +717,10 @@ export async function getEventFilterOptions(projectId,filter: refinedEventsFilter,columns: eventColumns,+ // Only the eager bulk request sets includeApproxCount, so the+ // approximate total is computed once (riding this scan), not per lazy+ // facet. uniq(span_id) over this scan already honors refinedEventsFilter.+ includeApproxCount: scopedParams.includeApproxCount,}): Promise.resolve([]),]);@@ -726,6 +740,22 @@ export async function getEventFilterOptions(omitCounts,);+ // Approximate total observation count for the footer "Total β X": the bulk+ // facet query returns it as a sentinel row (only when includeApproxCount was+ // set β i.e. the eager request). `null` when not requested.+ const approxTotalCountRow = eventFilterOptions.find(+ (row) => (row.column as string) === EVENTS_APPROX_TOTAL_COUNT_MARKER,+ );+ const approxTotalCount = approxTotalCountRow+ ? Number(approxTotalCountRow.count)+ : null;+ // Partial scope: the facet scan omits input/output/comment filters+ // (`omitCounts`), so the count over-counts vs the visible rows β the UI marks+ // it and drops the "within a few percent" claim. Score filters ARE honored+ // by the scan. (Full-text search isn't part of this query, so the client ORs+ // in its own searchQuery signal.)+ const approxTotalCountIsPartial = approxTotalCount !== null && omitCounts;+// name β the level(s) the name actually exists at, SPLIT PER DATA-TYPE// class: a name can be reused across types at different levels (a NUMERIC// observation-level "accuracy" next to an unrelated CATEGORICAL trace-level@@ -763,6 +793,13 @@ export async function getEventFilterOptions(// column only offers names its filter can match (LFE-10596).return {...eventFilterOptionsByColumn,+ // Approximate total observation count for the footer "Total β X". Included+ // ONLY when requested (the eager bulk query), so callers that didn't ask β+ // lazy per-column facet requests, the sidebar/search-bar option loaders β+ // don't carry stray count keys (mirrors the conditional score keys below).+ ...(scopedParams.includeApproxCount+ ? { approxTotalCount, approxTotalCountIsPartial }+ : {}),...(shouldLoadScoresAvg? { scores_avg: numericScoreNames.map((score) => score.name) }: {}),