@variance-authority/sense
v0.37.0
Published
Which components and tests a source change reaches: test selection and impact analysis from a versioned index of a checkout.
Readme
@variance-authority/sense
Which components and tests a source change reaches: test selection and impact analysis from a versioned index of a checkout.
Part of Variance Authority.
Point your coding agent at llms.txt.
Use this package to cut a test run down to the files a diff can actually affect.
It adds probes to your product source while your tests run, records which test
file covered which region of which module, and later answers a unified diff with
the list of test files that provably did not go near it. Wrap your runner
configuration once and set VARIANCE_AUTHORITY_SINCE, and the runner leaves those files out itself, or gets the list of paths to skip.
It answers four questions:
- Which test files covered the source regions a diff touches, and which can you skip?
- How far did the change travel to reach each of those tests, so you can run the near ones first?
- Which files and components can a changed file reach, from a scan of the checkout alone?
- Which named test cases covered a given function or line — the query an editor or a coding agent asks.
All four work from a wrapped runner. The fourth reads the per-case index the run writes beside its snapshot, and every host this package reaches writes one — what each one gives the recording is one table.
Skip this package if your tests run somewhere it cannot instrument, or if you need to exclude individual test cases rather than whole files: selection returns test files, and the runner still collects and executes every case inside each one.
npm install --save-dev @variance-authority/senseNode 22.15 or newer. Vitest (^4.1.0 || ^5.0.0) and Jest
(^30.0.0, with the @jest/globals and jest-circus it installs) are
optional peer dependencies: install the runner whose seam you use, and your own
copy is the one that runs. Under an older Jest, a
configuration that selects throws while it loads and names the version it
found. Storybook and Playwright come from sibling packages rather than from
here, and are covered below.
Cut a Vitest run down to a diff
Wrap the configuration once. withTestSelection keeps your plugins, setup
files, and reporters, and adds instrumentation, collection, and persistence.
The probes go in after your plugins, as they do in
a build, so a compiler that reads
syntax compiles the same output under the suite as it ships.
A plugin ahead of the probes that rewrites a file and returns no source map
stops the run, with an error naming the plugin and the file. Vite reads a
missing map as one that moves nothing, so probes placed through it would count
code that did not run. Return the map, or map: null when no position moved:
a map: null with text that changed the file's line count, other than by
appending to it, stops the run the same way.
Two kinds of file still reach the seam before your plugins read them. A test file has its lines marked for its cases first, so a compiler that reads a test file's syntax reads those marks. Under browser mode, every file is probed first, as it was before.
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import { withTestSelection } from '@variance-authority/sense/vitest';
export default withTestSelection(
defineConfig({
test: { include: ['src/**/*.test.ts'] },
}),
);Run the suite once as you normally would. That run writes a snapshot: a binary record of which test file covered which probed region of which module. From then on, the runner can skip what a diff cannot reach.
Let the runner skip them
Set VARIANCE_AUTHORITY_SINCE, and the wrapped configuration reads the
selection variance select prints, from @variance-authority/cli, and removes
the skipped files before Vitest starts any of them:
VARIANCE_AUTHORITY_SINCE= npx vitest run
VARIANCE_AUTHORITY_SINCE= VARIANCE_AUTHORITY_AT_DISTANCE=0-2 npx vitest runSet and empty, the variable reads each test from the commit the snapshot names.
Set to a ref, it also names the base for a snapshot that names no commit.
VARIANCE_AUTHORITY_AT_DISTANCE takes one range of hop counts, read as in Take
one range of hop counts at a time, and
a value that is not a range fails the run. Before the first file starts, stderr
shows one line: selected 12 of 340, selected none of 340, so none of them
runs and whether the change reached none of them or a leg or --local left them
for a later run, or
declined: and the reason the selection could not be read, in which case every
file runs. VARIANCE_AUTHORITY_LOCAL=1 is variance select --local: where the
record cannot narrow, only the files that import a changed file run, instead
of every file; any value other than 1 or 0 fails
the run. VARIANCE_AUTHORITY_RAN_AT=<commit> is variance select --ran-at:
in a merge queue's group of one, it names the pull request's tested commit,
and VARIANCE_AUTHORITY_SINCE the base the queue merged onto; beside an empty
VARIANCE_AUTHORITY_SINCE it fails the run
(a pull request in the merge queue).
A test file the snapshot has never seen runs. A run the
selection leaves nothing to run — selected none, or a shard that took none of
the files kept — passes: the seam sets passWithNoTests for that run. A run
that drops nothing keeps your setting.
The files are removed in a sequence.sequencer that wraps the one your
configuration names, before it shards and sorts, so every shard divides the
same list. --shard places that list by whole files, by the time each file took
on the last recorded run, or by file count when the record has no times, as sharding shows. Your sequencer still sorts
each shard, but it does not choose the shard's files. Watch mode does not select.
@variance-authority/cli has to be installed in the project; when the checkout cannot resolve it, the run fails and the message
names the package.
VARIANCE_AUTHORITY_GRAIN=case also skips, inside each selected file, the
cases that entered none of the changed regions. The sequencer writes their
names to one file before any worker starts, and the case runner marks them
skipped in onCollected, as it.skip would; under Jest, a jest-circus
run_start handler does the same. Nothing reaches argv. A file runs whole
whenever the record cannot say which cases the change reached, and a file run
in part is recorded incomplete, so the next selection runs it whole, and while
some test file was last finished at an earlier commit than the latest run,
every file runs whole. File grain is the default; any value other than file or case fails the run.
Ask for the skip list yourself
A runner with no seam, or a program that decides for itself, reads the same answer from the API:
// select.ts, in a package with "type": "module".
// Run it with your own TypeScript runner, or drop the types and run it as .mjs.
import { readFile } from 'node:fs/promises';
import {
changedLines,
narrowByExecution,
testCoverageFile,
textAtRecording,
} from '@variance-authority/sense/test-selection';
const root = process.cwd();
const diff = await readFile('change.diff', 'utf8');
const { whole, entered, unread, stale } = await narrowByExecution(
testCoverageFile(root),
diff,
{ sourceAt: textAtRecording(root, changedLines(diff).keys()), root },
);
const reached = new Set(entered);
const skip = whole.filter((test) => !reached.has(test));
if (unread.length > 0) console.error(`the record says nothing about: ${unread.join(', ')}`);
console.log(skip.join('\n'));Produce change.diff with git diff <base> HEAD > change.diff, or any unified
diff over the same checkout. Hand the runner every test file it would have run
except skip.
Ask for the skip list rather than the run list. A snapshot can only ever justify
exclusions: a run list has to be right about every test that exists, while a
skip list only has to be right about the tests it names, and a test it wrongly
leaves out of the skip list costs a test run rather than a missed regression. A
missing snapshot, a snapshot from another machine, and a first run all leave
whole empty, so skip is empty, so the suite runs.
What each field means
whole— the tests whose observation was complete. A test inwholeand not inenteredis one the record positively proves this diff did not reach.entered— the tests the diff reached. Never read an emptyenteredas "run nothing": this diff reached nobody and this snapshot recorded nobody are opposite facts, andwholeis the only thing that separates them.unread— changed paths the record has no row or declaration for, and the graph has no node for when you passrelations: a README, a script the tests spawn, a file outside the directories you scanned. It is a report, not a reason to run more. A module that reads such a file names it by a/// <depends>, and withrelationsa change to it selects the tests that load that module and the path leavesunread. Print it so the operator can see what nothing recorded.stale— modules whose text on disk no longer matches what their rows were recorded over. A report rather than work: a stale module is already charged whole insideentered. It comes back empty unless you passsourceAt, because nothing looked — which reads exactly like frames that agree.because— one entry per selected test, in the order ofentered, listing every reason it is there: aregion(file, name, path and lines of a recorded block a changed line charged), apreconditionby name, areader(a place inreaderthat reads the valuename, declared infile, that the change altered), or animporterwith the trail from the changed file to the file the test was found through. Print it beside each path a watch loop runs.readings— one entry per changed file, saying how the change was read. Averdictofnone,bodies,valuesorloadis what the edit does;nameslists the values it altered,effectsthe files whose package declares that loading them does something, andunseenthe tests that loaded the file through no import the graph holds. An entry withunreadinstead was charged by its lines:sourcewhen you passed nosourceAt,hunkwhen the diff does not apply to the recorded text,parsewhen a text does not parse, andaddonwhen this machine has no native scanner.
Pass root so a file's package.json is read for its sideEffects; without
it no file is read as load on that account.
selectTestFiles returns entered alone, for a caller that has established the
second half some other way.
Ask one stage alone
narrowByExecution runs every stage of selection in a fixed order: it cuts the
suite's ignored files out, routes each file by whether the record measured it,
reads the change, charges regions, reads the preconditions and walks the
graph. A system that already knows which files moved, or a simulation over
files and lines nobody wrote, needs one of those stages and no diff. Each stage
takes values and an open record, reads no git, and reads the checkout only
through root when you pass it. The composition calls the same stages, so a
stage asked alone answers as it does inside the whole:
import {
askCoverageFile,
changeOfFiles,
testsEnteringFromView,
testsLoadingFromView,
testCoverageFile,
} from '@variance-authority/sense/test-selection';
const files = ['src/cart.ts', 'src/cart.css'];
const { entered, unanswered } = askCoverageFile(testCoverageFile(process.cwd()), (view) =>
testsLoadingFromView(view, files),
);
// entered: every test that loaded src/cart.ts; unanswered: ['src/cart.css'], which has no row.
const lines = { lines: new Map([['src/cart.ts', [{ start: 40, end: 42 }]]]), hunks: new Map() };
askCoverageFile(testCoverageFile(process.cwd()), (view) =>
testsEnteringFromView(view, lines, { precision: 'function-use' }),
);Every stage answers { entered, because, unanswered }. unanswered lists the
files that stage holds no answer for; no stage selects more because of them.
| Stage | Asks | Answers |
|---|---|---|
| changeOfDiff, changeOfFiles | a unified diff, or a list of paths changed whole | the Change every other stage reads |
| changeOfPaths | a change and paths | the part of the change that moves those paths |
| ignoredChange | a change and the suite's ignore globs | what is kept and what is ignored |
| routesFromView | paths | coverage, relations or nothing per file |
| testsLoadingFromView | paths | every test that loaded each file: file-use |
| testsEnteringFromView | a change, and region-use, function-use or file-use | every test that entered the regions the lines fall in, with stale and readings |
| testsDeclaringFromView | a change, and sourceAt | every test that declared a changed file as a precondition, less one that ran the text it arrives at |
| graphReachFromView | paths and relations, and moved exports | the tests the import walk reaches: what file and symbol add; a file moved does not name is walked whole |
| importersFromView | a change, relations and sourceAt | the nearest measured importers' tests of each file with no row |
| dependsReachFromView | ignored paths and relations | the tests of the modules that /// <depends> on them |
| readRowlessFromView | a change, relations and sourceAt | the readers of a new or unmeasured module's exports, and its readings |
| narrowByChangeFromView | a change, and the options above | all of them composed: what narrowByExecution returns |
Given sourceAt, testsEnteringFromView checks the record's frame and reads
what the lines moved, as the composition does: rows cut from another text are
stale and charged whole. Without it, lines are read as given, in the
coordinates of the text the record was cut from. Lines with no hunks say where
a file moved and not what it became, so no parser reads them: they are charged
as given, and no declaring test counts as having run the text they arrive at.
A file one stage answers can still be another's question. A test can enter a
file and another declare it, and a file a test declares is still walked up
its importers for every other test. So the stages asked by hand give the
composition's answer only when each one gets the part of the change it reads
there: the suite's ignore cuts the change first, and the preconditions read
all of it, because no glob undoes a declaration.
const { kept, ignored } = ignoredChange(change, ignore);
const read = readRowlessFromView(view, kept, options);
const entered = new Set([
...testsEnteringFromView(view, kept, options).entered,
...testsDeclaringFromView(view, change, options).entered,
...read.entered,
...importersFromView(view, changeOfPaths(kept, read.unanswered), options).entered,
...dependsReachFromView(view, ignored, options).entered,
]);The three stages that end in the walk each read the precondition table, which
the composition reads once. When you need the whole answer and which stage
selected each test, ask narrowByChangeFromView: every reason in its
because names its stage, region for coverage, precondition, reader
for the reading and importer for a walk.
Without root, no stage reads a package's sideEffects or resolves an
import, so an edit that adds an import is read by its verdict alone. A
simulation over a record and no checkout answers what the composition answers
without root, not what it answers in the checkout.
The two stages before the route,
what an install moved and what the harness rests on, are beyondReach and
beforeReach in @variance-authority/core/relate, and they take values too.
Where the snapshot lives, and when it is rebuilt
withTestSelection writes outside your checkout by default: the coverage data
a run records is operational state rather than source.
<cache>/test-selection/<digest>/coverage.bin<cache> is your cache.
<digest> is taken from the checkout's path as seen from the cache directory, so two checkouts write no
file in common but .work/index-turn and .work/index-turn.holder, the lock that lets
one checkout of a repository index at a time
and the file that names its holder. testCoverageFile(root) returns that path,
and sourceIndexPath(root) the source index beside it. A git worktree gets
.work/<its own digest>/ in its own cache, which is inside the worktree at the
default location. Its coverage reads both layers and writes only its own, so a
worktree cut this morning inherits what the repository already recorded. Its source index is its own too,
and the first update in it starts from another checkout's index and reads only the
files that differ from it. Pass coverageFile in the options to put
it somewhere you name instead — a CI job that uploads the file as an artifact
needs that.
A repository that runs more than one test suite declares each of them, with its
kind, under suites in the root variance.config.json:
{ "suites": { "unit": { "kind": "unit" }, "stories": { "kind": "visual" } } }The kind is one of unit, integration, e2e, visual and job. Each declared
suite records on its own, at <digest>/suites/<name>/coverage.bin, and every
seam takes a suite option that names the one it runs, as in
withTestSelection(config, { suite: 'unit' }). A run under one suite never
replaces what another suite recorded. A seam that names none records into the
only declared suite. Among several it stops before the run starts, as does a
seam that names one the file does not declare. declaredSuites(root) returns what the file declares, and
testCoverageFile(root, { suite }) the path of one suite's record. A
repository that declares no suites keeps the one coverage.bin above.
Built as a side effect of a wrapped run: every test file writes a journal,
the reporter folds them when the run completes, and the result is landed over
whatever was there before. There is no separate build step. This package
records evidence and answers questions about it; the caller owns the inventory
of current test files and the dispatch, and a wrapped runner removes what a
selection skips only when VARIANCE_AUTHORITY_SINCE
is set.
Cached in CI by caching <cache> whole and restoring it
to the same absolute checkout path it was written from. Nothing about the branch
or the commit belongs in the key for correctness, but vary the key anyway so
each job writes a new entry and starts from the newest one that exists.
The source index gives the
worked cache configuration; the same rules and the same directory cover the
snapshot.
Retired per test file rather than wholesale. Each test-file observation records the identities of its own source, its configured setup, and any additional preconditions. Changing one of those starts a new generation for that file — its current batch of crossings against one fixed set of preconditions — and the inherited crossings are retired. An inherited module whose text on disk no longer matches its rows is read the way selection reads a diff, from both texts: an edit that runs nothing differently — a type, a type-only import, a comment — marks no test; an edit inside function bodies marks the tests on the regions it moved, gained, or left with no region; an edit to what the module does as it loads marks every test that loaded it. A marked test is partial and runs at the next selection, and when either text cannot be read, every test on a moved region is marked. An observation is complete only when every leaf task in its file passes; a focused, skipped, or failed run is partial, contributes its crossings, and can never justify a skip.
Invalidated whole only by being unreadable: a missing, corrupt, or foreign-layout snapshot is treated as absent, which costs a full suite and cannot produce a wrong skip. Delete the digest directory to force that.
What selects what
A changed file selects by how the snapshot records it.
- A product module selects the tests that covered the changed region.
- A test file selects itself: nothing covers a test, so its own edit is the only thing that can run it.
- A precondition selects every test it governs, which is what declaring one
is for. A
preconditionsentry governs every test of the run, so declare what every test rests on, such as compiler settings. A fixture a test reads withfsgoes in the module that reads it as/// <depends path="…" />. - A module with probes and no crossings answers: the build read it and nobody covered it.
- A module with no row at all selects nothing from the record: nothing
loaded it, every test that imports it mocked it, or it sits outside what the
run instrumented. Pass
relationsandsourceAtand it is read, with every export counted as changed; the nearest files that import it and have a row answer for what that reading cannot (below). An importer with no row is read from the text the change leaves it, so a file the diff adds charges only the functions that read a changed export. It is listed inunreadwhen no test declares it and the graph has no node for it either. - A stylesheet, image, or JSON file can take no probe, so it never has a
row. Pass
relationsto answer it through the graph instead (below). - A file the suite ignores selects only the tests that declared it. Pass
ignore, globs from the repository root (!takes a file back out), and a changed file one matches loses its regions and its import and asset edges, keeps its preconditions and/// <depends>edges, and is listed inignored. A module that declares it answers by its own row, and one with no row as any unmeasured file does: by its importers, or declined. A unit suite under jsdom paints nothing, soignore: ['**/*.css', '**/*.png']keeps a changed stylesheet from selecting every test that imports the component.variance selectpasses theignorelist of the suite it reads, fromvariance.config.json.
Each changed file is first read from both of its texts, and the verdict decides
what is charged, as running less of the
suite
describes. A file that cannot be read is charged by its lines, in the
coordinates of the diff's own base revision; so are the regions a bodies or
values verdict charges. The line rules, stage by stage with their costs, are
in tracing a diff to
tests.
A module the instrumenter could not parse is recorded with
instrumented: false; selection widens to every test that loaded it, each of
which treats the module as a precondition. When another build did instrument
the same file, that build's row answers, and the uninstrumented row takes
nothing from it.
Answer a file with no row through the import graph
narrowByExecution(file, diff, { relations }) walks from a stylesheet, image
or JSON file through asset edges — the kind the scan gives an import of
anything that is not a module — and depends edges, which a module draws with
/// <depends path="./rules.json" /> to a file it reads without importing it.
The walk goes through the stylesheets that import the file to the modules that
import or declare those, and no further. Build relations with
the scan.
A module with no instrumented row under any of its names, when it could not be
read or its verdict is load, is walked the same way along every runtime edge, never type, and each chain stops at the first test
file or instrumented module it reaches. A module the build could not instrument
is walked past, and its tests come from the preconditions. A test that mocked
the changed module, or the file it loaded it through, is cut.
A bumped dependency changes no line anybody recorded. Pass the names whose
install moved as packages, beside relations, and each is walked from its
package node: back through the packages that rest on it, to the files that
import them, and on to the tests. Compare two lockfiles with
changedPackages to get the names. A package only a type
import names reaches nothing.
Each chain answers for itself. A chain ending at a module the record measured selects the tests that ran it; a chain ending at a module the record never saw selects nobody, and takes nothing from the chain beside it. The walk uses the edges the scan read; an import the scan could not read is not one of them.
A snapshot that stores a file under another name — the built twin a sibling
package's tests loaded — is looked up under every name knownAs returns for it,
and each name selects the tests recorded under it.
Options on the Vitest seam
The optional second argument accepts root, suite, coverageFile,
include, unprobed, preconditions, mode, placement, continuations, cadence, selection, and record.
| option | default | use it when |
|---|---|---|
| root | the configuration root, then the current directory | the configuration is evaluated outside the checkout it records. Recorded paths are relative to the checkout that contains root, never to root itself, so a package-level configuration and a repository-level one name a file the same way. Relative option paths resolve against root |
| suite | none; the only suite when the root config declares one, required when it declares several | the repository declares its suites, and this configuration runs one of them. It cannot be combined with coverageFile |
| coverageFile | the cache path above | CI needs a named artifact |
| include | JavaScript and TypeScript modules, less test, spec, dependency and built-output files | restricting instrumentation to product source; it receives each absolute module path, except for a build whose sibling map leads to exactly one source: it receives that source's path first, and the module's own only if it refuses the source (below) |
| unprobed | none | product source a probe cannot sit in, such as a module whose functions you hand to page.evaluate, where the first probe throws. It is asked under the same names as include, and wins over it; the module runs unprobed with a mark at the end of its text, and a change to it selects every test that loaded it. A module you build into a bundle and inject into a page is not loaded by any test, so no mark reaches it: name the bundle's entry in the before of the suite that injects it |
| preconditions | the config file Vite loaded, the local modules it imports, and the configured setup files | naming a file the runner reads without Vite knowing, such as compiler settings. A change to one runs every test the run records, so a fixture a test reads goes in the module that reads it as /// <depends path="…" /> instead. Each entry is the path of one file that exists before the run starts, so write a generated file before the runner starts. A glob, a directory, a missing file or a file only a test writes, absent when the run starts, is refused before the first test. A project's entries are read when a test file of that project is in the run, and the entries of the configuration listing the projects when any project has one; a command that runs no test, such as vitest list, and a run with no test file are not refused, except that Rstest refuses a run with no test file in a page or in a watch session, where it cannot tell one yet. Jest, and Rstest in a page, start their run after global setup, so each accepts a file global setup writes, but that file moved during the run: every test declaring it is recorded incomplete and runs again |
| mode | 'presence' | 'entries' records module and function entries only, and nothing inside them. 'loads' records which files each test file loaded and nothing inside them: no module is probed, each one runs with one line added after its own text, and a change to a file selects every test file that loaded it. A record made so has no cases, so continuations and stories do not apply to it (below). Which precision each mode answers, and what each costs: record as finely as you select |
| placement | 'after-transforms' | 'before-transforms' places the probes in the file as read, ahead of your transforms, for a run whose transforms only strip types or JSX (below) |
| continuations | off | a case's work outlives it, or the suite is deliberately concurrent (below) |
| cadence | on | false leaves test files as you wrote them, and the record without the test line that reached each region and without the time of each case's statements (below) |
| selection | read from @variance-authority/cli when VARIANCE_AUTHORITY_SINCE is set | you compute the selection yourself: a function returning the SuiteSelection whose skip the run removes |
| record | on | false runs a second configuration over the same selection, such as one that shares modules between files: the run selects and places its files from the record as a recorded run would, and instruments, writes and lands nothing. A file whose cases the selection cuts runs whole. Vitest's seam only for now; Jest's and Rstest's record every run they select |
The config file Vite loaded, the local modules it imports and the configured setup files become preconditions automatically, and the runtime's own setup file is placed ahead of them so a setup file that loads an instrumented module finds the counter factory it needs. A setup entry that names a package rather than a file is not a precondition, since no diff mentions it.
Under isolate: false a run still records every file that consumed a module as
having covered it. A file consumes a module by running something in it: a module
of nothing but constants, evaluated once for an earlier file and only read by the
next, is recorded for the file that evaluated it and not for the reader. Under
mode: 'loads' a file is recorded as loading every module the shared realm
already held when it started, as well as what it loaded itself, since nothing it
does tells the module cache apart from a module it imported: no file is missed,
and a file that imports less is selected by more.
Each file's setup snapshots every counter before its first test runs, so a
region already covered by then is recorded as loaded by that file as well as
crossed by it — a function that ran because the module was imported rather than
because a test called it. loadedBy on the block is where you find it.
A configuration with projects needs the wrap in two places:
- Wrap each project. A Vitest project inherits neither plugins nor setup files from the configuration around it.
- Keep one wrap at the root for the reporter that folds the run.
A project's config file, the local modules it imports and its setup files are preconditions of that project's tests and of no other project's, so a change to the browser project's setup file does not rerun the unit tests. The root configuration decides which projects exist, and is a precondition of every test.
A root-only wrap is the shape that looks right and records nothing: the reporter
runs, the file is written, and it lists no source under any test. That run
prints a warning on the way out — instrumented 0 modules across N test
file(s).
Place the probes ahead of your transforms
By default every seam places the probes after your transforms: each module is read once from disk, its regions are cut from that text, and the probes go into what your transforms wrote, where their map carries each region. A compiler that reads the syntax it compiles, such as Compiled or React Compiler, then reads your file without probes in it. That costs a second parse, of the transformed text, and the map that leads back to the file.
A unit-test run whose transforms only strip types or JSX has nothing that
reads syntax, and can skip both. Set placement: 'before-transforms' and the
probes go into the file as read, ahead of every transform: one parse, no map
asked for, and no refusal for a transform that left none. The recorded regions
are the same, since they were always cut from the file.
withTestSelection(config, { placement: 'before-transforms' });The option has one name and one meaning on every seam that places probes: the
Vitest, Jest and Rstest withTestSelection, testSelectionProbes and
testSelectionRule. Nothing detects a syntax-reading compiler for you: React
Compiler runs inside another plugin's Babel options, and each bundler names
Compiled's step differently, so a check would miss as often as it caught. With a
compiler like that in the run, the compiler reads the probes too, and its output
changes or its extractor stops: keep the default.
Record only what each test file loaded
mode: 'loads' records which files each test file loaded, and nothing inside
them. No module is cut into regions or probed: each one runs with one line
added after its own text, which tells the run it loaded. A change to a file
then selects every test file that loaded it, whatever the change and whichever
line it touched.
withTestSelection(config, { mode: 'loads' });A module is marked as it loads, before any of its file's cases opens, so the
record keeps one entry per test file and no cases: continuations, cadence
and stories do not apply to it. The mark is one line after the module's own
text, globalThis.__VA__.m("<id>");, and it imports nothing: a runner seam
installs __VA__ in its setup, and a bundle seam adds the import of the page's
collector, as it does under every recipe. Nothing is parsed or probed, so the
run pays one call per module evaluated: on this repository's unit suite, 925
test files that take 66.8 s, 'loads' adds 1.9 s, and the
marks are half a second of it. Under the default placement the mark is
added after your transforms, so every transform in the run reads your code as
you wrote it. Choose it when a test file is the grain you select at, or when a
transform in the run cannot take probes.
A page reused between stories or test files evaluates a module once, so each drain leaves what the page already holds for the next one: every subject on the page is recorded as loading it. The mark runs when the module's text has run to its end, so two loads go unrecorded: a CommonJS module that returns from its top level before the end, and a file the runner loads without a transform, such as JSON under Jest. A change to either selects no test file through that file.
Record Jest journeys without selecting tests
withJourneyCoverage records the source regions entered by each named Jest
test. Jest seals the journals when its run ends and neither reads nor writes a
test-selection snapshot. A separate command folds those journals into the
artifact after Jest has reported whether the tests passed.
Install the CLI beside Sense for that post-run command:
npm install --save-dev @variance-authority/sense @variance-authority/cli// jest.config.mjs
import { withJourneyCoverage } from '@variance-authority/sense/jest';
export default withJourneyCoverage(
{
testEnvironment: 'jsdom',
transform: { '\\.[jt]sx?$': '@swc/jest' },
},
{ journeyFile: '.variance-authority/journeys.bin' },
);journeyFile is required. Finalize it in a CI step that runs after the Jest step
whether Jest passed or failed:
yarn exec variance journeys finalize .variance-authority/journeys.binUntil that command succeeds, the journals and their manifest remain in
.variance-authority/journeys.bin.pending. A failed finalization leaves them
there for another attempt. A successful one writes the artifact and removes the
pending directory.
Give every CI shard a different path and publish each finalized file
independently. The other options are root, preconditions, mode, and
continuations; they have the same meanings as on the selection seam below,
except that withJourneyCoverage refuses no entry in preconditions.
After downloading the artifacts, assemble them locally. The native fold reads the interned sets directly rather than expanding one JavaScript object per test and region. Assembly is order-independent, deduplicates a repeated test identity, and refuses artifacts whose region inventories disagree.
yarn exec variance journeys stitch \
shard-0.bin shard-1.bin shard-2.bin \
--into journeys.binvariance select --execution journeys.bin answers a patch from that file. To
do the same from code, pass the changed lines to narrowByJourneys, and pass
read from readJourneyChange(diff, before, { root, relations }), where
before returns the text the patch was written against. A journey file carries
no source text, so without read a line is charged as covering --line
charges it: to the region it falls in, and to the region around it when the
line opens a branch or a function. A comment above a function falls in the
module's own region, which every file that imports the module ran. With read,
a file whose change runs nothing charges nothing, and a file whose load-time
behaviour did not change charges only the functions its lines charge.
Follow a Jest case into a service it calls
A case that calls a service over HTTP runs code in another process, and that code is invisible to the case's own record. Change a branch in the service and nothing selects the case that exercised it. The join has to happen somewhere, and while Jest is still running is the wrong place: shards finish at different times, and a service answers several cases at once.
So the service writes what it ran to files, keyed by an id the case put on the request, and the finalize step joins them after the run. Nothing goes over the network during the run, and nothing waits for the service.
The case hands the id over itself. Nothing touches your requests:
import { journeyCookie } from '@variance-authority/sense/case-journey';
const response = await fetch(`${service}/quote?currency=eur`, {
headers: { cookie: journeyCookie() },
});journeyCookie() returns variance-authority-journey=<id>. The id is minted
the first time the running case calls it, and later calls in the same case get
the same one. caseJourney() returns the bare id if you carry it some other
way, such as trace baggage. Outside a case, both return nothing.
If your application already runs Sentry or OpenTelemetry, the id is the trace id and your tracing carries it through every hop. Hand the SDK over from a module that initializes it and exports it, and leave the requests alone:
// test/trace.cjs
const Sentry = require('@sentry/node');
const { sentry } = require('@variance-authority/sense/case-journey');
Sentry.init({ dsn: process.env.SENTRY_DSN });
module.exports = sentry(Sentry);Name that module as withJourneyCoverage's trace: trace: './test/trace.cjs'. With
OpenTelemetry, register your provider and export
openTelemetry(require('@opentelemetry/api')). Jest requires the module once
per worker, outside every test file's sandbox, and your testEnvironment, a
test file's @jest-environment and your runtime still run. A setup file runs again in each test file. An SDK hooks fetch for
the whole process, so a second initialization leaves the first file's hooks
sending its trace from the next file's cases.
Each case then runs inside a trace whose id is its journey, and the service is
configured with the same SDK: collectJourneys({ head: 'pricing', parts, trace:
sentry(Sentry) }). It reads the journey from the trace wherever a request did
not name one.
The service wraps its requests with collectJourneys, as in
the next section, and adds parts:
const journeys = collectJourneys({ head: 'pricing', parts: '/tmp/va-parts' });parts defaults to VARIANCE_AUTHORITY_PARTS. With it set, each process
appends frames to its own file in that directory: one frame per journey as its
scope settles, plus one frame for what ran outside any journey (startup, a
request with no cookie). If the process is killed mid-write, the fold reads past
the torn last frame. Then tell the Jest seam where the parts are:
withJourneyCoverage(config, {
journeyFile: '.variance-authority/journeys.bin',
parts: ['/tmp/va-parts'],
});Each module in a part names its repository-relative file and a digest of the text the service's build placed probes on. The fold reads that file from your checkout and cuts it into regions again, so the service's build writes nothing for the run to read.
A journey's frame is charged to the case that minted the id and to no other. The
no-journey frame is charged to every case the same file served. A shared
service's startup is every caller's, so a change to it selects every file that
called it. A case that called the service without its cookie is not charged at
all, because nothing names it. Under a tracer, a trace no case started (a
beforeAll call, a background job) is charged the same way as the no-journey
frame.
A runtime with no host filesystem, such as a Cloudflare Worker, sends its parts
to an address instead. Start a receiver on the host before the service, and
point parts at it:
import { receiveParts } from '@variance-authority/sense/journey';
const receiver = await receiveParts('/tmp/va-parts', { port: 5198 });
// VARIANCE_AUTHORITY_PARTS=http://127.0.0.1:5198 in the service's environment
await receiver.close();Each journey's frame is sent before the promise its scope returned settles, so a runtime that ends a request's work with its response still delivers it. A receiver that is gone loses that part, never the request.
A bundle evaluates every module before any of its own code can install a head,
so ask the build to install it first. With journeys set, as in
testSelectionProbes({ label: 'workers', journeys: true }), the collector
imports @variance-authority/sense/journey and installs the head under
label. Each entry's own collectJourneys() then
returns that head:
const journeys = collectJourneys();
export default {
fetch: (request, env, context) =>
journeys.enter(request.headers.get('cookie') ?? undefined, () => handle(request, env, context)),
};Cut a Jest run down to a diff
Wrap the configuration once. Each transform entry is wrapped: your own
transformer — @swc/jest, ts-jest, babel-jest, any module with Jest's
transformer shape — compiles the file as Jest read it, on its own pattern with
its own options, and the probes go into what it wrote, where the map it returns
carries each region of your file. The map handed on to Jest is that map moved
past the probes, so a stack trace points where it did before. A transformer
that changes the text and returns no map is handed the probed text instead, as
nothing carries a region into what it wrote. It then transforms each such
module twice and reads the probes, and the run warns once for each such
transformer, naming it. Vite and Rspack stop the build there instead: the
wrapper calls your transformer itself and can hand it the probed text, while a
plugin or loader ahead of the probes has already run and cannot be asked again.
setupFiles keep their order and
gain the counter factory at the start; setupFilesAfterEnv gain the journal
writer at the end; reporters gain one at the end, and a configuration with no
reporters keeps Jest's default.
// jest.config.mjs
import { withTestSelection } from '@variance-authority/sense/jest';
export default withTestSelection({
testEnvironment: 'jsdom',
transform: {
'\\.[jt]sx?$': ['@swc/jest', { jsc: { parser: { syntax: 'typescript', tsx: true } } }],
},
setupFilesAfterEnv: ['<rootDir>/test/setup.ts'],
});The second argument accepts root, suite, coverageFile, preconditions,
unprobed, mode, placement, continuations, cadence, and selection, with the meanings above.
With placement: 'before-transforms' the probes go into the file as Jest read
it, and your transformer compiles the probed text. Jest does not report which
config file it loaded, so name it in before in variance.config.json, and a
change to it runs the whole suite. unprobed is a list of
globs rather than a function, because Jest hands its transformer options as
data; relative globs resolve against root, and a glob
that opens with ! keeps a module probed, as it does in testMatch. There is no include:
product source is every JavaScript and TypeScript module the configuration's
testMatch or testRegex does not name, less dependencies and built output that
is not a library loaded from its build. A
setup entry that names a package — dotenv/config — is left alone. A
configuration with projects is instrumented project by project, each keeping
its own transform and setup files, with one reporter for the run. Each test's
setup and environment files are read from the project Jest ran it under, so a
change to one project's setup file does not rerun another project's tests; a
project named by path rather than spelled inline is refused, because its
transform cannot be wrapped from here.
With VARIANCE_AUTHORITY_SINCE set, a Jest run skips files as
a Vitest run does. A run that found test files and
selected none of them passes. A run where no project found a test file has nothing
to select from, so it fails as Jest fails, and a testMatch that matches nothing
stays red. One project with no file beside another that found some is not that
failure, as it is not without the selection. passWithNoTests in your configuration
or on the command line passes that run, as it always did. --testSequencer on the
command line replaces the sequencer that tells the two apart, so Jest fails both,
and stderr says so. The files are removed in
Jest's filter, which runs before --shard and --listTests, so every shard
and the listing see the same list. A filter your configuration names runs
first, and the selection removes files from what it kept. --filter on the
command line replaces the configuration's filter, the selection included, with
yours, and --skipFilter turns filters off. Either one turns the selection
off, and stderr says which.
withTestSelection reads the object you pass it, before Jest resolves
anything. It reads the preset's transform, merges it with yours as Jest does
and wraps the result, so a preset such as ts-jest needs nothing copied, and a
transform you name keeps its patterns beside the preset's. Presets and
transformers load from an absolute rootDir, or from root when the object
names none. Jest reads a relative rootDir from the config file, whose directory
the wrap is never told, so the wrap looks in root, or else in that path from
the working directory. With the config file in another folder, write rootDir
as an absolute path, and a preset such as ts-jest still needs nothing copied.
The wrap stops at config load, naming the preset, in four cases. Under a relative
rootDir, a preset spelled as a path, starting with . or <rootDir>, stops it
whether it is there or not, because the file there may not be the one Jest runs,
and the fix is an absolute rootDir even when the two are the same folder. A bare
name it does not find there stops it because Jest may find that preset from the
config file. A preset Jest awaits, such as one with top-level await or one that
exports a promise, stops it because the wrap is synchronous. Any preset stops it
when jest-resolve is not reachable from that directory, even one with no
transform, because the wrap finds a preset through jest-resolve. A missing
preset under an absolute rootDir, or under none, is Jest's to report.
A preset's setup files and environment are read from the configuration Jest resolved, so a local preset's files are preconditions without being named. An async configuration is yours to await: wrap the object it returns.
// jest.config.mjs
import { withTestSelection } from '@variance-authority/sense/jest';
import buildConfig from './jest.base.mjs';
export default async () =>
withTestSelection(await buildConfig(), { preconditions: ['jest.config.mjs', 'jest.base.mjs'] });Jest transforms inside the workers it forks and keeps the transformed text on
disk under a content key. The probes ride that cache, and nothing else is
written: each probe reports its file and a digest of the text it was placed on,
and the reporter cuts that file again from your checkout. Each test file writes
one journal from afterAll; nothing crosses the worker channel. Before it is
written, it is checked against Jest's module registry, require.cache. If your
test file evaluated a module whose probes ran and the journal does not name it,
the test file fails and the message names the module, because that journal would
select too little. A module your test evaluates outside the registry, through
jest.resetModules, jest.isolateModules or an automock, is still recorded; the
registry just no longer lists it, so it is not checked.
A Jest worker runs many test files, and each of them loads modules with probes
in them, so a recorded run needs more memory per worker than a plain one while
its wall clock stays close. If a recorded run starts to time out where the plain
one does not, compare peak memory first. Under Jest 30 on Node 24 or newer, run
with NODE_OPTIONS=--no-async-context-frame before anything else: with Node's
default AsyncLocalStorage, Jest 30 keeps the memory of each finished test file
until the worker's heap is close to its limit, with or without the recorder, and
the flag releases it. Then lower maxWorkers or set workerIdleMemoryLimit so
Jest restarts a worker once it passes that size.
Asking for the skip list yourself is the same call as for Vitest. narrowByExecution returns paths
relative to the checkout, whatever rootDir is set to, and each remaining path
is a pattern Jest accepts on its command line — jest test/alpha.case.ts
test/beta.case.ts. The snapshot is one file, so a repository whose unit tests
run under Jest and whose pages are driven by Playwright selects from one index.
To assemble a Jest configuration by hand instead, withTestSelection names four
modules by path, and you can name them yourself:
@variance-authority/sense/jest-transform,
@variance-authority/sense/jest-globals,
@variance-authority/sense/jest-setup, and
@variance-authority/sense/jest-reporter.
Place the probes from your own Rust transform
Wrapped as above, the probes go into what your transformer wrote. When that transformer is your own Rust — over swc, oxc or anything else — it can place them itself, inside its own pipeline. The package ships the instrumenter as a Rust crate, the code its own addon runs, so a project that installed sense already has the version its runtime reads:
# Cargo.toml
[dependencies]
variance-sense-instrument = { path = "node_modules/@variance-authority/sense/native/instrument" }Your transformer declares the recipe it was built with, and the wrapper then
hands it each module as Jest read it, with options.senseProbes saying where
the probes go:
// transformer.cjs, around your addon
const native = require('./transform.node');
module.exports = {
senseRecipe: (mode) => native.senseRecipe(mode),
process: (source, path, options) => ({ code: native.transform(source, path, options.senseProbes) }),
};use variance_sense_instrument::{instrument, recipe, Mode};
/// `options.senseProbes`, as your binding hands it over.
pub struct SenseProbes {
pub file: String,
pub module: String,
pub mode: String,
}
fn sense_recipe(mode: &str) -> String {
recipe(if mode == "entries" { Mode::Entries } else { Mode::Presence })
}
fn with_probes(source: String, probes: Option<SenseProbes>) -> String {
let Some(p) = probes else { return source };
let mode = if p.mode == "entries" { Mode::Entries } else { Mode::Presence };
instrument(&source, &p.file, &p.module, mode).map_or(source, |done| done.code)
}Run instrument before your own parse: every probe stays on its line, and the
text stays the language it was. senseProbes is absent for a test file, a file
outside product source and a file Jest loads before the collector exists, and
instrument returns nothing for a text it cannot parse; either way the module
runs without probes. A module unprobed names reaches your transformer without
senseProbes too, already carrying the wrapper's mark at the end of its text.
The wrapper compares senseRecipe with this package's recipe when Jest loads
it, and refuses one built from other sources of the crate, naming both; a
senseRecipe that answers nothing for the mode leaves the transformer a plain
one, and the probes go into what it wrote. A transformer that places the probes
itself does so as it compiles, so placement does not apply to it.
Under mode: 'loads' the wrapper never asks for senseRecipe and hands no
senseProbes: every module reaches your transformer as Jest read it and leaves
with the wrapper's mark after what your transformer wrote.
Cut an Rstest run down to a diff
Rstest builds the suite with Rspack and runs what it built, so the recording half is a loader rather than a plugin. Wrap the configuration once and it changes in three places:
- The rule is appended to
tools.rspackrather than replacing it. setupFileskeep their order and gain the counter factory at the start.reportersgain one at the end.
// rstest.config.ts
import { defineConfig } from '@rstest/core';
import { withTestSelection } from '@variance-authority/sense/rstest';
export default defineConfig(withTestSelection({
globals: true,
setupFiles: ['./test/setup.ts'],
}));The second argument accepts root, suite, coverageFile, include,
unprobed, preconditions, mode, placement, continuations, cadence, and selection, with the meanings above. Rstest
does not report which config file it loaded, so name it in preconditions. The
regions are cut from the text you wrote, so the lines a record carries are the
ones you edited, and a second loader at enforce: 'post' writes the probes into
what SWC and your loaders wrote, where their map carries each region. A loader
of yours that rewrites a file is handed the map so far and returns it composed
with its own. A file that reaches the second loader with no map stops the run,
naming the file: leave Rspack's devtool writing source maps, as Rstest sets
it. With placement: 'before-transforms' the first loader writes the probes
itself and the second passes each file through.
Recording per case needs nothing from the configuration. Rstest has no runner option, so
the per-case bracket goes around it and test themselves — on the realm when
globals: true puts them there, and on globalThis['@rstest/core'], which is
where Rstest assigns its API and what Rspack compiles an import of that external
to. A suite that imports its registrars and a suite that takes the injected ones
are recorded the same way, and a suite that mixes the two is too.
A configuration with projects describes the run rather than a suite: wrap each
project and keep one wrap at the root, the same shape a Vitest projects
layout needs. A project that sets name keeps its setup files and
preconditions for its own tests. A project Rstest names by default is named
after the wrap has run, so its files are preconditions of every test. An entry
that cannot be read is refused before any test once a wrapped project, or an
unwrapped one written inline in projects, has a test file in the run. A run of
nothing but an unwrapped project named by a path gives the seam nothing to refuse
from, so its tests run and the run fails when they end, and rstest merge-reports
fails the same way, for an entry a merged test rests on. Neither writes a record
without that entry. A project named by a path and not wrapped itself records no
coverage: wrap it to have its tests recorded.
VARIANCE_AUTHORITY_SINCE and VARIANCE_AUTHORITY_AT_DISTANCE read as in
Let the runner skip them: the wrap adds the files
the selection skips to the project's exclude before Rstest plans its entries,
and stderr shows the same selected line first. A selection that keeps no file
runs none and passes. Under projects, each wrapped project selects from its
own files and prints its own line. The variables read there read the same way;
--shard divides the kept files as Rstest divides any, not by recorded time,
and watch mode does not select. A kept file runs whole, so
VARIANCE_AUTHORITY_GRAIN=case fails the run rather than run more than it
asked for.
A --reporter on the command line replaces the seam's reporter, which is the
one that refuses and records. Such a run, and such a rstest merge-reports,
writes no record, refuses nothing and does not say so. Vitest does the same in a
run with no wrapped project.
To assemble a configuration by hand instead, withTestSelection names two
loaders by path, and you can name them yourself:
@variance-authority/sense/rstest-loader with enforce: 'pre', and
@variance-authority/sense/rstest-after-loader with enforce: 'post'. A
configuration that names the first and not the second fails when the run ends,
naming each file that never reached the second loader.
Record and select a node:test suite
@variance-authority/sense/node-test is the runner above, written for
node:test. runNodeTest({ files }) runs the files with node:test's own
run(), one process per file, records each case under its describe path, and
reads VARIANCE_AUTHORITY_SINCE: a file the record proves the diff did not
reach is not started, and the run prints selected N of M. It takes the options
startRecording takes. Record and select tests under
node:test walks through it, and
says why Bun's bun test is not recorded.
Record a runner this package has no seam for
The Vitest, Jest and Rstest seams are configuration, because each of those
runners names three places in its configuration: where source is transformed,
where a test file starts and ends, and where the run ends. Any other runner has
the same three places, including a harness you wrote yourself, but only its
author knows where they are. So @variance-authority/sense/runner gives you a
function to call from each one. The snapshot they write is the one every seam
writes, and variance select and selectTestFiles read it without knowing
which runner made it.
Here is a complete runner that forks one process per test file. A file passes when its process exits with 0:
// run.mjs: the process that starts the run
import { execFile } from 'node:child_process';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
import { startRecording } from '@variance-authority/sense/runner';
const execute = promisify(execFile);
const files = ['test/alpha.case.mjs', 'test/beta.case.mjs'].map((file) => resolve(file));
const recording = startRecording({ preconditions: ['run.mjs', 'worker.mjs'] });
const finished = [];
for (const file of files) {
const complete = await execute(process.execPath, ['worker.mjs', file]).then(() => true, () => false);
finished.push({ file, complete });
}
await recording.finish(finished);// worker.mjs: the process that runs one test file
import { observeTestFile, registerRecording } from '@variance-authority/sense/runner';
registerRecording();
const file = process.argv[2];
const observer = observeTestFile(file);
const cases = [];
globalThis.test = (name, body) => cases.push({ name, body });
await import(file);
let failed = false;
for (const { name, body } of cases) {
try {
await (observer ? observer.case(name, body) : body());
} catch (error) {
failed = true;
console.error(name, error);
}
}
observer?.finish();
process.exitCode = failed ? 1 : 0;Each function has one place in your runner:
startRecordinggoes in the process that starts the run. It takesroot,suite,coverageFile,preconditions,mode,continuationsandcadence, with the meanings they have on the Vitest seam, except that a relative entry inpreconditionsresolves against the working directory, andstartRecordingrefuses no entry. Name your runner's own files and configuration inpreconditions: nothing loads them through a transform, so nothing else records that a test's outcome depends on them. The call setsVARIANCE_AUTHORITY_RECORDING, which every child process and worker thread inherits. If your runner builds a child's environment from nothing, spreadrecording.envinto it. UnderVARIANCE_AUTHORITY_STORY=1it also carries where each case's story goes.recording.finishgoes where your runner has each file's result. A file iscompletewhen every case in it ran to the end and passed, or was skipped. A file that failed, errored or stopped early recorded only part of what it would have, so the snapshot keeps it as evidence that selects it and never as a reach that excludes it.registerRecordinggoes in every process that loads product source, before it loads any. It instruments what Node evaluates through its own module hooks: ES modules, CommonJS, TypeScript that Node strips itself, and whatever a loader registered before it hands on. It needs Node 22.15 or newer.includenarrows which files count as product source; the default is JavaScript and TypeScript inside the checkout, without test files, dependencies or built output.unprobednames the ones a probe cannot sit in, as it does on the Vitest seam. It also cuts the test file being observed, statement by statement, so each case records which of its lines reached each region.instrumentModulereplaces it if your runner already transforms source. Call it last, on the JavaScript about to run, with themapfrom the file on disk when an earlier step moved lines. Records then name the lines you edited, not the lines the transform emitted. Run each test file throughcutTestFilethe same way: it leaves every line where it was and carries an inline map for the columns it moved.observeTestFilegoes around each test file, in the process that runs it, before that process loads the file. Run each case throughobserver.case(name, body), wherenameis the declaration path, such as['Checkout', 'applies a coupon']. The case index records it astest/checkout.test.js > Checkout > applies a coupon. Anything that runs before the first case is credited to the whole file: its imports, its top level and the hooks your runner ran first. Callobserver.finish()after the last case.
A process observes one test file at a time, because a probe writes to the
file observed at the moment it fires. Opening a second observer before the
first one's finish throws. A runner that loads every file before it runs
any case has no moment when only one file is running. Give it one: run each
file in its own process, or load and run files one after another.
Outside a recording, the functions do nothing. observeTestFile and
registerRecording return undefined, and instrumentModule returns the code
it was given. So the runner above runs your suite unchanged when no recording is
open.
If a file ran a module that no transform wrote a record for, the snapshot keeps
that file as incomplete. If no transform wrote anything at all, finish prints
that and names where to look.
Record what a driven page executed
A Storybook preview or a Playwright-driven application is built by one process
and driven by another, so the two halves are written down separately and joined
by the driver. testSelectionProbes() instruments product source in your own
build; the page counts crossings; and recordExecution mer
