Skip to content

feat: reproducible chaos verdicts keyed per request and per action kind - #618

Draft
AnshulBhati01 wants to merge 33 commits into
CopilotKit:mainfrom
AnshulBhati01:contrib/aimock-reproducible-chaos
Draft

AnshulBhati01 wants to merge 33 commits into
CopilotKit:mainfrom
AnshulBhati01:contrib/aimock-reproducible-chaos

Conversation

@AnshulBhati01

@AnshulBhati01 AnshulBhati01 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

What and why

Chaos verdicts (dropRate, malformedRate, rateLimitRate, disconnectRate) are decided with Math.random(). A CI failure caused by an injected fault cannot be replayed.

This PR adds an opt-in chaos seed. With a seed, each verdict is a pure function of:

  • the seed;
  • the request identity key: method, raw target (query included) and a canonical hash of the parsed body (JSON key order ignored, headers excluded);
  • the action kind, each kind on its own draw stream;
  • a per-key occurrence counter, namespaced by testId and seed.

So the same seed and the same requests give the same faults on a fresh server, and unrelated requests do not shift each other's verdicts. The drop → malformed → rateLimit → disconnect order and the first-hit-wins rule are unchanged, so the rates mean exactly what they meant before. Seeded streaming jitter (streamingProfile.jitter) is drawn from the seed too. latencyMs was already fixed and is unchanged.

A seed can come from:

  • x-aimock-chaos-seed (request header);
  • fixture chaos.seed;
  • server chaos.seed (programmatic or llm.chaos.seed in the config file);
  • --chaos-seed (CLI);
  • POST /__aimock/chaos {"seed": ...} (GET echoes it).

The precedence is header > fixture > server. A seed is a finite number (used as its decimal string) or 1–128 visible ASCII characters with no spaces.

A seeded chaos hit reports x-aimock-chaos-seed, x-aimock-chaos-key and x-aimock-chaos-occurrence on the response, except on a disconnect. The journal entry gets chaosSeed, chaosKey and chaosOccurrence.

History and credit

The design and initial implementation are by @AnshulBhati01: the first commit on this branch (c02fc6a), kept unchanged under their authorship. It was based on a commit 806 behind main, so we merged current main into this branch (conflicts resolved in favor of main) and added our commits on top, as our own:

  1. feat(chaos): seeded, keyed chaos verdicts and jitter (core)
  2. feat(chaos): wiring through the server, CLI, control API and reset
  3. test(chaos): tests (replaces the hash-suffixed suites and manifest)
  4. docs(chaos): docs

Our commits re-implement the feature against main's current chaos code and remove the superseded files. Earlier this work was opened as #633, which is now closed in favor of this PR.

How the four decisions are handled

  1. No breaking changes. Without a seed there is no observable difference from main:

    The test unseeded chaos is unchanged proves this on a real server. It checks for no x-aimock-chaos-* header, an unchanged set of journal response keys, no new /metrics series, and one Math.random draw per configured rate.

  2. Proxy/record malformed keeps main's behavior. The proxy path is not restructured. Only how the verdict is drawn changes. proxy-only.test.ts passes with no changes.

  3. Bounded memory. ChaosOccurrenceRegistry holds at most chaosKeysMax counters per server. The default is 10,000; set it with the chaosKeysMax server option or --chaos-keys-max. Eviction is LRU. Counters are cleared:

    • per testId on POST and DELETE /__aimock/chaos;
    • entirely on POST /__aimock/reset.

    Unseeded chaos keeps no counters. The cap is documented on the chaos-testing page.

  4. Integration with current chaos.

    • There is one choke point: evaluateChaos, reached through applyChaosAsync/applyChaos and the split gates in server.ts. rateLimit, latencyMs, ChaosScope/testId scoping and the runtime control all work with seeds.
    • The seeded jitter source reaches the stream writers through a per-request AsyncLocalStorage scope (the same pattern as requestScope).
    • The realtime-transcription WebSocket path, the one WS path that applies streamingProfile jitter, resolves its seed directly.
    • chaos-async-call-sites.test.ts is unchanged: chaos.ts exports no new values.

RED (current main, new tests)

× two fresh servers with the same seed produce the same verdict sequence
✓ different seeds give different sequences            (passes by chance on random draws)
× accepts a numeric seed and treats it as its decimal string
× an unrelated request inserted mid-sequence does not change the keyed verdicts
× raising one rate does not reshuffle which requests another rate picks
× the x-aimock-chaos-seed header seeds an otherwise unseeded server
× the header seed overrides the server seed
× a fixture seed overrides the server seed
× the runtime control sets, echoes and replays the seed      (400 Unknown chaos field 'seed')
✓ the runtime control rejects an unusable seed with 400      (regression guard)
× re-installing chaos through the runtime control rewinds the sequence
× a full reset rewinds the sequence
× without a reset the sequence moves on rather than repeating
× respects chaosKeysMax: the least recently used key is evicted first
× puts the seed, key and occurrence on the response and in the journal
× keys the request by its body, not by headers
× replays on the Anthropic messages and embeddings endpoints
× a seeded stream draws its jitter from the seed, not Math.random   (Math.random called 15 times)
✓ unseeded: adds no header, journal field or metric                 (parity guard)
✓ unseeded: still decides through Math.random, one draw per rate    (parity guard)
× two CLI servers started with the same --chaos-seed replay the same verdicts  (Unknown option '--chaos-seed')
Tests  17 failed | 4 passed (21)

GREEN (this branch)

  • chaos-seed.test.ts: 21/21 pass. This runs on the real server through createServer, the built CLI, the runtime control, the header, fixture seeds, Anthropic /v1/messages and /v1/embeddings.
  • chaos-random.test.ts: 12/12 pass. It covers the registry cap/LRU/clearScope, key canonicalization, uniformity of the draws and the seeded jitter band.
  • Full suite: 493 files, 20165 passed, 11 skipped, 0 failed. No existing test was modified.
  • pnpm build, pnpm typecheck, pnpm lint, pnpm format:check and pnpm api:report are all clean.

API report

The changes are additions only, with no removed or changed signatures:

  • ChaosConfig.seed?: string | number
  • JournalEntry.response.chaosSeed? / chaosKey? / chaosOccurrence?
  • MockServerOptions.chaosKeysMax?
  • the chaos? option on the handleWebSocketRealtime defaults
  • the constants CHAOS_SEED_HEADER, CHAOS_KEY_HEADER and CHAOS_OCCURRENCE_HEADER

evaluateChaos and calculateDelay keep their exact signatures.

jpr5 added 5 commits November 23, 2026 11:21
A chaos seed makes every verdict a pure function of the seed, the
request identity key (method, raw target and canonical body hash), the
action kind and a per-key occurrence counter. The same seed and the same
requests give the same faults on a fresh server, and unrelated requests do
not shift each other's outcomes. Seeded streaming jitter is drawn the same
way.

Without a seed nothing changes: evaluateChaos keeps the same
Math.random() draws in the same order, and no header, journal field or
metric is added.

The per-server occurrence registry is bounded (default 10,000 counters,
LRU eviction) and namespaced by testId.

Design and initial implementation by @AnshulBhati01 in CopilotKit#618.
- x-aimock-chaos-seed header, fixture chaos.seed and server chaos.seed,
  with the usual header > fixture > server precedence
- --chaos-seed and --chaos-keys-max CLI flags; chaosKeysMax server option
- POST /__aimock/chaos accepts and GET echoes seed; POST/DELETE restart
  that testId's seeded sequences, and a full reset restarts them all
- per-request scope carries the seeded jitter source to the stream
  writers; the realtime transcription WebSocket path seeds its jitter too
- export CHAOS_SEED_HEADER, CHAOS_KEY_HEADER, CHAOS_OCCURRENCE_HEADER;
  regenerate the API reports (additions only)
- keep main's proxy/record malformed behavior (call upstream, record the
  real response, corrupt the relay) in recorder.ts; drop the auto-seed
  (LLMock.chaosSeed) and the fal.ts identity plumbing, which the
  per-request scope replaces. Unseeded chaos is unchanged.

Design and initial implementation by @AnshulBhati01 in CopilotKit#618.
Scenarios adapted from CopilotKit#618 by @AnshulBhati01 into chaos-seed.test.ts and
chaos-random.test.ts, against main's chaos APIs. The hash-suffixed suites
and manifest from CopilotKit#618 are replaced by these. proxy-only.test.ts returns
to main's assertions, since main's proxy malformed behavior is kept.
@jpr5 jpr5 added the public-api-addition Intended public API report changes reviewed for compatibility; freshness remains required label Nov 23, 2026
@jpr5

jpr5 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Thanks @AnshulBhati01, this is a really nice design: keyed draws, a separate stream per action kind and per-key occurrences made it easy to carry forward. The branch was 800+ commits behind main, so we merged current main into it and rebuilt the feature on top of your commit, which stays here unchanged under your name. Our commits follow it. Main changes from your version: no auto-generated seed (unseeded chaos stays exactly as it was), main's proxy malformed behavior is kept, and the per-key counters are capped. The PR description has the details.

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

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

commit: 515b82b

jpr5 added a commit to AnshulBhati01/aimock that referenced this pull request Nov 23, 2026
Say which inputs a replay needs (X-Test-Id, request bodies and the chat
X-AIMock-Context value), exactly which counters each reset rewinds, that
seeded jitter only reaches SSE streaming and live transcription, and
that seeds are trimmed strings without commas. The changelog entry now
covers the whole surface added by CopilotKit#618.
jpr5 added a commit to AnshulBhati01/aimock that referenced this pull request Nov 23, 2026
… now work

Wording only; no code changes.

- docs page: the occurrence is scoped by X-Test-Id or ?testId=; a replay
  needs the same fixtures and chaosKeysMax; setChaos, clearChaos and
  resetChaosOccurrences restart sequences; the Docker tab shows --chaos-seed.
- chaos-random.ts: jitter draws by chunk index, not occurrence; testId scopes
  the occurrence; identity recording names readBody and the split gates; the
  reset-isolation claim is limited to testId-scoped resets.
- chaos.ts: an unseeded verdict clears seeded request state; the unseeded
  seed lookup is described as it is; evaluateChaos says each seeded call
  consumes an occurrence.
- CHANGELOG: add (CopilotKit#618) to the second Unreleased bullet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jay9vBCbXhVHCDgyRBABVx
jpr5 added 18 commits November 23, 2026 16:09
validateFixtures read fields off fixture.chaos unchecked, so chaos: null threw a TypeError and
--validate-on-load crashed. chaos: null is now a validation error. An array or primitive, which
validated clean and is ignored at request time, gets a warning so it stays loadable.
…ed jitter

Raise dropRate (rolled before malformed) and compare the spared requests, assert same-seed jitter
replays and unseeded jitter uses Math.random, send null honestly and cover a non-finite server seed,
and fail instead of skipping when dist/cli.js is missing or stale.
… header

A seed could contain a comma, but the x-aimock-chaos-seed request header is
split on commas like every other chaos header. Replaying a reported seed such
as "run,7" through the header silently used "run".

Forbid commas in the seed grammar instead of special-casing the header. The
rate headers treat a comma as the separator between repeated values, and Node
folds a repeated header into one comma-joined string, so the seed header
cannot tell "run,7" from two headers "run" and "7". With commas out of the
grammar, the one gate (normalizeChaosSeed) rejects them at every entry point:
config and fixture chaos, --chaos-seed, the header and POST /__aimock/chaos.
The response echo writes the normalized seed, so every seed the server
reports now replays byte-for-byte through the header.

The seed header now also warns on a repeat with conflicting values, the same
way and in the same words as the rate headers. Both share one reader.
Unseeded requests are unchanged: with no seed header, nothing new is read or
logged.

Changed symbols and call sites (grep; the TypeScript LSP timed out on
findReferences in this worktree):
- normalizeChaosSeed (grammar only): chaos.ts readSeed, readSeedHeader,
  decideChaos; server.ts control API and default-seed check; cli.ts
  --chaos-seed; fixture-loader.ts validation; ws-realtime.ts realtime jitter.
- firstRepeatedHeaderValue (new, private): firstHeaderValue, readSeedHeader.
- firstHeaderValue: readHeaderField.
- readSeedHeader (now takes a logger): resolveChaosConfig.
applyChaos passed `origin: undefined` for an unseeded hit to
applyChaosAction, whose default parameter (currentChaosOrigin()) then read
the request scope. decideChaos never cleared that scope, so after a seeded
verdict earlier in the same request an unseeded hit reported the old seed,
key and occurrence (response headers and journal fields) and streamed with
the old seeded jitter. The split gates in server.ts (evaluateChaos, then
applyChaosAction with no origin) had the same hole. That broke the rule that
unseeded chaos is identical to main.

decideChaos now clears the scope's seeded origin and jitter on an unseeded
verdict (clearRequestChaosSeeding). After that, an undefined origin falls
back to an empty scope on both paths, and sse-writer's currentChaosJitter()
returns undefined, so jitter is Math.random(). For a request that was never
seeded the clear is a no-op, so unseeded traffic does exactly what it did
before. applyChaosAction keeps its signature, its scope default and its body
(the A8/A13 source-ownership tests read that body).

Changed symbols and call sites (grep; the TypeScript LSP timed out on
findReferences in this worktree):
- clearRequestChaosSeeding (new, chaos-random.ts, not in the barrel):
  decideChaos.
- decideChaos: evaluateChaos, applyChaos.
- Readers of the cleared state: currentChaosOrigin (applyChaosAction default,
  used by applyChaos and the six server.ts split-gate calls) and
  currentChaosJitter (sse-writer.ts calculateDelayWithJitter).
… seed

The occurrence registry used by callers without a server (evaluateChaos or
the deprecated applyChaos with a plain ChaosConfig that carries a seed) was a
process-global that nothing could clear. A direct caller could not rewind its
seeded sequence, so a fresh run in the same process did not replay the same
verdicts.

Move that registry next to the per-server registries in chaos-random.ts
(fallbackChaosOccurrences) and add resetChaosOccurrences(), exported from the
package barrel. It is deliberately NOT called by a server reset: server
counters are rewound by performFullReset and POST /__aimock/chaos already,
and clearing the process-wide registry from one server's reset would rewind
every other embedder's sequence (the same cross-talk the per-server warning
latch avoids). The registry lives outside chaos.ts so the chaos call-site
guard's export classification is unchanged.

Public API: additive only. etc/*.api.md gains
`export function resetChaosOccurrences(): void;` and nothing else.

Changed symbols and call sites (grep; the TypeScript LSP timed out on
findReferences in this worktree):
- resetChaosOccurrences (new): src/index.ts barrel; new tests.
- fallbackChaosOccurrences (moved from chaos.ts fallbackOccurrences):
  chaos.ts occurrencesFor (two returns); resetChaosOccurrences.
- occurrencesFor: decideChaos.
decideChaos normalizes a seed handed in through the `resolved` argument, but
an invalid one silently fell back to Math.random(). Read it through readSeed
instead, so it warns exactly like every other rejected seed ("[chaos]
resolved chaos config: rejected seed ...; ignoring it"). Behaviour is
otherwise unchanged: the verdict stays unseeded and rolls Math.random().

The warning is not latched, because a `resolved` config is per-call input
like a header. A config that resolveChaosConfig produced has an already
normalized seed, so server traffic gains no new log line.

Changed symbols and call sites (grep; the TypeScript LSP timed out on
findReferences in this worktree):
- readSeed (new caller): resolveChaosConfig (header, fixture, server levels)
  and now decideChaos.
- decideChaos: evaluateChaos, applyChaos.
The live transcription turn resolved its chaos seed from the upgrade
headers only, so a socket tagged with ?testId= (instead of X-Test-Id)
got the baseline seed rather than its test's. Pass a URL that carries
the socket's resolved testId, the way the misbehavior planner in the
same file already does, so both tagging styles resolve one scope.

Gemini-live and responses-over-WebSocket do not resolve chaos config, so
they have no such omission.

Changed call: resolveChaosConfig in emitLiveTranscriptionEvents
(src/ws-realtime.ts), reached from processMessage <- handleWebSocketRealtime
<- server.ts upgrade handler (REALTIME_PATH).

Tests: src/__tests__/chaos-seed-realtime-fixes.test.ts (real sockets).
The realtime upgrade handler spread the server defaults, which read the
`chaos` getter once at connect. A socket opened while an untagged seed
override was installed kept that seed after POST /__aimock/reset (or an
untagged DELETE /__aimock/chaos), because the snapshot's `base` still
held it. Pass a getter instead, so each turn reads the scope in effect
now, the way the HTTP routes resolve per request. Unseeded chaos never
reads it on this path, so unseeded behavior is unchanged.

Changed: the handleWebSocketRealtime call in the server.ts upgrade
handler (REALTIME_PATH). Its only reader of `chaos` is
emitLiveTranscriptionEvents (src/ws-realtime.ts). The gemini-live and
responses-over-WebSocket handlers do not read `chaos`.
…reate

handleResponseCreate declared a `chaos` field whose comment said it read
the seed for streaming jitter, but nothing read it: realtime
response.create, like gemini-live and responses-over-WebSocket, paces
frames by latency and recorded timings only and never applies a
streaming profile, so it draws no jitter, seeded or not. Remove the
field, and say in the remaining comments that live transcription is the
one WebSocket turn with jitter. No behavior change.

Seeded jitter on WebSocket turns was already complete: the only
WebSocket jitter draw (live transcription) uses the seed. Tests in
chaos-seed-realtime-fixes.test.ts pin that the other three transports
draw no jitter, with and without a seed.

Changed symbols and their call sites:
- handleResponseCreate (defaults type): called once, from processMessage in
  src/ws-realtime.ts (the response.create branch).
- processMessage / emitLiveTranscriptionEvents / handleWebSocketRealtime
  (comment only on their `chaos` field): handleWebSocketRealtime is
  called from the server.ts upgrade handler.
- calculateDelayWithJitter (comment only): called from
  emitLiveTranscriptionEvents and calculateDelay (src/sse-writer.ts).
…eline changes

An untagged POST or DELETE of /__aimock/chaos changes the server-wide
baseline, but it rewound the seeded occurrence counters of the default
testId only. A tagged testId with no override of its own runs on that
baseline and kept its old counts, so re-installing the same seed did not
replay its run.

The untagged control now clears the counters of the default scope and of
every testId that has no override of its own. A testId with its own
override keeps its counters, because the baseline change does not reach
it. Tagged control calls are unchanged. Unseeded chaos never reads the
counters, so it is unaffected.

Changed symbols and their call sites:
- rewindChaosOccurrences (new, src/server.ts): DELETE /__aimock/chaos and
  POST /__aimock/chaos handlers in src/server.ts.
- clearBaselineChaosOccurrences (new, src/chaos-random.ts):
  rewindChaosOccurrences in src/server.ts.
- ChaosOccurrenceRegistry.clearScopesWhere (new): clearScope and
  clearBaselineChaosOccurrences in src/chaos-random.ts.
- ChaosOccurrenceRegistry.clearScope (now delegates, same behavior):
  clearChaosOccurrences in src/chaos-random.ts; chaos-random.test.ts.
…the HTTP control

The defaults.chaos setter is how LLMock.setChaos and LLMock.clearChaos
change chaos on a running server. Unlike POST and DELETE /__aimock/chaos it
never cleared the seeded occurrence counters, so calling setChaos again
with the same seed continued the old sequence instead of replaying it.

The setter now clears counters the same way the HTTP control does:
assigning undefined (clearChaos, and the full reset) clears every
counter, and a baseline assignment (setChaos) clears the default scope and
every testId that inherits the baseline. Unseeded chaos never reads the
counters, so it is unaffected.

Changed symbols and their call sites:
- defaults.chaos setter (createServer, src/server.ts): LLMock.setChaos and
  LLMock.clearChaos in src/llmock.ts; performFullReset in src/server.ts
  (assigns undefined, then clears all counters itself; now a no-op repeat).
- clearBaselineChaosOccurrences, clearChaosOccurrences (src/chaos-random.ts):
  new call sites in the setter above.
…equests as bodiless

The two fal chaos gates (the x-fal-target-host gate and the
/fal/queue/requests gate) built a seeded request's identity key from the
raw body text. Every other route keys by the parsed body, so on fal the
same JSON with a different key order or whitespace got a different key.
The queue-requests gate also keyed a bodiless GET as if its body were
"{}", the stand-in it passes to handleFalQueue.

Both gates now key by the parsed body through falChaosBody. An empty body
is keyed as bodiless, and a GET on the queue-requests gate is keyed as
bodiless, the same as other routes. A body that is not JSON keeps its raw
text, so it still gets a stable key. The identity is only read when a
seed is set, so unseeded chaos is unaffected.

Changed symbols and their call sites:
- falChaosBody (new, src/server.ts): the x-fal-target-host chaos gate and
  the /fal/queue/requests chaos gate in createServer's request handler.
- setRequestChaosIdentity (unchanged): same two gates, now passed the
  parsed body.
… seeded chaos hit

Access-Control-Expose-Headers did not name x-aimock-chaos-seed,
x-aimock-chaos-key or x-aimock-chaos-occurrence, so a cross-origin browser
harness could not read the origin of a seeded chaos verdict.

The server-wide expose list is a static header sent on EVERY response, and
its exact value is asserted by existing tests and about 700 golden
snapshots. Adding the names there is additive in meaning, but it changes
the bytes of every unseeded response, which the no-breaking-change rule
for this feature does not allow. So the names are appended only on a
seeded chaos hit, the one response that carries these headers, in the
same place that sets them (applyChaosAction). A response with no expose
list (no CORS) is left alone. An unseeded response keeps the exact
value "X-Total-Count, X-Request-Id"; a new test checks that.

Changed symbols and their call sites:
- exposeChaosOriginHeaders (new, src/chaos.ts): applyChaosAction, on a
  seeded verdict whose headers are not yet sent.
- applyChaosAction (src/chaos.ts, signature unchanged): applyChaos in
  src/chaos.ts; handleCompletions in src/server.ts (4 sites); the
  x-fal-target-host and /fal/queue/requests chaos gates in src/server.ts.
Two fallbacks in the seeded chaos key registry were silent. An invalid
chaosKeysMax (not a positive integer) quietly became 10000, and hitting
the key cap evicted the least recently used key, restarting its count at
occurrence 0, with no log.

ChaosOccurrenceRegistry now takes the server logger. An invalid
chaosKeysMax is warned once, at construction, with the default it falls
back to. An eviction is warned once per burst: the first eviction warns,
then further evictions stay quiet until a clear takes the registry below
its cap again, so a server pinned at the cap does not log on every
request. Both use the existing "[chaos] ..." logger.warn style. No metrics
are added. The CLI already rejects an invalid --chaos-keys-max, so only
the programmatic option can reach the first warning. The registry only
fills on seeded requests, so unseeded chaos never logs either line.

Changed symbols and their call sites:
- ChaosOccurrenceRegistry constructor (new optional logger parameter):
  startServer in src/server.ts (passes the server logger); the
  fallbackOccurrences registry in src/chaos.ts (no logger, unchanged);
  src/__tests__/chaos-random.test.ts.
- ChaosOccurrenceRegistry.next: ChaosOccurrenceRegistry users via
  decideChaos in src/chaos.ts.
- ChaosOccurrenceRegistry.clear / clearScopesWhere (now re-arm the
  eviction warning): clearChaosOccurrences, clearScope and
  clearBaselineChaosOccurrences in src/chaos-random.ts.
Correct comments that drifted from the implementation: body keys come
from the parsed body (raw text for non-JSON), what an unseeded request
still touches, jitter indexed by chunk, separator no-overlap reasoning
for every hashed field, String(number) seed form, seeded draws in
evaluateChaos, the applyChaosAsync outcome, the bodiless-GET fallback
key and occurrence use at rate 0, and seed in the validation docs. The
rejected-seed warning reads its length from MAX_CHAOS_SEED_LENGTH; its
text is unchanged.
Say which inputs a replay needs (X-Test-Id, request bodies and the chat
X-AIMock-Context value), exactly which counters each reset rewinds, that
seeded jitter only reaches SSE streaming and live transcription, and
that seeds are trimmed strings without commas. The changelog entry now
covers the whole surface added by CopilotKit#618.
…racters

The canonical key form encoded a non-JSON body as one JSON string, so the
raw text hello and the JSON string "hello" got one key and shared one
occurrence counter. Raw text is now tagged `text:` before hashing
(ChaosRequestIdentity.rawText), so the two kinds can never meet. JSON keys
are unchanged.

chaosBodyFromRaw replaces the fal-only falChaosBody: empty text is no body,
JSON is parsed (null stays null), and anything else is raw text.

Call sites: src/server.ts x-fal-target-host gate and queue-requests gate.
applyChaos keyed a seeded verdict by the journal body, which on most routes
is the translated request: it carries _endpointType and _context, the latter
copied from the X-AIMock-Context header. Two identical requests with
different context headers got different keys and verdicts.

readBody now records the request body text in the chaos request scope (first
read wins; server requests only; multipart skipped, its boundary is random).
decideChaos, the one function every seeded verdict passes through, builds the
key from it via chaosKeyIdentity. With no recorded body (binary and multipart
routes, bodiless GETs) the caller's body is used with top-level _ fields left
out. This also fixes JSON null vs no body: the recorded "null" keys as null on
applyChaos routes and split gates alike; only an empty body is bodiless.

Unseeded requests are unchanged: the recorded text is read only for a seed.

Call sites covered through decideChaos: applyChaos / applyChaosAsync callers
in server.ts, messages.ts, responses.ts, bedrock.ts, bedrock-converse.ts,
cohere.ts, gemini.ts, gemini-interactions.ts, gemini-embeddings.ts,
embeddings.ts, ollama.ts, images.ts, speech.ts, transcription.ts,
audio-pipeline.ts, elevenlabs-*.ts, fal-audio.ts, batches.ts, fine-tuning.ts,
vector-stores.ts and the video modules; split gates in server.ts
(chat completions, x-fal-target-host, fal queue-requests).
jpr5 and others added 9 commits November 23, 2026 16:09
The key included the raw URL, so a test tagged by ?testId=x got a different
key, and a different verdict sequence, from the same test tagged by the
X-Test-Id: x header. chaosKeyIdentity now builds the key path with
chaosKeyPath, which drops every testId query parameter (name compared
percent-decoded, + as space, like resolveTestId) and keeps the others in
order as sent.

Docs: the chaos-testing page described the old key (query string included,
X-AIMock-Context hashed on chat completions); it now matches the code.

Adds src/__tests__/chaos-seed-key-fixes.test.ts (real server, seeded), which
covers all four key findings of CR round 2: X-AIMock-Context on chat
completions, messages and cohere; ?testId= vs X-Test-Id; JSON null vs no
body on /v1/batches and the fal split gate; raw text vs JSON string.

Call sites: decideChaos (every seeded verdict: applyChaos, applyChaosAsync,
evaluateChaos split gates in server.ts) via chaosKeyIdentity.
Number() accepted 0x10, 1e3 and " 5 " as valid key caps. The flag now uses
parseStrictIntegerText, the integer grammar --chaos-latency already uses
(plain decimal digits, safe integer), without trimming. Anything else, and 0,
exits non-zero with the existing "Invalid chaos-keys-max" error.

The --chaos-seed error text now reads its limit from MAX_CHAOS_SEED_LENGTH
instead of a hard-coded 128.
An embedder that calls evaluateChaos with a seed outside a server request has
no request scope, so setRequestChaosSeeding returned early. The verdict stayed
seeded, but its stream jitter went back to Math.random() with no notice.

Choice: warn once per process, not seed from a fallback. The fallback registry
works for verdicts because occurrence counts are keyed state. A jitter source
is per-request state that the stream writers read back from the scope, and a
process-wide slot would give one call's pacing to a different, concurrent
call. So the gap is reported instead. The notice goes through the caller's
logger when one is passed. Otherwise it uses console.warn with the [aimock]
prefix, as the applyChaos deprecation notice does.

Unseeded verdicts never call setRequestChaosSeeding, so they are unchanged.
fallbackChaosOccurrences, the registry for embedders that call evaluateChaos
without a server, was built without a logger. At its cap it evicted the
least recently used key with no notice, so that key restarted at occurrence
0 without a warning.

There is no server logger in that context, and a caller's logger cannot reach
a process-wide registry. So the registry now gets its own warn-level Logger,
which prints through console.warn with the [aimock] prefix. That is the same
fallback this module uses for the applyChaos notice. The existing eviction
warning text and its once-per-burst rearm on clear are reused unchanged.
… spawn

The built-CLI guard compared dist/cli.js only against src/cli.ts, so a dist
built before an edit to chaos.ts or server.ts still passed. It now compares
against the newest library source under src/ (tests excluded), shared by
both chaos CLI suites.

The --validate-on-load chaos-shape tests no longer skip when dist is
missing, spawn process.execPath, and kill the child on a start timeout.
An invalid fixture chaos.seed is covered as a validation warning.
…de it

- Move expects out of request handlers so a failure fails, never hangs.
- Comma seed header: assert the seed actually used is the first value.
- Reset: advance the counters first, then show the replay from occurrence 0.
- Jitter and verdict draws: assert on delays and verdicts, not on how many
  times Math.random was called.
- Cover: non-finite seed warning, eviction warning re-armed by a reset,
  resetChaosOccurrences leaving server counters alone, and the CLI exit on
  an invalid --chaos-seed or --chaos-keys-max.
… now work

Wording only; no code changes.

- docs page: the occurrence is scoped by X-Test-Id or ?testId=; a replay
  needs the same fixtures and chaosKeysMax; setChaos, clearChaos and
  resetChaosOccurrences restart sequences; the Docker tab shows --chaos-seed.
- chaos-random.ts: jitter draws by chunk index, not occurrence; testId scopes
  the occurrence; identity recording names readBody and the split gates; the
  reset-isolation claim is limited to testId-scoped resets.
- chaos.ts: an unseeded verdict clears seeded request state; the unseeded
  seed lookup is described as it is; evaluateChaos says each seeded call
  consumes an occurrence.
- CHANGELOG: add (CopilotKit#618) to the second Unreleased bullet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jay9vBCbXhVHCDgyRBABVx
A seeded request with a deeply nested JSON body (about 400 KB, far below the
body limit) overflowed the call stack in the key canonicalizer and got a
generic 500, while the same request unseeded was served. Walk the body with
an explicit work stack instead. The output is the same string, so every
existing key is unchanged. Real-server tests cover the seeded, unseeded and
keyed cases.
A BigInt seed from an untyped JS config was rejected, but the warning (and
its latch key) called JSON.stringify on it and threw: a fixture seed turned
the request into a 500, and a server option seed failed startup. Describe the
value with a helper that never throws (a BigInt reads as 42n). Any value
JSON.stringify accepts reads exactly as before.
@jpr5
jpr5 force-pushed the contrib/aimock-reproducible-chaos branch from 3984125 to 515b82b Compare November 24, 2026 00:09

This branch has not been deployed

No deployments
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.

2 participants