# HTTP fixtures

> How Count Patchula's tests replay recorded HTTP cassettes offline, and how to record and check new fixtures.

Production code accepts a `patchula_http::Transport`, which takes a reqwest `Request` built with `Request::new`, so building a request needs no client. `patchula-testkit` belongs only in dev-dependencies. Replay holds only the cassette data, the redactor and a consumption cursor, with no reqwest client and no fallback transport. An unmatched request fails as an ordinary transport error, and `assert_finished` catches interactions no request consumed. A test passes a panicking network factory and an unresolvable `.invalid` host to prove replay never reaches the network.

## Cassettes

JSON cassettes live under `fixtures/`, one per scenario, with a schema version, provenance, requests and responses. Bodies are parsed JSON, so they diff well and ignore key order, or UTF-8 text; binary and streaming bodies fail. Requests match on the method, sanitised URL, selected headers and the complete body, including GraphQL query and variables. The matched headers are `Accept`, `Content-Type`, `If-None-Match`, `If-Modified-Since` and `X-GitHub-Api-Version`. Repeated identical requests consume successive interactions, and `Replay::assert_finished` catches unused ones.

## Recording

Replay is the default. `from_env` calls the network factory only when `PATCHULA_RECORD=1`, which ordinary tests and CI never set. Recording starts a fresh scenario and saves atomically after each exchange, so a failure can leave a partial recording: review the diff and replay before committing.

```console
mise run test
mise run fixtures:check
# For real GitHub recordings, provide GITHUB_TOKEN in the invoking environment.
# Never put its value in command arguments, fixtures, or logs.
mise run fixtures:record
mise run test
```

Every real cassette must say it was recorded by patchula, with the endpoint URLs. Simulated rate-limit and transport responses are labelled as such. Never import another bot’s fixtures, including Renovate’s.

## Redaction

Redaction happens before anything is written:

- authorization and cookie headers, and sensitive JSON keys;
- URL credentials and token, key and signature query parameters;
- GitHub tokens anywhere: `ghp_`, `ghs_`, `gho_`, `ghu_`, `ghr_` and `github_pat_` values, including dotted [stateless `ghs_` tokens](https://github.blog/changelog/2026-04-24-notice-about-upcoming-new-format-for-github-app-installation-tokens/);
- legacy `v1.` tokens, which need at least 20 characters after the prefix so version tags such as `v1.24.0` survive;
- the recording token itself, as a literal, and any literals a caller adds through `Redactor::with_literals`.

Git blob contents are the exception: they are kept as GitHub served them, because the Count takes a blob only when its bytes hash to its SHA, and a workflow file’s `https://x-access-token:${GITHUB_TOKEN}@github.com/…` would otherwise be rewritten. Only content that hashes to the SHA its request named counts as a blob: a GraphQL batch’s `b{i}` text for the object `$o{i}`, or the raw body of `GET …/git/blobs/{sha}`. Such content still may not hold a literal or a token, and the recorder refuses one that does. In a file, a token is a token prefix followed by a run of at least 20 letters and digits, so `npm_config_cache` or “basic auth” is ordinary text; its URLs are left as they are.

The in-memory response a recording test sees is not redacted. The scanner (`mise run fixtures:check`, also part of `mise run ci`) checks raw and parsed JSON, escaped tokens, nested fields and URLs, and checks Git blob contents for literals and tokens the same way, not for URL credentials. A cassette field it does not know fails to parse rather than going unscanned. It accepts extra literals as comma-separated values in `PATCHULA_REDACT`. Failures name the cassette without printing the match.

## Stateful GitHub tests

Tests that simulate GitHub repository state — branches, commits, pulls, discovery listings — share one in-memory fake, `patchula_testkit::github::FakeGitHub`, instead of per-test transport scripts. The fake answers the REST and GraphQL routes the client calls, applies writes to its state, and scripts faults through `on(Matcher)`. Its pulls listing honours `state`, `sort=created`, `direction`, `per_page` and `page` with GitHub’s documented defaults and panics on parameters it does not model, and `repository.pullRequests` resolves `headRefName`/`states`/`orderBy` filtering with `first`/`after` paging. `Hosts` fronts it for a test’s other endpoints — OSV, npm, registries — so one transport covers a whole run.

Every request the fake sees feeds a per-test transcript: the request multiset is normalised, hashed and compared against `tests/transcripts.tsv` beside the suite. `mise run transcripts:snapshot` rewrites the snapshots; a request change that leaves the snapshot stale fails the test, so a port that alters what a suite asks is a deliberate, reviewed diff.

`settings.latency` sleeps a fixed time on Tokio’s paused clock before the fake answers, and `Hosts::set_latency` charges the same latency on the scripted routes, so one knob times a whole run. Virtual elapsed time divided by that latency is the run’s depth — the round trips on its critical path. Depth pins live beside the transcripts in `tests/depth.tsv` (a warm lookup, a no-op real run, and full writes of one and three plans) and the pin is exact: every repetition ends the pinned number of waves after it began, and an elapsed that does not divide by the latency fails too — a wobble means a wait reached the run without the clock seeing it, not noise to tolerate. A deterministic extra request moves the pin a wave and fails it the way a changed request fails a transcript; so does an improvement. `mise run transcripts:snapshot` rewrites both files.

Exactness is a property of the runtime, not a tolerance in the check. Tokio’s paused clock auto-advances when the runtime looks idle, and a wait on a `std::thread` is invisible to it: the cache serves SQLite through worker threads behind a channel, and while a reply was in flight the clock could jump — whether a later request landed before or after an earlier request’s latency then depended on real scheduling, and a measured wave slipped either way. `patchula-cache`’s `paused-clock` feature, enabled only by the dev-dependencies of the crates whose tests pin depth, runs each cache call’s send and reply wait inside `tokio::task::spawn_blocking`, which a current-thread runtime counts as work: the clock holds until the reply arrives, and every wait on the run’s path is either a virtual timer on the latency grid or a held real wait. What depth never changes is the transcript’s job: the request multiset still pins exactly which requests each test makes. And a write pin’s depth is mostly the governor’s one-second write pacing, not round trips — a read that fits inside a pacing window adds no wave.

## Fleet simulation

`crates/server/tests/fleet/` simulates the server over a synthetic fleet, offline, on the pieces above. It measures what the server costs and checks how stale its answers get, so a change to the scheduler can be compared with today’s.

- **Fleet.** One or more App installations, each with N repositories whose dependencies are drawn from a seeded Zipf-like popularity over the same P packages: npm packages, images on an OCI registry (`registry.example`), GitHub actions pinned to commits, and npm packages only a `package-lock.json` names. Each installation’s first repository holds hundreds of npm dependencies. With more than one installation, the last ones (one by default) read npm through an operator mirror (`npm-mirror.example`), which the operator settings allow for those installations alone. A tenth of the repositories have no `patchula.pkl`, and lockfile repositories are report-only, since a lockfile change needs a lockfile tool. Configured repositories wait 0, 2 or 24 hours, and the plain ones at an index of 1 modulo 4 keep a dashboard: 17 of the 77 plain repositories in every hundred (22%).
- **Upstreams.** A state machine per package: versions, publish times, deprecations, digests and OSV advisories, served through `Hosts` (npm, the registry, OSV.dev, the npm mirror) and `FakeGitHub` (action tags and releases), whose `installation/repositories` lists each installation’s own repositories to its token. npm, the registry and GitHub’s REST reads answer ETags and 304s (the fake’s `settings.etags`, which only the simulation turns on), so revalidations count as the requests they are.
- **Events.** A seeded schedule over the simulated days. Upstream: publishes and prereleases, releases reaching a repository’s `waitHours`, deprecations of a repository’s current version, advisories (on a direct and on a lockfile-only package), moved action tags and moved image tags. GitHub-side: pushes with and without their webhook, a person’s merge of someone’s PR (a push plus a `pull_request` delivery the server ignores), a person’s merge or close of one of the Count’s PRs, a tick of the dashboard’s re-check box, a completed check suite on the Count’s PR or someone else’s, a merge or close of the Count’s PR whose deliveries were all lost, and a push adding `patchula.pkl` to a repository without one, with and without its webhook (drawn from a generator of their own, so they leave every other event of a seed as it was; from then on the repository is a plain one the oracle tracks). A push or merge moves one of the repository’s npm dependencies to its newest release three times in ten, so it touches `package.json`, not only the README; merging the Count’s PR applies what its tip changed against its parent to the current files. The push rate (`--pushes-pct`, 50 a day per hundred repositories) and the other GitHub-side rates (`--github-pct`, 100 by default) are knobs. At 100 the rates per repository and day are those of a busy fleet: 1.5 merged PRs of people, 0.3 merges and 0.05 closes of the Count’s PRs, 4 completed check suites, 0.03 lost PR deliveries, and 0.4 dashboard ticks per repository with a dashboard. Most default-branch moves on active repositories are merged PRs, and busy repositories see several completed check suites a day; the simulation draws them as their own events at that rate, apart from the pushes and PR updates. `--github-pct 0` keeps only the upstream events and pushes.
- **Server.** The real runtime through `patchula_server::testing`, which the crate’s `testing` feature builds: the same engines, queue, webhook router, sweep enqueue and worker turn `serve` runs. The simulation decides when the sweep fires (from `sweepCron`), posts signed webhook deliveries through the router, and drains the queue. Before each sweep and each event it runs the [poller](https://count-patchula.sweepy.dev/internals/scheduler/) over every watch row due at that instant, as the poller’s task would have between the walk’s steps; its requests count with the rest. A run that leaves a repository stale wakes the walk once the requeue delay passes, as a worker would claim it then, and the oracle keeps comparing against the repository’s last row that was not stale.
- **Clock.** Every wall-clock read on the server’s path, the cache’s, the HTTP freshness rules’ and the datasources’ goes through `patchula_cache::clock`; the GitHub client keeps the system clock, so installation tokens are not re-minted as simulated hours pass. The `sim-clock` feature, which only the `testing` feature enables, adds `clock::freeze`, and the simulation sets the clock to each simulated instant. Normal builds read the system clock. Because the setting is process-wide, the simulation is its own test binary. Tokio’s paused clock times the batches: worker seconds are the virtual time batches take at a fixed per-request latency.

### The oracle

After each event and after each hourly sweep, the oracle builds a fresh engine with an empty cache for each installation, from the same operator settings and App, and dry-runs that installation’s affected repositories at the simulated instant. It compares two things for each configured repository:

- the dry run’s report row with the row of the repository’s last full run, which is the answer the server settled on, since a quiet sweep finishes a repository only when its replay hashes the same; the comparison clears the fields time alone fills, as the quiet sweep’s hash does;
- the open PR set: every PR the Count has open must be one the dry run plans, and as many planned PRs must be open as `prs.concurrent` allows. A dry run reads no PR inventory, so it cannot apply the limit itself. Nor can it see that a person closed a PR. So a branch whose PR a person closed may be open when planned, but is never expected open; while it is open it still takes one of the limit’s slots. The cost: a plan reopened on such a branch for a newer release goes unchecked.

A difference is attributed to a dependency (by package), a PR branch (by the package it names) or the rest of the row (a package file’s presence follows from its dependencies and is not part of it), and each event covers the differences its package can explain. A push with its webhook covers everything; one without covers the rest of the row (its commit) and the package it moved, if it moved one. A difference’s deadline is the latest among the events that could explain it, each counted from the event’s own instant, or one sweep after it was first seen when no event can. It fails the run when an observation finds it past its deadline, or when it heals after its deadline: a difference gone by an observation is judged at that observation’s instant, the first the oracle saw it gone, against the events pending when it was last seen, so one that heals between two observations still counts. An event that arrives after that last sighting is not used for it. An event is absorbed, and its staleness from its own instant recorded, once no difference it could explain remains. A comparison without the server’s settled row, as before a repository’s first settled run, says nothing about its dependencies, so it absorbs no event: one it cannot see stays pending until a settled comparison absorbs it, or is dropped without a staleness once its own deadline passes.

The bounds, from the code and the default settings:

| Event | Bound |
| - | - |
| Publish, prerelease, deprecation | `reuse_hours(waitHours)` + sweep + slack; `pollSecs` + sweep + slack with no wait |
| Release reaching `waitHours` | sweep + slack (`next_due`) |
| Advisory, lockfile-only advisory | `advisoryFreshnessSecs` + sweep + slack |
| Push with webhook | slack |
| Push without webhook | sweep (its probe) + slack |
| Moved action tag, moved image tag | sweep + slack |
| A person’s merge of a PR, a merge or close of the Count’s PR, a dashboard tick, a completed check | slack |
| Merge or close of the Count’s PR with every delivery lost | sweep (its probe) + slack |
| Push adding `patchula.pkl`, with webhook | slack |
| Push adding `patchula.pkl`, without webhook | sweep (its probe) + slack |

A delivered GitHub-side event covers every difference in its repository, as does a push adding a config. A repository that gains a config also inherits the upstream events of the packages it reads that are still inside their bounds at its wait, each from its own instant, with the release reaching the wait that each publish brings: its first runs read stored catalogs and advisory listings by the same reuse rules as every other reader, so a release published before the config can be missing from its answer until the release’s own bound ends. An inherited event records no staleness when absorbed, as the repository had no answer when it happened. A lost merge or close of the Count’s PR covers the rest of the row, every PR difference and the dependency its branch updates, and stays pending until none of those differences remains: a close changes no commit, so the row alone cannot tell it was seen. The next sweep’s probe is the catch-up: it finds the moved head, the closed PR or the added config and runs the repository, which is what a lost delivery waits for.

### The differential

Every server run in a test build passes a fixpoint check (`crates/server/src/runtime/differential.rs`): straight after the run, a cold full run of the repositories it settled, at the same instant, must reach the same report hash (the quiet sweep’s) and attempt no write. The cold run is a fresh engine over a copy of the server’s cache with the stored answers the sweep skips with (`quiet-run`) dropped, so nothing it does can heal what it looks for, and it sends through a transport that refuses every GitHub write and marks every read with `x-patchula-uncounted`. The fakes answer a marked request from the same state and rules without logging it, adding it to the transcript, charging latency, spending a rule or firing a mutation, and the simulation’s counters skip it, so the check changes no transcript, depth or count. It sits where `inputs::logged` guards input completeness, so it covers every test that drives the runtime (`crates/server/src/runtime/tests.rs`, the fleet scenarios and the simulation) without cases of its own. A finding fails the test; the simulation collects them instead and reports them with its other numbers.

The same place checks the public record. The open PRs the run left for its record (`patchula_update::open`, `Engine::run_settled_at`) must equal, field for field, what the old record path shows at that instant: a listing of open PRs and a read of each of the Count’s, sent uncounted through the same refusing transport on an empty cache, so no conditional read the server makes later answers differently. Every repository the run left a view of is checked, an empty view included, which must meet an empty listing. It runs while the run’s repository locks are still held, and the differential’s switch turns it off too.

`reuse_hours(w)` is `None` for `w = 0`, else `w - 1` clamped to 1–24 hours (`crates/engine/src/catalogs.rs`); the sweep is `sweepCron`’s interval, an hour by default; `pollSecs` is an hour by default; slack is five minutes, for the minute rounding of event times. The simulation prints the table with its values.

The no-wait catalog bound is interim. A run serves a catalog the poller confirmed within `pollSecs`, so a release published just after the last poll is seen by the next poll and acted on at the sweep after it: up to two hours at the defaults, where a run reading the catalog every sweep took one. Once a changed row wakes the repositories that read it, the bound returns to about one poll interval plus the wake delay ([poller](https://count-patchula.sweepy.dev/internals/scheduler/#bounds)).

### Running it

The simulation is excluded from the normal suite and from CI; the rest of the suite runs there as usual, the oracle’s pure unit tests included, and so do the poller’s scenarios (`crates/server/tests/fleet/scenarios.rs`): small hand-made worlds on the same upstreams, each pinning the requests a poll or a sweep sends, which take turns since each freezes the clock. The simulation runs on demand, as an ignored test, and a PR that changes the scheduler, the cache or how catalogs are read runs it and reports the numbers. It discards its transcript as it goes and reports counters instead, and it fails when the oracle finds any difference past its bound:

```sh
mise run benchmarks:fleet
mise run benchmarks:fleet --repos 200 --days 3 --seed 2
mise run benchmarks:fleet --installations 2 --mirrors 1
mise run benchmarks:fleet --pushes-pct 30 --github-pct 0
mise run benchmarks:fleet --differential --threads 1
```

The differential is off in the benchmark unless `--differential` asks for it: its requests are never counted, so the counters are the same either way, and it takes about three quarters of a run’s time. The oracle’s dry runs share `--threads` threads (one per core by default), each on its own paused runtime while the walk waits, over work units of eight repositories that do not depend on the thread count, so their answers are the same at any count. The server stays on the walk’s one paused clock. The summary is otherwise not byte-reproducible: settle times are real microseconds, and a few npm and registry requests a day vary from run to run with how the cache’s worker threads interleave with the server’s concurrent lookups.

It prints TSV tables: per day, sweeps, batches, full runs by report status, repositories the quiet check skipped, worker seconds and requests by host (GitHub REST and GraphQL, npm, the npm mirror, the registry, OSV), the poller’s polls by kind and how many found a change, the catalogs read live again before a write, and the runs such a re-read left stale because a catalog had changed; GitHub requests by API, phase (`poller`, `replay` for the quiet check, `run`), endpoint class, call site and answer (2xx, 304, other): 304s are apart because GitHub does not count them against the primary rate limit. Call sites come from `patchula_http::site::scope`, which the engine and update crates wrap around each stage (`scan`, `inventory`, `lifecycle`, `cleanup`, `publish-base`, `branch-rewrite`, `pr-fresh`, `obsolete`, `dashboard`, `check-candidate`, `record`, …) and which only test builds keep. Per day, full runs by cause (the claim’s priority, and for a sweep claim the quiet check’s verdict: no stored answer, a due time, the probe’s difference (head, refs, pulls, dashboard, config) or two failed probes, no stored config, no stored extraction, a changed answer) and how many of each wrote on GitHub; full runs by restore outcome and reason (complete, or partial with the receipts’ reason, the `obsolete`, `bannered` and `unsettled` flags and each plan’s fallback reason), read from the debug events the quiet check and `restore_inventory` log; and PR reads per run that took the full write path, by call site. Then the differential’s cold runs and the settled repositories they checked; per event kind, how many were absorbed and their median and maximum staleness in minutes; the bound table; the `catalog` state rows the server’s cache holds at the end; the watch rows by kind, the input rows and the dependents per watch row with at least one (median, 90th percentile, maximum) and the settles with their median and 99th-percentile time, both by nearest rank (the staleness medians take the upper middle value); and any violations. The App’s 30-second readiness probe is not simulated.

## mise

A subprocess has no HTTP cassette. mise lookups run through `patchula_process::Executor`, and tests swap in `patchula_testkit::MiseReplay`, which answers from `fixtures/mise/listings.json`: for each command after `mise` (such as `ls-remote --json --prerelease -- jq`), the JSON mise printed or the error it failed with. The replay keeps every command with its environment and working directory, so tests can assert the sandbox. A lookup missing from the fixture fails the test; replay never runs mise.

`mise run fixtures:record-mise` runs the pinned mise through `MiseRecorder` and rewrites the file. It needs the network, a `mise` on `PATH` and `GH_TOKEN`, which mise gets as it would in production and which is never written down. `mise run fixtures:check` scans these files with the cassettes.

## gh-actions-lock

`gh-actions-lock` is a real subprocess with real TLS, not an HTTP client the replay transport can stand in for, so its tests run it behind a loopback HTTPS CONNECT proxy (`GitHubProxy` in `crates/tools/src/lockfiles/tests/real_actions_lock.rs`). The proxy accepts `api.github.com:443` and refuses every other target, terminates TLS with a certificate `rcgen` mints for the test, and answers each request from the same cassette format as everything else, recorded with the same `PATCHULA_RECORD=1` flow and the same redaction — the token reaches the tool as `GH_TOKEN` and is redacted before a cassette is written. The suite also exercises the tool’s real flag contract against a frozen lockfile: `--no-interactive --no-onboard --no-narrow --ignore-local-actions --json=valid,findings` over an already-listed workflow exits 0 with `valid: true` and changes nothing.

## Replaying a webhook to a local server

```sh
mise run server:replay /tmp/push.json push local-push-001
```

The `server:replay` task signs a recorded payload with your webhook secret and posts it to a loopback listener. It prints only the HTTP status and refuses non-loopback targets. Set only one of `PATCHULA_WEBHOOK_SECRET_FILE` and `PATCHULA_WEBHOOK_SECRET` when you use it. A repeated delivery ID is accepted but ignored, so use a new ID to trigger again.
