Skip to content

feat(recorder): flag replays whose request no longer matches the recording - #640

Merged
jpr5 merged 5 commits into
mainfrom
feat/stale-fixture-detection
Nov 26, 2026
Merged

jpr5 merged 5 commits into
mainfrom
feat/stale-fixture-detection

Conversation

@jpr5

@jpr5 jpr5 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

What it does

Recorded fixtures used as a regression baseline could keep serving a stale reply after the app's
request changed (for example, a tool result going from {"refunded":500} to {"blocked":true}),
because the fixture still matched on userMessage / turnIndex / hasToolResult. Nothing showed it.

  • Recorder writes metadata.requestHash next to systemHash / toolsHash. It is a sha256
    (16 hex characters) of the canonical JSON of the request, taken after requestTransform. It covers
    the model (date suffix removed), messages, tools, customTools, tool_choice,
    response_format, temperature, max_tokens and embeddingInput. Headers, the stream flag,
    stream_options and the request context are not covered. The canonical form reuses the iterative
    canonicalJSON from chaos-random.ts, so key order and whitespace don't matter and deep bodies
    can't overflow the stack.
  • The hash is written only when the recorder already writes a metadata block (system prompt or
    tools present). Every other recording stays byte-identical to today.
  • Replay check happens once, at the end of the shared matcher (matchFixtureDiagnostic), so it
    covers every route that matches through it. When the served fixture has a requestHash and the
    request hashes differently, the journal entry gets
    response.staleFixture: { expected, actual }. The server logs one warning:
    STALE FIXTURE — POST /v1/chat/completions served fixture #0 { ... }, recorded on a different request (requestHash …, this request …); normalize changing content with requestTransform or re-record.
  • Serving is unchanged. There is no strict-miss option (left out, as the issue suggested).

Design proposed by @zhouxuandev in #638.

No-breaking-change guarantees and how each was verified

Guarantee Evidence
Same fixture, response, status and headers Parity run on main vs this branch (OpenAI chat, stream + non-stream): with a no-hash fixture and with a matching-hash fixture, the status, headers, body and journal entries are identical once random ids and ports are masked. A mismatching hash (positive control) adds only staleFixture and the warning.
Fixtures without the hash are never checked Tests: the issue's hand-written fixtures, and a recording with its hash removed, are never flagged.
Nothing new unless a hash exists and mismatches The parity runs show 0 staleFixture entries and 0 STALE log lines.
Existing tests pass with assertions unmodified Full pnpm test after pnpm build: the 8 recorder goldens, recorder.test.ts, A7 equivalence and policy-egress all pass unmodified. 6 CLI and timing files failed under full-suite load; each passes in isolation (none touch this change).
Older aimock loads new fixtures The hash lives in fixture metadata, which loaders copy through without checking its keys. 1.48.1 and 1.30.0 load and serve a fixture with requestHash, and aimock validate --strict (1.48.1) passes.
Public API additions only See the api-report delta below.

RED / GREEN (src/__tests__/stale-fixture.test.ts, real recorder + real HTTP)

RED on main (392f465):

× OpenAI chat completions > records a requestHash next to the other metadata hashes
× OpenAI chat completions > flags a replay whose tool result changed, and still serves the recording
× Anthropic messages (streamed) > records a requestHash ...
× Anthropic messages (streamed) > flags a replay whose tool result changed ...
× OpenAI Responses (streamed) > records a requestHash ...
× OpenAI Responses (streamed) > flags a replay whose tool result changed ...
Tests  6 failed | 9 passed (15)

GREEN on this branch:

✓ src/__tests__/stale-fixture.test.ts (15 tests)
Tests  15 passed (15)

Other cases: the unchanged request, key order and whitespace, a dated model name, a stream flag
change, a request with neither a system prompt nor tools (no hash, never flagged), and no-hash
fixtures. None of these are flagged.

Gates: pnpm build, pnpm typecheck, pnpm lint, prettier --check . and pnpm api:report are clean.

api-report delta (additions only, 14 reports)

     metadata?: {
         systemHash?: string;
         toolsHash?: string;
+        requestHash?: string;
     };
 ...
         recordSkipped?: string;
+        staleFixture?: {
+            expected: string;
+            actual: string;
+        };

Limitation

Content that changes on every run (dates, random IDs) must be normalized with requestTransform.
Otherwise every replay of that fixture is flagged. This is documented in the record/replay docs.

Closes #638

🤖 Generated with Claude Code

https://claude.ai/code/session_01Jay9vBCbXhVHCDgyRBABVx

jpr5 added 4 commits November 25, 2026 20:33
…ding

A served fixture with metadata.requestHash is compared with the request's
hash in the shared matcher. On a mismatch the journal entry gets
response.staleFixture { expected, actual } and the server logs one
STALE FIXTURE warning. Serving is unchanged; fixtures without the hash
are never checked. api-report: additions only.

Design proposed by @zhouxuandev in #638.
The hash covers model (date suffix removed), messages, tools,
customTools, tool_choice, response_format, temperature, max_tokens and
embeddingInput, after requestTransform, in canonical JSON. It is written
only when the metadata block already is (system prompt or tools), so
other recordings stay byte-identical.

Design proposed by @zhouxuandev in #638.
@jpr5 jpr5 added the public-api-addition Intended public API report changes reviewed for compatibility; freshness remains required label Nov 26, 2026
@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@copilotkit/aimock@640

commit: 0cdf15b

Tool-call ids are no longer hashed. The Responses, Cohere and Gemini
Interactions converters make up random ids for tool calls sent without
one, so every replay was flagged stale. Names, arguments and tool-result
content are still hashed.

Hashing now never throws: a requestTransform result with a circular
reference or a BigInt skips the stale check with one warning, and the
request is served and recorded as before, with no requestHash written.

The HASHED_FIELDS comment now lists exactly what the hash covers.
@jpr5
jpr5 merged commit b5499e2 into main Nov 26, 2026
30 checks passed
@jpr5
jpr5 deleted the feat/stale-fixture-detection branch November 26, 2026 05:09
jpr5 added a commit that referenced this pull request Dec 1, 2026
## Why

#618 added three flat journal fields for seeded chaos hits: `chaosSeed`,
`chaosKey` and `chaosOccurrence`. They have not shipped yet (the last
release is 1.48.1), so grouping them now costs nobody anything. One
`chaosOrigin` object reads better next to `chaosAction` and matches how
#640 put `staleFixture: { expected, actual }` in the same `response`
block.

## What changed

- `src/types.ts`: `JournalEntry.response` drops the three flat fields
and gains `chaosOrigin?: { seed: string; key: string; occurrence: number
}`.
- `src/chaos.ts`: `applyChaosAction` writes `{ chaosOrigin: { seed, key,
occurrence } }`. It still does this only for a seeded hit. An unseeded
hit gets nothing, as before.
- `docs/chaos-testing/index.html`: the journal field docs describe the
nested shape.
- `etc/*.api.md`: regenerated with `pnpm build && pnpm api:report`. This
changes the public report, so the PR needs the `public-api-addition`
label. Nothing released is affected.
- Tests: `chaos-seed.test.ts`, `chaos-seed-core-fixes.test.ts` and
`chaos-seed-key-fixes.test.ts` read `chaosOrigin` now. They also check
that the old flat fields are gone. A new test checks that an unseeded
hit journals no `chaosOrigin`.

Not changed: the `x-aimock-chaos-*` response headers, `chaosKeysMax`,
`chaosKeyFor` / `chaosOccurrencesFor`, and the CHANGELOG line for #618
(it does not name the fields). Nothing in `packages/aimock-pytest` reads
these fields.

## Red / green

The tests start a real aimock server with `chaos: { dropRate: 1, seed:
... }` and read the journal.

**Red** (new assertions, source unchanged):

```
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/__tests__/chaos-seed-core-fixes.test.ts > finding 1: a reported seed replays byte-for-byte through the seed header > a seed header carrying a comma is not silently shortened
AssertionError: expected { Object (status, fixture, ...) } to match object { chaosAction: 'drop', …(1) }
(8 matching properties omitted from actual)

- Expected
+ Received

  {
    "chaosAction": "drop",
-   "chaosOrigin": {
-     "seed": "run",
-   },
  }

 ❯ src/__tests__/chaos-seed-core-fixes.test.ts:149:56
    147|     expect(reply.status).toBe(500);
    148|     expect(reply.headers[SEED_HEADER]).toBe("run");
    149|     expect(instance.journal.getAll().at(-1)?.response).toMatchObject({
       |                                                        ^
    150|       chaosAction: "drop",
    151|       chaosOrigin: { seed: "run" },

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯

 FAIL  src/__tests__/chaos-seed.test.ts > seeded chaos: reporting on a chaos hit > puts the seed, key and occurrence on the response and in the journal
AssertionError: expected undefined to deeply equal { seed: 'report', …(2) }

- Expected: 
{
  "key": "1d100c5c22cca62f",
  "occurrence": 0,
  "seed": "report",
}

+ Received: 
undefined

 ❯ src/__tests__/chaos-seed.test.ts:339:41
    337|     const entry = instance.journal.getAll().at(-1);
    338|     expect(entry?.response.chaosAction).toBe("drop");
    339|     expect(entry?.response.chaosOrigin).toEqual({
       |                                         ^
    340|       seed: "report",
    341|       key: probe.headers[KEY_HEADER],

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯
```

**Green** (after the change):

```
 ✓ chaos-seed-core-fixes.test.ts > finding 1 > a seed header carrying a comma is not silently shortened
 ✓ chaos-seed-core-fixes.test.ts > finding 2 > applyChaos: seeded decision then unseeded hit in one scope reports no seed and uses Math.random
 ✓ chaos-seed-core-fixes.test.ts > finding 2 > split gate: seeded then unseeded evaluateChaos, then applyChaosAction, reports no seed
 ✓ chaos-seed.test.ts > seeded chaos: reporting on a chaos hit > puts the seed, key and occurrence on the response and in the journal
 ✓ chaos-seed.test.ts > seeded chaos: reporting on a chaos hit > an unseeded chaos hit journals no chaosOrigin
 ✓ chaos-seed.test.ts > seeded chaos: reporting on a chaos hit > keys the request by its body, not by headers
      Tests  43 passed (43)
```

`chaos-seed-key-fixes.test.ts > the journal entry carries the same
client-body key` also passes after it moved to `chaosOrigin?.key`.

## Checks

Build, typecheck, eslint and prettier pass. `api:report` reports 14
entries and 0 failures, and `etc/` matches what is committed. In the
full unit suite, 20344 tests pass and 2 fail. Neither failure comes from
this change:
- `response-a9-equivalence`: it needs 2 GiB of free memory. It fails the
same way on unmodified `main` on this machine.
- `multimedia > gpt-transcribe stream ... separate SSE frames`: a timing
check that failed under full-suite load. It passes 3 of 3 times when run
alone.
@jpr5 jpr5 mentioned this pull request Dec 1, 2026
jpr5 added a commit that referenced this pull request Dec 1, 2026
## [1.49.0] - 2026-11-30

### Added

- Replayable seeded chaos: `--chaos-seed`/`x-aimock-chaos-seed`; journal `chaosOrigin` (#618, #653)
- Recorder writes `requestHash`; stale replays get journal `staleFixture` and a warning (#640, #651)

### Changed

- `aimock-pytest` 0.7.4 defaults to `@copilotkit/aimock` 1.49.0

### Fixed

- Split image turns match `userMessage` on Anthropic, Gemini (+Live), Bedrock, Cohere (#643, #648)
- `llmock` now errors on blank `--port`/`--host`/`--latency`/... values instead of starting (#644)
jpr5 added a commit that referenced this pull request Dec 1, 2026
**Merging this publishes @copilotkit/aimock 1.49.0 to npm and
aimock-pytest 0.7.4 to PyPI.**

## [1.49.0] - 2026-11-30

### Added

- Replayable seeded chaos: `--chaos-seed`/`x-aimock-chaos-seed`; journal
`chaosOrigin` (#618, #653)
- Recorder writes `requestHash`; stale replays get journal
`staleFixture` and a warning (#640, #651)

### Changed

- `aimock-pytest` 0.7.4 defaults to `@copilotkit/aimock` 1.49.0

### Fixed

- Split image turns match `userMessage` on Anthropic, Gemini (+Live),
Bedrock, Cohere (#643, #648)
- `llmock` now errors on blank `--port`/`--host`/`--latency`/... values
instead of starting (#644)

Two new features, so this is a minor release.

## Version carriers (from `git grep -F 1.48.1`)

Bumped to 1.49.0:
- `package.json` version
- `charts/aimock/Chart.yaml` appVersion
- `.claude-plugin/plugin.json` version
- `.claude-plugin/marketplace.json` source version (`^1.49.0`)
- `docs/index.html` banner
- `packages/aimock-pytest/README.md` `--aimock-version` default
- `packages/aimock-pytest/src/aimock_pytest/_version.py`
`AIMOCK_VERSION`

Also bumped: `packages/aimock-pytest/pyproject.toml` 0.7.3 → 0.7.4,
because the pin moved (same pattern as #628).

Left as is: the `## [1.48.1]` CHANGELOG section.

## CHANGELOG edits

- `## [Unreleased]` becomes `## [1.49.0] - 2026-11-30`.
- Seven bullets became four, plus the aimock-pytest `Changed` line: the
two #618 lines are one, #643 and #648 are one, and #651 joins the
stale-fixture line.
- The stale-fixture line now references PR #640 instead of issue #638.

## Docs

- `docs/record-replay`: the `llmock` flag table gets `--chaos-seed` and
`--chaos-keys-max`, and a note that blank
`--port`/`--host`/`--latency`/`--journal-max`/`--fixture-counts-max`
values are a usage error (#644).
- `docs/fixtures`: the "last user message" rule now says a trailing
image-only user message is skipped (#643, #648).
- `README.md`: the Record & Replay line mentions stale-fixture flagging.
Seeded chaos was already in the Chaos Testing line.

Already covered, left alone: `docs/chaos-testing` (seeds,
`x-aimock-chaos-seed`, `chaosOrigin`, `--chaos-keys-max`) and the Stale
Fixtures section of `docs/record-replay` (`requestHash`, `staleFixture`,
the `STALE FIXTURE` warning, `requestTransform`). The `package.json`
description already matches the README subtitle.

## Local checks
- `pnpm install --frozen-lockfile`, `format:check`, `lint`, `typecheck`,
`build`: pass
- `api:report`: 14 entries, 0 failed, no report change
- `vitest run`: 503 files, 20,346 passed, 11 skipped
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

public-api-addition Intended public API report changes reviewed for compatibility; freshness remains required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recorded turn still gets served after the tool result changes, nothing in the journal

1 participant