Skip to content

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

fix(v4): fill empty timeline buckets (#14571)

Max Deichmann31cda869e238
diff --git a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
index d4276bb1bc..37a0e40379 100644
--- a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
+++ b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
@@ -79,7 +79,7 @@ describe("v4TransitionRouter", () => {
beforeEach(() => {
mockedQueryClickhouse.mockResolvedValue([
{
- time: "2026-06-25T12:00:00Z",
+ time: "2026-06-24T12:00:00Z",
entrypoint: "publicapi: GET /api/public/traces/{id}",
count: "0.6666666666666666",
},
@@ -100,13 +100,28 @@ describe("v4TransitionRouter", () => {
granularity: "auto",
});
- expect(rows).toEqual([
- {
- time: "2026-06-25T12:00:00Z",
- entrypoint: "publicapi: GET /api/public/traces/{id}",
- count: 0.6666666666666666,
- },
- ]);
+ expect(rows).toHaveLength(25);
+ expect(new Set(rows.map((row) => row.time)).size).toBe(24);
+ expect(rows[0]).toEqual({
+ time: "2026-06-24T00:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[12]).toEqual({
+ time: "2026-06-24T12:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[13]).toEqual({
+ time: "2026-06-24T12:00:00Z",
+ entrypoint: "publicapi: GET /api/public/traces/{id}",
+ count: 0.6666666666666666,
+ });
+ expect(rows[24]).toEqual({
+ time: "2026-06-24T23:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
expect(mockedQueryClickhouse).toHaveBeenCalledTimes(1);
const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
@@ -170,6 +185,244 @@ describe("v4TransitionRouter", () => {
);
});
+ it("fills daily buckets for a 30 day timeline", async () => {
+ mockedQueryClickhouse.mockResolvedValueOnce([
+ {
+ time: "2026-06-10T00:00:00Z",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: "42",
+ },
+ ]);
+
+ const caller = v4TransitionRouter.createCaller(
+ createInnerTRPCContext({ session, headers: {} }),
+ );
+
+ const rows = await caller.timeSeriesByEntrypoint({
+ projectId,
+ fromTimestamp: new Date("2026-05-26T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ granularity: "auto",
+ });
+
+ expect(rows).toHaveLength(31);
+ expect(new Set(rows.map((row) => row.time)).size).toBe(30);
+ expect(rows[0]).toEqual({
+ time: "2026-05-26T00:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[15]).toEqual({
+ time: "2026-06-10T00:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[16]).toEqual({
+ time: "2026-06-10T00:00:00Z",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 42,
+ });
+ expect(rows[30]).toEqual({
+ time: "2026-06-24T00:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+
+ const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(clickhouseQuery?.query).toContain(
+ "toStartOfInterval(event_time_microseconds, INTERVAL 1 DAY, 'UTC') AS bucket_time",
+ );
+ });
+
+ it("fills 2 minute buckets for a 1 hour timeline", async () => {
+ mockedQueryClickhouse.mockResolvedValueOnce([
+ {
+ time: "2026-06-24T00:20:00Z",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: "8",
+ },
+ ]);
+
+ const caller = createCaller();
+
+ const rows = await caller.timeSeriesByEntrypoint({
+ projectId,
+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),
+ toTimestamp: new Date("2026-06-24T01:00:00Z"),
+ granularity: "auto",
+ });
+
+ expect(rows).toHaveLength(31);
+ expect(new Set(rows.map((row) => row.time)).size).toBe(30);
+ expect(rows[0]).toEqual({
+ time: "2026-06-24T00:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[10]).toEqual({
+ time: "2026-06-24T00:20:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[11]).toEqual({
+ time: "2026-06-24T00:20:00Z",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 8,
+ });
+ expect(rows[30]).toEqual({
+ time: "2026-06-24T00:58:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+
+ const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(clickhouseQuery?.query).toContain(
+ "toStartOfInterval(event_time_microseconds, INTERVAL 2 MINUTE, 'UTC') AS bucket_time",
+ );
+ });
+
+ it("fills minute buckets for a non-special 45 minute timeline", async () => {
+ mockedQueryClickhouse.mockResolvedValueOnce([
+ {
+ time: "2026-06-24T00:15:00Z",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: "8",
+ },
+ ]);
+
+ const caller = createCaller();
+
+ const rows = await caller.timeSeriesByEntrypoint({
+ projectId,
+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),
+ toTimestamp: new Date("2026-06-24T00:45:00Z"),
+ granularity: "auto",
+ });
+
+ expect(rows).toHaveLength(46);
+ expect(new Set(rows.map((row) => row.time)).size).toBe(45);
+ expect(rows[0]).toEqual({
+ time: "2026-06-24T00:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[15]).toEqual({
+ time: "2026-06-24T00:15:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[16]).toEqual({
+ time: "2026-06-24T00:15:00Z",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 8,
+ });
+ expect(rows[45]).toEqual({
+ time: "2026-06-24T00:44:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+
+ const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(clickhouseQuery?.query).toContain(
+ "toStartOfInterval(event_time_microseconds, INTERVAL 1 MINUTE, 'UTC') AS bucket_time",
+ );
+ });
+
+ it("fills 5 minute buckets for a 3 hour timeline", async () => {
+ mockedQueryClickhouse.mockResolvedValueOnce([
+ {
+ time: "2026-06-24T01:00:00Z",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: "12",
+ },
+ ]);
+
+ const caller = createCaller();
+
+ const rows = await caller.timeSeriesByEntrypoint({
+ projectId,
+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),
+ toTimestamp: new Date("2026-06-24T03:00:00Z"),
+ granularity: "auto",
+ });
+
+ expect(rows).toHaveLength(37);
+ expect(new Set(rows.map((row) => row.time)).size).toBe(36);
+ expect(rows[0]).toEqual({
+ time: "2026-06-24T00:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[12]).toEqual({
+ time: "2026-06-24T01:00:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+ expect(rows[13]).toEqual({
+ time: "2026-06-24T01:00:00Z",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 12,
+ });
+ expect(rows[36]).toEqual({
+ time: "2026-06-24T02:55:00Z",
+ entrypoint: "",
+ count: 0,
+ });
+
+ const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(clickhouseQuery?.query).toContain(
+ "toStartOfInterval(event_time_microseconds, INTERVAL 5 MINUTE, 'UTC') AS bucket_time",
+ );
+ });
+
+ it("uses minute buckets for a non-special 7 day timeline", async () => {
+ mockedQueryClickhouse.mockResolvedValueOnce([]);
+
+ const caller = createCaller();
+
+ const rows = await caller.timeSeriesByEntrypoint({
+ projectId,
+ fromTimestamp: new Date("2026-06-18T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ granularity: "auto",
+ });
+
+ expect(rows).toEqual([]);
+
+ const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(clickhouseQuery?.query).toContain(
+ "toStartOfInterval(event_time_microseconds, INTERVAL 1 MINUTE, 'UTC') AS bucket_time",
+ );
+ });
+
+ it("rejects ranges over 30 days", async () => {
+ const mockPrisma = {
+ $queryRaw: vi.fn(),
+ };
+ const caller = createCaller(mockPrisma);
+
+ await expect(
+ caller.timeSeriesByEntrypoint({
+ projectId,
+ fromTimestamp: new Date("2026-05-25T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ granularity: "auto",
+ }),
+ ).rejects.toThrow("30 days");
+
+ await expect(
+ caller.traceLevelEvalExecutionsTimeSeries({
+ projectId,
+ fromTimestamp: new Date("2026-05-25T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ granularity: "auto",
+ }),
+ ).rejects.toThrow("30 days");
+
+ expect(mockedQueryClickhouse).not.toHaveBeenCalled();
+ expect(mockPrisma.$queryRaw).not.toHaveBeenCalled();
+ });
+
it("summarizes trace-level evals and legacy integrations", async () => {
const mockPrisma = {
jobConfiguration: {
@@ -264,7 +517,7 @@ describe("v4TransitionRouter", () => {
});
});
- it("queries trace-level eval execution counts by time bucket and generated score name", async () => {
+ it("queries trace-level eval execution counts with the same 2 minute buckets as the legacy API timeline", async () => {
const mockPrisma = {
$queryRaw: vi.fn().mockResolvedValue([
{
@@ -273,7 +526,7 @@ describe("v4TransitionRouter", () => {
count: 4n,
},
{
- time: "2026-06-25T12:05:00Z",
+ time: "2026-06-25T12:04:00Z",
scoreName: "helpfulness",
count: 2,
},
@@ -288,7 +541,7 @@ describe("v4TransitionRouter", () => {
granularity: "auto",
});
- expect(rows).toHaveLength(122);
+ expect(rows).toHaveLength(60);
expect(rows.slice(0, 4)).toEqual([
{
time: "2026-06-25T12:00:00Z",
@@ -301,12 +554,12 @@ describe("v4TransitionRouter", () => {
count: 4,
},
{
- time: "2026-06-25T12:01:00Z",
+ time: "2026-06-25T12:02:00Z",
scoreName: "helpfulness",
count: 0,
},
{
- time: "2026-06-25T12:01:00Z",
+ time: "2026-06-25T12:02:00Z",
scoreName: "toxicity",
count: 0,
},
@@ -314,16 +567,16 @@ describe("v4TransitionRouter", () => {
expect(
rows.find(
(row) =>
- row.time === "2026-06-25T12:05:00Z" &&
+ row.time === "2026-06-25T12:04:00Z" &&
row.scoreName === "helpfulness",
),
).toEqual({
- time: "2026-06-25T12:05:00Z",
+ time: "2026-06-25T12:04:00Z",
scoreName: "helpfulness",
count: 2,
});
expect(rows.at(-1)).toEqual({
- time: "2026-06-25T13:00:00Z",
+ time: "2026-06-25T12:58:00Z",
scoreName: "toxicity",
count: 0,
});
@@ -334,7 +587,7 @@ describe("v4TransitionRouter", () => {
| undefined;
const queryText = query?.sql ?? query?.text ?? "";
- expect(queryText).toContain("date_trunc(?, je.created_at)");
+ expect(queryText).toContain("date_bin(?::interval, je.created_at");
expect(queryText).toContain(
"INNER JOIN job_configurations jc ON jc.id = je.job_configuration_id",
);
@@ -347,9 +600,10 @@ describe("v4TransitionRouter", () => {
expect(queryText).toContain("je.status != 'CANCELLED'");
expect(queryText).toContain("je.created_at >= ?");
expect(queryText).toContain("je.created_at <= ?");
+ expect(queryText).toContain("bucket_time AT TIME ZONE 'UTC'");
expect(queryText).toContain("GROUP BY bucket_time, score_name");
expect(query?.values).toEqual([
- "minute",
+ "2 minutes",
projectId,
projectId,
"trace",
@@ -357,4 +611,25 @@ describe("v4TransitionRouter", () => {
new Date("2026-06-25T13:00:00Z"),
]);
});
+
+ it("uses minute buckets for non-special trace-level eval execution timelines", async () => {
+ const mockPrisma = {
+ $queryRaw: vi.fn().mockResolvedValue([]),
+ };
+ const caller = createCaller(mockPrisma);
+
+ const rows = await caller.traceLevelEvalExecutionsTimeSeries({
+ projectId,
+ fromTimestamp: new Date("2026-06-18T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ granularity: "auto",
+ });
+
+ expect(rows).toEqual([]);
+
+ const query = mockPrisma.$queryRaw.mock.calls[0]?.[0] as
+ | { sql?: string; text?: string; values?: unknown[] }
+ | undefined;
+ expect(query?.values?.[0]).toBe("1 minute");
+ });
});
diff --git a/web/src/features/v4/server/v4TransitionRouter.ts b/web/src/features/v4/server/v4TransitionRouter.ts
index 34aeffc3dd..20c578a130 100644
--- a/web/src/features/v4/server/v4TransitionRouter.ts
+++ b/web/src/features/v4/server/v4TransitionRouter.ts
@@ -14,20 +14,26 @@ import {
} from "@langfuse/shared/src/server";
const timelineGranularity = z.literal("auto");
-type ResolvedTimelineGranularity = "minute" | "hour" | "day" | "week" | "month";
+type ResolvedTimelineGranularity = "minute" | "2m" | "5m" | "hour" | "day";
+const MINUTE_MS = 60 * 1000;
+const MAX_TIMELINE_RANGE_MS = 30 * 24 * 60 * 60 * 1000;
+const TIMELINE_GRANULARITY_DURATION_TOLERANCE_MS = 1000;
+
+const isTimelineDuration = (actualMs: number, expectedMs: number): boolean =>
+ Math.abs(actualMs - expectedMs) <= TIMELINE_GRANULARITY_DURATION_TOLERANCE_MS;
const resolveTimelineGranularity = (
fromTimestamp: Date,
toTimestamp: Date,
): ResolvedTimelineGranularity => {
const diffMs = toTimestamp.getTime() - fromTimestamp.getTime();
- const diffHours = diffMs / (1000 * 60 * 60);
- if (diffHours < 2) return "minute";
- if (diffHours < 72) return "hour";
- if (diffHours < 1440) return "day";
- if (diffHours < 8760) return "week";
- return "month";
+ if (isTimelineDuration(diffMs, 60 * MINUTE_MS)) return "2m";
+ if (isTimelineDuration(diffMs, 3 * 60 * MINUTE_MS)) return "5m";
+ if (isTimelineDuration(diffMs, 24 * 60 * MINUTE_MS)) return "hour";
+ if (isTimelineDuration(diffMs, MAX_TIMELINE_RANGE_MS)) return "day";
+
+ return "minute";
};
const getTimelineBucketSql = (
@@ -36,10 +42,10 @@ const getTimelineBucketSql = (
): string => {
const intervalByGranularity: Record<ResolvedTimelineGranularity, string> = {
minute: "1 MINUTE",
+ "2m": "2 MINUTE",
+ "5m": "5 MINUTE",
hour: "1 HOUR",
day: "1 DAY",
- week: "1 WEEK",
- month: "1 MONTH",
};
return `toStartOfInterval(${sql}, INTERVAL ${intervalByGranularity[granularity]}, 'UTC')`;
@@ -48,100 +54,163 @@ const getTimelineBucketSql = (
const getPostgresTimelineBucketExpression = (
granularity: ResolvedTimelineGranularity,
): Prisma.Sql => {
- const precisionByGranularity: Record<ResolvedTimelineGranularity, string> = {
- minute: "minute",
- hour: "hour",
- day: "day",
- week: "week",
- month: "month",
+ const intervalByGranularity: Record<ResolvedTimelineGranularity, string> = {
+ minute: "1 minute",
+ "2m": "2 minutes",
+ "5m": "5 minutes",
+ hour: "1 hour",
+ day: "1 day",
};
- return Prisma.sql`date_trunc(${precisionByGranularity[granularity]}, je.created_at)`;
+ return Prisma.sql`date_bin(${intervalByGranularity[granularity]}::interval, je.created_at, '1970-01-01T00:00:00Z'::timestamptz)`;
};
-const startOfTimelineBucket = (
- date: Date,
- granularity: ResolvedTimelineGranularity,
-): Date => {
- const bucket = new Date(date);
+const legacyIntegrationExportSources =
+ new Set<AnalyticsIntegrationExportSource>([
+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,
+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,
+ ]);
- bucket.setUTCSeconds(0, 0);
+const TRACE_EVAL_TARGET = "trace";
- if (granularity === "minute") return bucket;
+const isLegacyIntegrationExportSource = (
+ exportSource: AnalyticsIntegrationExportSource | null | undefined,
+) => exportSource != null && legacyIntegrationExportSources.has(exportSource);
- bucket.setUTCMinutes(0, 0, 0);
+const isEnabledLegacyIntegration = (
+ integration:
+ | { enabled: boolean; exportSource: AnalyticsIntegrationExportSource }
+ | null
+ | undefined,
+) =>
+ Boolean(
+ integration?.enabled &&
+ isLegacyIntegrationExportSource(integration.exportSource),
+ );
- if (granularity === "hour") return bucket;
+const timelineInputSchema = z
+ .object({
+ projectId: z.string(),
+ fromTimestamp: z.date(),
+ toTimestamp: z.date(),
+ granularity: timelineGranularity.default("auto"),
+ })
+ .refine(
+ ({ fromTimestamp, toTimestamp }) =>
+ toTimestamp.getTime() > fromTimestamp.getTime(),
+ { message: "fromTimestamp must be before toTimestamp" },
+ )
+ .refine(
+ ({ fromTimestamp, toTimestamp }) =>
+ toTimestamp.getTime() - fromTimestamp.getTime() <= MAX_TIMELINE_RANGE_MS,
+ { message: "V4 timeline ranges cannot exceed 30 days" },
+ );
- bucket.setUTCHours(0, 0, 0, 0);
+type LegacyApiUsageRow = {
+ time: string;
+ entrypoint: string;
+ count: string | number;
+};
- if (granularity === "day") return bucket;
+type LegacyApiUsageResultRow = {
+ time: string;
+ entrypoint: string;
+ count: number;
+};
- if (granularity === "week") {
- const daysSinceMonday = (bucket.getUTCDay() + 6) % 7;
- bucket.setUTCDate(bucket.getUTCDate() - daysSinceMonday);
- return bucket;
- }
+const floorTimelineBucket = (
+ timestamp: Date,
+ granularity: ResolvedTimelineGranularity,
+): Date => {
+ const bucket = new Date(timestamp);
- bucket.setUTCDate(1);
- return bucket;
+ switch (granularity) {
+ case "minute":
+ bucket.setUTCSeconds(0, 0);
+ return bucket;
+ case "2m":
+ bucket.setUTCMinutes(Math.floor(bucket.getUTCMinutes() / 2) * 2, 0, 0);
+ return bucket;
+ case "5m":
+ bucket.setUTCMinutes(Math.floor(bucket.getUTCMinutes() / 5) * 5, 0, 0);
+ return bucket;
+ case "hour":
+ bucket.setUTCMinutes(0, 0, 0);
+ return bucket;
+ case "day":
+ bucket.setUTCHours(0, 0, 0, 0);
+ return bucket;
+ default: {
+ const exhaustiveCheck: never = granularity;
+ throw new Error(`Invalid timeline granularity: ${exhaustiveCheck}`);
+ }
+ }
};
-const incrementTimelineBucket = (
- date: Date,
+const addTimelineBucket = (
+ timestamp: Date,
granularity: ResolvedTimelineGranularity,
): Date => {
- const next = new Date(date);
+ const next = new Date(timestamp);
switch (granularity) {
case "minute":
next.setUTCMinutes(next.getUTCMinutes() + 1);
return next;
+ case "2m":
+ next.setUTCMinutes(next.getUTCMinutes() + 2);
+ return next;
+ case "5m":
+ next.setUTCMinutes(next.getUTCMinutes() + 5);
+ return next;
case "hour":
next.setUTCHours(next.getUTCHours() + 1);
return next;
case "day":
next.setUTCDate(next.getUTCDate() + 1);
return next;
- case "week":
- next.setUTCDate(next.getUTCDate() + 7);
- return next;
- case "month":
- next.setUTCMonth(next.getUTCMonth() + 1);
- return next;
+ default: {
+ const exhaustiveCheck: never = granularity;
+ throw new Error(`Invalid timeline granularity: ${exhaustiveCheck}`);
+ }
}
};
-const formatTimelineBucketTime = (date: Date): string =>
- date.toISOString().replace(".000Z", "Z");
-
-const legacyIntegrationExportSources =
- new Set<AnalyticsIntegrationExportSource>([
- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,
- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,
- ]);
+const formatTimelineBucket = (timestamp: Date): string =>
+ timestamp.toISOString().replace(/\.\d{3}Z$/, "Z");
-const TRACE_EVAL_TARGET = "trace";
+const getEmptyTimelineBuckets = (
+ fromTimestamp: Date,
+ toTimestamp: Date,
+ granularity: ResolvedTimelineGranularity,
+): LegacyApiUsageResultRow[] => {
+ const buckets: LegacyApiUsageResultRow[] = [];
-const isLegacyIntegrationExportSource = (
- exportSource: AnalyticsIntegrationExportSource | null | undefined,
-) => exportSource != null && legacyIntegrationExportSources.has(exportSource);
+ for (
+ let bucket = floorTimelineBucket(fromTimestamp, granularity);
+ bucket.getTime() < toTimestamp.getTime();
+ bucket = addTimelineBucket(bucket, granularity)
+ ) {
+ buckets.push({
+ time: formatTimelineBucket(bucket),
+ entrypoint: "",
+ count: 0,
+ });
+ }
-const isEnabledLegacyIntegration = (
- integration:
- | { enabled: boolean; exportSource: AnalyticsIntegrationExportSource }
- | null
- | undefined,
-) =>
- Boolean(
- integration?.enabled &&
- isLegacyIntegrationExportSource(integration.exportSource),
- );
+ return buckets;
+};
-type LegacyApiUsageRow = {
- time: string;
- entrypoint: string;
- count: string | number;
+const compareTimelineRows = (
+ left: LegacyApiUsageResultRow,
+ right: LegacyApiUsageResultRow,
+): number => {
+ if (left.time < right.time) return -1;
+ if (left.time > right.time) return 1;
+ if (left.entrypoint === right.entrypoint) return 0;
+ if (left.entrypoint === "") return -1;
+ if (right.entrypoint === "") return 1;
+ return left.entrypoint.localeCompare(right.entrypoint);
};
type TraceLevelEvalExecutionTimeSeriesRow = {
@@ -177,15 +246,14 @@ const fillTraceLevelEvalExecutionBuckets = ({
(row) => [`${row.time}\u0000${row.scoreName}`, row.count] as const,
),
);
- const endBucket = startOfTimelineBucket(toTimestamp, granularity);
const filledRows: TraceLevelEvalExecutionTimeSeriesPoint[] = [];
for (
- let bucket = startOfTimelineBucket(fromTimestamp, granularity);
- bucket.getTime() <= endBucket.getTime();
- bucket = incrementTimelineBucket(bucket, granularity)
+ let bucket = floorTimelineBucket(fromTimestamp, granularity);
+ bucket.getTime() < toTimestamp.getTime();
+ bucket = addTimelineBucket(bucket, granularity)
) {
- const time = formatTimelineBucketTime(bucket);
+ const time = formatTimelineBucket(bucket);
for (const scoreName of scoreNames) {
filledRows.push({
@@ -245,14 +313,7 @@ export const v4TransitionRouter = createTRPCRouter({
}),
traceLevelEvalExecutionsTimeSeries: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- fromTimestamp: z.date(),
- toTimestamp: z.date(),
- granularity: timelineGranularity.default("auto"),
- }),
- )
+ .input(timelineInputSchema)
.query(async ({ input, ctx }) => {
const granularity = resolveTimelineGranularity(
input.fromTimestamp,
@@ -280,7 +341,7 @@ WITH selected AS (
)
SELECT
- to_char(bucket_time, 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS time,
+ to_char(bucket_time AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS time,
score_name AS "scoreName",
COUNT(*)::bigint AS count
FROM selected
@@ -301,14 +362,7 @@ ORDER BY bucket_time ASC, score_name ASC
}),
timeSeriesByEntrypoint: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- fromTimestamp: z.date(),
- toTimestamp: z.date(),
- granularity: timelineGranularity.default("auto"),
- }),
- )
+ .input(timelineInputSchema)
.query(async ({ input }) => {
const granularity = resolveTimelineGranularity(
input.fromTimestamp,
@@ -408,10 +462,20 @@ SETTINGS skip_unavailable_shards = 1
},
});
- return rows.map((row) => ({
+ const dataRows = rows.map((row) => ({
time: row.time,
entrypoint: row.entrypoint,
count: Number(row.count),
}));
+
+ return dataRows.length === 0
+ ? dataRows
+ : getEmptyTimelineBuckets(
+ input.fromTimestamp,
+ input.toTimestamp,
+ granularity,
+ )
+ .concat(dataRows)
+ .sort(compareTimelineRows);
}),
});
diff --git a/web/src/pages/project/[projectId]/v4/index.tsx b/web/src/pages/project/[projectId]/v4/index.tsx
index 70d060c0c0..e0aec63366 100644
--- a/web/src/pages/project/[projectId]/v4/index.tsx
+++ b/web/src/pages/project/[projectId]/v4/index.tsx
@@ -10,14 +10,51 @@ import { DashboardCard } from "@/src/features/dashboard/components/cards/Dashboa
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { Button } from "@/src/components/ui/button";
import {
- DASHBOARD_AGGREGATION_OPTIONS,
+ DEFAULT_DASHBOARD_AGGREGATION_SELECTION,
toAbsoluteTimeRange,
+ type AbsoluteTimeRange,
+ type TimeRange,
} from "@/src/utils/date-range-utils";
-import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";
+import { useGlobalDateRange } from "@/src/features/global-time-range/useGlobalDateRange";
import { api } from "@/src/utils/api";
import { encodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";
import { numberFormatter } from "@/src/utils/numbers";
+const V4_TIME_RANGE_PRESETS = [
+ "last5Minutes",
+ "last30Minutes",
+ "last1Hour",
+ "last3Hours",
+ "last1Day",
+ "last7Days",
+ "last30Days",
+] as const;
+
+const MAX_V4_TIMELINE_RANGE_MS = 30 * 24 * 60 * 60 * 1000;
+
+const getCappedAbsoluteTimeRange = (
+ timeRange: TimeRange,
+): AbsoluteTimeRange => {
+ const absoluteRange =
+ toAbsoluteTimeRange(timeRange) ??
+ ({
+ from: new Date(Date.now() - 24 * 60 * 60 * 1000),
+ to: new Date(),
+ } satisfies AbsoluteTimeRange);
+
+ if (
+ absoluteRange.to.getTime() - absoluteRange.from.getTime() <=
+ MAX_V4_TIMELINE_RANGE_MS
+ ) {
+ return absoluteRange;
+ }
+
+ return {
+ from: new Date(absoluteRange.to.getTime() - MAX_V4_TIMELINE_RANGE_MS),
+ to: absoluteRange.to,
+ };
+};
+
const PUBLIC_API_DOCS = [
{
label: "V4 upgrade guide",
@@ -90,17 +127,20 @@ const ExternalDocButton = ({
export default function V4Page() {
const router = useRouter();
const projectId = router.query.projectId as string | undefined;
- const { timeRange, setTimeRange } = useDashboardDateRange();
+ const { timeRange, setTimeRange } = useGlobalDateRange({
+ allowedRanges: V4_TIME_RANGE_PRESETS,
+ fallback: DEFAULT_DASHBOARD_AGGREGATION_SELECTION,
+ });
const absoluteTimeRange = useMemo(() => {
- return (
- toAbsoluteTimeRange(timeRange) ?? {
- from: new Date(Date.now() - 24 * 60 * 60 * 1000),
- to: new Date(),
- }
- );
+ return getCappedAbsoluteTimeRange(timeRange);
}, [timeRange]);
+ const earliestSelectableDate = useMemo(
+ () => new Date(Date.now() - MAX_V4_TIMELINE_RANGE_MS),
+ [],
+ );
+
const legacyApiUsage = api.v4Transition.timeSeriesByEntrypoint.useQuery(
{
projectId: projectId ?? "",
@@ -203,7 +243,8 @@ export default function V4Page() {
<TimeRangePicker
timeRange={timeRange}
onTimeRangeChange={setTimeRange}
- timeRangePresets={DASHBOARD_AGGREGATION_OPTIONS}
+ timeRangePresets={V4_TIME_RANGE_PRESETS}
+ disabled={{ before: earliestSelectableDate }}
className="my-0 max-w-full overflow-x-auto"
/>
),