Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,12 +247,36 @@ Per-language operators on top of the canonical set:

Reports a mutation score (killed / total). Mutants run fully in parallel — including mutants on the same file — using language-native isolation strategies:

- **Go**: `go test -overlay` so each worker sees its own mutated copy without touching the real source tree.
- **Go**: every mutant of a package is compiled into one test binary behind a runtime switch, so the package is built once rather than once per mutant. A traced run of each test records which mutants it reaches, and a mutant is then tested by running only those tests, fastest first. Tests in packages beneath the mutated one count too. A mutant that cannot share the build (for example one in a constant expression) falls back to its own `go test -overlay` run.
- **Rust**: per-mutant temp-copy of the crate directory (isolated `target/`).
- **TypeScript**: per-mutant in-place text edit with restore-on-defer, serialized by file.

Concurrency defaults to `runtime.NumCPU()` and is tunable with `--mutation-workers`. Use `--skip-mutation` to skip entirely, or `--mutation-sample-rate 20` for a faster-but-noisier subset.

#### What counts toward the score

Only mutants that compiled and were tested are scored. The summary lists everything else separately:

| Outcome | Scored as | Meaning |
|---|---|---|
| killed | killed | a test failed |
| timed out | killed | the tests ran far longer than they do unmutated |
| survived | survived | every test that reaches the mutant passed |
| not covered | survived | no test executes the mutated code (Go) |
| does not compile | excluded | the mutation is not a valid program, so it says nothing about the tests |
| not run | excluded | the budget ran out or the run was cancelled; a gating tier with any of these is at least WARN |

If a package's tests fail before any mutation is applied, its mutants are reported as not run instead of all "killed".

#### Keeping large diffs fast

- Mutants are tested Tier 1 first, then Tier 2, then Tier 3, so a time limit costs the least important results.
- `--mutation-budget 15m` caps the wall-clock time. On SIGINT/SIGTERM (a cancelled CI job) the run stops and the report covers what finished.
- `--mutation-cache-dir <dir>` reuses outcomes for packages whose sources, tests, in-repo dependencies, `go.mod`/`go.sum` and toolchain are unchanged since a cached run (Go). Persist the directory between CI runs to make re-pushes cheap.
- `--mutation-shard i/n` tests one of `n` slices of the mutants, to split a run across parallel jobs.
- `--mutation-confidence 0.99` stops a gating tier once its pass/fail verdict is statistically settled at that confidence.
- Sampling is seeded (`--mutation-seed`, default 1), so the same commit selects the same mutants.

#### Tiered mutation scoring

The raw score is misleading for observability-heavy codebases: logging / metrics calls (`log.*`, `metrics.*`, `console.*`, `tracing::info!`) generate many `statement_deletion` and `branch_removal` survivors that tests can't observe by design. Diffguard groups operators into three tiers so you can gate CI on the ones that matter:
Expand Down Expand Up @@ -348,10 +372,16 @@ Flags:
--skip-deadcode Skip dead code (unused symbol) detection
--skip-generated Skip files marked as generated (for example `Code generated ... DO NOT EDIT`) (default true)
--mutation-sample-rate float Percentage of mutants to test, 0-100 (default 100)
--test-timeout duration Per-mutant test timeout (default 30s)
--test-timeout duration Ceiling on a mutant's test run (default 30s). For Go the limit is derived from
how long the same tests take unmutated, and this caps it
--test-pattern string Pattern passed to the per-language test runner (scopes tests to speed up slow suites;
Go: `go test -run`, Rust: `cargo test --`, TS: forwarded as npm_config_test_pattern)
--mutation-workers int Max packages processed concurrently during mutation testing; 0 = runtime.NumCPU() (default 0)
--mutation-budget duration Wall-clock cap on mutation testing; mutants not reached are reported as not run (default 0 = none)
--mutation-seed int Seed for mutant sampling and early-stop ordering (default 1)
--mutation-shard string Test only shard i of n of the mutants, as i/n (e.g. 2/4)
--mutation-cache-dir string Directory for cached mutant outcomes; unchanged packages are not re-tested
--mutation-confidence float Stop a gating tier early once its verdict holds at this confidence (default 0 = off)
--tier1-threshold float Minimum kill % for Tier-1 (logic) mutations; below triggers FAIL (default 90)
--tier2-threshold float Minimum kill % for Tier-2 (semantic) mutations; below triggers WARN (default 70)
--output string Output format: text, json (default "text")
Expand Down
50 changes: 50 additions & 0 deletions cmd/diffguard/main.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package main

import (
"context"
"flag"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strings"
"syscall"
"time"

"github.com/0xPolygon/diffguard/internal/churn"
Expand Down Expand Up @@ -40,6 +43,11 @@ func main() {
flag.DurationVar(&cfg.TestTimeout, "test-timeout", 30*time.Second, "Per-mutant test binary timeout (e.g. 60s, 2m)")
flag.StringVar(&cfg.TestPattern, "test-pattern", "", "Test name pattern passed to `go test -run` for each mutant (speeds up mutation testing on packages with slow suites)")
flag.IntVar(&cfg.MutationWorkers, "mutation-workers", 0, "Max packages processed concurrently during mutation testing; 0 = runtime.NumCPU()")
flag.DurationVar(&cfg.MutationBudget, "mutation-budget", 0, "Wall-clock cap on mutation testing (e.g. 15m); mutants not reached are reported as not run. 0 = no cap")
flag.Int64Var(&cfg.MutationSeed, "mutation-seed", 1, "Seed for mutant sampling and early-stop ordering; the same seed selects the same mutants")
flag.StringVar(&cfg.MutationShard, "mutation-shard", "", "Test only shard i of n of the mutants, as i/n (e.g. 2/4), to split a run across jobs")
flag.StringVar(&cfg.MutationCacheDir, "mutation-cache-dir", "", "Directory for cached mutant outcomes; packages unchanged since a cached run are not re-tested")
flag.Float64Var(&cfg.MutationConfidence, "mutation-confidence", 0, "Stop a gating tier early once its pass/fail verdict holds at this confidence (e.g. 0.99); 0 = test every mutant")
flag.Float64Var(&cfg.Tier1Threshold, "tier1-threshold", 90, "Minimum kill % for Tier-1 (logic) mutations; below triggers FAIL")
flag.Float64Var(&cfg.Tier2Threshold, "tier2-threshold", 70, "Minimum kill % for Tier-2 (semantic) mutations; below triggers WARN. Tier-3 (observability) is report-only.")
flag.StringVar(&cfg.Output, "output", "text", "Output format: text, json")
Expand All @@ -65,6 +73,19 @@ func main() {
cfg.BaseBranch = detectBaseBranch(repoPath)
}

shardIndex, shardCount, err := parseShard(cfg.MutationShard)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
cfg.shardIndex, cfg.shardCount = shardIndex, shardCount

// On SIGINT/SIGTERM (a cancelled CI job) mutation testing stops and the
// report covers what finished, instead of the run dying with nothing.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
cfg.ctx = ctx

if err := run(repoPath, cfg); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
Expand All @@ -87,13 +108,34 @@ type Config struct {
TestTimeout time.Duration
TestPattern string
MutationWorkers int
MutationBudget time.Duration
MutationSeed int64
MutationShard string
MutationCacheDir string
MutationConfidence float64
Tier1Threshold float64
Tier2Threshold float64
Output string
FailOn string
BaseBranch string
Paths string
Language string

ctx context.Context
shardIndex int
shardCount int
}

// parseShard parses an "i/n" shard spec into its 1-based index and count.
// An empty spec means no sharding.
func parseShard(spec string) (index, count int, err error) {
if spec == "" {
return 0, 0, nil
}
if _, err := fmt.Sscanf(spec, "%d/%d", &index, &count); err != nil || index < 1 || index > count {
return 0, 0, fmt.Errorf("invalid --mutation-shard %q: want i/n with 1 <= i <= n", spec)
}
return index, count, nil
}

// langResult bundles the per-language analysis output so the orchestrator
Expand Down Expand Up @@ -324,6 +366,14 @@ func runAnalyses(repoPath string, d *diff.Result, cfg Config, l lang.Language) (
Workers: cfg.MutationWorkers,
Tier1Threshold: cfg.Tier1Threshold,
Tier2Threshold: cfg.Tier2Threshold,
Context: cfg.ctx,
Budget: cfg.MutationBudget,
Seed: cfg.MutationSeed,
ShardIndex: cfg.shardIndex,
ShardCount: cfg.shardCount,
CacheDir: cfg.MutationCacheDir,
Confidence: cfg.MutationConfidence,
Progress: os.Stderr,
})
if err != nil {
return nil, fmt.Errorf("mutation analysis: %w", err)
Expand Down
17 changes: 17 additions & 0 deletions cmd/diffguard/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -599,3 +599,20 @@ func findSectionBySuffix(r report.Report, metricPrefix, langName string) *report
}
return nil
}

func TestParseShard(t *testing.T) {
if i, n, err := parseShard(""); i != 0 || n != 0 || err != nil {
t.Errorf("empty spec: got %d/%d, %v", i, n, err)
}
if i, n, err := parseShard("2/4"); i != 2 || n != 4 || err != nil {
t.Errorf("2/4: got %d/%d, %v", i, n, err)
}
if i, n, err := parseShard("4/4"); i != 4 || n != 4 || err != nil {
t.Errorf("4/4: got %d/%d, %v", i, n, err)
}
for _, bad := range []string{"0/4", "5/4", "x", "2", "2/"} {
if _, _, err := parseShard(bad); err == nil {
t.Errorf("parseShard(%q): want an error", bad)
}
}
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ module github.com/0xPolygon/diffguard
go 1.26.10

require github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82

require golang.org/x/tools v0.50.0
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@ github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82 h1:6C8qej6f
github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82/go.mod h1:xe4pgH49k4SsmkQq5OT8abwhWmnzkhpgnXeekbx2efw=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
114 changes: 114 additions & 0 deletions internal/lang/goanalyzer/fingerprint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package goanalyzer

import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"time"
)

// fingerprintVersion is bumped whenever a change to the engine could give a
// mutant a different outcome on unchanged code.
const fingerprintVersion = "go-schemata-1"

// MutationFingerprint implements lang.Fingerprinter. The fingerprint covers
// everything in the repository that can change the outcome of a mutant in
// file's package: the toolchain, the module's dependency pins, and every
// file of every in-repo package that the package's tests (and the tests of
// the packages beneath it) are built from, including their testdata.
func (*Language) MutationFingerprint(repoPath, file string) (string, error) {
dir := filepath.Join(repoPath, filepath.Dir(file))
goCmd := func(args ...string) (string, error) {
res := proc{dir: dir, timeout: 5 * time.Minute, name: "go", args: args, keep: 16 << 20}.run(context.Background())
if res.err != nil {
return "", fmt.Errorf("go %s: %w", args[0], res.err)
}
return res.output, nil
}
env, err := goCmd("env", "GOVERSION", "GOMOD", "GOOS", "GOARCH", "GOFLAGS")
if err != nil {
return "", err
}
deps, err := goCmd("list", "-test", "-deps", "-f", "{{if not .Standard}}{{.Dir}}{{end}}", "./...")
if err != nil {
return "", err
}

h := sha256.New()
fmt.Fprintf(h, "%s\n%s\n", fingerprintVersion, env)
if fields := strings.Fields(env); len(fields) > 1 {
hashFile(h, fields[1])
hashFile(h, strings.TrimSuffix(fields[1], ".mod")+".sum")
}
for _, d := range repoDirs(repoPath, deps) {
if err := hashPackageDir(h, d); err != nil {
return "", err
}
}
return hex.EncodeToString(h.Sum(nil)), nil
}

// repoDirs returns the distinct directories of listOutput (one per line)
// that lie inside repoPath, sorted. Packages outside the repository are
// pinned by go.sum and need no hashing.
func repoDirs(repoPath, listOutput string) []string {
seen := map[string]bool{}
var dirs []string
for _, d := range strings.Fields(listOutput) {
rel, err := filepath.Rel(repoPath, d)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || seen[d] {
continue
}
seen[d] = true
dirs = append(dirs, d)
}
sort.Strings(dirs)
return dirs
}

// hashPackageDir hashes the files directly inside dir, plus everything
// under its testdata directory.
func hashPackageDir(h io.Writer, dir string) error {
entries, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, e := range entries {
path := filepath.Join(dir, e.Name())
if e.Type().IsRegular() {
hashFile(h, path)
}
if e.IsDir() && e.Name() == "testdata" {
hashTree(h, path)
}
}
return nil
}

// hashTree hashes every regular file under root.
func hashTree(h io.Writer, root string) {
filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err == nil && d.Type().IsRegular() {
hashFile(h, path)
}
return nil
})
}

// hashFile writes the file's path and content to h. An unreadable file
// contributes only its path.
func hashFile(h io.Writer, path string) {
fmt.Fprintf(h, "%s\x00", path)
if f, err := os.Open(path); err == nil {
n, _ := io.Copy(h, f)
f.Close()
fmt.Fprintf(h, "\x00%d\x00", n)
}
}
Loading
Loading