From 896e5114d79d5c3004a35fb280bc915185c6b568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=99=9C=E5=99=9C?= <1828703450qq.com@gmail.com> Date: Sat, 21 Nov 2026 05:16:58 +0800 Subject: [PATCH 1/2] fix(eval): validate ground-truth session ids --- src/core/eval.tsx | 47 +++++++++- src/core/evalGroundTruth.test.ts | 142 +++++++++++++++++++++++++++++++ 2 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 src/core/evalGroundTruth.test.ts diff --git a/src/core/eval.tsx b/src/core/eval.tsx index fd24625a9..19c12f866 100644 --- a/src/core/eval.tsx +++ b/src/core/eval.tsx @@ -781,6 +781,9 @@ export class EvalClient implements CoreEvalClient { input: StartBatchEvaluationInput, options: CoreOptions, ): Promise { + for (const [index, metadata] of (input.groundTruth ?? []).entries()) { + requireGroundTruthSessionId(metadata.sessionId, index, "sessionId"); + } const dataSourceConfig = await this.dataSourceConfigForSource(input.source, options); return this.clients.data(toClientConfig(options)).send( new StartBatchEvaluationCommand({ @@ -908,10 +911,29 @@ export class EvalClient implements CoreEvalClient { } async evaluate(input: EvaluateInput, options: CoreOptions): Promise { + const refsBySession = groupRefsBySession(input.groundTruth); const data = this.clients.data(toClientConfig(options)); const control = this.clients.control(toClientConfig(options)); const levels = await resolveEvaluatorLevels(input.evaluatorIds, control, options); - const refsBySession = groupRefsBySession(input.groundTruth); + + // A reference is useful only if some evaluator will issue an Evaluate call + // for its session. TRACE and TOOL_CALL evaluators skip sessions with no IDs + // at that level, so warn for those as well as session IDs absent from traces. + const sessionsWithTargets = new Set(); + for (const evaluatorId of input.evaluatorIds) { + const level = levels.get(evaluatorId) ?? "SESSION"; + for (const trace of input.traces) { + if (targetBatches(level, trace).length > 0) sessionsWithTargets.add(trace.sessionId); + } + } + const unusedReferenceSessions = [...refsBySession.keys()].filter( + (sessionId) => !sessionsWithTargets.has(sessionId), + ); + if (unusedReferenceSessions.length > 0) { + this.logger.warn( + `ground-truth entries reference sessions not evaluated: ${unusedReferenceSessions.join(", ")}`, + ); + } const results: EvaluationResultContent[] = []; // Sessions that actually produced Evaluate results — distinct from the sessions @@ -2032,10 +2054,14 @@ function groupRefsBySession( groundTruth: EvaluationReferenceInput[] | undefined, ): Map { const map = new Map(); - for (const ref of groundTruth ?? []) { - const sessionId = + for (const [index, ref] of (groundTruth ?? []).entries()) { + const rawSessionId = ref.context && "spanContext" in ref.context ? ref.context.spanContext?.sessionId : undefined; - if (!sessionId) continue; + const sessionId = requireGroundTruthSessionId( + rawSessionId, + index, + "context.spanContext.sessionId", + ); const list = map.get(sessionId); if (list) list.push(ref); else map.set(sessionId, [ref]); @@ -2043,6 +2069,19 @@ function groupRefsBySession( return map; } +function requireGroundTruthSessionId( + sessionId: string | undefined, + index: number, + field: string, +): string { + if (typeof sessionId !== "string" || sessionId.trim().length === 0) { + throw new InputValidationError( + `Invalid value for option '--ground-truth': entry ${index} is missing ${field}`, + ); + } + return sessionId; +} + // targetBatches splits a session's evaluation targets into <=10-id Evaluate calls. // SESSION evaluators make a single call with no target; TRACE/TOOL_CALL sessions // with no ids at that level make none (the session is skipped for that evaluator). diff --git a/src/core/evalGroundTruth.test.ts b/src/core/evalGroundTruth.test.ts new file mode 100644 index 000000000..6092474bb --- /dev/null +++ b/src/core/evalGroundTruth.test.ts @@ -0,0 +1,142 @@ +import { test, expect, describe } from "bun:test"; +import { + EvaluateCommand, + StartBatchEvaluationCommand, + type EvaluationReferenceInput, + type SessionMetadataShape, +} from "@aws-sdk/client-bedrock-agentcore"; +import { GetEvaluatorCommand } from "@aws-sdk/client-bedrock-agentcore-control"; +import { EvalClient } from "./eval"; +import { InputValidationError } from "../errors"; +import type { Logger } from "../logging"; +import type { AwsClients } from "./types"; +import type { SessionTrace, SessionSourceValue } from "../handlers/eval/types"; + +const OPTIONS = { region: "us-west-2" }; +const TRACE: SessionTrace = { + sessionId: "session-1", + spans: [{ traceId: "trace-1", spanId: "span-1" }], + traceIds: ["trace-1"], + toolCallSpanIds: [], +}; + +function makeClient() { + const evaluateInputs: unknown[] = []; + const batchInputs: unknown[] = []; + const warnings: string[] = []; + const logger: Logger = { + debug: () => {}, + info: () => {}, + warn: (...messages) => warnings.push(messages.join(" ")), + error: () => {}, + child: () => logger, + }; + const clients = { + control: () => ({ + send: async (command: unknown) => { + if (command instanceof GetEvaluatorCommand) { + return { evaluatorId: "evaluator-1", level: "SESSION" }; + } + throw new Error(`unexpected control command: ${(command as object).constructor.name}`); + }, + }), + data: () => ({ + send: async (command: unknown) => { + if (command instanceof EvaluateCommand) { + evaluateInputs.push(command.input); + return { evaluationResults: [] }; + } + if (command instanceof StartBatchEvaluationCommand) { + batchInputs.push(command.input); + return { batchEvaluationId: "batch-1" }; + } + throw new Error(`unexpected data command: ${(command as object).constructor.name}`); + }, + }), + } as unknown as AwsClients; + return { + client: new EvalClient(clients, undefined, logger), + evaluateInputs, + batchInputs, + warnings, + }; +} + +describe("on-demand evaluation ground truth", () => { + test("rejects a reference without context.spanContext.sessionId before evaluating", async () => { + const { client, evaluateInputs } = makeClient(); + const reference = { + context: { spanContext: { traceId: "trace-1" } }, + expectedResponse: { text: "expected" }, + } as unknown as EvaluationReferenceInput; + + const error = await client + .evaluate( + { traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] }, + OPTIONS, + ) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(InputValidationError); + expect(error).toMatchObject({ + message: expect.stringMatching(/entry 0 is missing context\.spanContext\.sessionId/), + }); + expect(evaluateInputs).toHaveLength(0); + }); + + test("warns when a reference session does not have an evaluation target", async () => { + const { client, evaluateInputs, warnings } = makeClient(); + const reference: EvaluationReferenceInput = { + context: { spanContext: { sessionId: "other-session" } }, + expectedResponse: { text: "expected" }, + }; + + await client.evaluate( + { traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] }, + OPTIONS, + ); + + expect(evaluateInputs).toHaveLength(1); + expect(evaluateInputs[0]).toMatchObject({ evaluationReferenceInputs: undefined }); + expect(warnings).toEqual([ + "ground-truth entries reference sessions not evaluated: other-session", + ]); + }); + + test("attaches matching references to their session evaluation", async () => { + const { client, evaluateInputs, warnings } = makeClient(); + const reference: EvaluationReferenceInput = { + context: { spanContext: { sessionId: "session-1" } }, + expectedResponse: { text: "expected" }, + }; + + await client.evaluate( + { traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] }, + OPTIONS, + ); + + expect(evaluateInputs[0]).toMatchObject({ evaluationReferenceInputs: [reference] }); + expect(warnings).toEqual([]); + }); +}); + +describe("batch evaluation ground truth", () => { + test("rejects session metadata without sessionId before starting the job", async () => { + const { client, batchInputs } = makeClient(); + const source = { + origin: "raw", + dataSourceConfig: {}, + } as unknown as SessionSourceValue; + const groundTruth = [ + { groundTruth: { inline: { turns: [] } } }, + ] as unknown as SessionMetadataShape[]; + + await expect( + client.startBatchEvaluation( + { name: "eval-1", evaluatorIds: ["evaluator-1"], source, groundTruth }, + OPTIONS, + ), + ).rejects.toThrow(/entry 0 is missing sessionId/); + expect(batchInputs).toHaveLength(0); + }); +}); From 72c72051b70c92ee4710ec26d13f038b95e3502d Mon Sep 17 00:00:00 2001 From: He Yunhui <265310764+1828703450qqcom-ux@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:42:46 +0800 Subject: [PATCH 2/2] fix(eval): warn on stderr for unused ground truth and validate ground-truth entries --- src/core/eval.tsx | 55 ++++++++--- src/core/evalGroundTruth.test.ts | 77 ++++++++++++++- .../batch-evaluation.test.tsx | 17 ++++ .../eval/batch-evaluation/evaluate/index.tsx | 9 +- src/handlers/eval/ondemand/evaluate/index.tsx | 3 +- src/handlers/eval/ondemand/ondemand.test.tsx | 95 ++++++++++++++++++- src/handlers/eval/ondemand/simulate/index.tsx | 10 +- src/handlers/eval/types.tsx | 6 +- src/testing/TestCoreClient.tsx | 6 +- 9 files changed, 248 insertions(+), 30 deletions(-) diff --git a/src/core/eval.tsx b/src/core/eval.tsx index 19c12f866..7ddf94bb0 100644 --- a/src/core/eval.tsx +++ b/src/core/eval.tsx @@ -781,7 +781,17 @@ export class EvalClient implements CoreEvalClient { input: StartBatchEvaluationInput, options: CoreOptions, ): Promise { + if (input.groundTruth !== undefined && !Array.isArray(input.groundTruth)) { + throw new InputValidationError( + "Invalid value for option '--ground-truth': expected a JSON array", + ); + } for (const [index, metadata] of (input.groundTruth ?? []).entries()) { + if (!isPlainObject(metadata)) { + throw new InputValidationError( + `Invalid value for option '--ground-truth': entry ${index} must be a JSON object`, + ); + } requireGroundTruthSessionId(metadata.sessionId, index, "sessionId"); } const dataSourceConfig = await this.dataSourceConfigForSource(input.source, options); @@ -910,7 +920,11 @@ export class EvalClient implements CoreEvalClient { return traces; } - async evaluate(input: EvaluateInput, options: CoreOptions): Promise { + async evaluate( + input: EvaluateInput, + options: CoreOptions, + onWarning?: (message: string) => void, + ): Promise { const refsBySession = groupRefsBySession(input.groundTruth); const data = this.clients.data(toClientConfig(options)); const control = this.clients.control(toClientConfig(options)); @@ -930,9 +944,9 @@ export class EvalClient implements CoreEvalClient { (sessionId) => !sessionsWithTargets.has(sessionId), ); if (unusedReferenceSessions.length > 0) { - this.logger.warn( - `ground-truth entries reference sessions not evaluated: ${unusedReferenceSessions.join(", ")}`, - ); + const warning = `ground-truth entries reference sessions not evaluated: ${unusedReferenceSessions.join(", ")}`; + this.logger.warn(warning); + onWarning?.(warning); } const results: EvaluationResultContent[] = []; @@ -2046,6 +2060,10 @@ async function resolveEvaluatorLevels( return levels; } +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + // groupRefsBySession indexes ground-truth reference inputs by the session they // apply to (context.spanContext.sessionId), so each Evaluate call attaches only its // own session's references — the synchronous Evaluate shape, not batch's job-level @@ -2054,26 +2072,35 @@ function groupRefsBySession( groundTruth: EvaluationReferenceInput[] | undefined, ): Map { const map = new Map(); - for (const [index, ref] of (groundTruth ?? []).entries()) { - const rawSessionId = - ref.context && "spanContext" in ref.context ? ref.context.spanContext?.sessionId : undefined; + if (groundTruth === undefined) return map; + if (!Array.isArray(groundTruth)) { + throw new InputValidationError( + "Invalid value for option '--ground-truth': expected a JSON array", + ); + } + for (const [index, ref] of groundTruth.entries()) { + if (!isPlainObject(ref)) { + throw new InputValidationError( + `Invalid value for option '--ground-truth': entry ${index} must be a JSON object`, + ); + } + const context = isPlainObject(ref.context) ? ref.context : undefined; + const spanContext = + context && isPlainObject(context.spanContext) ? context.spanContext : undefined; + const rawSessionId = spanContext?.sessionId; const sessionId = requireGroundTruthSessionId( rawSessionId, index, "context.spanContext.sessionId", ); const list = map.get(sessionId); - if (list) list.push(ref); - else map.set(sessionId, [ref]); + if (list) list.push(ref as EvaluationReferenceInput); + else map.set(sessionId, [ref as EvaluationReferenceInput]); } return map; } -function requireGroundTruthSessionId( - sessionId: string | undefined, - index: number, - field: string, -): string { +function requireGroundTruthSessionId(sessionId: unknown, index: number, field: string): string { if (typeof sessionId !== "string" || sessionId.trim().length === 0) { throw new InputValidationError( `Invalid value for option '--ground-truth': entry ${index} is missing ${field}`, diff --git a/src/core/evalGroundTruth.test.ts b/src/core/evalGroundTruth.test.ts index 6092474bb..40f8f3b2c 100644 --- a/src/core/evalGroundTruth.test.ts +++ b/src/core/evalGroundTruth.test.ts @@ -20,7 +20,7 @@ const TRACE: SessionTrace = { toolCallSpanIds: [], }; -function makeClient() { +function makeClient(evaluatorLevel: "SESSION" | "TRACE" | "TOOL_CALL" = "SESSION") { const evaluateInputs: unknown[] = []; const batchInputs: unknown[] = []; const warnings: string[] = []; @@ -35,7 +35,7 @@ function makeClient() { control: () => ({ send: async (command: unknown) => { if (command instanceof GetEvaluatorCommand) { - return { evaluatorId: "evaluator-1", level: "SESSION" }; + return { evaluatorId: "evaluator-1", level: evaluatorLevel }; } throw new Error(`unexpected control command: ${(command as object).constructor.name}`); }, @@ -86,6 +86,7 @@ describe("on-demand evaluation ground truth", () => { test("warns when a reference session does not have an evaluation target", async () => { const { client, evaluateInputs, warnings } = makeClient(); + const emittedWarnings: string[] = []; const reference: EvaluationReferenceInput = { context: { spanContext: { sessionId: "other-session" } }, expectedResponse: { text: "expected" }, @@ -94,6 +95,7 @@ describe("on-demand evaluation ground truth", () => { await client.evaluate( { traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] }, OPTIONS, + (message) => emittedWarnings.push(message), ); expect(evaluateInputs).toHaveLength(1); @@ -101,6 +103,40 @@ describe("on-demand evaluation ground truth", () => { expect(warnings).toEqual([ "ground-truth entries reference sessions not evaluated: other-session", ]); + expect(emittedWarnings).toEqual(warnings); + }); + + test("warns and skips Evaluate when a session has no tool-call spans for a TOOL_CALL evaluator", async () => { + const { client, evaluateInputs, warnings } = makeClient("TOOL_CALL"); + const emittedWarnings: string[] = []; + const reference: EvaluationReferenceInput = { + context: { spanContext: { sessionId: "session-1" } }, + expectedResponse: { text: "expected" }, + }; + + const result = await client.evaluate( + { traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth: [reference] }, + OPTIONS, + (message) => emittedWarnings.push(message), + ); + + expect(evaluateInputs).toHaveLength(0); + expect(result).toEqual({ sessionsRequested: 1, sessionsEvaluated: 0, results: [] }); + expect(warnings).toEqual(["ground-truth entries reference sessions not evaluated: session-1"]); + expect(emittedWarnings).toEqual(warnings); + }); + + test("rejects '[null]' on-demand ground-truth entry before calling Evaluate", async () => { + const { client, evaluateInputs } = makeClient(); + const groundTruth = [null] as unknown as EvaluationReferenceInput[]; + + const error = await client + .evaluate({ traces: [TRACE], evaluatorIds: ["evaluator-1"], groundTruth }, OPTIONS) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(InputValidationError); + expect((error as Error).message).toMatch(/--ground-truth.*entry 0/); + expect(evaluateInputs).toHaveLength(0); }); test("attaches matching references to their session evaluation", async () => { @@ -139,4 +175,41 @@ describe("batch evaluation ground truth", () => { ).rejects.toThrow(/entry 0 is missing sessionId/); expect(batchInputs).toHaveLength(0); }); + + test("rejects non-array '{}' and '[null]' batch ground-truth entries before starting the job", async () => { + const { client, batchInputs } = makeClient(); + const source = { + origin: "raw", + dataSourceConfig: {}, + } as unknown as SessionSourceValue; + + const objectError = await client + .startBatchEvaluation( + { + name: "eval-1", + evaluatorIds: ["evaluator-1"], + source, + groundTruth: {} as unknown as SessionMetadataShape[], + }, + OPTIONS, + ) + .catch((caught: unknown) => caught); + expect(objectError).toBeInstanceOf(InputValidationError); + expect((objectError as Error).message).toMatch(/--ground-truth/); + + const nullEntryError = await client + .startBatchEvaluation( + { + name: "eval-1", + evaluatorIds: ["evaluator-1"], + source, + groundTruth: [null] as unknown as SessionMetadataShape[], + }, + OPTIONS, + ) + .catch((caught: unknown) => caught); + expect(nullEntryError).toBeInstanceOf(InputValidationError); + expect((nullEntryError as Error).message).toMatch(/--ground-truth.*entry 0/); + expect(batchInputs).toHaveLength(0); + }); }); diff --git a/src/handlers/eval/batch-evaluation/batch-evaluation.test.tsx b/src/handlers/eval/batch-evaluation/batch-evaluation.test.tsx index b70d6fd3b..49ba77042 100644 --- a/src/handlers/eval/batch-evaluation/batch-evaluation.test.tsx +++ b/src/handlers/eval/batch-evaluation/batch-evaluation.test.tsx @@ -430,6 +430,23 @@ describe("eval batch-evaluation evaluate --output-config", () => { ).rejects.toThrow(/only one option may read from stdin.*'--output-config'.*'--ground-truth'/); expect(core.eval.calls).toEqual([]); }); + + test("rejects non-array --ground-truth '{}' before any SDK call", async () => { + const core = new TestCoreClient(); + const io = testIO(); + const root = createRootHandler(core, { + io: io.io, + logger: createSilentLogger(), + globalConfigAccessor: new TestGlobalConfigAccessor(), + }); + const error = await root + .route(["node", "agentcore", ...BASE, "--ground-truth", "{}", "--region", "us-west-2"]) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(InputValidationError); + expect((error as Error).message).toMatch(/--ground-truth/); + expect(core.eval.calls).toEqual([]); + }); }); describe("eval batch-evaluation simulate --endpoint and --output-config", () => { diff --git a/src/handlers/eval/batch-evaluation/evaluate/index.tsx b/src/handlers/eval/batch-evaluation/evaluate/index.tsx index ddd7ddb4c..7b15d162b 100644 --- a/src/handlers/eval/batch-evaluation/evaluate/index.tsx +++ b/src/handlers/eval/batch-evaluation/evaluate/index.tsx @@ -4,7 +4,7 @@ import { JsonRendererKey } from "../../../../tui"; import { SourceResolver, type AppIO } from "../../../../io"; import type { Core } from "../../../types"; import type { SessionMetadataShape } from "@aws-sdk/client-bedrock-agentcore"; -import { coreOptsFromCtx, parseJsonFlag } from "../../../utils"; +import { coreOptsFromCtx, parseJsonArrayFlag } from "../../../utils"; import { SessionSource } from "../../sessionSource"; import { BatchOutputConfig } from "../outputConfig"; @@ -84,13 +84,12 @@ export const createEvaluateBatchEvaluationHandler = (core: Core, io: AppIO) => const resolver = new SourceResolver({ stdin: io.stdin }); const source = await SessionSource.resolve(flags, resolver); - const groundTruth = parseJsonFlag( - "ground-truth", - await resolver.resolveText("ground-truth", flags["ground-truth"]), - ); + const rawGroundTruth = await resolver.resolveText("ground-truth", flags["ground-truth"]); const outputConfig = await BatchOutputConfig.resolve(flags["output-config"], resolver); + const groundTruth = parseJsonArrayFlag("ground-truth", rawGroundTruth); + const response = await core.eval.startBatchEvaluation( { name: flags["name"], diff --git a/src/handlers/eval/ondemand/evaluate/index.tsx b/src/handlers/eval/ondemand/evaluate/index.tsx index e22f4e1c1..f8978e637 100644 --- a/src/handlers/eval/ondemand/evaluate/index.tsx +++ b/src/handlers/eval/ondemand/evaluate/index.tsx @@ -2,7 +2,7 @@ import z from "zod"; import { createHandler, flag } from "../../../../router"; import { InputValidationError } from "../../../../errors"; import { JsonRendererKey } from "../../../../tui"; -import { SourceResolver, type AppIO } from "../../../../io"; +import { SourceResolver, warn, type AppIO } from "../../../../io"; import type { Core } from "../../../types"; import type { EvaluationReferenceInput } from "@aws-sdk/client-bedrock-agentcore"; import { coreOptsFromCtx, parseJsonArrayFlag } from "../../../utils"; @@ -115,6 +115,7 @@ export const createEvaluateOnDemandHandler = (core: Core, io: AppIO) => const result = await core.eval.evaluate( { traces, evaluatorIds: flags["evaluators"], groundTruth }, opts, + (message) => warn(io, message), ); ctx.require(JsonRendererKey).renderJson(result); }, diff --git a/src/handlers/eval/ondemand/ondemand.test.tsx b/src/handlers/eval/ondemand/ondemand.test.tsx index 56699cb9c..11f82093e 100644 --- a/src/handlers/eval/ondemand/ondemand.test.tsx +++ b/src/handlers/eval/ondemand/ondemand.test.tsx @@ -54,8 +54,12 @@ type QueryFailureStatus = "Failed" | "Cancelled" | "Timeout"; type LogsOptions = { malformedRows?: ResultField[][]; + rows?: ResultField[][]; missingRuntimeLogGroup?: boolean; status?: QueryFailureStatus; + evaluatorLevel?: "SESSION" | "TRACE" | "TOOL_CALL"; + groundTruth?: string; + onEvaluate?: () => void; }; async function run(args: string[], configure?: (core: TestCoreClient) => void) { @@ -86,15 +90,20 @@ async function runWithRealCore(options: LogsOptions, logger = createSilentLogger return { agentRuntimeId: RUNTIME_ID, agentRuntimeName: "agent-1" }; } if (command instanceof GetEvaluatorCommand) { - return { evaluatorId: "Builtin.Helpfulness", level: "SESSION" }; + return { evaluatorId: "Builtin.Helpfulness", level: options.evaluatorLevel ?? "SESSION" }; } throw new Error(`unexpected control command: ${(command as object).constructor.name}`); }, } as unknown as BedrockAgentCoreControlClient; + let evaluateCalls = 0; const data = { send: async (command: unknown) => { - if (command instanceof EvaluateCommand) return { evaluationResults: [] }; + if (command instanceof EvaluateCommand) { + evaluateCalls++; + options.onEvaluate?.(); + return { evaluationResults: [] }; + } throw new Error(`unexpected data command: ${(command as object).constructor.name}`); }, } as unknown as BedrockAgentCoreClient; @@ -114,7 +123,10 @@ async function runWithRealCore(options: LogsOptions, logger = createSilentLogger if (command instanceof GetQueryResultsCommand) { return { status: options.status ?? "Complete", - results: command.input.queryId === "runtime-query" ? (options.malformedRows ?? []) : [], + results: + command.input.queryId === "runtime-query" + ? (options.rows ?? options.malformedRows ?? []) + : [], }; } throw new Error(`unexpected logs command: ${(command as object).constructor.name}`); @@ -152,9 +164,11 @@ async function runWithRealCore(options: LogsOptions, logger = createSilentLogger "Builtin.Helpfulness", "--session-ids", "session-1", + ...(options.groundTruth !== undefined ? ["--ground-truth", options.groundTruth] : []), "--region", "us-west-2", ]); + return { stdout: io.stdout(), stderr: io.stderr(), evaluateCalls }; } function telemetryRow(sessionId: string, message: string): ResultField[] { @@ -445,4 +459,79 @@ describe("eval ondemand evaluate telemetry failures", () => { expect(warnings).toEqual(["skipping malformed telemetry records"]); }); + + test("warns on stderr when ground truth references an unused session and keeps stdout valid JSON", async () => { + const rows = [ + telemetryRow( + "session-1", + JSON.stringify({ kind: "SERVER", traceId: "trace-1", spanId: "span-1" }), + ), + ]; + const groundTruth = JSON.stringify([ + { + context: { spanContext: { sessionId: "other-session" } }, + expectedResponse: { text: "ok" }, + }, + ]); + + const { stdout, stderr, evaluateCalls } = await runWithRealCore({ rows, groundTruth }); + + expect(stderr).toContain("warning:"); + expect(stderr).toContain("other-session"); + expect(JSON.parse(stdout)).toEqual({ + sessionsRequested: 1, + sessionsEvaluated: 0, + results: [], + }); + expect(evaluateCalls).toBe(1); + }); + + test("warns on stderr and makes no Evaluate call when a session has no tool-call spans for TOOL_CALL", async () => { + const rows = [ + telemetryRow( + "session-1", + JSON.stringify({ kind: "SERVER", traceId: "trace-1", spanId: "span-1" }), + ), + ]; + const groundTruth = JSON.stringify([ + { context: { spanContext: { sessionId: "session-1" } }, expectedResponse: { text: "ok" } }, + ]); + + const { stdout, stderr, evaluateCalls } = await runWithRealCore({ + evaluatorLevel: "TOOL_CALL", + rows, + groundTruth, + }); + + expect(stderr).toContain("warning:"); + expect(stderr).toContain("session-1"); + expect(JSON.parse(stdout)).toEqual({ + sessionsRequested: 1, + sessionsEvaluated: 0, + results: [], + }); + expect(evaluateCalls).toBe(0); + }); + + test("rejects on-demand --ground-truth '[null]' naming --ground-truth and entry 0", async () => { + let evaluateCalls = 0; + const rows = [ + telemetryRow( + "session-1", + JSON.stringify({ kind: "SERVER", traceId: "trace-1", spanId: "span-1" }), + ), + ]; + + const error = await runWithRealCore({ + rows, + groundTruth: "[null]", + onEvaluate: () => { + evaluateCalls++; + }, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(InputValidationError); + expect((error as Error).message).toMatch(/--ground-truth.*entry 0/); + expect(evaluateCalls).toBe(0); + }); }); diff --git a/src/handlers/eval/ondemand/simulate/index.tsx b/src/handlers/eval/ondemand/simulate/index.tsx index 854ce3a63..823ea0f02 100644 --- a/src/handlers/eval/ondemand/simulate/index.tsx +++ b/src/handlers/eval/ondemand/simulate/index.tsx @@ -3,7 +3,7 @@ import type { EvaluationReferenceInput } from "@aws-sdk/client-bedrock-agentcore import { createHandler, flag } from "../../../../router"; import { InputValidationError } from "../../../../errors"; import { JsonRendererKey } from "../../../../tui"; -import type { AppIO } from "../../../../io"; +import { warn, type AppIO } from "../../../../io"; import type { Core } from "../../../types"; import type { InvokedSession } from "../../types"; import { coreOptsFromCtx } from "../../../utils"; @@ -25,7 +25,7 @@ Example: --payload-template '{"messages":[{"role":"user","content":"{input}"}],"stream":false}'`; -export const createSimulateOnDemandHandler = (core: Core, _io: AppIO) => +export const createSimulateOnDemandHandler = (core: Core, io: AppIO) => createHandler({ name: "simulate", description: "replay a dataset against a Runtime, then evaluate the sessions client-side", @@ -114,7 +114,11 @@ export const createSimulateOnDemandHandler = (core: Core, _io: AppIO) => const groundTruth = replay.sessions.flatMap((s) => toReferenceInputs(s, traceIdsBySession.get(s.sessionId) ?? []), ); - const result = await core.eval.evaluate({ traces, evaluatorIds, groundTruth }, opts); + const result = await core.eval.evaluate( + { traces, evaluatorIds, groundTruth }, + opts, + (message) => warn(io, message), + ); ctx.require(JsonRendererKey).renderJson({ ...result, diff --git a/src/handlers/eval/types.tsx b/src/handlers/eval/types.tsx index 48f3ab598..0464062ee 100644 --- a/src/handlers/eval/types.tsx +++ b/src/handlers/eval/types.tsx @@ -490,7 +490,11 @@ export interface CoreEvalClient { // evaluate runs evaluators synchronously over already-gathered traces via the // Evaluate API and returns per-session scores. No job, no CloudWatch — the // trace read happened in getTracesForAgent. - evaluate(input: EvaluateInput, options: CoreOptions): Promise; + evaluate( + input: EvaluateInput, + options: CoreOptions, + onWarning?: (message: string) => void, + ): Promise; // invokeDataset replays a dataset against the runtime (invoke per example, client-side, // one session each) and returns the created sessions + neutral ground truth. Grader- // agnostic: the handler composes it with startBatchEvaluation (or, later, evaluate). diff --git a/src/testing/TestCoreClient.tsx b/src/testing/TestCoreClient.tsx index 998921427..316ca5f5b 100644 --- a/src/testing/TestCoreClient.tsx +++ b/src/testing/TestCoreClient.tsx @@ -2294,7 +2294,11 @@ export class TestEvalClient implements CoreEvalClient { return this.getTracesResponse; } - async evaluate(input: EvaluateInput, options: CoreOptions): Promise { + async evaluate( + input: EvaluateInput, + options: CoreOptions, + _onWarning?: (message: string) => void, + ): Promise { this.calls.push({ method: "evaluate", args: [input, options] }); if (this.error) throw this.error; return this.evaluateResponse;