🪢 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(env-filter): make envs cached again (#12286)
Nimar18bcf18433d2
diff --git a/web/src/hooks/use-environment-filter-options-cache.tsx b/web/src/hooks/use-environment-filter-options-cache.tsxnew file mode 100644index 0000000000..5ecbc6a085--- /dev/null+++ b/web/src/hooks/use-environment-filter-options-cache.tsx@@ -0,0 +1,164 @@+import useLocalStorage from "@/src/components/useLocalStorage";+import {+ type TimeRange,+ toAbsoluteTimeRange,+} from "@/src/utils/date-range-utils";+import { api } from "@/src/utils/api";+import { useMemo, useEffect } from "react";++const ENVIRONMENT_OPTIONS_CACHE_STORAGE_KEY =+ "langfuse-environment-options-cache-v1";++const SECOND_MS = 1000;+const MINUTE_MS = 60 * 1000;+const HALF_HOUR_MS = 30 * MINUTE_MS;+const DAY_MS = 24 * 60 * 60 * 1000;++const TTL_30_MINUTES_MS = 30 * SECOND_MS;+const TTL_1_DAY_MS = 5 * MINUTE_MS;+const TTL_7_DAYS_MS = 10 * MINUTE_MS;+const TTL_30_DAYS_MS = 30 * MINUTE_MS;+const TTL_LONG_MS = 60 * MINUTE_MS;++type EnvironmentOptionsCacheEntry = {+ options: string[];+ fetchedAt: number;+ expiresAt: number;+};++type EnvironmentOptionsCacheStore = Record<+ string,+ EnvironmentOptionsCacheEntry+>;++const getCacheBucketFromTimeRange = (timeRange: TimeRange) => {+ if ("range" in timeRange) return `relative:${timeRange.range}`;++ return `absolute:${timeRange.from.getTime()}:${timeRange.to.getTime()}`;+};++const getTtlMsFromTimeRange = (timeRange: TimeRange) => {+ const absoluteTimeRange = toAbsoluteTimeRange(timeRange);+ if (!absoluteTimeRange) return TTL_LONG_MS;++ const durationMs =+ absoluteTimeRange.to.getTime() - absoluteTimeRange.from.getTime();++ if (durationMs <= HALF_HOUR_MS) return TTL_30_MINUTES_MS;+ if (durationMs <= DAY_MS) return TTL_1_DAY_MS;+ if (durationMs <= 7 * DAY_MS) return TTL_7_DAYS_MS;+ if (durationMs <= 30 * DAY_MS) return TTL_30_DAYS_MS;+ return TTL_LONG_MS;+};++const pruneExpiredEntries = (+ store: EnvironmentOptionsCacheStore,+ now: number,+) => {+ return Object.fromEntries(+ Object.entries(store).filter(([, value]) => value.expiresAt > now),+ ) as EnvironmentOptionsCacheStore;+};++const dedupeOptions = (options: string[]) => Array.from(new Set(options));++export function useEnvironmentFilterOptionsCache({+ projectId,+ timeRange,+}: {+ projectId: string;+ timeRange: TimeRange;+}) {+ const absoluteTimeRange = useMemo(+ () => toAbsoluteTimeRange(timeRange) ?? undefined,+ [timeRange],+ );+ const cacheBucket = getCacheBucketFromTimeRange(timeRange);+ const ttlMs = getTtlMsFromTimeRange(timeRange);++ const cacheEntryKey = `${projectId}:${cacheBucket}`;+ const [cacheStore, setCacheStore] =+ useLocalStorage<EnvironmentOptionsCacheStore>(+ ENVIRONMENT_OPTIONS_CACHE_STORAGE_KEY,+ {},+ );++ const prunedCacheStore = useMemo(+ () => pruneExpiredEntries(cacheStore, Date.now()),+ [cacheStore],+ );+ const cacheEntry = prunedCacheStore[cacheEntryKey];+ const hasValidCache = Boolean(+ cacheEntry && cacheEntry.expiresAt > Date.now(),+ );++ // Persist cache cleanup to localStorage when needed.+ useEffect(() => {+ if (+ Object.keys(prunedCacheStore).length !== Object.keys(cacheStore).length+ ) {+ setCacheStore(prunedCacheStore);+ }+ }, [cacheStore, prunedCacheStore, setCacheStore]);++ const environmentFilterOptions =+ api.projects.environmentFilterOptions.useQuery(+ {+ projectId,+ fromTimestamp: absoluteTimeRange?.from,+ },+ {+ enabled: Boolean(projectId) && !hasValidCache,+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: ttlMs,+ },+ );++ useEffect(() => {+ if (!projectId || !environmentFilterOptions.data) return;++ const options = dedupeOptions(+ environmentFilterOptions.data.map((value) => value.environment),+ );+ const nextEntry: EnvironmentOptionsCacheEntry = {+ options,+ fetchedAt: Date.now(),+ expiresAt: Date.now() + ttlMs,+ };++ setCacheStore((previousStore) => {+ const nextStore = pruneExpiredEntries(previousStore, Date.now());+ nextStore[cacheEntryKey] = nextEntry;+ return nextStore;+ });+ }, [+ projectId,+ cacheEntryKey,+ environmentFilterOptions.data,+ ttlMs,+ setCacheStore,+ ]);++ const environmentOptions = useMemo(() => {+ if (hasValidCache && cacheEntry) return cacheEntry.options;++ return dedupeOptions(+ environmentFilterOptions.data?.map((value) => value.environment) ?? [],+ );+ }, [hasValidCache, cacheEntry, environmentFilterOptions.data]);++ return {+ environmentOptions,+ isPending: !hasValidCache && environmentFilterOptions.isPending,+ isReady:+ hasValidCache ||+ environmentFilterOptions.isSuccess ||+ environmentFilterOptions.isError,+ };+}diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsxindex 7ec916c2dd..002de12a64 100644--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx@@ -25,6 +25,7 @@ import {toAbsoluteTimeRange,} from "@/src/utils/date-range-utils";import { useEntitlementLimit } from "@/src/features/entitlements/hooks";+import { useEnvironmentFilterOptionsCache } from "@/src/hooks/use-environment-filter-options-cache";interface WidgetPlacement {id: string;@@ -206,28 +207,15 @@ export default function DashboardDetail() {},);- const environmentFilterOptions =- api.projects.environmentFilterOptions.useQuery(- {- projectId,- fromTimestamp: absoluteTimeRange?.from,- },- {- trpc: {- context: {- skipBatch: true,- },- },- refetchOnMount: false,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- staleTime: Infinity,- },- );- const environmentOptions =- environmentFilterOptions.data?.map((value) => ({- value: value.environment,- })) || [];+ const environmentOptionsState = useEnvironmentFilterOptionsCache({+ projectId,+ timeRange,+ });+ const environmentOptions = environmentOptionsState.environmentOptions.map(+ (value) => ({+ value,+ }),+ );const nameOptions = traceFilterOptions.data?.name || [];const tagsOptions = traceFilterOptions.data?.tags || [];diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsxindex 9277ff7173..4b09aebb9e 100644--- a/web/src/pages/project/[projectId]/index.tsx+++ b/web/src/pages/project/[projectId]/index.tsx@@ -38,6 +38,8 @@ import {} from "@/src/hooks/use-environment-filter";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";export default function Dashboard() {const router = useRouter();@@ -78,26 +80,12 @@ export default function Dashboard() {},);- const environmentFilterOptions =- api.projects.environmentFilterOptions.useQuery(- {- projectId,- fromTimestamp: absoluteTimeRange?.from,- },- {- trpc: {- context: {- skipBatch: true,- },- },- refetchOnMount: false,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- staleTime: Infinity,- },- );+ const environmentOptionsState = useEnvironmentFilterOptionsCache({+ projectId,+ timeRange,+ });const environmentOptions: string[] =- environmentFilterOptions.data?.map((value) => value.environment) || [];+ environmentOptionsState.environmentOptions;// Add effect to update filter state when environments changeconst { selectedEnvironments, setSelectedEnvironments } =@@ -184,6 +172,7 @@ export default function Dashboard() {...timeFilter,...environmentFilter,];+ const isDashboardDataReady = environmentOptionsState.isReady;return (<Page@@ -254,101 +243,105 @@ export default function Dashboard() {),}}>- <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={environmentFilterOptions.isPending}- metricsVersion={metricsVersion}- />- <ModelCostTable- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentFilterOptions.isPending}- metricsVersion={metricsVersion}- />- <ScoresTable- className="col-span-1 xl:col-span-2"- projectId={projectId}- globalFilterState={mergedFilterState}- isLoading={environmentFilterOptions.isPending}- metricsVersion={metricsVersion}- />- <TracesAndObservationsTimeSeriesChart- className="col-span-1 xl:col-span-3"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- agg={agg}- isLoading={environmentFilterOptions.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={environmentFilterOptions.isPending}- metricsVersion={metricsVersion}- />- <UserChart- className="col-span-1 xl:col-span-3"- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentFilterOptions.isPending}- metricsVersion={metricsVersion}- />- <ChartScores- className="col-span-1 xl:col-span-3"- agg={agg}- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentFilterOptions.isPending}- metricsVersion={metricsVersion}- />- <LatencyTables- projectId={projectId}- globalFilterState={[...userFilterState, ...environmentFilter]}- fromTimestamp={fromTimestamp}- toTimestamp={toTimestamp}- isLoading={environmentFilterOptions.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={environmentFilterOptions.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={environmentFilterOptions.isPending}- metricsVersion={metricsVersion}- />- </div>+ {!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>);}