Skip to content

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

test: re-enable Vitest parallelism (#13366)

Tobias Wochingerb7723758f2b2
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index 5970e7742f..5db428a285 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -230,7 +230,10 @@ jobs:
persist-credentials: false
- 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
+ curl --fail --location --retry 5 --retry-delay 2 --retry-all-errors \
+ --output migrate.linux-amd64.tar.gz \
+ https://github.com/golang-migrate/migrate/releases/download/v4.19.1/migrate.linux-amd64.tar.gz
+ tar xzf migrate.linux-amd64.tar.gz
sudo mv migrate /usr/bin/migrate
which migrate
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
@@ -364,7 +367,10 @@ jobs:
pnpm install
- 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
+ curl --fail --location --retry 5 --retry-delay 2 --retry-all-errors \
+ --output migrate.linux-amd64.tar.gz \
+ https://github.com/golang-migrate/migrate/releases/download/v4.19.1/migrate.linux-amd64.tar.gz
+ tar xzf migrate.linux-amd64.tar.gz
sudo mv migrate /usr/bin/migrate
which migrate
- name: Load default env
@@ -437,7 +443,10 @@ jobs:
pnpm install
- 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
+ curl --fail --location --retry 5 --retry-delay 2 --retry-all-errors \
+ --output migrate.linux-amd64.tar.gz \
+ https://github.com/golang-migrate/migrate/releases/download/v4.19.1/migrate.linux-amd64.tar.gz
+ tar xzf migrate.linux-amd64.tar.gz
sudo mv migrate /usr/bin/migrate
which migrate
- name: Load default env
@@ -531,7 +540,10 @@ jobs:
cp .env.dev.example web/.env
- 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
+ curl --fail --location --retry 5 --retry-delay 2 --retry-all-errors \
+ --output migrate.linux-amd64.tar.gz \
+ https://github.com/golang-migrate/migrate/releases/download/v4.19.1/migrate.linux-amd64.tar.gz
+ tar xzf migrate.linux-amd64.tar.gz
sudo mv migrate /usr/bin/migrate
which migrate
- name: Run + migrate
@@ -588,7 +600,10 @@ jobs:
pnpm install
- 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
+ curl --fail --location --retry 5 --retry-delay 2 --retry-all-errors \
+ --output migrate.linux-amd64.tar.gz \
+ https://github.com/golang-migrate/migrate/releases/download/v4.19.1/migrate.linux-amd64.tar.gz
+ tar xzf migrate.linux-amd64.tar.gz
sudo mv migrate /usr/bin/migrate
which migrate
- name: Load default env
diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.ts
index 014cacd6c6..1456b46ea8 100644
--- a/web/src/__tests__/server/api-auth.servertest.ts
+++ b/web/src/__tests__/server/api-auth.servertest.ts
@@ -2,6 +2,7 @@ import {
OrgEnrichedApiKey,
createBasicAuthHeader,
createOrgProjectAndApiKey,
+ createShaHash,
generateKeySet,
} from "@langfuse/shared/src/server";
import { Prisma, type PrismaClient, prisma } from "@langfuse/shared/src/db";
@@ -46,8 +47,13 @@ describe("Authenticate API calls", () => {
`${testApiKey.secretKey}-wrong`,
);
- const createMissingAuthHeader = () =>
- createBasicAuthHeader(`pk-missing-${v4()}`, `sk-missing-${v4()}`);
+ const createMissingAuthHeader = () => {
+ const secretKey = `sk-missing-${v4()}`;
+ return {
+ auth: createBasicAuthHeader(`pk-missing-${v4()}`, secretKey),
+ redisKey: `api-key:${createShaHash(secretKey, env.SALT)}`,
+ };
+ };
const getApiKeyCacheKeys = async (
redisClient: RedisTestClient,
@@ -492,13 +498,16 @@ describe("Authenticate API calls", () => {
const verification = await new ApiAuthService(
prisma,
redis,
- ).verifyAuthHeaderAndReturnScope(missingAuthHeader);
+ ).verifyAuthHeaderAndReturnScope(missingAuthHeader.auth);
expect(verification.validKey).toBe(false);
- const redisKeys = await getApiKeyCacheKeys(redis, "api-key:*");
+ const redisKeys = await getApiKeyCacheKeys(
+ redis,
+ missingAuthHeader.redisKey,
+ );
expect(redisKeys.length).toBe(1);
- const redisValue = await getRedisValue(redis, redisKeys[0]);
+ const redisValue = await getRedisValue(redis, missingAuthHeader.redisKey);
expect(redisValue).toBe('"api-key-non-existent"');
});
@@ -509,24 +518,33 @@ describe("Authenticate API calls", () => {
const verification = await new ApiAuthService(
prisma,
redis,
- ).verifyAuthHeaderAndReturnScope(missingAuthHeader);
+ ).verifyAuthHeaderAndReturnScope(missingAuthHeader.auth);
expect(verification.validKey).toBe(false);
- const redisKeys = await getApiKeyCacheKeys(redis, "api-key:*");
+ const redisKeys = await getApiKeyCacheKeys(
+ redis,
+ missingAuthHeader.redisKey,
+ );
expect(redisKeys.length).toBe(1);
- const redisValue = await getRedisValue(redis, redisKeys[0]);
+ const redisValue = await getRedisValue(redis, missingAuthHeader.redisKey);
expect(redisValue).toBe('"api-key-non-existent"');
const verification2 = await new ApiAuthService(
prisma,
redis,
- ).verifyAuthHeaderAndReturnScope(missingAuthHeader);
+ ).verifyAuthHeaderAndReturnScope(missingAuthHeader.auth);
expect(verification2.validKey).toBe(false);
- const redisKeys2 = await getApiKeyCacheKeys(redis, "api-key:*");
+ const redisKeys2 = await getApiKeyCacheKeys(
+ redis,
+ missingAuthHeader.redisKey,
+ );
expect(redisKeys2.length).toBe(1);
- const redisValue2 = await getRedisValue(redis, redisKeys[0]);
+ const redisValue2 = await getRedisValue(
+ redis,
+ missingAuthHeader.redisKey,
+ );
expect(redisValue2).toBe('"api-key-non-existent"');
});
@@ -763,10 +781,11 @@ describe("Authenticate API calls", () => {
});
it("if no keys in redis, invalidating org keys should do nothing", async () => {
+ const fastHashedSecretKey = `test-fast-hash-${v4()}`;
await prisma.apiKey.update({
where: { publicKey: testApiKey.publicKey },
data: {
- fastHashedSecretKey: Math.random().toString(36).substring(2, 15),
+ fastHashedSecretKey,
},
});
@@ -774,8 +793,11 @@ describe("Authenticate API calls", () => {
testApiKey.orgId,
);
- const keys = await getApiKeyCacheKeys(redis);
- expect(keys.length).toBe(0);
+ const cachedKey = await getRedisValue(
+ redis,
+ `api-key:${fastHashedSecretKey}`,
+ );
+ expect(cachedKey).toBeNull();
});
it("if no keys in redis, invalidating org keys without fast hash should do nothing", async () => {
@@ -783,8 +805,11 @@ describe("Authenticate API calls", () => {
testApiKey.orgId,
);
- const keys = await getApiKeyCacheKeys(redis);
- expect(keys.length).toBe(0);
+ const keysForCurrentApiKey = await getApiKeyCacheKeys(
+ redis,
+ `api-key:${createShaHash(testApiKey.secretKey, env.SALT)}`,
+ );
+ expect(keysForCurrentApiKey.length).toBe(0);
});
it("should invalidate project API keys in redis", async () => {
@@ -819,10 +844,11 @@ describe("Authenticate API calls", () => {
});
it("if no keys in redis, invalidating project keys should do nothing", async () => {
+ const fastHashedSecretKey = `test-fast-hash-${v4()}`;
await prisma.apiKey.update({
where: { publicKey: testApiKey.publicKey },
data: {
- fastHashedSecretKey: Math.random().toString(36).substring(2, 15),
+ fastHashedSecretKey,
},
});
@@ -830,8 +856,11 @@ describe("Authenticate API calls", () => {
testApiKey.projectId,
);
- const keys = await getApiKeyCacheKeys(redis);
- expect(keys.length).toBe(0);
+ const cachedKey = await getRedisValue(
+ redis,
+ `api-key:${fastHashedSecretKey}`,
+ );
+ expect(cachedKey).toBeNull();
});
it("if no keys in redis, invalidating project keys without fast hash should do nothing", async () => {
@@ -846,8 +875,11 @@ describe("Authenticate API calls", () => {
testApiKey.projectId,
);
- const keys = await getApiKeyCacheKeys(redis);
- expect(keys.length).toBe(0);
+ const keysForCurrentApiKey = await getApiKeyCacheKeys(
+ redis,
+ `api-key:${createShaHash(testApiKey.secretKey, env.SALT)}`,
+ );
+ expect(keysForCurrentApiKey.length).toBe(0);
});
});
diff --git a/web/src/__tests__/server/ingestion-api.servertest.ts b/web/src/__tests__/server/ingestion-api.servertest.ts
index 015a7ef19f..871ce9dd64 100644
--- a/web/src/__tests__/server/ingestion-api.servertest.ts
+++ b/web/src/__tests__/server/ingestion-api.servertest.ts
@@ -6,12 +6,22 @@ import {
getObservationById,
getScoreById,
getTraceById,
+ createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
-const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+let projectId: string;
+let auth: string;
+
+const postIngestion = (body: unknown) =>
+ makeAPICall("POST", "/api/public/ingestion", body, auth);
describe("/api/public/ingestion API Endpoint", () => {
+ beforeEach(async () => {
+ const fixture = await createOrgProjectAndApiKey();
+ projectId = fixture.projectId;
+ auth = fixture.auth;
+ });
it.each([
[
"plain",
@@ -87,7 +97,7 @@ describe("/api/public/ingestion API Endpoint", () => {
])(
"should create traces via the ingestion API (%s)",
async (_name: string, entity: any) => {
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [entity],
});
@@ -125,7 +135,7 @@ describe("/api/public/ingestion API Endpoint", () => {
// environment: "production",
// },
// };
- // const response = await makeAPICall("POST", "/api/public/ingestion", {
+ // const response = await postIngestion({
// batch: [entity],
// });
//
@@ -364,7 +374,7 @@ describe("/api/public/ingestion API Endpoint", () => {
])(
"should create observations via the ingestion API (%s)",
async (_name: string, type: string, entity: any) => {
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [
{
id: randomUUID(),
@@ -437,7 +447,7 @@ describe("/api/public/ingestion API Endpoint", () => {
])(
"should create scores via the ingestion API (%s)",
async (_name: string, entity: any) => {
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [entity],
});
@@ -489,7 +499,7 @@ describe("/api/public/ingestion API Endpoint", () => {
async (char: string) => {
const traceId = randomUUID();
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [
{
id: randomUUID(),
@@ -522,7 +532,7 @@ describe("/api/public/ingestion API Endpoint", () => {
it("should fail for \\r in id", async () => {
const traceId = v4();
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [
{
id: `${v4()}-\r-test`,
@@ -557,7 +567,7 @@ describe("/api/public/ingestion API Endpoint", () => {
const repeatCount = Math.ceil(1500 / baseString.length);
const name = baseString.repeat(repeatCount);
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [
{
id: v4(),
@@ -583,7 +593,7 @@ describe("/api/public/ingestion API Endpoint", () => {
});
it("should silently drop invalid float values in usageDetails", async () => {
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [
{
id: v4(),
@@ -632,7 +642,7 @@ describe("/api/public/ingestion API Endpoint", () => {
},
};
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [entity],
});
@@ -647,7 +657,7 @@ describe("/api/public/ingestion API Endpoint", () => {
const traceId = v4();
const eventId = v4();
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [
{
id: eventId,
@@ -700,7 +710,7 @@ describe("/api/public/ingestion API Endpoint", () => {
},
};
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [entity],
});
@@ -741,7 +751,7 @@ describe("/api/public/ingestion API Endpoint", () => {
},
};
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [entity],
});
@@ -786,7 +796,7 @@ describe("/api/public/ingestion API Endpoint", () => {
},
};
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [entity],
});
@@ -819,11 +829,6 @@ describe("/api/public/ingestion API Endpoint", () => {
},
};
- const response1 = await makeAPICall("POST", "/api/public/ingestion", {
- batch: [traceUpdate1],
- });
- expect(response1.status).toBe(207);
-
// Second update with additional metadata: {"step": 2, "error": ""}
// This should merge with the first update
const traceUpdate2 = {
@@ -838,7 +843,20 @@ describe("/api/public/ingestion API Endpoint", () => {
},
};
- const response2 = await makeAPICall("POST", "/api/public/ingestion", {
+ const response1 = await postIngestion({
+ batch: [traceUpdate1],
+ });
+ expect(response1.status).toBe(207);
+
+ await waitForExpect(async () => {
+ const trace = await getTraceById({ traceId, projectId });
+ expect(trace?.metadata).toEqual({
+ step: 1,
+ status: "started",
+ });
+ }, 15_000);
+
+ const response2 = await postIngestion({
batch: [traceUpdate2],
});
expect(response2.status).toBe(207);
@@ -892,7 +910,7 @@ describe("/api/public/ingestion API Endpoint", () => {
},
};
- const response = await makeAPICall("POST", "/api/public/ingestion", {
+ const response = await postIngestion({
batch: [score1, score2],
});
diff --git a/web/src/__tests__/server/observations-api-v2.servertest.ts b/web/src/__tests__/server/observations-api-v2.servertest.ts
index 6a04620b95..49a69682bc 100644
--- a/web/src/__tests__/server/observations-api-v2.servertest.ts
+++ b/web/src/__tests__/server/observations-api-v2.servertest.ts
@@ -1,15 +1,31 @@
import {
createEvent,
createEventsCh,
+ createOrgProjectAndApiKey,
queryClickhouse,
} from "@langfuse/shared/src/server";
-import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";
+import {
+ makeAPICall,
+ makeZodVerifiedAPICall,
+} from "@/src/__tests__/test-utils";
import { GetObservationsV2Response } from "@/src/features/public-api/types/observations";
import { randomUUID } from "crypto";
import { env } from "@/src/env.mjs";
import waitForExpect from "wait-for-expect";
-const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+let projectId: string;
+let auth: string;
+
+const getObservations = (url: string) =>
+ makeZodVerifiedAPICall(
+ GetObservationsV2Response,
+ "GET",
+ url,
+ undefined,
+ auth,
+ );
+
+const getRaw = (url: string) => makeAPICall("GET", url, undefined, auth);
const maybe =
env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"
@@ -17,6 +33,12 @@ const maybe =
: describe.skip;
describe("/api/public/v2/observations API Endpoint", () => {
+ beforeEach(async () => {
+ const fixture = await createOrgProjectAndApiKey();
+ projectId = fixture.projectId;
+ auth = fixture.auth;
+ });
+
it("should kill redis connection", () => {
// we need at least one test case to avoid hanging
// redis connection when everything else is skipped.
@@ -51,10 +73,8 @@ describe("/api/public/v2/observations API Endpoint", () => {
await createEventsCh([observation]);
// Request only basic field group (core is always included)
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
- `/api/public/v2/observations?fields=basic`,
+ const response = await getObservations(
+ `/api/public/v2/observations?fields=basic&traceId=${traceId}`,
);
expect(response.status).toBe(200);
@@ -114,9 +134,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
await createEventsCh([observation]);
// Request with parseIoAsJson=false (default)
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?fields=io&traceId=${traceId}&parseIoAsJson=false`,
);
@@ -132,9 +150,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
});
it("should return 400 when parseIoAsJson=true", async () => {
- const { makeAPICall } = await import("@/src/__tests__/test-utils");
- const response = await makeAPICall(
- "GET",
+ const response = await getRaw(
`/api/public/v2/observations?fields=io&parseIoAsJson=true`,
);
@@ -144,25 +160,36 @@ describe("/api/public/v2/observations API Endpoint", () => {
});
it("should respect limit parameter with default of 50", async () => {
+ const timestamp = Date.now() * 1000;
+ const observations = Array.from({ length: 6 }, (_, index) => {
+ const observationId = randomUUID();
+ return createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: randomUUID(),
+ project_id: projectId,
+ name: `limit-test-observation-${index}`,
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timestamp + index,
+ });
+ });
+
+ await createEventsCh(observations);
+
// Test default limit
- const response1 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
- "/api/public/v2/observations",
- );
+ const response1 = await getObservations("/api/public/v2/observations");
expect(response1.status).toBe(200);
- expect(response1.body.data.length).toBeLessThanOrEqual(50);
+ expect(response1.body.data.length).toBe(6);
// Test custom limit
- const response2 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response2 = await getObservations(
"/api/public/v2/observations?limit=5",
);
expect(response2.status).toBe(200);
- expect(response2.body.data.length).toBeLessThanOrEqual(5);
+ expect(response2.body.data.length).toBe(5);
});
it("should support standard filters (name, type, level, etc.)", async () => {
@@ -186,9 +213,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
await createEventsCh([observation]);
// Test filtering by name
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?fields=basic&name=unique-observation-name`,
);
@@ -335,9 +360,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
// Test each filter to ensure no SQL crashes
for (const testCase of filterTestCases) {
const filterParam = JSON.stringify(testCase.filter);
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&fields=basic,io,cost,model,metadata&filter=${encodeURIComponent(filterParam)}`,
);
@@ -358,9 +381,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
value: "test-user-123",
},
]);
- const userIdFilterResponse = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const userIdFilterResponse = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&fields=basic&filter=${encodeURIComponent(userIdFilterParam)}`,
);
@@ -381,9 +402,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
value: "test",
},
]);
- const traceNameResponse = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const traceNameResponse = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&fields=basic&filter=${encodeURIComponent(traceNameFilterParam)}`,
);
@@ -455,9 +474,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
},
]);
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&fields=basic,metadata&filter=${encodeURIComponent(filterParam)}`,
);
@@ -517,9 +534,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
);
// Request metadata with expansion - this switches to events_full table
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&fields=metadata&expandMetadata=expandMe`,
);
@@ -575,9 +590,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
);
// Request expansion for a key that doesn't exist
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&fields=metadata&expandMetadata=nonExistentKey`,
);
@@ -633,9 +646,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
);
// Request metadata with empty expandMetadata - should use events_core (truncated)
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&fields=metadata&expandMetadata=`,
);
@@ -694,9 +705,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
);
// Request with limit=5 - should return exactly 5, not all 10
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&limit=5`,
);
@@ -734,9 +743,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
await createEventsCh(observations);
// Fetch with limit=2 (should have cursor since we have 3 observations)
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&limit=2`,
);
@@ -772,9 +779,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
await createEventsCh(observations);
// Fetch with limit=5 (should not have cursor since we only have 2)
- const response = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const response = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&limit=5`,
);
@@ -809,9 +814,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
await createEventsCh(observations);
// Fetch first page with limit=2
- const page1 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const page1 = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&limit=2`,
);
@@ -822,9 +825,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
const page1Ids = page1.body.data.map((obs: any) => obs.id);
// Fetch second page using cursor
- const page2 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const page2 = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&limit=2&cursor=${page1.body.meta.cursor}`,
);
@@ -839,9 +840,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
expect(overlap.length).toBe(0);
// Fetch third page
- const page3 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const page3 = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&limit=2&cursor=${page2.body.meta.cursor}`,
);
@@ -900,9 +899,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
await createEventsCh([obs1, obs2, obs3]);
// Fetch first page
- const page1 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const page1 = await getObservations(
`/api/public/v2/observations?userId=${userId}&limit=2&fromStartTime=${new Date(timeValue / 1000).toISOString()}&toStartTime=${new Date(timeValue / 1000 + 1000).toISOString()}`,
);
@@ -912,9 +909,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
const page1Ids = page1.body.data.map((obs: any) => obs.id);
// Fetch second page using cursor
- const page2 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const page2 = await getObservations(
`/api/public/v2/observations?userId=${userId}&limit=2&cursor=${page1.body.meta.cursor}`,
);
@@ -959,9 +954,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
await createEventsCh(observations);
// Fetch first page with type filter
- const page1 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const page1 = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&type=SPAN&limit=2`,
);
@@ -973,9 +966,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
expect(page1.body.meta.cursor).toBeDefined();
// Fetch second page with same filter and cursor
- const page2 = await makeZodVerifiedAPICall(
- GetObservationsV2Response,
- "GET",
+ const page2 = await getObservations(
`/api/public/v2/observations?traceId=${traceId}&type=SPAN&limit=2&cursor=${page1.body.meta.cursor}`,
);
@@ -993,9 +984,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
});
it("should reject invalid cursor format", async () => {
- const { makeAPICall } = await import("@/src/__tests__/test-utils");
- const response = await makeAPICall(
- "GET",
+ const response = await getRaw(
`/api/public/v2/observations?fields=id&cursor=invalid-base64-string`,
);
diff --git a/web/src/__tests__/server/observations-api.servertest.ts b/web/src/__tests__/server/observations-api.servertest.ts
index f8bbf4127e..a878d0ea41 100644
--- a/web/src/__tests__/server/observations-api.servertest.ts
+++ b/web/src/__tests__/server/observations-api.servertest.ts
@@ -3,6 +3,7 @@ import {
createTrace,
createTracesCh,
createEvent,
+ createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
import {
createObservationsCh,
@@ -16,8 +17,6 @@ import { GetObservationsV1Response } from "@/src/features/public-api/types/obser
import { randomUUID } from "crypto";
import { env } from "@/src/env.mjs";
-const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
-
// Helper type for creating observation data
type ObservationData = {
id?: string;
@@ -111,6 +110,15 @@ const createAndInsertObservations = async (
};
describe("/api/public/observations API Endpoint", () => {
+ let projectId: string;
+ let auth: string;
+
+ beforeAll(async () => {
+ const fixture = await createOrgProjectAndApiKey();
+ projectId = fixture.projectId;
+ auth = fixture.auth;
+ });
+
// Test suite factory to run tests against both implementations
const runTestSuite = (useEventsTable: boolean) => {
const suiteName = useEventsTable
@@ -275,6 +283,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
@@ -459,6 +469,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}traceId=${traceId}&level=DEBUG`,
+ undefined,
+ auth,
);
expect(debugResponse.body.data.length).toBe(1);
@@ -471,6 +483,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}traceId=${traceId}&level=DEFAULT`,
+ undefined,
+ auth,
);
expect(defaultResponse.body.data.length).toBe(1);
@@ -483,6 +497,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}traceId=${traceId}&level=WARNING`,
+ undefined,
+ auth,
);
expect(warningResponse.body.data.length).toBe(1);
@@ -495,6 +511,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}traceId=${traceId}&level=ERROR`,
+ undefined,
+ auth,
);
expect(errorResponse.body.data.length).toBe(1);
@@ -543,6 +561,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}traceId=${traceId}&level=ERROR`,
+ undefined,
+ auth,
);
expect(errorResponse.body.data.length).toBe(0);
@@ -615,6 +635,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}&traceId=${traceId}&filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.body.data.length).toBe(1);
@@ -667,6 +689,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}&traceId=${traceId}&type=GENERATION&filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
// Should match only test-generation (both filters applied)
@@ -683,6 +707,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}&filter=${encodeURIComponent(malformedFilter)}`,
+ undefined,
+ auth,
);
fail("Should have thrown an error");
} catch (error) {
@@ -719,6 +745,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}&traceId=${traceId}&filter=`,
+ undefined,
+ auth,
);
expect(response.body.data.length).toBe(1);
@@ -764,6 +792,8 @@ describe("/api/public/observations API Endpoint", () => {
const response = await makeAPICall(
"GET",
`/api/public/observations${queryParam}&traceId=${traceId}&type=GENERATION&filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(400);
@@ -869,6 +899,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
@@ -984,6 +1016,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}traceId=${traceId}&filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
@@ -1075,6 +1109,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}traceId=${traceId}&filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
@@ -1210,6 +1246,8 @@ describe("/api/public/observations API Endpoint", () => {
GetObservationsV1Response,
"GET",
`/api/public/observations${queryParam}traceId=${traceId}&filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
diff --git a/web/src/__tests__/server/prompts.v2.servertest.ts b/web/src/__tests__/server/prompts.v2.servertest.ts
index 1a20d4f981..0bb62e5812 100644
--- a/web/src/__tests__/server/prompts.v2.servertest.ts
+++ b/web/src/__tests__/server/prompts.v2.servertest.ts
@@ -25,6 +25,10 @@ import { createPrompt } from "@/src/features/prompts/server/actions/createPrompt
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
const baseURI = "/api/public/v2/prompts";
+afterAll(async () => {
+ await disconnectQueues();
+});
+
type CreatePromptInDBParams = {
promptId?: string;
name: string;
@@ -124,9 +128,6 @@ const testPromptEquality = (
};
describe("/api/public/v2/prompts API Endpoint", () => {
- afterAll(async () => {
- await disconnectQueues();
- });
describe("when fetching a prompt", () => {
it("should return a 401 if key is invalid", async () => {
const projectId = uuidv4();
@@ -1897,10 +1898,6 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {
let triggerId: string;
let actionId: string;
- afterAll(async () => {
- await disconnectQueues();
- });
-
it("should update the labels of a prompt", async () => {
const { projectId: newProjectId, auth: newAuth } =
await createOrgProjectAndApiKey();
diff --git a/web/src/__tests__/server/rate-limit.servertest.ts b/web/src/__tests__/server/rate-limit.servertest.ts
index 58104f4870..fbc057b841 100644
--- a/web/src/__tests__/server/rate-limit.servertest.ts
+++ b/web/src/__tests__/server/rate-limit.servertest.ts
@@ -1,7 +1,9 @@
import {
createHttpHeaderFromRateLimit,
+ RATE_LIMIT_REDIS_KEY_PREFIX,
RateLimitService,
} from "@/src/features/public-api/server/RateLimitService";
+import { randomUUID } from "crypto";
import {
clearRedisKeysByPatternSafely,
createRedisTestClient,
@@ -10,7 +12,9 @@ import {
} from "@/src/__tests__/server/redis-test-utils";
describe("RateLimitService", () => {
- const orgId = "seed-org-id";
+ const orgId = `rate-limit-test-org-${randomUUID()}`;
+ const projectId = `rate-limit-test-project-${randomUUID()}`;
+ const rateLimitKeysPattern = `${RATE_LIMIT_REDIS_KEY_PREFIX}:*:${orgId}`;
let redis: RedisTestClient;
const createRedisClient = (): RedisTestClient => {
@@ -32,15 +36,15 @@ describe("RateLimitService", () => {
redis = createRedisClient();
}
await ensureRedisReady(redis);
- await clearRedisKeysByPatternSafely(redis, "rate-limit*");
+ await clearRedisKeysByPatternSafely(redis, rateLimitKeysPattern);
}, 20_000);
afterEach(async () => {
- await clearRedisKeysByPatternSafely(redis, "rate-limit*");
+ await clearRedisKeysByPatternSafely(redis, rateLimitKeysPattern);
}, 20_000);
afterAll(async () => {
- await clearRedisKeysByPatternSafely(redis, "rate-limit*");
+ await clearRedisKeysByPatternSafely(redis, rateLimitKeysPattern);
redis.disconnect();
RateLimitService.shutdown();
}, 20_000);
@@ -54,7 +58,7 @@ describe("RateLimitService", () => {
scope: {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [],
},
@@ -76,7 +80,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [],
};
@@ -99,7 +103,9 @@ describe("RateLimitService", () => {
expect(result?.isRateLimited()).toBe(false);
// check redis for the rate limit key
- const value = await redis.get("rate-limit:public-api:seed-org-id");
+ const value = await redis.get(
+ `${RATE_LIMIT_REDIS_KEY_PREFIX}:public-api:${orgId}`,
+ );
expect(value).toBeDefined();
expect(parseInt(value ?? "0")).toBeGreaterThan(0);
@@ -109,7 +115,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [],
};
@@ -135,7 +141,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [
{ resource: "public-api" as const, points: 100, durationInSec: 2 },
@@ -185,7 +191,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [
{ resource: "public-api" as const, points: 5, durationInSec: 60 },
@@ -216,7 +222,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [
{ resource: "public-api" as const, points: 5, durationInSec: 10 },
@@ -242,7 +248,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [
{ resource: "public-api" as const, points: 5, durationInSec: 10 },
@@ -261,7 +267,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [
{ resource: "ingestion" as const, points: null, durationInSec: null },
@@ -280,7 +286,7 @@ describe("RateLimitService", () => {
// const scope = {
// orgId: orgId,
// plan: "cloud:hobby" as const,
- // projectId: "test-project-id",
+ // projectId,
// accessLevel: "project" as const,
// rateLimitOverrides: [
// { resource: "public-api" as const, points: 5, durationInSec: 10 },
@@ -299,7 +305,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "oss" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [],
};
@@ -316,7 +322,7 @@ describe("RateLimitService", () => {
const scope = {
orgId: orgId,
plan: "cloud:hobby" as const,
- projectId: "test-project-id",
+ projectId,
accessLevel: "project" as const,
rateLimitOverrides: [],
};
diff --git a/web/src/__tests__/server/traces-api.servertest.ts b/web/src/__tests__/server/traces-api.servertest.ts
index f48a5168fc..7d1c5522fd 100644
--- a/web/src/__tests__/server/traces-api.servertest.ts
+++ b/web/src/__tests__/server/traces-api.servertest.ts
@@ -6,6 +6,7 @@ import {
createTrace,
getTraceById,
createEvent,
+ createOrgProjectAndApiKey,
type EventRecordInsertType,
} from "@langfuse/shared/src/server";
import {
@@ -28,8 +29,6 @@ import snakeCase from "lodash/snakeCase";
import { env } from "@/src/env.mjs";
import waitForExpect from "wait-for-expect";
-const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
-
// Helper type for creating observation/event data
// Times are always in milliseconds, conversion handled internally
type ObservationEventData = {
@@ -156,6 +155,15 @@ const createTraceWithObservations = async (
};
describe("/api/public/traces API Endpoint", () => {
+ let projectId: string;
+ let auth: string;
+
+ beforeEach(async () => {
+ const fixture = await createOrgProjectAndApiKey();
+ projectId = fixture.projectId;
+ auth = fixture.auth;
+ });
+
it("should create and get a trace via /traces", async () => {
const createdTrace = createTrace({
name: "trace-name",
@@ -194,6 +202,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTraceV1Response,
"GET",
"/api/public/traces/" + createdTrace.id,
+ undefined,
+ auth,
);
expect(trace.body.name).toBe("trace-name");
@@ -256,6 +266,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTraceV1Response,
"GET",
`/api/public/traces/${traceId}?fields=core`,
+ undefined,
+ auth,
);
expect(trace.body.id).toBe(traceId);
@@ -304,6 +316,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTraceV1Response,
"GET",
`/api/public/traces/${traceId}?fields=core,scores,metrics`,
+ undefined,
+ auth,
);
expect(trace.body.id).toBe(traceId);
@@ -342,6 +356,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTraceV1Response,
"GET",
`/api/public/traces/${traceId}?fields=invalid_group,also_invalid`,
+ undefined,
+ auth,
);
// All invalid fields should fall back to returning all field groups
@@ -393,6 +409,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces",
+ undefined,
+ auth,
);
expect(traces.body.meta.totalItems).toBeGreaterThanOrEqual(1);
@@ -443,6 +461,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces?${prop}=${value}`,
+ undefined,
+ auth,
);
expect(traces.body.meta.totalItems).toBe(1);
@@ -498,6 +518,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces?environment=${environment}`,
+ undefined,
+ auth,
);
expect(traces.body.meta.totalItems).toBe(1);
@@ -558,6 +580,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces?environment=${environment}`,
+ undefined,
+ auth,
);
expect(traces.body.meta.totalItems).toBe(1);
@@ -584,6 +608,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces?tags=${[tag]}`,
+ undefined,
+ auth,
);
expect(traces.body.meta.totalItems).toBe(1);
@@ -619,6 +645,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces?tags=${[tag]}&limit=1&offset=1`,
+ undefined,
+ auth,
);
expect(traces.body.meta.totalItems).toBe(3);
@@ -649,6 +677,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces?tags=${[tag]}&orderBy=name.desc`,
+ undefined,
+ auth,
);
expect(traces.body.meta.totalItems).toBe(2);
@@ -664,6 +694,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?page=0&limit=10",
+ undefined,
+ auth,
);
expect(response.status).toBe(400);
@@ -674,6 +706,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?page=0&limit=10",
+ undefined,
+ auth,
);
expect(response.status).toBe(400);
@@ -681,9 +715,10 @@ describe("/api/public/traces API Endpoint", () => {
it("LFE-3699: should fetch a single trace with unescaped metadata via traces list", async () => {
const traceId = randomUUID();
+ const traceName = `trace-name-${traceId}`;
const trace = createTrace({
id: traceId,
- name: "trace-name1",
+ name: traceName,
project_id: projectId,
metadata: { key: JSON.stringify({ foo: "bar" }) },
input: JSON.stringify({
@@ -700,12 +735,14 @@ describe("/api/public/traces API Endpoint", () => {
const traces = await makeZodVerifiedAPICall(
GetTracesV1Response,
"GET",
- `/api/public/traces`,
+ `/api/public/traces?name=${encodeURIComponent(traceName)}&limit=1`,
+ undefined,
+ auth,
);
const traceResponse = traces.body.data.find((t) => t.id === traceId);
expect(traceResponse).toBeDefined();
- expect(traceResponse!.name).toBe("trace-name1");
+ expect(traceResponse!.name).toBe(traceName);
expect(traceResponse!.metadata).toEqual({ key: { foo: "bar" } });
expect(traceResponse!.input).toEqual({
args: [
@@ -738,6 +775,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTraceV1Response,
"GET",
`/api/public/traces/${traceId}`,
+ undefined,
+ auth,
);
expect(traceResponse.body.name).toBe("trace-name1");
@@ -797,6 +836,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTraceV1Response,
"GET",
`/api/public/traces/${traceId}`,
+ undefined,
+ auth,
),
).rejects.toThrow(
"Observations in trace are too large: 90.00MB exceeds limit of 80.00MB",
@@ -816,6 +857,8 @@ describe("/api/public/traces API Endpoint", () => {
DeleteTraceV1Response,
"DELETE",
`/api/public/traces/${createdTrace.id}`,
+ undefined,
+ auth,
);
// Then
@@ -846,6 +889,7 @@ describe("/api/public/traces API Endpoint", () => {
{
traceIds: [createdTrace1.id, createdTrace2.id],
},
+ auth,
);
// Then
@@ -904,6 +948,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces",
+ undefined,
+ auth,
);
const trace = traces.body.data.find((t) => t.id === traceId);
@@ -957,6 +1003,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?fields=core",
+ undefined,
+ auth,
);
const trace = traces.body.data.find((t) => t.id === traceId);
@@ -999,6 +1047,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?fields=core,io",
+ undefined,
+ auth,
);
const trace = traces.body.data.find((t) => t.id === traceId);
@@ -1041,6 +1091,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?fields=core,scores",
+ undefined,
+ auth,
);
const trace = traces.body.data.find((t) => t.id === traceId);
@@ -1083,6 +1135,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?fields=core,observations",
+ undefined,
+ auth,
);
const trace = traces.body.data.find((t) => t.id === traceId);
@@ -1126,6 +1180,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?fields=core,metrics",
+ undefined,
+ auth,
);
const trace = traces.body.data.find((t) => t.id === traceId);
@@ -1150,6 +1206,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?fields=core,invalid,scores",
+ undefined,
+ auth,
);
// Should still work, just ignoring invalid field names
@@ -1196,6 +1254,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?fields=",
+ undefined,
+ auth,
);
// Should default to all fields when empty
@@ -1235,7 +1295,7 @@ describe("/api/public/traces API Endpoint", () => {
const testTraceId = randomUUID();
const testTraceId2 = randomUUID();
- beforeAll(async () => {
+ beforeEach(async () => {
// Create test traces with different metadata for filtering
const trace1 = createTrace({
id: testTraceId,
@@ -1293,6 +1353,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(filterParam)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1329,6 +1391,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(filterParam)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1362,6 +1426,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(filterParam)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1381,6 +1447,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`userId=filter-user-1&environment=production`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1412,6 +1480,8 @@ describe("/api/public/traces API Endpoint", () => {
buildUrl(
`userId=filter-user-2&filter=${encodeURIComponent(filterParam)}`,
),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1445,6 +1515,8 @@ describe("/api/public/traces API Endpoint", () => {
buildUrl(
`userId=filter-user-1&filter=${encodeURIComponent(filterParam)}`,
),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1466,6 +1538,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(malformedFilter)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(400);
@@ -1485,6 +1559,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(invalidFilterParam)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(400);
@@ -1495,6 +1571,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200); // Empty string should be treated as undefined
@@ -1514,6 +1592,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(invalidStructure)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(400);
@@ -1533,6 +1613,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(invalidOperator)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(400);
@@ -1559,6 +1641,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(filterRange)}`),
+ undefined,
+ auth,
);
expect(tracesRange.status).toBe(200);
@@ -1590,6 +1674,8 @@ describe("/api/public/traces API Endpoint", () => {
buildUrl(
`orderBy=timestamp.asc&fromTimestamp=2023-01-01T00:00:00Z&toTimestamp=2023-01-02T00:00:00Z&filter=${encodeURIComponent(filterParam)}`,
),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1675,6 +1761,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(filterParam)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1705,6 +1793,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`filter=${encodeURIComponent(filterParam2)}`),
+ undefined,
+ auth,
);
expect(traces2.status).toBe(200);
@@ -1828,6 +1918,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`fields=core&filter=${encodeURIComponent(filterParam)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -1919,6 +2011,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`fields=core&filter=${encodeURIComponent(filterParam)}`),
+ undefined,
+ auth,
);
expect(traces.status).toBe(200);
@@ -2003,6 +2097,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`fields=core,io,observations,metrics`),
+ undefined,
+ auth,
);
const trace = traces.body.data.find((t) => t.id === traceId);
@@ -2052,6 +2148,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`userId=${userId}`),
+ undefined,
+ auth,
);
expect(traces.body.meta.totalItems).toBeGreaterThanOrEqual(1);
@@ -2080,6 +2178,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`name=${traceName}`),
+ undefined,
+ auth,
);
const matchingTrace = traces.body.data.find((t) => t.id === traceId);
@@ -2103,6 +2203,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`environment=${environment}`),
+ undefined,
+ auth,
);
const matchingTrace = traces.body.data.find((t) => t.id === traceId);
@@ -2130,6 +2232,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`page=1&limit=2`),
+ undefined,
+ auth,
);
// Get page 2
@@ -2137,6 +2241,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`page=2&limit=2`),
+ undefined,
+ auth,
);
expect(page1.body.data.length).toBeLessThanOrEqual(2);
@@ -2181,6 +2287,8 @@ describe("/api/public/traces API Endpoint", () => {
buildUrl(
`fromTimestamp=${yesterday.toISOString()}&toTimestamp=${tomorrow.toISOString()}`,
),
+ undefined,
+ auth,
);
const inRangeFound = traces.body.data.find(
@@ -2218,6 +2326,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`fields=core,scores`),
+ undefined,
+ auth,
);
const trace = traces.body.data.find((t) => t.id === traceId);
@@ -2244,6 +2354,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
buildUrl(`name=count-test-${prefix}`),
+ undefined,
+ auth,
);
expect(result.body.meta.totalItems).toBeGreaterThanOrEqual(3);
@@ -2284,6 +2396,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces",
+ undefined,
+ auth,
);
expect(response.status).toBe(400);
@@ -2299,6 +2413,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces?fromTimestamp=${fromTimestamp}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
@@ -2312,6 +2428,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces",
+ undefined,
+ auth,
);
expect(response.status).toBe(400);
@@ -2352,6 +2470,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces",
+ undefined,
+ auth,
);
const trace = response.body.data.find((t) => t.id === traceId);
@@ -2385,6 +2505,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
"/api/public/traces?fields=core,io",
+ undefined,
+ auth,
);
const trace = response.body.data.find((t) => t.id === traceId);
@@ -2426,6 +2548,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
@@ -2451,6 +2575,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
@@ -2482,6 +2608,8 @@ describe("/api/public/traces API Endpoint", () => {
GetTracesV1Response,
"GET",
`/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,
+ undefined,
+ auth,
);
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index 374d422961..7602121532 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -143,14 +143,22 @@ export const getQueues = () => {
);
};
-export const disconnectQueues = async () => {
+export const disconnectQueues = async (disconnectTimeoutMs = 2_000) => {
await Promise.all(
getQueues().map(async (queue) => {
if (queue) {
+ let timeoutId: NodeJS.Timeout | undefined;
try {
- queue.disconnect();
+ await Promise.race([
+ queue.disconnect(),
+ new Promise<void>((resolve) => {
+ timeoutId = setTimeout(resolve, disconnectTimeoutMs);
+ }),
+ ]);
} catch (error) {
logger.error(`Error disconnecting queue ${queue.name}: ${error}`);
+ } finally {
+ if (timeoutId) clearTimeout(timeoutId);
}
}
}),
diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.ts
index 79d017a49f..cb14541d7d 100644
--- a/web/src/features/public-api/server/RateLimitService.ts
+++ b/web/src/features/public-api/server/RateLimitService.ts
@@ -24,6 +24,8 @@ import {
type PublicApiErrorContract,
} from "@/src/features/public-api/server/unstable-public-api-error-contract";
+export const RATE_LIMIT_REDIS_KEY_PREFIX = "rate-limit";
+
// Business Logic
// - rate limit strategy is based on org-id, org plan, and resources. Rate limits are applied in buckets of minutes.
// - rate limits are not applied for self hosters and are also not applied when Redis is not available
@@ -157,7 +159,7 @@ export class RateLimitService {
}
rateLimitPrefix(resource: string) {
- return `rate-limit:${resource}`;
+ return `${RATE_LIMIT_REDIS_KEY_PREFIX}:${resource}`;
}
}
diff --git a/web/vitest.config.mts b/web/vitest.config.mts
index cd2786b1b4..976763a7a6 100644
--- a/web/vitest.config.mts
+++ b/web/vitest.config.mts
@@ -31,7 +31,6 @@ export default defineConfig({
environment: "node",
setupFiles: ["./src/__tests__/after-teardown.ts"],
globalSetup: ["./src/__tests__/vitest-global-teardown.ts"],
- maxWorkers: 1,
},
},
{
@@ -43,7 +42,6 @@ export default defineConfig({
environment: "node",
setupFiles: ["./src/__tests__/after-teardown.ts"],
globalSetup: ["./src/__tests__/vitest-global-teardown.ts"],
- maxWorkers: 1,
},
},
],
diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.ts
index 633b97678d..8f23ba181b 100644
--- a/worker/src/__tests__/batchAction.test.ts
+++ b/worker/src/__tests__/batchAction.test.ts
@@ -5,10 +5,13 @@ import {
BatchActionStatus,
EvalTargetObject,
} from "@langfuse/shared";
-import { expect, describe, it, vi } from "vitest";
+import { expect, describe, it } from "vitest";
import { v4 as uuidv4 } from "uuid";
import { handleBatchActionJob } from "../features/batchAction/handleBatchActionJob";
-import { getDatabaseReadStreamPaginated } from "../features/database-read-stream/getDatabaseReadStream";
+import {
+ getDatabaseReadStreamPaginated,
+ getTraceIdentifierStream,
+} from "../features/database-read-stream/getDatabaseReadStream";
import {
createOrgProjectAndApiKey,
createTraceScore,
@@ -17,24 +20,95 @@ import {
createTracesCh,
createEvent,
createEventsCh,
- getQueue,
getScoresByIds,
QueueJobs,
QueueName,
- logger,
createDatasetRunItemsCh,
createDatasetRunItem,
createDatasetItem,
+ createNewRedisInstance,
+ getQueuePrefix,
+ redisQueueRetryOptions,
+ TQueueJobTypes,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { Decimal } from "decimal.js";
import waitForExpect from "wait-for-expect";
+import { Queue } from "bullmq";
const maybeDescribe =
process.env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"
? describe
: describe.skip;
+const withIsolatedCreateEvalQueue = async <T>(
+ projectId: string,
+ fn: (queue: Queue<TQueueJobTypes[QueueName.CreateEvalQueue]>) => Promise<T>,
+) => {
+ const queueName = `${QueueName.CreateEvalQueue}-${projectId}-${uuidv4()}`;
+ const redis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+ if (!redis) {
+ throw new Error("Redis is not initialized");
+ }
+
+ const queue = new Queue<TQueueJobTypes[QueueName.CreateEvalQueue]>(
+ queueName,
+ {
+ connection: redis,
+ prefix: getQueuePrefix(queueName),
+ },
+ );
+
+ try {
+ return await fn(queue);
+ } finally {
+ try {
+ await queue.obliterate({ force: true });
+ } finally {
+ try {
+ await queue.close();
+ } finally {
+ redis.disconnect();
+ }
+ }
+ }
+};
+
+const getCreateEvalQueueJobs = async (
+ queue: Queue<TQueueJobTypes[QueueName.CreateEvalQueue]>,
+) => {
+ return await queue.getJobs([
+ "waiting",
+ "delayed",
+ "paused",
+ "prioritized",
+ "active",
+ "completed",
+ "failed",
+ ]);
+};
+
+const waitForCreateEvalQueueJobs = async ({
+ queue,
+ expectedLength,
+}: {
+ queue: Queue<TQueueJobTypes[QueueName.CreateEvalQueue]>;
+ expectedLength: number;
+}) => {
+ let jobs: Awaited<ReturnType<typeof getCreateEvalQueueJobs>> = [];
+
+ await waitForExpect(async () => {
+ jobs = await getCreateEvalQueueJobs(queue);
+
+ expect(jobs.map((job) => job.data.payload)).toHaveLength(expectedLength);
+ }, 15_000);
+
+ return jobs;
+};
+
describe("select all test suite", () => {
it("should schedule trace deletions via pending_deletions table", async () => {
const { projectId } = await createOrgProjectAndApiKey();
@@ -223,25 +297,23 @@ describe("select all test suite", () => {
});
it("should create eval jobs for historic traces", async () => {
- // remove all jobs from the evaluation execution queue
- const queue = getQueue(QueueName.CreateEvalQueue);
- await queue?.obliterate({ force: true });
-
const { projectId } = await createOrgProjectAndApiKey();
+ const traceTimestamp = new Date("2024-01-01T00:00:00.000Z");
+ const cutoffCreatedAt = new Date("2024-01-02T00:00:00.000Z"); // one day later
const traceId1 = uuidv4();
const traces = [
createTrace({
project_id: projectId,
id: traceId1,
user_id: "user1",
- timestamp: new Date().getTime(),
+ timestamp: traceTimestamp.getTime(),
}),
createTrace({
project_id: projectId,
id: uuidv4(),
user_id: "user2",
- timestamp: new Date().getTime(),
+ timestamp: traceTimestamp.getTime(),
}),
];
@@ -298,7 +370,7 @@ describe("select all test suite", () => {
actionId: "eval-create" as const,
targetObject: EvalTargetObject.TRACE,
configId,
- cutoffCreatedAt: new Date(),
+ cutoffCreatedAt,
query: {
filter: [
{
@@ -316,36 +388,48 @@ describe("select all test suite", () => {
},
};
- await handleBatchActionJob(payload);
-
await waitForExpect(async () => {
- try {
- const queue = getQueue(QueueName.CreateEvalQueue);
+ const traceStream = await getTraceIdentifierStream({
+ projectId,
+ cutoffCreatedAt,
+ filter: payload.payload.query.filter,
+ orderBy: payload.payload.query.orderBy,
+ });
+
+ const traceIds: string[] = [];
+ for await (const trace of traceStream) {
+ traceIds.push(trace.id);
+ }
- const jobs = await queue?.getJobs();
+ expect(traceIds).toEqual([traceId1]);
+ }, 15_000);
- expect(jobs).toHaveLength(1);
+ await withIsolatedCreateEvalQueue(projectId, async (queue) => {
+ await handleBatchActionJob(payload, { evalCreatorQueue: queue });
- if (!jobs) {
- throw new Error("No jobs found");
- }
+ const jobs = await waitForCreateEvalQueueJobs({
+ queue,
+ expectedLength: 1,
+ });
- const job = jobs[0];
+ const job = jobs[0];
- expect(job.name).toBe("create-eval-job");
- expect(job.data.payload.projectId).toBe(projectId);
- expect(job.data.payload.traceId).toBe(traceId1);
- expect(job.data.payload.configId).toBe(configId);
- } catch (e) {
- logger.error(e);
- throw e;
+ if (!job) {
+ throw new Error("No jobs found");
}
+
+ expect(job.data.payload.projectId).toBe(projectId);
+ expect(job.data.payload.traceId).toBe(traceId1);
+ expect(job.data.payload.configId).toBe(configId);
});
- });
+ }, 30_000);
it("should create eval jobs for historic datasets", async () => {
const { projectId } = await createOrgProjectAndApiKey();
+ const traceTimestamp = new Date("2024-01-01T00:00:00.000Z");
+ const datasetRunItemTimestamp = new Date("2024-01-01T00:00:00.000Z");
+ const cutoffCreatedAt = new Date("2024-01-02T00:00:00.000Z"); // one day later
const traceId1 = uuidv4();
const traceId2 = uuidv4();
@@ -354,13 +438,13 @@ describe("select all test suite", () => {
project_id: projectId,
id: traceId1,
user_id: "user1",
- timestamp: new Date().getTime(),
+ timestamp: traceTimestamp.getTime(),
}),
createTrace({
project_id: projectId,
id: traceId2,
user_id: "user2",
- timestamp: new Date().getTime(),
+ timestamp: traceTimestamp.getTime(),
}),
];
@@ -411,6 +495,10 @@ describe("select all test suite", () => {
trace_id: traceId1,
dataset_run_id: runId,
dataset_id: dataset.id,
+ dataset_run_created_at: datasetRunItemTimestamp.getTime(),
+ created_at: datasetRunItemTimestamp.getTime(),
+ updated_at: datasetRunItemTimestamp.getTime(),
+ event_ts: datasetRunItemTimestamp.getTime(),
});
const datasetRunItem2 = createDatasetRunItem({
@@ -420,28 +508,14 @@ describe("select all test suite", () => {
trace_id: traceId2,
dataset_run_id: runId,
dataset_id: dataset.id,
+ dataset_run_created_at: datasetRunItemTimestamp.getTime(),
+ created_at: datasetRunItemTimestamp.getTime(),
+ updated_at: datasetRunItemTimestamp.getTime(),
+ event_ts: datasetRunItemTimestamp.getTime(),
});
await createDatasetRunItemsCh([datasetRunItem1, datasetRunItem2]);
- // Create clickhouse run items
- await createDatasetRunItemsCh([
- createDatasetRunItem({
- project_id: projectId,
- dataset_id: dataset.id,
- dataset_run_id: runId,
- dataset_item_id: datasetItem1.id,
- trace_id: traceId1,
- }),
- createDatasetRunItem({
- project_id: projectId,
- dataset_id: dataset.id,
- dataset_run_id: runId,
- dataset_item_id: datasetItem2.id,
- trace_id: traceId2,
- }),
- ]);
-
const templateId = uuidv4();
await prisma.evalTemplate.create({
@@ -484,9 +558,6 @@ describe("select all test suite", () => {
},
});
- const queue = getQueue(QueueName.CreateEvalQueue);
- await queue?.obliterate({ force: true });
-
const payload = {
id: uuidv4(),
timestamp: new Date(),
@@ -496,7 +567,7 @@ describe("select all test suite", () => {
actionId: "eval-create" as const,
targetObject: EvalTargetObject.DATASET,
configId,
- cutoffCreatedAt: new Date(),
+ cutoffCreatedAt,
query: {
filter: [
{
@@ -514,50 +585,60 @@ describe("select all test suite", () => {
},
};
- await handleBatchActionJob(payload);
-
await waitForExpect(async () => {
- try {
- const jobs = await queue?.getJobs();
- expect(jobs).toHaveLength(2);
- const jobTraceIds = jobs?.map((job) => job.data.payload.traceId);
- expect(jobTraceIds).toContain(traceId1);
- expect(jobTraceIds).toContain(traceId2);
-
- const jobDatasetIds = jobs?.map(
- (job) => job.data.payload.datasetItemId,
- );
- expect(jobDatasetIds).toContain(datasetItem1.id);
- expect(jobDatasetIds).toContain(datasetItem2.id);
- const configIds = jobs?.map((job) => job.data.payload.configId);
- expect(configIds).toContain(configId);
- } catch (e) {
- logger.error(e);
- throw e;
+ const dbReadStream = await getDatabaseReadStreamPaginated({
+ projectId,
+ cutoffCreatedAt,
+ filter: payload.payload.query.filter,
+ orderBy: payload.payload.query.orderBy,
+ tableName: BatchTableNames.DatasetRunItems,
+ });
+
+ const datasetRunItems: unknown[] = [];
+ for await (const item of dbReadStream) {
+ datasetRunItems.push(item);
}
+
+ expect(datasetRunItems).toHaveLength(2);
+ }, 15_000);
+
+ await withIsolatedCreateEvalQueue(projectId, async (queue) => {
+ await handleBatchActionJob(payload, { evalCreatorQueue: queue });
+
+ const jobs = await waitForCreateEvalQueueJobs({
+ queue,
+ expectedLength: 2,
+ });
+
+ const jobTraceIds = jobs.map((job) => job.data.payload.traceId);
+ expect(jobTraceIds).toContain(traceId1);
+ expect(jobTraceIds).toContain(traceId2);
+
+ const jobDatasetIds = jobs.map((job) => job.data.payload.datasetItemId);
+ expect(jobDatasetIds).toContain(datasetItem1.id);
+ expect(jobDatasetIds).toContain(datasetItem2.id);
+ const configIds = jobs.map((job) => job.data.payload.configId);
+ expect(configIds).toContain(configId);
});
- });
+ }, 30_000);
it("should not create evals if config does not exist", async () => {
const { projectId } = await createOrgProjectAndApiKey();
// Create a trace
const traceId = uuidv4();
+ const traceTimestamp = new Date("2024-01-01T00:00:00.000Z");
await createTracesCh([
createTrace({
project_id: projectId,
id: traceId,
- timestamp: new Date("2024-01-01").getTime(),
+ timestamp: traceTimestamp.getTime(),
}),
]);
// Use a non-existent config ID
const nonExistentConfigId = uuidv4();
- const queue = getQueue(QueueName.CreateEvalQueue);
- // Clear any existing jobs
- await queue?.obliterate({ force: true });
-
const payload = {
id: uuidv4(),
timestamp: new Date(),
@@ -567,7 +648,7 @@ describe("select all test suite", () => {
actionId: "eval-create" as const,
targetObject: EvalTargetObject.TRACE,
configId: nonExistentConfigId,
- cutoffCreatedAt: new Date(),
+ cutoffCreatedAt: new Date("2024-01-02T00:00:00.000Z"),
query: {
filter: [],
orderBy: {
@@ -578,12 +659,16 @@ describe("select all test suite", () => {
},
};
- // This should not throw
- await expect(handleBatchActionJob(payload)).resolves.not.toThrow();
+ await withIsolatedCreateEvalQueue(projectId, async (queue) => {
+ await expect(
+ handleBatchActionJob(payload, { evalCreatorQueue: queue }),
+ ).resolves.not.toThrow();
+
+ const jobs = await waitForCreateEvalQueueJobs({
+ queue,
+ expectedLength: 0,
+ });
- // Verify no jobs were created
- await waitForExpect(async () => {
- const jobs = await queue?.getJobs();
expect(jobs).toHaveLength(0);
});
});
diff --git a/worker/src/__tests__/evalService.filtering.test.ts b/worker/src/__tests__/evalService.filtering.test.ts
index 7e448fac66..a1a76447d3 100644
--- a/worker/src/__tests__/evalService.filtering.test.ts
+++ b/worker/src/__tests__/evalService.filtering.test.ts
@@ -174,7 +174,7 @@ const test = baseTest.extend<{
},
});
-describe.concurrent("test eval filtering", () => {
+describe("test eval filtering", () => {
test("creates eval job only for matching environment", async ({
expect,
upsertTwoTraces,
diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.ts
index 5f12ffc07f..ef7e07d318 100644
--- a/worker/src/features/batchAction/handleBatchActionJob.ts
+++ b/worker/src/features/batchAction/handleBatchActionJob.ts
@@ -21,7 +21,7 @@ import {
getTraceIdentifierStream,
} from "../database-read-stream/getDatabaseReadStream";
import { env } from "../../env";
-import { Job } from "bullmq";
+import { Job, Queue } from "bullmq";
import {
processAddObservationsToQueue,
processAddSessionsToQueue,
@@ -46,6 +46,10 @@ const convertDatesInFiltersFromStrings = (filters: FilterCondition[]) => {
);
};
+type HandleBatchActionJobDeps = {
+ evalCreatorQueue?: Queue<TQueueJobTypes[QueueName.CreateEvalQueue]>;
+};
+
/**
* ⚠️ All operations must be idempotent. In case of failure, the job should be retried.
* If it does, chunks that have already been processed might be processed again.
@@ -136,6 +140,7 @@ const assertIsDatasetRunItemTableRecord = (
export const handleBatchActionJob = async (
batchActionJob: Job<TQueueJobTypes[QueueName.BatchActionQueue]>["data"],
+ deps: HandleBatchActionJobDeps = {},
) => {
const batchActionEvent: BatchActionProcessingEventType =
batchActionJob.payload;
@@ -256,7 +261,8 @@ export const handleBatchActionJob = async (
rowLimit: env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,
});
- const evalCreatorQueue = CreateEvalQueue.getInstance();
+ const evalCreatorQueue =
+ deps.evalCreatorQueue ?? CreateEvalQueue.getInstance();
if (!evalCreatorQueue) {
logger.error("CreateEvalQueue is not initialized");
return;
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index c8fc022f25..74637deabe 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -16,12 +16,12 @@ import {
TraceRecordReadType,
createOrgProjectAndApiKey,
createIngestionEventSchema,
+ setNoEvalConfigsCache,
} from "@langfuse/shared/src/server";
import waitForExpect from "wait-for-expect";
import { ClickhouseWriter, TableName } from "../../ClickhouseWriter";
import { IngestionService } from "../../IngestionService";
import { ModelUsageUnit, ScoreSourceEnum } from "@langfuse/shared";
-import { Cluster } from "ioredis";
import { env } from "../../../env";
let projectId = "";
@@ -35,12 +35,7 @@ describe("Ingestion end-to-end tests", () => {
beforeEach(async () => {
if (!redis) throw new Error("Redis not initialized");
({ projectId } = await createOrgProjectAndApiKey());
-
- if (redis instanceof Cluster) {
- await Promise.all(redis.nodes("master").map((node) => node.flushall()));
- } else {
- await redis.flushall();
- }
+ await setNoEvalConfigsCache(projectId, "traceBased");
clickhouseWriter = ClickhouseWriter.getInstance();
diff --git a/worker/vitest.config.ts b/worker/vitest.config.ts
index 5bfa9abbeb..80ed18db8a 100644
--- a/worker/vitest.config.ts
+++ b/worker/vitest.config.ts
@@ -8,7 +8,6 @@ export default defineConfig({
test: {
dir: "./src",
pool: "forks",
- maxWorkers: 1,
server: {
deps: {
inline: ["@langfuse/shared"],