feat(eval): batch-evaluation simulate — each example owns its invoker - #2032

Merged
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr
Aug 24, 2026
Merged

feat(eval): batch-evaluation simulate — each example owns its invoker#2032
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr

Conversation

@jariy17

@jariy17jariy17 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

What

Adds batch-evaluation simulate to replay a dataset against a runtime and grade the resulting sessions.

Each dataset example is a self-running object that owns its own invoker (RunContext). invokeDataset builds one invoker per session and passes it into the example's run(). The example performs the invocation; the machine supplies the invoker and collects the result.

The invoker seam

A dataset example knows what to send and how to turn the responses into ground truth, but not how to reach the runtime. Its RunContext owns that runtime-specific invocation:

// src/core/eval/invokeDataset/example/types.tsexporttypeTurnResult={text: string};exporttypeRunContext={invokeOnce(input: string): Promise<TurnResult>};exportinterfaceExample{readonlyexampleId: string;readonlyschemaType: DatasetSchemaType;// Replay this example against the runtime `ctx` reaches, return neutral ground truth.run(ctx: RunContext): Promise<InlineGroundTruth|undefined>;}

invokeDataset resolves the runtime once, then builds a distinct invoker for each client-generated session and passes it to that example:

constresults=awaitrunExamples(examples,async(example)=>{constctx: RunContext={invokeOnce: async(input)=>{constres=awaitinvokeRuntime(deps,{/* resolved runtime, session, and rendered payload */},options,signal,);return{text: /* drained response body */};},};returnexample.run(ctx);});

The example decides how many times to call invokeOnce and in what order. Its invoker decides how each call reaches the runtime for that session.

Layout

src/core/eval/invokeDataset/
├── load.ts DatasetLoader — pure JSONL parse → shape-classify → new
├── run.ts runExamples — bounded-concurrency pool, failure isolation
├── invokeDataset.test.ts end-to-end golden coverage of the whole path
└── example/
├── types.ts Example interface, RunContext (the invoker), TurnResult
├── predefined.ts PredefinedExample — replays scripted turns, builds ground truth
└── simulated.ts SimulatedExample — not shipped; throws at construction

Plus src/core/invokeRuntime.ts, which extracts runtime invocation from runtime.tsx for reuse by both RuntimeClient and invokeDataset, and src/handlers/eval/batch-evaluation/simulate/index.tsx, which composes invokeDataset with startBatchEvaluation.

Testing

  • bun run typecheck passes.
  • bun test: 1544 pass, 0 fail.
  • invokeDataset.test.ts drives the real EvalClient.invokeDataset over a fake AWS layer with golden fixtures. Its snapshot covers created sessions and inline ground truth across every supported variation while exercising the loader, example classes, concurrency pool, template rendering, and runtime invocation.
  • simulate.test.tsx snapshots the handler's wrapped sessionMetadata.

@codecov-commenter

codecov-commenter commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.58444% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.33%. Comparing base (768ef10) to head (27c810f).

Files with missing linesPatch %Lines
src/core/eval.tsx85.71%14 Missing ⚠️
src/core/eval/invokeDataset/template.ts91.30%2 Missing ⚠️
src/core/eval/invokeDataset/example/simulated.ts92.30%1 Missing ⚠️
src/core/invokeRuntime.ts99.35%1 Missing ⚠️
Additional details and impacted files
@@ Coverage Diff @@## refactor #2032 +/- ##
============================================
- Coverage 97.36% 97.33% -0.04% 
============================================
Files 410 417 +7 Lines 24796 25181 +385 ============================================
+ Hits 24142 24509 +367 - Misses 654 672 +18 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actionsgithub-actionsBot removed the agentcore-harness-reviewing AgentCore Harness review in progress label Aug 18, 2026
@jariy17
jariy17force-pushed the feat/eval-invoke-dataset-pr branch 6 times, most recently from 6a2915e to b747257CompareAugust 19, 2026 18:45

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't get to all the examples work yet, but had a few small comments and a question on how we can simplify testing, because it feels pretty gnarly rn.

Comment threadsrc/io/template.ts Outdated
@@ -0,0 +1,33 @@
import { InputValidationError } from "../errors";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we keep this inside evals until there is an opportunity to re-use it? I feel like the io directory should be reserved for shared abstractions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking the invoke handler could use this but lets leave it in the simulate handler for now.

Comment threadsrc/io/template.ts Outdated
try {
parsed = JSON.parse(template);
} catch {
throw new InputValidationError(`--${flagName} must be valid JSON`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

qualifier?: string;
payloadTemplate: string; // e.g. {"prompt":"{input}"} — {input} is the example's turn input
headers?: [string, string][];
bearerToken?: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: is there a reason bearerToken is treated different from other headers?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the discriminator that selects the auth path, not an application header. Its presence routes the invoke to CUSTOM_JWT path (src/core/invokeRuntime.ts:73)

flag("dataset-version", "dataset version (with a dataset id)", z.string().optional()),
flag("evaluator", "evaluator id(s) to apply", z.array(z.string()).optional()),
flag("name", "batch evaluation name (unique in the account)", z.string().optional()),
flag("description", "optional description", z.string().optional()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what exactly is this describing? the simulation itself?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be batch-evaluation description. I'll rename this batch-eval-desc, same with name too.

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahhh, theres a shared abstraction for this, but looks like it hasn't been merged yet :(

#1986

maybe we can swap it over as a follow-up once its merged.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment threadsrc/core/eval.tsx Outdated
const groundTruth = await example.run(ctx);
return { exampleId: example.exampleId, sessionId, groundTruth };
} catch (error) {
this.logger.debug(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of logging and rethrowing, is there a way to enrich the error thrown to avoid noise?

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there anything we can poll on instead of a static wait time?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't poll right away because some traces might still be arriving, and I didn't want us to end up with incomplete session data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?


// A fake AWS layer: control resolves the runtime, data answers each invoke. Records every
// payload it was asked to send, and per `opts` can fail or delay specific invokes.
function fakeClients(opts: { fail?: (payload: string) => boolean; delayMs?: number } = {}): {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like a really complex testing setup. Is there a simpler way? I'm wondering if there's a structural change we could make to simplify here.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I fixed these tests as a follow up?

Comment threadsrc/core/eval/invokeDataset/load.ts Outdated
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import type { DatasetSchemaType } from "@aws-sdk/client-bedrock-agentcore-control";
import type { InlineGroundTruth } from "@aws-sdk/client-bedrock-agentcore";

// A record, not a bare string, so a future tool-branching type can widen it by a field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like the code explains this comment.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only blocking question is why we do an explicit wait, rest could be polished later/in a follow-up. Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

import { coreOptsFromCtx } from "../../../utils";
import { parseRuntimeInvokeHeaders } from "../../../runtime/invoke/request";

// Composes invokeDataset (replay) → startBatchEvaluation (grade). Invoke flags mirror

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the comment describing the implementation of the handler? What value does it provide over the code?

Comment threadsrc/core/eval.tsx
// Enrich with the example identity so the dropped-invoke reason is self-describing
// in firstError, instead of a bare transport message logged separately.
const cause = error instanceof Error ? error : new Error(String(error));
throw new Error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to confirm my understanding, this error never hits telemetry because an individual example failing does not bubble up so this error is purely for the user message it creates?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. An individual example failing is caught and dropped by runExamples rather than rethrown, so it never reaches telemetry — it only feeds the user-facing message on a total failure. That was intentional: a run can be hundreds of examples, and I didn't want per-example failures flooding our telemetry.

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?

try {
headers.set("Authorization", `Bearer ${bearerToken}`);
} catch {
throw new InputValidationError("Invalid bearer token");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause up to these errors to get the stack trace? (same with 132, 155 below)

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

logger
.child({
errorName:
error instanceof TypeError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason error instanceof error ? error.name : 'error' doesn't work here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this in the next PR.

};

// InvokeDatasetResult reports the created sessions plus how many examples were invoked
// vs dropped (a failed invoke is skipped, not fatal). firstError explains a total failure.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does firstError explain a total failure? I thought it stored the first failed example's error?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WE will remove it later. Yes lets do a follow up on this.

@@ -0,0 +1,263 @@
// Disables the post-invoke span-ingestion wait so the replay returns immediately.
process.env.SIMULATE_INGESTION_WAIT_MS = "0";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would this be a good application of global config? this might help this behavior be more discoverable by other tests that might need the same.

@jariy17jariy17Aug 24, 2026

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So add to the bunfig.toml to preload a script that run this:
./global-mocks.ts

// Global mocksimport{mock}from"bun:test";// Mock environment variablesprocess.env.SIMULATE_INGESTION_WAIT_MS="0";

bunfig.toml

[test]preload=["./global-mocks.ts"]

ref

Yes I could do that in the follow up Pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to inject the global config down through core with the data we want.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah that make sense

return this.groundTruth();
}

// Emit every turn (carrying its prompt), not just those with an expectation: filtering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not quite sure what this comment is saying?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ill remove it.

@Hweinstock

Copy link
Copy Markdown
Contributor

Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

from chatting offline, sounds like the wait approach is shared by the eval time. Still unsure how they can be confident the evaluator results are not incomplete, but approving since its an existing solution.

Hweinstock
Hweinstock previously approved these changes Aug 24, 2026
jariy17 added 3 commits August 24, 2026 21:29
- move renderJsonTemplate out of shared src/io into core/eval/invokeDataset
- invokeRuntime: raw TypeError/Error -> InputValidationError/RuntimeInvokeResponseError
- wire error causes in template + dataset JSON parse
- invokeDataset: enrich per-example invoke failure instead of log+rethrow
- simulate: bubble Ctrl-C cancellation (telemetry) instead of quiet return; clarify --description help; TODO(#1986) shared abort helper
- drop type-guaranteed 'no leak' test; keep AbortSignal wiring in composition test
- trim stale/redundant comments (runtime.tsx, invokeRuntime DTO note, TurnResult)
…in payload-template
Bug bash (real exploratory-account run) surfaced two defects in the shared invokeDataset path:
1. PredefinedExample blind-cast assertions/expected_trajectory as string[] with no load-time
validation (unlike turns). A non-array value passed load, burned a live paid invoke, then
threw a raw '.map is not a function' mislabeled 'failed to invoke'. Now validated in the
constructor -> clean InputValidationError before any invoke.
2. A --payload-template with no {input} placeholder was silently accepted, wasting a full
~3-min replay on a constant payload. Now rejected up front in invokeDataset.
Comment threadsrc/core/eval.tsx
const sessionId = randomUUID();
const ctx: RunContext = {
invokeOnce: async (payload) => {
const response = await invokeRuntime(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comparing this to src/handlers/runtime/invoke/request.ts, and I notice that the code calls normalizeRuntimeInvokeRequest to do some validation before invoking. Do you think we need something similar here?

@nborges-awsnborges-aws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. One comment with a question for you

@jariy17
jariy17 merged commit 83dab8f into refactorAug 24, 2026
13 checks passed
@jariy17
jariy17 deleted the feat/eval-invoke-dataset-pr branch August 24, 2026 22:48
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jariy17@codecov-commenter@Hweinstock@nborges-aws
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

feat(eval): batch-evaluation simulate — each example owns its invoker - #2032

Merged
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr
Aug 24, 2026
Merged

feat(eval): batch-evaluation simulate — each example owns its invoker#2032
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr

Conversation

@jariy17

@jariy17jariy17 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

What

Adds batch-evaluation simulate to replay a dataset against a runtime and grade the resulting sessions.

Each dataset example is a self-running object that owns its own invoker (RunContext). invokeDataset builds one invoker per session and passes it into the example's run(). The example performs the invocation; the machine supplies the invoker and collects the result.

The invoker seam

A dataset example knows what to send and how to turn the responses into ground truth, but not how to reach the runtime. Its RunContext owns that runtime-specific invocation:

// src/core/eval/invokeDataset/example/types.tsexporttypeTurnResult={text: string};exporttypeRunContext={invokeOnce(input: string): Promise<TurnResult>};exportinterfaceExample{readonlyexampleId: string;readonlyschemaType: DatasetSchemaType;// Replay this example against the runtime `ctx` reaches, return neutral ground truth.run(ctx: RunContext): Promise<InlineGroundTruth|undefined>;}

invokeDataset resolves the runtime once, then builds a distinct invoker for each client-generated session and passes it to that example:

constresults=awaitrunExamples(examples,async(example)=>{constctx: RunContext={invokeOnce: async(input)=>{constres=awaitinvokeRuntime(deps,{/* resolved runtime, session, and rendered payload */},options,signal,);return{text: /* drained response body */};},};returnexample.run(ctx);});

The example decides how many times to call invokeOnce and in what order. Its invoker decides how each call reaches the runtime for that session.

Layout

src/core/eval/invokeDataset/
├── load.ts DatasetLoader — pure JSONL parse → shape-classify → new
├── run.ts runExamples — bounded-concurrency pool, failure isolation
├── invokeDataset.test.ts end-to-end golden coverage of the whole path
└── example/
├── types.ts Example interface, RunContext (the invoker), TurnResult
├── predefined.ts PredefinedExample — replays scripted turns, builds ground truth
└── simulated.ts SimulatedExample — not shipped; throws at construction

Plus src/core/invokeRuntime.ts, which extracts runtime invocation from runtime.tsx for reuse by both RuntimeClient and invokeDataset, and src/handlers/eval/batch-evaluation/simulate/index.tsx, which composes invokeDataset with startBatchEvaluation.

Testing

  • bun run typecheck passes.
  • bun test: 1544 pass, 0 fail.
  • invokeDataset.test.ts drives the real EvalClient.invokeDataset over a fake AWS layer with golden fixtures. Its snapshot covers created sessions and inline ground truth across every supported variation while exercising the loader, example classes, concurrency pool, template rendering, and runtime invocation.
  • simulate.test.tsx snapshots the handler's wrapped sessionMetadata.

@codecov-commenter

codecov-commenter commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.58444% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.33%. Comparing base (768ef10) to head (27c810f).

Files with missing linesPatch %Lines
src/core/eval.tsx85.71%14 Missing ⚠️
src/core/eval/invokeDataset/template.ts91.30%2 Missing ⚠️
src/core/eval/invokeDataset/example/simulated.ts92.30%1 Missing ⚠️
src/core/invokeRuntime.ts99.35%1 Missing ⚠️
Additional details and impacted files
@@ Coverage Diff @@## refactor #2032 +/- ##
============================================
- Coverage 97.36% 97.33% -0.04% 
============================================
Files 410 417 +7 Lines 24796 25181 +385 ============================================
+ Hits 24142 24509 +367 - Misses 654 672 +18 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actionsgithub-actionsBot removed the agentcore-harness-reviewing AgentCore Harness review in progress label Aug 18, 2026
@jariy17
jariy17force-pushed the feat/eval-invoke-dataset-pr branch 6 times, most recently from 6a2915e to b747257CompareAugust 19, 2026 18:45

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't get to all the examples work yet, but had a few small comments and a question on how we can simplify testing, because it feels pretty gnarly rn.

Comment threadsrc/io/template.ts Outdated
@@ -0,0 +1,33 @@
import { InputValidationError } from "../errors";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we keep this inside evals until there is an opportunity to re-use it? I feel like the io directory should be reserved for shared abstractions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking the invoke handler could use this but lets leave it in the simulate handler for now.

Comment threadsrc/io/template.ts Outdated
try {
parsed = JSON.parse(template);
} catch {
throw new InputValidationError(`--${flagName} must be valid JSON`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

qualifier?: string;
payloadTemplate: string; // e.g. {"prompt":"{input}"} — {input} is the example's turn input
headers?: [string, string][];
bearerToken?: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: is there a reason bearerToken is treated different from other headers?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the discriminator that selects the auth path, not an application header. Its presence routes the invoke to CUSTOM_JWT path (src/core/invokeRuntime.ts:73)

flag("dataset-version", "dataset version (with a dataset id)", z.string().optional()),
flag("evaluator", "evaluator id(s) to apply", z.array(z.string()).optional()),
flag("name", "batch evaluation name (unique in the account)", z.string().optional()),
flag("description", "optional description", z.string().optional()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what exactly is this describing? the simulation itself?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be batch-evaluation description. I'll rename this batch-eval-desc, same with name too.

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahhh, theres a shared abstraction for this, but looks like it hasn't been merged yet :(

#1986

maybe we can swap it over as a follow-up once its merged.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment threadsrc/core/eval.tsx Outdated
const groundTruth = await example.run(ctx);
return { exampleId: example.exampleId, sessionId, groundTruth };
} catch (error) {
this.logger.debug(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of logging and rethrowing, is there a way to enrich the error thrown to avoid noise?

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there anything we can poll on instead of a static wait time?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't poll right away because some traces might still be arriving, and I didn't want us to end up with incomplete session data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?


// A fake AWS layer: control resolves the runtime, data answers each invoke. Records every
// payload it was asked to send, and per `opts` can fail or delay specific invokes.
function fakeClients(opts: { fail?: (payload: string) => boolean; delayMs?: number } = {}): {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like a really complex testing setup. Is there a simpler way? I'm wondering if there's a structural change we could make to simplify here.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I fixed these tests as a follow up?

Comment threadsrc/core/eval/invokeDataset/load.ts Outdated
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import type { DatasetSchemaType } from "@aws-sdk/client-bedrock-agentcore-control";
import type { InlineGroundTruth } from "@aws-sdk/client-bedrock-agentcore";

// A record, not a bare string, so a future tool-branching type can widen it by a field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like the code explains this comment.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only blocking question is why we do an explicit wait, rest could be polished later/in a follow-up. Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

import { coreOptsFromCtx } from "../../../utils";
import { parseRuntimeInvokeHeaders } from "../../../runtime/invoke/request";

// Composes invokeDataset (replay) → startBatchEvaluation (grade). Invoke flags mirror

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the comment describing the implementation of the handler? What value does it provide over the code?

Comment threadsrc/core/eval.tsx
// Enrich with the example identity so the dropped-invoke reason is self-describing
// in firstError, instead of a bare transport message logged separately.
const cause = error instanceof Error ? error : new Error(String(error));
throw new Error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to confirm my understanding, this error never hits telemetry because an individual example failing does not bubble up so this error is purely for the user message it creates?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. An individual example failing is caught and dropped by runExamples rather than rethrown, so it never reaches telemetry — it only feeds the user-facing message on a total failure. That was intentional: a run can be hundreds of examples, and I didn't want per-example failures flooding our telemetry.

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?

try {
headers.set("Authorization", `Bearer ${bearerToken}`);
} catch {
throw new InputValidationError("Invalid bearer token");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause up to these errors to get the stack trace? (same with 132, 155 below)

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

logger
.child({
errorName:
error instanceof TypeError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason error instanceof error ? error.name : 'error' doesn't work here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this in the next PR.

};

// InvokeDatasetResult reports the created sessions plus how many examples were invoked
// vs dropped (a failed invoke is skipped, not fatal). firstError explains a total failure.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does firstError explain a total failure? I thought it stored the first failed example's error?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WE will remove it later. Yes lets do a follow up on this.

@@ -0,0 +1,263 @@
// Disables the post-invoke span-ingestion wait so the replay returns immediately.
process.env.SIMULATE_INGESTION_WAIT_MS = "0";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would this be a good application of global config? this might help this behavior be more discoverable by other tests that might need the same.

@jariy17jariy17Aug 24, 2026

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So add to the bunfig.toml to preload a script that run this:
./global-mocks.ts

// Global mocksimport{mock}from"bun:test";// Mock environment variablesprocess.env.SIMULATE_INGESTION_WAIT_MS="0";

bunfig.toml

[test]preload=["./global-mocks.ts"]

ref

Yes I could do that in the follow up Pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to inject the global config down through core with the data we want.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah that make sense

return this.groundTruth();
}

// Emit every turn (carrying its prompt), not just those with an expectation: filtering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not quite sure what this comment is saying?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ill remove it.

@Hweinstock

Copy link
Copy Markdown
Contributor

Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

from chatting offline, sounds like the wait approach is shared by the eval time. Still unsure how they can be confident the evaluator results are not incomplete, but approving since its an existing solution.

Hweinstock
Hweinstock previously approved these changes Aug 24, 2026
jariy17 added 3 commits August 24, 2026 21:29
- move renderJsonTemplate out of shared src/io into core/eval/invokeDataset
- invokeRuntime: raw TypeError/Error -> InputValidationError/RuntimeInvokeResponseError
- wire error causes in template + dataset JSON parse
- invokeDataset: enrich per-example invoke failure instead of log+rethrow
- simulate: bubble Ctrl-C cancellation (telemetry) instead of quiet return; clarify --description help; TODO(#1986) shared abort helper
- drop type-guaranteed 'no leak' test; keep AbortSignal wiring in composition test
- trim stale/redundant comments (runtime.tsx, invokeRuntime DTO note, TurnResult)
…in payload-template
Bug bash (real exploratory-account run) surfaced two defects in the shared invokeDataset path:
1. PredefinedExample blind-cast assertions/expected_trajectory as string[] with no load-time
validation (unlike turns). A non-array value passed load, burned a live paid invoke, then
threw a raw '.map is not a function' mislabeled 'failed to invoke'. Now validated in the
constructor -> clean InputValidationError before any invoke.
2. A --payload-template with no {input} placeholder was silently accepted, wasting a full
~3-min replay on a constant payload. Now rejected up front in invokeDataset.
Comment threadsrc/core/eval.tsx
const sessionId = randomUUID();
const ctx: RunContext = {
invokeOnce: async (payload) => {
const response = await invokeRuntime(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comparing this to src/handlers/runtime/invoke/request.ts, and I notice that the code calls normalizeRuntimeInvokeRequest to do some validation before invoking. Do you think we need something similar here?

@nborges-awsnborges-aws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. One comment with a question for you

@jariy17
jariy17 merged commit 83dab8f into refactorAug 24, 2026
13 checks passed
@jariy17
jariy17 deleted the feat/eval-invoke-dataset-pr branch August 24, 2026 22:48
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jariy17@codecov-commenter@Hweinstock@nborges-aws
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(eval): batch-evaluation simulate — each example owns its invoker - #2032

Merged
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr
Aug 24, 2026
Merged

feat(eval): batch-evaluation simulate — each example owns its invoker#2032
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr

Conversation

@jariy17

@jariy17jariy17 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

What

Adds batch-evaluation simulate to replay a dataset against a runtime and grade the resulting sessions.

Each dataset example is a self-running object that owns its own invoker (RunContext). invokeDataset builds one invoker per session and passes it into the example's run(). The example performs the invocation; the machine supplies the invoker and collects the result.

The invoker seam

A dataset example knows what to send and how to turn the responses into ground truth, but not how to reach the runtime. Its RunContext owns that runtime-specific invocation:

// src/core/eval/invokeDataset/example/types.tsexporttypeTurnResult={text: string};exporttypeRunContext={invokeOnce(input: string): Promise<TurnResult>};exportinterfaceExample{readonlyexampleId: string;readonlyschemaType: DatasetSchemaType;// Replay this example against the runtime `ctx` reaches, return neutral ground truth.run(ctx: RunContext): Promise<InlineGroundTruth|undefined>;}

invokeDataset resolves the runtime once, then builds a distinct invoker for each client-generated session and passes it to that example:

constresults=awaitrunExamples(examples,async(example)=>{constctx: RunContext={invokeOnce: async(input)=>{constres=awaitinvokeRuntime(deps,{/* resolved runtime, session, and rendered payload */},options,signal,);return{text: /* drained response body */};},};returnexample.run(ctx);});

The example decides how many times to call invokeOnce and in what order. Its invoker decides how each call reaches the runtime for that session.

Layout

src/core/eval/invokeDataset/
├── load.ts DatasetLoader — pure JSONL parse → shape-classify → new
├── run.ts runExamples — bounded-concurrency pool, failure isolation
├── invokeDataset.test.ts end-to-end golden coverage of the whole path
└── example/
├── types.ts Example interface, RunContext (the invoker), TurnResult
├── predefined.ts PredefinedExample — replays scripted turns, builds ground truth
└── simulated.ts SimulatedExample — not shipped; throws at construction

Plus src/core/invokeRuntime.ts, which extracts runtime invocation from runtime.tsx for reuse by both RuntimeClient and invokeDataset, and src/handlers/eval/batch-evaluation/simulate/index.tsx, which composes invokeDataset with startBatchEvaluation.

Testing

  • bun run typecheck passes.
  • bun test: 1544 pass, 0 fail.
  • invokeDataset.test.ts drives the real EvalClient.invokeDataset over a fake AWS layer with golden fixtures. Its snapshot covers created sessions and inline ground truth across every supported variation while exercising the loader, example classes, concurrency pool, template rendering, and runtime invocation.
  • simulate.test.tsx snapshots the handler's wrapped sessionMetadata.

@codecov-commenter

codecov-commenter commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.58444% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.33%. Comparing base (768ef10) to head (27c810f).

Files with missing linesPatch %Lines
src/core/eval.tsx85.71%14 Missing ⚠️
src/core/eval/invokeDataset/template.ts91.30%2 Missing ⚠️
src/core/eval/invokeDataset/example/simulated.ts92.30%1 Missing ⚠️
src/core/invokeRuntime.ts99.35%1 Missing ⚠️
Additional details and impacted files
@@ Coverage Diff @@## refactor #2032 +/- ##
============================================
- Coverage 97.36% 97.33% -0.04% 
============================================
Files 410 417 +7 Lines 24796 25181 +385 ============================================
+ Hits 24142 24509 +367 - Misses 654 672 +18 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actionsgithub-actionsBot removed the agentcore-harness-reviewing AgentCore Harness review in progress label Aug 18, 2026
@jariy17
jariy17force-pushed the feat/eval-invoke-dataset-pr branch 6 times, most recently from 6a2915e to b747257CompareAugust 19, 2026 18:45

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't get to all the examples work yet, but had a few small comments and a question on how we can simplify testing, because it feels pretty gnarly rn.

Comment threadsrc/io/template.ts Outdated
@@ -0,0 +1,33 @@
import { InputValidationError } from "../errors";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we keep this inside evals until there is an opportunity to re-use it? I feel like the io directory should be reserved for shared abstractions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking the invoke handler could use this but lets leave it in the simulate handler for now.

Comment threadsrc/io/template.ts Outdated
try {
parsed = JSON.parse(template);
} catch {
throw new InputValidationError(`--${flagName} must be valid JSON`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

qualifier?: string;
payloadTemplate: string; // e.g. {"prompt":"{input}"} — {input} is the example's turn input
headers?: [string, string][];
bearerToken?: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: is there a reason bearerToken is treated different from other headers?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the discriminator that selects the auth path, not an application header. Its presence routes the invoke to CUSTOM_JWT path (src/core/invokeRuntime.ts:73)

flag("dataset-version", "dataset version (with a dataset id)", z.string().optional()),
flag("evaluator", "evaluator id(s) to apply", z.array(z.string()).optional()),
flag("name", "batch evaluation name (unique in the account)", z.string().optional()),
flag("description", "optional description", z.string().optional()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what exactly is this describing? the simulation itself?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be batch-evaluation description. I'll rename this batch-eval-desc, same with name too.

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahhh, theres a shared abstraction for this, but looks like it hasn't been merged yet :(

#1986

maybe we can swap it over as a follow-up once its merged.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment threadsrc/core/eval.tsx Outdated
const groundTruth = await example.run(ctx);
return { exampleId: example.exampleId, sessionId, groundTruth };
} catch (error) {
this.logger.debug(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of logging and rethrowing, is there a way to enrich the error thrown to avoid noise?

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there anything we can poll on instead of a static wait time?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't poll right away because some traces might still be arriving, and I didn't want us to end up with incomplete session data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?


// A fake AWS layer: control resolves the runtime, data answers each invoke. Records every
// payload it was asked to send, and per `opts` can fail or delay specific invokes.
function fakeClients(opts: { fail?: (payload: string) => boolean; delayMs?: number } = {}): {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like a really complex testing setup. Is there a simpler way? I'm wondering if there's a structural change we could make to simplify here.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I fixed these tests as a follow up?

Comment threadsrc/core/eval/invokeDataset/load.ts Outdated
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import type { DatasetSchemaType } from "@aws-sdk/client-bedrock-agentcore-control";
import type { InlineGroundTruth } from "@aws-sdk/client-bedrock-agentcore";

// A record, not a bare string, so a future tool-branching type can widen it by a field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like the code explains this comment.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only blocking question is why we do an explicit wait, rest could be polished later/in a follow-up. Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

import { coreOptsFromCtx } from "../../../utils";
import { parseRuntimeInvokeHeaders } from "../../../runtime/invoke/request";

// Composes invokeDataset (replay) → startBatchEvaluation (grade). Invoke flags mirror

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the comment describing the implementation of the handler? What value does it provide over the code?

Comment threadsrc/core/eval.tsx
// Enrich with the example identity so the dropped-invoke reason is self-describing
// in firstError, instead of a bare transport message logged separately.
const cause = error instanceof Error ? error : new Error(String(error));
throw new Error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to confirm my understanding, this error never hits telemetry because an individual example failing does not bubble up so this error is purely for the user message it creates?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. An individual example failing is caught and dropped by runExamples rather than rethrown, so it never reaches telemetry — it only feeds the user-facing message on a total failure. That was intentional: a run can be hundreds of examples, and I didn't want per-example failures flooding our telemetry.

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?

try {
headers.set("Authorization", `Bearer ${bearerToken}`);
} catch {
throw new InputValidationError("Invalid bearer token");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause up to these errors to get the stack trace? (same with 132, 155 below)

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

logger
.child({
errorName:
error instanceof TypeError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason error instanceof error ? error.name : 'error' doesn't work here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this in the next PR.

};

// InvokeDatasetResult reports the created sessions plus how many examples were invoked
// vs dropped (a failed invoke is skipped, not fatal). firstError explains a total failure.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does firstError explain a total failure? I thought it stored the first failed example's error?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WE will remove it later. Yes lets do a follow up on this.

@@ -0,0 +1,263 @@
// Disables the post-invoke span-ingestion wait so the replay returns immediately.
process.env.SIMULATE_INGESTION_WAIT_MS = "0";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would this be a good application of global config? this might help this behavior be more discoverable by other tests that might need the same.

@jariy17jariy17Aug 24, 2026

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So add to the bunfig.toml to preload a script that run this:
./global-mocks.ts

// Global mocksimport{mock}from"bun:test";// Mock environment variablesprocess.env.SIMULATE_INGESTION_WAIT_MS="0";

bunfig.toml

[test]preload=["./global-mocks.ts"]

ref

Yes I could do that in the follow up Pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to inject the global config down through core with the data we want.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah that make sense

return this.groundTruth();
}

// Emit every turn (carrying its prompt), not just those with an expectation: filtering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not quite sure what this comment is saying?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ill remove it.

@Hweinstock

Copy link
Copy Markdown
Contributor

Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

from chatting offline, sounds like the wait approach is shared by the eval time. Still unsure how they can be confident the evaluator results are not incomplete, but approving since its an existing solution.

Hweinstock
Hweinstock previously approved these changes Aug 24, 2026
jariy17 added 3 commits August 24, 2026 21:29
- move renderJsonTemplate out of shared src/io into core/eval/invokeDataset
- invokeRuntime: raw TypeError/Error -> InputValidationError/RuntimeInvokeResponseError
- wire error causes in template + dataset JSON parse
- invokeDataset: enrich per-example invoke failure instead of log+rethrow
- simulate: bubble Ctrl-C cancellation (telemetry) instead of quiet return; clarify --description help; TODO(#1986) shared abort helper
- drop type-guaranteed 'no leak' test; keep AbortSignal wiring in composition test
- trim stale/redundant comments (runtime.tsx, invokeRuntime DTO note, TurnResult)
…in payload-template
Bug bash (real exploratory-account run) surfaced two defects in the shared invokeDataset path:
1. PredefinedExample blind-cast assertions/expected_trajectory as string[] with no load-time
validation (unlike turns). A non-array value passed load, burned a live paid invoke, then
threw a raw '.map is not a function' mislabeled 'failed to invoke'. Now validated in the
constructor -> clean InputValidationError before any invoke.
2. A --payload-template with no {input} placeholder was silently accepted, wasting a full
~3-min replay on a constant payload. Now rejected up front in invokeDataset.
Comment threadsrc/core/eval.tsx
const sessionId = randomUUID();
const ctx: RunContext = {
invokeOnce: async (payload) => {
const response = await invokeRuntime(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comparing this to src/handlers/runtime/invoke/request.ts, and I notice that the code calls normalizeRuntimeInvokeRequest to do some validation before invoking. Do you think we need something similar here?

@nborges-awsnborges-aws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. One comment with a question for you

@jariy17
jariy17 merged commit 83dab8f into refactorAug 24, 2026
13 checks passed
@jariy17
jariy17 deleted the feat/eval-invoke-dataset-pr branch August 24, 2026 22:48
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jariy17@codecov-commenter@Hweinstock@nborges-aws
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(eval): batch-evaluation simulate — each example owns its invoker - #2032

Merged
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr
Aug 24, 2026
Merged

feat(eval): batch-evaluation simulate — each example owns its invoker#2032
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr

Conversation

@jariy17

@jariy17jariy17 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

What

Adds batch-evaluation simulate to replay a dataset against a runtime and grade the resulting sessions.

Each dataset example is a self-running object that owns its own invoker (RunContext). invokeDataset builds one invoker per session and passes it into the example's run(). The example performs the invocation; the machine supplies the invoker and collects the result.

The invoker seam

A dataset example knows what to send and how to turn the responses into ground truth, but not how to reach the runtime. Its RunContext owns that runtime-specific invocation:

// src/core/eval/invokeDataset/example/types.tsexporttypeTurnResult={text: string};exporttypeRunContext={invokeOnce(input: string): Promise<TurnResult>};exportinterfaceExample{readonlyexampleId: string;readonlyschemaType: DatasetSchemaType;// Replay this example against the runtime `ctx` reaches, return neutral ground truth.run(ctx: RunContext): Promise<InlineGroundTruth|undefined>;}

invokeDataset resolves the runtime once, then builds a distinct invoker for each client-generated session and passes it to that example:

constresults=awaitrunExamples(examples,async(example)=>{constctx: RunContext={invokeOnce: async(input)=>{constres=awaitinvokeRuntime(deps,{/* resolved runtime, session, and rendered payload */},options,signal,);return{text: /* drained response body */};},};returnexample.run(ctx);});

The example decides how many times to call invokeOnce and in what order. Its invoker decides how each call reaches the runtime for that session.

Layout

src/core/eval/invokeDataset/
├── load.ts DatasetLoader — pure JSONL parse → shape-classify → new
├── run.ts runExamples — bounded-concurrency pool, failure isolation
├── invokeDataset.test.ts end-to-end golden coverage of the whole path
└── example/
├── types.ts Example interface, RunContext (the invoker), TurnResult
├── predefined.ts PredefinedExample — replays scripted turns, builds ground truth
└── simulated.ts SimulatedExample — not shipped; throws at construction

Plus src/core/invokeRuntime.ts, which extracts runtime invocation from runtime.tsx for reuse by both RuntimeClient and invokeDataset, and src/handlers/eval/batch-evaluation/simulate/index.tsx, which composes invokeDataset with startBatchEvaluation.

Testing

  • bun run typecheck passes.
  • bun test: 1544 pass, 0 fail.
  • invokeDataset.test.ts drives the real EvalClient.invokeDataset over a fake AWS layer with golden fixtures. Its snapshot covers created sessions and inline ground truth across every supported variation while exercising the loader, example classes, concurrency pool, template rendering, and runtime invocation.
  • simulate.test.tsx snapshots the handler's wrapped sessionMetadata.

@codecov-commenter

codecov-commenter commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.58444% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.33%. Comparing base (768ef10) to head (27c810f).

Files with missing linesPatch %Lines
src/core/eval.tsx85.71%14 Missing ⚠️
src/core/eval/invokeDataset/template.ts91.30%2 Missing ⚠️
src/core/eval/invokeDataset/example/simulated.ts92.30%1 Missing ⚠️
src/core/invokeRuntime.ts99.35%1 Missing ⚠️
Additional details and impacted files
@@ Coverage Diff @@## refactor #2032 +/- ##
============================================
- Coverage 97.36% 97.33% -0.04% 
============================================
Files 410 417 +7 Lines 24796 25181 +385 ============================================
+ Hits 24142 24509 +367 - Misses 654 672 +18 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actionsgithub-actionsBot removed the agentcore-harness-reviewing AgentCore Harness review in progress label Aug 18, 2026
@jariy17
jariy17force-pushed the feat/eval-invoke-dataset-pr branch 6 times, most recently from 6a2915e to b747257CompareAugust 19, 2026 18:45

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't get to all the examples work yet, but had a few small comments and a question on how we can simplify testing, because it feels pretty gnarly rn.

Comment threadsrc/io/template.ts Outdated
@@ -0,0 +1,33 @@
import { InputValidationError } from "../errors";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we keep this inside evals until there is an opportunity to re-use it? I feel like the io directory should be reserved for shared abstractions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking the invoke handler could use this but lets leave it in the simulate handler for now.

Comment threadsrc/io/template.ts Outdated
try {
parsed = JSON.parse(template);
} catch {
throw new InputValidationError(`--${flagName} must be valid JSON`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

qualifier?: string;
payloadTemplate: string; // e.g. {"prompt":"{input}"} — {input} is the example's turn input
headers?: [string, string][];
bearerToken?: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: is there a reason bearerToken is treated different from other headers?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the discriminator that selects the auth path, not an application header. Its presence routes the invoke to CUSTOM_JWT path (src/core/invokeRuntime.ts:73)

flag("dataset-version", "dataset version (with a dataset id)", z.string().optional()),
flag("evaluator", "evaluator id(s) to apply", z.array(z.string()).optional()),
flag("name", "batch evaluation name (unique in the account)", z.string().optional()),
flag("description", "optional description", z.string().optional()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what exactly is this describing? the simulation itself?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be batch-evaluation description. I'll rename this batch-eval-desc, same with name too.

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahhh, theres a shared abstraction for this, but looks like it hasn't been merged yet :(

#1986

maybe we can swap it over as a follow-up once its merged.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment threadsrc/core/eval.tsx Outdated
const groundTruth = await example.run(ctx);
return { exampleId: example.exampleId, sessionId, groundTruth };
} catch (error) {
this.logger.debug(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of logging and rethrowing, is there a way to enrich the error thrown to avoid noise?

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there anything we can poll on instead of a static wait time?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't poll right away because some traces might still be arriving, and I didn't want us to end up with incomplete session data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?


// A fake AWS layer: control resolves the runtime, data answers each invoke. Records every
// payload it was asked to send, and per `opts` can fail or delay specific invokes.
function fakeClients(opts: { fail?: (payload: string) => boolean; delayMs?: number } = {}): {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like a really complex testing setup. Is there a simpler way? I'm wondering if there's a structural change we could make to simplify here.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I fixed these tests as a follow up?

Comment threadsrc/core/eval/invokeDataset/load.ts Outdated
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import type { DatasetSchemaType } from "@aws-sdk/client-bedrock-agentcore-control";
import type { InlineGroundTruth } from "@aws-sdk/client-bedrock-agentcore";

// A record, not a bare string, so a future tool-branching type can widen it by a field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like the code explains this comment.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only blocking question is why we do an explicit wait, rest could be polished later/in a follow-up. Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

import { coreOptsFromCtx } from "../../../utils";
import { parseRuntimeInvokeHeaders } from "../../../runtime/invoke/request";

// Composes invokeDataset (replay) → startBatchEvaluation (grade). Invoke flags mirror

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the comment describing the implementation of the handler? What value does it provide over the code?

Comment threadsrc/core/eval.tsx
// Enrich with the example identity so the dropped-invoke reason is self-describing
// in firstError, instead of a bare transport message logged separately.
const cause = error instanceof Error ? error : new Error(String(error));
throw new Error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to confirm my understanding, this error never hits telemetry because an individual example failing does not bubble up so this error is purely for the user message it creates?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. An individual example failing is caught and dropped by runExamples rather than rethrown, so it never reaches telemetry — it only feeds the user-facing message on a total failure. That was intentional: a run can be hundreds of examples, and I didn't want per-example failures flooding our telemetry.

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?

try {
headers.set("Authorization", `Bearer ${bearerToken}`);
} catch {
throw new InputValidationError("Invalid bearer token");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause up to these errors to get the stack trace? (same with 132, 155 below)

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

logger
.child({
errorName:
error instanceof TypeError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason error instanceof error ? error.name : 'error' doesn't work here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this in the next PR.

};

// InvokeDatasetResult reports the created sessions plus how many examples were invoked
// vs dropped (a failed invoke is skipped, not fatal). firstError explains a total failure.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does firstError explain a total failure? I thought it stored the first failed example's error?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WE will remove it later. Yes lets do a follow up on this.

@@ -0,0 +1,263 @@
// Disables the post-invoke span-ingestion wait so the replay returns immediately.
process.env.SIMULATE_INGESTION_WAIT_MS = "0";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would this be a good application of global config? this might help this behavior be more discoverable by other tests that might need the same.

@jariy17jariy17Aug 24, 2026

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So add to the bunfig.toml to preload a script that run this:
./global-mocks.ts

// Global mocksimport{mock}from"bun:test";// Mock environment variablesprocess.env.SIMULATE_INGESTION_WAIT_MS="0";

bunfig.toml

[test]preload=["./global-mocks.ts"]

ref

Yes I could do that in the follow up Pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to inject the global config down through core with the data we want.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah that make sense

return this.groundTruth();
}

// Emit every turn (carrying its prompt), not just those with an expectation: filtering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not quite sure what this comment is saying?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ill remove it.

@Hweinstock

Copy link
Copy Markdown
Contributor

Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

from chatting offline, sounds like the wait approach is shared by the eval time. Still unsure how they can be confident the evaluator results are not incomplete, but approving since its an existing solution.

Hweinstock
Hweinstock previously approved these changes Aug 24, 2026
jariy17 added 3 commits August 24, 2026 21:29
- move renderJsonTemplate out of shared src/io into core/eval/invokeDataset
- invokeRuntime: raw TypeError/Error -> InputValidationError/RuntimeInvokeResponseError
- wire error causes in template + dataset JSON parse
- invokeDataset: enrich per-example invoke failure instead of log+rethrow
- simulate: bubble Ctrl-C cancellation (telemetry) instead of quiet return; clarify --description help; TODO(#1986) shared abort helper
- drop type-guaranteed 'no leak' test; keep AbortSignal wiring in composition test
- trim stale/redundant comments (runtime.tsx, invokeRuntime DTO note, TurnResult)
…in payload-template
Bug bash (real exploratory-account run) surfaced two defects in the shared invokeDataset path:
1. PredefinedExample blind-cast assertions/expected_trajectory as string[] with no load-time
validation (unlike turns). A non-array value passed load, burned a live paid invoke, then
threw a raw '.map is not a function' mislabeled 'failed to invoke'. Now validated in the
constructor -> clean InputValidationError before any invoke.
2. A --payload-template with no {input} placeholder was silently accepted, wasting a full
~3-min replay on a constant payload. Now rejected up front in invokeDataset.
Comment threadsrc/core/eval.tsx
const sessionId = randomUUID();
const ctx: RunContext = {
invokeOnce: async (payload) => {
const response = await invokeRuntime(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comparing this to src/handlers/runtime/invoke/request.ts, and I notice that the code calls normalizeRuntimeInvokeRequest to do some validation before invoking. Do you think we need something similar here?

@nborges-awsnborges-aws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. One comment with a question for you

@jariy17
jariy17 merged commit 83dab8f into refactorAug 24, 2026
13 checks passed
@jariy17
jariy17 deleted the feat/eval-invoke-dataset-pr branch August 24, 2026 22:48
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jariy17@codecov-commenter@Hweinstock@nborges-aws
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

feat(eval): batch-evaluation simulate — each example owns its invoker - #2032

Merged
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr
Aug 24, 2026
Merged

feat(eval): batch-evaluation simulate — each example owns its invoker#2032
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr

Conversation

@jariy17

@jariy17jariy17 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

What

Adds batch-evaluation simulate to replay a dataset against a runtime and grade the resulting sessions.

Each dataset example is a self-running object that owns its own invoker (RunContext). invokeDataset builds one invoker per session and passes it into the example's run(). The example performs the invocation; the machine supplies the invoker and collects the result.

The invoker seam

A dataset example knows what to send and how to turn the responses into ground truth, but not how to reach the runtime. Its RunContext owns that runtime-specific invocation:

// src/core/eval/invokeDataset/example/types.tsexporttypeTurnResult={text: string};exporttypeRunContext={invokeOnce(input: string): Promise<TurnResult>};exportinterfaceExample{readonlyexampleId: string;readonlyschemaType: DatasetSchemaType;// Replay this example against the runtime `ctx` reaches, return neutral ground truth.run(ctx: RunContext): Promise<InlineGroundTruth|undefined>;}

invokeDataset resolves the runtime once, then builds a distinct invoker for each client-generated session and passes it to that example:

constresults=awaitrunExamples(examples,async(example)=>{constctx: RunContext={invokeOnce: async(input)=>{constres=awaitinvokeRuntime(deps,{/* resolved runtime, session, and rendered payload */},options,signal,);return{text: /* drained response body */};},};returnexample.run(ctx);});

The example decides how many times to call invokeOnce and in what order. Its invoker decides how each call reaches the runtime for that session.

Layout

src/core/eval/invokeDataset/
├── load.ts DatasetLoader — pure JSONL parse → shape-classify → new
├── run.ts runExamples — bounded-concurrency pool, failure isolation
├── invokeDataset.test.ts end-to-end golden coverage of the whole path
└── example/
├── types.ts Example interface, RunContext (the invoker), TurnResult
├── predefined.ts PredefinedExample — replays scripted turns, builds ground truth
└── simulated.ts SimulatedExample — not shipped; throws at construction

Plus src/core/invokeRuntime.ts, which extracts runtime invocation from runtime.tsx for reuse by both RuntimeClient and invokeDataset, and src/handlers/eval/batch-evaluation/simulate/index.tsx, which composes invokeDataset with startBatchEvaluation.

Testing

  • bun run typecheck passes.
  • bun test: 1544 pass, 0 fail.
  • invokeDataset.test.ts drives the real EvalClient.invokeDataset over a fake AWS layer with golden fixtures. Its snapshot covers created sessions and inline ground truth across every supported variation while exercising the loader, example classes, concurrency pool, template rendering, and runtime invocation.
  • simulate.test.tsx snapshots the handler's wrapped sessionMetadata.

@codecov-commenter

codecov-commenter commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.58444% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.33%. Comparing base (768ef10) to head (27c810f).

Files with missing linesPatch %Lines
src/core/eval.tsx85.71%14 Missing ⚠️
src/core/eval/invokeDataset/template.ts91.30%2 Missing ⚠️
src/core/eval/invokeDataset/example/simulated.ts92.30%1 Missing ⚠️
src/core/invokeRuntime.ts99.35%1 Missing ⚠️
Additional details and impacted files
@@ Coverage Diff @@## refactor #2032 +/- ##
============================================
- Coverage 97.36% 97.33% -0.04% 
============================================
Files 410 417 +7 Lines 24796 25181 +385 ============================================
+ Hits 24142 24509 +367 - Misses 654 672 +18 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actionsgithub-actionsBot removed the agentcore-harness-reviewing AgentCore Harness review in progress label Aug 18, 2026
@jariy17
jariy17force-pushed the feat/eval-invoke-dataset-pr branch 6 times, most recently from 6a2915e to b747257CompareAugust 19, 2026 18:45

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't get to all the examples work yet, but had a few small comments and a question on how we can simplify testing, because it feels pretty gnarly rn.

Comment threadsrc/io/template.ts Outdated
@@ -0,0 +1,33 @@
import { InputValidationError } from "../errors";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we keep this inside evals until there is an opportunity to re-use it? I feel like the io directory should be reserved for shared abstractions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking the invoke handler could use this but lets leave it in the simulate handler for now.

Comment threadsrc/io/template.ts Outdated
try {
parsed = JSON.parse(template);
} catch {
throw new InputValidationError(`--${flagName} must be valid JSON`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

qualifier?: string;
payloadTemplate: string; // e.g. {"prompt":"{input}"} — {input} is the example's turn input
headers?: [string, string][];
bearerToken?: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: is there a reason bearerToken is treated different from other headers?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the discriminator that selects the auth path, not an application header. Its presence routes the invoke to CUSTOM_JWT path (src/core/invokeRuntime.ts:73)

flag("dataset-version", "dataset version (with a dataset id)", z.string().optional()),
flag("evaluator", "evaluator id(s) to apply", z.array(z.string()).optional()),
flag("name", "batch evaluation name (unique in the account)", z.string().optional()),
flag("description", "optional description", z.string().optional()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what exactly is this describing? the simulation itself?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be batch-evaluation description. I'll rename this batch-eval-desc, same with name too.

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahhh, theres a shared abstraction for this, but looks like it hasn't been merged yet :(

#1986

maybe we can swap it over as a follow-up once its merged.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment threadsrc/core/eval.tsx Outdated
const groundTruth = await example.run(ctx);
return { exampleId: example.exampleId, sessionId, groundTruth };
} catch (error) {
this.logger.debug(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of logging and rethrowing, is there a way to enrich the error thrown to avoid noise?

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there anything we can poll on instead of a static wait time?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't poll right away because some traces might still be arriving, and I didn't want us to end up with incomplete session data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?


// A fake AWS layer: control resolves the runtime, data answers each invoke. Records every
// payload it was asked to send, and per `opts` can fail or delay specific invokes.
function fakeClients(opts: { fail?: (payload: string) => boolean; delayMs?: number } = {}): {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like a really complex testing setup. Is there a simpler way? I'm wondering if there's a structural change we could make to simplify here.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I fixed these tests as a follow up?

Comment threadsrc/core/eval/invokeDataset/load.ts Outdated
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import type { DatasetSchemaType } from "@aws-sdk/client-bedrock-agentcore-control";
import type { InlineGroundTruth } from "@aws-sdk/client-bedrock-agentcore";

// A record, not a bare string, so a future tool-branching type can widen it by a field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like the code explains this comment.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only blocking question is why we do an explicit wait, rest could be polished later/in a follow-up. Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

import { coreOptsFromCtx } from "../../../utils";
import { parseRuntimeInvokeHeaders } from "../../../runtime/invoke/request";

// Composes invokeDataset (replay) → startBatchEvaluation (grade). Invoke flags mirror

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the comment describing the implementation of the handler? What value does it provide over the code?

Comment threadsrc/core/eval.tsx
// Enrich with the example identity so the dropped-invoke reason is self-describing
// in firstError, instead of a bare transport message logged separately.
const cause = error instanceof Error ? error : new Error(String(error));
throw new Error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to confirm my understanding, this error never hits telemetry because an individual example failing does not bubble up so this error is purely for the user message it creates?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. An individual example failing is caught and dropped by runExamples rather than rethrown, so it never reaches telemetry — it only feeds the user-facing message on a total failure. That was intentional: a run can be hundreds of examples, and I didn't want per-example failures flooding our telemetry.

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?

try {
headers.set("Authorization", `Bearer ${bearerToken}`);
} catch {
throw new InputValidationError("Invalid bearer token");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause up to these errors to get the stack trace? (same with 132, 155 below)

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

logger
.child({
errorName:
error instanceof TypeError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason error instanceof error ? error.name : 'error' doesn't work here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this in the next PR.

};

// InvokeDatasetResult reports the created sessions plus how many examples were invoked
// vs dropped (a failed invoke is skipped, not fatal). firstError explains a total failure.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does firstError explain a total failure? I thought it stored the first failed example's error?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WE will remove it later. Yes lets do a follow up on this.

@@ -0,0 +1,263 @@
// Disables the post-invoke span-ingestion wait so the replay returns immediately.
process.env.SIMULATE_INGESTION_WAIT_MS = "0";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would this be a good application of global config? this might help this behavior be more discoverable by other tests that might need the same.

@jariy17jariy17Aug 24, 2026

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So add to the bunfig.toml to preload a script that run this:
./global-mocks.ts

// Global mocksimport{mock}from"bun:test";// Mock environment variablesprocess.env.SIMULATE_INGESTION_WAIT_MS="0";

bunfig.toml

[test]preload=["./global-mocks.ts"]

ref

Yes I could do that in the follow up Pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to inject the global config down through core with the data we want.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah that make sense

return this.groundTruth();
}

// Emit every turn (carrying its prompt), not just those with an expectation: filtering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not quite sure what this comment is saying?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ill remove it.

@Hweinstock

Copy link
Copy Markdown
Contributor

Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

from chatting offline, sounds like the wait approach is shared by the eval time. Still unsure how they can be confident the evaluator results are not incomplete, but approving since its an existing solution.

Hweinstock
Hweinstock previously approved these changes Aug 24, 2026
jariy17 added 3 commits August 24, 2026 21:29
- move renderJsonTemplate out of shared src/io into core/eval/invokeDataset
- invokeRuntime: raw TypeError/Error -> InputValidationError/RuntimeInvokeResponseError
- wire error causes in template + dataset JSON parse
- invokeDataset: enrich per-example invoke failure instead of log+rethrow
- simulate: bubble Ctrl-C cancellation (telemetry) instead of quiet return; clarify --description help; TODO(#1986) shared abort helper
- drop type-guaranteed 'no leak' test; keep AbortSignal wiring in composition test
- trim stale/redundant comments (runtime.tsx, invokeRuntime DTO note, TurnResult)
…in payload-template
Bug bash (real exploratory-account run) surfaced two defects in the shared invokeDataset path:
1. PredefinedExample blind-cast assertions/expected_trajectory as string[] with no load-time
validation (unlike turns). A non-array value passed load, burned a live paid invoke, then
threw a raw '.map is not a function' mislabeled 'failed to invoke'. Now validated in the
constructor -> clean InputValidationError before any invoke.
2. A --payload-template with no {input} placeholder was silently accepted, wasting a full
~3-min replay on a constant payload. Now rejected up front in invokeDataset.
Comment threadsrc/core/eval.tsx
const sessionId = randomUUID();
const ctx: RunContext = {
invokeOnce: async (payload) => {
const response = await invokeRuntime(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comparing this to src/handlers/runtime/invoke/request.ts, and I notice that the code calls normalizeRuntimeInvokeRequest to do some validation before invoking. Do you think we need something similar here?

@nborges-awsnborges-aws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. One comment with a question for you

@jariy17
jariy17 merged commit 83dab8f into refactorAug 24, 2026
13 checks passed
@jariy17
jariy17 deleted the feat/eval-invoke-dataset-pr branch August 24, 2026 22:48
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jariy17@codecov-commenter@Hweinstock@nborges-aws
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(eval): batch-evaluation simulate — each example owns its invoker - #2032

Merged
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr
Aug 24, 2026
Merged

feat(eval): batch-evaluation simulate — each example owns its invoker#2032
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr

Conversation

@jariy17

@jariy17jariy17 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

What

Adds batch-evaluation simulate to replay a dataset against a runtime and grade the resulting sessions.

Each dataset example is a self-running object that owns its own invoker (RunContext). invokeDataset builds one invoker per session and passes it into the example's run(). The example performs the invocation; the machine supplies the invoker and collects the result.

The invoker seam

A dataset example knows what to send and how to turn the responses into ground truth, but not how to reach the runtime. Its RunContext owns that runtime-specific invocation:

// src/core/eval/invokeDataset/example/types.tsexporttypeTurnResult={text: string};exporttypeRunContext={invokeOnce(input: string): Promise<TurnResult>};exportinterfaceExample{readonlyexampleId: string;readonlyschemaType: DatasetSchemaType;// Replay this example against the runtime `ctx` reaches, return neutral ground truth.run(ctx: RunContext): Promise<InlineGroundTruth|undefined>;}

invokeDataset resolves the runtime once, then builds a distinct invoker for each client-generated session and passes it to that example:

constresults=awaitrunExamples(examples,async(example)=>{constctx: RunContext={invokeOnce: async(input)=>{constres=awaitinvokeRuntime(deps,{/* resolved runtime, session, and rendered payload */},options,signal,);return{text: /* drained response body */};},};returnexample.run(ctx);});

The example decides how many times to call invokeOnce and in what order. Its invoker decides how each call reaches the runtime for that session.

Layout

src/core/eval/invokeDataset/
├── load.ts DatasetLoader — pure JSONL parse → shape-classify → new
├── run.ts runExamples — bounded-concurrency pool, failure isolation
├── invokeDataset.test.ts end-to-end golden coverage of the whole path
└── example/
├── types.ts Example interface, RunContext (the invoker), TurnResult
├── predefined.ts PredefinedExample — replays scripted turns, builds ground truth
└── simulated.ts SimulatedExample — not shipped; throws at construction

Plus src/core/invokeRuntime.ts, which extracts runtime invocation from runtime.tsx for reuse by both RuntimeClient and invokeDataset, and src/handlers/eval/batch-evaluation/simulate/index.tsx, which composes invokeDataset with startBatchEvaluation.

Testing

  • bun run typecheck passes.
  • bun test: 1544 pass, 0 fail.
  • invokeDataset.test.ts drives the real EvalClient.invokeDataset over a fake AWS layer with golden fixtures. Its snapshot covers created sessions and inline ground truth across every supported variation while exercising the loader, example classes, concurrency pool, template rendering, and runtime invocation.
  • simulate.test.tsx snapshots the handler's wrapped sessionMetadata.

@codecov-commenter

codecov-commenter commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.58444% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.33%. Comparing base (768ef10) to head (27c810f).

Files with missing linesPatch %Lines
src/core/eval.tsx85.71%14 Missing ⚠️
src/core/eval/invokeDataset/template.ts91.30%2 Missing ⚠️
src/core/eval/invokeDataset/example/simulated.ts92.30%1 Missing ⚠️
src/core/invokeRuntime.ts99.35%1 Missing ⚠️
Additional details and impacted files
@@ Coverage Diff @@## refactor #2032 +/- ##
============================================
- Coverage 97.36% 97.33% -0.04% 
============================================
Files 410 417 +7 Lines 24796 25181 +385 ============================================
+ Hits 24142 24509 +367 - Misses 654 672 +18 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actionsgithub-actionsBot removed the agentcore-harness-reviewing AgentCore Harness review in progress label Aug 18, 2026
@jariy17
jariy17force-pushed the feat/eval-invoke-dataset-pr branch 6 times, most recently from 6a2915e to b747257CompareAugust 19, 2026 18:45

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't get to all the examples work yet, but had a few small comments and a question on how we can simplify testing, because it feels pretty gnarly rn.

Comment threadsrc/io/template.ts Outdated
@@ -0,0 +1,33 @@
import { InputValidationError } from "../errors";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we keep this inside evals until there is an opportunity to re-use it? I feel like the io directory should be reserved for shared abstractions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking the invoke handler could use this but lets leave it in the simulate handler for now.

Comment threadsrc/io/template.ts Outdated
try {
parsed = JSON.parse(template);
} catch {
throw new InputValidationError(`--${flagName} must be valid JSON`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

qualifier?: string;
payloadTemplate: string; // e.g. {"prompt":"{input}"} — {input} is the example's turn input
headers?: [string, string][];
bearerToken?: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: is there a reason bearerToken is treated different from other headers?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the discriminator that selects the auth path, not an application header. Its presence routes the invoke to CUSTOM_JWT path (src/core/invokeRuntime.ts:73)

flag("dataset-version", "dataset version (with a dataset id)", z.string().optional()),
flag("evaluator", "evaluator id(s) to apply", z.array(z.string()).optional()),
flag("name", "batch evaluation name (unique in the account)", z.string().optional()),
flag("description", "optional description", z.string().optional()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what exactly is this describing? the simulation itself?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be batch-evaluation description. I'll rename this batch-eval-desc, same with name too.

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahhh, theres a shared abstraction for this, but looks like it hasn't been merged yet :(

#1986

maybe we can swap it over as a follow-up once its merged.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment threadsrc/core/eval.tsx Outdated
const groundTruth = await example.run(ctx);
return { exampleId: example.exampleId, sessionId, groundTruth };
} catch (error) {
this.logger.debug(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of logging and rethrowing, is there a way to enrich the error thrown to avoid noise?

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there anything we can poll on instead of a static wait time?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't poll right away because some traces might still be arriving, and I didn't want us to end up with incomplete session data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?


// A fake AWS layer: control resolves the runtime, data answers each invoke. Records every
// payload it was asked to send, and per `opts` can fail or delay specific invokes.
function fakeClients(opts: { fail?: (payload: string) => boolean; delayMs?: number } = {}): {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like a really complex testing setup. Is there a simpler way? I'm wondering if there's a structural change we could make to simplify here.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I fixed these tests as a follow up?

Comment threadsrc/core/eval/invokeDataset/load.ts Outdated
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import type { DatasetSchemaType } from "@aws-sdk/client-bedrock-agentcore-control";
import type { InlineGroundTruth } from "@aws-sdk/client-bedrock-agentcore";

// A record, not a bare string, so a future tool-branching type can widen it by a field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like the code explains this comment.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only blocking question is why we do an explicit wait, rest could be polished later/in a follow-up. Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

import { coreOptsFromCtx } from "../../../utils";
import { parseRuntimeInvokeHeaders } from "../../../runtime/invoke/request";

// Composes invokeDataset (replay) → startBatchEvaluation (grade). Invoke flags mirror

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the comment describing the implementation of the handler? What value does it provide over the code?

Comment threadsrc/core/eval.tsx
// Enrich with the example identity so the dropped-invoke reason is self-describing
// in firstError, instead of a bare transport message logged separately.
const cause = error instanceof Error ? error : new Error(String(error));
throw new Error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to confirm my understanding, this error never hits telemetry because an individual example failing does not bubble up so this error is purely for the user message it creates?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. An individual example failing is caught and dropped by runExamples rather than rethrown, so it never reaches telemetry — it only feeds the user-facing message on a total failure. That was intentional: a run can be hundreds of examples, and I didn't want per-example failures flooding our telemetry.

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?

try {
headers.set("Authorization", `Bearer ${bearerToken}`);
} catch {
throw new InputValidationError("Invalid bearer token");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause up to these errors to get the stack trace? (same with 132, 155 below)

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

logger
.child({
errorName:
error instanceof TypeError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason error instanceof error ? error.name : 'error' doesn't work here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this in the next PR.

};

// InvokeDatasetResult reports the created sessions plus how many examples were invoked
// vs dropped (a failed invoke is skipped, not fatal). firstError explains a total failure.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does firstError explain a total failure? I thought it stored the first failed example's error?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WE will remove it later. Yes lets do a follow up on this.

@@ -0,0 +1,263 @@
// Disables the post-invoke span-ingestion wait so the replay returns immediately.
process.env.SIMULATE_INGESTION_WAIT_MS = "0";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would this be a good application of global config? this might help this behavior be more discoverable by other tests that might need the same.

@jariy17jariy17Aug 24, 2026

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So add to the bunfig.toml to preload a script that run this:
./global-mocks.ts

// Global mocksimport{mock}from"bun:test";// Mock environment variablesprocess.env.SIMULATE_INGESTION_WAIT_MS="0";

bunfig.toml

[test]preload=["./global-mocks.ts"]

ref

Yes I could do that in the follow up Pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to inject the global config down through core with the data we want.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah that make sense

return this.groundTruth();
}

// Emit every turn (carrying its prompt), not just those with an expectation: filtering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not quite sure what this comment is saying?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ill remove it.

@Hweinstock

Copy link
Copy Markdown
Contributor

Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

from chatting offline, sounds like the wait approach is shared by the eval time. Still unsure how they can be confident the evaluator results are not incomplete, but approving since its an existing solution.

Hweinstock
Hweinstock previously approved these changes Aug 24, 2026
jariy17 added 3 commits August 24, 2026 21:29
- move renderJsonTemplate out of shared src/io into core/eval/invokeDataset
- invokeRuntime: raw TypeError/Error -> InputValidationError/RuntimeInvokeResponseError
- wire error causes in template + dataset JSON parse
- invokeDataset: enrich per-example invoke failure instead of log+rethrow
- simulate: bubble Ctrl-C cancellation (telemetry) instead of quiet return; clarify --description help; TODO(#1986) shared abort helper
- drop type-guaranteed 'no leak' test; keep AbortSignal wiring in composition test
- trim stale/redundant comments (runtime.tsx, invokeRuntime DTO note, TurnResult)
…in payload-template
Bug bash (real exploratory-account run) surfaced two defects in the shared invokeDataset path:
1. PredefinedExample blind-cast assertions/expected_trajectory as string[] with no load-time
validation (unlike turns). A non-array value passed load, burned a live paid invoke, then
threw a raw '.map is not a function' mislabeled 'failed to invoke'. Now validated in the
constructor -> clean InputValidationError before any invoke.
2. A --payload-template with no {input} placeholder was silently accepted, wasting a full
~3-min replay on a constant payload. Now rejected up front in invokeDataset.
Comment threadsrc/core/eval.tsx
const sessionId = randomUUID();
const ctx: RunContext = {
invokeOnce: async (payload) => {
const response = await invokeRuntime(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comparing this to src/handlers/runtime/invoke/request.ts, and I notice that the code calls normalizeRuntimeInvokeRequest to do some validation before invoking. Do you think we need something similar here?

@nborges-awsnborges-aws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. One comment with a question for you

@jariy17
jariy17 merged commit 83dab8f into refactorAug 24, 2026
13 checks passed
@jariy17
jariy17 deleted the feat/eval-invoke-dataset-pr branch August 24, 2026 22:48
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jariy17@codecov-commenter@Hweinstock@nborges-aws
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(eval): batch-evaluation simulate — each example owns its invoker - #2032

Merged
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr
Aug 24, 2026
Merged

feat(eval): batch-evaluation simulate — each example owns its invoker#2032
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr

Conversation

@jariy17

@jariy17jariy17 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

What

Adds batch-evaluation simulate to replay a dataset against a runtime and grade the resulting sessions.

Each dataset example is a self-running object that owns its own invoker (RunContext). invokeDataset builds one invoker per session and passes it into the example's run(). The example performs the invocation; the machine supplies the invoker and collects the result.

The invoker seam

A dataset example knows what to send and how to turn the responses into ground truth, but not how to reach the runtime. Its RunContext owns that runtime-specific invocation:

// src/core/eval/invokeDataset/example/types.tsexporttypeTurnResult={text: string};exporttypeRunContext={invokeOnce(input: string): Promise<TurnResult>};exportinterfaceExample{readonlyexampleId: string;readonlyschemaType: DatasetSchemaType;// Replay this example against the runtime `ctx` reaches, return neutral ground truth.run(ctx: RunContext): Promise<InlineGroundTruth|undefined>;}

invokeDataset resolves the runtime once, then builds a distinct invoker for each client-generated session and passes it to that example:

constresults=awaitrunExamples(examples,async(example)=>{constctx: RunContext={invokeOnce: async(input)=>{constres=awaitinvokeRuntime(deps,{/* resolved runtime, session, and rendered payload */},options,signal,);return{text: /* drained response body */};},};returnexample.run(ctx);});

The example decides how many times to call invokeOnce and in what order. Its invoker decides how each call reaches the runtime for that session.

Layout

src/core/eval/invokeDataset/
├── load.ts DatasetLoader — pure JSONL parse → shape-classify → new
├── run.ts runExamples — bounded-concurrency pool, failure isolation
├── invokeDataset.test.ts end-to-end golden coverage of the whole path
└── example/
├── types.ts Example interface, RunContext (the invoker), TurnResult
├── predefined.ts PredefinedExample — replays scripted turns, builds ground truth
└── simulated.ts SimulatedExample — not shipped; throws at construction

Plus src/core/invokeRuntime.ts, which extracts runtime invocation from runtime.tsx for reuse by both RuntimeClient and invokeDataset, and src/handlers/eval/batch-evaluation/simulate/index.tsx, which composes invokeDataset with startBatchEvaluation.

Testing

  • bun run typecheck passes.
  • bun test: 1544 pass, 0 fail.
  • invokeDataset.test.ts drives the real EvalClient.invokeDataset over a fake AWS layer with golden fixtures. Its snapshot covers created sessions and inline ground truth across every supported variation while exercising the loader, example classes, concurrency pool, template rendering, and runtime invocation.
  • simulate.test.tsx snapshots the handler's wrapped sessionMetadata.

@codecov-commenter

codecov-commenter commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.58444% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.33%. Comparing base (768ef10) to head (27c810f).

Files with missing linesPatch %Lines
src/core/eval.tsx85.71%14 Missing ⚠️
src/core/eval/invokeDataset/template.ts91.30%2 Missing ⚠️
src/core/eval/invokeDataset/example/simulated.ts92.30%1 Missing ⚠️
src/core/invokeRuntime.ts99.35%1 Missing ⚠️
Additional details and impacted files
@@ Coverage Diff @@## refactor #2032 +/- ##
============================================
- Coverage 97.36% 97.33% -0.04% 
============================================
Files 410 417 +7 Lines 24796 25181 +385 ============================================
+ Hits 24142 24509 +367 - Misses 654 672 +18 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actionsgithub-actionsBot removed the agentcore-harness-reviewing AgentCore Harness review in progress label Aug 18, 2026
@jariy17
jariy17force-pushed the feat/eval-invoke-dataset-pr branch 6 times, most recently from 6a2915e to b747257CompareAugust 19, 2026 18:45

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't get to all the examples work yet, but had a few small comments and a question on how we can simplify testing, because it feels pretty gnarly rn.

Comment threadsrc/io/template.ts Outdated
@@ -0,0 +1,33 @@
import { InputValidationError } from "../errors";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we keep this inside evals until there is an opportunity to re-use it? I feel like the io directory should be reserved for shared abstractions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking the invoke handler could use this but lets leave it in the simulate handler for now.

Comment threadsrc/io/template.ts Outdated
try {
parsed = JSON.parse(template);
} catch {
throw new InputValidationError(`--${flagName} must be valid JSON`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

qualifier?: string;
payloadTemplate: string; // e.g. {"prompt":"{input}"} — {input} is the example's turn input
headers?: [string, string][];
bearerToken?: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: is there a reason bearerToken is treated different from other headers?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the discriminator that selects the auth path, not an application header. Its presence routes the invoke to CUSTOM_JWT path (src/core/invokeRuntime.ts:73)

flag("dataset-version", "dataset version (with a dataset id)", z.string().optional()),
flag("evaluator", "evaluator id(s) to apply", z.array(z.string()).optional()),
flag("name", "batch evaluation name (unique in the account)", z.string().optional()),
flag("description", "optional description", z.string().optional()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what exactly is this describing? the simulation itself?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be batch-evaluation description. I'll rename this batch-eval-desc, same with name too.

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahhh, theres a shared abstraction for this, but looks like it hasn't been merged yet :(

#1986

maybe we can swap it over as a follow-up once its merged.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment threadsrc/core/eval.tsx Outdated
const groundTruth = await example.run(ctx);
return { exampleId: example.exampleId, sessionId, groundTruth };
} catch (error) {
this.logger.debug(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of logging and rethrowing, is there a way to enrich the error thrown to avoid noise?

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there anything we can poll on instead of a static wait time?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't poll right away because some traces might still be arriving, and I didn't want us to end up with incomplete session data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?


// A fake AWS layer: control resolves the runtime, data answers each invoke. Records every
// payload it was asked to send, and per `opts` can fail or delay specific invokes.
function fakeClients(opts: { fail?: (payload: string) => boolean; delayMs?: number } = {}): {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like a really complex testing setup. Is there a simpler way? I'm wondering if there's a structural change we could make to simplify here.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I fixed these tests as a follow up?

Comment threadsrc/core/eval/invokeDataset/load.ts Outdated
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import type { DatasetSchemaType } from "@aws-sdk/client-bedrock-agentcore-control";
import type { InlineGroundTruth } from "@aws-sdk/client-bedrock-agentcore";

// A record, not a bare string, so a future tool-branching type can widen it by a field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like the code explains this comment.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only blocking question is why we do an explicit wait, rest could be polished later/in a follow-up. Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

import { coreOptsFromCtx } from "../../../utils";
import { parseRuntimeInvokeHeaders } from "../../../runtime/invoke/request";

// Composes invokeDataset (replay) → startBatchEvaluation (grade). Invoke flags mirror

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the comment describing the implementation of the handler? What value does it provide over the code?

Comment threadsrc/core/eval.tsx
// Enrich with the example identity so the dropped-invoke reason is self-describing
// in firstError, instead of a bare transport message logged separately.
const cause = error instanceof Error ? error : new Error(String(error));
throw new Error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to confirm my understanding, this error never hits telemetry because an individual example failing does not bubble up so this error is purely for the user message it creates?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. An individual example failing is caught and dropped by runExamples rather than rethrown, so it never reaches telemetry — it only feeds the user-facing message on a total failure. That was intentional: a run can be hundreds of examples, and I didn't want per-example failures flooding our telemetry.

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?

try {
headers.set("Authorization", `Bearer ${bearerToken}`);
} catch {
throw new InputValidationError("Invalid bearer token");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause up to these errors to get the stack trace? (same with 132, 155 below)

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

logger
.child({
errorName:
error instanceof TypeError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason error instanceof error ? error.name : 'error' doesn't work here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this in the next PR.

};

// InvokeDatasetResult reports the created sessions plus how many examples were invoked
// vs dropped (a failed invoke is skipped, not fatal). firstError explains a total failure.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does firstError explain a total failure? I thought it stored the first failed example's error?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WE will remove it later. Yes lets do a follow up on this.

@@ -0,0 +1,263 @@
// Disables the post-invoke span-ingestion wait so the replay returns immediately.
process.env.SIMULATE_INGESTION_WAIT_MS = "0";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would this be a good application of global config? this might help this behavior be more discoverable by other tests that might need the same.

@jariy17jariy17Aug 24, 2026

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So add to the bunfig.toml to preload a script that run this:
./global-mocks.ts

// Global mocksimport{mock}from"bun:test";// Mock environment variablesprocess.env.SIMULATE_INGESTION_WAIT_MS="0";

bunfig.toml

[test]preload=["./global-mocks.ts"]

ref

Yes I could do that in the follow up Pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to inject the global config down through core with the data we want.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah that make sense

return this.groundTruth();
}

// Emit every turn (carrying its prompt), not just those with an expectation: filtering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not quite sure what this comment is saying?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ill remove it.

@Hweinstock

Copy link
Copy Markdown
Contributor

Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

from chatting offline, sounds like the wait approach is shared by the eval time. Still unsure how they can be confident the evaluator results are not incomplete, but approving since its an existing solution.

Hweinstock
Hweinstock previously approved these changes Aug 24, 2026
jariy17 added 3 commits August 24, 2026 21:29
- move renderJsonTemplate out of shared src/io into core/eval/invokeDataset
- invokeRuntime: raw TypeError/Error -> InputValidationError/RuntimeInvokeResponseError
- wire error causes in template + dataset JSON parse
- invokeDataset: enrich per-example invoke failure instead of log+rethrow
- simulate: bubble Ctrl-C cancellation (telemetry) instead of quiet return; clarify --description help; TODO(#1986) shared abort helper
- drop type-guaranteed 'no leak' test; keep AbortSignal wiring in composition test
- trim stale/redundant comments (runtime.tsx, invokeRuntime DTO note, TurnResult)
…in payload-template
Bug bash (real exploratory-account run) surfaced two defects in the shared invokeDataset path:
1. PredefinedExample blind-cast assertions/expected_trajectory as string[] with no load-time
validation (unlike turns). A non-array value passed load, burned a live paid invoke, then
threw a raw '.map is not a function' mislabeled 'failed to invoke'. Now validated in the
constructor -> clean InputValidationError before any invoke.
2. A --payload-template with no {input} placeholder was silently accepted, wasting a full
~3-min replay on a constant payload. Now rejected up front in invokeDataset.
Comment threadsrc/core/eval.tsx
const sessionId = randomUUID();
const ctx: RunContext = {
invokeOnce: async (payload) => {
const response = await invokeRuntime(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comparing this to src/handlers/runtime/invoke/request.ts, and I notice that the code calls normalizeRuntimeInvokeRequest to do some validation before invoking. Do you think we need something similar here?

@nborges-awsnborges-aws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. One comment with a question for you

@jariy17
jariy17 merged commit 83dab8f into refactorAug 24, 2026
13 checks passed
@jariy17
jariy17 deleted the feat/eval-invoke-dataset-pr branch August 24, 2026 22:48
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jariy17@codecov-commenter@Hweinstock@nborges-aws
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

feat(eval): batch-evaluation simulate — each example owns its invoker - #2032

Merged
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr
Aug 24, 2026
Merged

feat(eval): batch-evaluation simulate — each example owns its invoker#2032
jariy17 merged 3 commits into
refactorfrom
feat/eval-invoke-dataset-pr

Conversation

@jariy17

@jariy17jariy17 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

What

Adds batch-evaluation simulate to replay a dataset against a runtime and grade the resulting sessions.

Each dataset example is a self-running object that owns its own invoker (RunContext). invokeDataset builds one invoker per session and passes it into the example's run(). The example performs the invocation; the machine supplies the invoker and collects the result.

The invoker seam

A dataset example knows what to send and how to turn the responses into ground truth, but not how to reach the runtime. Its RunContext owns that runtime-specific invocation:

// src/core/eval/invokeDataset/example/types.tsexporttypeTurnResult={text: string};exporttypeRunContext={invokeOnce(input: string): Promise<TurnResult>};exportinterfaceExample{readonlyexampleId: string;readonlyschemaType: DatasetSchemaType;// Replay this example against the runtime `ctx` reaches, return neutral ground truth.run(ctx: RunContext): Promise<InlineGroundTruth|undefined>;}

invokeDataset resolves the runtime once, then builds a distinct invoker for each client-generated session and passes it to that example:

constresults=awaitrunExamples(examples,async(example)=>{constctx: RunContext={invokeOnce: async(input)=>{constres=awaitinvokeRuntime(deps,{/* resolved runtime, session, and rendered payload */},options,signal,);return{text: /* drained response body */};},};returnexample.run(ctx);});

The example decides how many times to call invokeOnce and in what order. Its invoker decides how each call reaches the runtime for that session.

Layout

src/core/eval/invokeDataset/
├── load.ts DatasetLoader — pure JSONL parse → shape-classify → new
├── run.ts runExamples — bounded-concurrency pool, failure isolation
├── invokeDataset.test.ts end-to-end golden coverage of the whole path
└── example/
├── types.ts Example interface, RunContext (the invoker), TurnResult
├── predefined.ts PredefinedExample — replays scripted turns, builds ground truth
└── simulated.ts SimulatedExample — not shipped; throws at construction

Plus src/core/invokeRuntime.ts, which extracts runtime invocation from runtime.tsx for reuse by both RuntimeClient and invokeDataset, and src/handlers/eval/batch-evaluation/simulate/index.tsx, which composes invokeDataset with startBatchEvaluation.

Testing

  • bun run typecheck passes.
  • bun test: 1544 pass, 0 fail.
  • invokeDataset.test.ts drives the real EvalClient.invokeDataset over a fake AWS layer with golden fixtures. Its snapshot covers created sessions and inline ground truth across every supported variation while exercising the loader, example classes, concurrency pool, template rendering, and runtime invocation.
  • simulate.test.tsx snapshots the handler's wrapped sessionMetadata.

@codecov-commenter

codecov-commenter commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.58444% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.33%. Comparing base (768ef10) to head (27c810f).

Files with missing linesPatch %Lines
src/core/eval.tsx85.71%14 Missing ⚠️
src/core/eval/invokeDataset/template.ts91.30%2 Missing ⚠️
src/core/eval/invokeDataset/example/simulated.ts92.30%1 Missing ⚠️
src/core/invokeRuntime.ts99.35%1 Missing ⚠️
Additional details and impacted files
@@ Coverage Diff @@## refactor #2032 +/- ##
============================================
- Coverage 97.36% 97.33% -0.04% 
============================================
Files 410 417 +7 Lines 24796 25181 +385 ============================================
+ Hits 24142 24509 +367 - Misses 654 672 +18 

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actionsgithub-actionsBot removed the agentcore-harness-reviewing AgentCore Harness review in progress label Aug 18, 2026
@jariy17
jariy17force-pushed the feat/eval-invoke-dataset-pr branch 6 times, most recently from 6a2915e to b747257CompareAugust 19, 2026 18:45

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't get to all the examples work yet, but had a few small comments and a question on how we can simplify testing, because it feels pretty gnarly rn.

Comment threadsrc/io/template.ts Outdated
@@ -0,0 +1,33 @@
import { InputValidationError } from "../errors";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we keep this inside evals until there is an opportunity to re-use it? I feel like the io directory should be reserved for shared abstractions.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was thinking the invoke handler could use this but lets leave it in the simulate handler for now.

Comment threadsrc/io/template.ts Outdated
try {
parsed = JSON.parse(template);
} catch {
throw new InputValidationError(`--${flagName} must be valid JSON`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

qualifier?: string;
payloadTemplate: string; // e.g. {"prompt":"{input}"} — {input} is the example's turn input
headers?: [string, string][];
bearerToken?: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: is there a reason bearerToken is treated different from other headers?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the discriminator that selects the auth path, not an application header. Its presence routes the invoke to CUSTOM_JWT path (src/core/invokeRuntime.ts:73)

flag("dataset-version", "dataset version (with a dataset id)", z.string().optional()),
flag("evaluator", "evaluator id(s) to apply", z.array(z.string()).optional()),
flag("name", "batch evaluation name (unique in the account)", z.string().optional()),
flag("description", "optional description", z.string().optional()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what exactly is this describing? the simulation itself?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be batch-evaluation description. I'll rename this batch-eval-desc, same with name too.

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahhh, theres a shared abstraction for this, but looks like it hasn't been merged yet :(

#1986

maybe we can swap it over as a follow-up once its merged.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment threadsrc/core/eval.tsx Outdated
const groundTruth = await example.run(ctx);
return { exampleId: example.exampleId, sessionId, groundTruth };
} catch (error) {
this.logger.debug(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of logging and rethrowing, is there a way to enrich the error thrown to avoid noise?

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there anything we can poll on instead of a static wait time?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't poll right away because some traces might still be arriving, and I didn't want us to end up with incomplete session data.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?


// A fake AWS layer: control resolves the runtime, data answers each invoke. Records every
// payload it was asked to send, and per `opts` can fail or delay specific invokes.
function fakeClients(opts: { fail?: (payload: string) => boolean; delayMs?: number } = {}): {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this feels like a really complex testing setup. Is there a simpler way? I'm wondering if there's a structural change we could make to simplify here.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I fixed these tests as a follow up?

Comment threadsrc/core/eval/invokeDataset/load.ts Outdated
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import type { DatasetSchemaType } from "@aws-sdk/client-bedrock-agentcore-control";
import type { InlineGroundTruth } from "@aws-sdk/client-bedrock-agentcore";

// A record, not a bare string, so a future tool-branching type can widen it by a field.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i feel like the code explains this comment.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing

@HweinstockHweinstock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only blocking question is why we do an explicit wait, rest could be polished later/in a follow-up. Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

throw new InputValidationError("required option '--name <name>' not specified");

// Ctrl-C aborts the run (invokes, the ingestion wait, the dataset download).
const controller = new AbortController();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like it was merged, so we should be able to leverage that shared abstraction now.
#1986

import { coreOptsFromCtx } from "../../../utils";
import { parseRuntimeInvokeHeaders } from "../../../runtime/invoke/request";

// Composes invokeDataset (replay) → startBatchEvaluation (grade). Invoke flags mirror

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the comment describing the implementation of the handler? What value does it provide over the code?

Comment threadsrc/core/eval.tsx
// Enrich with the example identity so the dropped-invoke reason is self-describing
// in firstError, instead of a bare transport message logged separately.
const cause = error instanceof Error ? error : new Error(String(error));
throw new Error(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to confirm my understanding, this error never hits telemetry because an individual example failing does not bubble up so this error is purely for the user message it creates?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. An individual example failing is caught and dropped by runExamples rather than rethrown, so it never reaches telemetry — it only feeds the user-facing message on a total failure. That was intentional: a run can be hundreds of examples, and I didn't want per-example failures flooding our telemetry.

Comment threadsrc/core/eval.tsx

// AgentCore emits spans ~30s-3min after invoke; grade too early and it reads an empty
// log group and fails every session. Disabled via SIMULATE_INGESTION_WAIT_MS=0 (tests).
const waitMs = Number(process.env.SIMULATE_INGESTION_WAIT_MS ?? 180_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how do we know that there aren't traces still coming in after 3 min mark?

try {
headers.set("Authorization", `Bearer ${bearerToken}`);
} catch {
throw new InputValidationError("Invalid bearer token");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we wire the cause up to these errors to get the stack trace? (same with 132, 155 below)

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing

logger
.child({
errorName:
error instanceof TypeError

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason error instanceof error ? error.name : 'error' doesn't work here?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll look into this in the next PR.

};

// InvokeDatasetResult reports the created sessions plus how many examples were invoked
// vs dropped (a failed invoke is skipped, not fatal). firstError explains a total failure.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does firstError explain a total failure? I thought it stored the first failed example's error?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WE will remove it later. Yes lets do a follow up on this.

@@ -0,0 +1,263 @@
// Disables the post-invoke span-ingestion wait so the replay returns immediately.
process.env.SIMULATE_INGESTION_WAIT_MS = "0";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would this be a good application of global config? this might help this behavior be more discoverable by other tests that might need the same.

@jariy17jariy17Aug 24, 2026

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So add to the bunfig.toml to preload a script that run this:
./global-mocks.ts

// Global mocksimport{mock}from"bun:test";// Mock environment variablesprocess.env.SIMULATE_INGESTION_WAIT_MS="0";

bunfig.toml

[test]preload=["./global-mocks.ts"]

ref

Yes I could do that in the follow up Pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should be able to inject the global config down through core with the data we want.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah that make sense

return this.groundTruth();
}

// Emit every turn (carrying its prompt), not just those with an expectation: filtering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm not quite sure what this comment is saying?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ill remove it.

@Hweinstock

Copy link
Copy Markdown
Contributor

Is there a way we can be sure the spans we need exist before evaluating or is there a reason we don't have to be?

from chatting offline, sounds like the wait approach is shared by the eval time. Still unsure how they can be confident the evaluator results are not incomplete, but approving since its an existing solution.

Hweinstock
Hweinstock previously approved these changes Aug 24, 2026
jariy17 added 3 commits August 24, 2026 21:29
- move renderJsonTemplate out of shared src/io into core/eval/invokeDataset
- invokeRuntime: raw TypeError/Error -> InputValidationError/RuntimeInvokeResponseError
- wire error causes in template + dataset JSON parse
- invokeDataset: enrich per-example invoke failure instead of log+rethrow
- simulate: bubble Ctrl-C cancellation (telemetry) instead of quiet return; clarify --description help; TODO(#1986) shared abort helper
- drop type-guaranteed 'no leak' test; keep AbortSignal wiring in composition test
- trim stale/redundant comments (runtime.tsx, invokeRuntime DTO note, TurnResult)
…in payload-template
Bug bash (real exploratory-account run) surfaced two defects in the shared invokeDataset path:
1. PredefinedExample blind-cast assertions/expected_trajectory as string[] with no load-time
validation (unlike turns). A non-array value passed load, burned a live paid invoke, then
threw a raw '.map is not a function' mislabeled 'failed to invoke'. Now validated in the
constructor -> clean InputValidationError before any invoke.
2. A --payload-template with no {input} placeholder was silently accepted, wasting a full
~3-min replay on a constant payload. Now rejected up front in invokeDataset.
Comment threadsrc/core/eval.tsx
const sessionId = randomUUID();
const ctx: RunContext = {
invokeOnce: async (payload) => {
const response = await invokeRuntime(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comparing this to src/handlers/runtime/invoke/request.ts, and I notice that the code calls normalizeRuntimeInvokeRequest to do some validation before invoking. Do you think we need something similar here?

@nborges-awsnborges-aws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. One comment with a question for you

@jariy17
jariy17 merged commit 83dab8f into refactorAug 24, 2026
13 checks passed
@jariy17
jariy17 deleted the feat/eval-invoke-dataset-pr branch August 24, 2026 22:48
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@jariy17@codecov-commenter@Hweinstock@nborges-aws