Repository navigation
Conversation
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 #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) Design and initial implementation by @AnshulBhati01 in #618.
Scenarios adapted from #618 by @AnshulBhati01.
commit: |
Contributor
Author
|
Closing in favor of #618. The same changes now sit on top of the contributor's original commit there, so their authorship is preserved. The final tree is identical to this PR's head. |
jpr5
added a commit
that referenced
this pull request
Nov 24, 2026
…nd (#618) ## 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`: - It is the same code path, with the same `Math.random()` draws in the same order. The existing tests that count `Math.random` calls pass unmodified. - No seed is generated automatically and no startup log line is added. I left out #618's auto-seed because replacing `Math.random()` for unseeded users would change existing behavior and break the tests that spy on it. - No new response headers, journal fields or metrics. #618's seed metric is not included. - Response bodies, timing and distributions are unchanged. 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What and why
Chaos verdicts (
dropRate,malformedRate,rateLimitRate,disconnectRate) are decided withMath.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:
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.latencyMswas already fixed and is unchanged.A seed can come from:
x-aimock-chaos-seed(request header);chaos.seed;chaos.seed(programmatic orllm.chaos.seedin the config file);--chaos-seed(CLI);POST /__aimock/chaos {"seed": ...}(GETechoes 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-keyandx-aimock-chaos-occurrenceon the response, except on a disconnect. The journal entry getschaosSeed,chaosKeyandchaosOccurrence.Credit
The design and initial implementation are by @AnshulBhati01 in #618: the FNV-1a/mulberry32 keyed draw, per-kind streams, per-key occurrence counters, seed precedence and seeded jitter. #618 was based on a commit 806 behind
mainand conflicted in 30 files. This PR re-implements it on currentmainand adapts the contributor's test scenarios.Supersedes #618.
How the four decisions are handled
No breaking changes. Without a seed there is no observable difference from
main:Math.random()draws in the same order. The existing tests that countMath.randomcalls pass unmodified.Math.random()for unseeded users would change existing behavior and break the tests that spy on it.The test
unseeded chaos is unchangedproves this on a real server. It checks for nox-aimock-chaos-*header, an unchanged set of journal response keys, no new/metricsseries, and oneMath.randomdraw per configured rate.Proxy/record
malformedkeepsmain's behavior. The proxy path is not restructured. Only how the verdict is drawn changes.proxy-only.test.tspasses with no changes.Bounded memory.
ChaosOccurrenceRegistryholds at mostchaosKeysMaxcounters per server. The default is 10,000; set it with thechaosKeysMaxserver option or--chaos-keys-max. Eviction is LRU. Counters are cleared:POSTandDELETE /__aimock/chaos;POST /__aimock/reset.Unseeded chaos keeps no counters. The cap is documented on the chaos-testing page.
Integration with current chaos.
evaluateChaos, reached throughapplyChaosAsync/applyChaosand the split gates inserver.ts.rateLimit,latencyMs,ChaosScope/testId scoping and the runtime control all work with seeds.AsyncLocalStoragescope (the same pattern asrequestScope).streamingProfilejitter, resolves its seed directly.chaos-async-call-sites.test.tsis unchanged:chaos.tsexports no new values.RED (current
main, new tests)GREEN (this branch)
chaos-seed.test.ts: 21/21 pass. This runs on the real server throughcreateServer, the built CLI, the runtime control, the header, fixture seeds, Anthropic/v1/messagesand/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.pnpm build,pnpm typecheck,pnpm lint,pnpm format:checkandpnpm api:reportare all clean.API report
The changes are additions only, with no removed or changed signatures:
ChaosConfig.seed?: string | numberJournalEntry.response.chaosSeed? / chaosKey? / chaosOccurrence?MockServerOptions.chaosKeysMax?chaos?option on thehandleWebSocketRealtimedefaultsCHAOS_SEED_HEADER,CHAOS_KEY_HEADERandCHAOS_OCCURRENCE_HEADERevaluateChaosandcalculateDelaykeep their exact signatures.