🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(ci): disable test sharding + speed up test suite (#13383)
Tobias Wochingere748cc102f8f
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 5db428a285..b9e9a73f1c 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -100,6 +100,8 @@ jobs:cp .env.dev.example .env- name: lint webrun: pnpm run lint+ - name: typecheck+ run: pnpm run typecheckprettier-check:runs-on: blacksmith-4vcpu-ubuntu-2404@@ -217,13 +219,12 @@ jobs:needs:- pre-jobif: needs.pre-job.outputs.should_skip != 'true'- name: tests-web (node${{ matrix.node-version }}, pg${{ matrix.postgres-version }}, mode${{ matrix.deploy-mode }}, shard${{ matrix.shard }}/3)+ name: tests-web (node${{ matrix.node-version }}, pg${{ matrix.postgres-version }}, mode${{ matrix.deploy-mode }})strategy:matrix:node-version: [24]postgres-version: [12, 15]deploy-mode: ["", "-azure", "-redis-cluster"]- shard: [1, 2, 3]steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:@@ -261,6 +262,7 @@ jobs:echo "LANGFUSE_INGESTION_QUEUE_DELAY_MS=1" >> .envecho "LANGFUSE_CACHE_PROMPT_ENABLED=false" >> .envecho "LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=1" >> .env+ echo "LANGFUSE_TRACE_DELETE_DELAY_MS=1" >> .envecho "LANGFUSE_TRACE_DELETE_CONCURRENCY=100" >> .envecho "ADMIN_API_KEY=admin-api-key" >> .envecho "LANGFUSE_EE_LICENSE_KEY=langfuse_ee_test" >> .env@@ -310,6 +312,9 @@ jobs:run: pnpm run buildenv:NODE_OPTIONS: --max_old_space_size=8192+ # TypeScript is checked explicitly in the lint job; skip duplicate+ # Next.js type checks in test builds to reduce CI runtime.+ NEXT_IGNORE_BUILD_ERRORS: "true"- name: Start Langfuserun: (pnpm run start&)env:@@ -325,9 +330,9 @@ jobs:LANGFUSE_INIT_USER_PASSWORD: "password"- name: run testsworking-directory: web- run: npx dotenv -e ../.env.test -e ../.env -- vitest run --project server --shard=${{ matrix.shard }}/3+ run: npx dotenv -e ../.env.test -e ../.env -- vitest run --project server- name: run test-client- if: matrix.deploy-mode == '' && matrix.shard == 1+ if: matrix.deploy-mode == ''working-directory: webrun: npx dotenv -e ../.env.test -e ../.env -- vitest run --project client@@ -567,8 +572,11 @@ jobs:run: pnpm run buildenv:NODE_OPTIONS: --max_old_space_size=8192+ # TypeScript is checked explicitly in the lint job; skip duplicate+ # Next.js type checks in test builds to reduce CI runtime.+ NEXT_IGNORE_BUILD_ERRORS: "true"- name: Install playwright- run: pnpm --filter=web exec playwright install --with-deps+ run: pnpm --filter=web exec playwright install --with-deps --only-shell chromium- name: Run e2e testsrun: pnpm --filter=web run test:e2e@@ -630,6 +638,9 @@ jobs:run: pnpm run buildenv:NODE_OPTIONS: --max_old_space_size=8192+ # TypeScript is checked explicitly in the lint job; skip duplicate+ # Next.js type checks in test builds to reduce CI runtime.+ NEXT_IGNORE_BUILD_ERRORS: "true"- name: Run serverrun: (pnpm run start&)- name: Check worker healthdiff --git a/.gitignore b/.gitignoreindex 2d3bd9c395..acb7d3f8b6 100644--- a/.gitignore+++ b/.gitignore@@ -93,3 +93,4 @@ web/test-results/*# Refactoring planning files (local only)**/.refactor/+**/.pi-lens/diff --git a/packages/shared/src/server/test-utils/org-factory.ts b/packages/shared/src/server/test-utils/org-factory.tsindex b728f2fab2..58e164b240 100644--- a/packages/shared/src/server/test-utils/org-factory.ts+++ b/packages/shared/src/server/test-utils/org-factory.ts@@ -1,7 +1,8 @@import { v4 } from "uuid";import { prisma } from "../../db";-import { hashSecretKey, getDisplaySecretKey } from "../auth/apiKeys";+import { env } from "../../env";import { CloudConfigSchema } from "../../interfaces/cloudConfigSchema";+import { createShaHash, getDisplaySecretKey } from "../auth/apiKeys";export function createBasicAuthHeader(username: string,@@ -17,6 +18,7 @@ export type CreateOrgProjectAndApiKeyOptions = {projectId?: string;plan?: "Team" | "Hobby" | "Core" | "Pro" | "Enterprise";};+export const createOrgProjectAndApiKey = async (props?: CreateOrgProjectAndApiKeyOptions,) => {@@ -38,7 +40,11 @@ export const createOrgProjectAndApiKey = async (},});const publicKey = v4();- const secretKey = v4();+ const secretKey = `sk-lf-${v4()}`;+ const salt = env.SALT;+ if (!salt) {+ throw new Error("SALT is not set");+ }const auth = createBasicAuthHeader(publicKey, secretKey);await prisma.apiKey.create({@@ -46,7 +52,11 @@ export const createOrgProjectAndApiKey = async (id: v4(),projectId: projectId,publicKey: publicKey,- hashedSecretKey: await hashSecretKey(secretKey),+ // Test fixtures use the modern fast-hash auth path. Avoid bcrypt here as+ // cost-11 hashing adds ~100ms per fixture; keep the legacy hash unique to+ // satisfy the database constraint without affecting authentication.+ hashedSecretKey: `test-hashed-secret-key-${v4()}`,+ fastHashedSecretKey: createShaHash(secretKey, salt),displaySecretKey: getDisplaySecretKey(secretKey),scope: "PROJECT",},diff --git a/scripts/vitest/ci-reporter.ts b/scripts/vitest/ci-reporter.tsnew file mode 100644index 0000000000..bdbb8ca569--- /dev/null+++ b/scripts/vitest/ci-reporter.ts@@ -0,0 +1,170 @@+const SLOW_TEST_LIMIT = 10;+const SLOW_FILE_LIMIT = 10;++type TestCaseLike = {+ fullName: string;+ module: {+ moduleId: string;+ relativeModuleId?: string;+ };+ diagnostic():+ | { duration: number; flaky?: boolean; retryCount?: number }+ | undefined;+ result(): { state: string };+};++type TestModuleLike = {+ children: {+ allTests(): Iterable<TestCaseLike>;+ };+};++type TestResult = {+ duration: number;+ file: string;+ name: string;+ state: string;+ retryCount: number;+ flaky: boolean;+};++type SlowFile = {+ duration: number;+ file: string;+ testCount: number;+};++const formatDuration = (duration: number) =>+ duration >= 1000+ ? `${(duration / 1000).toFixed(2)}s`+ : `${Math.round(duration)}ms`;++export class VitestCiReporter {+ onTestRunEnd(testModules: ReadonlyArray<TestModuleLike>) {+ const completedTests = testModules+ .flatMap((testModule) => [...testModule.children.allTests()])+ .map((testCase) => {+ const diagnostic = testCase.diagnostic();+ const duration = diagnostic?.duration;++ if (+ diagnostic === undefined ||+ duration === undefined ||+ !Number.isFinite(duration)+ ) {+ return undefined;+ }++ const result = testCase.result();++ if (result.state === "skipped") {+ return undefined;+ }++ return {+ duration,+ file: testCase.module.relativeModuleId ?? testCase.module.moduleId,+ name: testCase.fullName,+ state: result.state,+ retryCount: diagnostic.retryCount ?? 0,+ flaky: diagnostic.flaky ?? false,+ };+ })+ .filter((test): test is TestResult => test !== undefined);++ const slowestTests = [...completedTests]+ .sort((left, right) => right.duration - left.duration)+ .slice(0, SLOW_TEST_LIMIT);++ if (slowestTests.length === 0) {+ return;+ }++ const rankWidth = String(slowestTests.length).length;+ const durationWidth = Math.max(+ ...slowestTests.map((test) => formatDuration(test.duration).length),+ );++ console.log(`\nSlowest tests (top ${SLOW_TEST_LIMIT}):`);++ slowestTests.forEach((test, index) => {+ const rank = String(index + 1).padStart(rankWidth, " ");+ const duration = formatDuration(test.duration).padStart(+ durationWidth,+ " ",+ );+ const state = test.state === "passed" ? "" : ` [${test.state}]`;+ const retry = test.retryCount > 0 ? ` [retries=${test.retryCount}]` : "";+ const flaky = test.flaky ? " [flaky]" : "";++ console.log(+ `${rank}. ${duration} ${test.file} > ${test.name}${state}${retry}${flaky}`,+ );+ });++ const slowestFiles = Array.from(+ [...completedTests]+ .reduce<Map<string, SlowFile>>((filesByPath, test) => {+ const current = filesByPath.get(test.file) ?? {+ duration: 0,+ file: test.file,+ testCount: 0,+ };++ current.duration += test.duration;+ current.testCount += 1;+ filesByPath.set(test.file, current);++ return filesByPath;+ }, new Map())+ .values(),+ )+ .sort((left, right) => right.duration - left.duration)+ .slice(0, SLOW_FILE_LIMIT);++ const fileRankWidth = String(slowestFiles.length).length;+ const fileDurationWidth = Math.max(+ ...slowestFiles.map((file) => formatDuration(file.duration).length),+ );+ const testCountWidth = Math.max(+ ...slowestFiles.map((file) => String(file.testCount).length),+ );++ console.log(+ `\nSlowest test files (top ${SLOW_FILE_LIMIT}, summed test durations):`,+ );++ slowestFiles.forEach((file, index) => {+ const rank = String(index + 1).padStart(fileRankWidth, " ");+ const duration = formatDuration(file.duration).padStart(+ fileDurationWidth,+ " ",+ );+ const testCount = String(file.testCount).padStart(testCountWidth, " ");+ const pluralizedTests = file.testCount === 1 ? "test" : "tests";++ console.log(+ `${rank}. ${duration} ${file.file} (${testCount} ${pluralizedTests})`,+ );+ });++ const retriedTests = completedTests.filter((test) => test.retryCount > 0);++ if (retriedTests.length > 0) {+ const retryRankWidth = String(retriedTests.length).length;++ console.log(`\nRetried tests (${retriedTests.length}):`);+ retriedTests+ .sort((left, right) => right.retryCount - left.retryCount)+ .forEach((test, index) => {+ const rank = String(index + 1).padStart(retryRankWidth, " ");+ const flaky = test.flaky ? " [flaky]" : "";+ const state = test.state === "passed" ? "" : ` [${test.state}]`;++ console.log(+ `${rank}. retries=${test.retryCount} ${test.file} > ${test.name}${state}${flaky}`,+ );+ });+ }+ }+}diff --git a/turbo.json b/turbo.jsonindex 4cd413f43a..269c78d368 100644--- a/turbo.json+++ b/turbo.json@@ -44,9 +44,11 @@"persistent": true,"dependsOn": ["db:generate"]},+ // Prisma generate writes client types into node_modules. Turbo cache hits+ // only replay logs and do not restore those side effects on fresh CI runners."db:generate": {"inputs": ["packages/shared/prisma/schema.prisma"],- "cache": true,+ "cache": false,"dependsOn": ["^db:generate"]},"lint": {@@ -54,7 +56,7 @@"outputs": []},"typecheck": {- "dependsOn": ["db:generate"],+ "dependsOn": ["db:generate", "^build"],"cache": true,"outputs": []},diff --git a/web/next.config.mjs b/web/next.config.mjsindex 06eaf95244..aea6cee31f 100644--- a/web/next.config.mjs+++ b/web/next.config.mjs@@ -49,6 +49,12 @@ const reportToHeader = {const nextConfig = {// Allow building to alternate directory for parallel build checks while dev server runsdistDir: process.env.NEXT_DIST_DIR || ".next",+ typescript: {+ // CI test jobs run `pnpm run typecheck` separately and skip duplicate+ // Next.js type checks to keep test builds fast. Production/Docker builds+ // do not set this flag and still fail on TypeScript errors.+ ignoreBuildErrors: process.env.NEXT_IGNORE_BUILD_ERRORS === "true",+ },// Agent/browser tooling often targets 127.0.0.1 instead of localhost in dev.allowedDevOrigins: ["127.0.0.1"],staticPageGenerationTimeout: 500, // default is 60. Required for build process for amddiff --git a/web/src/__tests__/server/annotation-queues-api.servertest.ts b/web/src/__tests__/server/annotation-queues-api.servertest.tsindex 866313d088..e8077fb4f2 100644--- a/web/src/__tests__/server/annotation-queues-api.servertest.ts+++ b/web/src/__tests__/server/annotation-queues-api.servertest.ts@@ -20,25 +20,26 @@ import {import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import { v4 as uuidv4 } from "uuid";+const TOTAL_TEST_QUEUES = 10; // Create enough queues to test pagination+const TOTAL_TEST_QUEUE_ITEMS = 6; // Create enough queue items to test filtering+describe("Annotation Queues API Endpoints", () => {let auth: string;let projectId: string;- let queueId: string;- let queueItemId: string;- const TOTAL_TEST_QUEUES = 15; // Create enough queues to test pagination- const TOTAL_TEST_QUEUE_ITEMS = 20; // Create enough queue items to test pagination- beforeEach(async () => {- // Create organization, project, and API key for testing- const { auth: newAuth, projectId: newProjectId } =- await createOrgProjectAndApiKey();- auth = newAuth;- projectId = newProjectId;+ const createQueue = (overrides: Partial<{ name: string }> = {}) =>+ prisma.annotationQueue.create({+ data: {+ name: overrides.name ?? "Test Queue 1",+ description: "Test Queue Description 1",+ scoreConfigIds: [],+ projectId,+ },+ });- // Create multiple test annotation queues- const queuePromises = [];- for (let i = 0; i < TOTAL_TEST_QUEUES; i++) {- queuePromises.push(+ const createQueues = async (count = TOTAL_TEST_QUEUES) =>+ Promise.all(+ Array.from({ length: count }, (_, i) =>prisma.annotationQueue.create({data: {name: `Test Queue ${i + 1}`,@@ -47,30 +48,26 @@ describe("Annotation Queues API Endpoints", () => {projectId,},}),- );- }-- const queues = await Promise.all(queuePromises);- queueId = queues[0].id; // Use the first queue for specific tests-- // Create multiple test annotation queue items- const queueItemPromises = [];- for (let i = 0; i < TOTAL_TEST_QUEUE_ITEMS; i++) {- // Distribute items across the first 3 queues to test filtering- const targetQueueId = queues[i % 3].id;-- // Alternate between PENDING and COMPLETED status- const status =- i % 2 === 0- ? AnnotationQueueStatus.PENDING- : AnnotationQueueStatus.COMPLETED;-- // Set completedAt for COMPLETED items- const completedAt =- status === AnnotationQueueStatus.COMPLETED ? new Date() : null;-- queueItemPromises.push(- prisma.annotationQueueItem.create({+ ),+ );++ const createQueueItems = async (queueIds: string[]) =>+ Promise.all(+ Array.from({ length: TOTAL_TEST_QUEUE_ITEMS }, (_, i) => {+ // Distribute items across the provided queues to test filtering+ const targetQueueId = queueIds[i % queueIds.length];++ // Alternate between PENDING and COMPLETED status+ const status =+ i % 2 === 0+ ? AnnotationQueueStatus.PENDING+ : AnnotationQueueStatus.COMPLETED;++ // Set completedAt for COMPLETED items+ const completedAt =+ status === AnnotationQueueStatus.COMPLETED ? new Date() : null;++ return prisma.annotationQueueItem.create({data: {queueId: targetQueueId,objectId: uuidv4(),@@ -79,15 +76,33 @@ describe("Annotation Queues API Endpoints", () => {completedAt,projectId,},- }),- );- }+ });+ }),+ );++ const createScoreConfig = (name = "Test Score Config") =>+ prisma.scoreConfig.create({+ data: {+ name,+ description: "Test Score Config Description",+ projectId,+ dataType: "NUMERIC",+ },+ });- const queueItems = await Promise.all(queueItemPromises);- queueItemId = queueItems[0].id; // Use the first queue item for specific tests+ beforeEach(async () => {+ // Create organization, project, and API key for testing+ const { auth: newAuth, projectId: newProjectId } =+ await createOrgProjectAndApiKey();+ auth = newAuth;+ projectId = newProjectId;});describe("GET /annotation-queues", () => {+ beforeEach(async () => {+ await createQueues();+ });+it("should get all annotation queues", async () => {const response = await makeZodVerifiedAPICall(GetAnnotationQueuesResponse,@@ -128,23 +143,22 @@ describe("Annotation Queues API Endpoints", () => {it("should return different results for different pages", async () => {const limit = 5;- // Get first page- const firstPageResponse = await makeZodVerifiedAPICall(- GetAnnotationQueuesResponse,- "GET",- `/api/public/annotation-queues?page=1&limit=${limit}`,- undefined,- auth,- );-- // Get second page- const secondPageResponse = await makeZodVerifiedAPICall(- GetAnnotationQueuesResponse,- "GET",- `/api/public/annotation-queues?page=2&limit=${limit}`,- undefined,- auth,- );+ const [firstPageResponse, secondPageResponse] = await Promise.all([+ makeZodVerifiedAPICall(+ GetAnnotationQueuesResponse,+ "GET",+ `/api/public/annotation-queues?page=1&limit=${limit}`,+ undefined,+ auth,+ ),+ makeZodVerifiedAPICall(+ GetAnnotationQueuesResponse,+ "GET",+ `/api/public/annotation-queues?page=2&limit=${limit}`,+ undefined,+ auth,+ ),+ ]);expect(firstPageResponse.status).toBe(200);expect(secondPageResponse.status).toBe(200);@@ -169,14 +183,7 @@ describe("Annotation Queues API Endpoints", () => {describe("POST /annotation-queues", () => {it("should create a new annotation queue", async () => {- const scoreConfig = await prisma.scoreConfig.create({- data: {- name: "Test Score Config",- description: "Test Score Config Description",- projectId,- dataType: "NUMERIC",- },- });+ const scoreConfig = await createScoreConfig();const response = await makeZodVerifiedAPICall(CreateAnnotationQueueResponse,@@ -198,14 +205,7 @@ describe("Annotation Queues API Endpoints", () => {});it("should create a queue with description set to null", async () => {- const scoreConfig = await prisma.scoreConfig.create({- data: {- name: "Score Config for Null Desc",- description: "Test",- projectId,- dataType: "NUMERIC",- },- });+ const scoreConfig = await createScoreConfig("Score Config for Null Desc");const response = await makeZodVerifiedAPICall(CreateAnnotationQueueResponse,@@ -224,14 +224,7 @@ describe("Annotation Queues API Endpoints", () => {});it("should create a queue with description omitted", async () => {- const scoreConfig = await prisma.scoreConfig.create({- data: {- name: "Score Config for No Desc",- description: "Test",- projectId,- dataType: "NUMERIC",- },- });+ const scoreConfig = await createScoreConfig("Score Config for No Desc");const response = await makeZodVerifiedAPICall(CreateAnnotationQueueResponse,@@ -249,14 +242,7 @@ describe("Annotation Queues API Endpoints", () => {});it("should return 400 if the queue name already exists", async () => {- await prisma.annotationQueue.create({- data: {- name: "Test Queue",- description: "Test Queue Description",- scoreConfigIds: [],- projectId,- },- });+ await createQueue({ name: "Test Queue" });const response = await makeAPICall("POST",@@ -342,6 +328,13 @@ describe("Annotation Queues API Endpoints", () => {});describe("GET /annotation-queues/:queueId", () => {+ let queueId: string;++ beforeEach(async () => {+ const queue = await createQueue();+ queueId = queue.id;+ });+it("should get a specific annotation queue", async () => {const response = await makeZodVerifiedAPICall(GetAnnotationQueueByIdResponse,@@ -371,6 +364,14 @@ describe("Annotation Queues API Endpoints", () => {});describe("GET /annotation-queues/:queueId/items", () => {+ let queueId: string;++ beforeEach(async () => {+ const queues = await createQueues(3);+ queueId = queues[0].id;+ await createQueueItems(queues.map((queue) => queue.id));+ });+it("should get all items for a specific queue", async () => {const response = await makeZodVerifiedAPICall(GetAnnotationQueueItemsResponse,@@ -412,10 +413,9 @@ describe("Annotation Queues API Endpoints", () => {it("should return different results for different pages of queue items", async () => {// First, create enough items to ensure we have multiple pagesconst itemsToCreate = 15;- const createPromises = [];- for (let i = 0; i < itemsToCreate; i++) {- createPromises.push(+ await Promise.all(+ Array.from({ length: itemsToCreate }, () =>makeZodVerifiedAPICall(CreateAnnotationQueueItemResponse,"POST",@@ -426,30 +426,27 @@ describe("Annotation Queues API Endpoints", () => {},auth,),- );- }-- await Promise.all(createPromises);+ ),+ );const limit = 7;- // Get first page- const firstPageResponse = await makeZodVerifiedAPICall(- GetAnnotationQueueItemsResponse,- "GET",- `/api/public/annotation-queues/${queueId}/items?page=1&limit=${limit}`,- undefined,- auth,- );-- // Get second page- const secondPageResponse = await makeZodVerifiedAPICall(- GetAnnotationQueueItemsResponse,- "GET",- `/api/public/annotation-queues/${queueId}/items?page=2&limit=${limit}`,- undefined,- auth,- );+ const [firstPageResponse, secondPageResponse] = await Promise.all([+ makeZodVerifiedAPICall(+ GetAnnotationQueueItemsResponse,+ "GET",+ `/api/public/annotation-queues/${queueId}/items?page=1&limit=${limit}`,+ undefined,+ auth,+ ),+ makeZodVerifiedAPICall(+ GetAnnotationQueueItemsResponse,+ "GET",+ `/api/public/annotation-queues/${queueId}/items?page=2&limit=${limit}`,+ undefined,+ auth,+ ),+ ]);expect(firstPageResponse.status).toBe(200);expect(secondPageResponse.status).toBe(200);@@ -503,31 +500,35 @@ describe("Annotation Queues API Endpoints", () => {});describe("GET /annotation-queues/:queueId/items/:itemId", () => {- it("should get a specific annotation queue item", async () => {- // First, get an item that belongs to the queue- const itemsResponse = await makeZodVerifiedAPICall(- GetAnnotationQueueItemsResponse,- "GET",- `/api/public/annotation-queues/${queueId}/items?limit=1`,- undefined,- auth,- );-- expect(itemsResponse.status).toBe(200);- expect(itemsResponse.body.data.length).toBeGreaterThan(0);+ let queueId: string;+ let queueItemId: string;- const itemId = itemsResponse.body.data[0].id;+ beforeEach(async () => {+ const queue = await createQueue();+ queueId = queue.id;+ const queueItem = await prisma.annotationQueueItem.create({+ data: {+ queueId,+ objectId: uuidv4(),+ objectType: AnnotationQueueObjectType.TRACE,+ status: AnnotationQueueStatus.PENDING,+ projectId,+ },+ });+ queueItemId = queueItem.id;+ });+ it("should get a specific annotation queue item", async () => {const response = await makeZodVerifiedAPICall(GetAnnotationQueueItemByIdResponse,"GET",- `/api/public/annotation-queues/${queueId}/items/${itemId}`,+ `/api/public/annotation-queues/${queueId}/items/${queueItemId}`,undefined,auth,);expect(response.status).toBe(200);- expect(response.body.id).toBe(itemId);+ expect(response.body.id).toBe(queueItemId);expect(response.body.queueId).toBe(queueId);});@@ -557,6 +558,13 @@ describe("Annotation Queues API Endpoints", () => {});describe("POST /annotation-queues/:queueId/items", () => {+ let queueId: string;++ beforeEach(async () => {+ const queue = await createQueue();+ queueId = queue.id;+ });+it("should create a new annotation queue item", async () => {const objectId = uuidv4();const response = await makeZodVerifiedAPICall(@@ -578,39 +586,38 @@ describe("Annotation Queues API Endpoints", () => {});it("should create queue items with different object types and statuses", async () => {- // Create a queue item with TRACE object typeconst traceObjectId = uuidv4();- const traceResponse = await makeZodVerifiedAPICall(- CreateAnnotationQueueItemResponse,- "POST",- `/api/public/annotation-queues/${queueId}/items`,- {- objectId: traceObjectId,- objectType: AnnotationQueueObjectType.TRACE,- status: AnnotationQueueStatus.COMPLETED,- },- auth,- );+ const observationObjectId = uuidv4();++ const [traceResponse, observationResponse] = await Promise.all([+ makeZodVerifiedAPICall(+ CreateAnnotationQueueItemResponse,+ "POST",+ `/api/public/annotation-queues/${queueId}/items`,+ {+ objectId: traceObjectId,+ objectType: AnnotationQueueObjectType.TRACE,+ status: AnnotationQueueStatus.COMPLETED,+ },+ auth,+ ),+ makeZodVerifiedAPICall(+ CreateAnnotationQueueItemResponse,+ "POST",+ `/api/public/annotation-queues/${queueId}/items`,+ {+ objectId: observationObjectId,+ objectType: AnnotationQueueObjectType.OBSERVATION,+ status: AnnotationQueueStatus.PENDING,+ },+ auth,+ ),+ ]);expect(traceResponse.status).toBe(200);expect(traceResponse.body.objectType).toBe(AnnotationQueueObjectType.TRACE,);-- // Create a queue item with OBSERVATION object type- const observationObjectId = uuidv4();- const observationResponse = await makeZodVerifiedAPICall(- CreateAnnotationQueueItemResponse,- "POST",- `/api/public/annotation-queues/${queueId}/items`,- {- objectId: observationObjectId,- objectType: AnnotationQueueObjectType.OBSERVATION,- status: AnnotationQueueStatus.PENDING,- },- auth,- );-expect(observationResponse.status).toBe(200);expect(observationResponse.body.objectType).toBe(AnnotationQueueObjectType.OBSERVATION,@@ -662,6 +669,13 @@ describe("Annotation Queues API Endpoints", () => {});describe("PATCH /annotation-queues/:queueId/items/:itemId", () => {+ let queueId: string;++ beforeEach(async () => {+ const queue = await createQueue();+ queueId = queue.id;+ });+it("should update an annotation queue item to COMPLETED", async () => {// Create a new item to updateconst createResponse = await makeZodVerifiedAPICall(@@ -745,10 +759,19 @@ describe("Annotation Queues API Endpoints", () => {});it("should return 404 for non-existent queue", async () => {+ const queueItem = await prisma.annotationQueueItem.create({+ data: {+ queueId,+ objectId: uuidv4(),+ objectType: AnnotationQueueObjectType.TRACE,+ status: AnnotationQueueStatus.PENDING,+ projectId,+ },+ });const nonExistentId = uuidv4();const response = await makeAPICall("PATCH",- `/api/public/annotation-queues/${nonExistentId}/items/${queueItemId}`,+ `/api/public/annotation-queues/${nonExistentId}/items/${queueItem.id}`,{status: AnnotationQueueStatus.COMPLETED,},@@ -760,6 +783,13 @@ describe("Annotation Queues API Endpoints", () => {});describe("DELETE /annotation-queues/:queueId/items/:itemId", () => {+ let queueId: string;++ beforeEach(async () => {+ const queue = await createQueue();+ queueId = queue.id;+ });+it("should delete an annotation queue item", async () => {// Create a new item to deleteconst createResponse = await makeZodVerifiedAPICall(@@ -810,10 +840,19 @@ describe("Annotation Queues API Endpoints", () => {});it("should return 404 for non-existent queue", async () => {+ const queueItem = await prisma.annotationQueueItem.create({+ data: {+ queueId,+ objectId: uuidv4(),+ objectType: AnnotationQueueObjectType.TRACE,+ status: AnnotationQueueStatus.PENDING,+ projectId,+ },+ });const nonExistentId = uuidv4();const response = await makeAPICall("DELETE",- `/api/public/annotation-queues/${nonExistentId}/items/${queueItemId}`,+ `/api/public/annotation-queues/${nonExistentId}/items/${queueItem.id}`,undefined,auth,);diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.tsindex 1456b46ea8..cbe626a505 100644--- a/web/src/__tests__/server/api-auth.servertest.ts+++ b/web/src/__tests__/server/api-auth.servertest.ts@@ -4,6 +4,8 @@ import {createOrgProjectAndApiKey,createShaHash,generateKeySet,+ getDisplaySecretKey,+ hashSecretKey,} from "@langfuse/shared/src/server";import { Prisma, type PrismaClient, prisma } from "@langfuse/shared/src/db";import { env } from "@/src/env.mjs";@@ -249,8 +251,21 @@ describe("Authenticate API calls", () => {});it("should fail on wrong api key without new key", async () => {+ const legacySecretKey = ["legacy", "secret", "key"].join("-");+ const legacyPublicKey = `legacy-public-key-${v4()}`;+ await prisma.apiKey.create({+ data: {+ id: v4(),+ projectId: testApiKey.projectId,+ publicKey: legacyPublicKey,+ hashedSecretKey: await hashSecretKey(legacySecretKey),+ displaySecretKey: getDisplaySecretKey(legacySecretKey),+ scope: "PROJECT",+ },+ });+const initialApiKey = await prisma.apiKey.findUnique({- where: { publicKey: testApiKey.publicKey },+ where: { publicKey: legacyPublicKey },});expect(initialApiKey).not.toBeNull();expect(initialApiKey?.fastHashedSecretKey).toBeNull();@@ -258,11 +273,13 @@ describe("Authenticate API calls", () => {const auth = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(getInvalidAuthHeader());+ ).verifyAuthHeaderAndReturnScope(+ createBasicAuthHeader(legacyPublicKey, `${legacySecretKey}-wrong`),+ );expect(auth.validKey).toBe(false);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: testApiKey.publicKey },+ where: { publicKey: legacyPublicKey },});expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).toBeNull();@@ -298,6 +315,23 @@ describe("Authenticate API calls", () => {}, 20_000);it("should create new api key and read from cache", async () => {+ const legacySecretKey = ["legacy", "secret", "key"].join("-");+ const legacyPublicKey = `legacy-public-key-${v4()}`;+ const legacyAuth = createBasicAuthHeader(+ legacyPublicKey,+ legacySecretKey,+ );+ await prisma.apiKey.create({+ data: {+ id: v4(),+ projectId: testApiKey.projectId,+ publicKey: legacyPublicKey,+ hashedSecretKey: await hashSecretKey(legacySecretKey),+ displaySecretKey: getDisplaySecretKey(legacySecretKey),+ scope: "PROJECT",+ },+ });+// update the organization with a cloud configawait prisma.organization.update({where: { id: testApiKey.orgId },@@ -319,11 +353,11 @@ describe("Authenticate API calls", () => {// first auth will generate the fast hashed api keyawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- getValidAuthHeader(),+ legacyAuth,);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: testApiKey.publicKey },+ where: { publicKey: legacyPublicKey },});expect(apiKey).not.toBeNull();@@ -337,7 +371,7 @@ describe("Authenticate API calls", () => {// second will add the key to redisawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- getValidAuthHeader(),+ legacyAuth,);const cachedKey2 = await getRedisValue(@@ -640,28 +674,25 @@ describe("Authenticate API calls", () => {expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).not.toBeNull();- const ttl = await getRedisTtl(- redis,- `api-key:${apiKey?.fastHashedSecretKey}`,- );+ const redisKey = `api-key:${apiKey?.fastHashedSecretKey}`;+ const ttl = await getRedisTtl(redis, redisKey);expect(ttl).toBeGreaterThan(env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS - 2);- // wait for 5 seconds- await new Promise((resolve) => setTimeout(resolve, 5000));+ await redis.expire(redisKey, 10);+ const shortenedTtl = await getRedisTtl(redis, redisKey);+ expect(shortenedTtl).toBeGreaterThan(0);+ expect(shortenedTtl).toBeLessThan(env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS);await new ApiAuthService(mockPrisma as unknown as PrismaClient,redis,).verifyAuthHeaderAndReturnScope(getValidAuthHeader());- const ttl2 = await getRedisTtl(- redis,- `api-key:${apiKey?.fastHashedSecretKey}`,- );+ const ttl2 = await getRedisTtl(redis, redisKey);expect(ttl2).toBeGreaterThan(env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS - 2);- }, 10000);+ });it("should delete API keys from cache and db", async () => {// first auth will generate the fast hashed api keydiff --git a/web/src/__tests__/server/comments-api.servertest.ts b/web/src/__tests__/server/comments-api.servertest.tsindex 32cf22ab6c..3a229adda1 100644--- a/web/src/__tests__/server/comments-api.servertest.ts+++ b/web/src/__tests__/server/comments-api.servertest.ts@@ -150,7 +150,9 @@ describe("GET /api/public/comments API Endpoint", () => {await createObservationsCh([observation]);- await prisma.comment.deleteMany();+ await prisma.comment.deleteMany({+ where: { projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },+ });await prisma.comment.createMany({data: [{diff --git a/web/src/__tests__/server/datasets-schema-validation.servertest.ts b/web/src/__tests__/server/datasets-schema-validation.servertest.tsindex c68cfd3f29..8a18ca5ca9 100644--- a/web/src/__tests__/server/datasets-schema-validation.servertest.ts+++ b/web/src/__tests__/server/datasets-schema-validation.servertest.ts@@ -1,3 +1,4 @@+import { randomUUID } from "node:crypto";import { prisma } from "@langfuse/shared/src/db";import {makeAPICall,@@ -347,24 +348,60 @@ describe("Unit Tests - DatasetItemValidator", () => {// ============================================================================describe("Public API - Dataset Schema Enforcement", () => {+ const uniqueDatasetName = (name: string) => `${name}-${randomUUID()}`;+ const invalidInputDatasetName = "invalid-input-schema-fixture";+ const invalidOutputDatasetName = "invalid-output-schema-fixture";+ const allowsNullDatasetName = "allows-null-schema-fixture";+let auth: string;let projectId: string;- beforeEach(async () => {+ beforeAll(async () => {const { auth: newAuth, projectId: newProjectId } =await createOrgProjectAndApiKey();auth = newAuth;projectId = newProjectId;++ await Promise.all([+ makeAPICall(+ "POST",+ "/api/public/v2/datasets",+ {+ name: invalidInputDatasetName,+ inputSchema: TEST_SCHEMAS.simpleText,+ },+ auth,+ ),+ makeAPICall(+ "POST",+ "/api/public/v2/datasets",+ {+ name: invalidOutputDatasetName,+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,+ },+ auth,+ ),+ makeAPICall(+ "POST",+ "/api/public/v2/datasets",+ {+ name: allowsNullDatasetName,+ inputSchema: TEST_SCHEMAS.allowsNull,+ },+ auth,+ ),+ ]);});describe("POST /api/public/v2/datasets - Schema Creation", () => {it("should create dataset with input schema", async () => {+ const testDatasetName = uniqueDatasetName("test-dataset");const res = await makeZodVerifiedAPICall(PostDatasetsV2Response,"POST","/api/public/v2/datasets",{- name: "test-dataset",+ name: testDatasetName,description: "Test dataset",inputSchema: TEST_SCHEMAS.simpleText,},@@ -372,18 +409,19 @@ describe("Public API - Dataset Schema Enforcement", () => {);expect(res.status).toBe(200);- expect(res.body.name).toBe("test-dataset");+ expect(res.body.name).toBe(testDatasetName);expect(res.body.inputSchema).toEqual(TEST_SCHEMAS.simpleText);expect(res.body.expectedOutputSchema).toBeNull();});it("should create dataset with expectedOutput schema", async () => {+ const testDataset2DatasetName = uniqueDatasetName("test-dataset-2");const res = await makeZodVerifiedAPICall(PostDatasetsV2Response,"POST","/api/public/v2/datasets",{- name: "test-dataset-2",+ name: testDataset2DatasetName,expectedOutputSchema: TEST_SCHEMAS.requiresObject,},auth,@@ -397,12 +435,13 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should create dataset with both schemas", async () => {+ const testDataset3DatasetName = uniqueDatasetName("test-dataset-3");const res = await makeZodVerifiedAPICall(PostDatasetsV2Response,"POST","/api/public/v2/datasets",{- name: "test-dataset-3",+ name: testDataset3DatasetName,inputSchema: TEST_SCHEMAS.chatMessages,expectedOutputSchema: TEST_SCHEMAS.simpleText,},@@ -415,12 +454,13 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should create dataset without schemas", async () => {+ const testDataset4DatasetName = uniqueDatasetName("test-dataset-4");const res = await makeZodVerifiedAPICall(PostDatasetsV2Response,"POST","/api/public/v2/datasets",{- name: "test-dataset-4",+ name: testDataset4DatasetName,},auth,);@@ -431,11 +471,14 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should reject invalid JSON schema format", async () => {+ const testDatasetInvalidDatasetName = uniqueDatasetName(+ "test-dataset-invalid",+ );const res = await makeAPICall("POST","/api/public/v2/datasets",{- name: "test-dataset-invalid",+ name: testDatasetInvalidDatasetName,inputSchema: { type: "invalid-type" },},auth,@@ -447,12 +490,12 @@ describe("Public API - Dataset Schema Enforcement", () => {describe("POST /api/public/v2/datasets - UPSERT with Validation", () => {it("should add schema to existing dataset via UPSERT", async () => {+ const upsertDatasetName = uniqueDatasetName("upsert-dataset");// Create dataset without schema- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ await makeAPICall("POST","/api/public/v2/datasets",- { name: "upsert-dataset" },+ { name: upsertDatasetName },auth,);@@ -462,7 +505,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/v2/datasets",{- name: "upsert-dataset",+ name: upsertDatasetName,inputSchema: TEST_SCHEMAS.simpleText,},auth,@@ -473,12 +516,12 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should block UPSERT if existing items fail validation", async () => {+ const upsertFailDatasetName = uniqueDatasetName("upsert-fail");// Create dataset without schema- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ await makeAPICall("POST","/api/public/v2/datasets",- { name: "upsert-fail" },+ { name: upsertFailDatasetName },auth,);@@ -487,7 +530,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "upsert-fail",+ datasetName: upsertFailDatasetName,input: { text: 123 }, // Invalid for simpleText schema},auth,@@ -498,25 +541,25 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/v2/datasets",{- name: "upsert-fail",+ name: upsertFailDatasetName,inputSchema: TEST_SCHEMAS.simpleText,},auth,);expect(res.status).toBe(400);- expect(res.body.message).toContain("validation failed");+ expect((res.body as any).message).toContain("validation failed");});});describe("GET /api/public/v2/datasets - Schema Fields", () => {it("should return schemas in dataset list", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ const getTestDatasetName = uniqueDatasetName("get-test");+ await makeAPICall("POST","/api/public/v2/datasets",{- name: "get-test",+ name: getTestDatasetName,inputSchema: TEST_SCHEMAS.simpleText,},auth,@@ -524,35 +567,40 @@ describe("Public API - Dataset Schema Enforcement", () => {const res = await makeAPICall("GET",- "/api/public/v2/datasets?page=1&limit=10",+ "/api/public/v2/datasets?page=1&limit=100",undefined,auth,);expect(res.status).toBe(200);- expect(res.body.data[0].inputSchema).toEqual(TEST_SCHEMAS.simpleText);+ const dataset = (res.body as any).data.find(+ (d: any) => d.name === getTestDatasetName,+ );+ expect(dataset).toBeDefined();+ expect(dataset.inputSchema).toEqual(TEST_SCHEMAS.simpleText);});it("should return null schemas when not set", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ const noSchemaTestDatasetName = uniqueDatasetName("no-schema-test");+ await makeAPICall("POST","/api/public/v2/datasets",- { name: "no-schema-test" },+ { name: noSchemaTestDatasetName },auth,);const res = await makeAPICall("GET",- "/api/public/v2/datasets?page=1&limit=10",+ "/api/public/v2/datasets?page=1&limit=100",undefined,auth,);expect(res.status).toBe(200);- const dataset = res.body.data.find(- (d: any) => d.name === "no-schema-test",+ const dataset = (res.body as any).data.find(+ (d: any) => d.name === noSchemaTestDatasetName,);+ expect(dataset).toBeDefined();expect(dataset.inputSchema).toBeNull();expect(dataset.expectedOutputSchema).toBeNull();});@@ -560,12 +608,12 @@ describe("Public API - Dataset Schema Enforcement", () => {describe("POST /api/public/dataset-items - Schema Validation", () => {it("should create item with valid input (schema enforced)", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ const validInputTestDatasetName = uniqueDatasetName("valid-input-test");+ await makeAPICall("POST","/api/public/v2/datasets",{- name: "valid-input-test",+ name: validInputTestDatasetName,inputSchema: TEST_SCHEMAS.simpleText,},auth,@@ -576,7 +624,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "valid-input-test",+ datasetName: validInputTestDatasetName,input: { text: "hello" },},auth,@@ -587,12 +635,12 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should create item with valid expectedOutput (schema enforced)", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ const validOutputTestDatasetName = uniqueDatasetName("valid-output-test");+ await makeAPICall("POST","/api/public/v2/datasets",{- name: "valid-output-test",+ name: validOutputTestDatasetName,expectedOutputSchema: TEST_SCHEMAS.requiresObject,},auth,@@ -603,7 +651,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "valid-output-test",+ datasetName: validOutputTestDatasetName,input: "Hello",expectedOutput: { value: 42 },},@@ -615,11 +663,11 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should create item without schemas set", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ const noValidationDatasetName = uniqueDatasetName("no-validation");+ await makeAPICall("POST","/api/public/v2/datasets",- { name: "no-validation" },+ { name: noValidationDatasetName },auth,);@@ -628,7 +676,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "no-validation",+ datasetName: noValidationDatasetName,input: "anything goes",expectedOutput: 123,},@@ -639,22 +687,11 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should not create item with null even when schema allows null", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,- "POST",- "/api/public/v2/datasets",- {- name: "allows-null",- inputSchema: TEST_SCHEMAS.allowsNull,- },- auth,- );-const res = await makeAPICall("POST","/api/public/dataset-items",{- datasetName: "allows-null",+ datasetName: allowsNullDatasetName,input: null,},auth,@@ -664,48 +701,26 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should reject item with invalid input", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,- "POST",- "/api/public/v2/datasets",- {- name: "reject-invalid",- inputSchema: TEST_SCHEMAS.simpleText,- },- auth,- );-const res = await makeAPICall("POST","/api/public/dataset-items",{- datasetName: "reject-invalid",+ datasetName: invalidInputDatasetName,input: { text: 123 }, // Invalid type},auth,);expect(res.status).toBe(400);- expect(res.body.message).toContain("validation failed");+ expect((res.body as any).message).toContain("validation failed");});it("should reject item with invalid expectedOutput", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,- "POST",- "/api/public/v2/datasets",- {- name: "reject-output",- expectedOutputSchema: TEST_SCHEMAS.requiresObject,- },- auth,- );-const res = await makeAPICall("POST","/api/public/dataset-items",{- datasetName: "reject-output",+ datasetName: invalidOutputDatasetName,expectedOutput: "not an object",},auth,@@ -715,48 +730,26 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should reject item with null when schema doesn't allow null", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,- "POST",- "/api/public/v2/datasets",- {- name: "no-null",- inputSchema: TEST_SCHEMAS.simpleText, // Requires object- },- auth,- );-const res = await makeAPICall("POST","/api/public/dataset-items",{- datasetName: "no-null",+ datasetName: invalidInputDatasetName,input: null,},auth,);expect(res.status).toBe(400);- expect(res.body.message).toContain("validation failed");+ expect((res.body as any).message).toContain("validation failed");});it("should reject item with missing required fields", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,- "POST",- "/api/public/v2/datasets",- {- name: "missing-fields",- inputSchema: TEST_SCHEMAS.simpleText,- },- auth,- );-const res = await makeAPICall("POST","/api/public/dataset-items",{- datasetName: "missing-fields",+ datasetName: invalidInputDatasetName,input: {}, // Missing required 'text' field},auth,@@ -766,12 +759,12 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should validate complex nested structures", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ const nestedTestDatasetName = uniqueDatasetName("nested-test");+ await makeAPICall("POST","/api/public/v2/datasets",{- name: "nested-test",+ name: nestedTestDatasetName,inputSchema: TEST_SCHEMAS.chatMessages,},auth,@@ -782,7 +775,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "nested-test",+ datasetName: nestedTestDatasetName,input: {messages: [{ role: "user", content: "hello" },@@ -800,7 +793,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "nested-test",+ datasetName: nestedTestDatasetName,input: {messages: [{ role: "invalid-role", content: "test" }],},@@ -814,22 +807,11 @@ describe("Public API - Dataset Schema Enforcement", () => {describe("POST /api/public/dataset-items - UPSERT Validation", () => {it("should validate on UPSERT create", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,- "POST",- "/api/public/v2/datasets",- {- name: "upsert-create",- inputSchema: TEST_SCHEMAS.simpleText,- },- auth,- );-const res = await makeAPICall("POST","/api/public/dataset-items",{- datasetName: "upsert-create",+ datasetName: invalidInputDatasetName,id: "custom-id-1",input: { text: 123 }, // Invalid},@@ -840,24 +822,23 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should validate on UPSERT update", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ const upsertUpdateDatasetName = uniqueDatasetName("upsert-update");+ await makeAPICall("POST","/api/public/v2/datasets",{- name: "upsert-update",+ name: upsertUpdateDatasetName,inputSchema: TEST_SCHEMAS.simpleText,},auth,);// Create valid item- await makeZodVerifiedAPICall(- PostDatasetItemsV1Response,+ await makeAPICall("POST","/api/public/dataset-items",{- datasetName: "upsert-update",+ datasetName: upsertUpdateDatasetName,id: "update-id",input: { text: "valid" },},@@ -869,7 +850,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "upsert-update",+ datasetName: upsertUpdateDatasetName,id: "update-id",input: { text: 999 }, // Invalid},@@ -882,82 +863,84 @@ describe("Public API - Dataset Schema Enforcement", () => {describe("Dataset Schema Addition - Existing Items Validation", () => {it("should block schema addition if existing items are invalid", async () => {+ const existingInvalidDatasetName = uniqueDatasetName("existing-invalid");// Create dataset without schema- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ await makeAPICall("POST","/api/public/v2/datasets",- { name: "existing-invalid" },+ { name: existingInvalidDatasetName },auth,);// Create items with data that won't match future schema- await makeAPICall(- "POST",- "/api/public/dataset-items",- {- datasetName: "existing-invalid",- input: { text: 123 }, // Will be invalid for simpleText schema- },- auth,- );-- await makeAPICall(- "POST",- "/api/public/dataset-items",- {- datasetName: "existing-invalid",- input: { text: 456 },- },- auth,- );+ await Promise.all([+ makeAPICall(+ "POST",+ "/api/public/dataset-items",+ {+ datasetName: existingInvalidDatasetName,+ input: { text: 123 }, // Will be invalid for simpleText schema+ },+ auth,+ ),+ makeAPICall(+ "POST",+ "/api/public/dataset-items",+ {+ datasetName: existingInvalidDatasetName,+ input: { text: 456 },+ },+ auth,+ ),+ ]);// Try to add schema - should fail because items are invalidconst res = await makeAPICall("POST","/api/public/v2/datasets",{- name: "existing-invalid",+ name: existingInvalidDatasetName,inputSchema: TEST_SCHEMAS.simpleText,},auth,);expect(res.status).toBe(400);- expect(res.body.message).toContain("validation failed");- expect(res.body.message).toContain("2 item(s)"); // Both items failed+ expect((res.body as any).message).toContain("validation failed");+ expect((res.body as any).message).toContain("2 item(s)"); // Both items failed});it("should allow schema addition if all existing items are valid", async () => {+ const existingValidDatasetName = uniqueDatasetName("existing-valid");// Create dataset- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ await makeAPICall("POST","/api/public/v2/datasets",- { name: "existing-valid" },+ { name: existingValidDatasetName },auth,);// Create valid items- await makeAPICall(- "POST",- "/api/public/dataset-items",- {- datasetName: "existing-valid",- input: { text: "hello" },- },- auth,- );-- await makeAPICall(- "POST",- "/api/public/dataset-items",- {- datasetName: "existing-valid",- input: { text: "world" },- },- auth,- );+ await Promise.all([+ makeAPICall(+ "POST",+ "/api/public/dataset-items",+ {+ datasetName: existingValidDatasetName,+ input: { text: "hello" },+ },+ auth,+ ),+ makeAPICall(+ "POST",+ "/api/public/dataset-items",+ {+ datasetName: existingValidDatasetName,+ input: { text: "world" },+ },+ auth,+ ),+ ]);// Add schema - should succeedconst res = await makeZodVerifiedAPICall(@@ -965,7 +948,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/v2/datasets",{- name: "existing-valid",+ name: existingValidDatasetName,inputSchema: TEST_SCHEMAS.simpleText,},auth,@@ -976,12 +959,12 @@ describe("Public API - Dataset Schema Enforcement", () => {});it("should fail when existing items have null and schema doesn't allow null", async () => {+ const nullItemsDatasetName = uniqueDatasetName("null-items");// Create dataset- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ await makeAPICall("POST","/api/public/v2/datasets",- { name: "null-items" },+ { name: nullItemsDatasetName },auth,);@@ -990,7 +973,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "null-items",+ datasetName: nullItemsDatasetName,input: "hello",expectedOutput: null,},@@ -1002,7 +985,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/v2/datasets",{- name: "null-items",+ name: nullItemsDatasetName,expectedOutputSchema: TEST_SCHEMAS.simpleText, // Requires object},auth,@@ -1014,13 +997,14 @@ describe("Public API - Dataset Schema Enforcement", () => {describe("End-to-End Workflow", () => {it("should enforce schema across full workflow", async () => {+ const e2eWorkflowDatasetName = uniqueDatasetName("e2e-workflow");// 1. Create dataset with schemaconst datasetRes = await makeZodVerifiedAPICall(PostDatasetsV2Response,"POST","/api/public/v2/datasets",{- name: "e2e-workflow",+ name: e2eWorkflowDatasetName,inputSchema: TEST_SCHEMAS.simpleText,expectedOutputSchema: TEST_SCHEMAS.requiresObject,},@@ -1034,7 +1018,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "e2e-workflow",+ datasetName: e2eWorkflowDatasetName,input: { text: "valid input" },expectedOutput: { value: 100 },},@@ -1047,7 +1031,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "e2e-workflow",+ datasetName: e2eWorkflowDatasetName,input: { text: 123 }, // InvalidexpectedOutput: { value: 50 },},@@ -1057,7 +1041,7 @@ describe("Public API - Dataset Schema Enforcement", () => {// 4. Verify only valid item was createdconst dataset = await prisma.dataset.findFirst({- where: { name: "e2e-workflow", projectId },+ where: { name: e2eWorkflowDatasetName, projectId },});if (!dataset) {throw new Error("Dataset not found");@@ -1074,7 +1058,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/v2/datasets",{- name: "e2e-workflow",+ name: e2eWorkflowDatasetName,inputSchema: TEST_SCHEMAS.chatMessages, // Change schema},auth,@@ -1088,7 +1072,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/v2/datasets",{- name: "e2e-workflow",+ name: e2eWorkflowDatasetName,inputSchema: null,expectedOutputSchema: null,},@@ -1101,12 +1085,12 @@ describe("Public API - Dataset Schema Enforcement", () => {describe("Error Response Format", () => {it("should return detailed validation errors", async () => {- await makeZodVerifiedAPICall(- PostDatasetsV2Response,+ const errorFormatDatasetName = uniqueDatasetName("error-format");+ await makeAPICall("POST","/api/public/v2/datasets",{- name: "error-format",+ name: errorFormatDatasetName,inputSchema: TEST_SCHEMAS.chatMessages,},auth,@@ -1116,7 +1100,7 @@ describe("Public API - Dataset Schema Enforcement", () => {"POST","/api/public/dataset-items",{- datasetName: "error-format",+ datasetName: errorFormatDatasetName,input: {messages: [{ role: "bad-role", content: "test" }],},@@ -1125,9 +1109,9 @@ describe("Public API - Dataset Schema Enforcement", () => {);expect(res.status).toBe(400);- expect(res.body.message).toBeDefined();+ expect((res.body as any).message).toBeDefined();// Check that error details are included- const errorMessage = res.body.message;+ const errorMessage = (res.body as any).message;expect(typeof errorMessage).toBe("string");});});diff --git a/web/src/__tests__/server/ingestion-api.servertest.ts b/web/src/__tests__/server/ingestion-api.servertest.tsindex 871ce9dd64..696fa28958 100644--- a/web/src/__tests__/server/ingestion-api.servertest.ts+++ b/web/src/__tests__/server/ingestion-api.servertest.ts@@ -375,18 +375,7 @@ describe("/api/public/ingestion API Endpoint", () => {"should create observations via the ingestion API (%s)",async (_name: string, type: string, entity: any) => {const response = await postIngestion({- batch: [- {- id: randomUUID(),- type: "trace-create",- timestamp: new Date().toISOString(),- body: {- id: entity.traceId,- timestamp: new Date().toISOString(),- },- },- entity,- ],+ batch: [entity],});expect(response.status).toBe(207);diff --git a/web/src/__tests__/server/llm-connections-api.servertest.ts b/web/src/__tests__/server/llm-connections-api.servertest.tsindex 68d2d93f0f..8590f912dd 100644--- a/web/src/__tests__/server/llm-connections-api.servertest.ts+++ b/web/src/__tests__/server/llm-connections-api.servertest.ts@@ -16,6 +16,26 @@ import { encrypt } from "@langfuse/shared/encryption";const generateUniqueProvider = (baseName: string) =>`${baseName}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;+const BEDROCK_AWS_CREDENTIALS = {+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+};+const BEDROCK_API_KEY_CREDENTIALS = { apiKey: "bedrock-api-key-1234" };+const BEDROCK_REGION_CONFIG = { region: "us-east-1" };+const VERTEX_AI_CREDENTIALS = {+ type: "service_account",+ project_id: "test-project",+ private_key_id: "key123",+ private_key: "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----",+ client_email: "[email protected]",+ client_id: "123456789",+ auth_uri: "https://accounts.google.com/o/oauth2/auth",+ token_uri: "https://oauth2.googleapis.com/token",+ auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",+ client_x509_cert_url:+ "https://www.googleapis.com/robot/v1/metadata/x509/test",+};+describe("/api/public/llm-connections API Endpoints", () => {let auth: string;let projectId: string;@@ -211,22 +231,22 @@ describe("/api/public/llm-connections API Endpoints", () => {});it("should return 400 for invalid query parameters", async () => {- // Test negative page- const negativePageResponse = await makeAPICall(- "GET",- "/api/public/llm-connections?page=-1&limit=10",- undefined,- auth,- );- expect(negativePageResponse.status).toBe(400);+ const [negativePageResponse, negativeLimitResponse] = await Promise.all([+ makeAPICall(+ "GET",+ "/api/public/llm-connections?page=-1&limit=10",+ undefined,+ auth,+ ),+ makeAPICall(+ "GET",+ "/api/public/llm-connections?page=1&limit=-1",+ undefined,+ auth,+ ),+ ]);- // Test negative limit- const negativeLimitResponse = await makeAPICall(- "GET",- "/api/public/llm-connections?page=1&limit=-1",- undefined,- auth,- );+ expect(negativePageResponse.status).toBe(400);expect(negativeLimitResponse.status).toBe(400);});@@ -436,82 +456,71 @@ describe("/api/public/llm-connections API Endpoints", () => {});it("should return 400 for invalid request body", async () => {- // Test empty provider- const emptyProviderResponse = await makeAPICall(- "PUT",- "/api/public/llm-connections",- {- provider: "",- adapter: LLMAdapter.OpenAI,- secretKey: "sk-test",- },- auth,- );- expect(emptyProviderResponse.status).toBe(400);-- // Test missing provider- const missingProviderResponse = await makeAPICall(- "PUT",- "/api/public/llm-connections",- {- adapter: LLMAdapter.OpenAI,- secretKey: "sk-test",- },- auth,- );- expect(missingProviderResponse.status).toBe(400);-- // Test missing adapter- const missingAdapterResponse = await makeAPICall(- "PUT",- "/api/public/llm-connections",- {- provider: generateUniqueProvider("test-provider-missing-adapter"),- secretKey: "sk-test",- },- auth,- );- expect(missingAdapterResponse.status).toBe(400);-- // Test empty secretKey- const emptySecretResponse = await makeAPICall(- "PUT",- "/api/public/llm-connections",- {- provider: generateUniqueProvider("test-provider-empty-secret"),- adapter: LLMAdapter.OpenAI,- secretKey: "",- },- auth,- );- expect(emptySecretResponse.status).toBe(400);-- // Test invalid baseURL- const invalidUrlResponse = await makeAPICall(- "PUT",- "/api/public/llm-connections",- {- provider: generateUniqueProvider("test-provider-invalid-url"),- adapter: LLMAdapter.OpenAI,- secretKey: "sk-test",- baseURL: "not-a-valid-url",- },- auth,- );- expect(invalidUrlResponse.status).toBe(400);+ const responses = await Promise.all([+ makeAPICall(+ "PUT",+ "/api/public/llm-connections",+ {+ provider: "",+ adapter: LLMAdapter.OpenAI,+ secretKey: "sk-test",+ },+ auth,+ ),+ makeAPICall(+ "PUT",+ "/api/public/llm-connections",+ {+ adapter: LLMAdapter.OpenAI,+ secretKey: "sk-test",+ },+ auth,+ ),+ makeAPICall(+ "PUT",+ "/api/public/llm-connections",+ {+ provider: generateUniqueProvider("test-provider-missing-adapter"),+ secretKey: "sk-test",+ },+ auth,+ ),+ makeAPICall(+ "PUT",+ "/api/public/llm-connections",+ {+ provider: generateUniqueProvider("test-provider-empty-secret"),+ adapter: LLMAdapter.OpenAI,+ secretKey: "",+ },+ auth,+ ),+ makeAPICall(+ "PUT",+ "/api/public/llm-connections",+ {+ provider: generateUniqueProvider("test-provider-invalid-url"),+ adapter: LLMAdapter.OpenAI,+ secretKey: "sk-test",+ baseURL: "not-a-valid-url",+ },+ auth,+ ),+ makeAPICall(+ "PUT",+ "/api/public/llm-connections",+ {+ provider: generateUniqueProvider("test-provider-invalid-adapter"),+ adapter: "invalid-adapter",+ secretKey: "sk-test",+ },+ auth,+ ),+ ]);- // Test invalid adapter enum- const invalidAdapterResponse = await makeAPICall(- "PUT",- "/api/public/llm-connections",- {- provider: generateUniqueProvider("test-provider-invalid-adapter"),- adapter: "invalid-adapter",- secretKey: "sk-test",- },- auth,- );- expect(invalidAdapterResponse.status).toBe(400);+ for (const response of responses) {+ expect(response.status).toBe(400);+ }});it("should handle all LLM adapter types", async () => {@@ -535,20 +544,24 @@ describe("/api/public/llm-connections API Endpoints", () => {},];- for (const { adapter, provider } of adaptersWithoutConfig) {- const response = await makeZodVerifiedAPICall(- PutLlmConnectionV1Response,- "PUT",- "/api/public/llm-connections",- {- provider,- adapter,- secretKey: `sk-${provider}-test`,- },- auth,- 201,- );+ const adapterResponses = await Promise.all(+ adaptersWithoutConfig.map(({ adapter, provider }) =>+ makeZodVerifiedAPICall(+ PutLlmConnectionV1Response,+ "PUT",+ "/api/public/llm-connections",+ {+ provider,+ adapter,+ secretKey: `sk-${provider}-test`,+ },+ auth,+ 201,+ ).then((response) => ({ adapter, provider, response })),+ ),+ );+ for (const { adapter, provider, response } of adapterResponses) {expect(response.status).toBe(201);expect(response.body.adapter).toBe(adapter);expect(response.body.provider).toBe(provider);@@ -563,11 +576,8 @@ describe("/api/public/llm-connections API Endpoints", () => {{provider: generateUniqueProvider("test-bedrock"),adapter: LLMAdapter.Bedrock,- secretKey: JSON.stringify({- accessKeyId: "AKIAIOSFODNN7EXAMPLE",- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",- }),- config: { region: "us-east-1" },+ secretKey: JSON.stringify(BEDROCK_AWS_CREDENTIALS),+ config: BEDROCK_REGION_CONFIG,},auth,201,@@ -583,8 +593,8 @@ describe("/api/public/llm-connections API Endpoints", () => {{provider: generateUniqueProvider("test-bedrock-api-key"),adapter: LLMAdapter.Bedrock,- secretKey: JSON.stringify({ apiKey: "bedrock-api-key-1234" }),- config: { region: "us-east-1" },+ secretKey: JSON.stringify(BEDROCK_API_KEY_CREDENTIALS),+ config: BEDROCK_REGION_CONFIG,},auth,201,@@ -604,21 +614,7 @@ describe("/api/public/llm-connections API Endpoints", () => {{provider: generateUniqueProvider("test-vertex"),adapter: LLMAdapter.VertexAI,- secretKey: JSON.stringify({- type: "service_account",- project_id: "test-project",- private_key_id: "key123",- private_key:- "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----",- client_email: "[email protected]",- client_id: "123456789",- auth_uri: "https://accounts.google.com/o/oauth2/auth",- token_uri: "https://oauth2.googleapis.com/token",- auth_provider_x509_cert_url:- "https://www.googleapis.com/oauth2/v1/certs",- client_x509_cert_url:- "https://www.googleapis.com/robot/v1/metadata/x509/test",- }),+ secretKey: JSON.stringify(VERTEX_AI_CREDENTIALS),},auth,201,@@ -811,20 +807,24 @@ describe("/api/public/llm-connections API Endpoints", () => {generateUniqueProvider("ProviderWithCaps"),];- for (const provider of specialProviders) {- const response = await makeZodVerifiedAPICall(- PutLlmConnectionV1Response,- "PUT",- "/api/public/llm-connections",- {- provider,- adapter: LLMAdapter.OpenAI,- secretKey: `sk-${provider}-test`,- },- auth,- 201,- );+ const responses = await Promise.all(+ specialProviders.map((provider) =>+ makeZodVerifiedAPICall(+ PutLlmConnectionV1Response,+ "PUT",+ "/api/public/llm-connections",+ {+ provider,+ adapter: LLMAdapter.OpenAI,+ secretKey: `sk-${provider}-test`,+ },+ auth,+ 201,+ ).then((response) => ({ provider, response })),+ ),+ );+ for (const { provider, response } of responses) {expect(response.status).toBe(201);expect(response.body.provider).toBe(provider);}@@ -889,10 +889,7 @@ describe("/api/public/llm-connections API Endpoints", () => {const createData = {provider: generateUniqueProvider("bedrock-config-test"),adapter: LLMAdapter.Bedrock,- secretKey: JSON.stringify({- accessKeyId: "AKIAIOSFODNN7EXAMPLE",- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",- }),+ secretKey: JSON.stringify(BEDROCK_AWS_CREDENTIALS),config: {region: "us-east-1",},@@ -962,10 +959,7 @@ describe("/api/public/llm-connections API Endpoints", () => {const createData = {provider: generateUniqueProvider("bedrock-no-config"),adapter: LLMAdapter.Bedrock,- secretKey: JSON.stringify({- accessKeyId: "AKIAIOSFODNN7EXAMPLE",- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",- }),+ secretKey: JSON.stringify(BEDROCK_AWS_CREDENTIALS),// No config provided};@@ -986,10 +980,7 @@ describe("/api/public/llm-connections API Endpoints", () => {const createData = {provider: generateUniqueProvider("bedrock-bad-config"),adapter: LLMAdapter.Bedrock,- secretKey: JSON.stringify({- accessKeyId: "AKIAIOSFODNN7EXAMPLE",- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",- }),+ secretKey: JSON.stringify(BEDROCK_AWS_CREDENTIALS),config: {location: "us-central1", // Wrong key - should be 'region'},@@ -1013,7 +1004,7 @@ describe("/api/public/llm-connections API Endpoints", () => {provider: generateUniqueProvider("bedrock-default-creds"),adapter: LLMAdapter.Bedrock,secretKey: "__BEDROCK_DEFAULT_CREDENTIALS__",- config: { region: "us-east-1" },+ config: BEDROCK_REGION_CONFIG,};const response = await makeAPICall(@@ -1034,7 +1025,7 @@ describe("/api/public/llm-connections API Endpoints", () => {provider: generateUniqueProvider("bedrock-invalid-creds"),adapter: LLMAdapter.Bedrock,secretKey: JSON.stringify({ unknownField: "value" }),- config: { region: "us-east-1" },+ config: BEDROCK_REGION_CONFIG,};const response = await makeAPICall(@@ -1054,21 +1045,7 @@ describe("/api/public/llm-connections API Endpoints", () => {const createData = {provider: generateUniqueProvider("vertexai-config-test"),adapter: LLMAdapter.VertexAI,- secretKey: JSON.stringify({- type: "service_account",- project_id: "test-project",- private_key_id: "key123",- private_key:- "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----",- client_email: "[email protected]",- client_id: "123456789",- auth_uri: "https://accounts.google.com/o/oauth2/auth",- token_uri: "https://oauth2.googleapis.com/token",- auth_provider_x509_cert_url:- "https://www.googleapis.com/oauth2/v1/certs",- client_x509_cert_url:- "https://www.googleapis.com/robot/v1/metadata/x509/test",- }),+ secretKey: JSON.stringify(VERTEX_AI_CREDENTIALS),config: {location: "us-central1",},@@ -1091,21 +1068,7 @@ describe("/api/public/llm-connections API Endpoints", () => {const createData = {provider: generateUniqueProvider("vertexai-no-config"),adapter: LLMAdapter.VertexAI,- secretKey: JSON.stringify({- type: "service_account",- project_id: "test-project",- private_key_id: "key123",- private_key:- "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----",- client_email: "[email protected]",- client_id: "123456789",- auth_uri: "https://accounts.google.com/o/oauth2/auth",- token_uri: "https://oauth2.googleapis.com/token",- auth_provider_x509_cert_url:- "https://www.googleapis.com/oauth2/v1/certs",- client_x509_cert_url:- "https://www.googleapis.com/robot/v1/metadata/x509/test",- }),+ secretKey: JSON.stringify(VERTEX_AI_CREDENTIALS),// No config - allowed for VertexAI};@@ -1156,11 +1119,8 @@ describe("/api/public/llm-connections API Endpoints", () => {{provider,adapter: LLMAdapter.Bedrock,- secretKey: JSON.stringify({- accessKeyId: "AKIAIOSFODNN7EXAMPLE",- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",- }),- config: { region: "us-east-1" },+ secretKey: JSON.stringify(BEDROCK_AWS_CREDENTIALS),+ config: BEDROCK_REGION_CONFIG,},auth,201,@@ -1174,10 +1134,7 @@ describe("/api/public/llm-connections API Endpoints", () => {{provider,adapter: LLMAdapter.Bedrock,- secretKey: JSON.stringify({- accessKeyId: "AKIAIOSFODNN7EXAMPLE",- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",- }),+ secretKey: JSON.stringify(BEDROCK_AWS_CREDENTIALS),config: { region: "eu-west-1" },},auth,@@ -1196,12 +1153,7 @@ describe("/api/public/llm-connections API Endpoints", () => {projectId,provider,adapter: LLMAdapter.Bedrock,- secretKey: encrypt(- JSON.stringify({- accessKeyId: "AKIAIOSFODNN7EXAMPLE",- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",- }),- ),+ secretKey: encrypt(JSON.stringify(BEDROCK_AWS_CREDENTIALS)),displaySecretKey: "...KEY",config: { region: "ap-southeast-1" },},@@ -1225,21 +1177,7 @@ describe("/api/public/llm-connections API Endpoints", () => {const createData = {provider: generateUniqueProvider("vertexai-bad-config"),adapter: LLMAdapter.VertexAI,- secretKey: JSON.stringify({- type: "service_account",- project_id: "test-project",- private_key_id: "key123",- private_key:- "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----",- client_email: "[email protected]",- client_id: "123456789",- auth_uri: "https://accounts.google.com/o/oauth2/auth",- token_uri: "https://oauth2.googleapis.com/token",- auth_provider_x509_cert_url:- "https://www.googleapis.com/oauth2/v1/certs",- client_x509_cert_url:- "https://www.googleapis.com/robot/v1/metadata/x509/test",- }),+ secretKey: JSON.stringify(VERTEX_AI_CREDENTIALS),config: {region: "us-east-1", // Wrong key - should be 'location'},@@ -1463,22 +1401,22 @@ describe("/api/public/llm-connections API Endpoints", () => {});it("should require valid API key authentication", async () => {- // Test with malformed auth header- const malformedAuthResponse = await makeAPICall(- "GET",- "/api/public/llm-connections",- undefined,- "invalid-format",- );- expect(malformedAuthResponse.status).toBe(401);+ const [malformedAuthResponse, fakeKeyResponse] = await Promise.all([+ makeAPICall(+ "GET",+ "/api/public/llm-connections",+ undefined,+ "invalid-format",+ ),+ makeAPICall(+ "GET",+ "/api/public/llm-connections",+ undefined,+ "Basic " + Buffer.from("pk-lf-fake-key:").toString("base64"),+ ),+ ]);- // Test with non-existent API key- const fakeKeyResponse = await makeAPICall(- "GET",- "/api/public/llm-connections",- undefined,- "Basic " + Buffer.from("pk-lf-fake-key:").toString("base64"),- );+ expect(malformedAuthResponse.status).toBe(401);expect(fakeKeyResponse.status).toBe(401);});});diff --git a/web/src/__tests__/server/observations-comment-filter.servertest.ts b/web/src/__tests__/server/observations-comment-filter.servertest.tsindex 9e75c3fad0..2deef7ba2e 100644--- a/web/src/__tests__/server/observations-comment-filter.servertest.ts+++ b/web/src/__tests__/server/observations-comment-filter.servertest.ts@@ -3,6 +3,7 @@ import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import {+ createOrgProjectAndApiKey,createTrace,createTracesCh,createObservation,@@ -11,43 +12,49 @@ import {import { randomUUID } from "crypto";describe("Observations Comment Filtering", () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-- const session: Session = {- expires: "1",- user: {- id: "user-1",- canCreateOrganizations: true,- name: "Demo User",- organizations: [- {- id: "seed-org-id",- name: "Test Organization",- role: "OWNER",- plan: "cloud:hobby",- cloudConfig: undefined,- projects: [- {- id: projectId,- role: "ADMIN",- retentionDays: 30,- deletedAt: null,- name: "Test Project",- },- ],+ let projectId: string;+ let caller: ReturnType<typeof appRouter.createCaller>;++ beforeAll(async () => {+ const setup = await createOrgProjectAndApiKey();+ projectId = setup.projectId;++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: setup.orgId,+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,},- ],- featureFlags: {- excludeClickhouseRead: false,- templateFlag: true,+ admin: true,},- admin: true,- },- environment: {} as any,- };+ environment: {} as any,+ };- const ctx = createInnerTRPCContext({ session });- const caller = appRouter.createCaller({ ...ctx, prisma });+ const ctx = createInnerTRPCContext({ session });+ caller = appRouter.createCaller({ ...ctx, prisma });+ });// Helper to create standard query paramsconst createQueryParams = (filter: any[]) => ({diff --git a/web/src/__tests__/server/prompts.v2.servertest.ts b/web/src/__tests__/server/prompts.v2.servertest.tsindex 0bb62e5812..1898ed8783 100644--- a/web/src/__tests__/server/prompts.v2.servertest.ts+++ b/web/src/__tests__/server/prompts.v2.servertest.ts@@ -999,9 +999,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {"angled[brac]es]",];- for (const name of validNames) {- await testValidName(name, auth);- }+ await Promise.all(validNames.map((name) => testValidName(name, auth)));});});@@ -1209,7 +1207,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {let projectId: string;let auth: string;- beforeEach(async () => {+ beforeAll(async () => {// Create a prompt in a different project({ projectId: projectId, auth: auth } =await createOrgProjectAndApiKey());diff --git a/web/src/__tests__/server/rate-limit.servertest.ts b/web/src/__tests__/server/rate-limit.servertest.tsindex fbc057b841..e3198f3b87 100644--- a/web/src/__tests__/server/rate-limit.servertest.ts+++ b/web/src/__tests__/server/rate-limit.servertest.ts@@ -167,7 +167,7 @@ describe("RateLimitService", () => {isFirstInDuration: false,});- await new Promise((resolve) => setTimeout(resolve, 3000));+ await redis.del(`${RATE_LIMIT_REDIS_KEY_PREFIX}:public-api:${orgId}`);const secondResult = await rateLimitService.rateLimitRequest(scope,diff --git a/web/src/__tests__/server/score-comparison-analytics.servertest.ts b/web/src/__tests__/server/score-comparison-analytics.servertest.tsindex aff5322d43..e72c83d6b6 100644--- a/web/src/__tests__/server/score-comparison-analytics.servertest.ts+++ b/web/src/__tests__/server/score-comparison-analytics.servertest.ts@@ -5,10 +5,6 @@ import { createInnerTRPCContext } from "@/src/server/api/trpc";import {createTraceScore,createScoresCh,- createTrace,- createTracesCh,- createObservation,- createObservationsCh,createSessionScore,createDatasetRunScore,} from "@langfuse/shared/src/server";@@ -117,22 +113,14 @@ describe("Score Comparison Analytics tRPC", () => {scoreName1: string;scoreName2: string;}) => {+ const scoreTimestamp = Date.now();+for (let offset = 0; offset < totalRows; offset += batchSize) {const currentBatchSize = Math.min(batchSize, totalRows - offset);- const traces = [];const scores = [];for (let i = 0; i < currentBatchSize; i++) {const traceId = v4();- const scoreTimestamp = Date.now() - Math.floor(Math.random() * 3600000);-- traces.push(- createTrace({- id: traceId,- project_id: projectId,- timestamp: Date.now(),- }),- );scores.push(createTraceScore({@@ -161,7 +149,6 @@ describe("Score Comparison Analytics tRPC", () => {);}- await createTracesCh(traces);await createScoresCh(scores);}};@@ -175,22 +162,14 @@ describe("Score Comparison Analytics tRPC", () => {totalRows: number;scoreName: string;}) => {+ const scoreTimestamp = Date.now();+for (let offset = 0; offset < totalRows; offset += batchSize) {const currentBatchSize = Math.min(batchSize, totalRows - offset);- const traces = [];const scores = [];for (let i = 0; i < currentBatchSize; i++) {const traceId = v4();- const scoreTimestamp = Date.now() - Math.floor(Math.random() * 3600000);-- traces.push(- createTrace({- id: traceId,- project_id: projectId,- timestamp: Date.now(),- }),- );scores.push(createTraceScore({@@ -206,7 +185,6 @@ describe("Score Comparison Analytics tRPC", () => {);}- await createTracesCh(traces);await createScoresCh(scores);}};@@ -215,8 +193,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 1: Returns all result types with valid datait("should return all result types with matching scores", async () => {const traceId = v4();- const trace = createTrace({ id: traceId, project_id: projectId });- await createTracesCh([trace]);const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000); // 1 hour ago@@ -399,8 +375,6 @@ describe("Score Comparison Analytics tRPC", () => {// For datasets with estimated counts >= 100k: skips FINAL for performanceit("should use FINAL for small datasets (adaptive FINAL)", async () => {const traceId = v4();- const trace = createTrace({ id: traceId, project_id: projectId });- await createTracesCh([trace]);const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -480,10 +454,6 @@ describe("Score Comparison Analytics tRPC", () => {const scoreName2 = `test-large-score2-${v4()}`;const totalRows = 120_000;- console.log(- `Creating ${totalRows} matched score pairs for adaptive FINAL + sampling test...`,- );-await insertLargeTraceLevelScorePairs({totalRows,scoreName1,@@ -550,10 +520,6 @@ describe("Score Comparison Analytics tRPC", () => {const totalRows = 20_000;const forcedEstimateResults = buildEstimateResults(120_000);- console.log(- `Creating ${totalRows} identical scores for forced-sampling identity test...`,- );-await insertLargeIdenticalTraceLevelScores({totalRows,scoreName,@@ -602,12 +568,6 @@ describe("Score Comparison Analytics tRPC", () => {const trace2 = v4();const trace3 = v4();- await createTracesCh([- createTrace({ id: trace1, project_id: projectId }),- createTrace({ id: trace2, project_id: projectId }),- createTrace({ id: trace3, project_id: projectId }),- ]);-const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);const toTimestamp = new Date(now.getTime() + 3600000);@@ -681,11 +641,6 @@ describe("Score Comparison Analytics tRPC", () => {const trace1 = v4();const trace2 = v4();- await createTracesCh([- createTrace({ id: trace1, project_id: projectId }),- createTrace({ id: trace2, project_id: projectId }),- ]);-const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);const toTimestamp = new Date(now.getTime() + 3600000);@@ -737,9 +692,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 6: Generates correct bins for heatmapit("should generate correct bins for numeric heatmap", async () => {const traces = [v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -813,9 +765,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 7: Respects custom nBins parameterit("should respect a custom nBins value", async () => {const traceId = v4();- await createTracesCh([- createTrace({ id: traceId, project_id: projectId }),- ]);const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -868,9 +817,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 8: Includes min/max ranges for heatmap binsit("should include accurate min/max ranges for each heatmap bin", async () => {const traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -929,9 +875,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 9: Generates confusion matrix for BOOLEAN scoresit("should generate 2x2 confusion matrix for BOOLEAN scores", async () => {const traces = [v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -1004,9 +947,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 10: Generates confusion matrix for CATEGORICAL scoresit("should generate NxN confusion matrix for CATEGORICAL scores", async () => {const traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -1084,9 +1024,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 11: Calculates perfect correlation correctlyit("should calculate perfect correlation for identical scores", async () => {const traces = [v4(), v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -1147,9 +1084,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 12: Calculates statistics with known correlationit("should calculate statistics correctly for known dataset", async () => {const traces = [v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -1212,9 +1146,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 13: Aggregates time series by hourit("should aggregate time series correctly by hour", async () => {const traceId = v4();- await createTracesCh([- createTrace({ id: traceId, project_id: projectId }),- ]);const baseTime = new Date("2024-01-01T10:00:00Z");const fromTimestamp = new Date("2024-01-01T09:00:00Z");@@ -1302,9 +1233,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 14: Aggregates time series by dayit("should aggregate time series correctly by day", async () => {const traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const day1 = new Date("2024-01-01T12:00:00Z");const day2 = new Date("2024-01-02T12:00:00Z");@@ -1386,9 +1314,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 15: Aggregates time series by week and monthit("should aggregate time series correctly by week and month", async () => {const traceId = v4();- await createTracesCh([- createTrace({ id: traceId, project_id: projectId }),- ]);const fromTimestamp = new Date("2024-01-01T00:00:00Z");const toTimestamp = new Date("2024-03-01T00:00:00Z");@@ -1421,9 +1346,8 @@ describe("Score Comparison Analytics tRPC", () => {await createScoresCh(scores);- // Test 7-day interval (week equivalent)- const weekResult =- await caller.scoreAnalytics.getScoreComparisonAnalytics({+ const [weekResult, monthResult] = await Promise.all([+ caller.scoreAnalytics.getScoreComparisonAnalytics({projectId,score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },@@ -1431,13 +1355,8 @@ describe("Score Comparison Analytics tRPC", () => {toTimestamp,interval: { count: 7, unit: "day" },nBins: 10,- });-- expect(weekResult.timeSeries.length).toBeGreaterThan(0);-- // Test month interval- const monthResult =- await caller.scoreAnalytics.getScoreComparisonAnalytics({+ }),+ caller.scoreAnalytics.getScoreComparisonAnalytics({projectId,score1: { name: scoreName1, dataType: "NUMERIC", source: "API" },score2: { name: scoreName2, dataType: "NUMERIC", source: "API" },@@ -1445,17 +1364,16 @@ describe("Score Comparison Analytics tRPC", () => {toTimestamp,interval: { count: 1, unit: "month" },nBins: 10,- });+ }),+ ]);+ expect(weekResult.timeSeries.length).toBeGreaterThan(0);expect(monthResult.timeSeries.length).toBeGreaterThan(0);});// Test 16: Calculates distribution1 accuratelyit("should calculate distribution for first score accurately", async () => {const traces = [v4(), v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -1520,9 +1438,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 17: Calculates distribution2 accuratelyit("should calculate distribution for second score accurately", async () => {const traces = [v4(), v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -1582,11 +1497,6 @@ describe("Score Comparison Analytics tRPC", () => {const trace1 = v4();const trace2 = v4();- await createTracesCh([- createTrace({ id: trace1, project_id: projectId }),- createTrace({ id: trace2, project_id: projectId }),- ]);-const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);const toTimestamp = new Date(now.getTime() + 3600000);@@ -1651,24 +1561,6 @@ describe("Score Comparison Analytics tRPC", () => {const obs1 = v4();const obs2 = v4();- await createTracesCh([- createTrace({ id: traceId, project_id: projectId }),- ]);- await createObservationsCh([- createObservation({- id: obs1,- trace_id: traceId,- project_id: projectId,- type: "GENERATION",- }),- createObservation({- id: obs2,- trace_id: traceId,- project_id: projectId,- type: "GENERATION",- }),- ]);-const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);const toTimestamp = new Date(now.getTime() + 3600000);@@ -1790,9 +1682,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 22: Handles out-of-order timestampsit("should handle scores created in random order", async () => {const traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 7200000); // 2 hours ago@@ -1885,9 +1774,6 @@ describe("Score Comparison Analytics tRPC", () => {it("should align 7-day intervals to Monday (ISO 8601 week)", async () => {// Test that 7-day intervals use Monday-aligned weeks, not Thursday-aligned epochsconst traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );// Use a known Monday and Thursday// Nov 3, 2025 is a Monday@@ -1972,10 +1858,6 @@ describe("Score Comparison Analytics tRPC", () => {// Create two traces - one for morning, one for eveningconst trace1 = v4();const trace2 = v4();- await createTracesCh([- createTrace({ id: trace1, project_id: projectId }),- createTrace({ id: trace2, project_id: projectId }),- ]);const scores = [// Morning scores on trace1@@ -2072,11 +1954,6 @@ describe("Score Comparison Analytics tRPC", () => {const trace1 = v4();const trace2 = v4();const trace3 = v4();- await createTracesCh([- createTrace({ id: trace1, project_id: projectId }),- createTrace({ id: trace2, project_id: projectId }),- createTrace({ id: trace3, project_id: projectId }),- ]);const scores = [// Start of month on trace1@@ -2183,9 +2060,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 26: Matched Distributions - Basic Functionalityit("should return matched distributions excluding unmatched scores", async () => {const traces = [v4(), v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -2290,9 +2164,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 27: Matched Distributions - Empty When No Matchesit("should return empty matched distributions when no scores match", async () => {const traces = [v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -2356,30 +2227,6 @@ describe("Score Comparison Analytics tRPC", () => {const obs2 = v4();const obs3 = v4();- await createTracesCh([- createTrace({ id: traceId, project_id: projectId }),- ]);- await createObservationsCh([- createObservation({- id: obs1,- trace_id: traceId,- project_id: projectId,- type: "GENERATION",- }),- createObservation({- id: obs2,- trace_id: traceId,- project_id: projectId,- type: "GENERATION",- }),- createObservation({- id: obs3,- trace_id: traceId,- project_id: projectId,- type: "GENERATION",- }),- ]);-const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);const toTimestamp = new Date(now.getTime() + 3600000);@@ -2487,9 +2334,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 29: Individual Distributions - Correct Bounds for Numeric Scores with Different Rangesit("should use individual bounds for better visualization when score ranges differ", async () => {const traces = [v4(), v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -2578,9 +2422,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 30: Individual Distributions - Match Global When Ranges Similarit("should have similar distributions when score ranges are similar", async () => {const traces = [v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -2655,9 +2496,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 31: Individual Distributions - Categorical Scores Reference Originalit("should have individual distributions match regular distributions for categorical scores", async () => {const traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -2712,9 +2550,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 32: Cross-Data Type Handlingit("should handle individual distributions correctly for cross-type comparison", async () => {const traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -2789,9 +2624,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 33: Time Series Matched - Two-Score Functionalityit("should return matched time series excluding unmatched scores", async () => {const traces = [v4(), v4(), v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const day1 = new Date("2024-01-01T12:00:00Z");const day2 = new Date("2024-01-02T12:00:00Z");@@ -2931,9 +2763,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 34: Time Series Matched - Single Score Modeit("should handle timeSeriesMatched in single-score mode", async () => {const traces = [v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const day1 = new Date("2024-01-01T12:00:00Z");const day2 = new Date("2024-01-02T12:00:00Z");@@ -2997,9 +2826,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 36: Time Series Matched - Timestamp Precision (Critical)it("should return timestamps in seconds not milliseconds in timeSeriesMatched", async () => {const traceId = v4();- await createTracesCh([- createTrace({ id: traceId, project_id: projectId }),- ]);// Use specific timestamp: 2024-01-15 12:30:45.123 UTCconst specificTime = new Date("2024-01-15T12:30:45.123Z");@@ -3072,9 +2898,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 37: Time Series Matched - Empty When No Matchesit("should return empty timeSeriesMatched when no scores match", async () => {const traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const day1 = new Date("2024-01-01T12:00:00Z");const day2 = new Date("2024-01-02T12:00:00Z");@@ -3144,9 +2967,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 38: Heatmap GlobalMin/GlobalMax - Correct Positionit("should include globalMin and globalMax in heatmap with correct values", async () => {const traces = [v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -3215,9 +3035,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 39: Heatmap GlobalMin/GlobalMax - Single Score Scenarioit("should have identical bounds in single-score mode for heatmap", async () => {const traces = [v4(), v4(), v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -3274,9 +3091,6 @@ describe("Score Comparison Analytics tRPC", () => {// Test 40: Heatmap GlobalMin/GlobalMax - Disjoint Rangesit("should have global bounds spanning disjoint score ranges", async () => {const traces = [v4(), v4(), v4()];- await createTracesCh(- traces.map((id) => createTrace({ id, project_id: projectId })),- );const now = new Date();const fromTimestamp = new Date(now.getTime() - 3600000);@@ -3710,16 +3524,6 @@ describe("Score Comparison Analytics tRPC", () => {const scoreName2 = `objectType-test-score2-${v4()}`;// Create trace for trace-level scores- const trace = createTrace({ id: traceId, project_id: projectId });- await createTracesCh([trace]);-- // Create observation for observation-level scores- const observation = createObservation({- id: observationId,- trace_id: traceId,- project_id: projectId,- });- await createObservationsCh([observation]);const scores = [// Trace-level scores (2 pairs)@@ -3822,53 +3626,51 @@ describe("Score Comparison Analytics tRPC", () => {interval: { count: 1, unit: "hour" as const },};- // Test 1: objectType = "all" should return all 4 matched pairs- const resultAll = await caller.scoreAnalytics.getScoreComparisonAnalytics(- {+ const [+ resultAll,+ resultTrace,+ resultObservation,+ resultSession,+ resultDatasetRun,+ ] = await Promise.all([+ caller.scoreAnalytics.getScoreComparisonAnalytics({...baseParams,objectType: "all",- },- );+ }),+ caller.scoreAnalytics.getScoreComparisonAnalytics({+ ...baseParams,+ objectType: "trace",+ }),+ caller.scoreAnalytics.getScoreComparisonAnalytics({+ ...baseParams,+ objectType: "observation",+ }),+ caller.scoreAnalytics.getScoreComparisonAnalytics({+ ...baseParams,+ objectType: "session",+ }),+ caller.scoreAnalytics.getScoreComparisonAnalytics({+ ...baseParams,+ objectType: "dataset_run",+ }),+ ]);+expect(resultAll.counts.matchedCount).toBe(4);expect(resultAll.counts.score1Total).toBe(4);expect(resultAll.counts.score2Total).toBe(4);- // Test 2: objectType = "trace" should return only trace-level scores (1 pair)- const resultTrace =- await caller.scoreAnalytics.getScoreComparisonAnalytics({- ...baseParams,- objectType: "trace",- });expect(resultTrace.counts.matchedCount).toBe(1);expect(resultTrace.counts.score1Total).toBe(1);expect(resultTrace.counts.score2Total).toBe(1);- // Test 3: objectType = "observation" should return only observation-level scores (1 pair)- const resultObservation =- await caller.scoreAnalytics.getScoreComparisonAnalytics({- ...baseParams,- objectType: "observation",- });expect(resultObservation.counts.matchedCount).toBe(1);expect(resultObservation.counts.score1Total).toBe(1);expect(resultObservation.counts.score2Total).toBe(1);- // Test 4: objectType = "session" should return only session-level scores (1 pair)- const resultSession =- await caller.scoreAnalytics.getScoreComparisonAnalytics({- ...baseParams,- objectType: "session",- });expect(resultSession.counts.matchedCount).toBe(1);expect(resultSession.counts.score1Total).toBe(1);expect(resultSession.counts.score2Total).toBe(1);- // Test 5: objectType = "dataset_run" should return only dataset_run-level scores (1 pair)- const resultDatasetRun =- await caller.scoreAnalytics.getScoreComparisonAnalytics({- ...baseParams,- objectType: "dataset_run",- });expect(resultDatasetRun.counts.matchedCount).toBe(1);expect(resultDatasetRun.counts.score1Total).toBe(1);expect(resultDatasetRun.counts.score2Total).toBe(1);diff --git a/web/src/__tests__/server/scores-api-v1.servertest.ts b/web/src/__tests__/server/scores-api-v1.servertest.tsindex 8d686b9622..e59e6f2520 100644--- a/web/src/__tests__/server/scores-api-v1.servertest.ts+++ b/web/src/__tests__/server/scores-api-v1.servertest.ts@@ -269,6 +269,8 @@ describe("/api/public/scores API Endpoint", () => {...score,value: 200.5,metadata: { "test-key": "test-value-updated" },+ updated_at: score.updated_at + 1,+ event_ts: score.event_ts + 1,};await createScoresCh([updatedScore]);@@ -473,7 +475,7 @@ describe("/api/public/scores API Endpoint", () => {let authentication: string;let newProjectId: string;- beforeEach(async () => {+ beforeAll(async () => {const { projectId, auth } = await createOrgProjectAndApiKey();authentication = auth;newProjectId = projectId;@@ -500,24 +502,24 @@ describe("/api/public/scores API Endpoint", () => {environment: "production",});- await createTracesCh([trace, trace_2, trace_3]);-const generation = createObservation({id: generationId,project_id: newProjectId,type: "GENERATION",});- await createObservationsCh([generation]);-- const config = await prisma.scoreConfig.create({- data: {- name: scoreName,- dataType: "NUMERIC",- maxValue: 100,- projectId: newProjectId,- },- });+ const [config] = await Promise.all([+ prisma.scoreConfig.create({+ data: {+ name: scoreName,+ dataType: "NUMERIC",+ maxValue: 100,+ projectId: newProjectId,+ },+ }),+ createTracesCh([trace, trace_2, trace_3]),+ createObservationsCh([generation]),+ ]);configId = config.id;@@ -808,29 +810,50 @@ describe("/api/public/scores API Endpoint", () => {describe("should Filter scores by queueId", () => {describe("queueId filtering", () => {let queueId: string;+ let queueTraceId: string;+ let queueGenerationId: string;+ let queueAuth: string;beforeEach(async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ queueAuth = auth;queueId = v4();+ queueTraceId = v4();+ queueGenerationId = v4();++ await Promise.all([+ createTracesCh([+ createTrace({ id: queueTraceId, project_id: projectId }),+ ]),+ createObservationsCh([+ createObservation({+ id: queueGenerationId,+ project_id: projectId,+ type: "GENERATION",+ }),+ ]),+ ]);+const score = createTraceScore({id: v4(),- project_id: newProjectId,- trace_id: traceId,+ project_id: projectId,+ trace_id: queueTraceId,name: "score-name",value: 100.5,source: "ANNOTATION",comment: "comment",- observation_id: generationId,+ observation_id: queueGenerationId,queue_id: queueId,});const score2 = createTraceScore({id: v4(),- project_id: newProjectId,- trace_id: traceId,+ project_id: projectId,+ trace_id: queueTraceId,name: "score-name",value: 75.0,source: "ANNOTATION",comment: "comment",- observation_id: generationId,+ observation_id: queueGenerationId,queue_id: queueId,});@@ -843,7 +866,7 @@ describe("/api/public/scores API Endpoint", () => {"GET",`/api/public/scores?queueId=${queueId}`,undefined,- authentication,+ queueAuth,);expect(getAllScore.status).toBe(200);expect(getAllScore.body.meta).toMatchObject({@@ -854,8 +877,8 @@ describe("/api/public/scores API Endpoint", () => {});for (const val of getAllScore.body.data) {expect(val).toMatchObject({- traceId: traceId,- observationId: generationId,+ traceId: queueTraceId,+ observationId: queueGenerationId,queueId: queueId,source: "ANNOTATION",});diff --git a/web/src/__tests__/server/scores-api-v2.servertest.ts b/web/src/__tests__/server/scores-api-v2.servertest.tsindex 4de05a2854..c26433c25e 100644--- a/web/src/__tests__/server/scores-api-v2.servertest.ts+++ b/web/src/__tests__/server/scores-api-v2.servertest.ts@@ -19,9 +19,16 @@ import { z } from "zod";describe("/api/public/v2/scores API Endpoint", () => {describe("GET /api/public/v2/scores/:scoreId", () => {- it("should GET a trace score", async () => {- const { projectId: projectId, auth } = await createOrgProjectAndApiKey();+ let auth: string;+ let projectId: string;++ beforeAll(async () => {+ const project = await createOrgProjectAndApiKey();+ auth = project.auth;+ projectId = project.projectId;+ });+ it("should GET a trace score", async () => {const scoreId = v4();const traceId = v4();const score = createTraceScore({@@ -65,16 +72,12 @@ describe("/api/public/v2/scores API Endpoint", () => {});it("should GET score with minimal score data and minimal trace data", async () => {- const { projectId, auth } = await createOrgProjectAndApiKey();-const minimalTraceId = v4();const trace = createTrace({id: minimalTraceId,project_id: projectId,});- await createTracesCh([trace]);-const minimalScoreId = v4();const score = createTraceScore({@@ -87,7 +90,7 @@ describe("/api/public/v2/scores API Endpoint", () => {comment: null,observation_id: null,});- await createScoresCh([score]);+ await Promise.all([createTracesCh([trace]), createScoresCh([score])]);const fetchedScore = await makeZodVerifiedAPICall(GetScoreResponseV2,@@ -101,8 +104,6 @@ describe("/api/public/v2/scores API Endpoint", () => {});it("should GET a session score", async () => {- const { projectId: projectId, auth } = await createOrgProjectAndApiKey();-const scoreId = v4();const sessionId = v4();const score = createSessionScore({@@ -147,8 +148,6 @@ describe("/api/public/v2/scores API Endpoint", () => {});it("should GET a run score", async () => {- const { projectId: projectId, auth } = await createOrgProjectAndApiKey();-const scoreId = v4();const runId = v4();const score = createDatasetRunScore({@@ -192,8 +191,6 @@ describe("/api/public/v2/scores API Endpoint", () => {});it("should GET a text score", async () => {- const { projectId, auth } = await createOrgProjectAndApiKey();-const scoreId = v4();const traceId = v4();const score = createTraceScore({@@ -268,7 +265,7 @@ describe("/api/public/v2/scores API Endpoint", () => {let newProjectId: string;let executionTraceId: string;- beforeEach(async () => {+ beforeAll(async () => {const { projectId, auth } = await createOrgProjectAndApiKey();authentication = auth;newProjectId = projectId;@@ -296,24 +293,24 @@ describe("/api/public/v2/scores API Endpoint", () => {environment: "production",});- await createTracesCh([trace, trace_2, trace_3]);-const generation = createObservation({id: generationId,project_id: newProjectId,type: "GENERATION",});- await createObservationsCh([generation]);-- const config = await prisma.scoreConfig.create({- data: {- name: scoreName,- dataType: "NUMERIC",- maxValue: 100,- projectId: newProjectId,- },- });+ const [config] = await Promise.all([+ prisma.scoreConfig.create({+ data: {+ name: scoreName,+ dataType: "NUMERIC",+ maxValue: 100,+ projectId: newProjectId,+ },+ }),+ createTracesCh([trace, trace_2, trace_3]),+ createObservationsCh([generation]),+ ]);configId = config.id;@@ -667,8 +664,13 @@ describe("/api/public/v2/scores API Endpoint", () => {let sessionScoreWithEnvId: string;let sessionScoreDefaultEnvId: string;let traceScoreWithEnvId: string;+ let environmentProjectId: string;+ let environmentAuth: string;beforeEach(async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ environmentProjectId = projectId;+ environmentAuth = auth;sessionScoreWithEnvId = v4();sessionScoreDefaultEnvId = v4();traceScoreWithEnvId = v4();@@ -676,7 +678,7 @@ describe("/api/public/v2/scores API Endpoint", () => {// Session score with 'staging' environmentconst sessionScoreWithEnv = createSessionScore({id: sessionScoreWithEnvId,- project_id: newProjectId,+ project_id: environmentProjectId,session_id: v4(),name: "session-score-with-env",value: 80,@@ -687,7 +689,7 @@ describe("/api/public/v2/scores API Endpoint", () => {// Session score with default environmentconst sessionScoreDefaultEnv = createSessionScore({id: sessionScoreDefaultEnvId,- project_id: newProjectId,+ project_id: environmentProjectId,session_id: v4(),name: "session-score-default-env",value: 90,@@ -698,7 +700,7 @@ describe("/api/public/v2/scores API Endpoint", () => {// Trace score with 'staging' environment on a trace with 'development' environmentconst traceWithDifferentEnv = createTrace({id: v4(),- project_id: newProjectId,+ project_id: environmentProjectId,user_id: "env-test-user",environment: "development",});@@ -707,7 +709,7 @@ describe("/api/public/v2/scores API Endpoint", () => {const traceScoreWithEnv = createTraceScore({id: traceScoreWithEnvId,- project_id: newProjectId,+ project_id: environmentProjectId,trace_id: traceWithDifferentEnv.id,name: "trace-score-with-env",value: 70,@@ -728,7 +730,7 @@ describe("/api/public/v2/scores API Endpoint", () => {"GET",`/api/public/v2/scores?environment=staging`,undefined,- authentication,+ environmentAuth,);expect(getAllScore.status).toBe(200);@@ -746,7 +748,7 @@ describe("/api/public/v2/scores API Endpoint", () => {"GET",`/api/public/v2/scores?environment=default`,undefined,- authentication,+ environmentAuth,);expect(getAllScore.status).toBe(200);@@ -764,7 +766,7 @@ describe("/api/public/v2/scores API Endpoint", () => {"GET",`/api/public/v2/scores?environment=staging&userId=env-test-user`,undefined,- authentication,+ environmentAuth,);expect(getAllScore.status).toBe(200);@@ -784,7 +786,7 @@ describe("/api/public/v2/scores API Endpoint", () => {const matchingTrace = createTrace({id: matchingTraceId,- project_id: newProjectId,+ project_id: environmentProjectId,user_id: "matching-env-user",environment: "staging",});@@ -793,7 +795,7 @@ describe("/api/public/v2/scores API Endpoint", () => {const matchingScore = createTraceScore({id: matchingScoreId,- project_id: newProjectId,+ project_id: environmentProjectId,trace_id: matchingTraceId,name: "matching-score",value: 100,@@ -808,7 +810,7 @@ describe("/api/public/v2/scores API Endpoint", () => {"GET",`/api/public/v2/scores?environment=staging&userId=matching-env-user`,undefined,- authentication,+ environmentAuth,);expect(getAllScore.status).toBe(200);@@ -848,29 +850,50 @@ describe("/api/public/v2/scores API Endpoint", () => {describe("should Filter scores by queueId", () => {describe("queueId filtering", () => {let queueId: string;+ let queueTraceId: string;+ let queueGenerationId: string;+ let queueAuth: string;beforeEach(async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ queueAuth = auth;queueId = v4();+ queueTraceId = v4();+ queueGenerationId = v4();++ await Promise.all([+ createTracesCh([+ createTrace({ id: queueTraceId, project_id: projectId }),+ ]),+ createObservationsCh([+ createObservation({+ id: queueGenerationId,+ project_id: projectId,+ type: "GENERATION",+ }),+ ]),+ ]);+const score = createTraceScore({id: v4(),- project_id: newProjectId,- trace_id: traceId,+ project_id: projectId,+ trace_id: queueTraceId,name: "score-name",value: 100.5,source: "ANNOTATION",comment: "comment",- observation_id: generationId,+ observation_id: queueGenerationId,queue_id: queueId,});const score2 = createTraceScore({id: v4(),- project_id: newProjectId,- trace_id: traceId,+ project_id: projectId,+ trace_id: queueTraceId,name: "score-name",value: 75.0,source: "ANNOTATION",comment: "comment",- observation_id: generationId,+ observation_id: queueGenerationId,queue_id: queueId,});@@ -883,7 +906,7 @@ describe("/api/public/v2/scores API Endpoint", () => {"GET",`/api/public/v2/scores?queueId=${queueId}`,undefined,- authentication,+ queueAuth,);expect(getAllScore.status).toBe(200);expect(getAllScore.body.meta).toMatchObject({@@ -894,8 +917,8 @@ describe("/api/public/v2/scores API Endpoint", () => {});for (const val of getAllScore.body.data) {expect(val).toMatchObject({- traceId: traceId,- observationId: generationId,+ traceId: queueTraceId,+ observationId: queueGenerationId,queueId: queueId,source: "ANNOTATION",});@@ -1662,26 +1685,7 @@ describe("/api/public/v2/scores API Endpoint", () => {});it("should return 400 when requesting trace field without score field", async () => {- const { projectId, auth } = await createOrgProjectAndApiKey();- const traceId = v4();- const scoreId = v4();-- const trace = createTrace({- id: traceId,- project_id: projectId,- user_id: "test-user",- });- await createTracesCh([trace]);-- const score = createTraceScore({- id: scoreId,- project_id: projectId,- trace_id: traceId,- name: "test-score",- value: 100,- data_type: "NUMERIC",- });- await createScoresCh([score]);+ const { auth } = await createOrgProjectAndApiKey();const response = await makeZodVerifiedAPICall(z.object({@@ -1759,28 +1763,14 @@ describe("/api/public/v2/scores API Endpoint", () => {});describe("GET /api/public/v2/scores - fields validation", () => {- it("should return 400 when filtering by userId without trace field", async () => {- const { projectId, auth } = await createOrgProjectAndApiKey();- const traceId = v4();- const scoreId = v4();-- const trace = createTrace({- id: traceId,- project_id: projectId,- user_id: "test-user",- });- await createTracesCh([trace]);+ let validationAuth: string;- const score = createTraceScore({- id: scoreId,- project_id: projectId,- trace_id: traceId,- name: "test-score",- value: 100,- data_type: "NUMERIC",- });- await createScoresCh([score]);+ beforeAll(async () => {+ const { auth } = await createOrgProjectAndApiKey();+ validationAuth = auth;+ });+ it("should return 400 when filtering by userId without trace field", async () => {const response = await makeZodVerifiedAPICall(z.object({message: z.string(),@@ -1788,7 +1778,7 @@ describe("/api/public/v2/scores API Endpoint", () => {"GET",`/api/public/v2/scores?fields=score&userId=test-user`,undefined,- auth,+ validationAuth,400,);@@ -1799,27 +1789,6 @@ describe("/api/public/v2/scores API Endpoint", () => {});it("should return 400 when filtering by traceTags without trace field", async () => {- const { projectId, auth } = await createOrgProjectAndApiKey();- const traceId = v4();- const scoreId = v4();-- const trace = createTrace({- id: traceId,- project_id: projectId,- tags: ["tag1"],- });- await createTracesCh([trace]);-- const score = createTraceScore({- id: scoreId,- project_id: projectId,- trace_id: traceId,- name: "test-score",- value: 100,- data_type: "NUMERIC",- });- await createScoresCh([score]);-const response = await makeZodVerifiedAPICall(z.object({message: z.string(),@@ -1827,7 +1796,7 @@ describe("/api/public/v2/scores API Endpoint", () => {"GET",`/api/public/v2/scores?fields=score&traceTags=tag1`,undefined,- auth,+ validationAuth,400,);diff --git a/web/src/__tests__/server/sessions-comment-filter.servertest.ts b/web/src/__tests__/server/sessions-comment-filter.servertest.tsindex 6092110826..a9771b849b 100644--- a/web/src/__tests__/server/sessions-comment-filter.servertest.ts+++ b/web/src/__tests__/server/sessions-comment-filter.servertest.ts@@ -2,47 +2,57 @@ import type { Session } from "next-auth";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";-import { createTrace, createTracesCh } from "@langfuse/shared/src/server";+import {+ createOrgProjectAndApiKey,+ createTrace,+ createTracesCh,+} from "@langfuse/shared/src/server";import { randomUUID } from "crypto";describe("Sessions Comment Filtering", () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-- const session: Session = {- expires: "1",- user: {- id: "user-1",- canCreateOrganizations: true,- name: "Demo User",- organizations: [- {- id: "seed-org-id",- name: "Test Organization",- role: "OWNER",- plan: "cloud:hobby",- cloudConfig: undefined,- projects: [- {- id: projectId,- role: "ADMIN",- retentionDays: 30,- deletedAt: null,- name: "Test Project",- },- ],+ let projectId: string;+ let caller: ReturnType<typeof appRouter.createCaller>;++ beforeAll(async () => {+ const setup = await createOrgProjectAndApiKey();+ projectId = setup.projectId;++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: setup.orgId,+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,},- ],- featureFlags: {- excludeClickhouseRead: false,- templateFlag: true,+ admin: true,},- admin: true,- },- environment: {} as any,- };+ environment: {} as any,+ };- const ctx = createInnerTRPCContext({ session });- const caller = appRouter.createCaller({ ...ctx, prisma });+ const ctx = createInnerTRPCContext({ session });+ caller = appRouter.createCaller({ ...ctx, prisma });+ });// Helper to create standard query paramsconst createQueryParams = (filter: any[]) => ({diff --git a/web/src/__tests__/server/traces-api.servertest.ts b/web/src/__tests__/server/traces-api.servertest.tsindex 7d1c5522fd..57ac8ed6a6 100644--- a/web/src/__tests__/server/traces-api.servertest.ts+++ b/web/src/__tests__/server/traces-api.servertest.ts@@ -99,6 +99,46 @@ const createObservationOrEvent = (}};+const waitForEventsTable = async (useEventsTable: boolean) => {+ if (useEventsTable) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+};++const createFieldsFilteringFixture = (projectId: string) => {+ const traceId = randomUUID();+ const createdTrace = createTrace({+ id: traceId,+ name: "trace-with-all-fields",+ user_id: "user-1",+ project_id: projectId,+ metadata: { key: "value" },+ input: JSON.stringify({ prompt: "test" }),+ output: JSON.stringify({ response: "test response" }),+ release: "1.0.0",+ version: "2.0.0",+ });++ const observation = createObservation({+ trace_id: traceId,+ project_id: projectId,+ name: "test-observation",+ end_time: new Date().getTime(),+ start_time: new Date().getTime() - 1000,+ input: "observation input",+ output: "observation output",+ });++ const score = createTraceScore({+ trace_id: traceId,+ project_id: projectId,+ name: "test-score",+ value: 0.8,+ });++ return { createdTrace, observation, score, traceId };+};+// Helper to create trace with observations/eventsconst createTraceWithObservations = async (useEventsTable: boolean,@@ -159,6 +199,11 @@ describe("/api/public/traces API Endpoint", () => {let auth: string;beforeEach(async () => {+ const currentTestName = expect.getState().currentTestName ?? "";+ if (currentTestName.includes("Advanced Filtering - Dual Path Tests")) {+ return;+ }+const fixture = await createOrgProjectAndApiKey();projectId = fixture.projectId;auth = fixture.auth;@@ -195,8 +240,10 @@ describe("/api/public/traces API Endpoint", () => {}),];- await createTracesCh([createdTrace]);- await createObservationsCh(observations);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh(observations),+ ]);const trace = await makeZodVerifiedAPICall(GetTraceV1Response,@@ -258,9 +305,11 @@ describe("/api/public/traces API Endpoint", () => {value: 0.8,});- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);- await createScoresCh([score]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ createScoresCh([score]),+ ]);const trace = await makeZodVerifiedAPICall(GetTraceV1Response,@@ -308,9 +357,11 @@ describe("/api/public/traces API Endpoint", () => {value: 0.8,});- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);- await createScoresCh([score]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ createScoresCh([score]),+ ]);const trace = await makeZodVerifiedAPICall(GetTraceV1Response,@@ -349,8 +400,10 @@ describe("/api/public/traces API Endpoint", () => {cost_details: { input: 0.01, output: 0.02, total: 0.03 },});- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ ]);const trace = await makeZodVerifiedAPICall(GetTraceV1Response,@@ -402,8 +455,10 @@ describe("/api/public/traces API Endpoint", () => {}),];- await createTracesCh([createdTrace]);- await createObservationsCh(observations);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh(observations),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -701,18 +756,6 @@ describe("/api/public/traces API Endpoint", () => {expect(response.status).toBe(400);});- it("should return 400 error when page=0", async () => {- const response = await makeZodVerifiedAPICallSilent(- GetTracesV1Response,- "GET",- "/api/public/traces?page=0&limit=10",- undefined,- auth,- );-- expect(response.status).toBe(400);- });-it("LFE-3699: should fetch a single trace with unescaped metadata via traces list", async () => {const traceId = randomUUID();const traceName = `trace-name-${traceId}`;@@ -812,21 +855,10 @@ describe("/api/public/traces API Endpoint", () => {createObservation({trace_id: traceId,project_id: projectId,- input: "a".repeat(30e6),- output: "b".repeat(30e6),- metadata: {- foo: "c".repeat(30e6),- },- }),- ]);- await createObservationsCh([- createObservation({- trace_id: traceId,- project_id: projectId,- input: "a".repeat(30e6),- output: "b".repeat(30e6),+ input: "a".repeat(28e6),+ output: "b".repeat(28e6),metadata: {- foo: "c".repeat(30e6),+ foo: "c".repeat(28e6),},}),]);@@ -840,7 +872,7 @@ describe("/api/public/traces API Endpoint", () => {auth,),).rejects.toThrow(- "Observations in trace are too large: 90.00MB exceeds limit of 80.00MB",+ /Observations in trace are too large: .* exceeds limit of 80\.00MB/,);});@@ -895,54 +927,31 @@ describe("/api/public/traces API Endpoint", () => {// Thenexpect(deleteResponse.status).toBe(200);await waitForExpect(async () => {- const trace1 = await getTraceById({- traceId: createdTrace1.id,- projectId,- });+ const [trace1, trace2] = await Promise.all([+ getTraceById({+ traceId: createdTrace1.id,+ projectId,+ }),+ getTraceById({+ traceId: createdTrace2.id,+ projectId,+ }),+ ]);expect(trace1).toBeUndefined();- const trace2 = await getTraceById({- traceId: createdTrace2.id,- projectId,- });expect(trace2).toBeUndefined();}, 40_000);}, 60_000);describe("Fields Filtering", () => {it("should fetch traces with all fields by default", async () => {- const traceId = randomUUID();- const createdTrace = createTrace({- id: traceId,- name: "trace-with-all-fields",- user_id: "user-1",- project_id: projectId,- metadata: { key: "value" },- input: JSON.stringify({ prompt: "test" }),- output: JSON.stringify({ response: "test response" }),- release: "1.0.0",- version: "2.0.0",- });-- const observation = createObservation({- trace_id: traceId,- project_id: projectId,- name: "test-observation",- end_time: new Date().getTime(),- start_time: new Date().getTime() - 1000,- input: "observation input",- output: "observation output",- });+ const { createdTrace, observation, score, traceId } =+ createFieldsFilteringFixture(projectId);- const score = createTraceScore({- trace_id: traceId,- project_id: projectId,- name: "test-score",- value: 0.8,- });-- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);- await createScoresCh([score]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ createScoresCh([score]),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -995,9 +1004,11 @@ describe("/api/public/traces API Endpoint", () => {value: 0.8,});- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);- await createScoresCh([score]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ createScoresCh([score]),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -1084,8 +1095,10 @@ describe("/api/public/traces API Endpoint", () => {value: 0.8,});- await createTracesCh([createdTrace]);- await createScoresCh([score]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createScoresCh([score]),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -1128,8 +1141,10 @@ describe("/api/public/traces API Endpoint", () => {start_time: new Date().getTime() - 1000,});- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -1173,8 +1188,10 @@ describe("/api/public/traces API Endpoint", () => {total_cost: 0.05,});- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -1216,39 +1233,14 @@ describe("/api/public/traces API Endpoint", () => {});it("should handle empty fields parameter", async () => {- const traceId = randomUUID();- const createdTrace = createTrace({- id: traceId,- name: "trace-with-all-fields",- user_id: "user-1",- project_id: projectId,- metadata: { key: "value" },- input: JSON.stringify({ prompt: "test" }),- output: JSON.stringify({ response: "test response" }),- release: "1.0.0",- version: "2.0.0",- });-- const observation = createObservation({- trace_id: traceId,- project_id: projectId,- name: "test-observation",- end_time: new Date().getTime(),- start_time: new Date().getTime() - 1000,- input: "observation input",- output: "observation output",- });-- const score = createTraceScore({- trace_id: traceId,- project_id: projectId,- name: "test-score",- value: 0.8,- });+ const { createdTrace, observation, score, traceId } =+ createFieldsFilteringFixture(projectId);- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);- await createScoresCh([score]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ createScoresCh([score]),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -1292,10 +1284,16 @@ describe("/api/public/traces API Endpoint", () => {};describe(`${suiteName}`, () => {+ let projectId: string;+ let auth: string;const testTraceId = randomUUID();const testTraceId2 = randomUUID();- beforeEach(async () => {+ beforeAll(async () => {+ const fixture = await createOrgProjectAndApiKey();+ projectId = fixture.projectId;+ auth = fixture.auth;+// Create test traces with different metadata for filteringconst trace1 = createTrace({id: testTraceId,@@ -1331,11 +1329,12 @@ describe("/api/public/traces API Endpoint", () => {timestamp: new Date("2024-01-02T00:00:00Z").getTime(),});- await createTraceWithObservations(useEventsTable, trace1, []);- await createTraceWithObservations(useEventsTable, trace2, []);+ await Promise.all([+ createTraceWithObservations(useEventsTable, trace1, []),+ createTraceWithObservations(useEventsTable, trace2, []),+ ]);- // Simple wait to ensure data is available- await new Promise((resolve) => setTimeout(resolve, 100));+ await waitForEventsTable(useEventsTable);}, 10000);it("should support basic metadata filtering", async () => {@@ -1736,9 +1735,7 @@ describe("/api/public/traces API Endpoint", () => {];await createTraceWithObservations(useEventsTable, trace, events);-- // Simple wait to ensure data is available- await new Promise((resolve) => setTimeout(resolve, 100));+ await waitForEventsTable(useEventsTable);// The trace should NOT be returned because after aggregation,// it has version=2.0 (from the latest event)@@ -1871,24 +1868,13 @@ describe("/api/public/traces API Endpoint", () => {},];- await createTraceWithObservations(- useEventsTable,- trace1,- observations1,- );- await createTraceWithObservations(- useEventsTable,- trace2,- observations2,- );- await createTraceWithObservations(- useEventsTable,- trace3,- observations3,- );+ await Promise.all([+ createTraceWithObservations(useEventsTable, trace1, observations1),+ createTraceWithObservations(useEventsTable, trace2, observations2),+ createTraceWithObservations(useEventsTable, trace3, observations3),+ ]);- // Simple wait to ensure data is available- await new Promise((resolve) => setTimeout(resolve, 100));+ await waitForEventsTable(useEventsTable);// Test filtering by latency range (>= 0 and <= 1.9 seconds)// This should return trace1 and trace2, but not trace3@@ -1985,9 +1971,11 @@ describe("/api/public/traces API Endpoint", () => {observation_id: null, // Must be null for trace-level scores});- await createTraceWithObservations(useEventsTable, trace1, []);- await createTraceWithObservations(useEventsTable, trace2, []);- await createScoresCh([score1, score2]);+ await Promise.all([+ createTraceWithObservations(useEventsTable, trace1, []),+ createTraceWithObservations(useEventsTable, trace2, []),+ createScoresCh([score1, score2]),+ ]);// Test filtering by score_categories (check for "good" score)// This should return trace1 only@@ -2141,8 +2129,10 @@ describe("/api/public/traces API Endpoint", () => {project_id: projectId,});- await createTraceWithObservations(useEventsTable, createdTrace, []);- await createTraceWithObservations(useEventsTable, dummyTrace, []);+ await Promise.all([+ createTraceWithObservations(useEventsTable, createdTrace, []),+ createTraceWithObservations(useEventsTable, dummyTrace, []),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -2223,27 +2213,28 @@ describe("/api/public/traces API Endpoint", () => {}),);- for (const trace of traces) {- await createTraceWithObservations(useEventsTable, trace, []);- }-- // Get page 1- const page1 = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- buildUrl(`page=1&limit=2`),- undefined,- auth,+ await Promise.all(+ traces.map((trace) =>+ createTraceWithObservations(useEventsTable, trace, []),+ ),);- // Get page 2- const page2 = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- buildUrl(`page=2&limit=2`),- undefined,- auth,- );+ const [page1, page2] = await Promise.all([+ makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ buildUrl(`page=1&limit=2`),+ undefined,+ auth,+ ),+ makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ buildUrl(`page=2&limit=2`),+ undefined,+ auth,+ ),+ ]);expect(page1.body.data.length).toBeLessThanOrEqual(2);expect(page2.body.data.length).toBeLessThanOrEqual(2);@@ -2274,12 +2265,10 @@ describe("/api/public/traces API Endpoint", () => {timestamp: yesterday.getTime() - 24 * 60 * 60 * 1000,});- await createTraceWithObservations(useEventsTable, traceInRange, []);- await createTraceWithObservations(- useEventsTable,- traceOutOfRange,- [],- );+ await Promise.all([+ createTraceWithObservations(useEventsTable, traceInRange, []),+ createTraceWithObservations(useEventsTable, traceOutOfRange, []),+ ]);const traces = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -2346,9 +2335,11 @@ describe("/api/public/traces API Endpoint", () => {}),);- for (const trace of traces) {- await createTraceWithObservations(useEventsTable, trace, []);- }+ await Promise.all(+ traces.map((trace) =>+ createTraceWithObservations(useEventsTable, trace, []),+ ),+ );const result = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -2462,9 +2453,11 @@ describe("/api/public/traces API Endpoint", () => {value: 0.8,});- await createTracesCh([createdTrace]);- await createObservationsCh([observation]);- await createScoresCh([score]);+ await Promise.all([+ createTracesCh([createdTrace]),+ createObservationsCh([observation]),+ createScoresCh([score]),+ ]);const response = await makeZodVerifiedAPICall(GetTracesV1Response,@@ -2521,100 +2514,61 @@ describe("/api/public/traces API Endpoint", () => {// Comprehensive filter column tests - verify all documented filter columns don't crashdescribe("Filter Columns - Doesn't Fail Tests", () => {+ const filters = [+ // Aggregated Metrics (from observations)+ { column: "latency", type: "number", operator: ">=", value: 0 },+ { column: "inputTokens", type: "number", operator: ">=", value: 0 },+ { column: "outputTokens", type: "number", operator: ">=", value: 0 },+ { column: "totalTokens", type: "number", operator: ">=", value: 0 },+ { column: "inputCost", type: "number", operator: ">=", value: 0 },+ { column: "outputCost", type: "number", operator: ">=", value: 0 },+ { column: "totalCost", type: "number", operator: ">=", value: 0 },+ // Observation Level Aggregations+ { column: "level", type: "string", operator: "=", value: "ERROR" },+ { column: "warningCount", type: "number", operator: ">=", value: 0 },+ { column: "errorCount", type: "number", operator: ">=", value: 0 },+ { column: "defaultCount", type: "number", operator: ">=", value: 0 },+ { column: "debugCount", type: "number", operator: ">=", value: 0 },+ // Scores (should not crash, filters are ignored per our fix)+ {+ column: "scores_avg",+ type: "numberObject",+ key: "quality",+ operator: ">=",+ value: 0.5,+ },+ {+ column: "score_categories",+ type: "stringOptions",+ operator: "any of",+ value: ["good", "bad"],+ },+ ];+const runFilterTests = (useEventsTable: boolean) => {const suiteName = useEventsTable? "with events table": "with traces table";const queryParam = useEventsTable ? "?useEventsTable=true&" : "?";- describe(suiteName, () => {- // Aggregated Metrics (from observations)- const metricsFilters = [- { column: "latency", type: "number", operator: ">=", value: 0 },- { column: "inputTokens", type: "number", operator: ">=", value: 0 },- { column: "outputTokens", type: "number", operator: ">=", value: 0 },- { column: "totalTokens", type: "number", operator: ">=", value: 0 },- { column: "inputCost", type: "number", operator: ">=", value: 0 },- { column: "outputCost", type: "number", operator: ">=", value: 0 },- { column: "totalCost", type: "number", operator: ">=", value: 0 },- ];-- metricsFilters.forEach(({ column, type, operator, value }) => {- it(`should not fail when filtering by ${column}`, async () => {- const filterParam = JSON.stringify([- { type, column, operator, value },- ]);- const response = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- `/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,- undefined,- auth,- );- expect(response.status).toBe(200);- expect(response.body.data).toBeDefined();- expect(response.body.meta).toBeDefined();- });- });-- // Observation Level Aggregations- const observationAggFilters = [- { column: "level", type: "string", operator: "=", value: "ERROR" },- { column: "warningCount", type: "number", operator: ">=", value: 0 },- { column: "errorCount", type: "number", operator: ">=", value: 0 },- { column: "defaultCount", type: "number", operator: ">=", value: 0 },- { column: "debugCount", type: "number", operator: ">=", value: 0 },- ];-- observationAggFilters.forEach(({ column, type, operator, value }) => {- it(`should not fail when filtering by ${column}`, async () => {- const filterParam = JSON.stringify([- { type, column, operator, value },- ]);- const response = await makeZodVerifiedAPICall(- GetTracesV1Response,- "GET",- `/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,- undefined,- auth,- );- expect(response.status).toBe(200);- expect(response.body.data).toBeDefined();- expect(response.body.meta).toBeDefined();- });- });-- // Scores (should not crash, filters are ignored per our fix)- const scoreFilters = [- {- column: "scores_avg",- type: "numberObject",- key: "quality",- operator: ">=",- value: 0.5,- },- {- column: "score_categories",- type: "stringOptions",- operator: "any of",- value: ["good", "bad"],- },- ];-- scoreFilters.forEach((filterDef) => {- it(`should not fail when filtering by ${filterDef.column}`, async () => {+ it(`${suiteName}: should not fail for documented filter columns`, async () => {+ const responses = await Promise.all(+ filters.map((filterDef) => {const filterParam = JSON.stringify([filterDef]);- const response = await makeZodVerifiedAPICall(+ return makeZodVerifiedAPICall(GetTracesV1Response,"GET",`/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,undefined,auth,);- expect(response.status).toBe(200);- expect(response.body.data).toBeDefined();- expect(response.body.meta).toBeDefined();- });+ }),+ );++ responses.forEach((response) => {+ expect(response.status).toBe(200);+ expect(response.body.data).toBeDefined();+ expect(response.body.meta).toBeDefined();});});};diff --git a/web/src/__tests__/server/traces-comment-filter.servertest.ts b/web/src/__tests__/server/traces-comment-filter.servertest.tsindex c661da5f96..d5cb4f0c58 100644--- a/web/src/__tests__/server/traces-comment-filter.servertest.ts+++ b/web/src/__tests__/server/traces-comment-filter.servertest.ts@@ -2,47 +2,57 @@ import type { Session } from "next-auth";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";-import { createTrace, createTracesCh } from "@langfuse/shared/src/server";+import {+ createOrgProjectAndApiKey,+ createTrace,+ createTracesCh,+} from "@langfuse/shared/src/server";import { randomUUID } from "crypto";describe("Traces Comment Filtering", () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-- const session: Session = {- expires: "1",- user: {- id: "user-1",- canCreateOrganizations: true,- name: "Demo User",- organizations: [- {- id: "seed-org-id",- name: "Test Organization",- role: "OWNER",- plan: "cloud:hobby",- cloudConfig: undefined,- projects: [- {- id: projectId,- role: "ADMIN",- retentionDays: 30,- deletedAt: null,- name: "Test Project",- },- ],+ let projectId: string;+ let caller: ReturnType<typeof appRouter.createCaller>;++ beforeAll(async () => {+ const setup = await createOrgProjectAndApiKey();+ projectId = setup.projectId;++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: setup.orgId,+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,},- ],- featureFlags: {- excludeClickhouseRead: false,- templateFlag: true,+ admin: true,},- admin: true,- },- environment: {} as any,- };+ environment: {} as any,+ };- const ctx = createInnerTRPCContext({ session });- const caller = appRouter.createCaller({ ...ctx, prisma });+ const ctx = createInnerTRPCContext({ session });+ caller = appRouter.createCaller({ ...ctx, prisma });+ });// Helper to create standard query paramsconst createQueryParams = (filter: any[]) => ({diff --git a/web/vitest.config.mts b/web/vitest.config.mtsindex 976763a7a6..6279cdd21f 100644--- a/web/vitest.config.mts+++ b/web/vitest.config.mts@@ -1,11 +1,16 @@import { defineConfig } from "vitest/config";import react from "@vitejs/plugin-react";import tsconfigPaths from "vite-tsconfig-paths";+import { VitestCiReporter } from "../scripts/vitest/ci-reporter";export default defineConfig({plugins: [tsconfigPaths(), react()],test: {+ reporters: process.env.CI+ ? ["default", new VitestCiReporter()]+ : ["default"],globals: true,+ retry: process.env.CI ? 3 : 0,testTimeout: 30_000,server: {deps: {diff --git a/worker/src/__tests__/backfillValidToForDatasetItems.test.ts b/worker/src/__tests__/backfillValidToForDatasetItems.test.tsindex 7f841dae92..c47c79dcc1 100644--- a/worker/src/__tests__/backfillValidToForDatasetItems.test.ts+++ b/worker/src/__tests__/backfillValidToForDatasetItems.test.ts@@ -8,83 +8,89 @@ const t2 = new Date("2024-01-01T02:00:00Z");const t3 = new Date("2024-01-01T03:00:00Z");const t4 = new Date("2024-01-01T04:00:00Z");+// The migration processes projects in lexicographic order. Use IDs that sort+// before UUIDs from concurrently running tests so these fixtures are processed first.+const projectIdA = "00000000-0000-0000-0000-00000000000a";+const projectIdB = "00000000-0000-0000-0000-00000000000b";+const orgIdA = "00000000-0000-0000-0000-0000000000a0";+const orgIdB = "00000000-0000-0000-0000-0000000000b0";const datasetId1 = "dataset-1";const datasetId2 = "dataset-2";const items = [{id: "1",- projectId: "A",+ projectId: projectIdA,validFrom: t0,validTo: null,datasetId: datasetId1,},{id: "1",- projectId: "A",+ projectId: projectIdA,validFrom: t1,validTo: null,datasetId: datasetId1,},{id: "1",- projectId: "A",+ projectId: projectIdA,validFrom: t4,validTo: null,datasetId: datasetId1,},{id: "2",- projectId: "A",+ projectId: projectIdA,validFrom: t2,validTo: null,datasetId: datasetId1,},{id: "3",- projectId: "A",+ projectId: projectIdA,validFrom: t0,validTo: null,datasetId: datasetId1,},{id: "3",- projectId: "A",+ projectId: projectIdA,validFrom: t3,validTo: null,datasetId: datasetId1,},{id: "4",- projectId: "B",+ projectId: projectIdB,validFrom: t4,validTo: null,datasetId: datasetId2,},{id: "5",- projectId: "B",+ projectId: projectIdB,validFrom: t4,validTo: null,datasetId: datasetId2,},{id: "6",- projectId: "B",+ projectId: projectIdB,validFrom: t4,validTo: null,datasetId: datasetId2,},{id: "4",- projectId: "B",+ projectId: projectIdB,validFrom: t1,validTo: null,datasetId: datasetId2,},{id: "1",- projectId: "B",+ projectId: projectIdB,validFrom: t2,validTo: null,datasetId: datasetId2,@@ -93,18 +99,18 @@ const items = [describe("BackfillValidToForDatasetItems", () => {beforeAll(async () => {- // Clean up ALL dataset items to ensure isolated test environment- await prisma.datasetItem.deleteMany({});-// Clean up our test projects if they exist+ await prisma.datasetItem.deleteMany({+ where: { projectId: { in: [projectIdA, projectIdB] } },+ });await prisma.dataset.deleteMany({- where: { projectId: { in: ["A", "B"] } },+ where: { projectId: { in: [projectIdA, projectIdB] } },});await prisma.project.deleteMany({- where: { id: { in: ["A", "B"] } },+ where: { id: { in: [projectIdA, projectIdB] } },});await prisma.organization.deleteMany({- where: { id: { in: ["org-A", "org-B"] } },+ where: { id: { in: [orgIdA, orgIdB] } },});// Create projects first (foreign key requirement)@@ -112,14 +118,14 @@ describe("BackfillValidToForDatasetItems", () => {await prisma.organization.createMany({data: [{- id: "org-A",+ id: orgIdA,name: "Org A",cloudConfig: {plan: "Team",},},{- id: "org-B",+ id: orgIdB,name: "Org B",cloudConfig: {plan: "Team",@@ -130,14 +136,14 @@ describe("BackfillValidToForDatasetItems", () => {await prisma.project.createMany({data: [{- id: "A",+ id: projectIdA,name: "Project A",- orgId: "org-A",+ orgId: orgIdA,},{- id: "B",+ id: projectIdB,name: "Project B",- orgId: "org-B",+ orgId: orgIdB,},],});@@ -145,8 +151,8 @@ describe("BackfillValidToForDatasetItems", () => {// Create datasetsawait prisma.dataset.createMany({data: [- { id: datasetId1, name: "dataset-1", projectId: "A" },- { id: datasetId2, name: "dataset-2", projectId: "B" },+ { id: datasetId1, name: "dataset-1", projectId: projectIdA },+ { id: datasetId2, name: "dataset-2", projectId: projectIdB },],});});@@ -155,7 +161,7 @@ describe("BackfillValidToForDatasetItems", () => {// Clean up dataset items after each test for fresh stateawait prisma.datasetItem.deleteMany({where: {- projectId: { in: ["A", "B"] },+ projectId: { in: [projectIdA, projectIdB] },},});});@@ -168,7 +174,7 @@ describe("BackfillValidToForDatasetItems", () => {// First batch: Process 2 items from project Aconst result1 = await backfillValidToForDatasetItems("", "", 2);expect(result1.completed).toBe(false);- expect(result1.lastProcessedProjectId).toBe("A");+ expect(result1.lastProcessedProjectId).toBe(projectIdA);// Second batch: Process remaining item from project Aconst result2 = await backfillValidToForDatasetItems(@@ -176,7 +182,7 @@ describe("BackfillValidToForDatasetItems", () => {result1.lastProcessedId!,2,);- expect(result2.lastProcessedProjectId).toBe("A");+ expect(result2.lastProcessedProjectId).toBe(projectIdA);// Third batch: Should move to project Bconst result3 = await backfillValidToForDatasetItems(@@ -184,7 +190,7 @@ describe("BackfillValidToForDatasetItems", () => {result2.lastProcessedId!,2,);- expect(result3.lastProcessedProjectId).toBe("B");+ expect(result3.lastProcessedProjectId).toBe(projectIdB);});it("should not get stuck on a single project", async () => {@@ -198,7 +204,7 @@ describe("BackfillValidToForDatasetItems", () => {let iterations = 0;const maxIterations = 10;- while (iterations < maxIterations) {+ while (iterations < maxIterations && lastProjectId !== projectIdB) {const result = await backfillValidToForDatasetItems(lastProjectId,lastId,@@ -213,18 +219,19 @@ describe("BackfillValidToForDatasetItems", () => {iterations++;}- // Should have completed all items without getting stuck+ // Should have advanced from project A to project B without getting stuck.+ expect(lastProjectId).toBe(projectIdB);expect(iterations).toBeLessThan(maxIterations);// Verify all items in project A were processedconst projectAItems = await prisma.datasetItem.findMany({- where: { projectId: "A", validTo: null },+ where: { projectId: projectIdA, validTo: null },});// Only current versions should have validTo = nullconst projectAVersionCounts = await prisma.datasetItem.groupBy({by: ["id"],- where: { projectId: "A" },+ where: { projectId: projectIdA },_count: true,});@@ -235,7 +242,9 @@ describe("BackfillValidToForDatasetItems", () => {it("should use LEAD() correctly - validate version chain order", async () => {// Item with 3 versions at different timesawait prisma.datasetItem.createMany({- data: items.filter((item) => item.id === "1" && item.projectId === "A"),+ data: items.filter(+ (item) => item.id === "1" && item.projectId === projectIdA,+ ),});// Run migration@@ -243,7 +252,7 @@ describe("BackfillValidToForDatasetItems", () => {// Verify the chainconst versions = await prisma.datasetItem.findMany({- where: { id: "1", projectId: "A" },+ where: { id: "1", projectId: projectIdA },orderBy: { validFrom: "asc" },});@@ -269,7 +278,7 @@ describe("BackfillValidToForDatasetItems", () => {let lastId = "";let iterations = 0;- while (iterations < 20) {+ while (iterations < 20 && lastProjectId <= projectIdB) {const result = await backfillValidToForDatasetItems(lastProjectId,lastId,@@ -286,11 +295,12 @@ describe("BackfillValidToForDatasetItems", () => {// Count unique (projectId, id) pairsconst uniqueItems = await prisma.datasetItem.groupBy({by: ["projectId", "id"],+ where: { projectId: { in: [projectIdA, projectIdB] } },});// Count rows with valid_to = null (current versions)const currentVersions = await prisma.datasetItem.count({- where: { validTo: null },+ where: { projectId: { in: [projectIdA, projectIdB] }, validTo: null },});// Should have exactly one current version per unique item@@ -317,7 +327,7 @@ describe("BackfillValidToForDatasetItems", () => {// Items with single version (should not change)const singleVersionItems = items.filter((item) =>- item.projectId === "B" &&+ item.projectId === projectIdB &&(item.id === "5" || item.id === "6" || item.id === "1"),);@@ -331,7 +341,7 @@ describe("BackfillValidToForDatasetItems", () => {// Verify single-version items remain unchanged (valid_to = null)const unchangedItems = await prisma.datasetItem.findMany({where: {- projectId: "B",+ projectId: projectIdB,id: { in: ["5", "6", "1"] },},});@@ -350,28 +360,28 @@ describe("BackfillValidToForDatasetItems", () => {// Item "100": 3 old versions with NULL valid_to (need backfill){id: "100",- projectId: "A",+ projectId: projectIdA,validFrom: t0,validTo: null, // Should be backfilled to t1datasetId: datasetId1,},{id: "100",- projectId: "A",+ projectId: projectIdA,validFrom: t1,validTo: null, // Should be backfilled to t2datasetId: datasetId1,},{id: "100",- projectId: "A",+ projectId: projectIdA,validFrom: t2,validTo: t5, // Already set by new write pathdatasetId: datasetId1,},{id: "100",- projectId: "A",+ projectId: projectIdA,validFrom: t5,validTo: null, // Current version - should stay NULLdatasetId: datasetId1,@@ -379,21 +389,21 @@ describe("BackfillValidToForDatasetItems", () => {// Item "200": mix of old NULL and already-set valid_to{id: "200",- projectId: "A",+ projectId: projectIdA,validFrom: t0,validTo: null, // Should be backfilled to t3datasetId: datasetId1,},{id: "200",- projectId: "A",+ projectId: projectIdA,validFrom: t3,validTo: t6, // Already set by new write pathdatasetId: datasetId1,},{id: "200",- projectId: "A",+ projectId: projectIdA,validFrom: t6,validTo: null, // Current version - should stay NULLdatasetId: datasetId1,@@ -409,7 +419,7 @@ describe("BackfillValidToForDatasetItems", () => {// Verify item "100" chainconst item100Versions = await prisma.datasetItem.findMany({- where: { projectId: "A", id: "100" },+ where: { projectId: projectIdA, id: "100" },orderBy: { validFrom: "asc" },});@@ -421,7 +431,7 @@ describe("BackfillValidToForDatasetItems", () => {// Verify item "200" chainconst item200Versions = await prisma.datasetItem.findMany({- where: { projectId: "A", id: "200" },+ where: { projectId: projectIdA, id: "200" },orderBy: { validFrom: "asc" },});diff --git a/worker/src/__tests__/redisConsumer.test.ts b/worker/src/__tests__/redisConsumer.test.tsindex a386a38275..4f1f747bc5 100644--- a/worker/src/__tests__/redisConsumer.test.ts+++ b/worker/src/__tests__/redisConsumer.test.ts@@ -25,15 +25,19 @@ describe.sequential("handle redis events", () => {expect(traceUpsertQueue).toBeDefined();- const job = await traceUpsertQueue?.add(QueueJobs.TraceUpsert, {- id: randomUUID(),- timestamp: new Date(),- payload: {- projectId: "project-id",- traceId: "trace-id",+ const job = await traceUpsertQueue?.add(+ QueueJobs.TraceUpsert,+ {+ id: randomUUID(),+ timestamp: new Date(),+ payload: {+ projectId: "project-id",+ traceId: "trace-id",+ },+ name: QueueJobs.TraceUpsert as const,},- name: QueueJobs.TraceUpsert as const,- });+ { delay: 0 },+ );await vi.waitFor(async () => {diff --git a/worker/vitest.config.ts b/worker/vitest.config.tsindex 80ed18db8a..2b1f38ed6b 100644--- a/worker/vitest.config.ts+++ b/worker/vitest.config.ts@@ -1,11 +1,16 @@import { config } from "dotenv";import { defineConfig } from "vitest/config";+import { VitestCiReporter } from "../scripts/vitest/ci-reporter";// Load ../.env so direct Vitest runs and package scripts use the same worker env.config({ path: "../.env" });export default defineConfig({test: {+ reporters: process.env.CI+ ? ["default", new VitestCiReporter()]+ : ["default"],+ retry: process.env.CI ? 3 : 0,dir: "./src",pool: "forks",server: {