Skip to content

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

perf(scores): remove fk constraint from traceId and observationId on scores, change to projectId (#2012)

Marc Klingen10d84a409448
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 74b7a8534c..f327945e30 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -342,7 +342,7 @@ export type Prompt = {
export type Score = {
id: string;
timestamp: Generated<Timestamp>;
- project_id: string | null;
+ project_id: string;
name: string;
value: number;
source: ScoreSource;
diff --git a/packages/shared/prisma/migrations/20240512155021_scores_drop_fk_on_traces_and_observations/migration.sql b/packages/shared/prisma/migrations/20240512155021_scores_drop_fk_on_traces_and_observations/migration.sql
new file mode 100644
index 0000000000..5195945d02
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240512155021_scores_drop_fk_on_traces_and_observations/migration.sql
@@ -0,0 +1,5 @@
+-- DropForeignKey
+ALTER TABLE "scores" DROP CONSTRAINT "scores_observation_id_fkey";
+
+-- DropForeignKey
+ALTER TABLE "scores" DROP CONSTRAINT "scores_trace_id_fkey";
diff --git a/packages/shared/prisma/migrations/20240512155022_scores_non_null_and_add_fk_project_id/migration.sql b/packages/shared/prisma/migrations/20240512155022_scores_non_null_and_add_fk_project_id/migration.sql
new file mode 100644
index 0000000000..6bb0061d70
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240512155022_scores_non_null_and_add_fk_project_id/migration.sql
@@ -0,0 +1,11 @@
+/*
+ Warnings:
+
+ - Made the column `project_id` on table `scores` required. This step will fail if there are existing NULL values in that column.
+
+*/
+-- AlterTable
+ALTER TABLE "scores" ALTER COLUMN "project_id" SET NOT NULL;
+
+-- AddForeignKey
+ALTER TABLE "scores" ADD CONSTRAINT "scores_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/migrations/20240513082203_scores_unique_id_and_projectid_instead_of_id_and_traceid/migration.sql b/packages/shared/prisma/migrations/20240513082203_scores_unique_id_and_projectid_instead_of_id_and_traceid/migration.sql
new file mode 100644
index 0000000000..471dc81de9
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240513082203_scores_unique_id_and_projectid_instead_of_id_and_traceid/migration.sql
@@ -0,0 +1,8 @@
+/*
+ Warnings:
+
+ - A unique constraint covering the columns `[id,project_id]` on the table `scores` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- DropIndex
+DROP INDEX "scores_id_trace_id_key";
diff --git a/packages/shared/prisma/migrations/20240513082204_scores_unique_id_and_projectid_instead_of_id_and_traceid_index/migration.sql b/packages/shared/prisma/migrations/20240513082204_scores_unique_id_and_projectid_instead_of_id_and_traceid_index/migration.sql
new file mode 100644
index 0000000000..cbafc2f2cc
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240513082204_scores_unique_id_and_projectid_instead_of_id_and_traceid_index/migration.sql
@@ -0,0 +1,8 @@
+/*
+ Warnings:
+
+ - A unique constraint covering the columns `[id,project_id]` on the table `scores` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- CreateIndex
+CREATE UNIQUE INDEX CONCURRENTLY "scores_id_project_id_key" ON "scores"("id", "project_id");
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 6b5bfcf0ee..c46fa9f23a 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -113,6 +113,7 @@ model Project {
JobExecution JobExecution[]
LlmApiKeys LlmApiKeys[]
PosthogIntegration PosthogIntegration[]
+ Score Score[]
@@map("projects")
}
@@ -230,7 +231,6 @@ model Trace {
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- scores Score[]
DatasetRunItems DatasetRunItems[]
DatasetItem DatasetItem[]
JobExecution JobExecution[]
@@ -307,7 +307,6 @@ model Observation {
outputCost Decimal? @map("output_cost")
totalCost Decimal? @map("total_cost")
completionStartTime DateTime? @map("completion_start_time")
- scores Score[]
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
derivedDatasetItems DatasetItem[]
datasetRunItems DatasetRunItems[]
@@ -394,18 +393,17 @@ enum ObservationLevel {
model Score {
id String @id @default(cuid())
timestamp DateTime @default(now())
- projectId String? @map("project_id")
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
name String
value Float
source ScoreSource
comment String?
traceId String @map("trace_id")
- trace Trace @relation(fields: [traceId], references: [id], onDelete: Cascade)
observationId String? @map("observation_id")
- observation Observation? @relation(fields: [observationId], references: [id], onDelete: SetNull)
JobExecution JobExecution[]
- @@unique([id, traceId]) // used for upsert
+ @@unique([id, projectId]) // used for upserts via prisma
@@index(timestamp)
@@index([value])
@@index([projectId])
diff --git a/web/src/__tests__/ingestion.servertest.ts b/web/src/__tests__/ingestion.servertest.ts
index d4cb32aed9..e549cbbbe6 100644
--- a/web/src/__tests__/ingestion.servertest.ts
+++ b/web/src/__tests__/ingestion.servertest.ts
@@ -281,6 +281,7 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(dbScore?.name).toBe("score-name");
expect(dbScore?.value).toBe(100.5);
expect(dbScore?.observationId).toBeNull();
+ expect(dbScore?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
});
});
@@ -816,57 +817,6 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(dbTrace.length).toBe(1);
});
- it("should fail for auth errors", async () => {
- const traceId = v4();
- const scoreId = v4();
-
- const responseOne = await makeAPICall("POST", "/api/public/ingestion", {
- batch: [
- {
- id: v4(),
- type: "trace-create",
- timestamp: new Date().toISOString(),
- body: {
- id: traceId,
- name: "trace-name",
- userId: "user-1",
- metadata: { key: "value" },
- release: "1.0.0",
- version: "2.0.0",
- },
- },
- {
- id: v4(),
- type: "score-create",
- timestamp: new Date().toISOString(),
- body: {
- id: scoreId,
- name: "score-name",
- value: 100.5,
- traceId: "some-random-id",
- },
- },
- ],
- });
-
- expect(responseOne.status).toBe(207);
-
- expect("errors" in responseOne.body).toBe(true);
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- expect(responseOne.body.errors.length).toBe(1);
- expect("successes" in responseOne.body).toBe(true);
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- expect(responseOne.body.successes.length).toBe(1);
-
- const dbTrace = await prisma.trace.findMany({
- where: {
- name: "trace-name",
- },
- });
-
- expect(dbTrace.length).toBe(1);
- });
-
it("should fail for resource not found", async () => {
const traceId = v4();
@@ -1653,121 +1603,6 @@ IB Home / . . . / News / News about the IB / Why ChatGPT is an o
expect(dbScore?.value).toBe(scoreValue);
});
- it("should error on Bearer Auth for a trace from different project", async () => {
- const otherProjectId = "other_project_id";
- const traceId = "trace_id";
- const bearerAuth = "Bearer pk-lf-1234567890";
-
- const scoreId = "score_id";
- const scoreEventId = "score_event_id";
- const scoreName = "score-name";
- const scoreValue = 100.5;
-
- // Seed db with a trace to be scored
- try {
- await prisma.project.create({
- data: {
- id: otherProjectId,
- name: "another-project",
- },
- });
-
- await prisma.trace.create({
- data: {
- id: traceId,
- name: "trace-name",
- project: { connect: { id: otherProjectId } },
- },
- });
-
- const response = await makeAPICall(
- "POST",
- "/api/public/ingestion",
- {
- batch: [
- {
- id: scoreEventId,
- type: "score-create",
- timestamp: new Date().toISOString(),
- body: {
- id: scoreId,
- name: scoreName,
- value: scoreValue,
- traceId: traceId,
- },
- },
- ],
- },
- bearerAuth,
- );
-
- expect(response.status).toBe(207);
- expect(response.body.successes.length).toBe(0);
- expect(response.body).toHaveProperty("errors");
- expect(response.body.errors.length).toEqual(1);
- expect(response.body.errors[0]?.id).toEqual(scoreEventId);
-
- expect(await prisma.trace.count()).toBe(1);
- expect(await prisma.trace.count({ where: { id: traceId } })).toBe(1);
-
- const dbScore = await prisma.score.findUnique({
- where: {
- id: scoreId,
- },
- });
-
- expect(dbScore).toBeNull();
- } finally {
- await prisma.project.delete({ where: { id: otherProjectId } });
- }
- });
-
- it("should error on Bearer Auth with a trace that does not exist", async () => {
- const traceId = "trace_id";
- const bearerAuth = "Bearer pk-lf-1234567890";
-
- const scoreId = "score_id";
- const scoreEventId = "score_event_id";
- const scoreName = "score-name";
- const scoreValue = 100.5;
-
- const response = await makeAPICall(
- "POST",
- "/api/public/ingestion",
- {
- batch: [
- {
- id: scoreEventId,
- type: "score-create",
- timestamp: new Date().toISOString(),
- body: {
- id: scoreId,
- name: scoreName,
- value: scoreValue,
- traceId: traceId,
- },
- },
- ],
- },
- bearerAuth,
- );
-
- expect(response.status).toBe(207);
- expect(response.body.successes.length).toBe(0);
- expect(response.body.errors.length).toBe(1);
- expect(response.body.errors[0]?.id).toBe(scoreEventId);
-
- expect(await prisma.trace.count()).toBe(0);
-
- const dbScore = await prisma.score.findUnique({
- where: {
- id: scoreId,
- },
- });
-
- expect(dbScore).toBeNull();
- });
-
it("should error on wrong input", async () => {
const traceId = "trace_id";
const bearerAuth = "Bearer pk-lf-1234567890";
diff --git a/web/src/__tests__/query-builder.servertest.ts b/web/src/__tests__/query-builder.servertest.ts
index 69ddddc957..6724cdefa4 100644
--- a/web/src/__tests__/query-builder.servertest.ts
+++ b/web/src/__tests__/query-builder.servertest.ts
@@ -50,7 +50,7 @@ describe("Build valid SQL queries", () => {
table: "traces_scores",
values: ["project-id"],
strings: [
- ' FROM traces t JOIN scores s ON t.id = s.trace_id WHERE t."project_id" = ',
+ ' FROM traces t JOIN scores s ON t.id = s.trace_id AND t.project_id = s.project_id WHERE t."project_id" = ',
";",
],
} as const,
diff --git a/web/src/__tests__/scores.servertest.ts b/web/src/__tests__/scores.servertest.ts
index 33a3cdbe5f..6fe5cfc0c0 100644
--- a/web/src/__tests__/scores.servertest.ts
+++ b/web/src/__tests__/scores.servertest.ts
@@ -60,6 +60,7 @@ describe("/api/public/scores API Endpoint", () => {
expect(dbScore?.observationId).toBeNull();
expect(dbScore?.comment).toBe("comment");
expect(dbScore?.source).toBe("API");
+ expect(dbScore?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
});
it("should create score for a trace with int", async () => {
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index 50f10abb12..178d64ca61 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -147,6 +147,7 @@ export const datasetRouter = createTRPCRouter({
JOIN scores s
ON s.trace_id = ri.trace_id
AND (ri.observation_id IS NULL OR s.observation_id = ri.observation_id) -- only include scores that are linked to the observation if observation is linked
+ AND s.project_id = ${input.projectId}
JOIN traces t ON t.id = s.trace_id
WHERE t.project_id = ${input.projectId}
GROUP BY
@@ -553,13 +554,11 @@ export const datasetRouter = createTRPCRouter({
observation: {
select: {
id: true,
- scores: true,
},
},
trace: {
select: {
id: true,
- scores: true,
},
},
},
@@ -570,6 +569,27 @@ export const datasetRouter = createTRPCRouter({
skip: input.page * input.limit,
});
+ const traceScores = await ctx.prisma.score.findMany({
+ where: {
+ projectId: ctx.session.projectId,
+ traceId: {
+ in: runItems
+ .filter((ri) => ri.observationId === null) // only include trace scores if run is not linked to an observation
+ .map((ri) => ri.traceId),
+ },
+ },
+ });
+ const observationScores = await ctx.prisma.score.findMany({
+ where: {
+ projectId: ctx.session.projectId,
+ observationId: {
+ in: runItems
+ .filter((ri) => ri.observationId !== null)
+ .map((ri) => ri.observationId) as string[],
+ },
+ },
+ });
+
const totalRunItems = await ctx.prisma.datasetRunItems.count({
where: {
datasetRunId: input.datasetRunId,
@@ -582,14 +602,14 @@ export const datasetRouter = createTRPCRouter({
},
});
- const observationIds = runItems
- .map((ri) => ri.observation?.id)
- .filter(Boolean) as string[];
const observations = await ctx.prisma.observationView.findMany({
where: {
id: {
- in: observationIds,
+ in: runItems
+ .map((ri) => ri.observationId)
+ .filter(Boolean) as string[],
},
+ projectId: ctx.session.projectId,
},
select: {
id: true,
@@ -598,13 +618,10 @@ export const datasetRouter = createTRPCRouter({
},
});
- const traceIds = runItems
- .map((ri) => ri.trace?.id)
- .filter(Boolean) as string[];
const traces = await ctx.prisma.traceView.findMany({
where: {
id: {
- in: traceIds,
+ in: runItems.map((ri) => ri.traceId).filter(Boolean) as string[],
},
projectId: ctx.session.projectId,
},
@@ -621,10 +638,14 @@ export const datasetRouter = createTRPCRouter({
datasetItemId: ri.datasetItemId,
observation: observations.find((o) => o.id === ri.observationId),
trace: traces.find((t) => t.id === ri.traceId),
- scores:
- // use observation scores if run is linked to an observation, otherwise use all trace scores
- (!!ri.observationId ? ri.observation?.scores : ri.trace?.scores) ??
- [],
+ scores: [
+ ...traceScores.filter((s) => s.traceId === ri.traceId),
+ ...observationScores.filter(
+ (s) =>
+ s.observationId === ri.observationId &&
+ s.traceId === ri.traceId,
+ ),
+ ],
};
});
diff --git a/web/src/features/manual-scoring/components/ManualScoreButton.tsx b/web/src/features/manual-scoring/components/ManualScoreButton.tsx
index cc0fb0c9ed..10a718e50a 100644
--- a/web/src/features/manual-scoring/components/ManualScoreButton.tsx
+++ b/web/src/features/manual-scoring/components/ManualScoreButton.tsx
@@ -89,7 +89,7 @@ export function ManualScoreButton({
const handleDelete = async () => {
if (score) {
- await mutDeleteScore.mutateAsync(score.id);
+ await mutDeleteScore.mutateAsync({ id: score.id, projectId });
capture("score:delete", {
type: type,
source: source,
@@ -130,6 +130,7 @@ export function ManualScoreButton({
id: score.id,
value: values.score,
comment: values.comment,
+ projectId,
});
capture("score:update_form_submit", {
type: type,
@@ -142,6 +143,7 @@ export function ManualScoreButton({
comment: values.comment,
traceId,
observationId,
+ projectId,
});
capture("score:create_form_submit", {
type: type,
diff --git a/web/src/features/public-api/server/apiScope.ts b/web/src/features/public-api/server/apiScope.ts
index 19db3f8948..98fe70167d 100644
--- a/web/src/features/public-api/server/apiScope.ts
+++ b/web/src/features/public-api/server/apiScope.ts
@@ -59,7 +59,7 @@ async function isResourceInProject(resource: Resource, projectId: string) {
(await prisma.score.count({
where: {
id: resource.id,
- trace: { projectId },
+ projectId,
},
})) === 1;
if (!scoreCheck)
diff --git a/web/src/pages/api/cron/ingestion-metrics.ts b/web/src/pages/api/cron/ingestion-metrics.ts
index 60544417cf..e25d7e82fd 100644
--- a/web/src/pages/api/cron/ingestion-metrics.ts
+++ b/web/src/pages/api/cron/ingestion-metrics.ts
@@ -212,18 +212,17 @@ export default async function handler(
}>
>`
SELECT
- t.project_id,
+ s.project_id,
count(s.*)::integer count_scores
FROM
scores s
- JOIN traces t ON t.id = s.trace_id
- WHERE
- s.timestamp < ${endTimeframe}
- ${
- startTimeframe
- ? Prisma.sql`AND s.timestamp >= ${startTimeframe}`
- : Prisma.empty
- }
+ WHERE
+ s.timestamp < ${endTimeframe}
+ ${
+ startTimeframe
+ ? Prisma.sql`AND s.timestamp >= ${startTimeframe}`
+ : Prisma.empty
+ }
GROUP BY
1
`;
diff --git a/web/src/pages/api/public/scores.ts b/web/src/pages/api/public/scores.ts
index 14f632d0ea..d39bd5430c 100644
--- a/web/src/pages/api/public/scores.ts
+++ b/web/src/pages/api/public/scores.ts
@@ -20,15 +20,6 @@ import { isPrismaException } from "@/src/utils/exceptions";
const operators = ["<", ">", "<=", ">=", "!=", "="] as const;
-const prismaOperators: Record<(typeof operators)[number], string> = {
- "<": "lt",
- ">": "gt",
- "<=": "lte",
- ">=": "gte",
- "!=": "not",
- "=": "equals",
-};
-
const ScoresGetSchema = z.object({
...paginationZod,
userId: z.string().nullish(),
@@ -141,8 +132,8 @@ export default async function handler(
s.observation_id as "observationId",
json_build_object('userId', t.user_id) as "trace"
FROM "scores" AS s
- JOIN "traces" AS t ON t.id = s.trace_id
- WHERE t.project_id = ${authCheck.scope.projectId}
+ JOIN "traces" AS t ON t.id = s.trace_id AND t.project_id = ${authCheck.scope.projectId}
+ WHERE s.project_id = ${authCheck.scope.projectId}
${userCondition}
${nameCondition}
${sourceCondition}
@@ -151,25 +142,23 @@ export default async function handler(
ORDER BY t."timestamp" DESC
LIMIT ${obj.limit} OFFSET ${skipValue}
`);
- const totalItems = await prisma.score.count({
- where: {
- name: obj.name ? obj.name : undefined,
- source: obj.source ? obj.source : undefined,
- timestamp: obj.fromTimestamp
- ? { gte: new Date(obj.fromTimestamp) }
- : undefined,
- value:
- obj.operator && obj.value
- ? {
- [prismaOperators[obj.operator]]: obj.value,
- }
- : undefined,
- trace: {
- projectId: authCheck.scope.projectId,
- userId: obj.userId ? obj.userId : undefined,
- },
- },
- });
+
+ const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>(
+ Prisma.sql`
+ SELECT COUNT(*) as count
+ FROM "scores" AS s
+ JOIN "traces" AS t ON t.id = s.trace_id AND t.project_id = ${authCheck.scope.projectId}
+ WHERE s.project_id = ${authCheck.scope.projectId}
+ ${userCondition}
+ ${nameCondition}
+ ${sourceCondition}
+ ${fromTimestampCondition}
+ ${valueCondition}
+ `,
+ );
+
+ const totalItems =
+ totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;
return res.status(200).json({
data: scores,
diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].ts
index 0930181551..c9efc327e5 100644
--- a/web/src/pages/api/public/scores/[scoreId].ts
+++ b/web/src/pages/api/public/scores/[scoreId].ts
@@ -40,9 +40,7 @@ export default async function handler(
},
where: {
id: scoreId,
- trace: {
- projectId: authCheck.scope.projectId,
- },
+ projectId: authCheck.scope.projectId,
},
});
@@ -55,9 +53,7 @@ export default async function handler(
await prisma.score.delete({
where: {
id: scoreId,
- trace: {
- projectId: authCheck.scope.projectId,
- },
+ projectId: authCheck.scope.projectId,
},
});
@@ -107,9 +103,7 @@ export default async function handler(
const score = await prisma.score.findUnique({
where: {
id: scoreId,
- trace: {
- projectId: authCheck.scope.projectId,
- },
+ projectId: authCheck.scope.projectId,
},
});
diff --git a/web/src/pages/api/public/traces.ts b/web/src/pages/api/public/traces.ts
index b7725b81ea..4f1e36e980 100644
--- a/web/src/pages/api/public/traces.ts
+++ b/web/src/pages/api/public/traces.ts
@@ -139,7 +139,7 @@ export default async function handler(
COALESCE(ARRAY_AGG(DISTINCT s.id) FILTER (WHERE s.id IS NOT NULL), ARRAY[]::text[]) AS "scores"
FROM "traces" AS t
LEFT JOIN "observations_view" AS o ON t.id = o.trace_id AND o.project_id = ${authCheck.scope.projectId}
- LEFT JOIN "scores" AS s ON t.id = s.trace_id
+ LEFT JOIN "scores" AS s ON t.id = s.trace_id AND s.project_id = ${authCheck.scope.projectId}
WHERE t.project_id = ${authCheck.scope.projectId}
${userCondition}
${nameCondition}
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index 81adf3addf..a4e17422c8 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -48,9 +48,6 @@ export default async function handler(
id: traceId,
projectId: authCheck.scope.projectId,
},
- include: {
- scores: true,
- },
});
if (!trace) {
@@ -59,6 +56,13 @@ export default async function handler(
});
}
+ const scores = await prisma.score.findMany({
+ where: {
+ traceId: traceId,
+ projectId: authCheck.scope.projectId,
+ },
+ });
+
const observations = await prisma.observationView.findMany({
where: {
traceId: traceId,
@@ -70,6 +74,7 @@ export default async function handler(
return res.status(200).json({
...trace,
+ scores,
htmlPath: `/project/${authCheck.scope.projectId}/traces/${traceId}`,
totalCost: outObservations.reduce(
(acc, obs) => acc + (obs.calculatedTotalCost ?? 0),
diff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
index be076db9ca..15963b6b4f 100644
--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
@@ -77,6 +77,8 @@ export async function getAllGenerations({
comment
FROM
scores
+ WHERE
+ project_id = ${input.projectId}
GROUP BY
1,
2,
@@ -118,12 +120,11 @@ export async function getAllGenerations({
p.name as "promptName",
p.version as "promptVersion"
FROM observations_view o
- JOIN traces t ON t.id = o.trace_id AND t.project_id = o.project_id
+ JOIN traces t ON t.id = o.trace_id AND t.project_id = ${input.projectId}
LEFT JOIN scores_avg AS s_avg ON s_avg.trace_id = t.id and s_avg.observation_id = o.id
- LEFT JOIN prompts p ON p.id = o.prompt_id
+ LEFT JOIN prompts p ON p.id = o.prompt_id AND p.project_id = ${input.projectId}
WHERE
o.project_id = ${input.projectId}
- AND t.project_id = ${input.projectId}
AND o.type = 'GENERATION'
${datetimeFilter}
${searchCondition}
@@ -138,9 +139,7 @@ export async function getAllGenerations({
const scores = await prisma.score.findMany({
where: {
- trace: {
- projectId: input.projectId,
- },
+ projectId: input.projectId,
observationId: {
in: generations.map((gen) => gen.id),
},
diff --git a/web/src/server/api/routers/generations/filterOptionsQuery.ts b/web/src/server/api/routers/generations/filterOptionsQuery.ts
index 5a855cbce8..3ef643c905 100644
--- a/web/src/server/api/routers/generations/filterOptionsQuery.ts
+++ b/web/src/server/api/routers/generations/filterOptionsQuery.ts
@@ -14,9 +14,7 @@ export const filterOptionsQuery = protectedProjectProcedure
const scores = await ctx.prisma.score.groupBy({
where: {
- observation: {
- projectId: input.projectId,
- },
+ projectId: input.projectId,
},
take: 1000,
orderBy: {
diff --git a/web/src/server/api/routers/generations/getAllQuery.ts b/web/src/server/api/routers/generations/getAllQuery.ts
index 6df479cc64..c945222d0a 100644
--- a/web/src/server/api/routers/generations/getAllQuery.ts
+++ b/web/src/server/api/routers/generations/getAllQuery.ts
@@ -40,8 +40,8 @@ export const getAllQuery = protectedProjectProcedure
SELECT
count(*)
FROM observations_view o
- JOIN traces t ON t.id = o.trace_id AND t.project_id = o.project_id
- LEFT JOIN prompts p ON p.id = o.prompt_id
+ JOIN traces t ON t.id = o.trace_id AND t.project_id = ${input.projectId}
+ LEFT JOIN prompts p ON p.id = o.prompt_id AND p.project_id = ${input.projectId}
LEFT JOIN LATERAL (
SELECT
jsonb_object_agg(name::text, avg_value::double precision) AS "scores_avg"
@@ -52,15 +52,15 @@ export const getAllQuery = protectedProjectProcedure
FROM
scores
WHERE
- scores."trace_id" = t.id
+ scores."project_id" = ${input.projectId}
+ AND scores."trace_id" = t.id
AND scores."observation_id" = o.id
GROUP BY
name
) tmp
) AS s_avg ON true
WHERE
- t.project_id = ${input.projectId}
- AND o.type = 'GENERATION'
+ o.type = 'GENERATION'
AND o.project_id = ${input.projectId}
${datetimeFilter}
${searchCondition}
diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.ts
index 9c957a523e..989602ee28 100644
--- a/web/src/server/api/routers/observations.ts
+++ b/web/src/server/api/routers/observations.ts
@@ -23,6 +23,7 @@ export const observationsRouter = createTRPCRouter({
? await ctx.prisma.score.findMany({
where: {
traceId: observation.traceId,
+ projectId: observation.projectId,
},
})
: [];
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index 8a64e47a64..4e9f4a7efb 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -2,7 +2,6 @@ import { z } from "zod";
import {
createTRPCRouter,
- protectedProcedure,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
@@ -101,14 +100,18 @@ export const scoresRouter = createTRPCRouter({
.query(async ({ input, ctx }) => {
const names = await ctx.prisma.score.groupBy({
where: {
- trace: {
- projectId: input.projectId,
- },
+ projectId: input.projectId,
},
by: ["name"],
_count: {
_all: true,
},
+ take: 1000,
+ orderBy: {
+ _count: {
+ id: "desc",
+ },
+ },
});
const res: ScoreOptions = {
@@ -117,29 +120,10 @@ export const scoresRouter = createTRPCRouter({
return res;
}),
- byId: protectedProcedure.input(z.string()).query(({ input, ctx }) =>
- ctx.prisma.score.findFirstOrThrow({
- where: {
- id: input,
- ...(ctx.session.user.admin === true
- ? undefined
- : {
- trace: {
- project: {
- projectMembers: {
- some: {
- userId: ctx.session.user.id,
- },
- },
- },
- },
- }),
- },
- }),
- ),
- createReviewScore: protectedProcedure
+ createReviewScore: protectedProjectProcedure
.input(
z.object({
+ projectId: z.string(),
traceId: z.string(),
value: z.number(),
name: z.string(),
@@ -148,52 +132,38 @@ export const scoresRouter = createTRPCRouter({
}),
)
.mutation(async ({ input, ctx }) => {
- const trace = await ctx.prisma.trace.findFirstOrThrow({
- where: {
- id: input.traceId,
- project: {
- projectMembers: {
- some: {
- userId: ctx.session.user.id,
- },
- },
- },
- },
- });
throwIfNoAccess({
session: ctx.session,
- projectId: trace.projectId,
+ projectId: input.projectId,
scope: "scores:CUD",
});
+ const trace = await ctx.prisma.trace.findFirst({
+ where: {
+ id: input.traceId,
+ projectId: input.projectId,
+ },
+ });
+ if (!trace) {
+ throw new Error("No trace with this id in this project.");
+ }
+
const score = await ctx.prisma.score.create({
data: {
- trace: {
- connect: {
- id: trace.id,
- },
- },
- ...(input.observationId
- ? {
- observation: {
- connect: {
- id: input.observationId,
- },
- },
- }
- : undefined),
+ projectId: input.projectId,
+ traceId: input.traceId,
+ observationId: input.observationId,
value: input.value,
name: input.name,
comment: input.comment,
- projectId: trace.projectId,
source: "REVIEW",
},
});
await auditLog({
- projectId: trace.projectId,
+ projectId: input.projectId,
userId: ctx.session.user.id,
userProjectRole: ctx.session.user.projects.find(
- (p) => p.id === trace.projectId,
+ (p) => p.id === input.projectId,
)?.role as ProjectRole, // throwIfNoAccess ensures this is defined
resourceType: "score",
resourceId: score.id,
@@ -202,61 +172,48 @@ export const scoresRouter = createTRPCRouter({
});
return score;
}),
- updateReviewScore: protectedProcedure
+ updateReviewScore: protectedProjectProcedure
.input(
z.object({
+ projectId: z.string(),
id: z.string(),
value: z.number(),
comment: z.string().optional(),
}),
)
.mutation(async ({ input, ctx }) => {
- const score = await ctx.prisma.score.findFirstOrThrow({
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "scores:CUD",
+ });
+ const score = await ctx.prisma.score.findFirst({
where: {
id: input.id,
+ projectId: input.projectId,
source: "REVIEW",
- trace: {
- project: {
- projectMembers: {
- some: {
- userId: ctx.session.user.id,
- },
- },
- },
- },
},
- include: {
- trace: {
- select: {
- projectId: true,
- },
- },
- },
- });
- throwIfNoAccess({
- session: ctx.session,
- projectId: score.trace.projectId,
- scope: "scores:CUD",
});
+ if (!score) {
+ throw new Error("No review score with this id in this project.");
+ }
- // exclude trace object from audit log
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { trace, ...pureScore } = score;
await auditLog({
- projectId: trace.projectId,
+ projectId: input.projectId,
userId: ctx.session.user.id,
userProjectRole: ctx.session.user.projects.find(
- (p) => p.id === trace.projectId,
+ (p) => p.id === input.projectId,
)?.role as ProjectRole, // throwIfNoAccess ensures this is defined
resourceType: "score",
resourceId: score.id,
action: "update",
- after: pureScore,
+ after: score,
});
return ctx.prisma.score.update({
where: {
id: score.id,
+ projectId: input.projectId,
},
data: {
value: input.value,
@@ -264,52 +221,42 @@ export const scoresRouter = createTRPCRouter({
},
});
}),
- deleteReviewScore: protectedProcedure
- .input(z.string())
+ deleteReviewScore: protectedProjectProcedure
+ .input(z.object({ projectId: z.string(), id: z.string() }))
.mutation(async ({ input, ctx }) => {
- const score = await ctx.prisma.score.findFirstOrThrow({
- where: {
- id: input,
- source: "REVIEW",
- trace: {
- project: {
- projectMembers: {
- some: {
- userId: ctx.session.user.id,
- },
- },
- },
- },
- },
- include: {
- trace: {
- select: {
- projectId: true,
- },
- },
- },
- });
throwIfNoAccess({
session: ctx.session,
- projectId: score.trace.projectId,
+ projectId: input.projectId,
scope: "scores:CUD",
});
- const { trace, ...pureScore } = score;
+
+ const score = await ctx.prisma.score.findFirst({
+ where: {
+ id: input.id,
+ source: "REVIEW",
+ projectId: input.projectId,
+ },
+ });
+ if (!score) {
+ throw new Error("No review score with this id in this project.");
+ }
+
await auditLog({
- projectId: trace.projectId,
+ projectId: input.projectId,
userId: ctx.session.user.id,
userProjectRole: ctx.session.user.projects.find(
- (p) => p.id === trace.projectId,
+ (p) => p.id === input.projectId,
)?.role as ProjectRole, // throwIfNoAccess ensures this is defined
resourceType: "score",
resourceId: score.id,
action: "delete",
- before: pureScore,
+ before: score,
});
return ctx.prisma.score.delete({
where: {
id: score.id,
+ projectId: input.projectId,
},
});
}),
@@ -327,8 +274,9 @@ const generateScoresQuery = (
SELECT
${select}
FROM scores s
- JOIN traces t ON t.id = s.trace_id LEFT JOIN job_executions je ON je.job_output_score_id = s.id AND je.project_id = ${projectId}
- WHERE t.project_id = ${projectId}
+ JOIN traces t ON t.id = s.trace_id AND t.project_id = ${projectId}
+ LEFT JOIN job_executions je ON je.job_output_score_id = s.id AND je.project_id = ${projectId}
+ WHERE s.project_id = ${projectId}
${filterCondition}
${orderCondition}
LIMIT ${limit}
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 2d9c2d4c8b..d8ca5f96c6 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -166,7 +166,6 @@ export const sessionRouter = createTRPCRouter({
select: {
id: true,
userId: true,
- scores: true,
name: true,
timestamp: true,
},
@@ -180,6 +179,15 @@ export const sessionRouter = createTRPCRouter({
});
}
+ const scores = await ctx.prisma.score.findMany({
+ where: {
+ traceId: {
+ in: session.traces.map((t) => t.id),
+ },
+ projectId: input.projectId,
+ },
+ });
+
const totalCostQuery = Prisma.sql`
SELECT
SUM(COALESCE(o."calculated_total_cost", 0)) AS "totalCost"
@@ -197,6 +205,10 @@ export const sessionRouter = createTRPCRouter({
return {
...session,
+ traces: session.traces.map((t) => ({
+ ...t,
+ scores: scores.filter((s) => s.traceId === t.id),
+ })),
totalCost: costData?.totalCost ?? 0,
users: [
...new Set(
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index a34fad092d..27f7d98fcc 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -144,9 +144,7 @@ export const traceRouter = createTRPCRouter({
// performance of the query above
const scores = await ctx.prisma.score.findMany({
where: {
- trace: {
- projectId: input.projectId,
- },
+ projectId: input.projectId,
traceId: {
in: traces.map((t) => t.id),
},
@@ -178,9 +176,7 @@ export const traceRouter = createTRPCRouter({
.query(async ({ input, ctx }) => {
const scores = await ctx.prisma.score.groupBy({
where: {
- trace: {
- projectId: input.projectId,
- },
+ projectId: input.projectId,
},
take: 1000,
orderBy: {
@@ -239,9 +235,6 @@ export const traceRouter = createTRPCRouter({
where: {
id: input.traceId,
},
- include: {
- scores: true,
- },
});
const observations = await ctx.prisma.observationView.findMany({
select: {
@@ -281,6 +274,12 @@ export const traceRouter = createTRPCRouter({
projectId: trace.projectId,
},
});
+ const scores = await ctx.prisma.score.findMany({
+ where: {
+ traceId: input.traceId,
+ projectId: trace.projectId,
+ },
+ });
const obsStartTimes = observations
.map((o) => o.startTime)
@@ -302,6 +301,7 @@ export const traceRouter = createTRPCRouter({
return {
...trace,
+ scores,
latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
observations: observations as ObservationReturnType[],
};
@@ -346,6 +346,14 @@ export const traceRouter = createTRPCRouter({
projectId: input.projectId,
},
}),
+ ctx.prisma.score.deleteMany({
+ where: {
+ traceId: {
+ in: input.traceIds,
+ },
+ projectId: input.projectId,
+ },
+ }),
]);
}),
bookmark: protectedProjectProcedure
diff --git a/web/src/server/api/routers/users.ts b/web/src/server/api/routers/users.ts
index e7800417ac..bb18c9e490 100644
--- a/web/src/server/api/routers/users.ts
+++ b/web/src/server/api/routers/users.ts
@@ -155,6 +155,7 @@ export const userRouter = createTRPCRouter({
JOIN traces t ON t.id = s.trace_id
WHERE
s.trace_id IS NOT NULL
+ AND s.project_id = ${input.projectId}
AND t.project_id = ${input.projectId}
AND t.user_id IN (${Prisma.join(users.map((user) => user.userId))})
AND t.user_id IS NOT NULL
@@ -251,6 +252,7 @@ export const userRouter = createTRPCRouter({
JOIN traces t ON t.id = s.trace_id
WHERE
s.trace_id IS NOT NULL
+ AND s.project_id = ${input.projectId}
AND t.project_id = ${input.projectId}
AND t.user_id = ${input.userId}
AND t.user_id IS NOT NULL
diff --git a/web/src/server/api/services/EventProcessor.ts b/web/src/server/api/services/EventProcessor.ts
index 9bae8437d5..a7b95c66c2 100644
--- a/web/src/server/api/services/EventProcessor.ts
+++ b/web/src/server/api/services/EventProcessor.ts
@@ -1,5 +1,4 @@
import { tokenCount } from "@/src/features/ingest/lib/usage";
-import { checkApiAccessScope } from "@/src/features/public-api/server/apiScope";
import { type ApiAccessScope } from "@/src/features/public-api/server/types";
import {
type legacyObservationCreateEvent,
@@ -439,7 +438,7 @@ export class TraceProcessor implements EventProcessor {
if (existingTrace && existingTrace.projectId !== apiScope.projectId) {
throw new ForbiddenError(
- `Access denied for trace creation ${existingTrace.projectId} `,
+ `Access denied for trace creation ${existingTrace.projectId}`,
);
}
@@ -520,52 +519,53 @@ export class ScoreProcessor implements EventProcessor {
): Promise<Trace | Observation | Score> {
const { body } = this.event;
- const accessCheck = await checkApiAccessScope(
- apiScope,
- [
- { type: "trace", id: body.traceId },
- ...(body.observationId
- ? [{ type: "observation" as const, id: body.observationId }]
- : []),
- ],
- "score",
- );
- if (!accessCheck)
- throw new ForbiddenError("Access denied for score creation");
+ if (apiScope.accessLevel !== "scores" && apiScope.accessLevel !== "all")
+ throw new ForbiddenError(
+ `Access denied for score creation, ${apiScope.accessLevel}`,
+ );
const id = body.id ?? v4();
- // access control via traceId
+ const existingScore = await prisma.score.findFirst({
+ where: {
+ id: id,
+ },
+ select: {
+ projectId: true,
+ },
+ });
+ if (existingScore && existingScore.projectId !== apiScope.projectId) {
+ throw new ForbiddenError(
+ `Access denied for score creation ${existingScore.projectId}`,
+ );
+ }
+
return await prisma.score.upsert({
where: {
- id_traceId: {
+ id_projectId: {
id,
- traceId: body.traceId,
+ projectId: apiScope.projectId,
},
},
create: {
id,
projectId: apiScope.projectId,
- trace: { connect: { id: body.traceId } },
+ traceId: body.traceId,
+ observationId: body.observationId ?? undefined,
timestamp: new Date(),
value: body.value,
name: body.name,
- source: "API",
comment: body.comment,
- ...(body.observationId && {
- observation: { connect: { id: body.observationId } },
- }),
+ source: "API",
},
update: {
+ traceId: body.traceId,
+ observationId: body.observationId ?? undefined,
timestamp: new Date(),
- projectId: apiScope.projectId,
value: body.value,
name: body.name,
comment: body.comment,
source: "API",
- ...(body.observationId && {
- observation: { connect: { id: body.observationId } },
- }),
},
});
}
diff --git a/web/src/server/api/services/tableDefinitions.ts b/web/src/server/api/services/tableDefinitions.ts
index 261cefaf9e..afdad00a29 100644
--- a/web/src/server/api/services/tableDefinitions.ts
+++ b/web/src/server/api/services/tableDefinitions.ts
@@ -200,7 +200,7 @@ export const tableDefinitions: TableDefinitions = {
],
},
traces_scores: {
- table: ` traces t JOIN scores s ON t.id = s.trace_id`,
+ table: ` traces t JOIN scores s ON t.id = s.trace_id AND t.project_id = s.project_id`,
columns: [
tracesProjectId,
{ name: "value", id: "value", type: "number", internal: 's."value"' },
@@ -222,7 +222,7 @@ export const tableDefinitions: TableDefinitions = {
},
traces_parent_observation_scores: {
- table: ` traces t LEFT JOIN observations_view o on t."id" = o."trace_id" and o."parent_observation_id" is NULL LEFT JOIN scores s ON t."id" = s."trace_id"`,
+ table: ` traces t LEFT JOIN observations_view o on t."id" = o."trace_id" and o."parent_observation_id" is NULL AND t.project_id = o.project_id LEFT JOIN scores s ON t."id" = s."trace_id" AND t.project_id = s.project_id`,
columns: [
{
name: "projectId",
diff --git a/worker/generated/types.ts b/worker/generated/types.ts
index 9e8629ee73..075a213eae 100644
--- a/worker/generated/types.ts
+++ b/worker/generated/types.ts
@@ -347,7 +347,7 @@ export type Prompt = {
export type Score = {
id: string;
timestamp: Generated<Timestamp>;
- project_id: string | null;
+ project_id: string;
name: string;
value: number;
source: ScoreSource;
diff --git a/worker/src/__tests__/eval-service.test.ts b/worker/src/__tests__/eval-service.test.ts
index 67522aed06..e6c9f5cf34 100644
--- a/worker/src/__tests__/eval-service.test.ts
+++ b/worker/src/__tests__/eval-service.test.ts
@@ -342,6 +342,7 @@ describe("execute evals", () => {
expect(scores.length).toBe(1);
expect(scores[0].trace_id).toBe(traceId);
expect(scores[0].comment).not.toBeNull();
+ expect(scores[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
}, 10_000);
test("fails to eval without llm api key", async () => {