🪢 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
fix(experiments): return stable experiment id upon POST /dataset-run-items to perserve SDK expectations (#15616)
marliessophied920b3f8a1e6
diff --git a/web/src/__tests__/server/datasets-api.servertest.ts b/web/src/__tests__/server/datasets-api.servertest.tsindex 6d2fe6501f..807fac1d13 100644--- a/web/src/__tests__/server/datasets-api.servertest.ts+++ b/web/src/__tests__/server/datasets-api.servertest.ts@@ -4,6 +4,10 @@ process.env.LANGFUSE_DATASET_SERVICE_READ_FROM_VERSIONED_IMPLEMENTATION =process.env.LANGFUSE_DATASET_SERVICE_WRITE_TO_VERSIONED_IMPLEMENTATION = "true";import { prisma } from "@langfuse/shared/src/db";+import {+ buildStableDatasetRunItemResponseEventsOnly,+ createStableExperimentId,+} from "@/src/features/datasets/server/publicDatasetService";import {makeAPICall,makeZodVerifiedAPICall,@@ -1080,6 +1084,87 @@ describe("/api/public/datasets and /api/public/dataset-items API Endpoints", ()expect(runItemBoth.status).toBe(200);}, 90000);+ // The experiment id is what the SDK reuses across every item POST of a run,+ // so it must be identical for the same (projectId, datasetId, runName) and+ // carry the SDK's seeded id shape (16 hex chars).+ it("createStableExperimentId is deterministic and matches the SDK id shape", () => {+ const args = {+ projectId: "p-1",+ datasetId: "d-1",+ runName: "run-1",+ };+ const id = createStableExperimentId(args);++ expect(id).toMatch(/^[0-9a-f]{16}$/);+ expect(createStableExperimentId(args)).toBe(id);+ expect(createStableExperimentId({ ...args, runName: "run-2" })).not.toBe(+ id,+ );+ expect(createStableExperimentId({ ...args, datasetId: "d-2" })).not.toBe(+ id,+ );+ });++ // events_only is exercised against the helper directly: makeAPICall hits a+ // real HTTP server whose write mode we cannot flip from the test process.+ it("events_only returns a stable experiment id per run without persisting", async () => {+ const datasetId = v4();+ await prisma.dataset.create({+ data: { id: datasetId, name: "events-only-dataset", projectId },+ });+ const itemResult = await createDatasetItem({+ projectId,+ datasetId,+ input: { key: "value" },+ validateOpts: { normalizeUndefinedToNull: true },+ });+ if (!itemResult.success) throw new Error(itemResult.message);+ const datasetItemId = itemResult.datasetItem.id;++ const runName = "events-only-run";+ // The helper only reads auth.scope.projectId.+ const helperAuth = { scope: { projectId } } as any;++ const first = await buildStableDatasetRunItemResponseEventsOnly({+ auth: helperAuth,+ body: {+ datasetItemId,+ traceId,+ runName,+ metadata: { key: "value" },+ } as any,+ });++ expect(first.datasetRunName).toBe(runName);+ expect(first.datasetItemId).toBe(datasetItemId);+ expect(first.traceId).toBe(traceId);+ expect(first.datasetRunId).toBe(+ createStableExperimentId({ projectId, datasetId, runName }),+ );++ // Stable across separate POSTs of the same run, even with a different trace.+ const second = await buildStableDatasetRunItemResponseEventsOnly({+ auth: helperAuth,+ body: { datasetItemId, traceId: v4(), runName } as any,+ });+ expect(second.datasetRunId).toBe(first.datasetRunId);++ // Nothing is persisted: no dataset run row is created in Postgres.+ const dbRun = await prisma.datasetRuns.findFirst({+ where: { projectId, name: runName },+ });+ expect(dbRun).toBeNull();++ // A genuinely missing dataset item still 404s (not the "endpoint+ // unavailable" 404 we removed).+ await expect(+ buildStableDatasetRunItemResponseEventsOnly({+ auth: helperAuth,+ body: { datasetItemId: "does-not-exist", traceId, runName } as any,+ }),+ ).rejects.toThrow("Dataset item not found");+ });+it("GET /api/public/datasets/{datasetName}/runs", async () => {// create multiple runsawait makeZodVerifiedAPICall(diff --git a/web/src/features/datasets/server/publicDatasetService.ts b/web/src/features/datasets/server/publicDatasetService.tsindex 8617c35eb3..424f4c8fba 100644--- a/web/src/features/datasets/server/publicDatasetService.ts+++ b/web/src/features/datasets/server/publicDatasetService.ts@@ -1,4 +1,5 @@import type { NextApiResponse } from "next";+import { createHash } from "node:crypto";import { v4 } from "uuid";import { auditLog } from "@/src/features/audit-logs/auditLog";import { addDatasetRunItemsToEvalQueue } from "@/src/features/evals/server/addDatasetRunItemsToEvalQueue";@@ -728,6 +729,96 @@ export const deleteDatasetItemForApi = async ({};};+/**+ * Deterministic, stable experiment id (== dataset run id) for a+ * (projectId, datasetId, runName) triple.+ *+ * The Langfuse experiment runner calls POST /dataset-run-items once per dataset+ * item and uses the returned dataset run id as the experiment id shared by every+ * item of the run (see langfuse-python client.py: `experiment_id = dataset_run_id+ * or fallback`). So the value MUST be identical across the separate, stateless+ * POST requests that make up one run — hashing the run's identity gives us that+ * without persisting anything.+ *+ * We take the first 8 bytes of a sha256 digest (16 hex chars), matching the+ * shape of the SDK's own seeded id helper (`sha256(seed).digest()[:8].hex()`).+ */+export const createStableExperimentId = ({+ projectId,+ datasetId,+ runName,+}: {+ projectId: string;+ datasetId: string;+ runName: string;+}): string =>+ createHash("sha256")+ .update(+ JSON.stringify(["langfuse-experiment-v1", projectId, datasetId, runName]),+ "utf8",+ )+ .digest("hex")+ .slice(0, 16);++/**+ * events_only deployments no longer write dataset run items into the legacy+ * dataset_run_items ClickHouse table, so the full createDatasetRunItemForApi+ * flow has nothing to persist. The experiment runner still calls POST+ * /dataset-run-items per item and expects a dataset run id it can reuse as the+ * experiment id across the whole run, so we resolve the item's dataset and+ * return a stable experiment id derived from (projectId, datasetId, runName).+ *+ * In v4 the trace ↔ experiment link is established through OTel experiment span+ * attributes instead, so beyond the dataset-item lookup (needed for datasetId+ * and to 404 on genuinely missing items) we skip every legacy side effect:+ * the observation→trace lookup, ClickHouse ingestion, and the eval enqueue.+ */+export const buildStableDatasetRunItemResponseEventsOnly = async ({+ body,+ auth,+}: Pick<CreateDatasetRunItemInput, "body" | "auth">) => {+ const projectId = auth.scope.projectId;++ if (!projectId) {+ throw new UnauthorizedError(+ "Missing projectId in scope. Are you using an organization key?",+ );+ }++ const datasetItem = await getDatasetItemById({+ projectId,+ datasetItemId: body.datasetItemId,+ status: "ACTIVE",+ version: body.datasetVersion ?? undefined,+ });++ if (!datasetItem) {+ throw new LangfuseNotFoundError("Dataset item not found");+ }++ const experimentId = createStableExperimentId({+ projectId,+ datasetId: datasetItem.datasetId,+ runName: body.runName,+ });+ const createdAt = body.createdAt ? new Date(body.createdAt) : new Date();++ const datasetRunItem: APIDatasetRunItem = {+ id: v4(),+ datasetRunId: experimentId,+ datasetRunName: body.runName,+ datasetItemId: datasetItem.id,+ // events_only skips the observation→trace lookup; echo whatever the caller+ // provided (the body schema requires traceId or observationId).+ traceId: body.traceId ?? "",+ observationId: body.observationId ?? null,+ createdAt,+ updatedAt: createdAt,+ };++ return datasetRunItem;+};+export const createDatasetRunItemForApi = async ({body,auth,diff --git a/web/src/pages/api/public/dataset-run-items.ts b/web/src/pages/api/public/dataset-run-items.tsindex 3909f3a6e5..10c89eedaa 100644--- a/web/src/pages/api/public/dataset-run-items.ts+++ b/web/src/pages/api/public/dataset-run-items.ts@@ -8,9 +8,11 @@ import {} from "@/src/features/public-api/types/datasets";import {createDatasetRunItemForApi,+ buildStableDatasetRunItemResponseEventsOnly,listDatasetRunItemsForApi,} from "@/src/features/datasets/server/publicDatasetService";import { DATASET_RUN_ITEMS_DEPRECATION } from "@/src/features/public-api/server/deprecations";+import { env } from "@/src/env.mjs";export default withMiddlewares({POST: createAuthedProjectAPIRoute({@@ -19,10 +21,18 @@ export default withMiddlewares({responseSchema: PostDatasetRunItemsV1Response,rateLimitResource: "datasets",// Writes a dataset-run-item event into the legacy dataset_run_items- // ClickHouse table; events_only deployments expect the experiment runner- // SDK or OTel ingestion with experiment attributes instead.- rejectInEventsOnlyMode: true,+ // ClickHouse table. events_only deployments no longer populate that table,+ // so instead of writing anything we return a stable experiment id (== the+ // dataset run id) derived deterministically from (projectId, datasetId,+ // runName). The trace ↔ experiment link is established through OTel+ // experiment span attributes on ingestion instead.fn: async ({ body, auth, res }) => {+ if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only") {+ return await buildStableDatasetRunItemResponseEventsOnly({+ body,+ auth,+ });+ }return await createDatasetRunItemForApi({ body, auth, res });},}),