Skip to content

Commit b76df9a

Browse files
fix(scenarios): a recorded replay re-sends each turn's recorded writes before the read-back (#33764)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoEDtPjXPciS3z2UwV39x6wK)_ Clause-②: yes (widening) — new export `ReplayNotFaithfulError` and new optional field `AskTask.callTool`, both reached through `./runner` (`src/runner/index.ts` re-exports `driver.ts`) Metadata-protocol: none Fixes #33737 ## 维护者速读 - 改了什么:录制重放(`--driver recorded:`)现在会把录制里每个回合的写入(新建/修改/删除/调用动作)按原顺序、以同一角色重新发给新启动的应用,再读回结果;读操作不重发。 - 为什么改:以前重放只回放模型的回答、不发写入,所以「应当成功」的操作在重放里一律读不到数据、判失败(haiku crm 实跑 3/5,重放 1/4),操作分无法重评。 - 风险与回滚:只影响重放驱动,实跑驱动不变;重放时若应用的回答与录制不同(被拒的码不同、成功变失败等),该题/操作记为「未测量」并写明是哪个调用,绝不判失败。回滚即还原本 PR。 - 先看:`packages/qa/scenarios/src/runner/driver.ts` 的 `RecordedDriver.ask`(重发与比对),`src/runner/orchestrate.ts` 的 `runHalf`(把应用的 MCP 门交给驱动、接住不一致)。 - 两分钟验证:`pnpm --filter @objectstack/scenarios exec vitest run test/runner/orchestrate.test.ts`,应见 55 项全过,其中新的 eval#1 重放组 8 项。 - 需要你做的:无,席位落地。 ## What changes - `RecordedDriver.ask` re-sends the recorded turn's write calls (`create_record`, `update_record`, `delete_record`, `run_action`) to the booted app, in recorded order, through the new optional `AskTask.callTool` (the runner's own MCP door as the turn's persona), before it hands the turn back, so the runner's read-back finds what the recorded run wrote. Reads are never re-sent. - A recorded refused write is re-sent too and must meet the same refusal (same code; a flow refusal stays a flow refusal; an uncoded error stays uncoded). - A row the recorded run created gets a new id in the replayed app; a later recorded write naming the recorded id, in the same turn or a later one, is sent with the new id. - The replay is not faithful, and the turn measures nothing (`ReplayNotFaithfulError`), when the app answers a re-sent write otherwise than the recorded run did, or when a recorded write has no recorded answer (the turn was cut short; nothing of that turn is re-sent). `runHalf` records the question or operation NOT MEASURED with the reason naming each call, keeps the recorded turn summary, and never grades it a fail. - `runHalf` gives every question and operation turn the door (`callTool` bound to the persona's key through `AppHarness.callTool`). Live drivers ignore it; a caller that only re-reads a recording (no door) gets the turn back and nothing is sent. - README: one sentence on the replay in the runner's Driver paragraph. Changeset `33737-replay-resends-recorded-writes.md` (patch). ## Measurement (read-only, before the change) - Recordings: all 79 `*.rec.json` under the eval seat's runs (`/mnt/project-files/eval/runs/`, 2026-11-14/15): 533 recorded write calls, every one in an operation turn, every one with its recorded answer (0 without), 0 turns mixing answered and unanswered writes. Each call carries the tool name and its input, and the step key names the persona, so a faithful re-send is possible for every call. 2 writes name a row created earlier in the same turn (create then update), which the id remap covers. - eval#1's reading reproduced on `main` `53f5a4c9`: haiku `crm_account_with_contacts` replay, Run-operations `1/4 · 1 not measured`; `add_contact` "0 row(s) read back", `move_eli` read "ac3", declared "ac1", audit actor "admin". - Same recording on this branch (`5bdadc88`): Run-operations `3/4 · 1 not measured`, Iterate the same; `add_contact` and `move_eli` pass, as in the live run. `contact_bad_email` stays the existing build-denial NOT MEASURED, as on `main`. Build 27/27, 问数 8/9 unchanged. ## Tests - New top-level describe in `test/runner/orchestrate.test.ts` replaying the verbatim eval#1 turns (fixture `test/runner/fixtures/eval-haiku-crm-replay.recording.json`, four operation turns of the haiku crm recording, reads included) through `runHalf` against a fake MCP door that behaves as that build: `add_contact` reads its row back and passes, `move_eli` passes with its audit actor; the app receives exactly the recorded writes in order, each as its persona, and no read; a recorded refused delete and create are re-sent and refused again; an app that answers otherwise makes the operation NOT MEASURED naming the call, with no grade and no error. Driver-level: the created-id remap (same turn and later turn), the unanswered-write turn (nothing sent, not faithful), a door that throws, and a turn read without a door. - The four eval-r1 build-denial replay tests now see the replay's re-sent writes beside the runner's probes; their fake app answers the re-sends as that build did, and their grades are unchanged. ## Acceptance notes - `move_eli` on `main` read the audit actor as "admin": the replay's app had only the seed's writes. With the re-send the audit actor is the persona again. - A question turn's recorded writes are re-sent as well (the driver cannot tell a question from an operation, and re-sending keeps the app state later turns read the same as the live run's); the 79 recordings hold none. - Two local replays of the branch scaffolded a project whose install did not complete (`npx objectstack` 404, "no project was installed"); the scaffold precedes every driver call, and the third run with `--work` on a fixed directory completed. Not investigated further; noted in case it recurs. ## Verification <details><summary>Package and gates on 58da7e9 (re-run after the main merge on 20d149c)</summary> - `pnpm --filter @objectstack/scenarios build`, `typecheck`, `test`: exit 0, Test Files 32 passed, Tests 790 passed (after the merge: typecheck + test exit 0, 790/790). - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 62 derived families, all run, each exit 0 (`check-plugin-teardown-shape --self-test` after fetching its fixture commit; `check:dual-build-cjs-loads` after `turbo run build --filter=./packages/**`); `--ran` reconciliation: 62 derived, 62 run, 0 NOT-MEASURED, 0 UNRUN. - eslint on the three changed sources: exit 0. </details> <details><summary>Ablation (one, on the re-send)</summary> `node scripts/ablation-replace.mjs` replaced the re-send guard in `RecordedDriver.ask` with an unconditional `return turn` (anchor 1 → 0, blob e66c589 → 32a70041): `orchestrate.test.ts` went red, 10 failed (the 7 new replay tests that send, and 3 of the 4 build-denial tests). Restored by the tool; `git diff HEAD` empty afterwards. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qiby9eoofRB23PSVqcuM)_ <!-- signed: epic:#33595#1 · os-tesla · session_01L9qiby9eoofRB23PSVqcuM --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 25c1d3c commit b76df9a

6 files changed

Lines changed: 878 additions & 25 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/scenarios': patch
3+
---
4+
5+
fix(scenarios): a recorded replay re-sends each turn's recorded writes, so an applied operation reads back what the run wrote
6+
7+
Clause-②: yes (widening) — new export `ReplayNotFaithfulError` and new optional field `AskTask.callTool` (`./runner`)
8+
Metadata-protocol: none
9+
10+
`--driver recorded:FILE` handed back the recorded turn and sent nothing, so the freshly booted app never received the agent's writes: every `applied` operation read back no row and failed on replay ("0 row(s) read back"), and the operations half of a re-scored run was false fails.
11+
12+
The replay now re-sends a turn's recorded writes (`create_record`, `update_record`, `delete_record`, `run_action`) to the booted app, in recorded order, as the turn's persona, through the runner's own MCP door, before the runner reads the operation back. Reads are never re-sent. A recorded refused write is re-sent too and must meet the same refusal again. A row the recorded run created gets a new id in the replayed app, and a later recorded write naming the old id is sent with the new one. When the app answers a re-sent write otherwise than it answered the recorded run, or a recorded write has no recorded answer (the turn was cut short, so whether it wrote is unknown, and nothing of that turn is re-sent), the turn's question or operation is not measured, with the call named in the reason, never a fail. Live drivers are unchanged.

‎packages/qa/scenarios/README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,10 @@ npx @objectstack/scenarios help # the comma
245245
authoring timeout and the turn caps. Every turn records its process: elapsed time, the turn cap it ran under
246246
(`--max-turns`), and for a turn that did not finish its exit code or signal, whether the runner's timeout killed it,
247247
and the end of its stderr. `RecordedDriver` replays a recording, and refuses the live-driver limits and models below;
248-
its record keeps the driver of the recording (`replayOf`). For Codex and any other agent tool, see
248+
its record keeps the driver of the recording (`replayOf`). It re-sends each turn's recorded writes to the booted app,
249+
in recorded order, as the turn's persona, before the read-back (reads are never re-sent; a refused write must be
250+
refused again; a row the run created is named by its new id); a turn the app answers otherwise, or one whose write
251+
has no recorded answer, is not measured with the call named, never a fail. For Codex and any other agent tool, see
249252
[Other agent tools](#other-agent-tools--codex-and-the-external-driver-contract).
250253
- **Model** (`driver.ts`): `--model M` passes `claude --model M` on every turn, an alias (`sonnet`) or a name
251254
(`claude-sonnet-4-5`); `--author-model` sets the authoring turns (build and iterate) and `--ask-model` the question

‎packages/qa/scenarios/src/runner/driver.ts‎

Lines changed: 114 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@
2626
* contract (the package README states it).
2727
* - {@link RecordedDriver} replays turns recorded earlier, so the runner's
2828
* own tests (and a re-grade of an old run) need no model and no network.
29+
* It re-sends each turn's recorded writes to the booted app through the
30+
* runner's door ({@link AskTask.callTool}), so an operation reads back
31+
* what the recorded run wrote.
2932
*
3033
* {@link RecordingDriver} wraps a live driver and writes every turn it sees to
3134
* a recording the replay driver reads back.
@@ -37,8 +40,11 @@ import { tmpdir } from 'node:os';
3740
import { dirname, join, relative, resolve, sep } from 'node:path';
3841

3942
import { SCENARIO_TIERS, type ScenarioTier } from '../schema.js';
43+
import { flowRefusalOf } from '../score/scenario-run-grade.js';
44+
import type { ToolAnswer } from './app.js';
4045
import { noResult, runTurnProcess } from './drivers/process.js';
41-
import { parseStreamJson, type ParsedTurn } from './transcript.js';
46+
import { WRITE_TOOLS } from './observe.js';
47+
import { parseStreamJson, refusalCodeOf, type ParsedTurn, type RunnerToolCall } from './transcript.js';
4248

4349
/** Which run step a turn belongs to; the replay key is built from it. */
4450
export interface StepRef {
@@ -66,6 +72,13 @@ export interface AskTask extends StepRef {
6672
prompt: string;
6773
/** The booted app's MCP endpoint and the persona's API key. */
6874
mcp: { url: string; apiKey: string };
75+
/**
76+
* The runner's own door to the booted app as this turn's persona: one MCP
77+
* `tools/call` with the persona's key (`AppHarness.callTool`). The replay
78+
* driver re-sends the turn's recorded writes through it; a live driver
79+
* ignores it. Absent ⇒ a replay re-reads the turn and sends nothing.
80+
*/
81+
callTool?: (tool: string, args: Record<string, unknown>) => Promise<ToolAnswer>;
6982
}
7083

7184
export interface AuthorResult {
@@ -359,8 +372,76 @@ export class MissingRecordingError extends Error {
359372
}
360373
}
361374

362-
/** Replays a {@link Recording}. A step it has no turn for is a loud error, never an empty turn. */
375+
/**
376+
* A replayed turn whose recorded writes the booted app did not answer as it
377+
* answered the recorded run, or that the recording cannot re-send faithfully.
378+
* What the turn's operation reads back then measures the replay, not the
379+
* agent: the runner records it NOT MEASURED with {@link reason}, never a fail.
380+
*/
381+
export class ReplayNotFaithfulError extends Error {
382+
constructor(
383+
readonly key: string,
384+
/** Why, naming each write call that broke the replay. */
385+
readonly reason: string,
386+
/** The recorded turn, as the run saw it. */
387+
readonly turn: ParsedTurn,
388+
) {
389+
super(`the replay of \`${key}\` is not faithful: ${reason}`);
390+
this.name = 'ReplayNotFaithfulError';
391+
}
392+
}
393+
394+
/** The calls of a recorded turn to the app's write doors, in recorded order (reads are never re-sent). */
395+
const recordedWrites = (turn: ParsedTurn): RunnerToolCall[] => turn.toolCalls.filter((c) => (WRITE_TOOLS as readonly string[]).includes(c.name));
396+
397+
/** How a write door answered, as a replay compares it: `applied`, or the refusal it carried (rule 3 of `observe.ts`). */
398+
function answerOutcome(output: unknown, isError: boolean): string {
399+
const code = refusalCodeOf(output);
400+
if (code !== undefined) return `refused ${code}`;
401+
if (flowRefusalOf(output) !== undefined) return 'refused by its flow';
402+
return isError ? 'refused without a code' : 'applied';
403+
}
404+
405+
/** The id an applied create answered (`{ id }`), when its output carries one. */
406+
function createdIdOf(output: unknown): string | undefined {
407+
if (typeof output !== 'string') return undefined;
408+
try {
409+
const v: unknown = JSON.parse(output);
410+
const id = typeof v === 'object' && v !== null ? (v as Record<string, unknown>).id : undefined;
411+
return typeof id === 'string' && id !== '' ? id : undefined;
412+
} catch {
413+
return undefined;
414+
}
415+
}
416+
417+
/** `value` with every string equal to a recorded id replaced by the id the replay's app gave that row. */
418+
function remapIds(value: unknown, ids: ReadonlyMap<string, string>): unknown {
419+
if (typeof value === 'string') return ids.get(value) ?? value;
420+
if (Array.isArray(value)) return value.map((v) => remapIds(v, ids));
421+
if (typeof value === 'object' && value !== null) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, remapIds(v, ids)]));
422+
return value;
423+
}
424+
425+
/**
426+
* Replays a {@link Recording}. A step it has no turn for is a loud error, never an empty turn.
427+
*
428+
* A question or operation turn's recorded writes (`create_record`,
429+
* `update_record`, `delete_record`, `run_action` through the app's MCP door)
430+
* are re-sent to the freshly booted app, in recorded order, as the turn's
431+
* persona ({@link AskTask.callTool}), before the turn is handed back: the
432+
* runner's read-back then finds what the recorded run wrote. Reads are never
433+
* re-sent. A refused write is re-sent too, and must be refused again with the
434+
* same code. A row the recorded run created is known to the replay's app
435+
* under a new id, so a later write naming the recorded id is sent with the
436+
* new one. The replay is not faithful, and the turn's grade measures nothing
437+
* ({@link ReplayNotFaithfulError}), when a recorded write has no recorded
438+
* answer (nothing is re-sent for that turn: whether it ran is unknown), or
439+
* when the app answers a re-sent write otherwise than it answered the run.
440+
*/
363441
export class RecordedDriver implements AgentDriver {
442+
/** Recorded id → the id the replay's app gave the same created row. */
443+
private readonly ids = new Map<string, string>();
444+
364445
constructor(
365446
private readonly recording: Recording,
366447
private readonly source = '(in memory)',
@@ -402,6 +483,37 @@ export class RecordedDriver implements AgentDriver {
402483
const key = stepKey(task);
403484
const turn = this.recording.turns[key];
404485
if (!turn) throw new MissingRecordingError(key);
486+
const writes = recordedWrites(turn);
487+
if (writes.length === 0 || task.callTool === undefined) return turn;
488+
const unanswered = writes.filter((c) => c.output === undefined);
489+
if (unanswered.length > 0) {
490+
const names = unanswered.map((c) => `\`${c.name}\``).join(', ');
491+
throw new ReplayNotFaithfulError(key, `the recording holds no answer to ${names} (the turn was cut short), so whether it wrote is unknown; nothing was re-sent`, turn);
492+
}
493+
const broken: string[] = [];
494+
for (const c of writes) {
495+
const input = (typeof c.input === 'object' && c.input !== null && !Array.isArray(c.input) ? c.input : {}) as Record<string, unknown>;
496+
const target = typeof input.objectName === 'string' ? ` on ${input.objectName}` : '';
497+
const recorded = answerOutcome(c.output, c.isError === true);
498+
let replayed: string;
499+
let answer: ToolAnswer | undefined;
500+
try {
501+
answer = await task.callTool(c.name, remapIds(input, this.ids) as Record<string, unknown>);
502+
replayed = answerOutcome(answer.output, answer.isError);
503+
} catch (e) {
504+
replayed = `not sent (${e instanceof Error ? e.message : String(e)})`;
505+
}
506+
if (replayed !== recorded) {
507+
broken.push(`\`${c.name}\`${target} was ${recorded} in the recorded run and ${replayed} on replay`);
508+
continue;
509+
}
510+
if (c.name === 'create_record' && recorded === 'applied') {
511+
const was = createdIdOf(c.output);
512+
const now = createdIdOf(answer?.output);
513+
if (was !== undefined && now !== undefined && was !== now) this.ids.set(was, now);
514+
}
515+
}
516+
if (broken.length > 0) throw new ReplayNotFaithfulError(key, `the booted app answered a re-sent write otherwise than the recorded run: ${broken.join('; ')}`, turn);
405517
return turn;
406518
}
407519
}

‎packages/qa/scenarios/src/runner/orchestrate.ts‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ import {
4949
type ScenarioArtifactScore,
5050
} from '../score/index.js';
5151
import type { AppHarness, PersonaAccount } from './app.js';
52-
import { servedAsRequested, type AgentDriver, type StepRef } from './driver.js';
52+
import { ReplayNotFaithfulError, servedAsRequested, type AgentDriver, type AskTask, type StepRef } from './driver.js';
5353
import { citationLabels, namespaceOfArtifact, namespacedScenario, permissionSetName, templateHostName } from './namespace.js';
5454
import { agentSetOf, clockDates, observeOperation, observeProbe, probeCall, touchedRowId, writeCallsOn, type Row } from './observe.js';
5555
import type { CommandResult } from './project.js';
@@ -144,7 +144,11 @@ export interface BuildHalf {
144144
export interface QuestionResult {
145145
question: string;
146146
persona: string | null;
147-
/** Why this turn was not asked: its expected answer changes without the rows the seed could not load ({@link seedDependence}). Not measured, never a fail. */
147+
/**
148+
* Why this turn measures nothing: it was not asked, because its expected
149+
* answer changes without the rows the seed could not load ({@link seedDependence});
150+
* or it was replayed and the replay was not faithful (`ReplayNotFaithfulError`). Never a fail.
151+
*/
148152
notMeasured?: string;
149153
grade?: PersonaRunGrade;
150154
turn?: TurnSummary;
@@ -158,7 +162,9 @@ export interface OperationResult {
158162
* Why this operation is not measured: it was not run, because it acts on a
159163
* row the seed could not load ({@link seedDependence}); or it ran and its
160164
* grade measured nothing (`OperationGrade.notMeasured`: the build denies the
161-
* persona the write the card gives it, `buildDeniesWrite`). Never a fail.
165+
* persona the write the card gives it, `buildDeniesWrite`); or it was
166+
* replayed and the app did not answer its re-sent writes as it answered the
167+
* recorded run (`ReplayNotFaithfulError`). Never a fail.
162168
*/
163169
notMeasured?: string;
164170
/**
@@ -261,6 +267,9 @@ const summarize = (t: ParsedTurn): TurnSummary => {
261267

262268
const errText = (e: unknown) => (e instanceof Error ? e.message : String(e)).slice(0, 2000);
263269

270+
/** Why a replayed turn measures nothing ({@link ReplayNotFaithfulError}): what its read-back would grade is the replay's, not the agent's. */
271+
const replayNotFaithful = (e: ReplayNotFaithfulError): string => `the replay is not faithful: ${e.reason}`.slice(0, 2000);
272+
264273
/** `60 min`, `0.5 min`: a timeout as the not-measured reason states it. */
265274
export const minutesText = (ms: number): string => `${Number((ms / 60_000).toFixed(2))} min`;
266275

@@ -728,6 +737,12 @@ export async function runHalf(
728737
await seedApp(scenario, app, accounts, half.seed, requiredLookups(built)); // tallied in place, so a throw keeps the partial seed
729738

730739
const keyOf = (persona: string | null) => (persona === null ? adminKey : accounts.find((a) => a.persona === persona)!.apiKey);
740+
// The door a turn is given: the app's MCP endpoint as the persona, and the
741+
// runner's own call through it (a replay re-sends the recorded writes there).
742+
const doorOf = (persona: string | null): Pick<AskTask, 'mcp' | 'callTool'> => {
743+
const apiKey = keyOf(persona);
744+
return { mcp: { url: app.mcpUrl, apiKey }, callTool: (tool, args) => app.callTool(apiKey, tool, args) };
745+
};
731746
// A refused seed row makes what reads it not measured — never a fail of the app's answer.
732747
const dependence = seedDependence(scenario, half.seed.refused);
733748

@@ -741,7 +756,7 @@ export async function runHalf(
741756
continue;
742757
}
743758
try {
744-
const turn = await driver.ask({ ...ref, step: q.id, ...(persona ? { persona } : {}), prompt: questionPrompt(scenario, q.id), mcp: { url: app.mcpUrl, apiKey: keyOf(persona) } });
759+
const turn = await driver.ask({ ...ref, step: q.id, ...(persona ? { persona } : {}), prompt: questionPrompt(scenario, q.id), ...doorOf(persona) });
745760
res.turn = summarize(turn);
746761
res.grade = gradeCardAnswer(scenario, {
747762
question: q.id,
@@ -750,7 +765,10 @@ export async function runHalf(
750765
turn,
751766
});
752767
} catch (e) {
753-
res.error = errText(e);
768+
if (e instanceof ReplayNotFaithfulError) {
769+
res.turn = summarize(e.turn);
770+
res.notMeasured = replayNotFaithful(e);
771+
} else res.error = errText(e);
754772
}
755773
half.questions.push(res);
756774
}
@@ -766,7 +784,14 @@ export async function runHalf(
766784
try {
767785
const before = (await app.listRows(op.object)).rows as Row[];
768786
const started = new Date();
769-
const turn = await driver.ask({ ...ref, step: op.id, persona: op.actingAs, prompt: operationPrompt(card, op.id), mcp: { url: app.mcpUrl, apiKey: keyOf(op.actingAs) } });
787+
let turn: ParsedTurn;
788+
try {
789+
turn = await driver.ask({ ...ref, step: op.id, persona: op.actingAs, prompt: operationPrompt(card, op.id), ...doorOf(op.actingAs) });
790+
} catch (e) {
791+
if (!(e instanceof ReplayNotFaithfulError)) throw e;
792+
half.operations.push({ ...res, turn: summarize(e.turn), notMeasured: replayNotFaithful(e) });
793+
continue;
794+
}
770795
res.turn = summarize(turn);
771796
const after = (await app.listRows(op.object)).rows as Row[];
772797
// The card's today, the dates the app's clock read during the turn, and

0 commit comments

Comments
 (0)