Skip to content

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

test: add column contract tests for blob export and API v2 field groups (#13481)

Niklas Semmlerb94a230c53c6
diff --git a/web/src/__tests__/server/observations-api-v2.servertest.ts b/web/src/__tests__/server/observations-api-v2.servertest.ts
index 49a69682bc..ce2fe322b6 100644
--- a/web/src/__tests__/server/observations-api-v2.servertest.ts
+++ b/web/src/__tests__/server/observations-api-v2.servertest.ts
@@ -489,6 +489,194 @@ describe("/api/public/v2/observations API Endpoint", () => {
});
});
+ maybe("Field group contract", () => {
+ // Core fields always returned regardless of which group is requested
+ const CORE_FIELDS = [
+ "id",
+ "traceId",
+ "type",
+ "startTime",
+ "endTime",
+ "projectId",
+ "parentObservationId",
+ ] as const;
+
+ // All non-core fields across all groups — used to assert absence.
+ // Note: latency is computed from start_time/end_time (both in core). timeToFirstToken is computed from start_time
+ // and completion_start_time, but the converter spreads it when EITHER is defined; since start_time is in core and
+ // always selected, timeToFirstToken is always present (as null when completion_start_time is not selected).
+ const ALL_NON_CORE_FIELDS = [
+ // basic
+ "name",
+ "level",
+ "statusMessage",
+ "version",
+ "environment",
+ "bookmarked",
+ "public",
+ "userId",
+ "sessionId",
+ // time
+ "completionStartTime",
+ "createdAt",
+ "updatedAt",
+ // io
+ "input",
+ "output",
+ // metadata
+ "metadata",
+ // model — note: the API response uses "model" for the provided model name,
+ // not "providedModelName" (the domain type maps provided_model_name → model)
+ "model",
+ "internalModelId",
+ "modelParameters",
+ // usage
+ "usageDetails",
+ "costDetails",
+ "totalCost",
+ // prompt
+ "promptId",
+ "promptName",
+ "promptVersion",
+ ] as const;
+
+ let sharedObsId: string;
+ let sharedTraceId: string;
+
+ beforeEach(async () => {
+ sharedTraceId = randomUUID();
+ sharedObsId = randomUUID();
+ const now = new Date();
+ const timeValue = now.getTime() * 1000;
+
+ const obs = createEvent({
+ id: sharedObsId,
+ span_id: sharedObsId,
+ trace_id: sharedTraceId,
+ project_id: projectId,
+ name: "field-group-contract-obs",
+ type: "GENERATION",
+ level: "DEFAULT",
+ status_message: "ok",
+ version: "1.0",
+ environment: "production",
+ bookmarked: true,
+ public: true,
+ user_id: "test-user",
+ session_id: "test-session",
+ start_time: timeValue,
+ end_time: timeValue + 1000 * 1000,
+ completion_start_time: timeValue + 500 * 1000,
+ provided_model_name: "gpt-4",
+ model_id: randomUUID(),
+ model_parameters: '{"temperature":0.5}',
+ usage_details: { input: 10, output: 20, total: 30 },
+ cost_details: { input: 0.01, output: 0.02, total: 0.03 },
+ prompt_id: randomUUID(),
+ prompt_name: "contract-prompt",
+ prompt_version: 2,
+ input: "contract input",
+ output: "contract output",
+ metadata_names: ["key"],
+ metadata_values: ["val"],
+ });
+
+ await createEventsCh([obs]);
+ });
+
+ // Known fixture values — used to assert exact values, not just presence.
+ // toBeDefined() passes for null; for fields the fixture explicitly sets we
+ // assert the stored value so a null regression is caught.
+ const knownValues: Record<string, unknown> = {
+ name: "field-group-contract-obs",
+ level: "DEFAULT",
+ statusMessage: "ok",
+ version: "1.0",
+ environment: "production",
+ bookmarked: true,
+ public: true,
+ userId: "test-user",
+ sessionId: "test-session",
+ model: "gpt-4",
+ modelParameters: { temperature: 0.5 },
+ promptName: "contract-prompt",
+ promptVersion: 2,
+ input: "contract input",
+ output: "contract output",
+ };
+
+ const fieldsForGroup: Record<string, readonly string[]> = {
+ basic: [
+ "name",
+ "level",
+ "statusMessage",
+ "version",
+ "environment",
+ "bookmarked",
+ "public",
+ "userId",
+ "sessionId",
+ ],
+ time: ["completionStartTime", "createdAt", "updatedAt"],
+ io: ["input", "output"],
+ metadata: ["metadata"],
+ // "model" is the API response key for provided_model_name (see domain type)
+ model: ["model", "internalModelId", "modelParameters"],
+ usage: ["usageDetails", "costDetails", "totalCost"],
+ prompt: ["promptId", "promptName", "promptVersion"],
+ // latency and timeToFirstToken are always returned (computed from core start_time, completion_start_time,
+ // end_time), but the metrics group is still defined for documentation and to verify these fields are indeed
+ // present
+ metrics: ["latency", "timeToFirstToken"],
+ };
+
+ for (const [group, expectedFields] of Object.entries(fieldsForGroup)) {
+ it(`field group contract: ${group}`, async () => {
+ const response = await getObservations(
+ `/api/public/v2/observations?fields=${group}&traceId=${sharedTraceId}`,
+ );
+
+ expect(response.status).toBe(200);
+ const obs = response.body.data.find((o: any) => o.id === sharedObsId);
+ expect(obs).toBeDefined();
+ if (!obs) return; // narrow type; expect above already fails the test
+
+ // Core fields always present
+ for (const field of CORE_FIELDS) {
+ expect(obs[field]).toBeDefined();
+ }
+
+ // Requested group fields present — assert exact value when the fixture
+ // set one, toBeDefined() otherwise (e.g. dates, generated IDs).
+ for (const field of expectedFields) {
+ if (field in knownValues) {
+ expect(
+ obs[field],
+ `expected field "${field}" to equal fixture value for group "${group}"`,
+ ).toStrictEqual(knownValues[field]);
+ } else {
+ expect(
+ obs[field],
+ `expected field "${field}" to be defined for group "${group}"`,
+ ).toBeDefined();
+ }
+ }
+
+ // Fields from other groups absent (null or undefined — API may serialize
+ // absent fields as null rather than omitting them from the JSON)
+ const absentFields = ALL_NON_CORE_FIELDS.filter(
+ (f) => !(expectedFields as readonly string[]).includes(f),
+ );
+ for (const field of absentFields) {
+ expect(
+ obs[field] ?? undefined,
+ `expected field "${field}" to be null/undefined when only group "${group}" is requested`,
+ ).toBeUndefined();
+ }
+ });
+ }
+ });
+
maybe("Metadata expansion with expandMetadata parameter", () => {
it("should return full metadata values when expandMetadata is specified", async () => {
const traceId = randomUUID();
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index 99d3ef534c..e36069f374 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -4113,4 +4113,168 @@ maybeDescribe("getEventsForBlobStorageExport", () => {
expect(rows).toHaveLength(0);
});
+
+ it("should return exactly the expected set of output columns with correct types and values", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = Date.now();
+ const traceId = randomUUID();
+ const modelId = randomUUID();
+ const promptId = randomUUID();
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "column-contract-event",
+ start_time: now * 1000,
+ end_time: (now + 1000) * 1000,
+ completion_start_time: (now + 500) * 1000,
+ bookmarked: true,
+ public: true,
+ provided_model_name: "gpt-4",
+ model_id: modelId,
+ model_parameters: '{"temperature":0.7}',
+ usage_details: { input: 10, output: 20, total: 30 },
+ cost_details: { input: 0.01, output: 0.02, total: 0.03 },
+ prompt_id: promptId,
+ prompt_name: "test-prompt",
+ prompt_version: 1,
+ tool_calls: ["search"],
+ tool_definitions: { search: "Search the web" },
+ tool_call_names: ["search"],
+ input: "test input",
+ output: "test output",
+ metadata_names: ["env"],
+ metadata_values: ["production"],
+ });
+
+ await createEventsCh([event]);
+
+ const stream = getEventsForBlobStorageExport(
+ projectId,
+ new Date(now - 60 * 60 * 1000),
+ new Date(now + 60 * 60 * 1000),
+ );
+
+ const rows: Record<string, unknown>[] = [];
+ for await (const row of stream) {
+ rows.push(row);
+ }
+
+ expect(rows).toHaveLength(1);
+ const row = rows[0];
+
+ // Exact column set — any addition, removal, or rename will fail this test
+ const expectedColumns = [
+ "id",
+ "trace_id",
+ "project_id",
+ "start_time",
+ "end_time",
+ "name",
+ "type",
+ "environment",
+ "version",
+ "user_id",
+ "session_id",
+ "level",
+ "status_message",
+ "prompt_name",
+ "prompt_id",
+ "prompt_version",
+ "model_id",
+ "provided_model_name",
+ "model_parameters",
+ "usage_details",
+ "cost_details",
+ "total_cost",
+ "completion_start_time",
+ "latency",
+ "time_to_first_token",
+ "tags",
+ "release",
+ "trace_name",
+ "parent_observation_id",
+ "bookmarked",
+ "public",
+ "created_at",
+ "updated_at",
+ "tool_definitions",
+ "tool_calls",
+ "tool_call_names",
+ "usage_pricing_tier_name",
+ "input",
+ "output",
+ "metadata",
+ ].sort();
+
+ expect(Object.keys(row).sort()).toEqual(expectedColumns);
+
+ // --- Fixture-set string columns ---
+ expect(row.id).toBe(event.span_id);
+ expect(row.trace_id).toBe(traceId);
+ expect(row.project_id).toBe(projectId);
+ expect(row.name).toBe("column-contract-event");
+ expect(row.type).toBe("GENERATION");
+ expect(row.environment).toBe("default"); // createEvent default
+ expect(row.level).toBe("DEFAULT"); // createEvent default
+ expect(row.provided_model_name).toBe("gpt-4");
+ expect(row.model_id).toBe(modelId);
+ expect(row.model_parameters).toBe('{"temperature":0.7}');
+ expect(row.prompt_name).toBe("test-prompt");
+ expect(row.prompt_id).toBe(promptId);
+ expect(row.input).toBe("test input");
+ expect(row.output).toBe("test output");
+
+ // --- Boolean columns ---
+ expect(row.bookmarked).toBe(true);
+ expect(row.public).toBe(true);
+
+ // --- Numeric columns ---
+ expect(row.prompt_version).toBe(1);
+ // latency = date_diff('millisecond', start_time, end_time)
+ // start: now*1000 µs, end: (now+1000)*1000 µs → 1000 ms
+ expect(row.latency).toBe(1000);
+ // time_to_first_token = date_diff('millisecond', start_time, completion_start_time)
+ // start: now*1000 µs, completion: (now+500)*1000 µs → 500 ms
+ expect(row.time_to_first_token).toBe(500);
+
+ // --- Object / array columns ---
+ expect(row.usage_details).toEqual({ input: 10, output: 20, total: 30 });
+ expect(row.cost_details).toEqual({
+ input: 0.01,
+ output: 0.02,
+ total: 0.03,
+ });
+ expect(row.tool_calls).toEqual(["search"]);
+ expect(row.tool_definitions).toEqual({ search: "Search the web" });
+ expect(row.tool_call_names).toEqual(["search"]);
+ expect(row.tags).toEqual([]); // createEvent default
+ expect(row.metadata).toEqual({ env: "production" });
+
+ // --- Date columns — ClickHouse returns DateTime64 as strings ---
+ expect(typeof row.start_time).toBe("string");
+ expect(typeof row.end_time).toBe("string");
+ expect(typeof row.completion_start_time).toBe("string");
+ expect(typeof row.created_at).toBe("string");
+ expect(typeof row.updated_at).toBe("string");
+
+ // --- Unset String columns (non-nullable in events_core → return "" not null) ---
+ expect(row.version).toBe("");
+ expect(row.user_id).toBe("");
+ expect(row.session_id).toBe("");
+ expect(row.status_message).toBe("");
+ expect(row.release).toBe("");
+ // parent_span_id is non-nullable String; createEvent sets it to null → stored as ""
+ expect(row.parent_observation_id).toBe("");
+ // trace_name is non-nullable String; not populated (no trace inserted) → ""
+ expect(row.trace_name).toBe("");
+
+ // --- Nullable columns (NULL when unset) ---
+ // usage_pricing_tier_name is Nullable(String) in events_core
+ expect(row.usage_pricing_tier_name).toBeNull();
+
+ // --- total_cost: ALIAS for cost_details['total'] → 0.03 (set in fixture) ---
+ expect(row.total_cost).toBeCloseTo(0.03);
+ });
});