Caching¶
rstest keeps two caches in your project, its own .rstest_cache/ and pytest's .pytest_cache/, and can optionally share its cache across CI jobs through a remote backend.
.rstest_cache/ (rstest's own)¶
durations.json: per-test call durations, merged over runs (a filtered run updates only the tests it ran). Only passing tests are recorded: a failed test keeps its previous timing, and so does a test--durations-regressflagged, so the baseline it regressed from stays in place. Drives duration-aware scheduling and the suite-size heuristic behind-n auto. Each entry records its test file's path and a sha256 of its contents, so the cache self-heals: an edited test re-times on fresh numbers instead of stale ones, and a deleted or renamed test is dropped rather than kept forever. Because the hash is content, not mtime, and ignores line endings, a cache restored onto a fresh checkout (for example with CI's cache action) still matches. Safe to delete at any time; the next run rebuilds it (and is scheduled in collection order).scope_costs.json: the setup time of each module's and class's module- and class-scoped fixtures, merged over runs. Lets--dist loadkeep a costly module on one worker (Scheduling). Shared through--cache-push/--cache-pull. Safe to delete; the next run records it again.memory.json: the largest worker peak RSS of each of the last 5 parallel runs (and of single-worker runs-n autochose), which caps the next-n autoby memory (-n). Safe to delete;-n autois then CPU-sized until the next run records it.wall.json: the whole suite's last wall-clock time for this project (fixture setup and teardown included), used by the monorepo planner to weight a fixture-bound project by its real cost. It carries no per-test source to fingerprint, so it ages out on time instead: entries older thanRSTEST_WALL_TTL_DAYS(default 30,0disables) are ignored on read.collect.json: how long one worker spends collecting the whole suite, from the last parallel run with full collection (lazy runs leave it as is). Under full collection every worker repeats that, and lazy collection saves it, so the automatic collection choice lets the heaviest test file run that much past its per-worker share before it keeps full collection (Lazy collection). Same TTL aswall.json. Safe to delete; the choice then allows one second.mode_wall.json: the last parallel run's wall time under each collection mode (full and lazy), with its worker count and test count. When lazy took longer than full at the same worker count, the automatic choice keeps full collection (Lazy collection). Same TTL aswall.json. Safe to delete; the choice then goes by the other checks alone.flakes.json: sparse record of tests that flaked (passed only on rerun, via--reruns/@pytest.mark.flaky) or hard-failed, quarantined failures included. Used to surface repeat offenders, by--reruns-only-known-flaky, and by--order fail-fast. Entries with no event insideRSTEST_FLAKE_RETENTION_DAYS(default 90,0keeps history forever) are ignored on read. Auto-written, safe to delete, persisted the same way asdurations.json.history.msgpack: each test's last runs (default 50, set withRSTEST_HISTORY_RUNS): outcome, call and setup time, plus the run's commit (<sha>-dirtywhen the tree had uncommitted changes). Read byrstest explainfor the outcome strip, the duration spread and the commit a test started failing at, and at the start of every run by--auto-quarantineto find the tests that keep flipping. Deleting it empties the auto-quarantine set. Runs older thanRSTEST_FLAKE_RETENTION_DAYSare dropped on read. Not written byrstest replayor--dist each. Shared through--cache-push/--cache-pull(each pushed run carries its own entries; see Shared cache). Safe to delete. For its size on a large suite, see History size.report.html: the history dashboardrstest reportwrites by default. Output, not input: no run reads it; leave it out of a CI cache.green_env.json: what the last full run that exited 0 ran with (a run that selected part of the suite doesn't count): its commit, the interpreter version, installed third-party packages (read from the venv'ssite-packages, the project's own editable install excluded) and a few test-relevant environment variables (PYTEST_ADDOPTS,PYTHONPATH,PYTHONHASHSEED,PYTHONWARNINGS,PYTHONUTF8,TZ,LANG,LC_ALL). A red run diffs against it; see What changed since green. Not written byrstest replay. Shared through--cache-push/--cache-pull, including a sharded run once every shard is green (see Sharded CI). Safe to delete.coverage_index.json: line→test index (which tests' coverage executed each source line), written by any--cov-context=testrun. Lets--changedselect only the tests hitting the changed lines. Safe to delete:--changedfalls back to the import graph without it; rebuild by rerunning coverage with--cov-context=test. Merges through the shared cache like the others, so sharded coverage runs union into a full index (see Shared cache backend). Paths in it are relative to the rootdir, so a run from a subdirectory writes the same keys as a run from the root.last_green.json: the commit of the last fully green run on a clean working tree, stamped with an environment fingerprint (interpreter, dependency manifests and installed distributions). Read by--since-green; an environment change busts it, so the next run selects everything. Safe to delete.incremental_outcomes.json: per-test outcomes, source lines and coverage hashes from the last--incrementalrun, so an unchanged green test can be skipped. Also read byrstest explain. Safe to delete: the next run re-runs everything and rebuilds it. Rootdir-relative like the coverage index; a run of part of the suite keeps the other tests' records.replay/: the schedule of each parallel run (<run-uid>.json, the last 10 kept, pluslatest.json; none for--shard,--dist each,rstest replayor withRSTEST_NO_REPLAY_JOURNAL=1), read byrstest replay. Local to the machine that ran it: keep it out of any CI cache and uploadlatest.jsonas a failure artifact instead (see Replaying a CI-only failure)..lock: an empty sentinel file. rstest takes an OS advisory lock on it around each read-modify-write of the cache files, so concurrent runs or shards sharing one cache directory don't lose each other's updates. Never read or written; safe to delete when no run is active.
Persist it in CI (example) to get
duration-aware scheduling from the second run onward, minus replay/.
The cache lives at the pytest rootdir, the same directory .pytest_cache/
goes to: the directory of the pytest config file (pytest.ini,
pyproject.toml, tox.ini, setup.cfg, ...) found from the common ancestor
of the path arguments upward, else that common ancestor. Running from a
subdirectory (cd tests/unit && rstest) or passing paths therefore reads and
writes the project's one cache, so durations, flake history, replay journals
and rstest explain see every run. --rootdir and -c move it the way they
move pytest's rootdir. Set RSTEST_CACHE to relocate it explicitly
(distinct from RSTEST_CACHE_DIR, which steers the machine-global
interpreter-probe cache).
Like .pytest_cache/, the directory ignores itself: rstest writes a
.gitignore containing * and a CACHEDIR.TAG (so backup tools skip it)
when it creates the cache, and gives a .pytest_cache/ it creates itself the
same two files. No entry in your own .gitignore is needed.
With pytest's cacheprovider disabled (-p no:cacheprovider on the command
line, in addopts or in PYTEST_ADDOPTS), a run leaves no cache behind,
as pytest does: .rstest_cache/ is neither read nor created, and neither is
.pytest_cache/. The run uses a private scratch directory that is removed
when it ends, so it schedules cold (no saved durations), records no flake
history, leaves no replay journal for rstest replay, and adds nothing for
rstest explain to report (durations, flakes, coverage) later.
An explicit RSTEST_CACHE still takes effect.
Writes are atomic (tmp + rename), so a concurrent reader never sees a half-written file.
History size¶
history.msgpack grows with the number of tests times the runs it keeps,
until every test holds RSTEST_HISTORY_RUNS runs. Each kept result costs 13
bytes (outcome, call and setup time, and its run), and each test id is
stored once:
On pandas (193,843 tests, every one at the default 50 runs), the file is 154 MB: 126 MB of results and 27 MB of test ids, which are long parametrized names there (about 140 bytes each). Each kept run adds about 2.5 MB.
| Suite | Runs kept | History size |
|---|---|---|
| 1,000 tests | 50 | about 0.8 MB |
| 10,000 tests | 50 | about 8 MB |
| 50,000 tests | 50 | about 40 MB |
| 194,000 tests (pandas) | 50 | 154 MB |
| 194,000 tests (pandas) | 20 | about 78 MB |
| 194,000 tests (pandas) | 10 | about 52 MB |
A run reads the file once and writes it back, so its cost grows with its size: on pandas, the 154 MB history adds about 0.4s to every run.
How many runs to keep depends on what reads them:
--auto-quarantineneeds 3 flips (a failure right after a pass on the same clean commit), so a handful of recent runs catches most flapping tests; more runs catch rarer ones.--durations-regresscompares against a median that settles after 10 to 20 runs.rstest explainandrstest reportshow the outcome strip and the commit a test broke at as far back as the history goes.
The default of 50 suits suites up to about 50,000 tests. Beyond that,
RSTEST_HISTORY_RUNS=20 halves the file and its per-run cost and still
keeps enough for auto-quarantine and duration regression. Lowering it takes
effect over the next full run: a test's results are trimmed to the new cap
when it runs again, so tests left out of the run keep theirs. Results older
than RSTEST_FLAKE_RETENTION_DAYS (default 90) are dropped whatever the
cap.
Shared cache backend¶
Instead of hand-wiring actions/cache (with its per-key immutability dance and
a dedicated refresh job), rstest can publish and warm .rstest_cache to a
shared remote directly. See --cache-remote.
It is segmented, merge-on-read: each run pushes its own immutable segment rather than overwriting one shared blob, so concurrent shards and PRs never clobber each other.
<remote>/
base.json # compacted merged state
segments/seg-<id>.json # one immutable segment per run/shard
- Pull merges
base.jsonand every segment into the local cache, per data type:- durations: newest value per test;
- flake counts: summed per-run events, deduped by segment id so a re-pull never double-counts;
- coverage index: unioned per file. Segments that agree on a file's
content hash merge their line→test maps; a different hash keeps the newer
segment's map (same-second ties broken deterministically by hash). Because
the shards of one run share a commit, their hashes match, so their partial
slices union into a full index; if a file's content differs between
segments the newer wins and
--changedfalls back to the import graph for that file: still correct, only coarser. - fixture scope costs: newest value per module or class
(
scope_costs.json), so a fresh runner keeps costly modules on one worker from its first run; - run history: each segment carries its run (id, epoch, commit)
and one entry per test. Runs are unioned by
run id, so a run that arrives from the base, a segment and the local
history.msgpacklands once, then replayed oldest first; each test keeps its newestRSTEST_HISTORY_RUNSruns. Every shard of a sharded run is its own run, and each test appears in the shard that ran it. - green snapshot: a green run's environment (
green_env.json). A full green run counts on its own; a sharded run counts once every shard of the same commit pushed a green part, and its parts wait inbase.jsonuntil then. The newest such snapshot replaces the local one when it is newer.
- Push writes just this run's segment (
--cache-push): its slice of the durations, flake events, coverage index and run history this run measured, plus its green snapshot when its tests passed over the whole suite or one whole shard. - Compact (
cache-compact) folds segments into a new base and prunes them; a segment already folded is recorded in the base's absorbed-id set, so compaction is safe against concurrent pushes. Compaction also drops history runs older thanRSTEST_FLAKE_RETENTION_DAYS, so a deleted test's runs leave the base. The history is stored inbase.jsonas one compressed field (base64 of gzipped msgpack), a few MB at 10k tests and 50 runs instead of tens of MB as plain JSON; releases that predate it ignore the field.
Transports¶
--cache-remote (or RSTEST_CACHE_REMOTE) selects where the base + segments
live:
| Value | Backend |
|---|---|
a directory path / file://… |
local dir, NFS/EFS mount, or a dir a CI step materializes (download-artifact, aws s3 sync) |
s3://bucket/prefix |
the aws CLI on the runner (creds from the environment) |
gs://bucket/prefix |
gcloud storage (or gsutil) on the runner |
http(s)://host/path |
any endpoint honoring the listing contract below; bearer auth from RSTEST_CACHE_REMOTE_TOKEN (use https://: over plain http:// the bearer token is sent in cleartext) |
The s3/gs transports shell out to the cloud CLI already installed and
authenticated in CI: no SDK, no secrets in the URL. Any other scheme:// is
rejected loudly rather than silently written to a junk local directory.
Permissions¶
Every transport needs four operations on the <root> prefix:
list and read (pull), write (push a segment), and delete
(compaction and retention only, via cache-compact or --cache-compact-threshold).
A pull/push-only job that never compacts can drop delete. Least privilege: scope
the credential to the cache prefix, not the whole bucket. Concretely:
| Backend | Grant |
|---|---|
S3 (s3://bucket/prefix) |
s3:ListBucket (on the bucket, condition prefix), s3:GetObject/s3:PutObject/s3:DeleteObject on bucket/prefix/* |
GCS (gs://bucket/prefix) |
storage.objects.{list,get,create,delete}, e.g. roles/storage.objectAdmin scoped to the bucket/prefix |
| Azure Blob (dir-materialize) | Storage Blob Data Contributor on the container (the az CLI needs read+write; delete only if a job compacts) |
http(s):// |
endpoint enforces its own authz; rstest sends Authorization: Bearer $RSTEST_CACHE_REMOTE_TOKEN |
dir / mount (/path, file://) |
filesystem read+write+delete on the directory |
GitHub artifacts (the action's artifact backend) |
workflow permissions: { contents: read, actions: read }; actions: read reaches a prior run's segments |
HTTP listing contract¶
A bare GET/PUT can't enumerate a collection, so
an http(s):// remote must answer GET <root>/segments/ with a JSON array of
segment names (filenames or full keys/URLs) and support GET / PUT / DELETE
on the blobs. A static file server with autoindex-as-JSON, an S3 REST bucket, or
a tiny custom endpoint all satisfy it.
Trust boundary¶
Anything that can push a segment can influence later runs that pull it. rstest merges segments without checking who wrote them, so treat write access to the cache prefix as write access to your test selection. A crafted or corrupted segment can:
- make
--changedselect too few tests, because the coverage index is trusted for the lines it records; - inflate flake counts in
flakes.json, so--reruns-only-known-flakyretries (and hides) failures it should not,--order fail-fastreorders dispatch around them, andrstest explainreports them as genuine history; - fabricate flips in the run history, so
auto-quarantine (on by default) turns real
failures non-fatal and
rstest flakyranks the wrong tests; - skew durations or the history's per-run times, which unbalances shards and
shifts the
--durations-regressmedian, so it passes or fails wrongly; - publish a fake green snapshot, so
--since-greendiffs against a commit that never passed.
Recommended setup:
- Only trusted events write. Give
--cache-push(and the credential that allows it) to runs on your default branch (pushevents, merge queue, schedule). PR jobs, especially from forks, run pull-only, or push to a separate PR prefix that main never pulls. The GitHub action'scache-push: autodefault pushes to aremoteonly frompush,scheduleandworkflow_dispatchruns ofwarm-from-branch(andmerge_group). The credential is the real boundary: tests can read whatever the job holds (rstest keepsRSTEST_CACHE_REMOTE_TOKENout of their environment, but not out of reach), so give PR jobs read-only credentials. - Filter the warm-source lookup to trusted runs. With the artifact
backend, resolve the prior run with
gh run list --branch main --event push --status success. Without--event push, a successful PR run whose head branch is also namedmain(for example from a fork) could match. The GitHub action does this by default (warm-from-event: push). - Don't let the cache decide what a gate skips. On merge-queue or release
pipelines, run the full suite, or use
--changed-strictso files the index can't connect fall back to a full run.
Retention¶
cache-compact folds all segments by default. To bound the segment set
without discarding fresh history, keep a recent window loose:
cache-compact --keep-last N/RSTEST_CACHE_KEEP_LAST: retain the newest N.cache-compact --max-age 30d/RSTEST_CACHE_MAX_AGE: retain the young.--cache-compact-threshold N/RSTEST_CACHE_COMPACT_THRESHOLD: fold on push when the loose count exceeds N (honoring the window above), so no separate maintenance job is needed. Best-effort: never fails the run.
Recipes: Shared cache across CI jobs.
.pytest_cache/ (pytest's, shared)¶
Workers read it normally (--lf/--ff deselection happens inside the
vendored core). Writes to the run-level keys (lastfailed, nodeids,
stepwise) are blocked in workers (each worker sees only its own slice).
After the run the orchestrator writes the merged lastfailed; nothing
writes nodeids in a parallel run, and --sw runs as a single session, so
pytest's own stepwise plugin keeps stepwise. lastfailed is
updated the way pytest updates it: this run's failures are added, tests that
passed or were skipped are removed, and the failures of tests the run did not
execute stay, so a passing subset run keeps the rest. A test that was running
when Ctrl-C (or SIGTERM) stopped the run has no real outcome and is not
recorded there, nor in flakes.json or durations.json. Other plugins'
cache writes pass through untouched.
Worker temp directories¶
Each worker gets a disjoint tmp_path root under $TMPDIR/rstest-<pid>/gwN/
(one subdirectory per worker id: the same per-worker isolation xdist gets
from its popen-gwN roots), preventing numbered-directory cleanup races
between sibling workers. A user-provided --basetemp becomes the shared
parent instead: each worker uses <basetemp>/gwN, as under xdist. With
-n 0 it is used as given.
$TMPDIR/rstest-<pid>/ is deleted when the run ends, with everything else
rstest keeps in the temp dir for that run. A run killed too hard to clean up
(SIGKILL, out of memory) leaves its folder behind, and the next rstest run on
the machine deletes it. A user-provided --basetemp is never deleted, so pass
one to inspect tmp_path contents after a run.