Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(monitors): populate trace/observation name filter suggestions (LFE-10659) (#14860)

Mark Salpeter71f5a52f0bf2
diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.ts
index bc7ec0b4c5..bde5e1e590 100644
--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts
@@ -746,48 +746,6 @@ describe("Clickhouse Events Repository Test", () => {
expect(Number(range?.max)).toBeCloseTo(1, 3);
});
});
-
- it("uses the monitor window to scope monitor filter option queries", async () => {
- const uniqueProjectId = randomUUID();
- const traceId = randomUUID();
- const now = Date.now();
- const recentLevel = "WARNING";
- const oldLevel = "ERROR";
-
- await createEventsCh([
- createEvent({
- id: randomUUID(),
- span_id: randomUUID(),
- project_id: uniqueProjectId,
- trace_id: traceId,
- type: "SPAN",
- name: "recent-monitor-filter-option-event",
- level: recentLevel,
- start_time: (now - 60 * 1000) * 1000,
- }),
- createEvent({
- id: randomUUID(),
- span_id: randomUUID(),
- project_id: uniqueProjectId,
- trace_id: traceId,
- type: "SPAN",
- name: "old-monitor-filter-option-event",
- level: oldLevel,
- start_time: (now - 10 * 60 * 1000) * 1000,
- }),
- ]);
-
- await waitForExpect(async () => {
- const options = await getEventFilterOptions({
- projectId: uniqueProjectId,
- monitorWindow: "5m",
- });
- const levels = options.level.map((level) => level.value);
-
- expect(levels).toContain(recentLevel);
- expect(levels).not.toContain(oldLevel);
- });
- });
});
maybe("events filter option repository helpers", () => {
diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.ts
index 4a12e8477c..62b251c751 100644
--- a/web/src/features/events/server/eventsRouter.ts
+++ b/web/src/features/events/server/eventsRouter.ts
@@ -11,7 +11,6 @@ import {
paginationZod,
timeFilter,
} from "@langfuse/shared";
-import { MonitorWindowSchema } from "@langfuse/shared/monitors";
import {
toDomainArrayWithStringifiedMetadata,
toDomainWithStringifiedMetadata,
@@ -58,7 +57,6 @@ export type GetAllEventsInput = z.infer<typeof GetAllEventsInput>;
const GetEventFilterOptionsInput = zodSchema.object({
projectId: zodSchema.string(),
startTimeFilter: zodSchema.array(timeFilter).optional(),
- monitorWindow: MonitorWindowSchema.optional(),
isRootObservation: zodSchema.boolean().optional(),
hasParentObservation: zodSchema.boolean().optional(),
columns: zodSchema
@@ -170,7 +168,6 @@ export const eventsRouter = createTRPCRouter({
return getEventFilterOptions({
projectId: input.projectId,
startTimeFilter: input.startTimeFilter,
- monitorWindow: input.monitorWindow,
isRootObservation:
input.isRootObservation ??
(input.hasParentObservation !== undefined
diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.ts
index f765cf2823..402a574c5e 100644
--- a/web/src/features/events/server/eventsService.ts
+++ b/web/src/features/events/server/eventsService.ts
@@ -22,11 +22,6 @@ import {
type EventFilterOptionColumn,
} from "@langfuse/shared/src/server";
import { type timeFilter, type FilterState } from "@langfuse/shared";
-import {
- monitorEvaluationOffsetMs,
- type MonitorWindow,
- windowToMs,
-} from "@langfuse/shared/monitors";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
type TimeFilter = z.infer<typeof timeFilter>;
@@ -82,7 +77,6 @@ interface GetObservationsCountParams {
interface GetObservationsFilterOptionsParams {
projectId: string;
startTimeFilter?: TimeFilter[];
- monitorWindow?: MonitorWindow;
isRootObservation?: boolean;
hasParentObservation?: boolean;
observationType?: string;
@@ -155,29 +149,6 @@ const getDefaultEventFilterOptionsStartTimeFilter = (): TimeFilter[] => [
},
];
-const getMonitorWindowStartTimeFilter = (
- monitorWindow: MonitorWindow,
-): TimeFilter[] => {
- const windowMs = Number(windowToMs(monitorWindow));
- const to = new Date(Date.now() - monitorEvaluationOffsetMs);
- const from = new Date(to.getTime() - windowMs);
-
- return [
- {
- column: "startTime",
- type: "datetime",
- operator: ">=",
- value: from,
- },
- {
- column: "startTime",
- type: "datetime",
- operator: "<=",
- value: to,
- },
- ];
-};
-
const ensureStartTimeFilterForEventFilterOptions = <
TParams extends GetObservationsFilterOptionsParams,
>(
@@ -187,16 +158,6 @@ const ensureStartTimeFilterForEventFilterOptions = <
return params;
}
- if (params.monitorWindow) {
- return {
- ...params,
- startTimeFilter: [
- ...getMonitorWindowStartTimeFilter(params.monitorWindow),
- ...(params.startTimeFilter ?? []),
- ],
- };
- }
-
logger.warn(
"events.filterOptions called without lower startTimeFilter; applying default lookback",
{
diff --git a/web/src/features/monitors/components/MonitorChartPreview.tsx b/web/src/features/monitors/components/MonitorChartPreview.tsx
index 19c40008cb..e375e1a40a 100644
--- a/web/src/features/monitors/components/MonitorChartPreview.tsx
+++ b/web/src/features/monitors/components/MonitorChartPreview.tsx
@@ -21,9 +21,7 @@ import {
} from "@langfuse/shared/monitors";
import { renderChartSubtitle } from "../helpers/renderMonitorLabels";
-
-/** previewBucketCount is the number of complete window buckets the preview renders. */
-const previewBucketCount = 20;
+import { getMonitorPreviewRange } from "../helpers/monitorTimeRanges";
/** MonitorChartPreview renders the live time-series preview with alert/warning threshold bands for a monitor draft. */
export const MonitorChartPreview = ({
@@ -49,12 +47,10 @@ export const MonitorChartPreview = ({
}) => {
/** bucketRange spans 20 complete window buckets ending at the last floored boundary. */
const { fromTimestamp, toTimestamp } = useMemo(() => {
- const ms = Number(windowToMs(window));
- const to = Math.floor(Date.now() / ms) * ms;
- const from = to - previewBucketCount * ms;
+ const { from, to } = getMonitorPreviewRange(window, Date.now());
return {
- toTimestamp: new Date(to).toISOString(),
- fromTimestamp: new Date(from).toISOString(),
+ toTimestamp: to.toISOString(),
+ fromTimestamp: from.toISOString(),
};
}, [window]);
diff --git a/web/src/features/monitors/components/MonitorForm.clienttest.ts b/web/src/features/monitors/components/MonitorForm.clienttest.ts
index bb59054a8b..4f8fb7a490 100644
--- a/web/src/features/monitors/components/MonitorForm.clienttest.ts
+++ b/web/src/features/monitors/components/MonitorForm.clienttest.ts
@@ -140,6 +140,28 @@ describe("buildFilterColumnsParams", () => {
expect(values.length).toBeGreaterThan(0);
});
+ it("maps filterOptions.name into a searchable Observation Name stringOptions column", () => {
+ const params = buildFilterColumnsParams({
+ view: "observations",
+ filterOptions: {
+ name: [{ value: "generation-alpha" }, { value: "generation-beta" }],
+ } as Parameters<typeof buildFilterColumnsParams>[0]["filterOptions"],
+ datasets: undefined,
+ });
+ const column = getWidgetFilterColumns(params).find(
+ (c) => c.id === "observationName",
+ );
+ expect(column?.type).toBe("stringOptions");
+ const values =
+ column?.type === "stringOptions"
+ ? column.options.map((o) => o.value)
+ : [];
+ expect(values).toEqual(["generation-alpha", "generation-beta"]);
+ expect(getWidgetColumnsWithCustomSelect(params)).toContain(
+ "observationName",
+ );
+ });
+
it("keeps Type/Level as non-searchable columns (they rely on complete option lists)", () => {
// Confirms the fix must be complete enum lists: Type/Level are NOT custom
// (searchable/free-text) selects, so an empty option list is a hard dead-end.
diff --git a/web/src/features/monitors/components/MonitorForm.tsx b/web/src/features/monitors/components/MonitorForm.tsx
index bebcedb6c5..cb14e40989 100644
--- a/web/src/features/monitors/components/MonitorForm.tsx
+++ b/web/src/features/monitors/components/MonitorForm.tsx
@@ -80,11 +80,13 @@ import {
ObservationTypeDomain,
viewDeclarations,
type FilterState,
+ type TimeFilter,
} from "@langfuse/shared";
import TagManager from "@/src/features/tag/components/TagManager";
import { MonitorChartPreview } from "./MonitorChartPreview";
+import { getMonitorFilterOptionsLookbackFrom } from "../helpers/monitorTimeRanges";
import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";
import { MonitorSeverityBadge } from "./MonitorSeverityBadge";
import { Badge } from "@/src/components/ui/badge";
@@ -181,6 +183,7 @@ const buildFilterColumnsParams = ({
viewVersion: "v2" as const,
environmentOptions: filterOptions?.environment ?? [],
nameOptions: normalizeSingleValueOptions(filterOptions?.traceName),
+ observationNameOptions: normalizeSingleValueOptions(filterOptions?.name),
tagsOptions: filterOptions?.traceTags ?? [],
modelOptions: filterOptions?.providedModelName ?? [],
toolNamesOptions: filterOptions?.toolNames ?? [],
@@ -312,6 +315,19 @@ export const MonitorForm = ({
const watched = useWatch({ control: form.control });
const monitorWindow = (watched.window ?? "5m") as MonitorWindow;
+ /** filterOptionsStartTimeFilter lower-bounds discovery at max(20×window, 7d) so even a small monitor window still yields value suggestions. */
+ const filterOptionsStartTimeFilter = useMemo<TimeFilter[]>(
+ () => [
+ {
+ column: "startTime",
+ type: "datetime",
+ operator: ">=",
+ value: getMonitorFilterOptionsLookbackFrom(monitorWindow, Date.now()),
+ },
+ ],
+ [monitorWindow],
+ );
+
// Push the live name up to the host (e.g. the edit page header) so the page
// title can mirror it as the user types instead of waiting for save.
useEffect(() => {
@@ -322,7 +338,7 @@ export const MonitorForm = ({
const eventsFilterOptions = api.events.filterOptions.useQuery(
{
projectId,
- monitorWindow,
+ startTimeFilter: filterOptionsStartTimeFilter,
},
{
trpc: { context: { skipBatch: true } },
diff --git a/web/src/features/monitors/helpers/monitorTimeRanges.clienttest.ts b/web/src/features/monitors/helpers/monitorTimeRanges.clienttest.ts
new file mode 100644
index 0000000000..482d1d8a11
--- /dev/null
+++ b/web/src/features/monitors/helpers/monitorTimeRanges.clienttest.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+
+import { windowToMs } from "@langfuse/shared/monitors";
+
+import {
+ getMonitorFilterOptionsLookbackFrom,
+ getMonitorPreviewRange,
+ monitorPreviewBucketCount,
+} from "./monitorTimeRanges";
+
+const sevenDaysMs = 7 * 24 * 60 * 60 * 1000;
+
+describe("getMonitorPreviewRange", () => {
+ it("spans 20 window buckets ending at the last floored boundary", () => {
+ const bucketMs = Number(windowToMs("5m"));
+ const now = 1_700_000_123_456;
+ const range = getMonitorPreviewRange("5m", now);
+ expect(range.bucketMs).toBe(bucketMs);
+ expect(range.to.getTime()).toBe(Math.floor(now / bucketMs) * bucketMs);
+ expect(range.to.getTime() - range.from.getTime()).toBe(
+ monitorPreviewBucketCount * bucketMs,
+ );
+ });
+
+ it("returns the same bucketed `to` for two instants inside one window bucket", () => {
+ const bucketMs = Number(windowToMs("5m"));
+ const boundary = Math.floor(1_700_000_123_456 / bucketMs) * bucketMs;
+ const early = getMonitorPreviewRange("5m", boundary + 1);
+ const late = getMonitorPreviewRange("5m", boundary + bucketMs - 1);
+ expect(early.to.getTime()).toBe(boundary);
+ expect(late.to.getTime()).toBe(boundary);
+ });
+});
+
+describe("getMonitorFilterOptionsLookbackFrom", () => {
+ it("floors the lookback at 7d for a small window whose 20-bucket span is shorter", () => {
+ const now = 1_700_000_123_456;
+ const { to } = getMonitorPreviewRange("5m", now);
+ const from = getMonitorFilterOptionsLookbackFrom("5m", now);
+ expect(to.getTime() - from.getTime()).toBe(sevenDaysMs);
+ });
+
+ it("uses the full 20-bucket span for a large window that exceeds 7d", () => {
+ const now = 1_700_000_123_456;
+ const { to, bucketMs } = getMonitorPreviewRange("1d", now);
+ const from = getMonitorFilterOptionsLookbackFrom("1d", now);
+ expect(to.getTime() - from.getTime()).toBe(
+ monitorPreviewBucketCount * bucketMs,
+ );
+ });
+});
diff --git a/web/src/features/monitors/helpers/monitorTimeRanges.ts b/web/src/features/monitors/helpers/monitorTimeRanges.ts
new file mode 100644
index 0000000000..00b02e979e
--- /dev/null
+++ b/web/src/features/monitors/helpers/monitorTimeRanges.ts
@@ -0,0 +1,38 @@
+import { type MonitorWindow, windowToMs } from "@langfuse/shared/monitors";
+
+/** monitorPreviewBucketCount is the number of complete window buckets the preview renders. */
+export const monitorPreviewBucketCount = 20;
+
+/** monitorFilterOptionsLookbackFloorMs is the 7d floor guaranteeing non-empty filter suggestions for small windows. */
+const monitorFilterOptionsLookbackFloorMs = 7 * 24 * 60 * 60 * 1000;
+
+/** getMonitorPreviewRange returns the 20-bucket preview span ending at the last floored window boundary. */
+export const getMonitorPreviewRange = (
+ window: MonitorWindow,
+ now: number,
+): MonitorPreviewRange => {
+ const bucketMs = Number(windowToMs(window));
+ const to = Math.floor(now / bucketMs) * bucketMs;
+ const from = to - monitorPreviewBucketCount * bucketMs;
+ return { from: new Date(from), to: new Date(to), bucketMs };
+};
+
+/** getMonitorFilterOptionsLookbackFrom returns the discovery lower bound: the preview `to` minus max(20×window, 7d). */
+export const getMonitorFilterOptionsLookbackFrom = (
+ window: MonitorWindow,
+ now: number,
+): Date => {
+ const { to, bucketMs } = getMonitorPreviewRange(window, now);
+ const spanMs = Math.max(
+ monitorPreviewBucketCount * bucketMs,
+ monitorFilterOptionsLookbackFloorMs,
+ );
+ return new Date(to.getTime() - spanMs);
+};
+
+/** MonitorPreviewRange is the bucketed [from, to] preview span plus the per-bucket width. */
+type MonitorPreviewRange = {
+ from: Date;
+ to: Date;
+ bucketMs: number;
+};
diff --git a/web/src/features/widgets/components/WidgetForm.observationNameOptions.clienttest.tsx b/web/src/features/widgets/components/WidgetForm.observationNameOptions.clienttest.tsx
new file mode 100644
index 0000000000..6282d2821c
--- /dev/null
+++ b/web/src/features/widgets/components/WidgetForm.observationNameOptions.clienttest.tsx
@@ -0,0 +1,106 @@
+import { render } from "@testing-library/react";
+
+// Hoisted so the vi.mock factory can reference them.
+const { generationsFilterOptionsUseQuery, noopQuery } = vi.hoisted(() => ({
+ generationsFilterOptionsUseQuery: vi.fn(() => ({
+ data: undefined,
+ isLoading: false,
+ isSuccess: false,
+ })),
+ noopQuery: () => ({
+ data: undefined,
+ isLoading: false,
+ isSuccess: false,
+ isPending: false,
+ isError: false,
+ isFetching: false,
+ error: null,
+ refetch: vi.fn(),
+ }),
+}));
+
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ traces: { filterOptions: { useQuery: noopQuery } },
+ generations: {
+ filterOptions: { useQuery: generationsFilterOptionsUseQuery },
+ },
+ events: { filterOptions: { useQuery: noopQuery } },
+ projects: { environmentFilterOptions: { useQuery: noopQuery } },
+ datasets: { allDatasetMeta: { useQuery: noopQuery } },
+ dashboard: { executeQuery: { useQuery: noopQuery } },
+ },
+}));
+
+// Force the v1 path, which sources the observation-name picker from generations.
+vi.mock("@/src/features/events/hooks/useV4Beta", () => ({
+ useV4Beta: () => ({ isBetaEnabled: false }),
+}));
+
+vi.mock("next/router", () => ({
+ useRouter: () => ({
+ query: {},
+ asPath: "/",
+ push: vi.fn(),
+ replace: vi.fn(),
+ isReady: true,
+ }),
+}));
+
+vi.mock("use-query-params", () => ({
+ StringParam: {},
+ useQueryParams: () => [{ dateRange: undefined }, vi.fn()],
+}));
+
+vi.mock("next-auth/react", () => ({
+ useSession: () => ({ data: null, status: "unauthenticated" }),
+}));
+
+import { WidgetForm } from "./WidgetForm";
+
+describe("WidgetForm v1 observation-name options", () => {
+ beforeAll(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ Element.prototype.scrollIntoView = vi.fn();
+ Element.prototype.hasPointerCapture = vi.fn();
+ Element.prototype.releasePointerCapture = vi.fn();
+ });
+
+ it("v1 observations view queries observation names across ALL types", () => {
+ // The six filter-option queries fire at the top of the component body; a
+ // downstream child (filter builder / chart) may crash after, which is
+ // irrelevant to what input the query under test received.
+ try {
+ render(
+ <WidgetForm
+ projectId="p1"
+ onSave={vi.fn()}
+ initialValues={{
+ name: "w",
+ description: "",
+ view: "observations",
+ measure: "count",
+ aggregation: "count",
+ dimension: "none",
+ chartType: "LINE_TIME_SERIES",
+ filters: [],
+ }}
+ />,
+ );
+ } catch {
+ // Ignore downstream render failures; see comment above.
+ }
+
+ expect(generationsFilterOptionsUseQuery).toHaveBeenCalledWith(
+ expect.objectContaining({ observationType: "ALL" }),
+ expect.anything(),
+ );
+ });
+});
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index b805e1bde3..33eeb5b653 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -682,6 +682,7 @@ export function WidgetForm({
{
projectId,
startTimeFilter: getDateRangeFilter("startTime", dateRange),
+ observationType: "ALL",
},
{
trpc: {
@@ -755,6 +756,10 @@ export function WidgetForm({
viewVersion === "v2"
? normalizeSingleValueOptions(eventsFilterOptions.data?.traceName)
: normalizeSingleValueOptions(traceFilterOptions.data?.name);
+ const observationNameOptions =
+ viewVersion === "v2"
+ ? normalizeSingleValueOptions(eventsFilterOptions.data?.name)
+ : normalizeSingleValueOptions(generationsFilterOptions.data?.name);
const tagsOptions =
viewVersion === "v2"
? eventsFilterOptions.data?.traceTags || []
@@ -790,6 +795,7 @@ export function WidgetForm({
viewVersion,
environmentOptions,
nameOptions,
+ observationNameOptions,
tagsOptions,
modelOptions,
toolNamesOptions,
@@ -804,6 +810,7 @@ export function WidgetForm({
viewVersion,
environmentOptions,
nameOptions,
+ observationNameOptions,
tagsOptions,
modelOptions,
toolNamesOptions,
@@ -823,6 +830,7 @@ export function WidgetForm({
viewVersion,
environmentOptions,
nameOptions,
+ observationNameOptions,
tagsOptions,
modelOptions,
toolNamesOptions,
diff --git a/web/src/features/widgets/components/widgetFilterColumns.ts b/web/src/features/widgets/components/widgetFilterColumns.ts
index 7142e04644..c986ea46a0 100644
--- a/web/src/features/widgets/components/widgetFilterColumns.ts
+++ b/web/src/features/widgets/components/widgetFilterColumns.ts
@@ -11,6 +11,7 @@ type GetWidgetFilterColumnsParams = {
viewVersion: ViewVersion;
environmentOptions: SingleValueOption[];
nameOptions: SingleValueOption[];
+ observationNameOptions: SingleValueOption[];
tagsOptions: SingleValueOption[];
modelOptions: SingleValueOption[];
toolNamesOptions: SingleValueOption[];
@@ -31,6 +32,7 @@ const getWidgetFilterColumnSpecs = ({
viewVersion,
environmentOptions,
nameOptions,
+ observationNameOptions,
tagsOptions,
modelOptions,
toolNamesOptions,
@@ -129,9 +131,11 @@ const getWidgetFilterColumnSpecs = ({
column: {
name: "Observation Name",
id: "observationName",
- type: "string",
+ type: "stringOptions",
+ options: observationNameOptions,
internal: "internalValue",
},
+ customSelect: true,
});
}
@@ -152,9 +156,11 @@ const getWidgetFilterColumnSpecs = ({
column: {
name: "Observation Name",
id: "observationName",
- type: "string",
+ type: "stringOptions",
+ options: observationNameOptions,
internal: "internalValue",
},
+ customSelect: true,
},
);
}