🪢 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
perf(dashboards): use query scheduler to reduce concurrency (#12291)
Nimara67f4609945a
diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsxindex 4c6e6f5519..70801afd1c 100644--- a/web/src/features/dashboard/components/ChartScores.tsx+++ b/web/src/features/dashboard/components/ChartScores.tsx@@ -1,5 +1,3 @@-import { api } from "@/src/utils/api";-import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { type ScoreDataTypeType, type FilterState } from "@langfuse/shared";import {@@ -21,6 +19,7 @@ import {import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export function ChartScores(props: {className?: string;@@ -31,6 +30,7 @@ export function ChartScores(props: {projectId: string;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) {const scoresQuery: QueryType = {view: "scores-numeric",@@ -49,7 +49,7 @@ export function ChartScores(props: {orderBy: null,};- const scores = api.dashboard.executeQuery.useQuery(+ const scores = useScheduledDashboardExecuteQuery({projectId: props.projectId,query: scoresQuery,@@ -61,6 +61,7 @@ export function ChartScores(props: {skipBatch: true,},},+ queryId: `${props.schedulerId ?? "home:chart-scores"}:scores`,enabled: !props.isLoading,},);diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsxindex 97db04ddb7..9fee86d900 100644--- a/web/src/features/dashboard/components/LatencyChart.tsx+++ b/web/src/features/dashboard/components/LatencyChart.tsx@@ -1,4 +1,3 @@-import { api } from "@/src/utils/api";import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";import {extractTimeSeriesData,@@ -25,6 +24,7 @@ import {import type { DatabaseRow } from "@/src/server/api/services/sqlInterface";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export const GenerationLatencyChart = ({className,@@ -35,6 +35,7 @@ export const GenerationLatencyChart = ({toTimestamp,isLoading = false,metricsVersion,+ schedulerId,}: {className?: string;projectId: string;@@ -44,6 +45,7 @@ export const GenerationLatencyChart = ({toTimestamp: Date;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) => {const {allModels,@@ -58,7 +60,13 @@ export const GenerationLatencyChart = ({fromTimestamp,toTimestamp,metricsVersion,+ {+ enabled: !isLoading,+ queryId: `${schedulerId ?? "home:generation-latency"}:all-models`,+ },);+ const hasModelSelection = selectedModels.length > 0 && allModels.length > 0;+ const isLatencyEnabled = !isLoading && hasModelSelection;const latenciesQuery: QueryType = {view: "observations",@@ -94,19 +102,21 @@ export const GenerationLatencyChart = ({orderBy: null,};- const latencies = api.dashboard.executeQuery.useQuery(+ const latencies = useScheduledDashboardExecuteQuery({projectId,query: latenciesQuery,version: metricsVersion,},{- enabled: !isLoading && selectedModels.length > 0 && allModels.length > 0,+ enabled: isLatencyEnabled,trpc: {context: {skipBatch: true,},},+ queryId: `${schedulerId ?? "home:generation-latency"}:latencies`,+ priority: 1001,},);diff --git a/web/src/features/dashboard/components/LatencyTables.tsx b/web/src/features/dashboard/components/LatencyTables.tsxindex 1275fed244..237bee98a6 100644--- a/web/src/features/dashboard/components/LatencyTables.tsx+++ b/web/src/features/dashboard/components/LatencyTables.tsx@@ -2,7 +2,6 @@ import { RightAlignedCell } from "@/src/features/dashboard/components/RightAlignimport { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";-import { api } from "@/src/utils/api";import { formatIntervalSeconds } from "@/src/utils/dates";import { truncate } from "@/src/utils/string";@@ -12,6 +11,7 @@ import {type ViewVersion,mapLegacyUiTableFilterToView,} from "@/src/features/query";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export const LatencyTables = ({projectId,@@ -20,6 +20,7 @@ export const LatencyTables = ({toTimestamp,isLoading = false,metricsVersion,+ schedulerId,}: {projectId: string;globalFilterState: FilterState;@@ -27,6 +28,7 @@ export const LatencyTables = ({toTimestamp: Date;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) => {const generationsLatenciesQuery: QueryType = {view: "observations",@@ -53,7 +55,7 @@ export const LatencyTables = ({chartConfig: { type: "table", row_limit: 20 },};- const generationsLatencies = api.dashboard.executeQuery.useQuery(+ const generationsLatencies = useScheduledDashboardExecuteQuery({projectId,query: generationsLatenciesQuery,@@ -65,6 +67,7 @@ export const LatencyTables = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:latency-tables"}:generations`,enabled: !isLoading,},);@@ -94,7 +97,7 @@ export const LatencyTables = ({chartConfig: { type: "table", row_limit: 20 },};- const spansLatencies = api.dashboard.executeQuery.useQuery(+ const spansLatencies = useScheduledDashboardExecuteQuery({projectId,query: spansLatenciesQuery,@@ -106,6 +109,7 @@ export const LatencyTables = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:latency-tables"}:spans`,enabled: !isLoading,},);@@ -127,7 +131,7 @@ export const LatencyTables = ({chartConfig: { type: "table", row_limit: 20 },};- const tracesLatencies = api.dashboard.executeQuery.useQuery(+ const tracesLatencies = useScheduledDashboardExecuteQuery({projectId,query: tracesLatenciesQuery,@@ -139,6 +143,7 @@ export const LatencyTables = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:latency-tables"}:traces`,enabled: !isLoading,},);diff --git a/web/src/features/dashboard/components/ModelCostTable.tsx b/web/src/features/dashboard/components/ModelCostTable.tsxindex 9f9a489f0b..0b3bf7bf28 100644--- a/web/src/features/dashboard/components/ModelCostTable.tsx+++ b/web/src/features/dashboard/components/ModelCostTable.tsx@@ -4,7 +4,6 @@ import { LeftAlignedCell } from "@/src/features/dashboard/components/LeftAlignedimport { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";-import { api } from "@/src/utils/api";import { compactNumberFormatter } from "@/src/utils/numbers";import { TotalMetric } from "./TotalMetric";import { totalCostDashboardFormatted } from "@/src/features/dashboard/lib/dashboard-utils";@@ -14,6 +13,7 @@ import {type ViewVersion,mapLegacyUiTableFilterToView,} from "@/src/features/query";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export const ModelCostTable = ({className,@@ -23,6 +23,7 @@ export const ModelCostTable = ({toTimestamp,isLoading = false,metricsVersion,+ schedulerId,}: {className: string;projectId: string;@@ -31,6 +32,7 @@ export const ModelCostTable = ({toTimestamp: Date;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) => {const modelCostQuery: QueryType = {view: "observations",@@ -55,7 +57,7 @@ export const ModelCostTable = ({chartConfig: { type: "table", row_limit: 20 },};- const metrics = api.dashboard.executeQuery.useQuery(+ const metrics = useScheduledDashboardExecuteQuery({projectId,query: modelCostQuery,@@ -67,6 +69,7 @@ export const ModelCostTable = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:model-costs"}:metrics`,enabled: !isLoading,},);diff --git a/web/src/features/dashboard/components/ModelSelector.tsx b/web/src/features/dashboard/components/ModelSelector.tsxindex ee12a04ed4..0a712b958d 100644--- a/web/src/features/dashboard/components/ModelSelector.tsx+++ b/web/src/features/dashboard/components/ModelSelector.tsx@@ -13,7 +13,7 @@ import {PopoverContent,PopoverTrigger,} from "@/src/components/ui/popover";-import { getAllModels } from "@/src/features/dashboard/components/hooks";+import { useAllModels } from "@/src/features/dashboard/components/hooks";import { cn } from "@/src/utils/tailwind";import { type FilterState } from "@langfuse/shared";import { type ViewVersion } from "@/src/features/query";@@ -108,13 +108,18 @@ export const useModelSelection = (fromTimestamp: Date,toTimestamp: Date,metricsVersion?: ViewVersion,+ options?: {+ enabled?: boolean;+ queryId: string;+ },) => {- const allModels = getAllModels(+ const allModels = useAllModels(projectId,globalFilterState,fromTimestamp,toTimestamp,metricsVersion,+ options,);const [selectedModels, setSelectedModels] = useState<string[]>([]);diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsxindex 6bc1e121ac..94e35aa845 100644--- a/web/src/features/dashboard/components/ModelUsageChart.tsx+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx@@ -27,6 +27,7 @@ import {import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export const ModelUsageChart = ({className,@@ -38,6 +39,7 @@ export const ModelUsageChart = ({userAndEnvFilterState,isLoading = false,metricsVersion,+ schedulerId,}: {className?: string;projectId: string;@@ -48,6 +50,7 @@ export const ModelUsageChart = ({userAndEnvFilterState: FilterState;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) => {const {allModels,@@ -62,7 +65,13 @@ export const ModelUsageChart = ({fromTimestamp,toTimestamp,metricsVersion,+ {+ enabled: !isLoading,+ queryId: `${schedulerId ?? "home:model-usage"}:all-models`,+ },);+ const hasModelSelection = selectedModels.length > 0 && allModels.length > 0;+ const isModelUsageEnabled = !isLoading && hasModelSelection;const modelUsageQuery: QueryType = {view: "observations",@@ -95,19 +104,21 @@ export const ModelUsageChart = ({orderBy: null,};- const queryResult = api.dashboard.executeQuery.useQuery(+ const queryResult = useScheduledDashboardExecuteQuery({projectId,query: modelUsageQuery,version: metricsVersion,},{- enabled: !isLoading && selectedModels.length > 0 && allModels.length > 0,+ enabled: isModelUsageEnabled,trpc: {context: {skipBatch: true,},},+ queryId: `${schedulerId ?? "home:model-usage"}:timeseries`,+ priority: 1001,},);@@ -154,7 +165,7 @@ export const ModelUsageChart = ({version: metricsVersion,},{- enabled: !isLoading && selectedModels.length > 0 && allModels.length > 0,+ enabled: isModelUsageEnabled,trpc: {context: {skipBatch: true,@@ -204,7 +215,7 @@ export const ModelUsageChart = ({version: metricsVersion,},{- enabled: !isLoading && selectedModels.length > 0 && allModels.length > 0,+ enabled: isModelUsageEnabled,trpc: {context: {skipBatch: true,diff --git a/web/src/features/dashboard/components/TracesBarListChart.tsx b/web/src/features/dashboard/components/TracesBarListChart.tsxindex 0c2ff0ec1a..f97098ee28 100644--- a/web/src/features/dashboard/components/TracesBarListChart.tsx+++ b/web/src/features/dashboard/components/TracesBarListChart.tsx@@ -1,4 +1,3 @@-import { api } from "@/src/utils/api";import { type FilterState } from "@langfuse/shared";import { ExpandListButton } from "@/src/features/dashboard/components/cards/ChevronButton";import { useState } from "react";@@ -10,6 +9,7 @@ import { type QueryType, type ViewVersion } from "@/src/features/query";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { barListToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";import { traceViewQuery } from "@/src/features/dashboard/lib/dashboard-utils";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export const TracesBarListChart = ({className,@@ -19,6 +19,7 @@ export const TracesBarListChart = ({toTimestamp,isLoading = false,metricsVersion,+ schedulerId,}: {className?: string;projectId: string;@@ -27,6 +28,7 @@ export const TracesBarListChart = ({toTimestamp: Date;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) => {const [isExpanded, setIsExpanded] = useState(false);@@ -44,7 +46,7 @@ export const TracesBarListChart = ({orderBy: null,};- const totalTraces = api.dashboard.executeQuery.useQuery(+ const totalTraces = useScheduledDashboardExecuteQuery({projectId,query: totalTracesQuery,@@ -56,6 +58,7 @@ export const TracesBarListChart = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:traces"}:total`,enabled: !isLoading,},);@@ -75,7 +78,7 @@ export const TracesBarListChart = ({chartConfig: { type: "table", row_limit: 20 },};- const traces = api.dashboard.executeQuery.useQuery(+ const traces = useScheduledDashboardExecuteQuery({projectId,query: tracesQuery,@@ -87,6 +90,7 @@ export const TracesBarListChart = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:traces"}:grouped`,enabled: !isLoading,},);diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsxindex 9349b2d553..e01ba92f53 100644--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx@@ -1,4 +1,3 @@-import { api } from "@/src/utils/api";import { type FilterState } from "@langfuse/shared";import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { TotalMetric } from "@/src/features/dashboard/components/TotalMetric";@@ -17,6 +16,7 @@ import {} from "@/src/features/query";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export const TracesAndObservationsTimeSeriesChart = ({className,@@ -27,6 +27,7 @@ export const TracesAndObservationsTimeSeriesChart = ({agg,isLoading = false,metricsVersion,+ schedulerId,}: {className?: string;projectId: string;@@ -36,6 +37,7 @@ export const TracesAndObservationsTimeSeriesChart = ({agg: DashboardDateRangeAggregationOption;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) => {const isV2 = metricsVersion === "v2";@@ -53,7 +55,7 @@ export const TracesAndObservationsTimeSeriesChart = ({orderBy: null,};- const traces = api.dashboard.executeQuery.useQuery(+ const traces = useScheduledDashboardExecuteQuery({projectId,query: tracesQuery,@@ -65,6 +67,7 @@ export const TracesAndObservationsTimeSeriesChart = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:traces-time-series"}:traces`,enabled: !isLoading && !isV2,},);@@ -101,7 +104,7 @@ export const TracesAndObservationsTimeSeriesChart = ({orderBy: null,};- const observations = api.dashboard.executeQuery.useQuery(+ const observations = useScheduledDashboardExecuteQuery({projectId,query: observationsQuery,@@ -113,6 +116,7 @@ export const TracesAndObservationsTimeSeriesChart = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:traces-time-series"}:observations`,enabled: !isLoading,},);diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsxindex 548380070c..e24b43bfd3 100644--- a/web/src/features/dashboard/components/UserChart.tsx+++ b/web/src/features/dashboard/components/UserChart.tsx@@ -1,4 +1,3 @@-import { api } from "@/src/utils/api";import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";import { compactNumberFormatter } from "@/src/utils/numbers";@@ -16,6 +15,7 @@ import {import { Chart } from "@/src/features/widgets/chart-library/Chart";import { barListToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";import { traceViewQuery } from "@/src/features/dashboard/lib/dashboard-utils";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";type BarChartDataPoint = {name: string;@@ -30,6 +30,7 @@ export const UserChart = ({toTimestamp,isLoading = false,metricsVersion,+ schedulerId,}: {className?: string;projectId: string;@@ -38,6 +39,7 @@ export const UserChart = ({toTimestamp: Date;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) => {const [isExpanded, setIsExpanded] = useState(false);const userCostQuery: QueryType = {@@ -62,7 +64,7 @@ export const UserChart = ({orderBy: null,};- const user = api.dashboard.executeQuery.useQuery(+ const user = useScheduledDashboardExecuteQuery({projectId,query: userCostQuery,@@ -74,6 +76,7 @@ export const UserChart = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:users"}:cost`,enabled: !isLoading,},);@@ -90,7 +93,7 @@ export const UserChart = ({orderBy: null,};- const traces = api.dashboard.executeQuery.useQuery(+ const traces = useScheduledDashboardExecuteQuery({projectId,query: traceCountQuery,@@ -102,6 +105,7 @@ export const UserChart = ({skipBatch: true,},},+ queryId: `${schedulerId ?? "home:users"}:traces`,enabled: !isLoading,},);diff --git a/web/src/features/dashboard/components/hooks.ts b/web/src/features/dashboard/components/hooks.tsindex a95af5b6ca..ff0f0d7d7e 100644--- a/web/src/features/dashboard/components/hooks.ts+++ b/web/src/features/dashboard/components/hooks.ts@@ -5,20 +5,26 @@ export type TimeSeriesChartDataPoint = {values: { label: string; value?: number }[];};import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";-import { api } from "@/src/utils/api";import {type ViewVersion,mapLegacyUiTableFilterToView,} from "@/src/features/query";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";-export const getAllModels = (+type UseAllModelsOptions = {+ enabled?: boolean;+ queryId: string;+};++export const useAllModels = (projectId: string,globalFilterState: FilterState,fromTimestamp: Date,toTimestamp: Date,metricsVersion?: ViewVersion,+ options?: UseAllModelsOptions,) => {- const allModels = api.dashboard.executeQuery.useQuery(+ const allModels = useScheduledDashboardExecuteQuery({projectId,version: metricsVersion,@@ -47,6 +53,8 @@ export const getAllModels = (skipBatch: true,},},+ enabled: options?.enabled ?? true,+ queryId: `${options?.queryId ?? "dashboard:all-models"}:models`,},);diff --git a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsxindex c26ba2b37d..e6f87b68a1 100644--- a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx+++ b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx@@ -1,4 +1,3 @@-import { api } from "@/src/utils/api";import { type FilterState } from "@langfuse/shared";import { createTracesTimeFilter } from "@/src/features/dashboard/lib/dashboard-utils";import {@@ -18,6 +17,7 @@ import { Chart } from "@/src/features/widgets/chart-library/Chart";import { scoreChartDataToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";import { isEmptyChart } from "@/src/features/dashboard/lib/score-analytics-utils";import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export function CategoricalScoreChart(props: {projectId: string;@@ -27,6 +27,7 @@ export function CategoricalScoreChart(props: {toTimestamp: Date;agg?: DashboardDateRangeAggregationOption;metricsVersion?: ViewVersion;+ schedulerId?: string;}) {const scoresQuery: QueryType = {view: "scores-categorical",@@ -67,7 +68,7 @@ export function CategoricalScoreChart(props: {orderBy: null,};- const scores = api.dashboard.executeQuery.useQuery(+ const scores = useScheduledDashboardExecuteQuery({projectId: props.projectId,query: scoresQuery,@@ -79,6 +80,7 @@ export function CategoricalScoreChart(props: {skipBatch: true,},},+ queryId: `${props.schedulerId ?? "home:score-analytics"}:categorical:${props.scoreData.source}:${props.scoreData.name}:${props.agg ?? "aggregate"}`,},);diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsxindex ce93f04620..e78c10eb17 100644--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx@@ -1,5 +1,3 @@-import { api } from "@/src/utils/api";-import {type ScoreSourceType,type FilterState,@@ -25,6 +23,7 @@ import {import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";import { Chart } from "@/src/features/widgets/chart-library/Chart";import { timeSeriesToDataPoints } from "@/src/features/dashboard/lib/chart-data-adapters";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export function NumericScoreTimeSeriesChart(props: {projectId: string;@@ -36,6 +35,7 @@ export function NumericScoreTimeSeriesChart(props: {fromTimestamp: Date;toTimestamp: Date;metricsVersion?: ViewVersion;+ schedulerId?: string;}) {const scoresQuery: QueryType = {view: "scores-numeric",@@ -74,7 +74,7 @@ export function NumericScoreTimeSeriesChart(props: {orderBy: null,};- const scores = api.dashboard.executeQuery.useQuery(+ const scores = useScheduledDashboardExecuteQuery({projectId: props.projectId,query: scoresQuery,@@ -86,6 +86,7 @@ export function NumericScoreTimeSeriesChart(props: {skipBatch: true,},},+ queryId: `${props.schedulerId ?? "home:score-analytics"}:numeric:${props.source}:${props.name}`,},);diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsxindex 885eccbd40..57ad928941 100644--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx@@ -31,6 +31,7 @@ export function ScoreAnalytics(props: {projectId: string;isLoading?: boolean;metricsVersion?: ViewVersion;+ schedulerId?: string;}) {// Stale score selections in localStorage are ignored as we only show scores that exist in scoreAnalyticsOptionsconst [selectedDashboardScoreKeys, setSelectedDashboardScoreKeys] =@@ -127,6 +128,7 @@ export function ScoreAnalytics(props: {fromTimestamp={props.fromTimestamp}toTimestamp={props.toTimestamp}metricsVersion={props.metricsVersion}+ schedulerId={props.schedulerId}/>)}{(isNumericDataType(dataType) ||@@ -162,6 +164,7 @@ export function ScoreAnalytics(props: {fromTimestamp={props.fromTimestamp}toTimestamp={props.toTimestamp}metricsVersion={props.metricsVersion}+ schedulerId={props.schedulerId}/>)}{(isNumericDataType(dataType) ||@@ -181,6 +184,7 @@ export function ScoreAnalytics(props: {fromTimestamp={props.fromTimestamp}toTimestamp={props.toTimestamp}metricsVersion={props.metricsVersion}+ schedulerId={props.schedulerId}/>)}</div>diff --git a/web/src/features/widgets/chart-library/HistogramChart.tsx b/web/src/features/widgets/chart-library/HistogramChart.tsxindex e8b61302a4..cef981faed 100644--- a/web/src/features/widgets/chart-library/HistogramChart.tsx+++ b/web/src/features/widgets/chart-library/HistogramChart.tsx@@ -1,6 +1,6 @@import React from "react";import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";-import { BarChart, Bar, XAxis, YAxis, ResponsiveContainer } from "recharts";+import { BarChart, Bar, XAxis, YAxis } from "recharts";import {ChartContainer,ChartTooltip,@@ -71,49 +71,47 @@ const HistogramChart = ({config={config}className="[&_.recharts-bar-rectangle:hover]:opacity-30 dark:[&_.recharts-bar-rectangle:hover]:opacity-100 dark:[&_.recharts-bar-rectangle:hover]:brightness-[3]">- <ResponsiveContainer width="100%" height="100%">- <BarChart- data={histogramData}- margin={{ top: 20, right: 30, left: 20, bottom: 5 }}- >- <XAxis- dataKey="binLabel"- stroke="hsl(var(--chart-grid))"- fontSize={12}- tickLine={false}- axisLine={false}- angle={-45}- textAnchor="end"- height={90}- />- <YAxis- stroke="hsl(var(--chart-grid))"- fontSize={12}- tickLine={false}- axisLine={false}- />- <Bar- dataKey="count"- fill="hsl(var(--chart-1))"- radius={[2, 2, 0, 0]}- fillOpacity={subtleFill ? 0.3 : 1}- />- <ChartTooltip- cursor={false}- contentStyle={{ backgroundColor: "hsl(var(--background))" }}- content={({ active, payload, label }) => (- <ChartTooltipContent- active={active}- payload={payload}- label={label}- valueFormatter={(v) => compactSmallNumberFormatter(Number(v))}- nameFormatter={(name) => (name === "count" ? "Count" : name)}- labelFormatter={(label) => `Bin: ${label}`}- />- )}- />- </BarChart>- </ResponsiveContainer>+ <BarChart+ data={histogramData}+ margin={{ top: 20, right: 30, left: 20, bottom: 5 }}+ >+ <XAxis+ dataKey="binLabel"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ angle={-45}+ textAnchor="end"+ height={90}+ />+ <YAxis+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ <Bar+ dataKey="count"+ fill="hsl(var(--chart-1))"+ radius={[2, 2, 0, 0]}+ fillOpacity={subtleFill ? 0.3 : 1}+ />+ <ChartTooltip+ cursor={false}+ contentStyle={{ backgroundColor: "hsl(var(--background))" }}+ content={({ active, payload, label }) => (+ <ChartTooltipContent+ active={active}+ payload={payload}+ label={label}+ valueFormatter={(v) => compactSmallNumberFormatter(Number(v))}+ nameFormatter={(name) => (name === "count" ? "Count" : name)}+ labelFormatter={(label) => `Bin: ${label}`}+ />+ )}+ />+ </BarChart></ChartContainer>);};diff --git a/web/src/features/widgets/components/DashboardGrid.tsx b/web/src/features/widgets/components/DashboardGrid.tsxindex a0a60cebb4..f7bad46713 100644--- a/web/src/features/widgets/components/DashboardGrid.tsx+++ b/web/src/features/widgets/components/DashboardGrid.tsx@@ -36,6 +36,7 @@ export function DashboardGrid({filterState,onDeleteWidget,dashboardOwner,+ getWidgetSchedulerId,}: {widgets: WidgetPlacement[];onChange: (widgets: WidgetPlacement[]) => void;@@ -46,6 +47,7 @@ export function DashboardGrid({filterState: FilterState;onDeleteWidget: (tileId: string) => void;dashboardOwner: "LANGFUSE" | "PROJECT" | undefined;+ getWidgetSchedulerId?: (widgetPlacementId: string) => string;}) {const [rowHeight, setRowHeight] = useState(150);@@ -104,6 +106,7 @@ export function DashboardGrid({return (<div className="flex w-full flex-col gap-4">{widgets+ .slice().sort((a, b) => a.y - b.y || a.x - b.x) // Sort by position for consistent order.map((widget) => (<div@@ -119,6 +122,7 @@ export function DashboardGrid({filterState={filterState}onDeleteWidget={onDeleteWidget}dashboardOwner={dashboardOwner || "PROJECT"}+ schedulerId={getWidgetSchedulerId?.(widget.id)}/></div>))}@@ -152,6 +156,7 @@ export function DashboardGrid({filterState={filterState}onDeleteWidget={onDeleteWidget}dashboardOwner={dashboardOwner || "PROJECT"}+ schedulerId={getWidgetSchedulerId?.(widget.id)}/></div>))}diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsxindex e6a3fed0f7..c15488ebc2 100644--- a/web/src/features/widgets/components/DashboardWidget.tsx+++ b/web/src/features/widgets/components/DashboardWidget.tsx@@ -24,6 +24,7 @@ import { ChartLoadingState } from "@/src/features/widgets/chart-library/ChartLoaimport { getChartLoadingStateProps } from "@/src/features/widgets/chart-library/chartLoadingStateUtils";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { type ViewVersion } from "@/src/features/query";+import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";export interface WidgetPlacement {id: string;@@ -43,6 +44,7 @@ export function DashboardWidget({filterState,onDeleteWidget,dashboardOwner,+ schedulerId,}: {projectId: string;dashboardId: string;@@ -51,6 +53,7 @@ export function DashboardWidget({filterState: FilterState;onDeleteWidget: (tileId: string) => void;dashboardOwner: "LANGFUSE" | "PROJECT";+ schedulerId?: string;}) {const router = useRouter();const utils = api.useUtils();@@ -99,7 +102,7 @@ export function DashboardWidget({setSortState(newSort);}, []);- const queryResult = api.dashboard.executeQuery.useQuery(+ const queryResult = useScheduledDashboardExecuteQuery({projectId,version: metricsVersion,@@ -143,6 +146,7 @@ export function DashboardWidget({skipBatch: true,},},+ queryId: `${schedulerId ?? `dashboard-widget:${placement.id}`}:execute`,meta: {silentHttpCodes: [422],},diff --git a/web/src/hooks/useDashboardQueryScheduler.tsx b/web/src/hooks/useDashboardQueryScheduler.tsxnew file mode 100644index 0000000000..d9641e93d1--- /dev/null+++ b/web/src/hooks/useDashboardQueryScheduler.tsx@@ -0,0 +1,333 @@+import {+ type TimeRange,+ toAbsoluteTimeRange,+} from "@/src/utils/date-range-utils";+import { api, type RouterInputs } from "@/src/utils/api";+import { hashKey } from "@tanstack/react-query";+import {+ createContext,+ type ReactNode,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";++type SchedulerItemStatus = "queued" | "running" | "done";++type SchedulerItem = {+ id: string;+ priority: number;+ isEligible: boolean;+ runKey: string;+ status: SchedulerItemStatus;+};++export type DashboardQuerySchedulerApi = {+ register: (+ id: string,+ priority: number,+ isEligible?: boolean,+ runKey?: string,+ ) => void;+ unregister: (id: string) => void;+ canFetch: (id: string) => boolean;+ markDone: (id: string) => void;+};++const DAY_MS = 24 * 60 * 60 * 1000;++export const getDashboardQuerySchedulerMaxConcurrent = (+ timeRange: TimeRange,+) => {+ const absoluteTimeRange = toAbsoluteTimeRange(timeRange);+ if (!absoluteTimeRange) return 5;++ const durationMs =+ absoluteTimeRange.to.getTime() - absoluteTimeRange.from.getTime();++ if (durationMs >= 90 * DAY_MS) return 2;+ if (durationMs >= 30 * DAY_MS) return 4;+ if (durationMs >= 7 * DAY_MS) return 6;+ if (durationMs >= DAY_MS) return 6;+ return 9;+};++export const useDashboardQueryScheduler = ({+ maxConcurrent,+ resetKey,+}: {+ maxConcurrent: number;+ resetKey?: string;+}): DashboardQuerySchedulerApi => {+ const itemsRef = useRef<Map<string, SchedulerItem>>(new Map());+ const [_version, setVersion] = useState(0);+ const previousResetKeyRef = useRef<string | undefined>(resetKey);++ const syncQueue = useCallback(() => {+ const items = itemsRef.current;+ let runningCount = 0;+ let changed = false;++ for (const item of items.values()) {+ if (item.status === "running") {+ runningCount += 1;+ }+ }++ const candidates = Array.from(items.values())+ .filter((item) => item.status === "queued" && item.isEligible)+ .sort((a, b) => a.priority - b.priority);++ for (const candidate of candidates) {+ if (runningCount >= maxConcurrent) break;+ candidate.status = "running";+ runningCount += 1;+ changed = true;+ }++ if (changed) {+ setVersion((value) => value + 1);+ }+ }, [maxConcurrent]);++ const register = useCallback(+ (+ id: string,+ priority: number,+ isEligible: boolean = true,+ runKey: string = id,+ ) => {+ const existingItem = itemsRef.current.get(id);++ if (!existingItem) {+ itemsRef.current.set(id, {+ id,+ priority,+ isEligible,+ runKey,+ status: "queued",+ });+ syncQueue();+ return;+ }++ const didRunKeyChange = existingItem.runKey !== runKey;+ const shouldRequeue = didRunKeyChange && existingItem.status === "done";+ const didChange =+ existingItem.priority !== priority ||+ existingItem.isEligible !== isEligible ||+ didRunKeyChange ||+ shouldRequeue;++ if (didChange) {+ existingItem.priority = priority;+ existingItem.isEligible = isEligible;+ existingItem.runKey = runKey;+ if (shouldRequeue) {+ existingItem.status = "queued";+ }+ setVersion((value) => value + 1);+ }++ syncQueue();+ },+ [syncQueue],+ );++ const unregister = useCallback(+ (id: string) => {+ const existing = itemsRef.current.get(id);+ if (!existing) return;++ itemsRef.current.delete(id);+ setVersion((value) => value + 1);++ if (existing.status === "running") {+ syncQueue();+ }+ },+ [syncQueue],+ );++ const markDone = useCallback(+ (id: string) => {+ const item = itemsRef.current.get(id);+ if (!item || item.status === "done") return;++ item.status = "done";+ setVersion((value) => value + 1);+ syncQueue();+ },+ [syncQueue],+ );++ const resetQueue = useCallback(() => {+ let changed = false;++ for (const item of itemsRef.current.values()) {+ if (item.status !== "queued") {+ item.status = "queued";+ changed = true;+ }+ }++ if (changed) {+ setVersion((value) => value + 1);+ }++ syncQueue();+ }, [syncQueue]);++ const canFetch = useCallback((id: string) => {+ const item = itemsRef.current.get(id);+ if (!item) return false;+ return item.status === "running";+ }, []);++ useEffect(() => {+ syncQueue();+ }, [maxConcurrent, syncQueue]);++ useEffect(() => {+ if (previousResetKeyRef.current === resetKey) return;+ previousResetKeyRef.current = resetKey;+ resetQueue();+ }, [resetKey, resetQueue]);++ return {+ register,+ unregister,+ canFetch,+ markDone,+ };+};++type DashboardQuerySchedulerContextValue = {+ scheduler: Pick<+ DashboardQuerySchedulerApi,+ "register" | "unregister" | "canFetch" | "markDone"+ >;+};++const DashboardQuerySchedulerContext =+ createContext<DashboardQuerySchedulerContextValue | null>(null);++export const DashboardQuerySchedulerProvider = ({+ scheduler,+ children,+}: {+ scheduler: DashboardQuerySchedulerContextValue["scheduler"];+ children: ReactNode;+}) => {+ const contextValue = useMemo(+ () => ({+ scheduler: {+ register: scheduler.register,+ unregister: scheduler.unregister,+ canFetch: scheduler.canFetch,+ markDone: scheduler.markDone,+ },+ }),+ [+ scheduler.register,+ scheduler.unregister,+ scheduler.canFetch,+ scheduler.markDone,+ ],+ );++ return (+ <DashboardQuerySchedulerContext.Provider value={contextValue}>+ {children}+ </DashboardQuerySchedulerContext.Provider>+ );+};++const useDashboardQuerySchedulerContext = () => {+ return useContext(DashboardQuerySchedulerContext);+};++type DashboardExecuteQueryInput = RouterInputs["dashboard"]["executeQuery"];+type DashboardExecuteQueryOptions = NonNullable<+ Parameters<+ typeof api.dashboard.executeQuery.useQuery<Record<string, unknown>[]>+ >[1]+>;+type ScheduledDashboardExecuteQueryOptions = Omit<+ DashboardExecuteQueryOptions,+ "enabled" | "meta"+> & {+ enabled?: boolean;+ meta?: DashboardExecuteQueryOptions["meta"];+ priority?: number;+ queryId: string;+ runKey?: string;+};++const getDefaultRunKey = (input: DashboardExecuteQueryInput) =>+ hashKey([input]);++export const useScheduledDashboardExecuteQuery = (+ input: DashboardExecuteQueryInput,+ {+ enabled = true,+ meta,+ priority = 1000,+ queryId,+ runKey,+ ...queryOptions+ }: ScheduledDashboardExecuteQueryOptions,+) => {+ const context = useDashboardQuerySchedulerContext();+ const scheduler = context?.scheduler;+ const register = scheduler?.register;+ const unregister = scheduler?.unregister;+ const markDone = scheduler?.markDone;+ const effectiveRunKey = useMemo(+ () => runKey ?? getDefaultRunKey(input),+ [input, runKey],+ );++ useEffect(() => {+ if (!unregister) return;+ return () => {+ unregister(queryId);+ };+ }, [queryId, unregister]);++ useEffect(() => {+ if (!register) return;+ register(queryId, priority, enabled, effectiveRunKey);+ }, [effectiveRunKey, enabled, priority, queryId, register]);++ const canFetch = scheduler ? scheduler.canFetch(queryId) : true;++ const queryResult = api.dashboard.executeQuery.useQuery<+ Record<string, unknown>[]+ >(input, {+ ...queryOptions,+ enabled: enabled && canFetch,+ meta,+ });++ useEffect(() => {+ if (!markDone) return;+ if (!enabled || !canFetch) return;+ if (queryResult.fetchStatus !== "idle") return;+ if (queryResult.isPending) return;++ markDone(queryId);+ }, [+ canFetch,+ enabled,+ markDone,+ queryId,+ queryResult.fetchStatus,+ queryResult.isPending,+ ]);++ return queryResult;+};diff --git a/web/src/hooks/use-environment-filter.tsx b/web/src/hooks/useEnvironmentFilter.tsxsimilarity index 91%rename from web/src/hooks/use-environment-filter.tsxrename to web/src/hooks/useEnvironmentFilter.tsxindex da397ade12..13c1c2e6f9 100644--- a/web/src/hooks/use-environment-filter.tsx+++ b/web/src/hooks/useEnvironmentFilter.tsx@@ -35,9 +35,11 @@ export function useEnvironmentFilter({},);- const visibleEnvironments = (availableEnvironments || []).filter(- (env) => visibilityMap[env] === true,- );+ const getDefaultVisibility = (env: string) => !env.startsWith("langfuse-");++ const visibleEnvironments = (availableEnvironments || []).filter((env) => {+ return visibilityMap[env] ?? getDefaultVisibility(env);+ });const handleSetVisibilityMap = (environments: string[]) => {const selectedSet = new Set(environments);@@ -61,7 +63,7 @@ export function useEnvironmentFilter(// If environment doesn't exist in map, set default visibility// Environments prefixed with "langfuse-" are deselected by defaultif (updatedMap[env] === undefined) {- updatedMap[env] = !env.startsWith("langfuse-");+ updatedMap[env] = getDefaultVisibility(env);hasChanges = true;}});diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsxindex 002de12a64..e9ffe061cb 100644--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx@@ -26,6 +26,11 @@ import {} from "@/src/utils/date-range-utils";import { useEntitlementLimit } from "@/src/features/entitlements/hooks";import { useEnvironmentFilterOptionsCache } from "@/src/hooks/use-environment-filter-options-cache";+import {+ DashboardQuerySchedulerProvider,+ getDashboardQuerySchedulerMaxConcurrent,+ useDashboardQueryScheduler,+} from "@/src/hooks/useDashboardQueryScheduler";interface WidgetPlacement {id: string;@@ -381,123 +386,160 @@ export default function DashboardDetail() {};const dashboardTimeRangePresets = DASHBOARD_AGGREGATION_OPTIONS;+ const widgetSchedulerPrefix = `dashboard:${projectId}:${dashboardId}:widget:`;+ const widgetPlacements = useMemo(+ () => localDashboardDefinition?.widgets ?? [],+ [localDashboardDefinition?.widgets],+ );++ const getWidgetSchedulerId = useCallback(+ (widgetPlacementId: string) =>+ `${widgetSchedulerPrefix}${widgetPlacementId}`,+ [widgetSchedulerPrefix],+ );++ const schedulerResetKey = useMemo(() => {+ return [+ projectId,+ dashboardId,+ absoluteTimeRange?.from?.toISOString() ?? "",+ absoluteTimeRange?.to?.toISOString() ?? "",+ JSON.stringify(currentFilters),+ widgetPlacements.map((widget) => widget.id).join(","),+ ].join("|");+ }, [+ absoluteTimeRange?.from,+ absoluteTimeRange?.to,+ currentFilters,+ dashboardId,+ projectId,+ widgetPlacements,+ ]);++ const scheduler = useDashboardQueryScheduler({+ maxConcurrent: getDashboardQuerySchedulerMaxConcurrent(timeRange),+ resetKey: schedulerResetKey,+ });return (- <Page- withPadding- scrollable- headerProps={{- title:- (dashboard.data?.name || "Dashboard") +- (dashboard.data?.owner === "LANGFUSE"- ? " (Langfuse Maintained)"- : ""),- breadcrumb: [- {- name: "Dashboards",- href: `/project/${projectId}/dashboards`,+ <DashboardQuerySchedulerProvider scheduler={scheduler}>+ <Page+ withPadding+ scrollable+ headerProps={{+ title:+ (dashboard.data?.name || "Dashboard") ++ (dashboard.data?.owner === "LANGFUSE"+ ? " (Langfuse Maintained)"+ : ""),+ breadcrumb: [+ {+ name: "Dashboards",+ href: `/project/${projectId}/dashboards`,+ },+ ],+ help: {+ description:+ dashboard.data?.description || "No description available",},- ],- help: {- description:- dashboard.data?.description || "No description available",- },- actionButtonsRight: (- <>- {hasCUDAccess && hasUnsavedFilterChanges && (- <Button- onClick={handleSaveFilters}- disabled={updateDashboardFilters.isPending}- variant="outline"- >- {updateDashboardFilters.isPending- ? "Saving..."- : "Save Filters"}- </Button>- )}- {hasCUDAccess && (- <Button onClick={handleAddWidget}>- <PlusIcon size={16} className="mr-1 h-4 w-4" />- Add Widget- </Button>- )}- {hasCloneAccess && (- <Button- onClick={handleCloneDashboard}- disabled={mutateCloneDashboard.isPending}- >- <Copy size={16} className="mr-1 h-4 w-4" />- Clone- </Button>- )}- </>- ),- }}- >- <SelectWidgetDialog- open={isWidgetDialogOpen}- onOpenChange={setIsWidgetDialogOpen}- projectId={projectId}- onSelectWidget={handleSelectWidget}- dashboardId={dashboardId}- />- {dashboard.isPending || !localDashboardDefinition ? (- <NoDataOrLoading isLoading={true} />- ) : dashboard.isError ? (- <div className="flex h-64 items-center justify-center">- <div className="text-destructive">- Error: {dashboard.error.message}+ actionButtonsRight: (+ <>+ {hasCUDAccess && hasUnsavedFilterChanges && (+ <Button+ onClick={handleSaveFilters}+ disabled={updateDashboardFilters.isPending}+ variant="outline"+ >+ {updateDashboardFilters.isPending+ ? "Saving..."+ : "Save Filters"}+ </Button>+ )}+ {hasCUDAccess && (+ <Button onClick={handleAddWidget}>+ <PlusIcon size={16} className="mr-1 h-4 w-4" />+ Add Widget+ </Button>+ )}+ {hasCloneAccess && (+ <Button+ onClick={handleCloneDashboard}+ disabled={mutateCloneDashboard.isPending}+ >+ <Copy size={16} className="mr-1 h-4 w-4" />+ Clone+ </Button>+ )}+ </>+ ),+ }}+ >+ <SelectWidgetDialog+ open={isWidgetDialogOpen}+ onOpenChange={setIsWidgetDialogOpen}+ projectId={projectId}+ onSelectWidget={handleSelectWidget}+ dashboardId={dashboardId}+ />+ {dashboard.isPending || !localDashboardDefinition ? (+ <NoDataOrLoading isLoading={true} />+ ) : dashboard.isError ? (+ <div className="flex h-64 items-center justify-center">+ <div className="text-destructive">+ Error: {dashboard.error.message}+ </div></div>- </div>- ) : (- <div>- <div className="my-3 flex flex-wrap items-center justify-between gap-2">- <div className="flex flex-col gap-2 lg:flex-row lg:gap-3">- <TimeRangePicker- timeRange={timeRange}- onTimeRangeChange={setTimeRange}- timeRangePresets={dashboardTimeRangePresets}- className="my-0 max-w-full overflow-x-auto"- disabled={- lookbackLimit- ? {- before: new Date(- new Date().getTime() -- lookbackLimit * 24 * 60 * 60 * 1000,- ),- }- : undefined- }- />- <PopoverFilterBuilder- columns={filterColumns}- filterState={currentFilters}- onChange={setCurrentFilters}- />+ ) : (+ <div>+ <div className="my-3 flex flex-wrap items-center justify-between gap-2">+ <div className="flex flex-col gap-2 lg:flex-row lg:gap-3">+ <TimeRangePicker+ timeRange={timeRange}+ onTimeRangeChange={setTimeRange}+ timeRangePresets={dashboardTimeRangePresets}+ className="my-0 max-w-full overflow-x-auto"+ disabled={+ lookbackLimit+ ? {+ before: new Date(+ new Date().getTime() -+ lookbackLimit * 24 * 60 * 60 * 1000,+ ),+ }+ : undefined+ }+ />+ <PopoverFilterBuilder+ columns={filterColumns}+ filterState={currentFilters}+ onChange={setCurrentFilters}+ />+ </div></div>+ <DashboardGrid+ widgets={localDashboardDefinition.widgets}+ onChange={(updatedWidgets) => {+ setLocalDashboardDefinition({+ ...localDashboardDefinition,+ widgets: updatedWidgets,+ });+ saveDashboardChanges({+ ...localDashboardDefinition,+ widgets: updatedWidgets,+ });+ }}+ canEdit={hasCUDAccess}+ dashboardId={dashboardId}+ projectId={projectId}+ dateRange={absoluteTimeRange}+ filterState={currentFilters}+ onDeleteWidget={handleDeleteWidget}+ dashboardOwner={dashboard.data?.owner}+ getWidgetSchedulerId={getWidgetSchedulerId}+ /></div>- <DashboardGrid- widgets={localDashboardDefinition.widgets}- onChange={(updatedWidgets) => {- setLocalDashboardDefinition({- ...localDashboardDefinition,- widgets: updatedWidgets,- });- saveDashboardChanges({- ...localDashboardDefinition,- widgets: updatedWidgets,- });- }}- canEdit={hasCUDAccess}- dashboardId={dashboardId}- projectId={projectId}- dateRange={absoluteTimeRange}- filterState={currentFilters}- onDeleteWidget={handleDeleteWidget}- dashboardOwner={dashboard.data?.owner}- />- </div>- )}- </Page>+ )}+ </Page>+ </DashboardQuerySchedulerProvider>);}diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex 4b09aebb9e..e572033336 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -13,14 +13,13 @@ import { FeedbackButtonWrapper } from "@/src/features/feedback/component/Feedbacimport { BarChart2 } from "lucide-react";import { Button } from "@/src/components/ui/button";import { PopoverFilterBuilder } from "@/src/features/filters/components/filter-builder";-import { type FilterState } from "@langfuse/shared";-import { type ColumnDefinition } from "@langfuse/shared";+import { type ColumnDefinition, type FilterState } from "@langfuse/shared";import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";import { LatencyTables } from "@/src/features/dashboard/components/LatencyTables";import { useMemo } from "react";import {- findClosestDashboardInterval,DASHBOARD_AGGREGATION_OPTIONS,+ findClosestDashboardInterval,toAbsoluteTimeRange,type DashboardDateRangeAggregationOption,} from "@/src/utils/date-range-utils";@@ -35,11 +34,29 @@ import { MultiSelect } from "@/src/features/filters/components/multi-select";import {convertSelectedEnvironmentsToFilter,useEnvironmentFilter,-} from "@/src/hooks/use-environment-filter";+} from "@/src/hooks/useEnvironmentFilter";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { type ViewVersion } from "@/src/features/query";import { useEnvironmentFilterOptionsCache } from "@/src/hooks/use-environment-filter-options-cache";import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";+import {+ DashboardQuerySchedulerProvider,+ getDashboardQuerySchedulerMaxConcurrent,+ useDashboardQueryScheduler,+} from "@/src/hooks/useDashboardQueryScheduler";++const HOME_DASHBOARD_CARD_IDS = {+ traces: "home:traces",+ modelCosts: "home:model-costs",+ scoresTable: "home:scores-table",+ tracesTimeSeries: "home:traces-time-series",+ modelUsage: "home:model-usage",+ users: "home:users",+ chartScores: "home:chart-scores",+ latencyTables: "home:latency-tables",+ generationLatency: "home:generation-latency",+ scoreAnalytics: "home:score-analytics",+} as const;export default function Dashboard() {const router = useRouter();@@ -54,7 +71,6 @@ export default function Dashboard() {);const uiCustomization = useUiCustomization();-const lookbackLimit = useEntitlementLimit("data-access-days");const [userFilterState, setUserFilterState] = useQueryFilterState(@@ -87,7 +103,6 @@ export default function Dashboard() {const environmentOptions: string[] =environmentOptionsState.environmentOptions;- // Add effect to update filter state when environments changeconst { selectedEnvironments, setSelectedEnvironments } =useEnvironmentFilter(environmentOptions, projectId);@@ -174,174 +189,209 @@ export default function Dashboard() {];const isDashboardDataReady = environmentOptionsState.isReady;+ const schedulerResetKey = useMemo(() => {+ return [+ projectId,+ metricsVersion,+ absoluteTimeRange?.from?.toISOString() ?? "",+ absoluteTimeRange?.to?.toISOString() ?? "",+ JSON.stringify(userFilterState),+ selectedEnvironments.join(","),+ ].join("|");+ }, [+ absoluteTimeRange?.from,+ absoluteTimeRange?.to,+ metricsVersion,+ projectId,+ selectedEnvironments,+ userFilterState,+ ]);++ const scheduler = useDashboardQueryScheduler({+ maxConcurrent: getDashboardQuerySchedulerMaxConcurrent(timeRange),+ resetKey: schedulerResetKey,+ });+ const homeSchedulerIdPrefix = `${projectId}:`;+return (- <Page- withPadding- scrollable- headerProps={{- title: "Home",- actionButtonsLeft: (- <>- <TimeRangePicker- timeRange={timeRange}- onTimeRangeChange={setTimeRange}- timeRangePresets={dashboardTimeRangePresets}- className="my-0 max-w-full overflow-x-auto"- disabled={- lookbackLimit- ? {- before: new Date(- new Date().getTime() -- lookbackLimit * 24 * 60 * 60 * 1000,- ),+ <DashboardQuerySchedulerProvider scheduler={scheduler}>+ <Page+ withPadding+ scrollable+ headerProps={{+ title: "Home",+ actionButtonsLeft: (+ <>+ <TimeRangePicker+ timeRange={timeRange}+ onTimeRangeChange={setTimeRange}+ timeRangePresets={dashboardTimeRangePresets}+ className="my-0 max-w-full overflow-x-auto"+ disabled={+ lookbackLimit+ ? {+ before: new Date(+ new Date().getTime() -+ lookbackLimit * 24 * 60 * 60 * 1000,+ ),+ }+ : undefined+ }+ />+ <MultiSelect+ title="Environment"+ label="Env"+ values={selectedEnvironments}+ onValueChange={useDebounce(setSelectedEnvironments)}+ options={environmentOptions.map((env) => ({+ value: env,+ }))}+ className="my-0 w-auto overflow-hidden"+ />+ <PopoverFilterBuilder+ columns={filterColumns}+ filterState={userFilterState}+ onChange={useDebounce(setUserFilterState)}+ />+ </>+ ),+ actionButtonsRight: (+ <>+ {uiCustomization?.feedbackHref === undefined && (+ <FeedbackButtonWrapper+ title="Request Chart"+ description="Your feedback matters! Let the Langfuse team know what additional data or metrics you'd like to see in your dashboard."+ className="hidden lg:flex"+ >+ <Button+ id="date"+ variant={"outline"}+ className={+ "group justify-start gap-x-3 text-left font-semibold text-primary hover:bg-primary-foreground hover:text-primary-accent"}- : undefined- }+ >+ <BarChart2+ className="hidden h-6 w-6 shrink-0 text-primary group-hover:text-primary-accent lg:block"+ aria-hidden="true"+ />+ Request Chart+ </Button>+ </FeedbackButtonWrapper>+ )}+ <SetupTracingButton />+ </>+ ),+ }}+ >+ {!isDashboardDataReady ? (+ <NoDataOrLoading isLoading />+ ) : (+ <div className="grid w-full grid-cols-1 gap-3 overflow-hidden lg:grid-cols-2 xl:grid-cols-6">+ <TracesBarListChart+ className="col-span-1 xl:col-span-2"+ projectId={projectId}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.traces}`}/>- <MultiSelect- title="Environment"- label="Env"- values={selectedEnvironments}- onValueChange={useDebounce(setSelectedEnvironments)}- options={environmentOptions.map((env) => ({- value: env,- }))}- className="my-0 w-auto overflow-hidden"+ <ModelCostTable+ className="col-span-1 xl:col-span-2"+ projectId={projectId}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.modelCosts}`}/>- <PopoverFilterBuilder- columns={filterColumns}- filterState={userFilterState}- onChange={useDebounce(setUserFilterState)}+ <ScoresTable+ className="col-span-1 xl:col-span-2"+ projectId={projectId}+ globalFilterState={mergedFilterState}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}/>- </>- ),- actionButtonsRight: (- <>- {uiCustomization?.feedbackHref === undefined && (- <FeedbackButtonWrapper- title="Request Chart"- description="Your feedback matters! Let the Langfuse team know what additional data or metrics you'd like to see in your dashboard."- className="hidden lg:flex"- >- <Button- id="date"- variant={"outline"}- className={- "group justify-start gap-x-3 text-left font-semibold text-primary hover:bg-primary-foreground hover:text-primary-accent"- }- >- <BarChart2- className="hidden h-6 w-6 shrink-0 text-primary group-hover:text-primary-accent lg:block"- aria-hidden="true"- />- Request Chart- </Button>- </FeedbackButtonWrapper>- )}- <SetupTracingButton />- </>- ),- }}- >- {!isDashboardDataReady ? (- <NoDataOrLoading isLoading />- ) : (- <div className="grid w-full grid-cols-1 gap-3 overflow-hidden lg:grid-cols-2 xl:grid-cols-6">- <TracesBarListChart- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <ModelCostTable- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <ScoresTable- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={mergedFilterState}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <TracesAndObservationsTimeSeriesChart- className="col-span-1 xl:col-span-3"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- agg={agg}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <ModelUsageChart- className="col-span-1 min-h-24 xl:col-span-3"- projectId={projectId}- globalFilterState={mergedFilterState}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- userAndEnvFilterState={[...userFilterState, ...environmentFilter]}- agg={agg}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <UserChart- className="col-span-1 xl:col-span-3"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <ChartScores- className="col-span-1 xl:col-span-3"- agg={agg}- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <LatencyTables- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <GenerationLatencyChart- className="col-span-1 flex-auto justify-between lg:col-span-full"- projectId={projectId}- agg={agg}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- <ScoreAnalytics- className="col-span-1 flex-auto justify-between lg:col-span-full"- agg={agg}- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentOptionsState.isPending}- metricsVersion={metricsVersion}- />- </div>- )}- </Page>+ <TracesAndObservationsTimeSeriesChart+ className="col-span-1 xl:col-span-3"+ projectId={projectId}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ agg={agg}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.tracesTimeSeries}`}+ />+ <ModelUsageChart+ className="col-span-1 min-h-24 xl:col-span-3"+ projectId={projectId}+ globalFilterState={mergedFilterState}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ userAndEnvFilterState={[...userFilterState, ...environmentFilter]}+ agg={agg}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.modelUsage}`}+ />+ <UserChart+ className="col-span-1 xl:col-span-3"+ projectId={projectId}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.users}`}+ />+ <ChartScores+ className="col-span-1 xl:col-span-3"+ agg={agg}+ projectId={projectId}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.chartScores}`}+ />+ <LatencyTables+ projectId={projectId}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.latencyTables}`}+ />+ <GenerationLatencyChart+ className="col-span-1 flex-auto justify-between lg:col-span-full"+ projectId={projectId}+ agg={agg}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.generationLatency}`}+ />+ <ScoreAnalytics+ className="col-span-1 flex-auto justify-between lg:col-span-full"+ agg={agg}+ projectId={projectId}+ globalFilterState={[...userFilterState, ...environmentFilter]}+ fromTimestamp={fromTimestamp}+ toTimestamp={toTimestamp}+ isLoading={environmentOptionsState.isPending}+ metricsVersion={metricsVersion}+ schedulerId={`${homeSchedulerIdPrefix}${HOME_DASHBOARD_CARD_IDS.scoreAnalytics}`}+ />+ </div>+ )}+ </Page>+ </DashboardQuerySchedulerProvider>);}diff --git a/web/src/pages/project/[projectId]/users.tsx b/web/src/pages/project/[projectId]/users.tsxindex 177efbdc9c..6e26f99f36 100644--- a/web/src/pages/project/[projectId]/users.tsx+++ b/web/src/pages/project/[projectId]/users.tsx@@ -28,7 +28,7 @@ import { UsersOnboarding } from "@/src/components/onboarding/UsersOnboarding";import {useEnvironmentFilter,convertSelectedEnvironmentsToFilter,-} from "@/src/hooks/use-environment-filter";+} from "@/src/hooks/useEnvironmentFilter";import { Badge } from "@/src/components/ui/badge";type RowData = {