Skip to content

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

feat(v4): load migration timelines asynchronously (#14599)

Max Deichmann1a3aaee62946
diff --git a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
index 9373d492f4..45fa9c1dfc 100644
--- a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
+++ b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
@@ -441,11 +441,8 @@ describe("v4TransitionRouter", () => {
expect(mockPrisma.$queryRaw).not.toHaveBeenCalled();
});
- it("summarizes trace-level evals and legacy integrations", async () => {
+ it("summarizes legacy integrations", async () => {
const mockPrisma = {
- jobConfiguration: {
- count: vi.fn().mockResolvedValue(3),
- },
posthogIntegration: {
findUnique: vi.fn().mockResolvedValue({
enabled: true,
@@ -468,7 +465,6 @@ describe("v4TransitionRouter", () => {
const caller = createCaller(mockPrisma);
await expect(caller.summary({ projectId })).resolves.toEqual({
- traceLevelEvalCount: 3,
legacyIntegrationCount: 2,
legacyIntegrations: {
posthog: true,
@@ -477,13 +473,6 @@ describe("v4TransitionRouter", () => {
},
});
- expect(mockPrisma.jobConfiguration.count).toHaveBeenCalledWith({
- where: {
- projectId,
- jobType: "EVAL",
- targetObject: "trace",
- },
- });
expect(mockPrisma.posthogIntegration.findUnique).toHaveBeenCalledWith({
where: { projectId },
select: { enabled: true, exportSource: true },
@@ -498,11 +487,29 @@ describe("v4TransitionRouter", () => {
});
});
- it("does not count disabled legacy integrations", async () => {
+ it("summarizes trace-level evals", async () => {
const mockPrisma = {
jobConfiguration: {
- count: vi.fn().mockResolvedValue(0),
+ count: vi.fn().mockResolvedValue(3),
+ },
+ };
+ const caller = createCaller(mockPrisma);
+
+ await expect(caller.traceLevelEvalSummary({ projectId })).resolves.toEqual({
+ traceLevelEvalCount: 3,
+ });
+
+ expect(mockPrisma.jobConfiguration.count).toHaveBeenCalledWith({
+ where: {
+ projectId,
+ jobType: "EVAL",
+ targetObject: "trace",
},
+ });
+ });
+
+ it("does not count disabled legacy integrations", async () => {
+ const mockPrisma = {
posthogIntegration: {
findUnique: vi.fn().mockResolvedValue({
enabled: false,
@@ -525,7 +532,6 @@ describe("v4TransitionRouter", () => {
const caller = createCaller(mockPrisma);
await expect(caller.summary({ projectId })).resolves.toEqual({
- traceLevelEvalCount: 0,
legacyIntegrationCount: 1,
legacyIntegrations: {
posthog: false,
@@ -535,7 +541,7 @@ describe("v4TransitionRouter", () => {
});
});
- it("summarizes v4 migration data by active organization project", async () => {
+ it("summarizes legacy integrations by active organization project", async () => {
const mockPrisma = {
project: {
findMany: vi.fn().mockResolvedValue([
@@ -543,14 +549,6 @@ describe("v4TransitionRouter", () => {
{ id: secondProjectId, name: "Second Project" },
]),
},
- jobConfiguration: {
- groupBy: vi.fn().mockResolvedValue([
- {
- projectId,
- _count: { _all: 3 },
- },
- ]),
- },
posthogIntegration: {
findMany: vi.fn().mockResolvedValue([
{
@@ -591,7 +589,6 @@ describe("v4TransitionRouter", () => {
{
projectId,
projectName: "V4 Transition Project",
- traceLevelEvalCount: 3,
legacyIntegrationCount: 1,
legacyIntegrations: {
posthog: true,
@@ -602,7 +599,6 @@ describe("v4TransitionRouter", () => {
{
projectId: secondProjectId,
projectName: "Second Project",
- traceLevelEvalCount: 0,
legacyIntegrationCount: 1,
legacyIntegrations: {
posthog: false,
@@ -626,6 +622,48 @@ describe("v4TransitionRouter", () => {
createdAt: "desc",
},
});
+ });
+
+ it("summarizes trace-level evals by active organization project", async () => {
+ const mockPrisma = {
+ project: {
+ findMany: vi
+ .fn()
+ .mockResolvedValue([{ id: projectId }, { id: secondProjectId }]),
+ },
+ jobConfiguration: {
+ groupBy: vi.fn().mockResolvedValue([
+ {
+ projectId,
+ _count: { _all: 3 },
+ },
+ ]),
+ },
+ };
+ const caller = createCaller(mockPrisma);
+
+ await expect(
+ caller.traceLevelEvalSummaryByProject({ orgId }),
+ ).resolves.toEqual([
+ {
+ projectId,
+ traceLevelEvalCount: 3,
+ },
+ {
+ projectId: secondProjectId,
+ traceLevelEvalCount: 0,
+ },
+ ]);
+
+ expect(mockPrisma.project.findMany).toHaveBeenCalledWith({
+ where: {
+ orgId,
+ deletedAt: null,
+ },
+ select: {
+ id: true,
+ },
+ });
expect(mockPrisma.jobConfiguration.groupBy).toHaveBeenCalledWith({
by: ["projectId"],
where: {
@@ -652,6 +690,14 @@ describe("v4TransitionRouter", () => {
orgId,
}),
).resolves.toEqual({ projects: [] });
+ await expect(
+ createCaller(
+ mockPrisma,
+ createSessionWithOrgRole("OWNER"),
+ ).traceLevelEvalSummaryByProject({
+ orgId,
+ }),
+ ).resolves.toEqual([]);
await expect(
createCaller(
@@ -661,6 +707,14 @@ describe("v4TransitionRouter", () => {
orgId,
}),
).resolves.toEqual({ projects: [] });
+ await expect(
+ createCaller(
+ mockPrisma,
+ createSessionWithOrgRole("ADMIN"),
+ ).traceLevelEvalSummaryByProject({
+ orgId,
+ }),
+ ).resolves.toEqual([]);
});
it("forbids organization members from accessing org-level v4 data", async () => {
@@ -677,21 +731,17 @@ describe("v4TransitionRouter", () => {
code: "FORBIDDEN",
});
await expect(
- caller.traceLevelEvalExecutionsTimeSeriesByProject({
+ caller.traceLevelEvalSummaryByProject({
orgId,
- fromTimestamp: new Date("2026-06-25T12:00:00Z"),
- toTimestamp: new Date("2026-06-25T13:00:00Z"),
- granularity: "auto",
}),
).rejects.toMatchObject({
code: "FORBIDDEN",
});
await expect(
- caller.timeSeriesByEntrypointByProject({
+ caller.legacyApiUsageSummaryByProject({
orgId,
fromTimestamp: new Date("2026-06-24T00:00:00Z"),
toTimestamp: new Date("2026-06-25T00:00:00Z"),
- granularity: "auto",
}),
).rejects.toMatchObject({
code: "FORBIDDEN",
@@ -814,90 +864,15 @@ describe("v4TransitionRouter", () => {
expect(query?.values?.[0]).toBe("1 minute");
});
- it("queries trace-level eval execution counts by organization project", async () => {
- const mockPrisma = {
- project: {
- findMany: vi
- .fn()
- .mockResolvedValue([{ id: projectId }, { id: secondProjectId }]),
- },
- $queryRaw: vi.fn().mockResolvedValue([
- {
- projectId,
- time: "2026-06-25T12:00:00Z",
- scoreName: "toxicity",
- count: 4n,
- },
- {
- projectId: secondProjectId,
- time: "2026-06-25T12:04:00Z",
- scoreName: "helpfulness",
- count: 2,
- },
- ]),
- };
- const caller = createCaller(mockPrisma);
-
- const rows = await caller.traceLevelEvalExecutionsTimeSeriesByProject({
- orgId,
- fromTimestamp: new Date("2026-06-25T12:00:00Z"),
- toTimestamp: new Date("2026-06-25T13:00:00Z"),
- granularity: "auto",
- });
-
- expect(rows).toContainEqual({
- projectId,
- time: "2026-06-25T12:00:00Z",
- scoreName: "toxicity",
- count: 4,
- });
- expect(rows).toContainEqual({
- projectId: secondProjectId,
- time: "2026-06-25T12:04:00Z",
- scoreName: "helpfulness",
- count: 2,
- });
- expect(rows.every((row) => Boolean(row.projectId))).toBe(true);
-
- expect(mockPrisma.project.findMany).toHaveBeenCalledWith({
- where: {
- orgId,
- deletedAt: null,
- },
- select: {
- id: true,
- },
- });
- const query = mockPrisma.$queryRaw.mock.calls[0]?.[0] as
- | { sql?: string; text?: string; values?: unknown[] }
- | undefined;
- const queryText = query?.sql ?? query?.text ?? "";
-
- expect(queryText).toContain('project_id AS "projectId"');
- expect(queryText).toContain("je.project_id IN (?,?)");
- expect(queryText).toContain("bucket_time AT TIME ZONE 'UTC'");
- expect(queryText).toContain("GROUP BY project_id, bucket_time, score_name");
- expect(query?.values).toEqual([
- "2 minutes",
- projectId,
- secondProjectId,
- "trace",
- new Date("2026-06-25T12:00:00Z"),
- new Date("2026-06-25T13:00:00Z"),
- ]);
- });
-
- it("queries legacy public API usage by organization project", async () => {
+ it("summarizes legacy public API usage by organization project", async () => {
mockedQueryClickhouse.mockResolvedValue([
{
projectId,
- time: "2026-06-24T12:00:00Z",
entrypoint: "publicapi: GET /api/public/traces/{id}",
count: "0.6666666666666666",
},
{
projectId: secondProjectId,
- time: "2026-06-24T13:00:00Z",
entrypoint: "publicapi: GET /api/public/metrics",
count: 3,
},
@@ -911,42 +886,29 @@ describe("v4TransitionRouter", () => {
};
const caller = createCaller(mockPrisma);
- const rows = await caller.timeSeriesByEntrypointByProject({
+ const rows = await caller.legacyApiUsageSummaryByProject({
orgId,
fromTimestamp: new Date("2026-06-24T00:00:00Z"),
toTimestamp: new Date("2026-06-25T00:00:00Z"),
- granularity: "auto",
});
- expect(rows).toHaveLength(50);
- expect(
- rows.filter(
- (row) => row.projectId === projectId && row.entrypoint === "",
- ),
- ).toHaveLength(24);
- expect(
- rows.filter(
- (row) => row.projectId === secondProjectId && row.entrypoint === "",
- ),
- ).toHaveLength(24);
- expect(rows).toContainEqual({
- projectId,
- time: "2026-06-24T12:00:00Z",
- entrypoint: "publicapi: GET /api/public/traces/{id}",
- count: 0.6666666666666666,
- });
- expect(rows).toContainEqual({
- projectId: secondProjectId,
- time: "2026-06-24T13:00:00Z",
- entrypoint: "publicapi: GET /api/public/metrics",
- count: 3,
- });
+ expect(rows).toEqual([
+ {
+ projectId,
+ entrypoint: "publicapi: GET /api/public/traces/{id}",
+ count: 0.6666666666666666,
+ },
+ {
+ projectId: secondProjectId,
+ entrypoint: "publicapi: GET /api/public/metrics",
+ count: 3,
+ },
+ ]);
expect(mockedQueryClickhouse).toHaveBeenCalledTimes(1);
const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
- expect(clickhouseQuery?.query).toContain(
- "toStartOfInterval(event_time_microseconds, INTERVAL 1 HOUR, 'UTC') AS bucket_time",
- );
+ expect(clickhouseQuery?.query).not.toContain("toStartOfInterval");
+ expect(clickhouseQuery?.query).not.toContain("bucket_time");
expect(clickhouseQuery?.query).toContain(
"JSONExtractString(log_comment, 'projectId') AS project_id",
);
@@ -955,13 +917,13 @@ describe("v4TransitionRouter", () => {
);
expect(clickhouseQuery?.query).toContain("project_id AS projectId");
expect(clickhouseQuery?.query).toContain(
- "GROUP BY project_id, bucket_time, legacy_route",
+ "GROUP BY project_id, legacy_route",
);
expect(clickhouseQuery?.params).toMatchObject({
projectIds: [projectId, secondProjectId],
});
expect(clickhouseQuery?.tags).toEqual({
- route: "v4-org-legacy-api-usage",
+ route: "v4-org-legacy-api-usage-summary",
});
});
});
diff --git a/web/src/features/v4/components/V4MigrationProjectCards.tsx b/web/src/features/v4/components/V4MigrationProjectCards.tsx
index e9f36b9705..729d9d752a 100644
--- a/web/src/features/v4/components/V4MigrationProjectCards.tsx
+++ b/web/src/features/v4/components/V4MigrationProjectCards.tsx
@@ -5,6 +5,7 @@ import { ChevronRight, ExternalLink } from "lucide-react";
import { Bar, BarChart, XAxis, YAxis } from "recharts";
import { Badge } from "@/src/components/ui/badge";
import { Alert, AlertDescription } from "@/src/components/ui/alert";
+import { Skeleton } from "@/src/components/ui/skeleton";
import {
ChartContainer,
ChartTooltip,
@@ -26,8 +27,7 @@ export type V4LegacyIntegrations = {
blobStorage: boolean;
};
-export type V4MigrationSummary = {
- traceLevelEvalCount: number;
+export type V4LegacyIntegrationSummary = {
legacyIntegrationCount: number;
legacyIntegrations: V4LegacyIntegrations;
};
@@ -184,6 +184,21 @@ const Notice = ({ children }: { children: ReactNode }) => (
</Alert>
);
+const SectionLoading = () => (
+ <div className="rounded-md border p-3">
+ <div className="mb-3 flex items-center justify-between gap-3">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-3 w-20" />
+ </div>
+ <Skeleton className="h-28 w-full" />
+ <div className="mt-3 flex gap-3 border-t pt-3">
+ <Skeleton className="h-3 w-24" />
+ <Skeleton className="h-3 w-32" />
+ <Skeleton className="h-3 w-20" />
+ </div>
+ </div>
+);
+
const InlineLink = ({
href,
external,
@@ -217,11 +232,13 @@ const InlineLink = ({
const Section = ({
title,
count,
+ isCountLoading,
detailsHref,
children,
}: {
title: string;
count: number;
+ isCountLoading?: boolean;
detailsHref: ProductHref;
children: ReactNode;
}) => (
@@ -229,9 +246,13 @@ const Section = ({
<div className="flex items-center justify-between gap-3">
<h3 className="text-sm font-medium">{title}</h3>
<div className="flex items-center gap-2">
- <Badge variant="outline-solid" size="sm">
- {numberFormatter(count, 0)}
- </Badge>
+ {isCountLoading ? (
+ <Skeleton className="h-5 w-8 rounded-full" />
+ ) : (
+ <Badge variant="outline-solid" size="sm">
+ {numberFormatter(count, 0)}
+ </Badge>
+ )}
<InlineLink href={detailsHref}>Go to details</InlineLink>
</div>
</div>
@@ -430,25 +451,31 @@ const ActionRow = ({
export const V4MigrationProjectCards = ({
projectId,
projectName,
- summary,
+ legacyIntegrationSummary,
+ traceLevelEvalCount: configuredTraceLevelEvalCount,
legacyApiUsage,
traceLevelEvalExecutions,
- isSummaryLoading,
+ isLegacyIntegrationSummaryLoading,
+ isTraceLevelEvalSummaryLoading,
isLegacyApiUsageLoading,
isTraceLevelEvalExecutionsLoading,
- hasSummaryError,
+ hasLegacyIntegrationSummaryError,
+ hasTraceLevelEvalSummaryError,
hasLegacyApiUsageError,
hasTraceLevelEvalExecutionsError,
}: {
projectId: string;
projectName?: string;
- summary: V4MigrationSummary | undefined;
+ legacyIntegrationSummary: V4LegacyIntegrationSummary | undefined;
+ traceLevelEvalCount: number | undefined;
legacyApiUsage: V4LegacyApiUsagePoint[] | undefined;
traceLevelEvalExecutions: V4TraceLevelEvalExecutionPoint[] | undefined;
- isSummaryLoading: boolean;
+ isLegacyIntegrationSummaryLoading: boolean;
+ isTraceLevelEvalSummaryLoading: boolean;
isLegacyApiUsageLoading: boolean;
isTraceLevelEvalExecutionsLoading: boolean;
- hasSummaryError: boolean;
+ hasLegacyIntegrationSummaryError: boolean;
+ hasTraceLevelEvalSummaryError: boolean;
hasLegacyApiUsageError: boolean;
hasTraceLevelEvalExecutionsError: boolean;
}) => {
@@ -486,130 +513,144 @@ export const V4MigrationProjectCards = ({
const legacyIntegrationLinks = useMemo(
() =>
INTEGRATION_LINKS.filter(
- (link) => summary?.legacyIntegrations[link.key] === true,
+ (link) =>
+ legacyIntegrationSummary?.legacyIntegrations[link.key] === true,
),
- [summary?.legacyIntegrations],
+ [legacyIntegrationSummary?.legacyIntegrations],
);
const hasAnyError =
- hasSummaryError ||
+ hasLegacyIntegrationSummaryError ||
+ hasTraceLevelEvalSummaryError ||
hasLegacyApiUsageError ||
hasTraceLevelEvalExecutionsError;
const traceLevelEvalCount =
- summary?.traceLevelEvalCount ?? evalExecutionSeries.length;
+ configuredTraceLevelEvalCount ?? evalExecutionSeries.length;
const activeTaskCount =
legacyApiSeries.length +
traceLevelEvalCount +
legacyIntegrationLinks.length;
const migrationStatus = getV4MigrationStatus(activeTaskCount);
- const isLoading =
- isSummaryLoading ||
- isLegacyApiUsageLoading ||
- isTraceLevelEvalExecutionsLoading;
+ const isSummaryLoading =
+ isLegacyIntegrationSummaryLoading || isTraceLevelEvalSummaryLoading;
+ const isTimelineLoading =
+ isLegacyApiUsageLoading || isTraceLevelEvalExecutionsLoading;
return (
<DashboardCard
title="Required changes"
description={
- isLoading
+ isSummaryLoading
? "Loading V4 migration data."
: hasAnyError
? `${projectName ? `${projectName} - ` : ""}Some migration data could not be loaded.`
- : `${projectName ? `${projectName} - ` : ""}${numberFormatter(
- activeTaskCount,
- 0,
- )} required ${
- activeTaskCount === 1 ? "change" : "changes"
- } in the selected time range`
+ : isTimelineLoading
+ ? `${projectName ? `${projectName} - ` : ""}Loading usage timelines.`
+ : `${projectName ? `${projectName} - ` : ""}${numberFormatter(
+ activeTaskCount,
+ 0,
+ )} required ${
+ activeTaskCount === 1 ? "change" : "changes"
+ } in the selected time range`
}
- isLoading={isLoading}
+ isLoading={isSummaryLoading}
headerRight={
- isLoading ? undefined : (
+ isSummaryLoading ? undefined : (
<div className="flex items-center gap-2">
<InlineLink href={V4_DOCS_LINK.href} external>
{V4_DOCS_LINK.label}
</InlineLink>
<Badge
variant={
- hasAnyError ? "outline-solid" : migrationStatus.badgeVariant
+ hasAnyError || isTimelineLoading
+ ? "outline-solid"
+ : migrationStatus.badgeVariant
}
className="whitespace-nowrap"
>
- {hasAnyError ? "Unavailable" : migrationStatus.label}
+ {hasAnyError
+ ? "Unavailable"
+ : isTimelineLoading
+ ? "Loading"
+ : migrationStatus.label}
</Badge>
</div>
)
}
>
- {isLoading ? (
- <div className="min-h-80" />
- ) : (
- <>
- <Section
- title="Legacy public APIs"
- count={legacyApiSeries.length}
- detailsHref={`/project/${projectId}/settings/api-keys`}
- >
- {hasLegacyApiUsageError ? (
- <Notice>Failed to load public API usage.</Notice>
- ) : legacyApiSeries.length ? (
- <UsageStackedBarOverview
- bucketTimes={legacyApiBucketTimes}
- series={legacyApiSeries}
- valueLabel="calls"
- />
- ) : (
- <Notice>No legacy public API usage in this range.</Notice>
- )}
- </Section>
-
- <Section
- title="Trace-level evals"
- count={traceLevelEvalCount}
- detailsHref={traceLevelEvalsHref}
- >
- {hasSummaryError || hasTraceLevelEvalExecutionsError ? (
- <Notice>Failed to load trace-level eval data.</Notice>
- ) : evalExecutionSeries.length ? (
- <UsageStackedBarOverview
- bucketTimes={evalExecutionBucketTimes}
- series={evalExecutionSeries}
- valueLabel="executions"
- />
- ) : traceLevelEvalCount > 0 ? (
- <ActionRow
- title={`${numberFormatter(
- traceLevelEvalCount,
- 0,
- )} configured trace-level evals`}
- detail="No executions found in the selected range."
- />
- ) : (
- <Notice>No trace-level evals detected.</Notice>
- )}
- </Section>
-
- <Section
- title="Integrations"
- count={legacyIntegrationLinks.length}
- detailsHref={`/project/${projectId}/settings/integrations`}
- >
- {hasSummaryError ? (
- <Notice>Failed to load integration data.</Notice>
- ) : legacyIntegrationLinks.length ? (
- legacyIntegrationLinks.map((integration) => (
- <ActionRow
- key={integration.key}
- title={integration.label}
- detail="Legacy traces and observations export is enabled."
- />
- ))
- ) : (
- <Notice>No legacy integration exports detected.</Notice>
- )}
- </Section>
- </>
- )}
+ <Section
+ title="Legacy public APIs"
+ count={legacyApiSeries.length}
+ isCountLoading={isLegacyApiUsageLoading}
+ detailsHref={`/project/${projectId}/settings/api-keys`}
+ >
+ {isLegacyApiUsageLoading ? (
+ <SectionLoading />
+ ) : hasLegacyApiUsageError ? (
+ <Notice>Failed to load public API usage.</Notice>
+ ) : legacyApiSeries.length ? (
+ <UsageStackedBarOverview
+ bucketTimes={legacyApiBucketTimes}
+ series={legacyApiSeries}
+ valueLabel="calls"
+ />
+ ) : (
+ <Notice>No legacy public API usage in this range.</Notice>
+ )}
+ </Section>
+
+ <Section
+ title="Trace-level evals"
+ count={traceLevelEvalCount}
+ isCountLoading={isTraceLevelEvalSummaryLoading}
+ detailsHref={traceLevelEvalsHref}
+ >
+ {isTraceLevelEvalSummaryLoading || isTraceLevelEvalExecutionsLoading ? (
+ <SectionLoading />
+ ) : hasTraceLevelEvalSummaryError ||
+ hasTraceLevelEvalExecutionsError ? (
+ <Notice>Failed to load trace-level eval data.</Notice>
+ ) : evalExecutionSeries.length ? (
+ <UsageStackedBarOverview
+ bucketTimes={evalExecutionBucketTimes}
+ series={evalExecutionSeries}
+ valueLabel="executions"
+ />
+ ) : traceLevelEvalCount > 0 ? (
+ <ActionRow
+ title={`${numberFormatter(
+ traceLevelEvalCount,
+ 0,
+ )} configured trace-level evals`}
+ detail="No executions found in the selected range."
+ />
+ ) : (
+ <Notice>No trace-level evals detected.</Notice>
+ )}
+ </Section>
+
+ <Section
+ title="Integrations"
+ count={legacyIntegrationLinks.length}
+ isCountLoading={isLegacyIntegrationSummaryLoading}
+ detailsHref={`/project/${projectId}/settings/integrations`}
+ >
+ {isLegacyIntegrationSummaryLoading ? (
+ <SectionLoading />
+ ) : hasLegacyIntegrationSummaryError ? (
+ <Notice>Failed to load integration data.</Notice>
+ ) : legacyIntegrationLinks.length ? (
+ legacyIntegrationLinks.map((integration) => (
+ <ActionRow
+ key={integration.key}
+ title={integration.label}
+ detail="Legacy traces and observations export is enabled."
+ />
+ ))
+ ) : (
+ <Notice>No legacy integration exports detected.</Notice>
+ )}
+ </Section>
</DashboardCard>
);
};
diff --git a/web/src/features/v4/server/v4TransitionRouter.ts b/web/src/features/v4/server/v4TransitionRouter.ts
index 8c8d2b3d38..6f6b80824a 100644
--- a/web/src/features/v4/server/v4TransitionRouter.ts
+++ b/web/src/features/v4/server/v4TransitionRouter.ts
@@ -109,12 +109,11 @@ const timelineInputSchema = z
{ message: "V4 timeline ranges cannot exceed 30 days" },
);
-const organizationTimelineInputSchema = z
+const organizationTimeRangeInputSchema = z
.object({
orgId: z.string(),
fromTimestamp: z.date(),
toTimestamp: z.date(),
- granularity: timelineGranularity.default("auto"),
})
.refine(
({ fromTimestamp, toTimestamp }) =>
@@ -124,7 +123,7 @@ const organizationTimelineInputSchema = z
.refine(
({ fromTimestamp, toTimestamp }) =>
toTimestamp.getTime() - fromTimestamp.getTime() <= MAX_TIMELINE_RANGE_MS,
- { message: "V4 timeline ranges cannot exceed 30 days" },
+ { message: "V4 migration ranges cannot exceed 30 days" },
);
type LegacyApiUsageRow = {
@@ -139,12 +138,16 @@ type LegacyApiUsageResultRow = {
count: number;
};
-type LegacyApiUsageByProjectRow = LegacyApiUsageRow & {
+type LegacyApiUsageSummaryByProjectRow = {
projectId: string;
+ entrypoint: string;
+ count: string | number;
};
-type LegacyApiUsageByProjectResultRow = LegacyApiUsageResultRow & {
+type LegacyApiUsageSummaryByProjectResultRow = {
projectId: string;
+ entrypoint: string;
+ count: number;
};
const floorTimelineBucket = (
@@ -242,15 +245,6 @@ const compareTimelineRows = (
return left.entrypoint.localeCompare(right.entrypoint);
};
-const compareTimelineRowsByProject = (
- left: LegacyApiUsageByProjectResultRow,
- right: LegacyApiUsageByProjectResultRow,
-): number => {
- if (left.projectId < right.projectId) return -1;
- if (left.projectId > right.projectId) return 1;
- return compareTimelineRows(left, right);
-};
-
type TraceLevelEvalExecutionTimeSeriesRow = {
time: string;
scoreName: string;
@@ -263,15 +257,10 @@ type TraceLevelEvalExecutionTimeSeriesPoint = {
count: number;
};
-type TraceLevelEvalExecutionTimeSeriesByProjectRow =
- TraceLevelEvalExecutionTimeSeriesRow & {
- projectId: string;
- };
-
-type TraceLevelEvalExecutionTimeSeriesByProjectPoint =
- TraceLevelEvalExecutionTimeSeriesPoint & {
- projectId: string;
- };
+type TraceLevelEvalSummaryByProjectResultRow = {
+ projectId: string;
+ traceLevelEvalCount: number;
+};
type LegacyIntegrations = {
posthog: boolean;
@@ -321,46 +310,6 @@ const fillTraceLevelEvalExecutionBuckets = ({
return filledRows;
};
-const fillTraceLevelEvalExecutionBucketsByProject = ({
- rows,
- fromTimestamp,
- toTimestamp,
- granularity,
-}: {
- rows: TraceLevelEvalExecutionTimeSeriesByProjectPoint[];
- fromTimestamp: Date;
- toTimestamp: Date;
- granularity: ResolvedTimelineGranularity;
-}): TraceLevelEvalExecutionTimeSeriesByProjectPoint[] => {
- const rowsByProject = new Map<
- string,
- TraceLevelEvalExecutionTimeSeriesPoint[]
- >();
-
- for (const row of rows) {
- const projectRows = rowsByProject.get(row.projectId) ?? [];
- projectRows.push({
- time: row.time,
- scoreName: row.scoreName,
- count: row.count,
- });
- rowsByProject.set(row.projectId, projectRows);
- }
-
- return Array.from(rowsByProject.entries()).flatMap(
- ([projectId, projectRows]) =>
- fillTraceLevelEvalExecutionBuckets({
- rows: projectRows,
- fromTimestamp,
- toTimestamp,
- granularity,
- }).map((row) => ({
- projectId,
- ...row,
- })),
- );
-};
-
const protectedV4MigrationOrgProcedure = protectedOrganizationProcedure.use(
({ ctx, next }) => {
throwIfNoOrganizationAccess({
@@ -398,32 +347,21 @@ export const v4TransitionRouter = createTRPCRouter({
summary: protectedProjectProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
- const [
- traceLevelEvalCount,
- posthogIntegration,
- mixpanelIntegration,
- blobStorageIntegration,
- ] = await Promise.all([
- ctx.prisma.jobConfiguration.count({
- where: {
- projectId: input.projectId,
- jobType: "EVAL",
- targetObject: TRACE_EVAL_TARGET,
- },
- }),
- ctx.prisma.posthogIntegration.findUnique({
- where: { projectId: input.projectId },
- select: { enabled: true, exportSource: true },
- }),
- ctx.prisma.mixpanelIntegration.findUnique({
- where: { projectId: input.projectId },
- select: { enabled: true, exportSource: true },
- }),
- ctx.prisma.blobStorageIntegration.findUnique({
- where: { projectId: input.projectId },
- select: { enabled: true, exportSource: true },
- }),
- ]);
+ const [posthogIntegration, mixpanelIntegration, blobStorageIntegration] =
+ await Promise.all([
+ ctx.prisma.posthogIntegration.findUnique({
+ where: { projectId: input.projectId },
+ select: { enabled: true, exportSource: true },
+ }),
+ ctx.prisma.mixpanelIntegration.findUnique({
+ where: { projectId: input.projectId },
+ select: { enabled: true, exportSource: true },
+ }),
+ ctx.prisma.blobStorageIntegration.findUnique({
+ where: { projectId: input.projectId },
+ select: { enabled: true, exportSource: true },
+ }),
+ ]);
const legacyIntegrations = getLegacyIntegrations({
posthogIntegration,
@@ -432,13 +370,26 @@ export const v4TransitionRouter = createTRPCRouter({
});
return {
- traceLevelEvalCount,
legacyIntegrationCount:
Object.values(legacyIntegrations).filter(Boolean).length,
legacyIntegrations,
};
}),
+ traceLevelEvalSummary: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const traceLevelEvalCount = await ctx.prisma.jobConfiguration.count({
+ where: {
+ projectId: input.projectId,
+ jobType: "EVAL",
+ targetObject: TRACE_EVAL_TARGET,
+ },
+ });
+
+ return { traceLevelEvalCount };
+ }),
+
summaryByProject: protectedV4MigrationOrgProcedure
.input(z.object({ orgId: z.string() }))
.query(async ({ input, ctx }) => {
@@ -462,20 +413,10 @@ export const v4TransitionRouter = createTRPCRouter({
}
const [
- traceLevelEvalCounts,
posthogIntegrations,
mixpanelIntegrations,
blobStorageIntegrations,
] = await Promise.all([
- ctx.prisma.jobConfiguration.groupBy({
- by: ["projectId"],
- where: {
- projectId: { in: projectIds },
- jobType: "EVAL",
- targetObject: TRACE_EVAL_TARGET,
- },
- _count: { _all: true },
- }),
ctx.prisma.posthogIntegration.findMany({
where: { projectId: { in: projectIds } },
select: { projectId: true, enabled: true, exportSource: true },
@@ -490,9 +431,6 @@ export const v4TransitionRouter = createTRPCRouter({
}),
]);
- const traceLevelEvalCountsByProjectId = new Map(
- traceLevelEvalCounts.map((row) => [row.projectId, row._count._all]),
- );
const posthogIntegrationsByProjectId = new Map(
posthogIntegrations.map((integration) => [
integration.projectId,
@@ -527,8 +465,6 @@ export const v4TransitionRouter = createTRPCRouter({
return {
projectId: project.id,
projectName: project.name,
- traceLevelEvalCount:
- traceLevelEvalCountsByProjectId.get(project.id) ?? 0,
legacyIntegrationCount:
Object.values(legacyIntegrations).filter(Boolean).length,
legacyIntegrations,
@@ -537,6 +473,44 @@ export const v4TransitionRouter = createTRPCRouter({
};
}),
+ traceLevelEvalSummaryByProject: protectedV4MigrationOrgProcedure
+ .input(z.object({ orgId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const projects = await ctx.prisma.project.findMany({
+ where: {
+ orgId: input.orgId,
+ deletedAt: null,
+ },
+ select: {
+ id: true,
+ },
+ });
+ const projectIds = projects.map((project) => project.id);
+
+ if (projectIds.length === 0) return [];
+
+ const traceLevelEvalCounts = await ctx.prisma.jobConfiguration.groupBy({
+ by: ["projectId"],
+ where: {
+ projectId: { in: projectIds },
+ jobType: "EVAL",
+ targetObject: TRACE_EVAL_TARGET,
+ },
+ _count: { _all: true },
+ });
+ const traceLevelEvalCountsByProjectId = new Map(
+ traceLevelEvalCounts.map((row) => [row.projectId, row._count._all]),
+ );
+
+ return projectIds.map(
+ (projectId): TraceLevelEvalSummaryByProjectResultRow => ({
+ projectId,
+ traceLevelEvalCount:
+ traceLevelEvalCountsByProjectId.get(projectId) ?? 0,
+ }),
+ );
+ }),
+
traceLevelEvalExecutionsTimeSeries: protectedProjectProcedure
.input(timelineInputSchema)
.query(async ({ input, ctx }) => {
@@ -586,8 +560,8 @@ ORDER BY bucket_time ASC, score_name ASC
});
}),
- traceLevelEvalExecutionsTimeSeriesByProject: protectedV4MigrationOrgProcedure
- .input(organizationTimelineInputSchema)
+ legacyApiUsageSummaryByProject: protectedV4MigrationOrgProcedure
+ .input(organizationTimeRangeInputSchema)
.query(async ({ input, ctx }) => {
const projects = await ctx.prisma.project.findMany({
where: {
@@ -602,72 +576,11 @@ ORDER BY bucket_time ASC, score_name ASC
if (projectIds.length === 0) return [];
- const granularity = resolveTimelineGranularity(
- input.fromTimestamp,
- input.toTimestamp,
- );
- const bucketExpression = getPostgresTimelineBucketExpression(granularity);
-
- const rows = await ctx.prisma.$queryRaw<
- TraceLevelEvalExecutionTimeSeriesByProjectRow[]
- >(Prisma.sql`
-WITH selected AS (
- SELECT
- je.project_id AS project_id,
- ${bucketExpression} AS bucket_time,
- jc.score_name AS score_name
- FROM job_executions je
- INNER JOIN job_configurations jc ON jc.id = je.job_configuration_id
- AND jc.project_id = je.project_id
- WHERE je.project_id IN (${Prisma.join(projectIds)})
- AND jc.project_id = je.project_id
- AND jc.job_type = 'EVAL'
- AND jc.target_object = ${TRACE_EVAL_TARGET}
- AND je.status != 'CANCELLED'
- AND je.created_at >= ${input.fromTimestamp}
- AND je.created_at <= ${input.toTimestamp}
-)
-
-SELECT
- project_id AS "projectId",
- 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
-GROUP BY project_id, bucket_time, score_name
-ORDER BY project_id ASC, bucket_time ASC, score_name ASC
- `);
-
- return fillTraceLevelEvalExecutionBucketsByProject({
- rows: rows.map((row) => ({
- projectId: row.projectId,
- time: row.time,
- scoreName: row.scoreName,
- count: Number(row.count),
- })),
- fromTimestamp: input.fromTimestamp,
- toTimestamp: input.toTimestamp,
- granularity,
- });
- }),
-
- timeSeriesByEntrypoint: protectedProjectProcedure
- .input(timelineInputSchema)
- .query(async ({ input }) => {
- const granularity = resolveTimelineGranularity(
- input.fromTimestamp,
- input.toTimestamp,
- );
- const bucketTimeSql = getTimelineBucketSql(
- "event_time_microseconds",
- granularity,
- );
-
- const rows = await queryClickhouse<LegacyApiUsageRow>({
+ const rows = await queryClickhouse<LegacyApiUsageSummaryByProjectRow>({
query: `
WITH selected AS (
SELECT
- ${bucketTimeSql} AS bucket_time,
+ JSONExtractString(log_comment, 'projectId') AS project_id,
splitByChar('?', JSONExtractString(log_comment, 'route'))[1] AS route_path
FROM ${systemTableRef("system.query_log")}
WHERE
@@ -678,11 +591,11 @@ WITH selected AS (
AND type = 'QueryFinish'
AND JSONExtractString(log_comment, 'tag_schema_version') = '1'
AND JSONExtractString(log_comment, 'surface') = 'publicapi'
- AND JSONExtractString(log_comment, 'projectId') = {projectId: String}
+ AND JSONExtractString(log_comment, 'projectId') IN {projectIds: Array(String)}
),
classified AS (
SELECT
- bucket_time,
+ project_id,
multiIf(
route_path IN (
'GET /api/public/spans',
@@ -727,24 +640,23 @@ classified AS (
)
SELECT
- formatDateTime(bucket_time, '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS time,
+ project_id AS projectId,
concat('publicapi: ', legacy_route) AS entrypoint,
sum(1.0 / clickhouse_queries_per_api_call) AS count
FROM classified
WHERE legacy_route IS NOT NULL
AND clickhouse_queries_per_api_call IS NOT NULL
-GROUP BY bucket_time, legacy_route
-ORDER BY bucket_time ASC, legacy_route ASC
+GROUP BY project_id, legacy_route
+ORDER BY project_id ASC, legacy_route ASC
SETTINGS skip_unavailable_shards = 1
`,
params: {
- projectId: input.projectId,
+ projectIds,
fromTimestamp: convertDateToClickhouseDateTime(input.fromTimestamp),
toTimestamp: convertDateToClickhouseDateTime(input.toTimestamp),
},
tags: {
- projectId: input.projectId,
- route: "v4-legacy-api-usage",
+ route: "v4-org-legacy-api-usage-summary",
},
preferredClickhouseService: "ReadOnly",
clickhouseSettings: {
@@ -752,39 +664,18 @@ SETTINGS skip_unavailable_shards = 1
},
});
- 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);
+ return rows.map(
+ (row): LegacyApiUsageSummaryByProjectResultRow => ({
+ projectId: row.projectId,
+ entrypoint: row.entrypoint,
+ count: Number(row.count),
+ }),
+ );
}),
- timeSeriesByEntrypointByProject: protectedV4MigrationOrgProcedure
- .input(organizationTimelineInputSchema)
- .query(async ({ input, ctx }) => {
- const projects = await ctx.prisma.project.findMany({
- where: {
- orgId: input.orgId,
- deletedAt: null,
- },
- select: {
- id: true,
- },
- });
- const projectIds = projects.map((project) => project.id);
-
- if (projectIds.length === 0) return [];
-
+ timeSeriesByEntrypoint: protectedProjectProcedure
+ .input(timelineInputSchema)
+ .query(async ({ input }) => {
const granularity = resolveTimelineGranularity(
input.fromTimestamp,
input.toTimestamp,
@@ -794,12 +685,11 @@ SETTINGS skip_unavailable_shards = 1
granularity,
);
- const rows = await queryClickhouse<LegacyApiUsageByProjectRow>({
+ const rows = await queryClickhouse<LegacyApiUsageRow>({
query: `
WITH selected AS (
SELECT
${bucketTimeSql} AS bucket_time,
- JSONExtractString(log_comment, 'projectId') AS project_id,
splitByChar('?', JSONExtractString(log_comment, 'route'))[1] AS route_path
FROM ${systemTableRef("system.query_log")}
WHERE
@@ -810,11 +700,10 @@ WITH selected AS (
AND type = 'QueryFinish'
AND JSONExtractString(log_comment, 'tag_schema_version') = '1'
AND JSONExtractString(log_comment, 'surface') = 'publicapi'
- AND JSONExtractString(log_comment, 'projectId') IN {projectIds: Array(String)}
+ AND JSONExtractString(log_comment, 'projectId') = {projectId: String}
),
classified AS (
SELECT
- project_id,
bucket_time,
multiIf(
route_path IN (
@@ -860,24 +749,24 @@ classified AS (
)
SELECT
- project_id AS projectId,
formatDateTime(bucket_time, '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS time,
concat('publicapi: ', legacy_route) AS entrypoint,
sum(1.0 / clickhouse_queries_per_api_call) AS count
FROM classified
WHERE legacy_route IS NOT NULL
AND clickhouse_queries_per_api_call IS NOT NULL
-GROUP BY project_id, bucket_time, legacy_route
-ORDER BY project_id ASC, bucket_time ASC, legacy_route ASC
+GROUP BY bucket_time, legacy_route
+ORDER BY bucket_time ASC, legacy_route ASC
SETTINGS skip_unavailable_shards = 1
`,
params: {
- projectIds,
+ projectId: input.projectId,
fromTimestamp: convertDateToClickhouseDateTime(input.fromTimestamp),
toTimestamp: convertDateToClickhouseDateTime(input.toTimestamp),
},
tags: {
- route: "v4-org-legacy-api-usage",
+ projectId: input.projectId,
+ route: "v4-legacy-api-usage",
},
preferredClickhouseService: "ReadOnly",
clickhouseSettings: {
@@ -886,7 +775,6 @@ SETTINGS skip_unavailable_shards = 1
});
const dataRows = rows.map((row) => ({
- projectId: row.projectId,
time: row.time,
entrypoint: row.entrypoint,
count: Number(row.count),
@@ -894,18 +782,12 @@ SETTINGS skip_unavailable_shards = 1
return dataRows.length === 0
? dataRows
- : Array.from(new Set(dataRows.map((row) => row.projectId)))
- .flatMap((projectId) =>
- getEmptyTimelineBuckets(
- input.fromTimestamp,
- input.toTimestamp,
- granularity,
- ).map((row) => ({
- projectId,
- ...row,
- })),
- )
+ : getEmptyTimelineBuckets(
+ input.fromTimestamp,
+ input.toTimestamp,
+ granularity,
+ )
.concat(dataRows)
- .sort(compareTimelineRowsByProject);
+ .sort(compareTimelineRows);
}),
});
diff --git a/web/src/pages/organization/[organizationId]/v4/index.tsx b/web/src/pages/organization/[organizationId]/v4/index.tsx
index 6cbc63bc55..8ee75227fb 100644
--- a/web/src/pages/organization/[organizationId]/v4/index.tsx
+++ b/web/src/pages/organization/[organizationId]/v4/index.tsx
@@ -25,9 +25,7 @@ import {
import { numberFormatter } from "@/src/utils/numbers";
import {
V4MigrationProjectCards,
- type V4LegacyApiUsagePoint,
- type V4MigrationSummary,
- type V4TraceLevelEvalExecutionPoint,
+ type V4LegacyIntegrationSummary,
} from "@/src/features/v4/components/V4MigrationProjectCards";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import {
@@ -39,17 +37,20 @@ import {
} from "@/src/features/v4/utils";
import { cn } from "@/src/utils/tailwind";
-type ProjectSummary = V4MigrationSummary & {
+type ProjectSummary = V4LegacyIntegrationSummary & {
projectId: string;
projectName: string;
};
-type ProjectScopedLegacyApiUsagePoint = V4LegacyApiUsagePoint & {
+type ProjectScopedLegacyApiUsageSummary = {
projectId: string;
+ entrypoint: string;
+ count: number;
};
-type ProjectScopedEvalExecutionPoint = V4TraceLevelEvalExecutionPoint & {
+type ProjectTraceLevelEvalSummary = {
projectId: string;
+ traceLevelEvalCount: number;
};
const groupByProjectId = <T extends { projectId: string }>(
@@ -67,14 +68,15 @@ const groupByProjectId = <T extends { projectId: string }>(
};
const sumLegacyApiUsage = (
- rows: ProjectScopedLegacyApiUsagePoint[] | undefined,
+ rows: Array<{ count: number }> | undefined,
): number => rows?.reduce((total, row) => total + row.count, 0) ?? 0;
const getProjectActionCount = (
project: ProjectSummary,
+ traceLevelEvalCount: number,
legacyApiEntrypointCount: number,
): number =>
- project.traceLevelEvalCount +
+ traceLevelEvalCount +
project.legacyIntegrationCount +
legacyApiEntrypointCount;
@@ -109,13 +111,12 @@ export default function OrganizationV4Page() {
},
);
- const legacyApiUsageByProject =
- api.v4Transition.timeSeriesByEntrypointByProject.useQuery(
+ const legacyApiUsageSummaryByProject =
+ api.v4Transition.legacyApiUsageSummaryByProject.useQuery(
{
orgId: organizationId ?? "",
fromTimestamp: absoluteTimeRange.from,
toTimestamp: absoluteTimeRange.to,
- granularity: "auto",
},
{
enabled: Boolean(organizationId) && canViewOrgV4Page,
@@ -127,32 +128,39 @@ export default function OrganizationV4Page() {
},
);
- const traceLevelEvalExecutionsByProject =
- api.v4Transition.traceLevelEvalExecutionsTimeSeriesByProject.useQuery(
+ const traceLevelEvalSummaryByProject =
+ api.v4Transition.traceLevelEvalSummaryByProject.useQuery(
{
orgId: organizationId ?? "",
- fromTimestamp: absoluteTimeRange.from,
- toTimestamp: absoluteTimeRange.to,
- granularity: "auto",
},
{
enabled: Boolean(organizationId) && canViewOrgV4Page,
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
},
);
const legacyApiUsageRowsByProjectId = useMemo(
() =>
- groupByProjectId<ProjectScopedLegacyApiUsagePoint>(
- legacyApiUsageByProject.data,
+ groupByProjectId<ProjectScopedLegacyApiUsageSummary>(
+ legacyApiUsageSummaryByProject.data,
),
- [legacyApiUsageByProject.data],
+ [legacyApiUsageSummaryByProject.data],
);
- const evalExecutionRowsByProjectId = useMemo(
+ const traceLevelEvalCountsByProjectId = useMemo(
() =>
- groupByProjectId<ProjectScopedEvalExecutionPoint>(
- traceLevelEvalExecutionsByProject.data,
+ new Map(
+ (traceLevelEvalSummaryByProject.data ?? []).map(
+ (row: ProjectTraceLevelEvalSummary) => [
+ row.projectId,
+ row.traceLevelEvalCount,
+ ],
+ ),
),
- [traceLevelEvalExecutionsByProject.data],
+ [traceLevelEvalSummaryByProject.data],
);
const projects = useMemo(
@@ -160,12 +168,14 @@ export default function OrganizationV4Page() {
[...(summaryByProject.data?.projects ?? [])].sort((a, b) => {
const bActionCount = getProjectActionCount(
b,
+ traceLevelEvalCountsByProjectId.get(b.projectId) ?? 0,
countLegacyApiEntrypoints(
legacyApiUsageRowsByProjectId.get(b.projectId),
),
);
const aActionCount = getProjectActionCount(
a,
+ traceLevelEvalCountsByProjectId.get(a.projectId) ?? 0,
countLegacyApiEntrypoints(
legacyApiUsageRowsByProjectId.get(a.projectId),
),
@@ -174,7 +184,11 @@ export default function OrganizationV4Page() {
if (bActionCount !== aActionCount) return bActionCount - aActionCount;
return a.projectName.localeCompare(b.projectName);
}),
- [summaryByProject.data?.projects, legacyApiUsageRowsByProjectId],
+ [
+ summaryByProject.data?.projects,
+ legacyApiUsageRowsByProjectId,
+ traceLevelEvalCountsByProjectId,
+ ],
);
const [selectedProjectId, setSelectedProjectId] = useState<
string | undefined
@@ -185,6 +199,43 @@ export default function OrganizationV4Page() {
projects[0],
[projects, selectedProjectId],
);
+
+ const selectedProjectLegacyApiUsage =
+ api.v4Transition.timeSeriesByEntrypoint.useQuery(
+ {
+ projectId: selectedProject?.projectId ?? "",
+ fromTimestamp: absoluteTimeRange.from,
+ toTimestamp: absoluteTimeRange.to,
+ granularity: "auto",
+ },
+ {
+ enabled: Boolean(selectedProject?.projectId) && canViewOrgV4Page,
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const selectedProjectTraceLevelEvalExecutions =
+ api.v4Transition.traceLevelEvalExecutionsTimeSeries.useQuery(
+ {
+ projectId: selectedProject?.projectId ?? "",
+ fromTimestamp: absoluteTimeRange.from,
+ toTimestamp: absoluteTimeRange.to,
+ granularity: "auto",
+ },
+ {
+ enabled: Boolean(selectedProject?.projectId) && canViewOrgV4Page,
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
const migrationSummary = useMemo(() => {
return projects.reduce(
(summary, project) => {
@@ -193,6 +244,7 @@ export default function OrganizationV4Page() {
);
const actionCount = getProjectActionCount(
project,
+ traceLevelEvalCountsByProjectId.get(project.projectId) ?? 0,
countLegacyApiEntrypoints(legacyApiRows),
);
@@ -204,9 +256,20 @@ export default function OrganizationV4Page() {
},
{ projectsNotMigrated: 0, actionCount: 0 },
);
- }, [legacyApiUsageRowsByProjectId, projects]);
+ }, [
+ legacyApiUsageRowsByProjectId,
+ projects,
+ traceLevelEvalCountsByProjectId,
+ ]);
+ const isProjectListLoading = summaryByProject.isPending;
const isProjectReadinessLoading =
- summaryByProject.isPending || legacyApiUsageByProject.isPending;
+ summaryByProject.isPending ||
+ legacyApiUsageSummaryByProject.isPending ||
+ traceLevelEvalSummaryByProject.isPending;
+ const hasProjectReadinessError =
+ Boolean(summaryByProject.error) ||
+ Boolean(legacyApiUsageSummaryByProject.error) ||
+ Boolean(traceLevelEvalSummaryByProject.error);
useEffect(() => {
if (
@@ -252,16 +315,18 @@ export default function OrganizationV4Page() {
description={
isProjectReadinessLoading
? "Loading V4 migration data."
- : `${numberFormatter(
- migrationSummary.projectsNotMigrated,
- 0,
- )} of ${numberFormatter(
- projects.length,
- 0,
- )} projects not migrated - ${numberFormatter(
- migrationSummary.actionCount,
- 0,
- )} required changes`
+ : hasProjectReadinessError
+ ? "Some project readiness data could not be loaded."
+ : `${numberFormatter(
+ migrationSummary.projectsNotMigrated,
+ 0,
+ )} of ${numberFormatter(
+ projects.length,
+ 0,
+ )} projects not migrated - ${numberFormatter(
+ migrationSummary.actionCount,
+ 0,
+ )} required changes`
}
isLoading={isProjectReadinessLoading}
>
@@ -269,7 +334,7 @@ export default function OrganizationV4Page() {
<Alert>
<AlertDescription>Failed to load projects.</AlertDescription>
</Alert>
- ) : isProjectReadinessLoading ? (
+ ) : isProjectListLoading ? (
<div className="min-h-40" />
) : projects.length > 0 ? (
<div className="overflow-x-auto">
@@ -301,9 +366,23 @@ export default function OrganizationV4Page() {
countLegacyApiEntrypoints(legacyApiRows);
const actionCount = getProjectActionCount(
project,
+ traceLevelEvalCountsByProjectId.get(project.projectId) ??
+ 0,
legacyApiEntrypointCount,
);
- const migrationStatus = getV4MigrationStatus(actionCount);
+ const traceLevelEvalCount =
+ traceLevelEvalCountsByProjectId.get(project.projectId) ??
+ 0;
+ const isStatusPending =
+ legacyApiUsageSummaryByProject.isPending ||
+ traceLevelEvalSummaryByProject.isPending;
+ const hasStatusError =
+ Boolean(legacyApiUsageSummaryByProject.error) ||
+ Boolean(traceLevelEvalSummaryByProject.error);
+ const migrationStatus =
+ isStatusPending || hasStatusError
+ ? null
+ : getV4MigrationStatus(actionCount);
const isSelected =
selectedProject?.projectId === project.projectId;
@@ -322,31 +401,41 @@ export default function OrganizationV4Page() {
</TableCell>
<TableCell density="comfortable">
<Badge
- variant={migrationStatus.badgeVariant}
+ variant={
+ migrationStatus?.badgeVariant ?? "outline-solid"
+ }
size="sm"
>
- {migrationStatus.label}
+ {hasStatusError
+ ? "Unavailable"
+ : (migrationStatus?.label ?? "Loading")}
</Badge>
</TableCell>
<TableCell density="comfortable" className="text-right">
- {numberFormatter(project.traceLevelEvalCount, 0)}
+ {traceLevelEvalSummaryByProject.isPending
+ ? "Loading..."
+ : traceLevelEvalSummaryByProject.error
+ ? "Failed"
+ : numberFormatter(traceLevelEvalCount, 0)}
</TableCell>
<TableCell density="comfortable" className="text-right">
{numberFormatter(project.legacyIntegrationCount, 0)}
</TableCell>
<TableCell density="comfortable" className="text-right">
- {legacyApiUsageByProject.error
- ? "Failed"
- : legacyApiEntrypointCount > 0
- ? `${numberFormatter(
- legacyApiEntrypointCount,
- 0,
- )} routes - ${numberFormatter(
- legacyApiUsageCount,
- 0,
- 2,
- )} calls`
- : "0"}
+ {legacyApiUsageSummaryByProject.isPending
+ ? "Loading..."
+ : legacyApiUsageSummaryByProject.error
+ ? "Failed"
+ : legacyApiEntrypointCount > 0
+ ? `${numberFormatter(
+ legacyApiEntrypointCount,
+ 0,
+ )} routes - ${numberFormatter(
+ legacyApiUsageCount,
+ 0,
+ 2,
+ )} calls`
+ : "0"}
</TableCell>
<TableCell density="comfortable">
<Button
@@ -378,22 +467,32 @@ export default function OrganizationV4Page() {
<V4MigrationProjectCards
projectId={selectedProject.projectId}
projectName={selectedProject.projectName}
- summary={selectedProject}
- legacyApiUsage={legacyApiUsageRowsByProjectId.get(
- selectedProject.projectId,
- )}
- traceLevelEvalExecutions={evalExecutionRowsByProjectId.get(
- selectedProject.projectId,
- )}
- isSummaryLoading={summaryByProject.isPending}
- isLegacyApiUsageLoading={legacyApiUsageByProject.isPending}
+ legacyIntegrationSummary={selectedProject}
+ traceLevelEvalCount={
+ traceLevelEvalCountsByProjectId.get(selectedProject.projectId) ??
+ 0
+ }
+ legacyApiUsage={selectedProjectLegacyApiUsage.data}
+ traceLevelEvalExecutions={
+ selectedProjectTraceLevelEvalExecutions.data
+ }
+ isLegacyIntegrationSummaryLoading={summaryByProject.isPending}
+ isTraceLevelEvalSummaryLoading={
+ traceLevelEvalSummaryByProject.isPending
+ }
+ isLegacyApiUsageLoading={selectedProjectLegacyApiUsage.isPending}
isTraceLevelEvalExecutionsLoading={
- traceLevelEvalExecutionsByProject.isPending
+ selectedProjectTraceLevelEvalExecutions.isPending
}
- hasSummaryError={Boolean(summaryByProject.error)}
- hasLegacyApiUsageError={Boolean(legacyApiUsageByProject.error)}
+ hasLegacyIntegrationSummaryError={Boolean(summaryByProject.error)}
+ hasTraceLevelEvalSummaryError={Boolean(
+ traceLevelEvalSummaryByProject.error,
+ )}
+ hasLegacyApiUsageError={Boolean(
+ selectedProjectLegacyApiUsage.error,
+ )}
hasTraceLevelEvalExecutionsError={Boolean(
- traceLevelEvalExecutionsByProject.error,
+ selectedProjectTraceLevelEvalExecutions.error,
)}
/>
) : null}
diff --git a/web/src/pages/project/[projectId]/v4/index.tsx b/web/src/pages/project/[projectId]/v4/index.tsx
index d7cdc1589c..d74340fcf8 100644
--- a/web/src/pages/project/[projectId]/v4/index.tsx
+++ b/web/src/pages/project/[projectId]/v4/index.tsx
@@ -55,6 +55,20 @@ export default function V4Page() {
},
);
+ const traceLevelEvalSummary = api.v4Transition.traceLevelEvalSummary.useQuery(
+ {
+ projectId: projectId ?? "",
+ },
+ {
+ enabled: Boolean(projectId),
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
const traceLevelEvalExecutions =
api.v4Transition.traceLevelEvalExecutionsTimeSeries.useQuery(
{
@@ -65,6 +79,11 @@ export default function V4Page() {
},
{
enabled: Boolean(projectId),
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
},
);
@@ -90,13 +109,16 @@ export default function V4Page() {
<div className="mx-auto flex w-full max-w-screen-xl flex-col gap-3">
<V4MigrationProjectCards
projectId={projectId ?? ""}
- summary={summary.data}
+ legacyIntegrationSummary={summary.data}
+ traceLevelEvalCount={traceLevelEvalSummary.data?.traceLevelEvalCount}
legacyApiUsage={legacyApiUsage.data}
traceLevelEvalExecutions={traceLevelEvalExecutions.data}
- isSummaryLoading={summary.isPending}
+ isLegacyIntegrationSummaryLoading={summary.isPending}
+ isTraceLevelEvalSummaryLoading={traceLevelEvalSummary.isPending}
isLegacyApiUsageLoading={legacyApiUsage.isPending}
isTraceLevelEvalExecutionsLoading={traceLevelEvalExecutions.isPending}
- hasSummaryError={Boolean(summary.error)}
+ hasLegacyIntegrationSummaryError={Boolean(summary.error)}
+ hasTraceLevelEvalSummaryError={Boolean(traceLevelEvalSummary.error)}
hasLegacyApiUsageError={Boolean(legacyApiUsage.error)}
hasTraceLevelEvalExecutionsError={Boolean(
traceLevelEvalExecutions.error,