Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): compare Datadog eval experiments across runs and share results by default (#3905)

Matan Kushnerf0a9ee199cc3
diff --git a/.changeset/datadog-stable-dataset-records.md b/.changeset/datadog-stable-dataset-records.md
new file mode 100644
index 000000000..1e22cbea6
--- /dev/null
+++ b/.changeset/datadog-stable-dataset-records.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The Datadog reporter now records eval content by default and reuses one dataset across runs, so experiments can be compared in Datadog.
diff --git a/docs/evals/reporters.mdx b/docs/evals/reporters.mdx
index 6438552ff..deabdcfa3 100644
--- a/docs/evals/reporters.mdx
+++ b/docs/evals/reporters.mdx
@@ -57,11 +57,13 @@ export default defineEvalConfig({
});
```
-The reporter creates one Datadog Experiment, submits one synthetic experiment span per completed eve eval, associates that eval's assertion scores as experiment metrics, and prints the Datadog Experiment URL after the run completes. Without input recording, the external Experiment uses a placeholder dataset and spans are submitted as evals finish. With `recordInputs: true`, the reporter instead creates and pushes a versioned Datadog dataset after the evals finish, adds one record per eval, starts the Experiment against that dataset version, passes each dataset record id to its corresponding experiment span, and prints both Dataset and Experiment URLs. Buffering is necessary because an imperative eval's first `t.send(...)` input is only known after that eval executes. `dd-trace` generates dataset record, experiment trace, and experiment span identifiers; the reporter does not mutate or link the agent runtime's OpenTelemetry spans.
+The reporter creates one Datadog Experiment, submits one synthetic experiment span per completed eve eval, associates that eval's assertion scores as experiment metrics, and prints the Datadog Experiment URL after the run completes. Without input recording, the external Experiment uses a placeholder dataset and spans are submitted as evals finish. With `recordInputs` (the default), the reporter instead syncs a versioned Datadog dataset after the evals finish, starts the Experiment against that dataset version, passes each dataset record id to its corresponding experiment span, and prints both Dataset and Experiment URLs. Buffering is necessary because an imperative eval's first `t.send(...)` input is only known after that eval executes. `dd-trace` generates dataset record, experiment trace, and experiment span identifiers; the reporter does not mutate or link the agent runtime's OpenTelemetry spans.
-Assertion metrics use descriptive assertion names by default: characters outside letters, numbers, underscores, and hyphens are normalized to underscores, gate labels receive a `gate_` prefix, and repeated or reserved labels receive numeric suffixes. For example, `succeeded` becomes `gate_succeeded` and `calledTool(get_stock_quote)` becomes `gate_calledTool_get_stock_quote`. Authors can use `.label("stable name")` on an assertion handle to choose a stable metric name. Because assertion names can contain authored expectations, review them before exporting sensitive evals. Pass `recordAssertionDetails: true` only when the destination is also approved for raw assertion-name tags and failed assertion messages in row metadata.
+Every run reuses the dataset named by `datasetName` (default `<projectName> evals`), so Datadog can compare experiments across runs. Records are matched by eval description, with `#2`, `#3` suffixes for duplicates, so give each case a unique description.
-Datadog needs `dd-trace` installed in the app and Datadog credentials in the environment. The reporter is tested against `[email protected]`; install it with `npm install [email protected]` and set `DD_API_KEY`, `DD_APP_KEY`, and `DD_SITE` as appropriate. By default, the reporter records assertion scores, eval metadata, and the target URL origin only. Pass `recordInputs: true`, `recordOutputs: true`, `recordExpectedOutputs: true`, or `recordErrors: true` if your destination is approved for eval prompts, outputs, authored expectations, or execution error messages. `recordInputs` stores the eval input in both the linked dataset record and experiment span. Input is read from the eval's first `t.send(...)` message, falling back to the eval description when no message event is available. When `recordExpectedOutputs` is enabled, expected output is read from eval `metadata.expectedOutput`, `metadata.expected`, or `metadata.expected_output` and stored in both the dataset record and experiment span; when no expected output is authored, the input-only dataset record is still valid. Those expected-output keys are excluded from the general metadata payload. Target URL credentials, paths, query parameters, and fragments are never reported.
+Assertion metrics use descriptive assertion names by default: characters outside letters, numbers, underscores, and hyphens are normalized to underscores, gate labels receive a `gate_` prefix, and repeated or reserved labels receive numeric suffixes. For example, `succeeded` becomes `gate_succeeded` and `calledTool(get_stock_quote)` becomes `gate_calledTool_get_stock_quote`. Authors can use `.label("stable name")` on an assertion handle to choose a stable metric name. Because assertion names can contain authored expectations, review them before exporting sensitive evals. Pass `recordAssertionDetails: false` to omit raw assertion-name tags and failed assertion messages.
+
+Datadog needs `dd-trace` installed in the app and Datadog credentials in the environment. The reporter is tested against `[email protected]`; install it with `npm install [email protected]` and set `DD_API_KEY`, `DD_APP_KEY`, and `DD_SITE` as appropriate; without credentials, reporting is skipped. Like the Braintrust reporter, it records eval prompts, outputs, authored expectations, and execution error messages by default. Pass `recordInputs: false`, `recordOutputs: false`, `recordExpectedOutputs: false`, or `recordErrors: false` if your destination is not approved for that content. `recordInputs` stores the eval input in both the linked dataset record and experiment span. Input is read from the eval's first `t.send(...)` message, falling back to the eval description when no message event is available. When `recordExpectedOutputs` is enabled, expected output is read from eval `metadata.expectedOutput`, `metadata.expected`, or `metadata.expected_output` and stored in both the dataset record and experiment span; when no expected output is authored, the input-only dataset record is still valid. Those expected-output keys are excluded from the general metadata payload. Target URL credentials, paths, query parameters, and fragments are never reported.
## JUnit
diff --git a/packages/eve/src/evals/runner/reporters/datadog-client.ts b/packages/eve/src/evals/runner/reporters/datadog-client.ts
new file mode 100644
index 000000000..1a913b1fa
--- /dev/null
+++ b/packages/eve/src/evals/runner/reporters/datadog-client.ts
@@ -0,0 +1,249 @@
+import { createRequire } from "node:module";
+
+import type ddTrace from "dd-trace";
+
+import { parseJsonValue, type JsonValue } from "#shared/json.js";
+
+// eve-owned seam over the dd-trace LLM Observability experiments API.
+
+export type DatadogJsonValue =
+ | string
+ | number
+ | boolean
+ | null
+ | DatadogJsonValue[]
+ | { [key: string]: DatadogJsonValue };
+
+export interface DatadogDatasetRecordInput {
+ inputData: DatadogJsonValue;
+ expectedOutput?: DatadogJsonValue;
+ metadata?: Record<string, DatadogJsonValue>;
+ tags?: string[];
+}
+
+export interface DatadogDatasetRecord {
+ readonly id: string | null;
+ readonly input: DatadogJsonValue;
+ readonly expectedOutput: DatadogJsonValue;
+ readonly metadata: Record<string, DatadogJsonValue>;
+}
+
+export interface DatadogDatasetRecordFields {
+ input: DatadogJsonValue;
+ expectedOutput: DatadogJsonValue;
+ metadata: Record<string, DatadogJsonValue>;
+}
+
+export interface DatadogDataset {
+ id(): string | null;
+ name(): string;
+ version(): number | null;
+ latestVersion(): number | null;
+ records(): readonly DatadogDatasetRecord[];
+ addRecords(records: DatadogDatasetRecordInput[]): DatadogDataset;
+ update(index: number, fields: Partial<DatadogDatasetRecordFields>): DatadogDataset;
+ url(): string | null;
+ push(): Promise<{ pushedCount: number; totalCount: number }>;
+}
+
+export interface DatadogExperimentsClient {
+ createDataset?(
+ name: string,
+ options?: {
+ projectName?: string;
+ description?: string;
+ },
+ ): DatadogDataset;
+ pullDataset?(
+ name: string,
+ options?: { projectName?: string; maxWaitMs?: number },
+ ): Promise<DatadogDataset>;
+ startExperiment(options: DatadogStartExperimentOptions): Promise<DatadogExternalExperiment>;
+}
+
+export interface DatadogStartExperimentOptions {
+ name: string;
+ projectName?: string;
+ description?: string;
+ tags?: Record<string, string>;
+ metadata?: Record<string, DatadogJsonValue>;
+ config?: Record<string, DatadogJsonValue>;
+ dataset?: {
+ id?: string;
+ version?: number;
+ name?: string;
+ description?: string;
+ };
+}
+
+export interface DatadogExternalExperiment {
+ experimentId(): string;
+ url(): string | null;
+ submitSpan(row: DatadogExternalExperimentSpanInput): Promise<DatadogExternalExperimentSpan>;
+ submitEvaluationMetrics(
+ span: Pick<DatadogExternalExperimentSpan, "experimentId" | "spanId" | "traceId">,
+ metrics: DatadogEvaluationMetricInput[],
+ ): Promise<void>;
+ close(options?: { status?: string; error?: string | Error }): Promise<void>;
+}
+
+export interface DatadogExternalExperimentSpanInput {
+ name?: string;
+ input?: DatadogJsonValue;
+ output?: DatadogJsonValue;
+ expectedOutput?: DatadogJsonValue;
+ metadata?: Record<string, DatadogJsonValue>;
+ tags?: Record<string, string>;
+ startedAt?: Date | string | number;
+ completedAt?: Date | string | number;
+ durationMs?: number;
+ error?: string | Error | { type?: string; name?: string; message?: string; stack?: string };
+ datasetRecordId?: string;
+ runId?: string;
+ runIteration?: number;
+}
+
+interface DatadogExternalExperimentSpan {
+ experimentId: string;
+ spanId: string;
+ traceId: string;
+ url: string | null;
+}
+
+export interface DatadogEvaluationMetricInput {
+ label: string;
+ value?: DatadogJsonValue;
+ error?: string | Error;
+ timestamp?: Date | string | number;
+ tags?: Record<string, string>;
+ source?: string;
+}
+
+/** Options used when eve initializes `dd-trace` itself. */
+export interface DatadogClientConfig {
+ readonly client?: DatadogExperimentsClient;
+ readonly service?: string;
+ readonly env?: string;
+ readonly site?: string;
+ readonly mlApp?: string;
+}
+
+type DatadogTraceModule = typeof ddTrace;
+
+const DD_TRACE_PACKAGE = "dd-trace";
+const DATASET_PULL_MAX_WAIT_MS = 5_000;
+export const MISSING_DATASET_API_MESSAGE = [
+ "The installed 'dd-trace' package does not expose tracer.llmobs.experiments.createDataset() and pullDataset().",
+ "Update to a release compatible with [email protected].",
+].join("\n");
+
+/** Pulls the named dataset, creating it when Datadog has no dataset with that name. */
+export async function getDatadogDataset(
+ client: DatadogExperimentsClient,
+ name: string,
+ options: { projectName?: string; description: string },
+): Promise<DatadogDataset> {
+ if (!client.pullDataset || !client.createDataset) {
+ throw new Error(MISSING_DATASET_API_MESSAGE);
+ }
+ try {
+ return await client.pullDataset(name, {
+ projectName: options.projectName,
+ maxWaitMs: DATASET_PULL_MAX_WAIT_MS,
+ });
+ } catch (error) {
+ // dd-trace reports a missing dataset only through this message.
+ if (!(error instanceof Error) || !error.message.startsWith(`Dataset '${name}' not found`)) {
+ throw error;
+ }
+ }
+ return client.createDataset(name, options);
+}
+
+/** Returns `config.client`, or initializes `dd-trace` and returns its experiments API. */
+export async function resolveDatadogClient(
+ config: DatadogClientConfig,
+ projectName: string,
+): Promise<DatadogExperimentsClient> {
+ if (config.client) return config.client;
+
+ const sdk = await loadDatadogSdk();
+ const tracer = sdk.init({
+ service: config.service ?? process.env.DD_SERVICE ?? projectName,
+ env: config.env ?? process.env.DD_ENV,
+ site: config.site ?? process.env.DD_SITE,
+ llmobs: {
+ projectName,
+ mlApp: config.mlApp ?? projectName,
+ agentlessEnabled: true,
+ },
+ });
+
+ const experiments = tracer.llmobs?.experiments;
+ if (!experiments?.startExperiment) {
+ throw new Error(
+ [
+ "The installed 'dd-trace' package does not expose tracer.llmobs.experiments.startExperiment().",
+ "Update to a release compatible with [email protected].",
+ ].join("\n"),
+ );
+ }
+ return experiments;
+}
+
+async function loadDatadogSdk(): Promise<DatadogTraceModule> {
+ try {
+ const requireFromApp = createRequire(`${process.cwd()}/package.json`);
+ return requireFromApp(DD_TRACE_PACKAGE) as DatadogTraceModule;
+ } catch {
+ try {
+ const mod = (await import(DD_TRACE_PACKAGE)) as { default?: unknown };
+ return (mod.default ?? mod) as DatadogTraceModule;
+ } catch {
+ throw new Error(
+ [
+ "The 'dd-trace' package is required for Datadog reporting but was not found.",
+ "",
+ "Install the tested release with:",
+ " npm install [email protected]",
+ ].join("\n"),
+ );
+ }
+ }
+}
+
+export function toOptionalDatadogJsonValue(value: unknown): DatadogJsonValue | undefined {
+ return value === undefined ? undefined : toDatadogJsonValue(value);
+}
+
+export function toDatadogJsonRecord(
+ value: Readonly<Record<string, unknown>> | undefined,
+): Record<string, DatadogJsonValue> | undefined {
+ if (value === undefined) return undefined;
+
+ const output: Record<string, DatadogJsonValue> = {};
+ for (const [key, entry] of Object.entries(value)) {
+ if (entry !== undefined) {
+ output[key] = toDatadogJsonValue(entry);
+ }
+ }
+ return output;
+}
+
+export function toDatadogJsonValue(value: unknown): DatadogJsonValue {
+ return cloneDatadogJsonValue(parseJsonValue(value));
+}
+
+function cloneDatadogJsonValue(value: JsonValue): DatadogJsonValue {
+ if (Array.isArray(value)) {
+ return value.map((entry) => cloneDatadogJsonValue(entry));
+ }
+ if (value !== null && typeof value === "object") {
+ const output: Record<string, DatadogJsonValue> = {};
+ for (const [key, entry] of Object.entries(value)) {
+ output[key] = cloneDatadogJsonValue(entry);
+ }
+ return output;
+ }
+ return value;
+}
diff --git a/packages/eve/src/evals/runner/reporters/datadog.test.ts b/packages/eve/src/evals/runner/reporters/datadog.test.ts
index ee906cfc7..1f060c065 100644
--- a/packages/eve/src/evals/runner/reporters/datadog.test.ts
+++ b/packages/eve/src/evals/runner/reporters/datadog.test.ts
@@ -4,6 +4,14 @@ import { createEmptyDerivedFacts } from "#evals/runner/derive-run-facts.js";
import { Datadog, type DatadogReporterConfig } from "#evals/reporters/index.js";
import type { EveEval, EveEvalResult, EveEvalRunSummary, EveEvalTarget } from "#evals/types.js";
+const RECORDING_DISABLED = {
+ recordInputs: false,
+ recordOutputs: false,
+ recordExpectedOutputs: false,
+ recordAssertionDetails: false,
+ recordErrors: false,
+} satisfies DatadogReporterConfig;
+
function makeTarget(kind: "local" | "remote" = "local"): EveEvalTarget {
return {
capabilities: { devRoutes: kind === "local" },
@@ -98,6 +106,88 @@ function makeSummary(result: EveEvalResult = makeEvalResult()): EveEvalRunSummar
};
}
+type FakeJson = string | number | boolean | null | FakeJson[] | { [key: string]: FakeJson };
+
+interface FakeDatasetRecord {
+ id: string;
+ input: FakeJson;
+ expectedOutput: FakeJson;
+ metadata: Record<string, FakeJson>;
+}
+
+/** In-memory stand-in for Datadog datasets that persists across reporter runs. */
+function makeDatasetStore() {
+ const stored = new Map<string, { id: string; version: number; records: FakeDatasetRecord[] }>();
+ let nextRecordId = 1;
+
+ // Like dd-trace, version() stays null until a push creates a new version.
+ function open(name: string, initialRecords: readonly FakeDatasetRecord[]) {
+ let records = initialRecords.map((record) => ({ ...record }));
+ let version: number | null = null;
+ let hasChanges = false;
+ const dataset = {
+ id: () => stored.get(name)?.id ?? null,
+ name: () => name,
+ version: () => version,
+ latestVersion: () => stored.get(name)?.version ?? null,
+ records: () => records,
+ url: () => `https://dd.test/datasets/${name}`,
+ addRecords: vi.fn(
+ (
+ added: Array<{
+ inputData: FakeJson;
+ expectedOutput?: FakeJson;
+ metadata?: Record<string, FakeJson>;
+ }>,
+ ) => {
+ for (const record of added) {
+ records.push({
+ id: `record-${nextRecordId++}`,
+ input: record.inputData,
+ expectedOutput: record.expectedOutput ?? null,
+ metadata: record.metadata ?? {},
+ });
+ }
+ hasChanges = true;
+ return dataset;
+ },
+ ),
+ update: vi.fn((index: number, fields: Partial<Omit<FakeDatasetRecord, "id">>) => {
+ records = records.map((record, recordIndex) =>
+ recordIndex === index ? { ...record, ...fields } : record,
+ );
+ hasChanges = true;
+ return dataset;
+ }),
+ push: vi.fn(async () => {
+ const current = stored.get(name);
+ if (!hasChanges && current) return { pushedCount: 0, totalCount: 0 };
+ const nextVersion = (current?.version ?? 0) + 1;
+ stored.set(name, {
+ id: current?.id ?? `dataset-${stored.size + 1}`,
+ version: nextVersion,
+ records: records.map((record) => ({ ...record })),
+ });
+ version = nextVersion;
+ hasChanges = false;
+ return { pushedCount: records.length, totalCount: records.length };
+ }),
+ };
+ return dataset;
+ }
+
+ return {
+ create: (name: string) => open(name, []),
+ async pull(name: string) {
+ const remote = stored.get(name);
+ if (!remote)
+ throw new Error(`Dataset '${name}' not found in project 'test-project' (after 5000ms)`);
+ return open(name, remote.records);
+ },
+ get: (name: string) => stored.get(name),
+ };
+}
+
function makeConfig(overrides: Partial<DatadogReporterConfig> = {}) {
const span = {
experimentId: "exp-1",
@@ -112,43 +202,15 @@ function makeConfig(overrides: Partial<DatadogReporterConfig> = {}) {
submitEvaluationMetrics: vi.fn(async (_span: unknown, _metrics: unknown) => undefined),
close: vi.fn(async () => undefined),
};
- let datasetName = "dataset-1";
- let datasetRecords: Array<{
- id: string;
- inputData: unknown;
- expectedOutput?: unknown;
- metadata?: Readonly<Record<string, unknown>>;
- }> = [];
- const dataset = {
- id: vi.fn(() => "dataset-1"),
- name: vi.fn(() => datasetName),
- version: vi.fn(() => 3),
- records: vi.fn(() => datasetRecords),
- url: vi.fn(() => "https://dd.test/dataset"),
- push: vi.fn(async () => ({
- pushedCount: datasetRecords.length,
- totalCount: datasetRecords.length,
- })),
- };
+ const datasets = makeDatasetStore();
const client = {
createDataset: vi.fn(
- (
- name: string,
- options?: {
- records?: Array<{
- inputData: unknown;
- expectedOutput?: unknown;
- metadata?: Readonly<Record<string, unknown>>;
- }>;
- },
- ) => {
- datasetName = name;
- datasetRecords = (options?.records ?? []).map((record, index) => ({
- id: `record-${index + 1}`,
- ...record,
- }));
- return dataset;
- },
+ (name: string, _options?: { projectName?: string; description?: string }) =>
+ datasets.create(name),
+ ),
+ pullDataset: vi.fn(
+ async (name: string, _options?: { projectName?: string; maxWaitMs?: number }) =>
+ datasets.pull(name),
),
startExperiment: vi.fn(async (_options: unknown) => experiment),
};
@@ -160,12 +222,15 @@ function makeConfig(overrides: Partial<DatadogReporterConfig> = {}) {
...overrides,
} satisfies DatadogReporterConfig;
- return { client, config, dataset, experiment, lines, span };
+ return { client, config, datasets, experiment, lines, span };
}
describe("Datadog", () => {
- it("creates an experiment, submits one span, and attaches assertion metrics", async () => {
- const { client, config, experiment, span } = makeConfig({ experimentName: "run-1" });
+ it("submits scores only, as evals finish, when every recording option is disabled", async () => {
+ const { client, config, experiment, span } = makeConfig({
+ experimentName: "run-1",
+ ...RECORDING_DISABLED,
+ });
const reporter = Datadog(config);
const evaluation = makeEval();
const result = makeEvalResult();
@@ -226,8 +291,8 @@ describe("Datadog", () => {
);
});
- it("redacts target URL secrets and execution errors by default", async () => {
- const { client, config, experiment } = makeConfig();
+ it("redacts target URL secrets and omits execution errors when recordErrors is disabled", async () => {
+ const { client, config, experiment } = makeConfig({ recordInputs: false, recordErrors: false });
const reporter = Datadog(config);
const target: EveEvalTarget = {
...makeTarget("remote"),
@@ -246,20 +311,23 @@ describe("Datadog", () => {
expect(experiment.submitSpan.mock.calls[0]?.[0]).not.toHaveProperty("error");
});
- it("records execution errors only when enabled", async () => {
- const { config, experiment } = makeConfig({ recordErrors: true });
+ it("records execution errors by default", async () => {
+ const { config, experiment } = makeConfig();
const reporter = Datadog(config);
await reporter.onRunStart([makeEval()], makeTarget());
- await reporter.onEvalComplete(makeEvalResult({ error: "application error" }));
+ await reporter.onRunComplete(makeSummary(makeEvalResult({ error: "application error" })));
expect(experiment.submitSpan).toHaveBeenCalledWith(
expect.objectContaining({ error: "application error" }),
);
});
- it("redacts failing assertion details by default", async () => {
- const { config, experiment } = makeConfig();
+ it("redacts failing assertion details when recordAssertionDetails is disabled", async () => {
+ const { config, experiment } = makeConfig({
+ recordInputs: false,
+ recordAssertionDetails: false,
+ });
const reporter = Datadog(config);
const result = makeEvalResult({
assertions: [
@@ -295,8 +363,8 @@ describe("Datadog", () => {
);
});
- it("records assertion name tags and failure messages only when enabled", async () => {
- const { config, experiment } = makeConfig({ recordAssertionDetails: true });
+ it("records assertion name tags and failure messages by default", async () => {
+ const { config, experiment } = makeConfig();
const reporter = Datadog(config);
const result = makeEvalResult({
assertions: [
@@ -313,7 +381,7 @@ describe("Datadog", () => {
});
await reporter.onRunStart([makeEval()], makeTarget());
- await reporter.onEvalComplete(result);
+ await reporter.onRunComplete(makeSummary(result));
expect(experiment.submitSpan.mock.calls[0]?.[0]).toHaveProperty(
"metadata.eveFailedAssertions",
@@ -337,7 +405,7 @@ describe("Datadog", () => {
});
it("deduplicates assertion metric labels and reserves built-in labels", async () => {
- const { config, experiment } = makeConfig({ recordAssertionDetails: true });
+ const { config, experiment } = makeConfig({ recordInputs: false });
const reporter = Datadog(config);
const result = makeEvalResult({
assertions: [
@@ -363,14 +431,8 @@ describe("Datadog", () => {
]);
});
- it("creates dataset records from opted-in eval inputs and links experiment rows", async () => {
- const { client, config, dataset, experiment, lines } = makeConfig({
- datasetName: "greeting inputs",
- experimentName: "run-1",
- recordInputs: true,
- recordOutputs: true,
- recordExpectedOutputs: true,
- });
+ it("records inputs, outputs, and expected outputs in a shared dataset by default", async () => {
+ const { client, config, datasets, experiment, lines } = makeConfig({ experimentName: "run-1" });
const reporter = Datadog(config);
const result = makeEvalResult();
@@ -382,27 +444,26 @@ describe("Datadog", () => {
await reporter.onRunComplete(makeSummary(result));
- expect(client.createDataset).toHaveBeenCalledWith(
- "greeting inputs",
- expect.objectContaining({
- projectName: "test-project",
- records: [
- {
- inputData: "What should I send you?",
- expectedOutput: "helpful onboarding answer",
- metadata: { eveEvalId: "eval-1" },
- },
- ],
- }),
+ expect(client.pullDataset).toHaveBeenCalledWith(
+ "test-project evals",
+ expect.objectContaining({ projectName: "test-project" }),
);
- expect(dataset.push).toHaveBeenCalledOnce();
- expect(dataset.push.mock.invocationCallOrder[0]).toBeLessThan(
- client.startExperiment.mock.invocationCallOrder[0] ?? 0,
+ expect(client.createDataset).toHaveBeenCalledWith(
+ "test-project evals",
+ expect.objectContaining({ projectName: "test-project" }),
);
+ expect(datasets.get("test-project evals")?.records).toEqual([
+ {
+ id: "record-1",
+ input: "What should I send you?",
+ expectedOutput: "helpful onboarding answer",
+ metadata: { eveRecordKey: "Say hello", eveEvalId: "eval-1" },
+ },
+ ]);
expect(client.startExperiment).toHaveBeenCalledWith(
expect.objectContaining({
name: "run-1",
- dataset: { id: "dataset-1", name: "greeting inputs", version: 3 },
+ dataset: { id: "dataset-1", name: "test-project evals", version: 1 },
}),
);
expect(experiment.submitSpan).toHaveBeenCalledWith(
@@ -413,14 +474,126 @@ describe("Datadog", () => {
datasetRecordId: "record-1",
}),
);
- expect(lines.join("\n")).toContain("Datadog dataset URL: https://dd.test/dataset");
+ expect(lines.join("\n")).toContain(
+ "Datadog dataset URL: https://dd.test/datasets/test-project evals",
+ );
+ });
+
+ it("reuses dataset records by description across runs even when eval ids shift", async () => {
+ const { client, config, datasets, experiment } = makeConfig();
+ const reporter = Datadog(config);
+ const first = makeEval({ id: "cases/0000", description: "First case" });
+ const second = makeEval({ id: "cases/0001", description: "Second case" });
+
+ await reporter.onRunStart([first, second], makeTarget());
+ const firstRun = [makeEvalResult({ id: "cases/0000" }), makeEvalResult({ id: "cases/0001" })];
+ await reporter.onRunComplete({ ...makeSummary(), results: firstRun });
+ const recordIds = datasets.get("test-project evals")?.records.map((record) => record.id);
+
+ // Removing the first case shifts the second case's index-based id.
+ const shifted = makeEval({ id: "cases/0000", description: "Second case" });
+ await reporter.onRunStart([shifted], makeTarget());
+ await reporter.onRunComplete({
+ ...makeSummary(),
+ results: [makeEvalResult({ id: "cases/0000" })],
+ });
+
+ expect(client.createDataset).toHaveBeenCalledOnce();
+ expect(client.startExperiment).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ dataset: { id: "dataset-1", name: "test-project evals", version: 2 },
+ }),
+ );
+ expect(experiment.submitSpan).toHaveBeenLastCalledWith(
+ expect.objectContaining({ name: "cases/0000", datasetRecordId: recordIds?.[1] }),
+ );
+ // Records missing from a run are kept so filtered runs never delete cases.
+ expect(datasets.get("test-project evals")?.records).toEqual([
+ expect.objectContaining({
+ id: recordIds?.[0],
+ metadata: expect.objectContaining({ eveRecordKey: "First case" }),
+ }),
+ expect.objectContaining({
+ id: recordIds?.[1],
+ metadata: { eveRecordKey: "Second case", eveEvalId: "cases/0000" },
+ }),
+ ]);
+ });
+
+ it("pins the latest version without pushing when records are unchanged", async () => {
+ const { client, config } = makeConfig();
+ const reporter = Datadog(config);
+ const result = makeEvalResult();
+
+ for (let run = 0; run < 2; run += 1) {
+ await reporter.onRunStart([makeEval()], makeTarget());
+ await reporter.onRunComplete(makeSummary(result));
+ }
+
+ expect(client.startExperiment).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ dataset: { id: "dataset-1", name: "test-project evals", version: 1 },
+ }),
+ );
+ });
+
+ it("updates a record in place when its input changes", async () => {
+ const { config, datasets } = makeConfig();
+ const reporter = Datadog(config);
+
+ await reporter.onRunStart([makeEval()], makeTarget());
+ await reporter.onRunComplete(makeSummary());
+ const recordId = datasets.get("test-project evals")?.records[0]?.id;
+
+ const reworded = makeEvalResult({
+ result: {
+ ...makeEvalResult().result,
+ events: [
+ {
+ type: "message.received",
+ data: { message: "What greeting should I send?", sequence: 1, turnId: "turn-1" },
+ meta: { at: "2026-01-01T00:00:00.000Z", id: "event-1" },
+ },
+ ],
+ },
+ });
+ await reporter.onRunStart([makeEval()], makeTarget());
+ await reporter.onRunComplete(makeSummary(reworded));
+
+ expect(datasets.get("test-project evals")).toMatchObject({
+ version: 2,
+ records: [{ id: recordId, input: "What greeting should I send?" }],
+ });
+ });
+
+ it("suffixes duplicate descriptions in discovery order and falls back to eval ids", async () => {
+ const { config, datasets } = makeConfig();
+ const reporter = Datadog(config);
+ const evaluations = [
+ makeEval({ id: "cases/0000", description: "Same case" }),
+ makeEval({ id: "cases/0001", description: "Same case" }),
+ makeEval({ id: "cases/0002", description: undefined }),
+ ];
+
+ await reporter.onRunStart(evaluations, makeTarget());
+ // Completion order differs from discovery order under concurrency.
+ await reporter.onRunComplete({
+ ...makeSummary(),
+ results: [
+ makeEvalResult({ id: "cases/0002" }),
+ makeEvalResult({ id: "cases/0001" }),
+ makeEvalResult({ id: "cases/0000" }),
+ ],
+ });
+
+ expect(
+ datasets.get("test-project evals")?.records.map((record) => record.metadata.eveRecordKey),
+ ).toEqual(["cases/0002", "Same case #2", "Same case"]);
});
it("creates an input-only dataset record when no expected output is authored", async () => {
- const { client, config } = makeConfig({
+ const { config, datasets } = makeConfig({
datasetName: "input-only dataset",
- recordInputs: true,
- recordExpectedOutputs: true,
});
const reporter = Datadog(config);
const evaluation = makeEval({ metadata: { suite: "unit" } });
@@ -430,17 +603,33 @@ describe("Datadog", () => {
await reporter.onEvalComplete(result);
await reporter.onRunComplete(makeSummary(result));
- const record = client.createDataset.mock.calls[0]?.[1]?.records?.[0];
- expect(record).toEqual({
- inputData: "What should I send you?",
- metadata: { eveEvalId: "eval-1" },
- });
+ expect(datasets.get("input-only dataset")?.records).toEqual([
+ {
+ id: "record-1",
+ input: "What should I send you?",
+ expectedOutput: null,
+ metadata: { eveRecordKey: "Say hello", eveEvalId: "eval-1" },
+ },
+ ]);
+ });
+
+ it("does not create a duplicate dataset when pulling fails for another reason", async () => {
+ const { client, config } = makeConfig();
+ client.pullDataset.mockRejectedValueOnce(
+ new Error("Failed to list datasets in project 'test-project': 503"),
+ );
+ const reporter = Datadog(config);
+
+ await reporter.onRunStart([makeEval()], makeTarget());
+
+ await expect(reporter.onRunComplete(makeSummary())).rejects.toThrow("Failed to list datasets");
+ expect(client.createDataset).not.toHaveBeenCalled();
});
it("uses the dd-trace project environment variable by default", async () => {
vi.stubEnv("DD_LLMOBS_PROJECT_NAME", "environment-project");
try {
- const { client, config } = makeConfig({ projectName: undefined });
+ const { client, config } = makeConfig({ projectName: undefined, recordInputs: false });
const reporter = Datadog(config);
await reporter.onRunStart([makeEval()], makeTarget());
@@ -464,6 +653,25 @@ describe("Datadog", () => {
expect(lines.join("\n")).toContain("Datadog experiment URL: https://dd.test/experiment");
});
+ it("skips reporting without Datadog credentials instead of failing the run", async () => {
+ vi.stubEnv("DD_API_KEY", "");
+ vi.stubEnv("DD_APP_KEY", "");
+ try {
+ const lines: string[] = [];
+ const reporter = Datadog({ projectName: "test-project", log: (line) => lines.push(line) });
+
+ await reporter.onRunStart([makeEval()], makeTarget());
+ await reporter.onEvalComplete(makeEvalResult());
+ await reporter.onRunComplete(makeSummary());
+
+ expect(lines).toEqual([
+ "Datadog reporting skipped: set DD_API_KEY and DD_APP_KEY to upload eval results.\n",
+ ]);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
it("is a no-op before the experiment is initialized", async () => {
const reporter = Datadog(makeConfig().config);
diff --git a/packages/eve/src/evals/runner/reporters/datadog.ts b/packages/eve/src/evals/runner/reporters/datadog.ts
index 81c5910ee..3809dd2e7 100644
--- a/packages/eve/src/evals/runner/reporters/datadog.ts
+++ b/packages/eve/src/evals/runner/reporters/datadog.ts
@@ -1,17 +1,28 @@
-import { createRequire } from "node:module";
-
-import type ddTrace from "dd-trace";
-
import type { EveEval, EveEvalResult, EveEvalRunSummary, EveEvalTarget } from "#evals/types.js";
import type { EvalReporter } from "#evals/runner/reporters/types.js";
+import {
+ getDatadogDataset,
+ MISSING_DATASET_API_MESSAGE,
+ resolveDatadogClient,
+ toDatadogJsonRecord,
+ toDatadogJsonValue,
+ toOptionalDatadogJsonValue,
+ type DatadogDatasetRecord,
+ type DatadogDatasetRecordFields,
+ type DatadogDatasetRecordInput,
+ type DatadogEvaluationMetricInput,
+ type DatadogExperimentsClient,
+ type DatadogExternalExperiment,
+ type DatadogExternalExperimentSpanInput,
+ type DatadogStartExperimentOptions,
+} from "#evals/runner/reporters/datadog-client.js";
import { resolveLocalGitMetadata } from "#evals/runner/resolve-git-metadata.js";
-import { parseJsonValue, type JsonValue } from "#shared/json.js";
/** Configuration for the Datadog reporter. */
export interface DatadogReporterConfig {
/** Datadog LLM Observability project name. Defaults to `DD_LLMOBS_PROJECT_NAME`, the configured ml_app, `DD_SERVICE`, or the first eval id. */
readonly projectName?: string;
- /** Name for the dataset used by the experiment. Defaults to `<experimentName> dataset`. */
+ /** Dataset reused across runs. Defaults to `<projectName> evals`, or `<experimentName> dataset` without `recordInputs`. */
readonly datasetName?: string;
/** Name for the created experiment. Defaults to a timestamped eve eval run name. */
readonly experimentName?: string;
@@ -31,15 +42,15 @@ export interface DatadogReporterConfig {
readonly metadata?: Readonly<Record<string, unknown>>;
/** JSON-serializable Datadog Experiment config. */
readonly config?: Readonly<Record<string, unknown>>;
- /** Include the first sent message, falling back to the eval description, in the experiment row and a linked dataset record. Defaults to false. */
+ /** Include the first sent message, falling back to the eval description, in the experiment row and a linked dataset record. Defaults to true. */
readonly recordInputs?: boolean;
- /** Include eval outputs in the synthetic experiment row output. Defaults to false. */
+ /** Include eval outputs in the synthetic experiment row output. Defaults to true. */
readonly recordOutputs?: boolean;
- /** Include `metadata.expectedOutput`, `metadata.expected`, or `metadata.expected_output` on experiment rows. Defaults to false. */
+ /** Include `metadata.expectedOutput`, `metadata.expected`, or `metadata.expected_output` on experiment rows. Defaults to true. */
readonly recordExpectedOutputs?: boolean;
- /** Include raw assertion names as metric tags and failure messages in row metadata. Defaults to false. */
+ /** Include raw assertion names as metric tags and failure messages in row metadata. Defaults to true. */
readonly recordAssertionDetails?: boolean;
- /** Include execution error messages, which may contain application data. Defaults to false. */
+ /** Include execution error messages, which may contain application data. Defaults to true. */
readonly recordErrors?: boolean;
/** Console hook used for tests. */
readonly log?: (line: string) => void;
@@ -47,109 +58,20 @@ export interface DatadogReporterConfig {
readonly client?: DatadogExperimentsClient;
}
-type DatadogJsonValue =
- | string
- | number
- | boolean
- | null
- | DatadogJsonValue[]
- | { [key: string]: DatadogJsonValue };
-
-interface DatadogDatasetRecordInput {
- inputData: DatadogJsonValue;
- expectedOutput?: DatadogJsonValue;
- metadata?: Record<string, DatadogJsonValue>;
- tags?: string[];
-}
-
-interface DatadogDatasetRecord {
- readonly id: string | null;
-}
-
-interface DatadogDataset {
- id(): string | null;
- name(): string;
- version(): number | null;
- records(): readonly DatadogDatasetRecord[];
- url(): string | null;
- push(): Promise<{ pushedCount: number; totalCount: number }>;
-}
-
-interface DatadogExperimentsClient {
- createDataset?(
- name: string,
- options?: {
- projectName?: string;
- description?: string;
- records?: DatadogDatasetRecordInput[];
- },
- ): DatadogDataset;
- startExperiment(options: DatadogStartExperimentOptions): Promise<DatadogExternalExperiment>;
-}
-
-interface DatadogStartExperimentOptions {
- name: string;
- projectName?: string;
- description?: string;
- tags?: Record<string, string>;
- metadata?: Record<string, DatadogJsonValue>;
- config?: Record<string, DatadogJsonValue>;
- dataset?: {
- id?: string;
- version?: number;
- name?: string;
- description?: string;
- };
-}
-
-interface DatadogExternalExperiment {
- experimentId(): string;
- url(): string | null;
- submitSpan(row: DatadogExternalExperimentSpanInput): Promise<DatadogExternalExperimentSpan>;
- submitEvaluationMetrics(
- span: Pick<DatadogExternalExperimentSpan, "experimentId" | "spanId" | "traceId">,
- metrics: DatadogEvaluationMetricInput[],
- ): Promise<void>;
- close(options?: { status?: string; error?: string | Error }): Promise<void>;
-}
-
-interface DatadogExternalExperimentSpanInput {
- name?: string;
- input?: DatadogJsonValue;
- output?: DatadogJsonValue;
- expectedOutput?: DatadogJsonValue;
- metadata?: Record<string, DatadogJsonValue>;
- tags?: Record<string, string>;
- startedAt?: Date | string | number;
- completedAt?: Date | string | number;
- durationMs?: number;
- error?: string | Error | { type?: string; name?: string; message?: string; stack?: string };
- datasetRecordId?: string;
- runId?: string;
- runIteration?: number;
-}
-
-interface DatadogExternalExperimentSpan {
- experimentId: string;
- spanId: string;
- traceId: string;
- url: string | null;
-}
-
-interface DatadogEvaluationMetricInput {
- label: string;
- value?: DatadogJsonValue;
- error?: string | Error;
- timestamp?: Date | string | number;
- tags?: Record<string, string>;
- source?: string;
-}
-
-type DatadogTraceModule = typeof ddTrace;
+type DatadogRecordingOptions = Required<
+ Pick<
+ DatadogReporterConfig,
+ | "recordInputs"
+ | "recordOutputs"
+ | "recordExpectedOutputs"
+ | "recordAssertionDetails"
+ | "recordErrors"
+ >
+>;
/**
- * Creates an {@link EvalReporter} that uploads eval assertion scores to a
- * Datadog LLM Observability Experiment. Requires the optional `dd-trace`
+ * Creates an {@link EvalReporter} that uploads eval results to a Datadog LLM
+ * Observability Experiment. Requires the optional `dd-trace`
* package and `DD_API_KEY`/`DD_APP_KEY` credentials unless `config.client` is
* provided.
*/
@@ -159,7 +81,9 @@ export function Datadog(config: DatadogReporterConfig = {}): EvalReporter {
class DatadogReporter implements EvalReporter {
readonly #config: DatadogReporterConfig;
+ readonly #recording: DatadogRecordingOptions;
readonly #evaluations = new Map<string, EveEval>();
+ #recordKeys = new Map<string, string>();
#client: DatadogExperimentsClient | undefined;
#experimentOptions: DatadogStartExperimentOptions | undefined;
#experiment: DatadogExternalExperiment | undefined;
@@ -167,6 +91,13 @@ class DatadogReporter implements EvalReporter {
constructor(config: DatadogReporterConfig) {
this.#config = config;
+ this.#recording = {
+ recordInputs: config.recordInputs ?? true,
+ recordOutputs: config.recordOutputs ?? true,
+ recordExpectedOutputs: config.recordExpectedOutputs ?? true,
+ recordAssertionDetails: config.recordAssertionDetails ?? true,
+ recordErrors: config.recordErrors ?? true,
+ };
}
async onRunStart(evaluations: readonly EveEval[], target: EveEvalTarget): Promise<void> {
@@ -178,8 +109,18 @@ class DatadogReporter implements EvalReporter {
for (const evaluation of evaluations) {
this.#evaluations.set(evaluation.id, evaluation);
}
+ this.#recordKeys = composeDatasetRecordKeys(evaluations);
+
+ // Without credentials, dd-trace datasets never receive ids.
+ if (!this.#config.client && (!process.env.DD_API_KEY || !process.env.DD_APP_KEY)) {
+ (this.#config.log ?? console.log)(
+ "Datadog reporting skipped: set DD_API_KEY and DD_APP_KEY to upload eval results.\n",
+ );
+ return;
+ }
- const client = await resolveDatadogClient(this.#config, evaluations);
+ const projectName = resolveProjectName(this.#config, evaluations);
+ const client = await resolveDatadogClient(this.#config, projectName);
const git = resolveLocalGitMetadata(process.cwd());
const experimentName = this.#config.experimentName ?? defaultExperimentName();
@@ -190,21 +131,22 @@ class DatadogReporter implements EvalReporter {
}
Object.assign(metadata, this.#config.metadata);
+ const defaultDatasetName = this.#recording.recordInputs
+ ? `${projectName} evals`
+ : `${experimentName} dataset`;
const experimentOptions: DatadogStartExperimentOptions = {
name: experimentName,
- projectName: resolveProjectName(this.#config, evaluations),
+ projectName,
description: this.#config.description,
- dataset: { name: this.#config.datasetName ?? `${experimentName} dataset` },
+ dataset: { name: this.#config.datasetName ?? defaultDatasetName },
tags: resolveExperimentTags(this.#config, target),
metadata: toDatadogJsonRecord(metadata),
config: toDatadogJsonRecord(this.#config.config),
};
- if (this.#config.recordInputs) {
- if (!client.createDataset) {
- throw new Error(
- "The installed 'dd-trace' package does not expose tracer.llmobs.experiments.createDataset().",
- );
+ if (this.#recording.recordInputs) {
+ if (!client.createDataset || !client.pullDataset) {
+ throw new Error(MISSING_DATASET_API_MESSAGE);
}
this.#client = client;
this.#experimentOptions = experimentOptions;
@@ -215,13 +157,13 @@ class DatadogReporter implements EvalReporter {
}
async onEvalComplete(result: EveEvalResult): Promise<void> {
- if (this.#config.recordInputs || !this.#experiment) return;
+ if (this.#recording.recordInputs || !this.#experiment) return;
await this.#submitResult(result);
}
async onRunComplete(summary: EveEvalRunSummary): Promise<void> {
try {
- if (this.#config.recordInputs) {
+ if (this.#recording.recordInputs) {
await this.#startDatasetBackedExperiment(summary.results);
}
if (!this.#experiment) return;
@@ -251,47 +193,64 @@ class DatadogReporter implements EvalReporter {
async #startDatasetBackedExperiment(results: readonly EveEvalResult[]): Promise<void> {
const client = this.#client;
const experimentOptions = this.#experimentOptions;
- if (!client?.createDataset || !experimentOptions) return;
-
- const datasetName = experimentOptions.dataset?.name ?? `${experimentOptions.name} dataset`;
- const records = results.map((result): DatadogDatasetRecordInput => {
- const evaluation = this.#evaluations.get(result.id);
- const record: DatadogDatasetRecordInput = {
- inputData: toDatadogJsonValue(resolveInput(result, evaluation)),
- metadata: { eveEvalId: result.id },
- };
- if (this.#config.recordExpectedOutputs) {
- const expectedOutput = toOptionalDatadogJsonValue(resolveExpectedOutput(evaluation));
- if (expectedOutput !== undefined) {
- record.expectedOutput = expectedOutput;
- }
- }
- return record;
- });
- const dataset = client.createDataset(datasetName, {
+ if (!client || !experimentOptions) return;
+
+ const datasetName = experimentOptions.dataset?.name ?? `${experimentOptions.projectName} evals`;
+ const dataset = await getDatadogDataset(client, datasetName, {
projectName: experimentOptions.projectName,
- description:
- this.#config.description ?? `Eve eval inputs for experiment '${experimentOptions.name}'.`,
- records,
+ description: this.#config.description ?? "eve eval inputs.",
});
+ const recordIndexes = new Map<string, number>();
+ for (const [index, record] of dataset.records().entries()) {
+ const recordKey = record.metadata[DATASET_RECORD_KEY_METADATA];
+ if (typeof recordKey === "string") {
+ recordIndexes.set(recordKey, index);
+ }
+ }
+
+ const newRecords: DatadogDatasetRecordInput[] = [];
+ for (const result of results) {
+ const nextRecord = this.#composeDatasetRecord(result);
+ const index = recordIndexes.get(this.#getRecordKey(result.id));
+ if (index === undefined) {
+ newRecords.push({
+ inputData: nextRecord.input,
+ metadata: nextRecord.metadata,
+ ...(nextRecord.expectedOutput === null
+ ? {}
+ : { expectedOutput: nextRecord.expectedOutput }),
+ });
+ continue;
+ }
+ const record = dataset.records()[index];
+ if (record && !isDatasetRecordEqual(record, nextRecord)) {
+ dataset.update(index, nextRecord);
+ }
+ }
+ if (newRecords.length > 0) {
+ dataset.addRecords(newRecords);
+ }
+
await dataset.push();
const datasetId = dataset.id();
if (!datasetId) {
throw new Error(`Datadog dataset '${datasetName}' has no id after push().`);
}
- const datasetRecords = dataset.records();
- if (datasetRecords.length !== results.length) {
- throw new Error(
- `Datadog dataset '${datasetName}' has ${datasetRecords.length} records for ${results.length} eval results.`,
- );
+ const recordIds = new Map<string, string>();
+ for (const record of dataset.records()) {
+ const recordKey = record.metadata[DATASET_RECORD_KEY_METADATA];
+ if (typeof recordKey === "string" && record.id) {
+ recordIds.set(recordKey, record.id);
+ }
}
const datasetOptions: NonNullable<DatadogStartExperimentOptions["dataset"]> = {
id: datasetId,
name: dataset.name(),
};
- const datasetVersion = dataset.version();
+ // An unchanged pulled dataset has no pinned version.
+ const datasetVersion = dataset.version() ?? dataset.latestVersion();
if (datasetVersion !== null) {
datasetOptions.version = datasetVersion;
}
@@ -301,15 +260,37 @@ class DatadogReporter implements EvalReporter {
dataset: datasetOptions,
});
- for (const [index, result] of results.entries()) {
- const datasetRecordId = datasetRecords[index]?.id;
+ for (const result of results) {
+ const recordKey = this.#getRecordKey(result.id);
+ const datasetRecordId = recordIds.get(recordKey);
if (!datasetRecordId) {
- throw new Error(`Datadog dataset record ${index + 1} has no id after push().`);
+ throw new Error(
+ `Datadog dataset '${datasetName}' has no record id for '${recordKey}' after push().`,
+ );
}
await this.#submitResult(result, datasetRecordId);
}
}
+ #getRecordKey(evalId: string): string {
+ return this.#recordKeys.get(evalId) ?? evalId;
+ }
+
+ #composeDatasetRecord(result: EveEvalResult): DatadogDatasetRecordFields {
+ const evaluation = this.#evaluations.get(result.id);
+ const expectedOutput = this.#recording.recordExpectedOutputs
+ ? toOptionalDatadogJsonValue(resolveExpectedOutput(evaluation))
+ : undefined;
+ return {
+ input: toDatadogJsonValue(resolveInput(result, evaluation)),
+ expectedOutput: expectedOutput ?? null,
+ metadata: {
+ [DATASET_RECORD_KEY_METADATA]: this.#getRecordKey(result.id),
+ eveEvalId: result.id,
+ },
+ };
+ }
+
async #submitResult(result: EveEvalResult, datasetRecordId?: string): Promise<void> {
if (!this.#experiment) return;
@@ -317,23 +298,23 @@ class DatadogReporter implements EvalReporter {
const spanInput: DatadogExternalExperimentSpanInput = {
name: result.id,
metadata: toDatadogJsonRecord(
- resolveResultMetadata(result, evaluation, this.#config.recordAssertionDetails === true),
+ resolveResultMetadata(result, evaluation, this.#recording.recordAssertionDetails),
),
tags: resolveResultTags(result, evaluation),
startedAt: result.startedAt,
completedAt: result.completedAt,
durationMs: elapsedMs(result.startedAt, result.completedAt),
};
- if (this.#config.recordInputs) {
+ if (this.#recording.recordInputs) {
spanInput.input = toOptionalDatadogJsonValue(resolveInput(result, evaluation));
}
- if (this.#config.recordOutputs) {
+ if (this.#recording.recordOutputs) {
spanInput.output = toOptionalDatadogJsonValue(result.result.output);
}
- if (this.#config.recordExpectedOutputs) {
+ if (this.#recording.recordExpectedOutputs) {
spanInput.expectedOutput = toOptionalDatadogJsonValue(resolveExpectedOutput(evaluation));
}
- if (this.#config.recordErrors && result.error !== undefined) {
+ if (this.#recording.recordErrors && result.error !== undefined) {
spanInput.error = result.error;
}
if (datasetRecordId !== undefined) {
@@ -343,12 +324,11 @@ class DatadogReporter implements EvalReporter {
const span = await this.#experiment.submitSpan(spanInput);
await this.#experiment.submitEvaluationMetrics(
span,
- resolveEvaluationMetrics(result, this.#config.recordAssertionDetails === true),
+ resolveEvaluationMetrics(result, this.#recording.recordAssertionDetails),
);
}
}
-const DD_TRACE_PACKAGE = "dd-trace";
const EXPECTED_OUTPUT_METADATA_KEYS: ReadonlySet<string> = new Set([
"expectedOutput",
"expected",
@@ -360,57 +340,30 @@ const BUILT_IN_METRIC_LABELS = [
"eve_message_count",
"eve_reasoning_block_count",
] as const;
-
-async function resolveDatadogClient(
- config: DatadogReporterConfig,
- evaluations: readonly EveEval[],
-): Promise<DatadogExperimentsClient> {
- if (config.client) return config.client;
-
- const sdk = await loadDatadogSdk();
- const projectName = resolveProjectName(config, evaluations);
- const tracer = sdk.init({
- service: config.service ?? process.env.DD_SERVICE ?? projectName,
- env: config.env ?? process.env.DD_ENV,
- site: config.site ?? process.env.DD_SITE,
- llmobs: {
- projectName,
- mlApp: config.mlApp ?? projectName,
- agentlessEnabled: true,
- },
- });
-
- const experiments = tracer.llmobs?.experiments;
- if (!experiments?.startExperiment) {
- throw new Error(
- [
- "The installed 'dd-trace' package does not expose tracer.llmobs.experiments.startExperiment().",
- "Update to a release compatible with [email protected].",
- ].join("\n"),
- );
+const DATASET_RECORD_KEY_METADATA = "eveRecordKey";
+
+// Index-based eval ids shift when cases move, so records are keyed by description.
+function composeDatasetRecordKeys(evaluations: readonly EveEval[]): Map<string, string> {
+ const keys = new Map<string, string>();
+ const counts = new Map<string, number>();
+ for (const evaluation of evaluations) {
+ const baseKey = evaluation.description?.trim() || evaluation.id;
+ const count = (counts.get(baseKey) ?? 0) + 1;
+ counts.set(baseKey, count);
+ keys.set(evaluation.id, count === 1 ? baseKey : `${baseKey} #${count}`);
}
- return experiments;
+ return keys;
}
-async function loadDatadogSdk(): Promise<DatadogTraceModule> {
- try {
- const requireFromApp = createRequire(`${process.cwd()}/package.json`);
- return requireFromApp(DD_TRACE_PACKAGE) as DatadogTraceModule;
- } catch {
- try {
- const mod = (await import(DD_TRACE_PACKAGE)) as { default?: unknown };
- return (mod.default ?? mod) as DatadogTraceModule;
- } catch {
- throw new Error(
- [
- "The 'dd-trace' package is required for Datadog reporting but was not found.",
- "",
- "Install the tested release with:",
- " npm install [email protected]",
- ].join("\n"),
- );
- }
- }
+function isDatasetRecordEqual(
+ record: DatadogDatasetRecord,
+ fields: DatadogDatasetRecordFields,
+): boolean {
+ return (
+ JSON.stringify(record.input) === JSON.stringify(fields.input) &&
+ JSON.stringify(record.expectedOutput ?? null) === JSON.stringify(fields.expectedOutput) &&
+ JSON.stringify(record.metadata) === JSON.stringify(fields.metadata)
+ );
}
function resolveProjectName(
@@ -592,39 +545,3 @@ function elapsedMs(startedAt: string, completedAt: string): number | undefined {
if (!Number.isFinite(start) || !Number.isFinite(completed)) return undefined;
return Math.max(0, completed - start);
}
-
-function toOptionalDatadogJsonValue(value: unknown): DatadogJsonValue | undefined {
- return value === undefined ? undefined : toDatadogJsonValue(value);
-}
-
-function toDatadogJsonRecord(
- value: Readonly<Record<string, unknown>> | undefined,
-): Record<string, DatadogJsonValue> | undefined {
- if (value === undefined) return undefined;
-
- const output: Record<string, DatadogJsonValue> = {};
- for (const [key, entry] of Object.entries(value)) {
- if (entry !== undefined) {
- output[key] = toDatadogJsonValue(entry);
- }
- }
- return output;
-}
-
-function toDatadogJsonValue(value: unknown): DatadogJsonValue {
- return cloneDatadogJsonValue(parseJsonValue(value));
-}
-
-function cloneDatadogJsonValue(value: JsonValue): DatadogJsonValue {
- if (Array.isArray(value)) {
- return value.map((entry) => cloneDatadogJsonValue(entry));
- }
- if (value !== null && typeof value === "object") {
- const output: Record<string, DatadogJsonValue> = {};
- for (const [key, entry] of Object.entries(value)) {
- output[key] = cloneDatadogJsonValue(entry);
- }
- return output;
- }
- return value;
-}
diff --git a/research/datadog-experiment-reporter.md b/research/datadog-experiment-reporter.md
index a9c1c720d..002060dd6 100644
--- a/research/datadog-experiment-reporter.md
+++ b/research/datadog-experiment-reporter.md
@@ -61,21 +61,21 @@ project from explicit reporter config, `DD_LLMOBS_PROJECT_NAME`, ml_app config,
## Row mapping
- `name`: the path-derived eve eval id.
-- `input`, `output`, and expected output: opt-in because they may contain user
- data. When input recording is enabled, completed evals are buffered until run
- completion, their inputs are pushed as versioned dataset records, and each
+- `input`, `output`, and expected output: recorded by default, with opt-outs.
+ When input recording is enabled, completed evals are buffered until run
+ completion, their inputs are synced into one reused dataset keyed by eval
+ description, and each
experiment span carries its generated dataset record id. Expected output is
- included in the dataset record only when present and explicitly enabled.
+ included in the dataset record only when present and enabled.
- `metadata`: verdict, status, session id, tool/subagent names, authored eval
metadata, sanitized target origin, and local git metadata when available.
- `tags`: eval id, verdict, status, and authored eval tags.
- metrics: assertion scores under normalized descriptive assertion names plus
tool, subagent, message, and reasoning counts. Gate labels receive a `gate_`
prefix, and authors can set stable names with `.label(...)`. Raw assertion-name
- tags and failure messages require the explicit `recordAssertionDetails`
- privacy opt-in.
+ tags and failure messages can be omitted with `recordAssertionDetails`.
- timestamps: the values already captured by the eval runner.
-- error: opt-in because exception messages may contain application data.
+- error: recorded by default; `recordErrors: false` omits it.
All metadata, config, inputs, and outputs are normalized to the JSON value shape
accepted by `dd-trace` before submission.