🪢 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
refactor(web): unify server test layout and CI (#12182)
Max Deichmann77dce36e4085
diff --git a/.cursor/rules/public-api.mdc b/.cursor/rules/public-api.mdcindex da949fbda3..c8decef94e 100644--- a/.cursor/rules/public-api.mdc+++ b/.cursor/rules/public-api.mdc@@ -10,8 +10,8 @@ alwaysApply: false- New api routes should follow these guidelines:- Use [withMiddlewares.ts](mdc:web/src/features/public-api/server/withMiddlewares.ts) as a wrapper- Define types of api request and response in /web/src/features/public-api/types, use strict() for all zod objects- - Add end-to-end test, similar to [datasets-api.servertest.ts](mdc:web/src/__tests__/async/datasets-api.servertest.ts)+ - Add end-to-end test, similar to [datasets-api.servertest.ts](mdc:web/src/__tests__/server/datasets-api.servertest.ts)- Add fern configuration in /fern, learn more about structure here: https://buildwithfern.com/learn/api-definition/fern/overview- Prompt user to regenerate the OpenAPI spec via the fern CLI- Pagination starts at 1, query typing defined in publicApiPaginationZod, return meta in paginationMetaResponseZod-- For tests, please look at [this directory](mdc:web/src/__tests__/async/) for examples+- For tests, please look at [this directory](mdc:web/src/__tests__/server/) for examplesdiff --git a/.cursor/rules/tests.mdc b/.cursor/rules/tests.mdcindex 3f0dd71d6e..c32a800da1 100644--- a/.cursor/rules/tests.mdc+++ b/.cursor/rules/tests.mdc@@ -6,4 +6,4 @@ alwaysApply: true# Writing tests- When writing tests, focus on decoupling each `it` or `test` block to ensure that they can run independently and concurrently. Tests must never depend on the action or outcome of previous or subsequent tests.-- When writing tests, especially in the __tests__/async directory, ensure that you avoid `pruneDatabase` calls.\ No newline at end of file+- When writing tests, especially in the __tests__/server directory, ensure that you avoid `pruneDatabase` calls.diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 26b871a5e6..b1f95a91cd 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -157,120 +157,13 @@ jobs:run: |timeout 10 bash -c 'until curl -f http://localhost:3000/api/public/health; do sleep 2; done'- tests-web-sync:+ tests-web:timeout-minutes: 30runs-on: ubuntu-latestneeds:- pre-jobif: needs.pre-job.outputs.should_skip != 'true'- name: tests-web-sync (node${{ matrix.node-version }}, pg${{ matrix.postgres-version }})- strategy:- matrix:- node-version: [24]- postgres-version: [12, 15]- steps:- - uses: actions/checkout@v4- - name: Install golang-migrate for Clickhouse migrations- run: |- curl -L https://github.com/golang-migrate/migrate/releases/download/v4.19.1/migrate.linux-amd64.tar.gz | tar xvz- sudo mv migrate /usr/bin/migrate- which migrate- - uses: pnpm/action-setup@v3- with:- version: 9.5.0- - name: Login to Docker Hub- if: github.repository == 'langfuse/langfuse' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)- uses: docker/login-action@v3- with:- username: ${{ secrets.DOCKERHUB_USERNAME_READ }}- password: ${{ secrets.DOCKERHUB_TOKEN_READ }}- - name: Use Node.js ${{ matrix.node-version }}- uses: actions/setup-node@v4- with:- node-version: ${{ matrix.node-version }}- cache: "pnpm"- cache-dependency-path: "pnpm-lock.yaml"- - name: install dependencies- run: |- pnpm install- - name: Load default env- run: |- cp .env.dev.example .env- grep -v -e '^LANGFUSE_S3_BATCH_EXPORT_ENABLED=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev.example > .env- echo "LANGFUSE_INGESTION_QUEUE_DELAY_MS=1" >> .env- echo "LANGFUSE_CACHE_PROMPT_ENABLED=false" >> .env- echo "LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=1" >> .env- - name: Setup Turbo cache- uses: actions/cache@v4- with:- path: .turbo- key: ${{ runner.os }}-turbo-${{ github.sha }}- restore-keys: |- ${{ runner.os }}-turbo-- - name: Cache Next.js builds- uses: actions/cache@v4- with:- path: |- ~/.npm- ${{ github.workspace }}/web/.next/cache- key: ${{ runner.os }}-nextjs-${{ matrix.node-version }}-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ hashFiles('web/**/*.js', 'web/**/*.jsx', 'web/**/*.ts', 'web/**/*.tsx') }}- restore-keys: |- ${{ runner.os }}-nextjs-${{ matrix.node-version }}-${{ hashFiles('**/pnpm-lock.yaml') }}-- ${{ runner.os }}-nextjs-${{ matrix.node-version }}-- - name: Run dev containers- run: |- docker compose -f docker-compose.dev.yml up -d- sleep 5 # Wait for PostgreSQL to accept connections- docker compose ps- env:- POSTGRES_VERSION: ${{ matrix.postgres-version }}- - name: Migrate DB- run: |- pnpm run db:migrate- pnpm --filter=shared ch:up- - name: Download and extract ClickHouse client for dev-tables setup- run: |- CH_VERSION="24.9.3.128"- ARCH="amd64"- wget "https://packages.clickhouse.com/deb/pool/main/c/clickhouse/clickhouse-common-static_${CH_VERSION}_${ARCH}.deb" -O clickhouse-client.deb-- # The binary is usually located in ./usr/bin/clickhouse in the archive- dpkg-deb -x clickhouse-client.deb ch_client_dir- sudo cp ch_client_dir/usr/bin/clickhouse /usr/local/bin/- - name: Setup Dev Tables- run: |- pnpm --filter=shared ch:dev-tables- - name: Build- run: pnpm run build- env:- NODE_OPTIONS: --max_old_space_size=8192- - name: Start Langfuse- run: (pnpm run start&)- env:- LANGFUSE_INIT_ORG_ID: "seed-org-id"- LANGFUSE_INIT_ORG_NAME: "Seed Org"- LANGFUSE_INIT_ORG_CLOUD_PLAN: "Team"- LANGFUSE_INIT_PROJECT_ID: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a"- LANGFUSE_INIT_PROJECT_NAME: "Seed Project"- LANGFUSE_INIT_PROJECT_PUBLIC_KEY: "pk-lf-1234567890"- LANGFUSE_INIT_PROJECT_SECRET_KEY: "sk-lf-1234567890"- LANGFUSE_INIT_USER_EMAIL: "[email protected]"- LANGFUSE_INIT_USER_NAME: "Demo User"- LANGFUSE_INIT_USER_PASSWORD: "password"- - name: run test-sync- working-directory: web- run: npx cross-env NODE_OPTIONS='--no-experimental-require-module' npx dotenv -e ../.env.test -e ../.env -- npx jest --verbose --runInBand --detectOpenHandles --selectProjects sync-server- - name: run test-client- working-directory: web- run: npx cross-env NODE_OPTIONS='--no-experimental-require-module' npx dotenv -e ../.env.test -e ../.env -- npx jest --verbose --runInBand --detectOpenHandles --selectProjects client-- tests-web-async:- timeout-minutes: 30- runs-on: ubuntu-latest- needs:- - pre-job- if: needs.pre-job.outputs.should_skip != 'true'- name: tests-web-async (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 }}, shard${{ matrix.shard }}/3)strategy:matrix:node-version: [24]@@ -307,6 +200,7 @@ jobs:cp .env.dev${{ matrix.deploy-mode }}.example .envgrep -v -e '^LANGFUSE_S3_BATCH_EXPORT_ENABLED=' -e '^NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT=' .env.dev${{ matrix.deploy-mode }}.example > .envecho "LANGFUSE_INGESTION_QUEUE_DELAY_MS=1" >> .env+ echo "LANGFUSE_CACHE_PROMPT_ENABLED=false" >> .envecho "LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=1" >> .envecho "LANGFUSE_TRACE_DELETE_CONCURRENCY=100" >> .envecho "ADMIN_API_KEY=admin-api-key" >> .env@@ -324,10 +218,10 @@ jobs:path: |~/.npm${{ github.workspace }}/web/.next/cache- key: ${{ runner.os }}-nextjs-async-${{ matrix.node-version }}-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ hashFiles('web/**/*.js', 'web/**/*.jsx', 'web/**/*.ts', 'web/**/*.tsx') }}+ key: ${{ runner.os }}-nextjs-web-${{ matrix.node-version }}-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ hashFiles('web/**/*.js', 'web/**/*.jsx', 'web/**/*.ts', 'web/**/*.tsx') }}restore-keys: |- ${{ runner.os }}-nextjs-async-${{ matrix.node-version }}-${{ hashFiles('**/pnpm-lock.yaml') }}-- ${{ runner.os }}-nextjs-async-${{ matrix.node-version }}-+ ${{ runner.os }}-nextjs-web-${{ matrix.node-version }}-${{ hashFiles('**/pnpm-lock.yaml') }}-+ ${{ runner.os }}-nextjs-web-${{ matrix.node-version }}-- name: Run dev containersrun: |docker compose -f docker-compose.dev${{ matrix.deploy-mode }}.yml up -d@@ -372,7 +266,11 @@ jobs:LANGFUSE_INIT_USER_PASSWORD: "password"- name: run testsworking-directory: web- run: npx cross-env NODE_OPTIONS='--no-experimental-require-module' npx dotenv -e ../.env.test -e ../.env -- npx jest --verbose --runInBand --detectOpenHandles --selectProjects async-server --shard=${{ matrix.shard }}/3+ run: npx cross-env NODE_OPTIONS='--no-experimental-require-module' npx dotenv -e ../.env.test -e ../.env -- npx jest --verbose --runInBand --detectOpenHandles --selectProjects server --shard=${{ matrix.shard }}/3+ - name: run test-client+ if: matrix.deploy-mode == '' && matrix.shard == 1+ working-directory: web+ run: npx cross-env NODE_OPTIONS='--no-experimental-require-module' npx dotenv -e ../.env.test -e ../.env -- npx jest --verbose --runInBand --detectOpenHandles --selectProjects clienttests-worker:timeout-minutes: 20@@ -674,13 +572,12 @@ jobs:[lint,prettier-check,- tests-web-sync,+ tests-web,tests-worker,test-worker-llm-connections,# e2e-tests, # Temporarily disabled - flaky timeoutstest-docker-build,e2e-server-tests,- tests-web-async,]if: always()outputs:diff --git a/AGENTS.md b/AGENTS.mdindex 1843ab476f..285d88ae02 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -9,7 +9,7 @@ Langfuse is an **open source LLM engineering** platform for developing, monitori## Tests- Codex cannot run the test suite because it depends on Docker-based infrastructure that is unavailable in this environment.- When writing tests, focus on decoupling each `it` or `test` block to ensure that they can run independently and concurrently. Tests must never depend on the action or outcome of previous or subsequent tests.-- When writing tests, especially in the __tests__/async directory, ensure that you avoid `pruneDatabase` calls.+- When writing tests, especially in the __tests__/server directory, ensure that you avoid `pruneDatabase` calls.## Cursor Rules- Additional folder-specific rules live in `.cursor/rules/`.diff --git a/CLAUDE.md b/CLAUDE.mdindex c8055dd530..37c22919d4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -81,12 +81,9 @@ pnpm build:check # Full Next.js build to alternate dir (can### Testing in Web PackageThe web package uses JEST for unit tests.-Depending on the file location (sync, async)`web` related tests must go into the `web/src/__tests__/` folder.```sh-pnpm test-sync --testPathPatterns="$FILE_LOCATION_PATTERN" --testNamePattern="$TEST_NAME_PATTERN"-# For tests in the async folder:-pnpm test -- --testPathPatterns="$FILE_LOCATION_PATTERN" --testNamePattern="$TEST_NAME_PATTERN"+pnpm test --testPathPatterns="$FILE_LOCATION_PATTERN" --testNamePattern="$TEST_NAME_PATTERN"# For client tests:pnpm test-client --testPathPatterns="buildStepData" --testNamePattern="buildStepData"```@@ -159,7 +156,7 @@ pnpm run nuke # Remove all node_modules, build files, wipe database- For backend/API changes, tests must pass before pushes- Add tests for new API endpoints and features- When writing tests, focus on decoupling each `it` or `test` block to ensure that they can run independently and concurrently. Tests must never depend on the action or outcome of previous or subsequent tests.-- When writing tests, especially in the __tests__/async directory, ensure that you avoid `pruneDatabase` calls.+- When writing tests, especially in the __tests__/server directory, ensure that you avoid `pruneDatabase` calls.### Code Conventions- **Pages Router** (not App Router)diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex de5082027b..8f62d793ba 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -244,19 +244,16 @@ Tests automatically create the PostgreSQL test database if it doesn't exist andWe're using Jest with in the `web` package. Therefore, if you want to provide an argument to the test runner, do it directly without an intermittent `--`.-There are three types of unit tests:--- `test-sync`-- `test` (for async folder tests)-- `test-client`+There are two types of unit tests:++- `test` (server tests)+- `test-client`To run a specific test, for example the test: `"should handle special characters in prompt names"` in `prompts.v2.servertest.ts`, run:```sh-cd web # or with --filter=web-pnpm test-sync --testPathPatterns="prompts\.v2\.servertest" --testNamePattern="should handle special characters in prompt names"-# for async folder tests:-pnpm test -- --testPathPatterns="observations-api" --testNamePattern="should fetch all observations"+cd web # or with --filter=web+pnpm test --testPathPatterns="prompts\.v2\.servertest" --testNamePattern="should handle special characters in prompt names"```To run all tests:diff --git a/packages/shared/src/server/auth/invalidateApiKeys.ts b/packages/shared/src/server/auth/invalidateApiKeys.tsindex 153716cab3..4f6f940792 100644--- a/packages/shared/src/server/auth/invalidateApiKeys.ts+++ b/packages/shared/src/server/auth/invalidateApiKeys.ts@@ -1,6 +1,7 @@import { prisma } from "../../db";import { redis, safeMultiDel } from "..";import { logger } from "../logger";+import type { Cluster, Redis } from "ioredis";import { type ApiKey } from "../../db";@@ -22,6 +23,7 @@ import { type ApiKey } from "../../db";export async function invalidateCachedApiKeys(apiKeys: ApiKey[],identifier: string,+ redisClient: Redis | Cluster | null = redis,) {const hashKeys = apiKeys.map((key) => key.fastHashedSecretKey);@@ -33,10 +35,10 @@ export async function invalidateCachedApiKeys(return;}- if (redis) {+ if (redisClient) {logger.info(`Invalidating API keys in redis for ${identifier}`);const keysToDelete = filteredHashKeys.map((hash) => `api-key:${hash}`);- await safeMultiDel(redis, keysToDelete);+ await safeMultiDel(redisClient, keysToDelete);}}@@ -53,7 +55,10 @@ export async function invalidateCachedApiKeys(** @param orgId - The organization ID whose API keys should be invalidated from cache*/-export async function invalidateCachedOrgApiKeys(orgId: string): Promise<void> {+export async function invalidateCachedOrgApiKeys(+ orgId: string,+ redisClient: Redis | Cluster | null = redis,+): Promise<void> {const apiKeys = await prisma.apiKey.findMany({where: {OR: [@@ -76,10 +81,10 @@ export async function invalidateCachedOrgApiKeys(orgId: string): Promise<void> {return;}- if (redis) {+ if (redisClient) {logger.info(`Invalidating API keys in redis for org ${orgId}`);const keysToDelete = hashKeys.map((hash) => `api-key:${hash}`);- await safeMultiDel(redis, keysToDelete);+ await safeMultiDel(redisClient, keysToDelete);}}@@ -94,6 +99,7 @@ export async function invalidateCachedOrgApiKeys(orgId: string): Promise<void> {*/export async function invalidateCachedProjectApiKeys(projectId: string,+ redisClient: Redis | Cluster | null = redis,): Promise<void> {const apiKeys = await prisma.apiKey.findMany({where: {@@ -111,9 +117,9 @@ export async function invalidateCachedProjectApiKeys(return;}- if (redis) {+ if (redisClient) {logger.info(`Invalidating API keys in redis for project ${projectId}`);const keysToDelete = hashKeys.map((hash) => `api-key:${hash}`);- await safeMultiDel(redis, keysToDelete);+ await safeMultiDel(redisClient, keysToDelete);}}diff --git a/packages/shared/src/server/clickhouse/clickhouse-logger.ts b/packages/shared/src/server/clickhouse/clickhouse-logger.tsindex a43e8e94b7..0effe315ac 100644--- a/packages/shared/src/server/clickhouse/clickhouse-logger.ts+++ b/packages/shared/src/server/clickhouse/clickhouse-logger.ts@@ -8,11 +8,11 @@ import { logger as winstonLogger } from "../logger";*/export class ClickHouseLogger implements Logger {trace({ module, message, args }: LogParams): void {- winstonLogger.info(`[${module}] ${message}`, args);+ winstonLogger.debug(`[${module}] ${message}`, args);}debug({ module, message, args }: LogParams): void {- winstonLogger.info(`[${module}] ${message}`, args);+ winstonLogger.debug(`[${module}] ${message}`, args);}info({ module, message, args }: LogParams): void {diff --git a/web/jest.config.mjs b/web/jest.config.mjsindex 2d782fb576..2d01136854 100644--- a/web/jest.config.mjs+++ b/web/jest.config.mjs@@ -14,19 +14,9 @@ const clientTestConfig = {};const serverTestConfig = {- displayName: "sync-server",- testMatch: ["/**/*.servertest.[jt]s?(x)"],- testPathIgnorePatterns: ["async", "__e2e__"],- testEnvironment: "jest-environment-node",- testEnvironmentOptions: { globalsCleanup: "on" },- setupFilesAfterEnv: ["<rootDir>/src/__tests__/after-teardown.ts"],- globalTeardown: "<rootDir>/src/__tests__/teardown.ts",-};--const asyncServerTestConfig = {- displayName: "async-server",+ displayName: "server",testPathIgnorePatterns: ["__e2e__"],- testMatch: ["/**/async/**/*.servertest.[jt]s?(x)"],+ testMatch: ["/**/server/**/*.servertest.[jt]s?(x)"],testEnvironment: "jest-environment-node",testEnvironmentOptions: { globalsCleanup: "on" },setupFilesAfterEnv: ["<rootDir>/src/__tests__/after-teardown.ts"],@@ -69,12 +59,6 @@ const config = {`/web/node_modules/(?!(${esModules.join("|")})/)`,],},- {- ...(await createJestConfig(asyncServerTestConfig)()),- transformIgnorePatterns: [- `/web/node_modules/(?!(${esModules.join("|")})/)`,- ],- },{...(await createJestConfig(endToEndServerTestConfig)()),transformIgnorePatterns: [diff --git a/web/package.json b/web/package.jsonindex ffef0b368c..db41ea86a4 100644--- a/web/package.json+++ b/web/package.json@@ -16,13 +16,12 @@"lint:fix": "dotenv -e ../.env -- eslint . --cache --cache-location .next/cache/eslint/ --fix","clean": "rm -rf node_modules","start": "dotenv -e ../.env -- sh -c 'NEXT_MANUAL_SIG_HANDLE=true next start'",- "test": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --runInBand --selectProjects async-server",- "test-sync": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --runInBand --selectProjects sync-server",+ "test": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --runInBand --selectProjects server","test-client": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --selectProjects client","test:watch": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --watch --runInBand","test:e2e": "dotenv -e ../.env.test -e ../.env -- playwright test --reporter=line","test:e2e:server": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --runInBand --verbose --selectProjects e2e-server",- "test:debug-handles": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --runInBand --detectOpenHandles --selectProjects async-server",+ "test:debug-handles": "cross-env NODE_OPTIONS='--no-experimental-require-module' dotenv -e ../.env.test -e ../.env -- jest --verbose --runInBand --detectOpenHandles --selectProjects server","build-trace": "dotenv -e ../.env -- next internal trace .next/trace-turbopack"},"dependencies": {diff --git a/web/src/__tests__/posthog-integration.servertest.ts b/web/src/__tests__/posthog-integration.servertest.tsdeleted file mode 100644index e9f3f5281f..0000000000--- a/web/src/__tests__/posthog-integration.servertest.ts+++ /dev/null@@ -1,74 +0,0 @@-/** @jest-environment node */--import type { Session } from "next-auth";-import { pruneDatabase } from "@/src/__tests__/test-utils";-import { prisma } from "@langfuse/shared/src/db";-import { appRouter } from "@/src/server/api/root";-import { createInnerTRPCContext } from "@/src/server/api/trpc";--describe("PostHog Integration SSRF Protection", () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";- const originalEncryptionKey = process.env.ENCRYPTION_KEY;-- beforeAll(() => {- // Set a test encryption key (64 hex characters = 32 bytes)- process.env.ENCRYPTION_KEY =- "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";- });-- afterAll(() => {- // Restore original environment- process.env.ENCRYPTION_KEY = originalEncryptionKey;- });-- beforeEach(async () => await pruneDatabase());-- const session: Session = {- expires: "1",- user: {- id: "user-1",- name: "Demo User",- canCreateOrganizations: true,- organizations: [- {- id: "seed-org-id",- role: "OWNER",- plan: "cloud:hobby",- cloudConfig: undefined,- name: "Test Organization",- metadata: {},- projects: [- {- id: projectId,- role: "ADMIN",- name: "Test Project",- deletedAt: null,- retentionDays: null,- metadata: {},- },- ],- },- ],- featureFlags: {- templateFlag: true,- excludeClickhouseRead: false,- },- admin: true,- },- environment: {} as any,- };-- const ctx = createInnerTRPCContext({ session, headers: {} });- const caller = appRouter.createCaller({ ...ctx, prisma });-- it("should reject private IPs and localhost in PostHog hostname", async () => {- await expect(- caller.posthogIntegration.update({- projectId,- posthogHostname: "http://localhost",- posthogProjectApiKey: "phc_test_key_12345",- enabled: true,- }),- ).rejects.toThrow(/Invalid PostHog hostname.*Blocked/);- });-});diff --git a/web/src/__tests__/admin-api-key-auth.servertest.ts b/web/src/__tests__/server/admin-api-key-auth.servertest.tssimilarity index 100%rename from web/src/__tests__/admin-api-key-auth.servertest.tsrename to web/src/__tests__/server/admin-api-key-auth.servertest.tsdiff --git a/web/src/__tests__/async/annotation-queue-assignments-api.servertest.ts b/web/src/__tests__/server/annotation-queue-assignments-api.servertest.tssimilarity index 98%rename from web/src/__tests__/async/annotation-queue-assignments-api.servertest.tsrename to web/src/__tests__/server/annotation-queue-assignments-api.servertest.tsindex c805543c76..fca3584fc5 100644--- a/web/src/__tests__/async/annotation-queue-assignments-api.servertest.ts+++ b/web/src/__tests__/server/annotation-queue-assignments-api.servertest.ts@@ -3,7 +3,6 @@import {makeZodVerifiedAPICall,makeAPICall,- pruneDatabase,} from "@/src/__tests__/test-utils";import { prisma } from "@langfuse/shared/src/db";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";@@ -21,7 +20,7 @@ describe("/api/public/annotation-queues/:queueId/assignments API", () => {let testUserId: string;let secondTestUserId: string;- beforeAll(async () => {+ beforeEach(async () => {const {auth: newAuth,projectId: newProjectId,@@ -104,10 +103,6 @@ describe("/api/public/annotation-queues/:queueId/assignments API", () => {});});- afterAll(async () => {- await pruneDatabase();- });-describe("POST /api/public/annotation-queues/:queueId/assignments", () => {it("should create annotation queue assignment successfully", async () => {const response = await makeZodVerifiedAPICall(diff --git a/web/src/__tests__/annotation-queues-api.servertest.ts b/web/src/__tests__/server/annotation-queues-api.servertest.tssimilarity index 99%rename from web/src/__tests__/annotation-queues-api.servertest.tsrename to web/src/__tests__/server/annotation-queues-api.servertest.tsindex 3a154c4632..73c298d2b3 100644--- a/web/src/__tests__/annotation-queues-api.servertest.ts+++ b/web/src/__tests__/server/annotation-queues-api.servertest.ts@@ -4,7 +4,6 @@ import { prisma } from "@langfuse/shared/src/db";import {makeZodVerifiedAPICall,makeAPICall,- pruneDatabase,} from "@/src/__tests__/test-utils";import {GetAnnotationQueuesResponse,@@ -31,7 +30,7 @@ describe("Annotation Queues API Endpoints", () => {const TOTAL_TEST_QUEUES = 15; // Create enough queues to test paginationconst TOTAL_TEST_QUEUE_ITEMS = 20; // Create enough queue items to test pagination- beforeAll(async () => {+ beforeEach(async () => {// Create organization, project, and API key for testingconst { auth: newAuth, projectId: newProjectId } =await createOrgProjectAndApiKey();@@ -90,10 +89,6 @@ describe("Annotation Queues API Endpoints", () => {queueItemId = queueItems[0].id; // Use the first queue item for specific tests});- afterAll(async () => {- await pruneDatabase();- });-describe("GET /annotation-queues", () => {it("should get all annotation queues", async () => {const response = await makeZodVerifiedAPICall(@@ -205,6 +200,15 @@ 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,+ },+ });+const response = await makeAPICall("POST","/api/public/annotation-queues",diff --git a/web/src/__tests__/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.tssimilarity index 68%rename from web/src/__tests__/api-auth.servertest.tsrename to web/src/__tests__/server/api-auth.servertest.tsindex 05866a817d..7160a0e820 100644--- a/web/src/__tests__/api-auth.servertest.ts+++ b/web/src/__tests__/server/api-auth.servertest.ts@@ -1,52 +1,110 @@import {- getDisplaySecretKey,- hashSecretKey,OrgEnrichedApiKey,+ createBasicAuthHeader,+ createOrgProjectAndApiKey,} from "@langfuse/shared/src/server";import { Prisma, type PrismaClient, prisma } from "@langfuse/shared/src/db";-import { Redis } from "ioredis";import { env } from "@/src/env.mjs";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { v4 } from "uuid";+import {+ clearRedisKeysByPatternSafely,+ createRedisTestClient,+ ensureRedisReady,+ getRedisKeysByPattern,+ getRedisTtl,+ getRedisValue,+ setRedisValue,+ type RedisTestClient,+} from "@/src/__tests__/server/redis-test-utils";describe("Authenticate API calls", () => {+ type TestApiKeyFixture = {+ id: string;+ auth: string;+ publicKey: string;+ secretKey: string;+ orgId: string;+ projectId: string;+ note: string;+ };++ let testApiKey: TestApiKeyFixture;++ const createRedisClient = (): RedisTestClient => {+ return createRedisTestClient({+ maxRetriesPerRequest: null,+ });+ };++ const getValidAuthHeader = () => testApiKey.auth;++ const getInvalidAuthHeader = () =>+ createBasicAuthHeader(+ testApiKey.publicKey,+ `${testApiKey.secretKey}-wrong`,+ );++ const createMissingAuthHeader = () =>+ createBasicAuthHeader(`pk-missing-${v4()}`, `sk-missing-${v4()}`);++ const getApiKeyCacheKeys = async (+ redisClient: RedisTestClient,+ pattern = "api-key*",+ ) => {+ return await getRedisKeysByPattern(redisClient, pattern);+ };++ const clearApiKeyCacheSafely = async (redisClient: RedisTestClient) => {+ await clearRedisKeysByPatternSafely(redisClient, "api-key*");+ };+beforeEach(async () => {- await prisma.apiKey.deleteMany();- });- afterEach(async () => {- await prisma.apiKey.deleteMany();+ const fixture = await createOrgProjectAndApiKey({ plan: "Hobby" });+ const note = "seeded key";+ const createdApiKey = await prisma.apiKey.findUniqueOrThrow({+ where: { publicKey: fixture.publicKey },+ });+ await prisma.apiKey.update({+ where: { id: createdApiKey.id },+ data: { note },+ });+ testApiKey = {+ id: createdApiKey.id,+ auth: fixture.auth,+ publicKey: fixture.publicKey,+ secretKey: fixture.secretKey,+ orgId: fixture.orgId,+ projectId: fixture.projectId,+ note,+ };});describe("validates without redis", () => {it("should create new api key", async () => {- await createAPIKey();const auth = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(auth.validKey).toBe(true);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).not.toBeNull();});it("should create new api key and succeed with new key", async () => {- await createAPIKey();const auth = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(auth.validKey).toBe(true);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).not.toBeNull();@@ -54,18 +112,14 @@ describe("Authenticate API calls", () => {const auth2 = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(auth2.validKey).toBe(true);});it("should create new api key with stripe data and succeed with new key", async () => {- await createAPIKey();-await prisma.organization.update({where: {- id: "seed-org-id",+ id: testApiKey.orgId,},data: {cloudConfig: {@@ -79,32 +133,30 @@ describe("Authenticate API calls", () => {});await new ApiAuthService(prisma, null).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);const auth = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(auth.validKey).toBe(true);if (auth.validKey) {- expect(auth.scope.orgId).toBe("seed-org-id");+ expect(auth.scope.orgId).toBe(testApiKey.orgId);expect(auth.scope.plan).toBe("cloud:hobby");expect(auth.scope.rateLimitOverrides).toEqual([]);}const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).not.toBeNull();await prisma.organization.update({where: {- id: "seed-org-id",+ id: testApiKey.orgId,},data: {cloudConfig: Prisma.JsonNull,@@ -113,11 +165,9 @@ describe("Authenticate API calls", () => {});it("should create new api key with custom rate limits and succeed with new key", async () => {- await createAPIKey();-await prisma.organization.update({where: {- id: "seed-org-id",+ id: testApiKey.orgId,},data: {cloudConfig: {@@ -133,19 +183,17 @@ describe("Authenticate API calls", () => {});await new ApiAuthService(prisma, null).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);const auth = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(auth.validKey).toBe(true);if (auth.validKey) {- expect(auth.scope.orgId).toBe("seed-org-id");+ expect(auth.scope.orgId).toBe(testApiKey.orgId);expect(auth.scope.plan).toBe("cloud:hobby");expect(auth.scope.rateLimitOverrides).toEqual([{@@ -157,14 +205,14 @@ describe("Authenticate API calls", () => {}const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).not.toBeNull();await prisma.organization.update({where: {- id: "seed-org-id",+ id: testApiKey.orgId,},data: {cloudConfig: Prisma.JsonNull,@@ -173,17 +221,14 @@ describe("Authenticate API calls", () => {});it("should fail on wrong api key with new key", async () => {- await createAPIKey();const auth = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(auth.validKey).toBe(true);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();@@ -192,16 +237,13 @@ describe("Authenticate API calls", () => {const wrongAuth = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",- );+ ).verifyAuthHeaderAndReturnScope(getInvalidAuthHeader());expect(wrongAuth.validKey).toBe(false);});it("should fail on wrong api key without new key", async () => {- await createAPIKey();const initialApiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(initialApiKey).not.toBeNull();expect(initialApiKey?.fastHashedSecretKey).toBeNull();@@ -209,13 +251,11 @@ describe("Authenticate API calls", () => {const auth = await new ApiAuthService(prisma,null,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",- );+ ).verifyAuthHeaderAndReturnScope(getInvalidAuthHeader());expect(auth.validKey).toBe(false);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).toBeNull();@@ -223,39 +263,37 @@ describe("Authenticate API calls", () => {});describe("validates with redis", () => {- const redis = new Redis("redis://:[email protected]:6379", {- maxRetriesPerRequest: null,- });+ let redis: RedisTestClient;++ beforeAll(async () => {+ redis = createRedisClient();+ await ensureRedisReady(redis);+ }, 20_000);beforeEach(async () => {+ if (redis.status === "close" || redis.status === "end") {+ redis = createRedisClient();+ }+ await ensureRedisReady(redis);// if we do not remove the key, it will remain in the cache and// calling the test twice will not add the key to the cache-- const keys = await redis.keys("api-key*");- if (keys.length > 0) {- await redis.del(keys);- }- });+ await clearApiKeyCacheSafely(redis);+ }, 20_000);afterEach(async () => {// if we do not remove the key, it will remain in the cache and// calling the test twice will not add the key to the cache- const keys = await redis.keys("api-key*");- if (keys.length > 0) {- await redis.del(keys);- }- });+ await clearApiKeyCacheSafely(redis);+ }, 20_000);- afterAll(async () => {+ afterAll(() => {redis.disconnect();- });+ }, 20_000);it("should create new api key and read from cache", async () => {- await createAPIKey();-// update the organization with a cloud configawait prisma.organization.update({- where: { id: "seed-org-id" },+ where: { id: testApiKey.orgId },data: {cloudConfig: {rateLimitOverrides: [@@ -274,27 +312,29 @@ describe("Authenticate API calls", () => {// first auth will generate the fast hashed api keyawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).not.toBeNull();- const cachedKey = await redis.get(+ const cachedKey = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);expect(cachedKey).toBeNull();// second will add the key to redisawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);- const cachedKey2 = await redis.get(+ const cachedKey2 = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);@@ -304,7 +344,7 @@ describe("Authenticate API calls", () => {expect(parsed).toEqual({...apiKey,- orgId: "seed-org-id",+ orgId: testApiKey.orgId,plan: "cloud:hobby",rateLimitOverrides: [{@@ -321,7 +361,7 @@ describe("Authenticate API calls", () => {});await prisma.organization.update({- where: { id: "seed-org-id" },+ where: { id: testApiKey.orgId },data: {cloudConfig: Prisma.JsonNull,},@@ -329,11 +369,9 @@ describe("Authenticate API calls", () => {});it("should handle non-scoped key format gracefully and fallback to prisma", async () => {- await createAPIKey();-// update the organization with a cloud configawait prisma.organization.update({- where: { id: "seed-org-id" },+ where: { id: testApiKey.orgId },data: {cloudConfig: {rateLimitOverrides: [@@ -352,11 +390,11 @@ describe("Authenticate API calls", () => {// first auth will generate the fast hashed api keyawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();@@ -366,29 +404,29 @@ describe("Authenticate API calls", () => {const nonScopedKey = {id: "seed-api-key",note: "seeded key",- publicKey: "pk-lf-1234567890",+ publicKey: testApiKey.publicKey,displaySecretKey: "sk-lf-...7890",createdAt: new Date().toISOString(),lastUsedAt: null,expiresAt: null,fastHashedSecretKey: apiKey?.fastHashedSecretKey,hashedSecretKey: apiKey?.hashedSecretKey,- orgId: "seed-org-id",+ orgId: testApiKey.orgId,plan: "cloud:team",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId: testApiKey.projectId,// scope property is intentionally missing};// Add the non-scoped key to Redis- await redis.set(+ await setRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,JSON.stringify(nonScopedKey),- "EX",- 3600, // 1 hour TTL);// Verify the key is in Redis- const cachedKey = await redis.get(+ const cachedKey = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);expect(cachedKey).not.toBeNull();@@ -402,14 +440,13 @@ describe("Authenticate API calls", () => {const verification = await new ApiAuthService(prisma,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(verification.validKey).toBe(true);// The invalid key should be removed from Redis- const cachedKeyAfterAuth = await redis.get(+ const cachedKeyAfterAuth = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);@@ -421,10 +458,10 @@ describe("Authenticate API calls", () => {expect(parsed).toEqual({...apiKey,- orgId: "seed-org-id",+ orgId: testApiKey.orgId,plan: "cloud:hobby",scope: "PROJECT", // Now the scope is present- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId: testApiKey.projectId,rateLimitOverrides: [{resource: "public-api",@@ -440,7 +477,7 @@ describe("Authenticate API calls", () => {});await prisma.organization.update({- where: { id: "seed-org-id" },+ where: { id: testApiKey.orgId },data: {cloudConfig: Prisma.JsonNull,},@@ -449,56 +486,50 @@ describe("Authenticate API calls", () => {it("searching for non-existing key stores flag in redis and fails auth", async () => {// key does not exist in database+ const missingAuthHeader = createMissingAuthHeader();const verification = await new ApiAuthService(prisma,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(missingAuthHeader);expect(verification.validKey).toBe(false);- const redisKeys = await redis.keys(`api-key:*`);+ const redisKeys = await getApiKeyCacheKeys(redis, "api-key:*");expect(redisKeys.length).toBe(1);- const redisValue = await redis.get(redisKeys[0]);+ const redisValue = await getRedisValue(redis, redisKeys[0]);expect(redisValue).toBe('"api-key-non-existent"');});it("searching for non-existing key again fails auth", async () => {// key does not exist in database+ const missingAuthHeader = createMissingAuthHeader();const verification = await new ApiAuthService(prisma,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(missingAuthHeader);expect(verification.validKey).toBe(false);- const redisKeys = await redis.keys(`api-key:*`);+ const redisKeys = await getApiKeyCacheKeys(redis, "api-key:*");expect(redisKeys.length).toBe(1);- const redisValue = await redis.get(redisKeys[0]);+ const redisValue = await getRedisValue(redis, redisKeys[0]);expect(redisValue).toBe('"api-key-non-existent"');const verification2 = await new ApiAuthService(prisma,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(missingAuthHeader);expect(verification2.validKey).toBe(false);- const redisKeys2 = await redis.keys(`api-key:*`);+ const redisKeys2 = await getApiKeyCacheKeys(redis, "api-key:*");expect(redisKeys2.length).toBe(1);- const redisValue2 = await redis.get(redisKeys[0]);+ const redisValue2 = await getRedisValue(redis, redisKeys[0]);expect(redisValue2).toBe('"api-key-non-existent"');});it("prisma should not be used when reading cached keys", async () => {- await createAPIKey();-// Mock prismaconst mockPrisma = {apiKey: {@@ -508,32 +539,35 @@ describe("Authenticate API calls", () => {// first auth will generate the fast hashed api keyawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);// second will add the key to redisconst auth2 = await new ApiAuthService(prisma,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());// third will read from redis onlyawait new ApiAuthService(mockPrisma as unknown as PrismaClient,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(auth2.validKey).toBe(true);+ const apiKey = await prisma.apiKey.findUnique({+ where: { publicKey: testApiKey.publicKey },+ });+ expect(apiKey).not.toBeNull();+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();+// Ensure prisma was not calledexpect(mockPrisma.apiKey.findUnique).not.toHaveBeenCalled();- const cachedKey = await redis.get(- "api-key:ed6818ada09bdad405a74ac72773dde1708dd3fc6fe8bb81b59927400419d227",+ const cachedKey = await getRedisValue(+ redis,+ `api-key:${apiKey?.fastHashedSecretKey}`,);expect(cachedKey).not.toBeNull();@@ -542,7 +576,7 @@ describe("Authenticate API calls", () => {expect(parsed).toEqual({id: expect.any(String),note: "seeded key",- publicKey: "pk-lf-1234567890",+ publicKey: testApiKey.publicKey,hashedSecretKey: expect.any(String),fastHashedSecretKey: expect.any(String),displaySecretKey: expect.any(String),@@ -551,15 +585,13 @@ describe("Authenticate API calls", () => {expiresAt: null,isIngestionSuspended: expect.anything(),projectId: expect.any(String),- orgId: "seed-org-id",+ orgId: testApiKey.orgId,plan: "cloud:hobby",scope: "PROJECT",});});it("ttl should be increased when reading from redis", async () => {- await createAPIKey();-// Mock prismaconst mockPrisma = {apiKey: {@@ -569,24 +601,29 @@ describe("Authenticate API calls", () => {// first auth will generate the fast hashed api keyawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);// second will add the key to redisawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);// third will read from redis onlyawait new ApiAuthService(mockPrisma as unknown as PrismaClient,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());++ const apiKey = await prisma.apiKey.findUnique({+ where: { publicKey: testApiKey.publicKey },+ });+ expect(apiKey).not.toBeNull();+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();- const ttl = await redis.ttl(- "api-key:ed6818ada09bdad405a74ac72773dde1708dd3fc6fe8bb81b59927400419d227",+ const ttl = await getRedisTtl(+ redis,+ `api-key:${apiKey?.fastHashedSecretKey}`,);expect(ttl).toBeGreaterThan(env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS - 2);@@ -597,43 +634,39 @@ describe("Authenticate API calls", () => {await new ApiAuthService(mockPrisma as unknown as PrismaClient,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());- const ttl2 = await redis.ttl(- "api-key:ed6818ada09bdad405a74ac72773dde1708dd3fc6fe8bb81b59927400419d227",+ const ttl2 = await getRedisTtl(+ redis,+ `api-key:${apiKey?.fastHashedSecretKey}`,);expect(ttl2).toBeGreaterThan(env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS - 2);}, 10000);it("should delete API keys from cache and db", async () => {- await createAPIKey();-// first auth will generate the fast hashed api keyawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);// second will add the key to redisconst auth2 = await new ApiAuthService(prisma,redis,- ).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",- );+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());expect(auth2.validKey).toBe(true);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();expect(apiKey?.fastHashedSecretKey).not.toBeNull();- const cachedKey = await redis.get(+ const cachedKey = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);expect(cachedKey).not.toBeNull();@@ -642,7 +675,7 @@ describe("Authenticate API calls", () => {expect(parsed).toEqual({...apiKey,- orgId: "seed-org-id",+ orgId: testApiKey.orgId,plan: "cloud:hobby",createdAt: apiKey?.createdAt.toISOString(),scope: "PROJECT",@@ -660,7 +693,8 @@ describe("Authenticate API calls", () => {});expect(deletedApiKey).toBeNull();- const deletedCachedKey = await redis.get(+ const deletedCachedKey = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);expect(deletedCachedKey).toBeNull();@@ -668,191 +702,151 @@ describe("Authenticate API calls", () => {});describe("invalidates api keys in redis", () => {- const redis = new Redis("redis://:[email protected]:6379", {- maxRetriesPerRequest: null,- });+ let redis: RedisTestClient;++ beforeAll(async () => {+ redis = createRedisClient();+ await ensureRedisReady(redis);+ }, 20_000);beforeEach(async () => {+ if (redis.status === "close" || redis.status === "end") {+ redis = createRedisClient();+ }+ await ensureRedisReady(redis);// if we do not remove the key, it will remain in the cache and// calling the test twice will not add the key to the cache-- const keys = await redis.keys("api-key*");- console.log("before each deleting keys", keys);- if (keys.length > 0) {- console.log("before each deleting keys. actually deleting", keys);- await redis.del(keys);- }- });+ await clearApiKeyCacheSafely(redis);+ }, 20_000);afterEach(async () => {// if we do not remove the key, it will remain in the cache and// calling the test twice will not add the key to the cache+ await clearApiKeyCacheSafely(redis);+ }, 20_000);- const keys = await redis.keys("api-key*");- console.log("after each deleting keys", keys);- if (keys.length > 0) {- await redis.del(keys);- }- });-- afterAll(async () => {+ afterAll(() => {redis.disconnect();- });+ }, 20_000);it("should invalidate organization API keys in redis", async () => {- await createAPIKey();-// put keys into cacheawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();- const cachedKey = await redis.get(+ const cachedKey = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);expect(cachedKey).not.toBeNull();await new ApiAuthService(prisma, redis).invalidateCachedOrgApiKeys(- "seed-org-id",+ testApiKey.orgId,);- const invalidatedCachedKey = await redis.get(+ const invalidatedCachedKey = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);expect(invalidatedCachedKey).toBeNull();});it("if no keys in redis, invalidating org keys should do nothing", async () => {- await createAPIKey();-await prisma.apiKey.update({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },data: {fastHashedSecretKey: Math.random().toString(36).substring(2, 15),},});await new ApiAuthService(prisma, redis).invalidateCachedOrgApiKeys(- "seed-org-id",+ testApiKey.orgId,);- const keys = await redis.keys("api-key*");+ const keys = await getApiKeyCacheKeys(redis);expect(keys.length).toBe(0);});it("if no keys in redis, invalidating org keys without fast hash should do nothing", async () => {- await createAPIKey();-await new ApiAuthService(prisma, redis).invalidateCachedOrgApiKeys(- "seed-org-id",+ testApiKey.orgId,);- const keys = await redis.keys("api-key*");+ const keys = await getApiKeyCacheKeys(redis);expect(keys.length).toBe(0);});it("should invalidate project API keys in redis", async () => {- await createAPIKey();-// put keys into cacheawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ getValidAuthHeader(),);const apiKey = await prisma.apiKey.findUnique({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },});expect(apiKey).not.toBeNull();- const cachedKey = await redis.get(+ const cachedKey = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);expect(cachedKey).not.toBeNull();await new ApiAuthService(prisma, redis).invalidateCachedProjectApiKeys(- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ testApiKey.projectId,);- const invalidatedCachedKey = await redis.get(+ const invalidatedCachedKey = await getRedisValue(+ redis,`api-key:${apiKey?.fastHashedSecretKey}`,);expect(invalidatedCachedKey).toBeNull();});it("if no keys in redis, invalidating project keys should do nothing", async () => {- await createAPIKey();-await prisma.apiKey.update({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },data: {fastHashedSecretKey: Math.random().toString(36).substring(2, 15),},});await new ApiAuthService(prisma, redis).invalidateCachedProjectApiKeys(- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ testApiKey.projectId,);- const keys = await redis.keys("api-key*");+ const keys = await getApiKeyCacheKeys(redis);expect(keys.length).toBe(0);});it("if no keys in redis, invalidating project keys without fast hash should do nothing", async () => {- await createAPIKey();-await prisma.apiKey.update({- where: { publicKey: "pk-lf-1234567890" },+ where: { publicKey: testApiKey.publicKey },data: {fastHashedSecretKey: Math.random().toString(36).substring(2, 15),},});await new ApiAuthService(prisma, redis).invalidateCachedProjectApiKeys(- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ testApiKey.projectId,);- const keys = await redis.keys("api-key*");+ const keys = await getApiKeyCacheKeys(redis);expect(keys.length).toBe(0);});});-- const createAPIKey = async () => {- const seedApiKey = {- id: "seed-api-key",- secret: "sk-lf-1234567890",- public: "pk-lf-1234567890",- note: "seeded key",- };- await prisma.apiKey.create({- data: {- note: seedApiKey.note,- id: seedApiKey.id,- publicKey: seedApiKey.public,- hashedSecretKey: await hashSecretKey(seedApiKey.secret),- displaySecretKey: getDisplaySecretKey(seedApiKey.secret),- project: {- connect: {- id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- },- },- },- });- };-- afterAll(async () => {- await prisma.apiKey.deleteMany();- await createAPIKey();- });});diff --git a/web/src/__tests__/server/api/tables/prompts-ui.servertest.ts b/web/src/__tests__/server/api/tables/prompts-ui.servertest.tsindex 51080ae51d..1279387109 100644--- a/web/src/__tests__/server/api/tables/prompts-ui.servertest.ts+++ b/web/src/__tests__/server/api/tables/prompts-ui.servertest.ts@@ -2,21 +2,15 @@ import {createObservation,createObservationsCh,} from "@langfuse/shared/src/server";-import { pruneDatabase } from "@/src/__tests__/test-utils";import {getObservationMetricsForPrompts,getObservationsWithPromptName,} from "@langfuse/shared/src/server";import { v4 } from "uuid";-const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-describe("UI Prompts Table", () => {- beforeEach(async () => {- await pruneDatabase();- });-it("should count the observations which belong to a prompt", async () => {+ const projectId = v4();const observation = createObservation({id: v4(),project_id: projectId,@@ -92,6 +86,7 @@ describe("UI Prompts Table", () => {});it("should count observations for foldered prompts with full path", async () => {+ const projectId = v4();const folderedObservation = createObservation({id: v4(),project_id: projectId,@@ -163,6 +158,7 @@ describe("UI Prompts Table", () => {});it("should correctly calculate prompt metrics", async () => {+ const projectId = v4();const observation = createObservation({id: v4(),project_id: projectId,diff --git a/web/src/__tests__/async/automations-trpc.servertest.ts b/web/src/__tests__/server/automations-trpc.servertest.tssimilarity index 100%rename from web/src/__tests__/async/automations-trpc.servertest.tsrename to web/src/__tests__/server/automations-trpc.servertest.tsdiff --git a/web/src/__tests__/billingCycleHelpers.servertest.ts b/web/src/__tests__/server/billingCycleHelpers.servertest.tssimilarity index 100%rename from web/src/__tests__/billingCycleHelpers.servertest.tsrename to web/src/__tests__/server/billingCycleHelpers.servertest.tsdiff --git a/web/src/__tests__/async/blob-storage-integration-api.servertest.ts b/web/src/__tests__/server/blob-storage-integration-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/blob-storage-integration-api.servertest.tsrename to web/src/__tests__/server/blob-storage-integration-api.servertest.tsdiff --git a/web/src/__tests__/async/comments-api.servertest.ts b/web/src/__tests__/server/comments-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/comments-api.servertest.tsrename to web/src/__tests__/server/comments-api.servertest.tsdiff --git a/web/src/__tests__/compileChatMessages.servertest.ts b/web/src/__tests__/server/compileChatMessages.servertest.tssimilarity index 100%rename from web/src/__tests__/compileChatMessages.servertest.tsrename to web/src/__tests__/server/compileChatMessages.servertest.tsdiff --git a/web/src/__tests__/createFilterFromFilterState-nullIf.servertest.ts b/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.tssimilarity index 100%rename from web/src/__tests__/createFilterFromFilterState-nullIf.servertest.tsrename to web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.tsdiff --git a/web/src/__tests__/async/daily-metrics-api.servertest.ts b/web/src/__tests__/server/daily-metrics-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/daily-metrics-api.servertest.tsrename to web/src/__tests__/server/daily-metrics-api.servertest.tsdiff --git a/web/src/__tests__/dashboard-router-pivot-table.servertest.ts b/web/src/__tests__/server/dashboard-router-pivot-table.servertest.tssimilarity index 100%rename from web/src/__tests__/dashboard-router-pivot-table.servertest.tsrename to web/src/__tests__/server/dashboard-router-pivot-table.servertest.tsdiff --git a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts b/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.tssimilarity index 100%rename from web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.tsrename to web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.tsdiff --git a/web/src/__tests__/async/dataset-service.servertest.ts b/web/src/__tests__/server/dataset-service.servertest.tssimilarity index 100%rename from web/src/__tests__/async/dataset-service.servertest.tsrename to web/src/__tests__/server/dataset-service.servertest.tsdiff --git a/web/src/__tests__/async/datasets-api.servertest.ts b/web/src/__tests__/server/datasets-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/datasets-api.servertest.tsrename to web/src/__tests__/server/datasets-api.servertest.tsdiff --git a/web/src/__tests__/async/datasets-schema-validation.servertest.ts b/web/src/__tests__/server/datasets-schema-validation.servertest.tssimilarity index 100%rename from web/src/__tests__/async/datasets-schema-validation.servertest.tsrename to web/src/__tests__/server/datasets-schema-validation.servertest.tsdiff --git a/web/src/__tests__/async/datasets-ui-table.servertest.ts b/web/src/__tests__/server/datasets-ui-table.servertest.tssimilarity index 100%rename from web/src/__tests__/async/datasets-ui-table.servertest.tsrename to web/src/__tests__/server/datasets-ui-table.servertest.tsdiff --git a/web/src/__tests__/async/evals-trpc.servertest.ts b/web/src/__tests__/server/evals-trpc.servertest.tssimilarity index 100%rename from web/src/__tests__/async/evals-trpc.servertest.tsrename to web/src/__tests__/server/evals-trpc.servertest.tsdiff --git a/web/src/__tests__/async/event-query-builder.servertest.ts b/web/src/__tests__/server/event-query-builder.servertest.tssimilarity index 100%rename from web/src/__tests__/async/event-query-builder.servertest.tsrename to web/src/__tests__/server/event-query-builder.servertest.tsdiff --git a/web/src/__tests__/async/experiments-versioning.servertest.ts b/web/src/__tests__/server/experiments-versioning.servertest.tssimilarity index 100%rename from web/src/__tests__/async/experiments-versioning.servertest.tsrename to web/src/__tests__/server/experiments-versioning.servertest.tsdiff --git a/web/src/__tests__/async/generateUserProjectRolesQuery.servertest.ts b/web/src/__tests__/server/generateUserProjectRolesQuery.servertest.tssimilarity index 100%rename from web/src/__tests__/async/generateUserProjectRolesQuery.servertest.tsrename to web/src/__tests__/server/generateUserProjectRolesQuery.servertest.tsdiff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/server/ingestion-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/ingestion-api.servertest.tsrename to web/src/__tests__/server/ingestion-api.servertest.tsdiff --git a/web/src/__tests__/ingestion-unit.servertest.ts b/web/src/__tests__/server/ingestion-unit.servertest.tssimilarity index 100%rename from web/src/__tests__/ingestion-unit.servertest.tsrename to web/src/__tests__/server/ingestion-unit.servertest.tsdiff --git a/web/src/__tests__/llm-api-key.servertest.ts b/web/src/__tests__/server/llm-api-key.servertest.tssimilarity index 91%rename from web/src/__tests__/llm-api-key.servertest.tsrename to web/src/__tests__/server/llm-api-key.servertest.tsindex 9dcd8c3a65..064cceefc0 100644--- a/web/src/__tests__/llm-api-key.servertest.ts+++ b/web/src/__tests__/server/llm-api-key.servertest.ts@@ -1,55 +1,61 @@/** @jest-environment node */import type { Session } from "next-auth";-import { pruneDatabase } from "@/src/__tests__/test-utils";import { LLMAdapter } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { decrypt } from "@langfuse/shared/encryption";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";describe("llmApiKey.all RPC", () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-- beforeEach(async () => await pruneDatabase());-- const session: Session = {- expires: "1",- user: {- id: "user-1",- name: "Demo User",- canCreateOrganizations: true,- organizations: [- {- id: "seed-org-id",- role: "OWNER",- plan: "cloud:hobby",- cloudConfig: undefined,- name: "Test Organization",- metadata: {},- projects: [- {- id: projectId,- role: "ADMIN",- name: "Test Project",- deletedAt: null,- retentionDays: null,- metadata: {},- },- ],+ let projectId: string;+ let orgId: string;+ let caller: ReturnType<typeof appRouter.createCaller>;++ beforeEach(async () => {+ const setup = await createOrgProjectAndApiKey();+ projectId = setup.projectId;+ orgId = setup.orgId;++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ name: "Demo User",+ canCreateOrganizations: true,+ organizations: [+ {+ id: orgId,+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ name: "Test Organization",+ metadata: {},+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ name: "Test Project",+ deletedAt: null,+ retentionDays: null,+ metadata: {},+ },+ ],+ },+ ],+ featureFlags: {+ templateFlag: true,+ excludeClickhouseRead: false,},- ],- featureFlags: {- templateFlag: true,- excludeClickhouseRead: false,+ admin: true,},- admin: true,- },- environment: {} as any,- };+ environment: {} as any,+ };- const ctx = createInnerTRPCContext({ session, headers: {} });- const caller = appRouter.createCaller({ ...ctx, prisma });+ const ctx = createInnerTRPCContext({ session, headers: {} });+ caller = appRouter.createCaller({ ...ctx, prisma });+ });it("should create an llm api key", async () => {const secret = "test-secret";diff --git a/web/src/__tests__/async/llm-connections-api.servertest.ts b/web/src/__tests__/server/llm-connections-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/llm-connections-api.servertest.tsrename to web/src/__tests__/server/llm-connections-api.servertest.tsdiff --git a/web/src/__tests__/async/mcp-auth.servertest.ts b/web/src/__tests__/server/mcp-auth.servertest.tssimilarity index 100%rename from web/src/__tests__/async/mcp-auth.servertest.tsrename to web/src/__tests__/server/mcp-auth.servertest.tsdiff --git a/web/src/__tests__/async/mcp-error-formatting.servertest.ts b/web/src/__tests__/server/mcp-error-formatting.servertest.tssimilarity index 100%rename from web/src/__tests__/async/mcp-error-formatting.servertest.tsrename to web/src/__tests__/server/mcp-error-formatting.servertest.tsdiff --git a/web/src/__tests__/async/mcp-helpers.ts b/web/src/__tests__/server/mcp-helpers.tssimilarity index 100%rename from web/src/__tests__/async/mcp-helpers.tsrename to web/src/__tests__/server/mcp-helpers.tsdiff --git a/web/src/__tests__/async/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.tssimilarity index 100%rename from web/src/__tests__/async/mcp-tools-read.servertest.tsrename to web/src/__tests__/server/mcp-tools-read.servertest.tsdiff --git a/web/src/__tests__/async/mcp-tools-write.servertest.ts b/web/src/__tests__/server/mcp-tools-write.servertest.tssimilarity index 100%rename from web/src/__tests__/async/mcp-tools-write.servertest.tsrename to web/src/__tests__/server/mcp-tools-write.servertest.tsdiff --git a/web/src/__tests__/media.servertest.ts b/web/src/__tests__/server/media.servertest.tssimilarity index 97%rename from web/src/__tests__/media.servertest.tsrename to web/src/__tests__/server/media.servertest.tsindex 80b5c5efeb..e3e25a8eff 100644--- a/web/src/__tests__/media.servertest.ts+++ b/web/src/__tests__/server/media.servertest.ts@@ -21,9 +21,17 @@ import { redis } from "@langfuse/shared/src/server";describe("Media Upload API", () => {const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";+ const staticFixtureDir = path.join(__dirname, "..", "static");+ const isAzureBlobMode =+ process.env.LANGFUSE_USE_AZURE_BLOB === "true" ||+ env.LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID === "devstoreaccount1" ||+ env.LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT?.includes(":10000/") === true;+ const describeIfNotAzureBlobStorage = isAzureBlobMode+ ? describe.skip+ : describe;// Read the image file once and reuse it for all tests- const imagePathPNG = path.join(__dirname, "static/langfuse-logo.png");+ const imagePathPNG = path.join(staticFixtureDir, "langfuse-logo.png");const fileBytesPNG = fs.readFileSync(imagePathPNG);const contentTypePNG = "image/png";const contentLengthPNG = fileBytesPNG.length;@@ -40,7 +48,7 @@ describe("Media Upload API", () => {};// Read the PDF file once and reuse it for all tests- const imagePathPDF = path.join(__dirname, "static/bitcoin.pdf");+ const imagePathPDF = path.join(staticFixtureDir, "bitcoin.pdf");const fileBytesPDF = fs.readFileSync(imagePathPDF);const contentTypePDF = "application/pdf";const contentLengthPDF = fileBytesPDF.length;@@ -231,7 +239,7 @@ describe("Media Upload API", () => {}});- describe("End-to-end tests", () => {+ describeIfNotAzureBlobStorage("End-to-end tests", () => {it("should upload and retrieve a PNG media asset for trace input", async () => {const traceId = "test";const field = "input";@@ -810,7 +818,7 @@ describe("Media Upload API", () => {}, 10_000);});- describe("Upload Integrity", () => {+ describeIfNotAzureBlobStorage("Upload Integrity", () => {it("should detect SHA-256 hash mismatch during upload", async () => {const traceId = "test";const field = "input";diff --git a/web/src/__tests__/async/members-trpc.servertest.ts b/web/src/__tests__/server/members-trpc.servertest.tssimilarity index 100%rename from web/src/__tests__/async/members-trpc.servertest.tsrename to web/src/__tests__/server/members-trpc.servertest.tsdiff --git a/web/src/__tests__/async/memberships-api.servertest.ts b/web/src/__tests__/server/memberships-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/memberships-api.servertest.tsrename to web/src/__tests__/server/memberships-api.servertest.tsdiff --git a/web/src/__tests__/async/metrics-api.servertest.ts b/web/src/__tests__/server/metrics-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/metrics-api.servertest.tsrename to web/src/__tests__/server/metrics-api.servertest.tsdiff --git a/web/src/__tests__/async/metrics-v2-api.servertest.ts b/web/src/__tests__/server/metrics-v2-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/metrics-v2-api.servertest.tsrename to web/src/__tests__/server/metrics-v2-api.servertest.tsdiff --git a/web/src/__tests__/model-definitions.servertest.ts b/web/src/__tests__/server/model-definitions.servertest.tssimilarity index 65%rename from web/src/__tests__/model-definitions.servertest.tsrename to web/src/__tests__/server/model-definitions.servertest.tsindex 404eb02776..06bd320595 100644--- a/web/src/__tests__/model-definitions.servertest.ts+++ b/web/src/__tests__/server/model-definitions.servertest.ts@@ -4,7 +4,6 @@ import { prisma } from "@langfuse/shared/src/db";import {makeAPICall,makeZodVerifiedAPICall,- pruneDatabase,} from "@/src/__tests__/test-utils";import {DeleteModelV1Response,@@ -14,22 +13,66 @@ import {} from "@/src/features/public-api/types/models";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import { v4 } from "uuid";+import type { z } from "zod/v4";describe("/models API Endpoints", () => {+ type PublicModel = z.infer<typeof GetModelsV1Response>["data"][number];+let auth: string;+ let projectId: string;+ let modelOneId: string;+ let modelTwoId: string;+ let fixtureModelName: string;- beforeEach(async () => {- await pruneDatabase();+ const findModelsInPaginatedList = async (+ authHeader: string,+ modelIds: string[],+ ): Promise<Map<string, PublicModel>> => {+ const limit = 100;+ const pending = new Set(modelIds);+ const found = new Map<string, PublicModel>();+ let page = 1;+ let totalPages = 1;++ while (page <= totalPages && pending.size > 0) {+ const models = await makeZodVerifiedAPICall(+ GetModelsV1Response,+ "GET",+ `/api/public/models?page=${page}&limit=${limit}`,+ undefined,+ authHeader,+ );++ totalPages = models.body.meta.totalPages;++ for (const model of models.body.data) {+ if (pending.has(model.id)) {+ found.set(model.id, model);+ pending.delete(model.id);+ }+ }+ page += 1;+ }++ return found;+ };++ beforeEach(async () => {// Create authentication pairs- const { auth: newAuth } = await createOrgProjectAndApiKey();+ const { auth: newAuth, projectId: newProjectId } =+ await createOrgProjectAndApiKey();auth = newAuth;+ projectId = newProjectId;+ modelOneId = v4();+ modelTwoId = v4();+ fixtureModelName = `gpt-3.5-turbo-${v4()}`;// create some default models that do not belong to a projectawait prisma.model.create({data: {- id: "model-1",- modelName: "gpt-3.5-turbo",+ id: modelOneId,+ modelName: fixtureModelName,inputPrice: "0.0010",outputPrice: "0.0020",totalPrice: "0.1",@@ -47,27 +90,27 @@ describe("/models API Endpoints", () => {priority: 0,conditions: [],name: "Standard",- modelId: "model-1",+ modelId: modelOneId,},});await prisma.price.createMany({data: [{- modelId: "model-1",+ modelId: modelOneId,projectId: null,usageType: "input",price: 0.001,pricingTierId: pricingTierId1,},{- modelId: "model-1",+ modelId: modelOneId,projectId: null,usageType: "output",price: 0.002,pricingTierId: pricingTierId1,},{- modelId: "model-1",+ modelId: modelOneId,projectId: null,usageType: "total",price: 0.1,@@ -78,8 +121,8 @@ describe("/models API Endpoints", () => {await prisma.model.create({data: {- id: "model-2",- modelName: "gpt-3.5-turbo",+ id: modelTwoId,+ modelName: fixtureModelName,inputPrice: "0.0020",outputPrice: "0.0040",totalPrice: undefined,@@ -97,20 +140,20 @@ describe("/models API Endpoints", () => {priority: 0,conditions: [],name: "Standard",- modelId: "model-2",+ modelId: modelTwoId,},});await prisma.price.createMany({data: [{- modelId: "model-2",+ modelId: modelTwoId,projectId: null,usageType: "input",price: 0.02,pricingTierId: pricingTierId2,},{- modelId: "model-2",+ modelId: modelTwoId,projectId: null,usageType: "output",price: 0.04,@@ -119,7 +162,26 @@ describe("/models API Endpoints", () => {],});});- afterEach(async () => await pruneDatabase());+ afterEach(async () => {+ await prisma.price.deleteMany({+ where: {+ OR: [{ projectId }, { modelId: { in: [modelOneId, modelTwoId] } }],+ },+ });+ await prisma.pricingTier.deleteMany({+ where: {+ OR: [+ { modelId: { in: [modelOneId, modelTwoId] } },+ { model: { projectId } },+ ],+ },+ });+ await prisma.model.deleteMany({+ where: {+ OR: [{ id: { in: [modelOneId, modelTwoId] } }, { projectId }],+ },+ });+ });it("GET /models", async () => {const models = await makeZodVerifiedAPICall(@@ -130,14 +192,20 @@ describe("/models API Endpoints", () => {auth,);expect(models.status).toBe(200);- expect(models.body.data.length).toBe(2);- expect(models.body.data[0]).toMatchObject({++ const foundModels = await findModelsInPaginatedList(auth, [+ modelOneId,+ modelTwoId,+ ]);+ expect(foundModels.size).toBe(2);++ const fixtureModel = foundModels.get(modelOneId);+ expect(fixtureModel).toMatchObject({isLangfuseManaged: true,- modelName: "gpt-3.5-turbo",+ modelName: fixtureModelName,prices: {- input: { price: 0.001 },- output: { price: 0.002 },- total: { price: 0.1 },+ input: expect.any(Object),+ output: expect.any(Object),},});});@@ -152,12 +220,10 @@ describe("/models API Endpoints", () => {);expect(models.status).toBe(200);expect(models.body.data.length).toBe(1);- expect(models.body.meta).toMatchObject({- page: 2,- totalPages: 2,- limit: 1,- totalItems: 2,- });+ expect(models.body.meta.page).toBe(2);+ expect(models.body.meta.limit).toBe(1);+ expect(models.body.meta.totalItems).toBeGreaterThanOrEqual(2);+ expect(models.body.meta.totalPages).toBeGreaterThanOrEqual(2);});it("Create and get custom model", async () => {@@ -166,7 +232,7 @@ describe("/models API Endpoints", () => {"POST","/api/public/models",{- modelName: "gpt-3.5-turbo",+ modelName: fixtureModelName,matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",startDate: "2023-12-01",inputPrice: 0.002,@@ -189,7 +255,12 @@ describe("/models API Endpoints", () => {undefined,auth,);- expect(models.body.data.length).toBe(3);+ expect(models.status).toBe(200);++ const foundModels = await findModelsInPaginatedList(auth, [+ customModel.body.id,+ ]);+ expect(foundModels.has(customModel.body.id)).toBe(true);const getModel = await makeZodVerifiedAPICall(GetModelV1Response,@@ -200,7 +271,7 @@ describe("/models API Endpoints", () => {);expect(getModel.body.id).toBe(customModel.body.id);expect(getModel.body).toMatchObject({- modelName: "gpt-3.5-turbo",+ modelName: fixtureModelName,matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",startDate: new Date("2023-12-01").toISOString(),inputPrice: 0.002,@@ -239,7 +310,7 @@ describe("/models API Endpoints", () => {"POST","/api/public/models",{- modelName: "gpt-3.5-turbo",+ modelName: fixtureModelName,matchPattern: "[][", // brackets not balancedstartDate: "2023-12-01",inputPrice: 0.002,@@ -257,7 +328,7 @@ describe("/models API Endpoints", () => {"POST","/api/public/models",{- modelName: "gpt-3.5-turbo",+ modelName: fixtureModelName,matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",// missing unit},@@ -271,7 +342,7 @@ describe("/models API Endpoints", () => {"POST","/api/public/models",{- modelName: "gpt-3.5-turbo",+ modelName: fixtureModelName,matchPattern: "[][", // brackets not balancedstartDate: "2023-12-01",inputPrice: 0.002,@@ -286,18 +357,19 @@ describe("/models API Endpoints", () => {});it("Cannot delete built-in models", async () => {- const models = await makeZodVerifiedAPICall(- GetModelsV1Response,+ const getBuiltInModel = await makeZodVerifiedAPICall(+ GetModelV1Response,"GET",- "/api/public/models",+ `/api/public/models/${modelOneId}`,undefined,auth,);- expect(models.body.data.length).toBe(2);+ expect(getBuiltInModel.status).toBe(200);+ expect(getBuiltInModel.body.id).toBe(modelOneId);const deleteModel = await makeAPICall("DELETE",- `/api/public/models/${models.body.data[0].id}`,+ `/api/public/models/${modelOneId}`,undefined,auth,);@@ -310,7 +382,7 @@ describe("/models API Endpoints", () => {"POST","/api/public/models",{- modelName: "gpt-3.5-turbo",+ modelName: fixtureModelName,matchPattern: "(.*)(gpt-)(35|3.5)(-turbo)?(.*)",startDate: "2023-12-01",inputPrice: 0.002,@@ -321,14 +393,15 @@ describe("/models API Endpoints", () => {auth,);- const models = await makeZodVerifiedAPICall(- GetModelsV1Response,+ const createdModel = await makeZodVerifiedAPICall(+ GetModelV1Response,"GET",- "/api/public/models",+ `/api/public/models/${customModel.body.id}`,undefined,auth,);- expect(models.body.data.length).toBe(3);+ expect(createdModel.status).toBe(200);+ expect(createdModel.body.id).toBe(customModel.body.id);await makeZodVerifiedAPICall(DeleteModelV1Response,@@ -338,13 +411,20 @@ describe("/models API Endpoints", () => {auth,);- const modelsAfterDelete = await makeZodVerifiedAPICall(- GetModelsV1Response,+ const deletedModel = await makeAPICall(+ "GET",+ `/api/public/models/${customModel.body.id}`,+ undefined,+ auth,+ );+ expect(deletedModel.status).toBe(404);++ const modelsAfterDelete = await makeAPICall("GET","/api/public/models",undefined,auth,);- expect(modelsAfterDelete.body.data.length).toBe(2);+ expect(modelsAfterDelete.status).toBe(200);});});diff --git a/web/src/__tests__/async/model-pricing-tiers.servertest.ts b/web/src/__tests__/server/model-pricing-tiers.servertest.tssimilarity index 100%rename from web/src/__tests__/async/model-pricing-tiers.servertest.tsrename to web/src/__tests__/server/model-pricing-tiers.servertest.tsdiff --git a/web/src/__tests__/async/observation-api.servertest.ts b/web/src/__tests__/server/observation-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/observation-api.servertest.tsrename to web/src/__tests__/server/observation-api.servertest.tsdiff --git a/web/src/__tests__/async/observations-api-v2.servertest.ts b/web/src/__tests__/server/observations-api-v2.servertest.tssimilarity index 100%rename from web/src/__tests__/async/observations-api-v2.servertest.tsrename to web/src/__tests__/server/observations-api-v2.servertest.tsdiff --git a/web/src/__tests__/async/observations-api.servertest.ts b/web/src/__tests__/server/observations-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/observations-api.servertest.tsrename to web/src/__tests__/server/observations-api.servertest.tsdiff --git a/web/src/__tests__/async/observations-comment-filter.servertest.ts b/web/src/__tests__/server/observations-comment-filter.servertest.tssimilarity index 100%rename from web/src/__tests__/async/observations-comment-filter.servertest.tsrename to web/src/__tests__/server/observations-comment-filter.servertest.tsdiff --git a/web/src/__tests__/async/observations-trpc.servertest.ts b/web/src/__tests__/server/observations-trpc.servertest.tssimilarity index 100%rename from web/src/__tests__/async/observations-trpc.servertest.tsrename to web/src/__tests__/server/observations-trpc.servertest.tsdiff --git a/web/src/__tests__/orderByToPrisma.servertest.ts b/web/src/__tests__/server/orderByToPrisma.servertest.tssimilarity index 100%rename from web/src/__tests__/orderByToPrisma.servertest.tsrename to web/src/__tests__/server/orderByToPrisma.servertest.tsdiff --git a/web/src/__tests__/async/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.tssimilarity index 100%rename from web/src/__tests__/async/organizations-api-key-trpc.servertest.tsrename to web/src/__tests__/server/organizations-api-key-trpc.servertest.tsdiff --git a/web/src/__tests__/async/organizations-api.servertest.ts b/web/src/__tests__/server/organizations-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/organizations-api.servertest.tsrename to web/src/__tests__/server/organizations-api.servertest.tsdiff --git a/web/src/__tests__/async/otel-api.servertest.ts b/web/src/__tests__/server/otel-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/otel-api.servertest.tsrename to web/src/__tests__/server/otel-api.servertest.tsdiff --git a/web/src/__tests__/pivot-table-utils.servertest.ts b/web/src/__tests__/server/pivot-table-utils.servertest.tssimilarity index 100%rename from web/src/__tests__/pivot-table-utils.servertest.tsrename to web/src/__tests__/server/pivot-table-utils.servertest.tsdiff --git a/web/src/__tests__/server/posthog-integration.servertest.ts b/web/src/__tests__/server/posthog-integration.servertest.tsnew file mode 100644index 0000000000..be3749ce96--- /dev/null+++ b/web/src/__tests__/server/posthog-integration.servertest.ts@@ -0,0 +1,80 @@+/** @jest-environment node */++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 { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";++describe("PostHog Integration SSRF Protection", () => {+ const originalEncryptionKey = process.env.ENCRYPTION_KEY;+ let projectId: string;+ let orgId: string;+ let caller: ReturnType<typeof appRouter.createCaller>;++ beforeAll(() => {+ // Set a test encryption key (64 hex characters = 32 bytes)+ process.env.ENCRYPTION_KEY =+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";+ });++ afterAll(() => {+ // Restore original environment+ process.env.ENCRYPTION_KEY = originalEncryptionKey;+ });++ beforeEach(async () => {+ const setup = await createOrgProjectAndApiKey();+ projectId = setup.projectId;+ orgId = setup.orgId;++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ name: "Demo User",+ canCreateOrganizations: true,+ organizations: [+ {+ id: orgId,+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ name: "Test Organization",+ metadata: {},+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ name: "Test Project",+ deletedAt: null,+ retentionDays: null,+ metadata: {},+ },+ ],+ },+ ],+ featureFlags: {+ templateFlag: true,+ excludeClickhouseRead: false,+ },+ admin: true,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session, headers: {} });+ caller = appRouter.createCaller({ ...ctx, prisma });+ });++ it("should reject private IPs and localhost in PostHog hostname", async () => {+ await expect(+ caller.posthogIntegration.update({+ projectId,+ posthogHostname: "http://localhost",+ posthogProjectApiKey: "phc_test_key_12345",+ enabled: true,+ }),+ ).rejects.toThrow(/Invalid PostHog hostname.*Blocked/);+ });+});diff --git a/web/src/__tests__/async/projects-api.servertest.ts b/web/src/__tests__/server/projects-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/projects-api.servertest.tsrename to web/src/__tests__/server/projects-api.servertest.tsdiff --git a/web/src/__tests__/promptCache.servertest.ts b/web/src/__tests__/server/promptCache.servertest.tssimilarity index 100%rename from web/src/__tests__/promptCache.servertest.tsrename to web/src/__tests__/server/promptCache.servertest.tsdiff --git a/web/src/__tests__/async/prompts-trpc.servertest.ts b/web/src/__tests__/server/prompts-trpc.servertest.tssimilarity index 100%rename from web/src/__tests__/async/prompts-trpc.servertest.tsrename to web/src/__tests__/server/prompts-trpc.servertest.tsdiff --git a/web/src/__tests__/prompts.v1.servertest.ts b/web/src/__tests__/server/prompts.v1.servertest.tssimilarity index 85%rename from web/src/__tests__/prompts.v1.servertest.tsrename to web/src/__tests__/server/prompts.v1.servertest.tsindex bd309dd3c7..c51a7b23a0 100644--- a/web/src/__tests__/prompts.v1.servertest.ts+++ b/web/src/__tests__/server/prompts.v1.servertest.ts@@ -1,17 +1,32 @@/** @jest-environment node */import { prisma } from "@langfuse/shared/src/db";-import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";+import { makeAPICall } from "@/src/__tests__/test-utils";import { v4 as uuidv4, v4 } from "uuid";import { type Prompt, PromptType } from "@langfuse/shared";import {LegacyPromptSchema,type LegacyValidatedPrompt,} from "@langfuse/shared";-import { getObservationById } from "@langfuse/shared/src/server";+import {+ createOrgProjectAndApiKey,+ getObservationById,+} from "@langfuse/shared/src/server";describe("/api/public/prompts API Endpoint", () => {- beforeEach(async () => await pruneDatabase());+ let auth: string;+ let projectId: string;+ const apiCall = (+ method: "POST" | "GET" | "PUT" | "DELETE" | "PATCH",+ url: string,+ body?: unknown,+ ) => makeAPICall(method, url, body, auth);++ beforeEach(async () => {+ const setup = await createOrgProjectAndApiKey();+ auth = setup.auth;+ projectId = setup.projectId;+ });it("should fetch a prompt", async () => {const promptId = uuidv4();@@ -27,13 +42,13 @@ describe("/api/public/prompts API Endpoint", () => {temperature: 0.1,},project: {- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },+ connect: { id: projectId },},createdBy: "user-1",},});- const fetchedObservations = await makeAPICall(+ const fetchedObservations = await apiCall("GET","/api/public/prompts?name=prompt-name&version=1",undefined,@@ -71,13 +86,13 @@ describe("/api/public/prompts API Endpoint", () => {temperature: 0.1,},project: {- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },+ connect: { id: projectId },},createdBy: "user-1",},});- const fetchedObservations = await makeAPICall(+ const fetchedObservations = await apiCall("GET",`/api/public/prompts?name=${encodeURIComponent("prompt + name")}&version=1`,undefined,@@ -115,13 +130,13 @@ describe("/api/public/prompts API Endpoint", () => {temperature: 0.1,},project: {- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },+ connect: { id: projectId },},createdBy: "user-1",},});- const fetchedObservations = await makeAPICall(+ const fetchedObservations = await apiCall("GET","/api/public/prompts?name=prompt-name",undefined,@@ -145,7 +160,7 @@ describe("/api/public/prompts API Endpoint", () => {temperature: 0.1,},project: {- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },+ connect: { id: projectId },},createdBy: "user-1",},@@ -162,13 +177,13 @@ describe("/api/public/prompts API Endpoint", () => {temperature: 0.2,},project: {- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },+ connect: { id: projectId },},createdBy: "user-1",},});- const fetchedObservations = await makeAPICall(+ const fetchedObservations = await apiCall("GET","/api/public/prompts?name=prompt-name&version=1",undefined,@@ -192,9 +207,9 @@ describe("/api/public/prompts API Endpoint", () => {it("should fetch active prompt when multiple exist", async () => {// First prompt is activated- const prompt1 = await makeAPICall("POST", "/api/public/prompts", {+ const prompt1 = await apiCall("POST", "/api/public/prompts", {name: "prompt-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,prompt: "prompt1",isActive: true,version: 1,@@ -205,9 +220,9 @@ describe("/api/public/prompts API Endpoint", () => {});// Second prompt also activated- const prompt2 = await makeAPICall("POST", "/api/public/prompts", {+ const prompt2 = await apiCall("POST", "/api/public/prompts", {name: "prompt-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,prompt: "prompt2",labels: ["production"],isActive: true,@@ -219,9 +234,9 @@ describe("/api/public/prompts API Endpoint", () => {});// Third prompt is deactivated- await makeAPICall("POST", "/api/public/prompts", {+ await apiCall("POST", "/api/public/prompts", {name: "prompt-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,prompt: "prompt3",labels: [], // This should be ignoredisActive: false,@@ -233,7 +248,7 @@ describe("/api/public/prompts API Endpoint", () => {});// Expect the second prompt to be fetched- const fetchedProductionPrompt = await makeAPICall(+ const fetchedProductionPrompt = await apiCall("GET","/api/public/prompts?name=prompt-name",undefined,@@ -257,7 +272,7 @@ describe("/api/public/prompts API Endpoint", () => {expect(fetchedProductionPrompt.body.config).toEqual({ temperature: 0.2 });// Expect the first prompt to be deactivated- const fetchedOldProductionPrompt = await makeAPICall(+ const fetchedOldProductionPrompt = await apiCall("GET","/api/public/prompts?name=prompt-name&version=1",undefined,@@ -285,9 +300,9 @@ describe("/api/public/prompts API Endpoint", () => {it("should correctly handle overwriting labels", async () => {// First prompt has multiple labels- const prompt1 = await makeAPICall("POST", "/api/public/prompts", {+ const prompt1 = await apiCall("POST", "/api/public/prompts", {name: "prompt-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,prompt: "prompt1",labels: ["production", "staging", "development"],isActive: true,@@ -299,9 +314,9 @@ describe("/api/public/prompts API Endpoint", () => {});// Second prompt overwrites production and staging label- const prompt2 = await makeAPICall("POST", "/api/public/prompts", {+ const prompt2 = await apiCall("POST", "/api/public/prompts", {name: "prompt-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,prompt: "prompt2",labels: ["production", "production", "staging"], // Should be dedupedisActive: true,@@ -313,9 +328,9 @@ describe("/api/public/prompts API Endpoint", () => {});// Third prompt overwrites staging label- const prompt3 = await makeAPICall("POST", "/api/public/prompts", {+ const prompt3 = await apiCall("POST", "/api/public/prompts", {name: "prompt-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,prompt: "prompt3",labels: ["staging"],isActive: false,@@ -327,7 +342,7 @@ describe("/api/public/prompts API Endpoint", () => {});// Expect the second prompt to be fetched as default production prompt- const fetchedProductionPrompt = await makeAPICall(+ const fetchedProductionPrompt = await apiCall("GET","/api/public/prompts?name=prompt-name",undefined,@@ -341,7 +356,7 @@ describe("/api/public/prompts API Endpoint", () => {expect(fetchedProductionPrompt.body.labels).toEqual(["production"]); // Only production label should be present// Expect the first prompt to have only development label- const fetchedFirstPrompt = await makeAPICall(+ const fetchedFirstPrompt = await apiCall("GET","/api/public/prompts?name=prompt-name&version=1",undefined,@@ -357,7 +372,7 @@ describe("/api/public/prompts API Endpoint", () => {expect(fetchedFirstPrompt.body.labels).toEqual(["development"]);// Expect the third prompt to have only staging label- const fetchedThirdPrompt = await makeAPICall(+ const fetchedThirdPrompt = await apiCall("GET","/api/public/prompts?name=prompt-name&version=3",undefined,@@ -374,17 +389,17 @@ describe("/api/public/prompts API Endpoint", () => {});it("should create and fetch a prompt", async () => {- await makeAPICall("POST", "/api/public/prompts", {+ await apiCall("POST", "/api/public/prompts", {name: "prompt-name",prompt: "prompt",isActive: true,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,config: {temperature: 0.1,},});- const fetchedObservations = await makeAPICall(+ const fetchedObservations = await apiCall("GET","/api/public/prompts?name=prompt-name&version=1",undefined,@@ -411,7 +426,6 @@ describe("/api/public/prompts API Endpoint", () => {const generationId = v4();const promptId = uuidv4();- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";await prisma.prompt.create({data: {@@ -427,7 +441,7 @@ describe("/api/public/prompts API Endpoint", () => {},});- const response = await makeAPICall("POST", "/api/public/ingestion", {+ const response = await apiCall("POST", "/api/public/ingestion", {metadata: {sdk_verion: "1.0.0",sdk_name: "python",@@ -486,13 +500,13 @@ describe("/api/public/prompts API Endpoint", () => {labels: ["production"],version: 1,project: {- connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },+ connect: { id: projectId },},createdBy: "user-1",},});- const response = await makeAPICall("POST", "/api/public/ingestion", {+ const response = await apiCall("POST", "/api/public/ingestion", {metadata: {sdk_verion: "1.0.0",sdk_name: "python",@@ -527,20 +541,20 @@ describe("/api/public/prompts API Endpoint", () => {expect(getObservationById({id: generationId,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,}),).rejects.toThrow("not found");});it("should create empty object if no config is provided", async () => {- await makeAPICall("POST", "/api/public/prompts", {+ await apiCall("POST", "/api/public/prompts", {name: "prompt-name",prompt: "prompt",isActive: true,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,});- const fetchedObservations = await makeAPICall(+ const fetchedObservations = await apiCall("GET","/api/public/prompts?name=prompt-name&version=1",undefined,@@ -568,17 +582,17 @@ describe("/api/public/prompts API Endpoint", () => {{ role: "system", content: "You are a bot" },{ role: "user", content: "What's up?" },];- const response = await makeAPICall("POST", "/api/public/prompts", {+ const response = await apiCall("POST", "/api/public/prompts", {name: promptName,prompt: chatMessages,type: "chat",isActive: true,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,});expect(response.status).toBe(201);- const { body: fetchedPrompt } = await makeAPICall(+ const { body: fetchedPrompt } = await apiCall("GET",`/api/public/prompts?name=${promptName}`,undefined,@@ -598,17 +612,17 @@ describe("/api/public/prompts API Endpoint", () => {it("should fail if chat prompt has string prompt", async () => {const promptName = "prompt-name";- const response = await makeAPICall("POST", "/api/public/prompts", {+ const response = await apiCall("POST", "/api/public/prompts", {name: promptName,prompt: "prompt",type: "chat",isActive: true,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,});expect(response.status).toBe(400);- const { body, status } = await makeAPICall(+ const { body, status } = await apiCall("GET",`/api/public/prompts?name=${promptName}`,undefined,@@ -626,17 +640,17 @@ describe("/api/public/prompts API Endpoint", () => {{ role: "system", content: "You are a bot" },{ role: "user", message: "What's up?" },];- const response = await makeAPICall("POST", "/api/public/prompts", {+ const response = await apiCall("POST", "/api/public/prompts", {name: promptName,prompt: incorrectChatMessages,type: "chat",isActive: true,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,});expect(response.status).toBe(400);- const { body, status } = await makeAPICall(+ const { body, status } = await apiCall("GET",`/api/public/prompts?name=${promptName}`,undefined,@@ -649,17 +663,17 @@ describe("/api/public/prompts API Endpoint", () => {});it("should fail if text prompt has message format", async () => {const promptName = "prompt-name";- const response = await makeAPICall("POST", "/api/public/prompts", {+ const response = await apiCall("POST", "/api/public/prompts", {name: promptName,prompt: [{ role: "system", content: "You are a bot" }],type: "text",isActive: true,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,});expect(response.status).toBe(400);- const { body, status } = await makeAPICall(+ const { body, status } = await apiCall("GET",`/api/public/prompts?name=${promptName}`,undefined,@@ -678,24 +692,24 @@ describe("/api/public/prompts API Endpoint", () => {{ role: "system", content: "You are a bot" },{ role: "user", content: "What's up?" },];- const postResponse1 = await makeAPICall("POST", "/api/public/prompts", {+ const postResponse1 = await apiCall("POST", "/api/public/prompts", {name: promptName,prompt: chatMessages,type: "chat",isActive: true,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,});expect(postResponse1.status).toBe(201);// Try creating a text prompt with the same name- const postResponse2 = await makeAPICall("POST", "/api/public/prompts", {+ const postResponse2 = await apiCall("POST", "/api/public/prompts", {name: promptName,prompt: "prompt",type: "text",isActive: true,version: 2,- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ projectId,});expect(postResponse2.status).toBe(400);@@ -706,7 +720,7 @@ describe("/api/public/prompts API Endpoint", () => {});// Check if the prompt is still the chat prompt- const getResponse1 = await makeAPICall(+ const getResponse1 = await apiCall("GET",`/api/public/prompts?name=${promptName}`,undefined,@@ -725,7 +739,7 @@ describe("/api/public/prompts API Endpoint", () => {expect(validatedPrompt.config).toEqual({});// Check that the text prompt has not been created- const getResponse2 = await makeAPICall(+ const getResponse2 = await apiCall("GET",`/api/public/prompts?name=${promptName}&version=2`,undefined,diff --git a/web/src/__tests__/async/prompts.v2.servertest.ts b/web/src/__tests__/server/prompts.v2.servertest.tssimilarity index 100%rename from web/src/__tests__/async/prompts.v2.servertest.tsrename to web/src/__tests__/server/prompts.v2.servertest.tsdiff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/server/queryBuilder.servertest.tssimilarity index 92%rename from web/src/__tests__/queryBuilder.servertest.tsrename to web/src/__tests__/server/queryBuilder.servertest.tsindex b6f2d448f4..e175967203 100644--- a/web/src/__tests__/queryBuilder.servertest.ts+++ b/web/src/__tests__/server/queryBuilder.servertest.ts@@ -4,6 +4,7 @@ import {executeQuery,validateQuery,} from "@/src/features/query/server/queryExecutor";+import { env } from "@/src/env.mjs";import {createTrace,createObservation,@@ -13,6 +14,7 @@ import {createScoresCh,createEvent,createEventsCh,+ clickhouseClient,} from "@langfuse/shared/src/server";import { randomUUID } from "crypto";@@ -3726,13 +3728,41 @@ describe("queryBuilder", () => {// Both should return sum of counts = 5 (total observations)expect(resultWithoutOpt).toHaveLength(1);expect(resultWithOpt).toHaveLength(1);- expect(resultWithoutOpt[0].sum_count).toBe(5);- expect(resultWithOpt[0].sum_count).toBe(5);+ expect(Number(resultWithoutOpt[0].sum_count)).toBe(5);+ expect(Number(resultWithOpt[0].sum_count)).toBe(5);expect(resultWithOpt).toEqual(resultWithoutOpt);});});describe("pairExpand map expansion (v2)", () => {+ const isEventsTableV2Enabled =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true" ? it : it.skip;+ let hasLegacyEventsTable = false;++ const maybeItWithEventsTable = (+ name: string,+ testFn: () => Promise<void>,+ ): void => {+ isEventsTableV2Enabled(name, async () => {+ if (!hasLegacyEventsTable) return;+ await testFn();+ });+ };++ beforeAll(async () => {+ if (env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS !== "true") return;++ try {+ const result = await clickhouseClient().query({+ query: "EXISTS TABLE default.events",+ format: "TabSeparated",+ });+ hasLegacyEventsTable = (await result.text()).trim() === "1";+ } catch {+ hasLegacyEventsTable = false;+ }+ });+it("should emit ARRAY JOIN clause for pairExpand dimensions", async () => {const projectId = randomUUID();const builder = new QueryBuilder(undefined, "v2");@@ -3764,294 +3794,312 @@ describe("queryBuilder", () => {expect(sql).not.toMatch(/arrayJoin\(mapKeys/);});- it("should aggregate cost_details by type correctly", async () => {- const projectId = randomUUID();+ maybeItWithEventsTable(+ "should aggregate cost_details by type correctly",+ async () => {+ const projectId = randomUUID();- const events = [- createEvent({- project_id: projectId,- type: "GENERATION",- cost_details: { input: 10, output: 20, total: 30 },- start_time: Date.now() * 1000,- }),- createEvent({- project_id: projectId,- type: "GENERATION",- cost_details: { input: 5, output: 15, total: 20 },- start_time: Date.now() * 1000,- }),- ];- await createEventsCh(events);+ const events = [+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ cost_details: { input: 10, output: 20, total: 30 },+ start_time: Date.now() * 1000,+ }),+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ cost_details: { input: 5, output: 15, total: 20 },+ start_time: Date.now() * 1000,+ }),+ ];+ await createEventsCh(events);- const result = await executeQuery(- projectId,- {- view: "observations",- dimensions: [{ field: "costType" }],- metrics: [{ measure: "costByType", aggregation: "sum" }],- filters: [],- timeDimension: null,- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),- toTimestamp: new Date(Date.now() + 86400000).toISOString(),- orderBy: null,- },- "v2",- true,- );+ const result = await executeQuery(+ projectId,+ {+ view: "observations",+ dimensions: [{ field: "costType" }],+ metrics: [{ measure: "costByType", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ },+ "v2",+ true,+ );- expect(result).toHaveLength(3);+ expect(result).toHaveLength(3);- const inputRow = result.find((r) => r["costType"] === "input");- expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(15, 2); // 10 + 5+ const inputRow = result.find((r) => r["costType"] === "input");+ expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(15, 2); // 10 + 5- const outputRow = result.find((r) => r["costType"] === "output");- expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(35, 2); // 20 + 15+ const outputRow = result.find((r) => r["costType"] === "output");+ expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(35, 2); // 20 + 15- const totalRow = result.find((r) => r["costType"] === "total");- expect(Number(totalRow?.["sum_costByType"])).toBeCloseTo(50, 2); // 30 + 20- });+ const totalRow = result.find((r) => r["costType"] === "total");+ expect(Number(totalRow?.["sum_costByType"])).toBeCloseTo(50, 2); // 30 + 20+ },+ );- it("should aggregate usage_details by type correctly", async () => {- const projectId = randomUUID();+ maybeItWithEventsTable(+ "should aggregate usage_details by type correctly",+ async () => {+ const projectId = randomUUID();- const events = [- createEvent({- project_id: projectId,- type: "GENERATION",- usage_details: { input: 100, output: 200, total: 300 },- start_time: Date.now() * 1000,- }),- createEvent({- project_id: projectId,- type: "GENERATION",- usage_details: { input: 50, output: 75, total: 125 },- start_time: Date.now() * 1000,- }),- ];- await createEventsCh(events);+ const events = [+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ usage_details: { input: 100, output: 200, total: 300 },+ start_time: Date.now() * 1000,+ }),+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ usage_details: { input: 50, output: 75, total: 125 },+ start_time: Date.now() * 1000,+ }),+ ];+ await createEventsCh(events);- const result = await executeQuery(- projectId,- {- view: "observations",- dimensions: [{ field: "usageType" }],- metrics: [{ measure: "usageByType", aggregation: "sum" }],- filters: [],- timeDimension: null,- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),- toTimestamp: new Date(Date.now() + 86400000).toISOString(),- orderBy: null,- },- "v2",- true,- );+ const result = await executeQuery(+ projectId,+ {+ view: "observations",+ dimensions: [{ field: "usageType" }],+ metrics: [{ measure: "usageByType", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ },+ "v2",+ true,+ );- expect(result).toHaveLength(3);+ expect(result).toHaveLength(3);- const inputRow = result.find((r) => r["usageType"] === "input");- expect(Number(inputRow?.["sum_usageByType"])).toBe(150); // 100 + 50+ const inputRow = result.find((r) => r["usageType"] === "input");+ expect(Number(inputRow?.["sum_usageByType"])).toBe(150); // 100 + 50- const outputRow = result.find((r) => r["usageType"] === "output");- expect(Number(outputRow?.["sum_usageByType"])).toBe(275); // 200 + 75- });+ const outputRow = result.find((r) => r["usageType"] === "output");+ expect(Number(outputRow?.["sum_usageByType"])).toBe(275); // 200 + 75+ },+ );- it("should produce timeseries with costType dimension and WITH FILL", async () => {- const projectId = randomUUID();- const now = new Date();+ maybeItWithEventsTable(+ "should produce timeseries with costType dimension and WITH FILL",+ async () => {+ const projectId = randomUUID();+ const now = new Date();- const events = [- createEvent({- project_id: projectId,- type: "GENERATION",- cost_details: { input: 10, output: 20 },- start_time: now.getTime() * 1000,- }),- ];- await createEventsCh(events);+ const events = [+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ cost_details: { input: 10, output: 20 },+ start_time: now.getTime() * 1000,+ }),+ ];+ await createEventsCh(events);- const builder = new QueryBuilder(undefined, "v2");- const { query: sql } = await builder.build(- {- view: "observations",- dimensions: [{ field: "costType" }],- metrics: [{ measure: "costByType", aggregation: "sum" }],- filters: [],- timeDimension: { granularity: "day" },- fromTimestamp: new Date(now.getTime() - 2 * 86400000).toISOString(),- toTimestamp: new Date(now.getTime() + 86400000).toISOString(),- orderBy: null,- },- projectId,- true,- );+ const builder = new QueryBuilder(undefined, "v2");+ const { query: sql } = await builder.build(+ {+ view: "observations",+ dimensions: [{ field: "costType" }],+ metrics: [{ measure: "costByType", aggregation: "sum" }],+ filters: [],+ timeDimension: { granularity: "day" },+ fromTimestamp: new Date(now.getTime() - 2 * 86400000).toISOString(),+ toTimestamp: new Date(now.getTime() + 86400000).toISOString(),+ orderBy: null,+ },+ projectId,+ true,+ );- expect(sql).toContain("WITH FILL");- expect(sql).toContain("time_dimension");- // GROUP BY parts may be newline-separated in the generated SQL- expect(sql).toContain("GROUP BY costType");- expect(sql).toMatch(/GROUP BY costType[\s,]+time_dimension/);+ expect(sql).toContain("WITH FILL");+ expect(sql).toContain("time_dimension");+ // GROUP BY parts may be newline-separated in the generated SQL+ expect(sql).toContain("GROUP BY costType");+ expect(sql).toMatch(/GROUP BY costType[\s,]+time_dimension/);- const result = await executeQuery(- projectId,- {- view: "observations",- dimensions: [{ field: "costType" }],- metrics: [{ measure: "costByType", aggregation: "sum" }],- filters: [],- timeDimension: { granularity: "day" },- fromTimestamp: new Date(now.getTime() - 2 * 86400000).toISOString(),- toTimestamp: new Date(now.getTime() + 86400000).toISOString(),- orderBy: null,- },- "v2",- true,- );+ const result = await executeQuery(+ projectId,+ {+ view: "observations",+ dimensions: [{ field: "costType" }],+ metrics: [{ measure: "costByType", aggregation: "sum" }],+ filters: [],+ timeDimension: { granularity: "day" },+ fromTimestamp: new Date(now.getTime() - 2 * 86400000).toISOString(),+ toTimestamp: new Date(now.getTime() + 86400000).toISOString(),+ orderBy: null,+ },+ "v2",+ true,+ );- expect(result.length).toBeGreaterThan(0);- expect(result[0]).toHaveProperty("time_dimension");- expect(result[0]).toHaveProperty("costType");- expect(result[0]).toHaveProperty("sum_costByType");- });+ expect(result.length).toBeGreaterThan(0);+ expect(result[0]).toHaveProperty("time_dimension");+ expect(result[0]).toHaveProperty("costType");+ expect(result[0]).toHaveProperty("sum_costByType");+ },+ );- it("should respect type filter with pairExpand dimensions", async () => {- const projectId = randomUUID();+ maybeItWithEventsTable(+ "should respect type filter with pairExpand dimensions",+ async () => {+ const projectId = randomUUID();- const events = [- createEvent({- project_id: projectId,- type: "GENERATION",- cost_details: { input: 10 },- start_time: Date.now() * 1000,- }),- createEvent({- project_id: projectId,- type: "SPAN",- cost_details: { input: 999 },- start_time: Date.now() * 1000,- }),- ];- await createEventsCh(events);+ const events = [+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ cost_details: { input: 10 },+ start_time: Date.now() * 1000,+ }),+ createEvent({+ project_id: projectId,+ type: "SPAN",+ cost_details: { input: 999 },+ start_time: Date.now() * 1000,+ }),+ ];+ await createEventsCh(events);- const result = await executeQuery(- projectId,- {- view: "observations",- dimensions: [{ field: "costType" }],- metrics: [{ measure: "costByType", aggregation: "sum" }],- filters: [- {- column: "type",- operator: "=",- value: "GENERATION",- type: "string",- },- ],- timeDimension: null,- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),- toTimestamp: new Date(Date.now() + 86400000).toISOString(),- orderBy: null,- },- "v2",- true,- );+ const result = await executeQuery(+ projectId,+ {+ view: "observations",+ dimensions: [{ field: "costType" }],+ metrics: [{ measure: "costByType", aggregation: "sum" }],+ filters: [+ {+ column: "type",+ operator: "=",+ value: "GENERATION",+ type: "string",+ },+ ],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ },+ "v2",+ true,+ );- const inputRow = result.find((r) => r["costType"] === "input");- // Only GENERATION row contributes: 10, not 999- expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(10, 2);- });+ const inputRow = result.find((r) => r["costType"] === "input");+ // Only GENERATION row contributes: 10, not 999+ expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(10, 2);+ },+ );- it("should aggregate cost_details by type correctly via two-level query path", async () => {- // Forces the two-level path by passing useSingleLevelOptimization=false.- // Verifies that the bare alias reference in buildInnerDimensionsPart- // (not any()) is correct when the pairExpand dim is in GROUP BY.- const projectId = randomUUID();+ maybeItWithEventsTable(+ "should aggregate cost_details by type correctly via two-level query path",+ async () => {+ // Forces the two-level path by passing useSingleLevelOptimization=false.+ // Verifies that the bare alias reference in buildInnerDimensionsPart+ // (not any()) is correct when the pairExpand dim is in GROUP BY.+ const projectId = randomUUID();- const events = [- createEvent({- project_id: projectId,- type: "GENERATION",- cost_details: { input: 10, output: 20, total: 30 },- start_time: Date.now() * 1000,- }),- createEvent({- project_id: projectId,- type: "GENERATION",- cost_details: { input: 5, output: 15, total: 20 },- start_time: Date.now() * 1000,- }),- ];- await createEventsCh(events);+ const events = [+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ cost_details: { input: 10, output: 20, total: 30 },+ start_time: Date.now() * 1000,+ }),+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ cost_details: { input: 5, output: 15, total: 20 },+ start_time: Date.now() * 1000,+ }),+ ];+ await createEventsCh(events);- const result = await executeQuery(- projectId,- {- view: "observations",- dimensions: [{ field: "costType" }],- metrics: [{ measure: "costByType", aggregation: "sum" }],- filters: [],- timeDimension: null,- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),- toTimestamp: new Date(Date.now() + 86400000).toISOString(),- orderBy: null,- },- "v2",- false, // force two-level path- );+ const result = await executeQuery(+ projectId,+ {+ view: "observations",+ dimensions: [{ field: "costType" }],+ metrics: [{ measure: "costByType", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ },+ "v2",+ false, // force two-level path+ );- expect(result).toHaveLength(3);+ expect(result).toHaveLength(3);- const inputRow = result.find((r) => r["costType"] === "input");- expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(15, 2); // 10 + 5+ const inputRow = result.find((r) => r["costType"] === "input");+ expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(15, 2); // 10 + 5- const outputRow = result.find((r) => r["costType"] === "output");- expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(35, 2); // 20 + 15+ const outputRow = result.find((r) => r["costType"] === "output");+ expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(35, 2); // 20 + 15- const totalRow = result.find((r) => r["costType"] === "total");- expect(Number(totalRow?.["sum_costByType"])).toBeCloseTo(50, 2); // 30 + 20- });+ const totalRow = result.find((r) => r["costType"] === "total");+ expect(Number(totalRow?.["sum_costByType"])).toBeCloseTo(50, 2); // 30 + 20+ },+ );- it("should auto-include costType dimension when only costByType measure is requested", async () => {- // Verifies requiresDimension: the query builder must inject the costType- // dimension automatically so the ARRAY JOIN is emitted and cost_value is in scope.- const projectId = randomUUID();+ maybeItWithEventsTable(+ "should auto-include costType dimension when only costByType measure is requested",+ async () => {+ // Verifies requiresDimension: the query builder must inject the costType+ // dimension automatically so the ARRAY JOIN is emitted and cost_value is in scope.+ const projectId = randomUUID();- const events = [- createEvent({- project_id: projectId,- type: "GENERATION",- cost_details: { input: 7, output: 3 },- start_time: Date.now() * 1000,- }),- ];- await createEventsCh(events);+ const events = [+ createEvent({+ project_id: projectId,+ type: "GENERATION",+ cost_details: { input: 7, output: 3 },+ start_time: Date.now() * 1000,+ }),+ ];+ await createEventsCh(events);- // No costType dimension requested — the builder should add it automatically.- const result = await executeQuery(- projectId,- {- view: "observations",- dimensions: [], // intentionally empty- metrics: [{ measure: "costByType", aggregation: "sum" }],- filters: [],- timeDimension: null,- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),- toTimestamp: new Date(Date.now() + 86400000).toISOString(),- orderBy: null,- },- "v2",- true,- );+ // No costType dimension requested — the builder should add it automatically.+ const result = await executeQuery(+ projectId,+ {+ view: "observations",+ dimensions: [], // intentionally empty+ metrics: [{ measure: "costByType", aggregation: "sum" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ },+ "v2",+ true,+ );- // costType should appear in results even though it was not explicitly requested- expect(result.length).toBeGreaterThan(0);- expect(result[0]).toHaveProperty("costType");+ // costType should appear in results even though it was not explicitly requested+ expect(result.length).toBeGreaterThan(0);+ expect(result[0]).toHaveProperty("costType");- const inputRow = result.find((r) => r["costType"] === "input");- expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(7, 2);+ const inputRow = result.find((r) => r["costType"] === "input");+ expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(7, 2);- const outputRow = result.find((r) => r["costType"] === "output");- expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(3, 2);- });+ const outputRow = result.find((r) => r["costType"] === "output");+ expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(3, 2);+ },+ );it("should throw when multiple pairExpand dimensions are requested directly", async () => {// Two separate ARRAY JOIN clauses create a cartesian product in ClickHouse.diff --git a/web/src/__tests__/queryBuilderDashboards.servertest.ts b/web/src/__tests__/server/queryBuilderDashboards.servertest.tssimilarity index 100%rename from web/src/__tests__/queryBuilderDashboards.servertest.tsrename to web/src/__tests__/server/queryBuilderDashboards.servertest.tsdiff --git a/web/src/__tests__/queryBuilderSQLI.servertest.ts b/web/src/__tests__/server/queryBuilderSQLI.servertest.tssimilarity index 100%rename from web/src/__tests__/queryBuilderSQLI.servertest.tsrename to web/src/__tests__/server/queryBuilderSQLI.servertest.tsdiff --git a/web/src/__tests__/rate-limit.servertest.ts b/web/src/__tests__/server/rate-limit.servertest.tssimilarity index 90%rename from web/src/__tests__/rate-limit.servertest.tsrename to web/src/__tests__/server/rate-limit.servertest.tsindex 694b0965f4..67185fbb35 100644--- a/web/src/__tests__/rate-limit.servertest.ts+++ b/web/src/__tests__/server/rate-limit.servertest.ts@@ -2,37 +2,48 @@ import {createHttpHeaderFromRateLimit,RateLimitService,} from "@/src/features/public-api/server/RateLimitService";-import { Redis } from "ioredis";+import {+ clearRedisKeysByPatternSafely,+ createRedisTestClient,+ ensureRedisReady,+ type RedisTestClient,+} from "@/src/__tests__/server/redis-test-utils";describe("RateLimitService", () => {const orgId = "seed-org-id";- let redis: Redis;+ let redis: RedisTestClient;- beforeAll(() => {- redis = new Redis("redis://:[email protected]:6379", {+ const createRedisClient = (): RedisTestClient => {+ return createRedisTestClient({maxRetriesPerRequest: null,enableAutoPipelining: false, // Align with our settings overwrite for rate limit service});- });+ };- afterAll(async () => {- redis.disconnect();- });+ beforeAll(async () => {+ RateLimitService.shutdown();+ redis = createRedisClient();+ await ensureRedisReady(redis);+ }, 20_000);beforeEach(async () => {- expect(redis).toBeDefined();- const keys = await redis?.keys("rate-limit*");- if (keys && keys?.length > 0) {- await redis?.del(keys);+ if (redis.status === "close" || redis.status === "end") {+ RateLimitService.shutdown();+ redis = createRedisClient();}- });+ await ensureRedisReady(redis);+ await clearRedisKeysByPatternSafely(redis, "rate-limit*");+ }, 20_000);afterEach(async () => {- const keys = await redis?.keys("rate-limit*");- if (keys && keys.length > 0) {- await redis?.del(keys);- }- });+ await clearRedisKeysByPatternSafely(redis, "rate-limit*");+ }, 20_000);++ afterAll(async () => {+ await clearRedisKeysByPatternSafely(redis, "rate-limit*");+ redis.disconnect();+ RateLimitService.shutdown();+ }, 20_000);it("should create correct ratelimit headers", () => {const rateLimitRes = {diff --git a/web/src/__tests__/server/redis-test-utils.ts b/web/src/__tests__/server/redis-test-utils.tsnew file mode 100644index 0000000000..f73f1a6683--- /dev/null+++ b/web/src/__tests__/server/redis-test-utils.ts@@ -0,0 +1,114 @@+import {+ createNewRedisInstance,+ safeMultiDel,+ scanKeys,+} from "@langfuse/shared/src/server";+import type { RedisOptions } from "ioredis";++export type RedisTestClient = NonNullable<+ ReturnType<typeof createNewRedisInstance>+>;++const DEFAULT_READY_ATTEMPTS = 20;+const DEFAULT_READY_DELAY_MS = 250;+const DEFAULT_SET_TTL_SECONDS = 3600;++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++export const createRedisTestClient = (+ options: Partial<RedisOptions> = {},+): RedisTestClient => {+ const client = createNewRedisInstance(options);++ if (!client) {+ throw new Error("Failed to initialize Redis client for tests.");+ }++ return client;+};++export const isRedisConnectionClosedError = (error: unknown): boolean =>+ error instanceof Error && error.message.includes("Connection is closed");++export const ensureRedisReady = async (+ redisClient: RedisTestClient,+ attempts = DEFAULT_READY_ATTEMPTS,+ delayMs = DEFAULT_READY_DELAY_MS,+): Promise<void> => {+ let lastError: unknown = null;++ for (let attempt = 0; attempt < attempts; attempt++) {+ try {+ await redisClient.ping();+ return;+ } catch (error) {+ lastError = error;+ if (isRedisConnectionClosedError(error)) {+ try {+ await redisClient.connect();+ } catch {+ // Ignore reconnect errors and retry ping.+ }+ }+ await sleep(delayMs);+ }+ }++ throw lastError ?? new Error("Redis client not ready");+};++export const getRedisKeysByPattern = async (+ redisClient: RedisTestClient,+ pattern: string,+): Promise<string[]> => {+ return await scanKeys(redisClient, pattern);+};++export const clearRedisKeysByPattern = async (+ redisClient: RedisTestClient,+ pattern: string,+): Promise<void> => {+ const keys = await getRedisKeysByPattern(redisClient, pattern);+ if (keys.length > 0) {+ await safeMultiDel(redisClient, keys);+ }+};++export const clearRedisKeysByPatternSafely = async (+ redisClient: RedisTestClient,+ pattern: string,+): Promise<void> => {+ try {+ await clearRedisKeysByPattern(redisClient, pattern);+ } catch (error) {+ if (!isRedisConnectionClosedError(error)) {+ throw error;+ }+ }+};++export const getRedisValue = async (+ redisClient: RedisTestClient,+ key: string,+) => {+ await ensureRedisReady(redisClient);+ return await redisClient.get(key);+};++export const setRedisValue = async (+ redisClient: RedisTestClient,+ key: string,+ value: string,+ ttlSeconds = DEFAULT_SET_TTL_SECONDS,+) => {+ await ensureRedisReady(redisClient);+ return await redisClient.set(key, value, "EX", ttlSeconds);+};++export const getRedisTtl = async (+ redisClient: RedisTestClient,+ key: string,+) => {+ await ensureRedisReady(redisClient);+ return await redisClient.ttl(key);+};diff --git a/web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.ts b/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.tsrename to web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.tsdiff --git a/web/src/__tests__/async/repositories/dashboard-repository.servertest.ts b/web/src/__tests__/server/repositories/dashboard-repository.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/dashboard-repository.servertest.tsrename to web/src/__tests__/server/repositories/dashboard-repository.servertest.tsdiff --git a/web/src/__tests__/async/repositories/dataset-items-repository.servertest.ts b/web/src/__tests__/server/repositories/dataset-items-repository.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/dataset-items-repository.servertest.tsrename to web/src/__tests__/server/repositories/dataset-items-repository.servertest.tsdiff --git a/web/src/__tests__/async/repositories/environment-repository.servertest.ts b/web/src/__tests__/server/repositories/environment-repository.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/environment-repository.servertest.tsrename to web/src/__tests__/server/repositories/environment-repository.servertest.tsdiff --git a/web/src/__tests__/async/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/event-repository.servertest.tsrename to web/src/__tests__/server/repositories/event-repository.servertest.tsdiff --git a/web/src/__tests__/async/repositories/hasAnyTrace.servertest.ts b/web/src/__tests__/server/repositories/hasAnyTrace.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/hasAnyTrace.servertest.tsrename to web/src/__tests__/server/repositories/hasAnyTrace.servertest.tsdiff --git a/web/src/__tests__/async/repositories/observation-repository.servertest.ts b/web/src/__tests__/server/repositories/observation-repository.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/observation-repository.servertest.tsrename to web/src/__tests__/server/repositories/observation-repository.servertest.tsdiff --git a/web/src/__tests__/async/repositories/score-repository.servertest.ts b/web/src/__tests__/server/repositories/score-repository.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/score-repository.servertest.tsrename to web/src/__tests__/server/repositories/score-repository.servertest.tsdiff --git a/web/src/__tests__/async/repositories/trace-repository.servertest.ts b/web/src/__tests__/server/repositories/trace-repository.servertest.tssimilarity index 100%rename from web/src/__tests__/async/repositories/trace-repository.servertest.tsrename to web/src/__tests__/server/repositories/trace-repository.servertest.tsdiff --git a/web/src/__tests__/async/scim-api.servertest.ts b/web/src/__tests__/server/scim-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/scim-api.servertest.tsrename to web/src/__tests__/server/scim-api.servertest.tsdiff --git a/web/src/__tests__/async/score-comparison-analytics.servertest.ts b/web/src/__tests__/server/score-comparison-analytics.servertest.tssimilarity index 100%rename from web/src/__tests__/async/score-comparison-analytics.servertest.tsrename to web/src/__tests__/server/score-comparison-analytics.servertest.tsdiff --git a/web/src/__tests__/score-configs.servertest.ts b/web/src/__tests__/server/score-configs.servertest.tssimilarity index 96%rename from web/src/__tests__/score-configs.servertest.tsrename to web/src/__tests__/server/score-configs.servertest.tsindex 841d8b954a..f3b3314c97 100644--- a/web/src/__tests__/score-configs.servertest.ts+++ b/web/src/__tests__/server/score-configs.servertest.ts@@ -3,7 +3,6 @@import {makeAPICall,makeZodVerifiedAPICall,- pruneDatabase,} from "@/src/__tests__/test-utils";import {GetScoreConfigResponse,@@ -14,10 +13,11 @@ import {import { ScoreConfigDataType } from "@langfuse/shared";import { type ScoreConfig, prisma } from "@langfuse/shared/src/db";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import { v4 } from "uuid";const configOne = [{- projectId: "<to be replaced>",+ projectId: "",name: "Test Boolean Config",description: "Test Description",dataType: ScoreConfigDataType.BOOLEAN,@@ -31,7 +31,7 @@ const configOne = [];const configTwo = [{- projectId: "<to be replaced>",+ projectId: "",name: "Test Numeric Config",description: "Test Description",dataType: ScoreConfigDataType.NUMERIC,@@ -43,7 +43,7 @@ const configTwo = [const configThree = [{- projectId: "<to be replaced>",+ projectId: "",name: "Test Categorical Config",description: "Test Description",dataType: ScoreConfigDataType.CATEGORICAL,@@ -61,29 +61,21 @@ describe("/api/public/score-configs API Endpoint", () => {let auth: string;let projectId: string;- beforeAll(- async () => {- await pruneDatabase();+ beforeEach(async () => {+ const { auth: newAuth, projectId: newProjectId } =+ await createOrgProjectAndApiKey();+ auth = newAuth;+ projectId = newProjectId;- // Create authentication pairs- const { auth: newAuth, projectId: newProjectId } =- await createOrgProjectAndApiKey();- auth = newAuth;- projectId = newProjectId;+ // Update the project IDs in configs to use the new project ID+ configOne[0].projectId = projectId;+ configTwo[0].projectId = projectId;+ configThree[0].projectId = projectId;- // Update the project IDs in configs to use the new project ID- configOne[0].projectId = projectId;- configTwo[0].projectId = projectId;- configThree[0].projectId = projectId;-- await prisma.scoreConfig.createMany({- data: [...configOne, ...configTwo, ...configThree],- });- },- afterAll(async () => {- await pruneDatabase();- }),- );+ await prisma.scoreConfig.createMany({+ data: [...configOne, ...configTwo, ...configThree],+ });+ });it("should GET a score config", async () => {const { id: configId } = (await prisma.scoreConfig.findFirst({@@ -153,7 +145,7 @@ describe("/api/public/score-configs API Endpoint", () => {});it("should return 500 when hitting corrupted score config", async () => {- const configId = "corrupted-config-id";+ const configId = v4();await prisma.scoreConfig.create({data: {diff --git a/web/src/__tests__/async/scores-api-v1.servertest.ts b/web/src/__tests__/server/scores-api-v1.servertest.tssimilarity index 100%rename from web/src/__tests__/async/scores-api-v1.servertest.tsrename to web/src/__tests__/server/scores-api-v1.servertest.tsdiff --git a/web/src/__tests__/async/scores-api-v2.servertest.ts b/web/src/__tests__/server/scores-api-v2.servertest.tssimilarity index 100%rename from web/src/__tests__/async/scores-api-v2.servertest.tsrename to web/src/__tests__/server/scores-api-v2.servertest.tsdiff --git a/web/src/__tests__/async/scores-trpc.servertest.ts b/web/src/__tests__/server/scores-trpc.servertest.tssimilarity index 72%rename from web/src/__tests__/async/scores-trpc.servertest.tsrename to web/src/__tests__/server/scores-trpc.servertest.tsindex d2d2b2a18a..1be381bd83 100644--- a/web/src/__tests__/async/scores-trpc.servertest.ts+++ b/web/src/__tests__/server/scores-trpc.servertest.ts@@ -21,7 +21,6 @@ jest.mock("@langfuse/shared/src/server", () => {});import type { Session } from "next-auth";-import { pruneDatabase } from "@/src/__tests__/test-utils";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -31,49 +30,58 @@ import {ScoreDeleteQueue,BatchActionQueue,QueueJobs,+ createOrgProjectAndApiKey,} from "@langfuse/shared/src/server";import { randomUUID } from "crypto";describe("scores trpc", () => {- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-- beforeEach(pruneDatabase);-- 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 orgId: string;+ let caller: ReturnType<typeof appRouter.createCaller>;++ beforeEach(async () => {+ const setup = await createOrgProjectAndApiKey();+ projectId = setup.projectId;+ orgId = setup.orgId;+ mockAddScoreDelete.mockClear();+ mockAddBatchAction.mockClear();++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: 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 });+ });describe("scores.deleteMany", () => {it("should delete scores by ids", async () => {diff --git a/web/src/__tests__/async/sessions-api.servertest.ts b/web/src/__tests__/server/sessions-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/sessions-api.servertest.tsrename to web/src/__tests__/server/sessions-api.servertest.tsdiff --git a/web/src/__tests__/async/sessions-comment-filter.servertest.ts b/web/src/__tests__/server/sessions-comment-filter.servertest.tssimilarity index 100%rename from web/src/__tests__/async/sessions-comment-filter.servertest.tsrename to web/src/__tests__/server/sessions-comment-filter.servertest.tsdiff --git a/web/src/__tests__/async/sessions-trpc.servertest.ts b/web/src/__tests__/server/sessions-trpc.servertest.tssimilarity index 100%rename from web/src/__tests__/async/sessions-trpc.servertest.tsrename to web/src/__tests__/server/sessions-trpc.servertest.tsdiff --git a/web/src/__tests__/async/sessions-ui-table.servertest.ts b/web/src/__tests__/server/sessions-ui-table.servertest.tssimilarity index 100%rename from web/src/__tests__/async/sessions-ui-table.servertest.tsrename to web/src/__tests__/server/sessions-ui-table.servertest.tsdiff --git a/web/src/__tests__/server/sessions.servertest.ts b/web/src/__tests__/server/sessions.servertest.tsnew file mode 100644index 0000000000..46f275b649--- /dev/null+++ b/web/src/__tests__/server/sessions.servertest.ts@@ -0,0 +1,41 @@+/** @jest-environment node */++import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";+import { PostTracesV1Response } from "@/src/features/public-api/types/traces";+import { prisma } from "@langfuse/shared/src/db";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import { randomUUID } from "crypto";+import waitForExpect from "wait-for-expect";++describe("Create and get sessions", () => {+ it("should create a session via a trace", async () => {+ const { auth, projectId } = await createOrgProjectAndApiKey();+ const sessionId = `session-${randomUUID()}`;++ await makeZodVerifiedAPICall(+ PostTracesV1Response,+ "POST",+ "/api/public/traces",+ {+ name: "trace-name",+ projectId,+ sessionId,+ },+ auth,+ );++ await waitForExpect(async () => {+ const dbSession = await prisma.traceSession.findFirst({+ where: {+ id: sessionId,+ },+ });++ expect(dbSession).not.toBeNull();+ expect(dbSession).toMatchObject({+ id: sessionId,+ projectId,+ });+ });+ });+});diff --git a/web/src/__tests__/async/slack-integration.servertest.ts b/web/src/__tests__/server/slack-integration.servertest.tssimilarity index 100%rename from web/src/__tests__/async/slack-integration.servertest.tsrename to web/src/__tests__/server/slack-integration.servertest.tsdiff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/server/traces-api.servertest.tssimilarity index 100%rename from web/src/__tests__/async/traces-api.servertest.tsrename to web/src/__tests__/server/traces-api.servertest.tsdiff --git a/web/src/__tests__/async/traces-comment-filter.servertest.ts b/web/src/__tests__/server/traces-comment-filter.servertest.tssimilarity index 100%rename from web/src/__tests__/async/traces-comment-filter.servertest.tsrename to web/src/__tests__/server/traces-comment-filter.servertest.tsdiff --git a/web/src/__tests__/async/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.tssimilarity index 100%rename from web/src/__tests__/async/traces-trpc.servertest.tsrename to web/src/__tests__/server/traces-trpc.servertest.tsdiff --git a/web/src/__tests__/async/traces-ui-table.servertest.ts b/web/src/__tests__/server/traces-ui-table.servertest.tssimilarity index 100%rename from web/src/__tests__/async/traces-ui-table.servertest.tsrename to web/src/__tests__/server/traces-ui-table.servertest.tsdiff --git a/web/src/__tests__/async/users-ui-table.servertest.ts b/web/src/__tests__/server/users-ui-table.servertest.tssimilarity index 100%rename from web/src/__tests__/async/users-ui-table.servertest.tsrename to web/src/__tests__/server/users-ui-table.servertest.tsdiff --git a/web/src/__tests__/withMiddlewares.servertest.ts b/web/src/__tests__/server/withMiddlewares.servertest.tssimilarity index 100%rename from web/src/__tests__/withMiddlewares.servertest.tsrename to web/src/__tests__/server/withMiddlewares.servertest.tsdiff --git a/web/src/__tests__/zod.servertest.ts b/web/src/__tests__/server/zod.servertest.tssimilarity index 100%rename from web/src/__tests__/zod.servertest.tsrename to web/src/__tests__/server/zod.servertest.tsdiff --git a/web/src/__tests__/sessions.servertest.ts b/web/src/__tests__/sessions.servertest.tsdeleted file mode 100644index e0d5d8a7c9..0000000000--- a/web/src/__tests__/sessions.servertest.ts+++ /dev/null@@ -1,43 +0,0 @@-/** @jest-environment node */--import {- makeZodVerifiedAPICall,- pruneDatabase,-} from "@/src/__tests__/test-utils";-import { PostTracesV1Response } from "@/src/features/public-api/types/traces";-import { prisma } from "@langfuse/shared/src/db";--describe("Create and get sessions", () => {- beforeEach(async () => await pruneDatabase());- afterEach(async () => await pruneDatabase());-- it("should create a session via a trace", async () => {- await pruneDatabase();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- name: "trace-name",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- sessionId: "session-id",- },- );-- // Delay to allow for async processing- await new Promise((resolve) => setTimeout(resolve, 500));-- const dbSession = await prisma.traceSession.findFirst({- where: {- id: "session-id",- },- });-- expect(dbSession).not.toBeNull();- expect(dbSession).toMatchObject({- id: "session-id",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- });- });-});diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex 47ace16213..e9eea54a5d 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -1,7 +1,6 @@import { env } from "@/src/env.mjs";import { prisma } from "@langfuse/shared/src/db";import {- clickhouseClient,createBasicAuthHeader,getQueue,IngestionQueue,@@ -82,25 +81,6 @@ export const ensureTestDatabaseExists = async () => {// ClickHouse uses default database (no setup needed)};-export const pruneDatabase = async () => {- if (!env.DATABASE_URL.includes("localhost:5432")) {- throw new Error("You cannot prune database unless running on localhost.");- }-- await prisma.scoreConfig.deleteMany();- await prisma.traceSession.deleteMany();- await prisma.datasetItem.deleteMany();- await prisma.dataset.deleteMany();- await prisma.datasetRuns.deleteMany();- await prisma.prompt.deleteMany();- await prisma.promptDependency.deleteMany();- await prisma.model.deleteMany();- await prisma.llmApiKeys.deleteMany();- await prisma.comment.deleteMany();- await prisma.media.deleteMany();-- await truncateClickhouseTables();-};export const getQueues = () => {const queues: string[] = Object.values(QueueName);queues.push(@@ -152,35 +132,6 @@ export const disconnectQueues = async () => {);};-export const truncateClickhouseTables = async () => {- if (!env.CLICKHOUSE_URL?.includes("localhost:8123")) {- throw new Error("You cannot prune clickhouse unless running on localhost.");- }-- // Additional safety check for test database- if (env.CLICKHOUSE_DB === "test") {- console.log(- "Running tests against test ClickHouse database:",- env.CLICKHOUSE_DB,- );- } else if (env.CLICKHOUSE_DB !== "default") {- console.log(- "Running tests against ClickHouse database:",- env.CLICKHOUSE_DB,- );- }-- await clickhouseClient().command({- query: "TRUNCATE TABLE IF EXISTS observations",- });- await clickhouseClient().command({- query: "TRUNCATE TABLE IF EXISTS scores",- });- await clickhouseClient().command({- query: "TRUNCATE TABLE IF EXISTS traces",- });-};-export type IngestionAPIResponse = {errors: ErrorIngestion[];successes: SuccessfulIngestion[];diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.tsindex 79fd925987..7fc7ce8d7e 100644--- a/web/src/features/public-api/server/RateLimitService.ts+++ b/web/src/features/public-api/server/RateLimitService.ts@@ -46,6 +46,8 @@ export class RateLimitService {if (RateLimitService.redis && RateLimitService.redis.status !== "end") {RateLimitService.redis.disconnect();}+ RateLimitService.redis = null;+ RateLimitService.instance = null;}async rateLimitRequest(diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 8bed724f76..f0b16b4b67 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -39,15 +39,15 @@ export class ApiAuthService {// - when projects move across organisations, the orgId in the API key cache needs to be updated// - when the plan of the org changes, the plan in the API key cache needs to be updated as wellasync invalidateCachedApiKeys(apiKeys: ApiKey[], identifier: string) {- await invalidateCachedApiKeysShared(apiKeys, identifier);+ await invalidateCachedApiKeysShared(apiKeys, identifier, this.redis);}async invalidateCachedOrgApiKeys(orgId: string) {- await invalidateCachedOrgApiKeysShared(orgId);+ await invalidateCachedOrgApiKeysShared(orgId, this.redis);}async invalidateCachedProjectApiKeys(projectId: string) {- await invalidateCachedProjectApiKeysShared(projectId);+ await invalidateCachedProjectApiKeysShared(projectId, this.redis);}/**@@ -73,7 +73,7 @@ export class ApiAuthService {// if redis is available, delete the key from there as well// delete from redis even if caching is disabled via env for consistency- this.invalidateCachedApiKeys([apiKey], `key ${id}`);+ await this.invalidateCachedApiKeys([apiKey], `key ${id}`);await this.prisma.apiKey.delete({where: {diff --git a/web/src/features/score-analytics/README.md b/web/src/features/score-analytics/README.mdindex 32ddefa5cc..8870ad9c60 100644--- a/web/src/features/score-analytics/README.md+++ b/web/src/features/score-analytics/README.md@@ -384,7 +384,7 @@ if (isSingleScoreColors(colors)) {## Testing-Backend tests: `/web/src/__tests__/async/score-comparison-analytics.servertest.ts`+Backend tests: `/web/src/__tests__/server/score-comparison-analytics.servertest.ts`Test coverage:- All data types (NUMERIC, BOOLEAN, CATEGORICAL)