cache

package
v0.7.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cache implements PIT-style incremental analysis: per-mutant outcomes are persisted keyed by content hashes of the mutated file, the rest of its package's production sources (its //go:embed inputs included), and the files that decide what the covering tests assert. On the next run, mutants whose hashes still match are skipped.

The cache is a single JSON file (default .gomutants-cache.json), opt-in via the --cache flag. NOT_COVERED is intentionally not cached — coverage is recomputed every run by discover.FilterByCoverage, which keeps "no longer covered" reclassifications correct.

tests_hash is computed from the union of files identified by the TestFilesForFn callback (typically backed by the per-test coverage map + TestIndex). This handles cross-package -coverpkg correctly: tests in package B that exercise code in package A invalidate A's mutants when edited — and so do B's own helpers and production sources, which is where an end-to-end test keeps most of what it asserts.

Index

Constants

View Source
const SchemaVersion = 11

SchemaVersion is the on-disk format version. Bump when Entry shape or any hashing algorithm changes so old cache files are silently discarded rather than producing wrong skips.

v1: package-dir tests_hash (replaced — undercounted cross-package coverage).
v2: per-mutant tests_hash via TestFilesForFn; TIMED_OUT now gated on tests_hash.
v3: top-level CoverageKey/CoverageProfile so warm no-op runs can skip
    `go test -coverprofile`. HashCoverageInputs framing is part of the
    invariant — any algorithm change there demands another bump.
v4: GoToolchain joins the metadata gate, and EQUIVALENT is a reusable
    status. Equivalence verdicts depend on the compiler, so a toolchain
    change must discard the cache.
v5: TestFlags joins the metadata gate. --test-flags changes what the
    inner `go test` actually executes, so a verdict recorded under one
    value must not be replayed under another.
v6: TestFlags cache identity preserves argv order. v5 sorted distinct
    flag names, but arbitrary test-binary flags can interact even when
    their names differ, so old keys can describe a different run.
v7: pkg_hash joins the per-mutant key. Through v6 the key covered only
    the mutated file and the covering tests, so editing a *sibling*
    file in the same package replayed a stale verdict — a KILLED mutant
    whose kill depended on a constant next door stayed KILLED after that
    constant changed, without executing anything. v6 entries carry no
    pkg_hash and must not be replayed. The coverage key gained an
    //go:embed dimension in the same version: a v7 profile recorded
    before it simply mismatches and is recomputed, which is why this
    framing change rides on v7 rather than a bump of its own.
v8: LIVED means the mutant survived every test suite that can kill it,
    not just the tests the coverage map routed it to, which could miss
    a test that covers the line only after another test has run. v7
    LIVED entries can be such false survivors. With -coverpkg the
    tests dimension now spans every package whose tests link the
    mutant's, as all of them decide a LIVED verdict. Entries record
    whether the mutant was re-checked, so a cache hit counts in the
    report's re-check totals as the run that tested it did.
v9: KILLED means the mutant failed tests that pass together without it.
    Through v8 a mutant could be routed to covering tests that each
    pass alone but fail together on unmutated code — one leaves state
    behind that breaks another — so v8 KILLED entries can be such
    false kills.
v10: NOT_VIABLE means the mutation itself doesn't compile. Through v9 a
    mutant that removed the last use of an import or local variable
    failed on Go's unused checks instead, so v9 NOT_VIABLE entries can
    be mutants that now compile (see patch.ApplyMutant) and must run.
v11: Likewise for a replacement that fused with the token next to it in
    unformatted source (`return!ok` → `returnok`, `a<0` → `a<-1`), now
    spaced off from it, so v10 NOT_VIABLE entries can again be mutants
    that compile.

Variables

This section is empty.

Functions

func HashFile

func HashFile(absPath string) (string, error)

HashFile returns the hex-encoded sha256 of the file at absPath.

Implemented over os.ReadFile rather than open+io.Copy: the file is already small (cache entries are keyed off prod-source files we already pre-read into memory in the discovery phase, and test files in the rare cold-cache path), and a single error path means no hidden mutants where one if-err return is shadowed by another.

func Save

func Save(c *Cache, path string) error

Save writes c to path, creating parent directories as needed. The write is atomic within the target's filesystem: serialization goes to a temp file in the same directory, then os.Rename swaps it into place. A crash before the rename leaves the prior cache file untouched; a crash after leaves the new one fully written. Either way the file on disk parses successfully on the next Load.

Types

type Cache

type Cache struct {
	SchemaVersion int    `json:"schema_version"`
	GoModule      string `json:"go_module"`
	ToolVersion   string `json:"tool_version"`
	// BuildTags is the `--tags` value the cache was built with. It joins
	// the metadata-gate identity (alongside SchemaVersion/GoModule/
	// ToolVersion): changing build tags can flip a mutant's outcome by
	// pulling in different compiled-in code even when the mutated source
	// and its test files are byte-identical, so a tag change must discard
	// the whole cache. omitempty + the default "" keeps pre-existing
	// (tag-less) caches reusable for tag-less runs.
	BuildTags string `json:"build_tags,omitempty"`
	// TestFlags is the `--test-flags` value the cache was built with, in
	// canonical form — whitespace collapsed but argv order preserved (see
	// config.CanonicalTestFlags), so behaviorally distinct orderings cannot
	// share a generation. It joins the metadata-gate identity for
	// the same reason BuildTags does, but the pressure here is sharper:
	// the documented workflow is alternating between a cheap gate run
	// (`--test-flags '-rapid.checks=20'`) and a full scoring run, and
	// per-mutant verdicts are not comparable across the two. A LIVED
	// recorded at 20 checks must not be replayed as the verdict for a
	// 100-check run, nor a KILLED under a full suite for a `-short` one.
	// omitempty + the default "" keeps flag-less caches reusable for
	// flag-less runs.
	TestFlags string `json:"test_flags,omitempty"`
	// GoToolchain is the project's `go version` string the cache was built
	// with. It joins the metadata-gate identity because the EQUIVALENT
	// classification is decided by the compiler's generated code, which can
	// change between toolchains; a toolchain change must therefore discard
	// the cache rather than reuse stale equivalence (or any other) verdicts.
	// omitempty + the default "" keeps pre-v4 caches inert (they fail the
	// gate on the SchemaVersion bump anyway).
	GoToolchain     string  `json:"go_toolchain,omitempty"`
	CoverageKey     string  `json:"coverage_key,omitempty"`
	CoverageProfile string  `json:"coverage_profile,omitempty"`
	Entries         []Entry `json:"entries"`
}

Cache is the on-disk artifact. Entries are keyed by mutant identity (rel_file, line, col, type, start_offset, original, replacement).

CoverageKey/CoverageProfile (v3+) memoize the output of `go test -count=1 -coverprofile` so warm no-op runs can skip the coverage subprocess. The key fingerprints every input that could change the profile (see HashCoverageInputs); on a match the stored profile is parsed via coverage.ParseBytes instead. The omitempty tags are defensive forward-compat: a future code path that skips writing the coverage fields (e.g. when the user disables coverage caching) won't pollute the JSON with empty strings.

func Load

func Load(path, goModule, toolVersion, buildTags, testFlags, goToolchain string) *Cache

Load reads the cache from path. Returns an empty (but valid) Cache stamped with the caller's identity if the file is missing, fails to parse, or has a mismatched schema/module/tool version. Callers should treat the returned Cache as authoritative regardless of error — Load never returns nil.

Mutator definitions can change between tool versions, so stale entries can silently produce wrong skips. Pessimistic invalidation on any metadata mismatch is the safe default; the metadata gate is the *only* observable rejection path because the read- and parse-failure branches both produce a zero-value Cache that fails the gate identically (SchemaVersion=0 ≠ caller's SchemaVersion).

func (*Cache) Lookup

func (c *Cache) Lookup(mutants []mutator.Mutant, h *Hasher, testFilesFor TestFilesForFn) int

Lookup applies cache hits to the mutants slice in place. For each pending mutant whose identity key + content hashes match a cached entry, sets Status, Duration, Rechecked and FromCache so the runner's Pending-only filter naturally skips it. Returns the number of hits.

Skip rules — pkg_hash gates every reusable status:

prior=KILLED      + prod_hash + pkg_hash + tests_hash match → reuse
prior=LIVED       + prod_hash + pkg_hash + tests_hash match → reuse
prior=TIMED_OUT   + prod_hash + pkg_hash + tests_hash match → reuse
prior=EQUIVALENT  + prod_hash + pkg_hash + tests_hash match → reuse
prior=NOT_VIABLE  + prod_hash + pkg_hash match (compile failure — tests irrelevant) → reuse
otherwise → leave Pending

TIMED_OUT is gated on tests because adding a faster killer test could legitimately turn a prior timeout into KILLED on the next run; without the gate we'd silently skip a now-killable mutant. NOT_VIABLE is the one outcome independent of *test* content (it failed to compile), so it alone skips the tests_hash check — but it is not independent of the rest of the package: a sibling file supplying a missing symbol turns a prior NOT_VIABLE into a real, testable mutant, so pkg_hash still gates it.

pkg_hash exists because prod_hash describes only the mutated file. A mutant compiles as part of its whole package, so its verdict can flip when a *sibling* file changes while the mutated file and the covering tests stay byte-identical — a KILLED mutant whose kill depends on a constant defined next door survives once that constant changes. Without this dimension the cache replays the stale KILLED without executing anything, which is the dangerous direction to be wrong in: silent false confidence.

Scope, stated plainly. Between them the three dimensions cover: the mutated file, every other non-test .go file in its package, that package's //go:embed inputs, every _test.go file in its package, and — for a covering test the coverage map places in another package, which takes an instrumentation scope wider than the package under test (--integration, or an explicit --coverpkg) — that package's test *and* production sources.

That last half is conditional on the wider scope for a reason: the coverage map's test names carry no package, so without one a foreign declaring directory is a name collision rather than a dependency, and expanding on it would fold unrelated packages' sources into tests_hash. See TestIndex.CoveringFiles.

What is left: an edit in a package the mutant's package *imports*. That mutant still replays a stale verdict. Closing it needs the forward import closure, and the churn it would add is real — a change to a widely imported package would invalidate most of the repository's cache. The --integration direction is not in that bucket even though it looks similar: the reverse-dependency closure is already computed for that mode and the covering package is named for us by the coverage map, so it costs nothing to hash.

Also outside the key: //go:embed inputs of *test* files (go list's TestEmbedFiles/XTestEmbedFiles). A golden file embedded by a test and edited to expect a looser value replays a stale KILLED, the same shape as the production-embed case that is closed above.

Hash failures (unreadable file/dir) are silently treated as a miss for that mutant so a transient I/O error never produces a wrong skip.

The "no entries" and "key not found" cases fall through naturally: indexing an empty (or nil — see below) idx with `idx[k]` returns the zero-value Entry whose Status="" parses to Pending and fails canReuse, so no extra short-circuit is needed.

func (*Cache) String

func (c *Cache) String() string

String returns a short human-readable summary of the cache state for debug output.

func (*Cache) Update

func (c *Cache) Update(mutants []mutator.Mutant, h *Hasher, projectDir string, testFilesFor TestFilesForFn)

Update merges this run's results into c and drops entries whose prod_hash or pkg_hash no longer matches the current source. Entries for files outside this run's mutant set (e.g. excluded by --changed-since) are preserved when their file still exists with matching content *and* their package still hashes the same — a carried-over entry is reused by the next run's Lookup, so it has to clear the same two gates Lookup applies.

projectDir lets us resolve a stored RelFile back to an absolute path for re-hashing prior entries.

type Entry

type Entry struct {
	RelFile     string `json:"rel_file"`
	Line        int    `json:"line"`
	Col         int    `json:"col"`
	Type        string `json:"type"`
	StartOffset int    `json:"start_offset"`
	Original    string `json:"original"`
	Replacement string `json:"replacement"`
	ProdHash    string `json:"prod_hash"`
	// PkgHash (v7+) fingerprints the non-test .go files in the mutant's
	// own package directory — see Hasher.HashPkgFiles. ProdHash alone
	// describes the mutated file; a mutant's verdict is decided by the
	// whole package that file compiles into, so this is the dimension
	// that catches a sibling file changing underneath a byte-identical
	// mutated file. It gates every reusable status, NOT_VIABLE included.
	PkgHash    string `json:"pkg_hash,omitempty"`
	TestsHash  string `json:"tests_hash"`
	Status     string `json:"status"`
	DurationMs int64  `json:"duration_ms"`
	// Rechecked (v8+) is the mutant's Rechecked, restored on a hit so the
	// report's re-check counts don't depend on how many mutants hit.
	Rechecked bool `json:"rechecked,omitempty"`
}

Entry is one cached mutant outcome.

type Hasher

type Hasher struct {
	// contains filtered or unexported fields
}

Hasher memoizes per-file hashes within a single run. Not safe for concurrent use — the pipeline calls Lookup/Update sequentially.

func NewHasher

func NewHasher(srcCache map[string][]byte) *Hasher

NewHasher returns an empty per-run hasher. If srcCache is non-nil, it is used as a fast path for File() so production sources already read into memory by the discovery phase aren't re-read from disk.

func (*Hasher) File

func (h *Hasher) File(absPath string) (string, error)

File returns the hash of absPath, computing it on first call.

func (*Hasher) HashCoverageInputs

func (h *Hasher) HashCoverageInputs(pkgDirs []string, projectDir, coverPkg, tags, testFlags, toolchain, envSnapshot string) (string, error)

HashCoverageInputs returns a stable fingerprint of every input that could change the coverage profile produced by `go test -coverprofile`. A mismatch on the next run invalidates the cached profile.

pkgDirs must contain every directory whose source could land in the profile, not just the user's target packages. With -coverpkg=<pattern> covering a broader set than the target, the caller is responsible for resolving the expanded list (e.g. via a second go-list call) before invoking this method.

Each input dimension is hashed with the same length-prefixed framing used by HashTestFiles so STATEMENT_REMOVE / boundary-alias mutations against the new writes are observable from the tests. A read error on any required file is propagated — callers should treat it as a miss and re-run coverage.

go.sum is optional: a missing file contributes the empty-content hash. This keeps the helper usable on modules with no recorded checksums (single-module repos with no external deps) without an extra branch at every call site. testFlags is the user's --test-flags string. It is a hash dimension because those flags reach the coverage run itself: `-short` can skip tests, which changes which lines the profile marks covered, so a profile recorded under one value must never be replayed under another.

func (*Hasher) HashPkgFiles

func (h *Hasher) HashPkgFiles(dir string) (string, error)

HashPkgFiles returns a stable hex-encoded sha256 over every non-test .go file directly inside dir, followed by every file the package's production //go:embed directives pull in. It is the per-mutant key's dependency dimension: a mutant's verdict is decided by the whole package it compiles into, not just the file the mutation lives in, so a sibling file changing must invalidate that mutant even when its own file is byte-identical.

Embedded files count as package inputs for the same reason. A mutant killed by a test that asserts on a parsed schema.json survives once that schema changes, with every .go file byte-identical — the same stale-KILLED shape a sibling .go edit produces. They are hashed only when the caller supplied them via SetEmbedFiles; a package with no embed directives (the overwhelming majority) writes nothing extra and hashes exactly as before.

Framing matches HashTestFiles — sorted, deduped, length-prefixed — so no STATEMENT_REMOVE or boundary-alias mutation against the writes can go unobserved. The embed half is framed by embedFrames, which the coverage key shares.

Results are memoized per directory for the lifetime of the Hasher, so a package is listed and hashed once per run rather than once per mutant. The memo is keyed on dir alone. SetSrcCache retakes it for the mutants' packages once their sources are frozen, so the hash a verdict is stored under is that snapshot, not one from before coverage ran.

A read or listing error is propagated — callers treat it as a cache miss for that mutant, never as a match.

func (*Hasher) HashTestFiles

func (h *Hasher) HashTestFiles(absPaths []string) (string, error)

HashTestFiles returns a stable hex-encoded sha256 over the union of the test files in absPaths. Inputs are sorted and de-duplicated, so any iteration order produces the same hash. The per-file Fprintf uses length-prefixed framing so concatenation can't alias one file boundary into another.

An empty (or nil) input returns the hash of the empty string — the same value the loop produces naturally without an early return, so no special-case branch is needed. A read error on any file is propagated — callers should treat this as a cache miss for that mutant.

func (*Hasher) SetEmbedFiles

func (h *Hasher) SetEmbedFiles(embeds map[string][]string)

SetEmbedFiles attaches the //go:embed inputs of each package, keyed by absolute package directory and valued by the dir-relative slash paths `go list` resolved the patterns to. HashPkgFiles folds them into pkg_hash, so editing an embedded file invalidates the mutants of the package that embeds it.

Called after package resolution, which happens later than the Hasher's construction (the coverage-key calc needs a Hasher first) — hence a setter rather than a constructor argument. Directories absent from the map contribute no embed inputs, which is the correct answer for the packages that have none.

There is no memo to invalidate here: HashPkgFiles is reached only from Lookup and Update, both of which run well after package resolution, so no directory hash predates this call.

func (*Hasher) SetSrcCache

func (h *Hasher) SetSrcCache(srcCache map[string][]byte)

SetSrcCache attaches an in-memory source map (typically populated by discover.PreReadFiles) after the hasher was constructed. Used by callers that need a Hasher before pre-read completes (e.g. the coverage-key calc runs before discovery) and want subsequent File() calls to skip the disk read.

Every package input is hashed again here, at the moment srcCache froze the bytes the mutants are measured on. The memos the coverage-key calc left behind were read from disk before coverage and the baseline ran, so every non-test file memo is dropped: not just srcCache's own files, but a sibling srcCache leaves out (--exclude-files, a build tag) and an embedded file, both of which the mutants still compile from disk. A verdict measured on an edit saved in between must not be keyed on the version before it, or reverting the edit would replay that verdict.

The pkg_hash of every directory srcCache has a file in is then taken right away rather than on first use. A --run-mutant-id run skips Lookup, so first use would be Update, after the mutant ran — and a sibling edited during the run would be recorded against a verdict measured on the old one. A directory that fails to hash memoizes nothing; Lookup and Update try again and treat a failure as a miss.

Test-file memos are kept. srcCache holds production sources only, so a test file's hash taken by the coverage-key calc stays the one the cache entries are stored under: a snapshot from before any mutant ran, which an edit to the test mid-run can only turn into a miss on the next run. A re-hash at write time would instead record the edited test against a verdict measured on the old one, and replay that verdict.

type TestFilesForFn

type TestFilesForFn func(m mutator.Mutant) []string

TestFilesForFn resolves a mutant to the set of absolute test-file paths whose contents gate cache reuse for that mutant. The integrator wires this through TestIndex.CoveringFiles: every _test.go in the mutant's package directory, plus the files declaring whichever tests the per-test coverage map attributes to the mutant (those can live in another package under -coverpkg, and that package is then hashed whole). The package-wide halves are what keep an edit to a test helper — which declares no test entry point, so no coverage-derived name names it — from replaying a stale verdict.

type TestIndex

type TestIndex struct {
	// contains filtered or unexported fields
}

TestIndex resolves test function names to the absolute paths of the _test.go files where they are declared, and lists every _test.go file in each known package directory. It is built once per run from a parse of every test file in scope.

Cross-package coverage (tests in package B exercising code in package A via -coverpkg) means the per-test coverage map can return test names whose defining files live outside the mutant's own package directory. FilesFor surfaces those, so tests_hash includes every covering test file regardless of which package declared it. CoveringFiles combines both lookups into the set callers actually hash.

func BuildTestIndex

func BuildTestIndex(pkgDirs []string) *TestIndex

BuildTestIndex parses each _test.go file in pkgDirs and indexes top-level test/benchmark/example/fuzz function declarations.

Behavior on errors:

  • A directory that fails to read is skipped (no entries indexed).
  • A file that fails to parse is recorded in byDir (so fallback hashing still includes it) but contributes no byName entries — its tests are unknown, so any mutant resolving through it falls back to the directory-wide list.

Names that exist in multiple packages map to all declaring files; the per-test coverage map collapses package context, so we treat a same- named test as potentially covering through any of those files.

func (*TestIndex) AllInDir

func (ti *TestIndex) AllInDir(pkgDir string) []string

AllInDir returns every _test.go file in pkgDir (absolute paths). It is the local half of every covering set — see CoveringFiles — and the whole of it when the per-test coverage map is unavailable.

func (*TestIndex) CoveringFiles

func (ti *TestIndex) CoveringFiles(pkgDir string, testNames []string, crossPkg bool) []string

CoveringFiles returns the files outside prod_hash and pkg_hash whose content gates cache reuse for a mutant in pkgDir that the per-test coverage map attributes to testNames. Pass a nil/empty testNames when no coverage map is available.

The result is always a superset of AllInDir(pkgDir): every test file in the mutant's own package is in the set, not just the files declaring the covering tests. A package-level test helper — a table builder, a custom assertion, a fake — lives in a _test.go file that need not declare any test entry point at all, so BuildTestIndex records no name for it and no coverage-derived name can ever resolve to it. Loosen an assertion inside such a helper and a KILLED mutant starts surviving while its own file, its package's non-test files, and the covering test's file are all byte-identical. Test files are deliberately outside pkg_hash (folding them in would invalidate test-independent NOT_VIABLE entries on every test edit), so tests_hash is the only dimension that can carry them, and it can only carry them at package granularity.

testNames then adds the cross-package half: with -coverpkg (--integration) the covering tests can be declared outside pkgDir entirely, and those files gate the mutant too. Names the index doesn't know contribute nothing — they resolve to no file, and the local set already stands.

crossPkg says whether a foreign declaring directory can be a genuine cross-package coverage relationship: the caller sets it when this run instruments beyond the package under test (--integration, or an explicit --coverpkg), which is what it takes for a test outside pkgDir to record coverage on the mutant at all. When it is set, a foreign directory contributes its whole package the way pkgDir does: every _test.go in it (the same helper-only argument as above, which applies verbatim to R's assertion helpers) and every non-test .go file. Under --integration the dependency arrow points the other way from the usual one: mutants live in target package T, the covering tests live in importer R, and pkg_hash only ever hashes T. R's helpers and fixture builders — most of what an end-to-end test is made of — would otherwise sit in no dimension of the key at all, so loosening R's fixture would replay T's mutant as KILLED after it started surviving. pkgDir itself is excluded from this: pkg_hash already covers the mutant's own package, and re-adding it here would make an unrelated production edit invalidate the tests dimension too.

Without crossPkg the expansion is skipped and only the declaring file itself is added, because a foreign hit is then a name collision rather than a dependency. TestMap.TestsFor deliberately projects package context out of the covering names, so FilesFor("TestNew") resolves to every indexed package declaring a TestNew — and TestAdd, TestParse or TestString live in several packages of most repositories, this one included. Expanding on a collision would fold unrelated packages' production sources into tests_hash and make an edit anywhere in them invalidate this mutant: package-scoped invalidation degraded to repository-scoped by a name two packages happened to share. The declaring file itself is still added — it is one file, and it keeps the conservative direction on the off chance that the name really is the covering test.

A nil receiver yields nil, but there is no `ti == nil` guard here: both lookups this delegates to are already nil-safe and return nil, so the loops below iterate zero times and files stays nil. An explicit guard would be an unobservable branch — the same reason BuildTestIndex elides its redundant `|| f == nil`.

func (*TestIndex) FilesFor

func (ti *TestIndex) FilesFor(testName string) []string

FilesFor returns the test files declaring testName, or nil if the name is unknown. Multiple files are returned when the same name was declared in more than one indexed package.

func (*TestIndex) PackageFiles

func (ti *TestIndex) PackageFiles(dir string) []string

PackageFiles returns every indexed file of dir: its test files and its production sources. A package whose whole suite runs for a mutant (see coverage.TestMap.SuitePkgs) decides the verdict through all of them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL