From 3ae94920ea477b30924995db7b8b9cd308f320a2 Mon Sep 17 00:00:00 2001 From: kamuikatsurgi Date: Fri, 20 Nov 2026 13:56:56 +0530 Subject: [PATCH] feat(mutation): compile each package's mutants once and run only the tests that reach them Go mutation testing ran a fresh go test -overlay ./... for every mutant, so cost grew linearly with the diff: heimdall-v2 PR 701 (568 mutants) took 21m on a 12-core machine and was cancelled at the 40m CI timeout. All mutants of a package are now compiled into one test binary behind a runtime switch. A traced run of each test records which mutants it reaches, and a mutant is tested by running only those tests. Mutants that cannot share the build fall back to their own overlay run. Also: - classify outcomes (killed, timed out, survived, not covered, does not compile, not run) and score only mutants that compiled and ran - identify sites by offset so two sites on a line are distinct mutants - zero returned values with typed zero values so the mutant compiles - run gating tiers first; add a wall-clock budget, progress lines and a partial report on SIGINT/SIGTERM - add a result cache, sharding, early stopping and seeded sampling --- README.md | 34 +- cmd/diffguard/main.go | 50 ++ cmd/diffguard/main_test.go | 17 + go.mod | 2 + go.sum | 2 + internal/lang/goanalyzer/fingerprint.go | 114 +++ internal/lang/goanalyzer/mutation_apply.go | 83 +-- .../lang/goanalyzer/mutation_apply_test.go | 153 +++- internal/lang/goanalyzer/mutation_generate.go | 32 +- .../lang/goanalyzer/mutation_generate_test.go | 34 + internal/lang/goanalyzer/mutation_locate.go | 170 +++++ internal/lang/goanalyzer/proc.go | 78 ++ internal/lang/goanalyzer/schemata.go | 379 ++++++++++ internal/lang/goanalyzer/schemata_test.go | 247 +++++++ internal/lang/goanalyzer/session.go | 317 ++++++++ internal/lang/goanalyzer/session_prepare.go | 390 ++++++++++ internal/lang/goanalyzer/session_test.go | 696 ++++++++++++++++++ internal/lang/goanalyzer/testrunner.go | 11 +- internal/lang/lang.go | 102 +++ internal/lang/lang_test.go | 19 + internal/mutation/cache.go | 130 ++++ internal/mutation/cache_test.go | 140 ++++ internal/mutation/earlystop.go | 107 +++ internal/mutation/earlystop_test.go | 102 +++ internal/mutation/mutation.go | 364 +++------ internal/mutation/mutation_extra_test.go | 8 +- internal/mutation/plan.go | 68 ++ internal/mutation/plan_test.go | 134 ++++ internal/mutation/run.go | 275 +++++++ internal/mutation/run_test.go | 476 ++++++++++++ internal/mutation/section.go | 187 +++++ internal/mutation/tiers.go | 26 +- internal/mutation/tiers_test.go | 2 +- 33 files changed, 4580 insertions(+), 369 deletions(-) create mode 100644 internal/lang/goanalyzer/fingerprint.go create mode 100644 internal/lang/goanalyzer/mutation_locate.go create mode 100644 internal/lang/goanalyzer/proc.go create mode 100644 internal/lang/goanalyzer/schemata.go create mode 100644 internal/lang/goanalyzer/schemata_test.go create mode 100644 internal/lang/goanalyzer/session.go create mode 100644 internal/lang/goanalyzer/session_prepare.go create mode 100644 internal/lang/goanalyzer/session_test.go create mode 100644 internal/mutation/cache.go create mode 100644 internal/mutation/cache_test.go create mode 100644 internal/mutation/earlystop.go create mode 100644 internal/mutation/earlystop_test.go create mode 100644 internal/mutation/plan.go create mode 100644 internal/mutation/plan_test.go create mode 100644 internal/mutation/run.go create mode 100644 internal/mutation/run_test.go create mode 100644 internal/mutation/section.go diff --git a/README.md b/README.md index a46b4ab..f05d8ff 100644 --- a/README.md +++ b/README.md @@ -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 ` 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: @@ -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") diff --git a/cmd/diffguard/main.go b/cmd/diffguard/main.go index 8cd7b6f..c5212e3 100644 --- a/cmd/diffguard/main.go +++ b/cmd/diffguard/main.go @@ -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" @@ -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") @@ -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) @@ -87,6 +108,11 @@ 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 @@ -94,6 +120,22 @@ type Config struct { 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 @@ -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) diff --git a/cmd/diffguard/main_test.go b/cmd/diffguard/main_test.go index fdee859..286a75c 100644 --- a/cmd/diffguard/main_test.go +++ b/cmd/diffguard/main_test.go @@ -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) + } + } +} diff --git a/go.mod b/go.mod index b110adc..187d804 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index 702e57b..8dae582 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/internal/lang/goanalyzer/fingerprint.go b/internal/lang/goanalyzer/fingerprint.go new file mode 100644 index 0000000..a89eef8 --- /dev/null +++ b/internal/lang/goanalyzer/fingerprint.go @@ -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) + } +} diff --git a/internal/lang/goanalyzer/mutation_apply.go b/internal/lang/goanalyzer/mutation_apply.go index b9c7da5..ee563cb 100644 --- a/internal/lang/goanalyzer/mutation_apply.go +++ b/internal/lang/goanalyzer/mutation_apply.go @@ -8,6 +8,8 @@ import ( "go/token" "strings" + "golang.org/x/tools/go/ast/astutil" + "github.com/0xPolygon/diffguard/internal/lang" ) @@ -28,68 +30,26 @@ func (mutantApplierImpl) ApplyMutation(absPath string, site lang.MutantSite) ([] if err != nil { return nil, nil } - - var applied bool - if site.Operator == "statement_deletion" { - applied = applyStatementDeletion(fset, f, site) - } else { - applied = applyMutationToAST(fset, f, site) - } - if !applied { + if !applyMutationToAST(fset, f, site) { return nil, nil } return renderFile(fset, f), nil } +// applyMutationToAST mutates the node m refers to in place and reports +// whether it found one. func applyMutationToAST(fset *token.FileSet, f *ast.File, m lang.MutantSite) bool { - applied := false - ast.Inspect(f, func(n ast.Node) bool { - if applied || n == nil { - return false - } - if fset.Position(n.Pos()).Line != m.Line { - return true - } - applied = tryApplyMutation(n, m) - return !applied - }) - return applied -} - -// applyStatementDeletion walks BlockStmts instead of the flat ast.Inspect -// used for other operators because it needs the containing block to replace -// a statement. -func applyStatementDeletion(fset *token.FileSet, f *ast.File, m lang.MutantSite) bool { - applied := false - ast.Inspect(f, func(n ast.Node) bool { - if applied { - return false - } - block, ok := n.(*ast.BlockStmt) - if !ok { + applied := locateSites(fset, f, []lang.MutantSite{m}, func(c *astutil.Cursor, _ int, fn *ast.FuncType) bool { + switch m.Operator { + case "return_value": + return applyReturnMutation(c.Node(), fn) + case "statement_deletion": + c.Replace(&ast.EmptyStmt{Semicolon: c.Node().Pos()}) return true } - if tryDeleteInBlock(fset, block, m) { - applied = true - return false - } - return true + return tryApplyMutation(c.Node(), m) }) - return applied -} - -func tryDeleteInBlock(fset *token.FileSet, block *ast.BlockStmt, m lang.MutantSite) bool { - for i, stmt := range block.List { - if fset.Position(stmt.Pos()).Line != m.Line { - continue - } - if _, ok := stmt.(*ast.ExprStmt); !ok { - continue - } - block.List[i] = &ast.EmptyStmt{Semicolon: stmt.Pos()} - return true - } - return false + return applied[0] } func tryApplyMutation(n ast.Node, m lang.MutantSite) bool { @@ -98,8 +58,6 @@ func tryApplyMutation(n ast.Node, m lang.MutantSite) bool { return applyBinaryMutation(n, m) case "boolean_substitution": return applyBoolMutation(n, m) - case "return_value": - return applyReturnMutation(n) case "incdec": return applyIncDecMutation(n) case "branch_removal": @@ -139,14 +97,15 @@ func applyBoolMutation(n ast.Node, m lang.MutantSite) bool { return true } -func applyReturnMutation(n ast.Node) bool { +// applyReturnMutation replaces the returned values with the zero value of +// each of fn's result types, so the mutant compiles whatever those types are. +func applyReturnMutation(n ast.Node, fn *ast.FuncType) bool { ret, ok := n.(*ast.ReturnStmt) - if !ok { + zeros := zeroResults(fn) + if !ok || len(zeros) == 0 { return false } - for i := range ret.Results { - ret.Results[i] = zeroValueExpr(ret.Results[i]) - } + ret.Results = zeros return true } @@ -197,10 +156,6 @@ func parseMutationOp(desc string) (from, to token.Token) { return fromOp, toOp } -func zeroValueExpr(expr ast.Expr) ast.Expr { - return &ast.Ident{Name: "nil", NamePos: expr.Pos()} -} - func renderFile(fset *token.FileSet, f *ast.File) []byte { var buf bytes.Buffer if err := printer.Fprint(&buf, fset, f); err != nil { diff --git a/internal/lang/goanalyzer/mutation_apply_test.go b/internal/lang/goanalyzer/mutation_apply_test.go index 2181908..c747560 100644 --- a/internal/lang/goanalyzer/mutation_apply_test.go +++ b/internal/lang/goanalyzer/mutation_apply_test.go @@ -3,12 +3,14 @@ package goanalyzer import ( "go/ast" "go/parser" + "go/printer" "go/token" "os" "path/filepath" "strings" "testing" + "github.com/0xPolygon/diffguard/internal/diff" "github.com/0xPolygon/diffguard/internal/lang" ) @@ -91,23 +93,41 @@ func TestApplyBoolMutation_WrongNodeType(t *testing.T) { } } +func intResults(n int) *ast.FuncType { + fields := make([]*ast.Field, n) + for i := range fields { + fields[i] = &ast.Field{Type: ast.NewIdent("int")} + } + return &ast.FuncType{Results: &ast.FieldList{List: fields}} +} + func TestApplyReturnMutation_Success(t *testing.T) { ret := &ast.ReturnStmt{Results: []ast.Expr{&ast.Ident{Name: "x", NamePos: 1}}} - if !applyReturnMutation(ret) { + if !applyReturnMutation(ret, intResults(2)) { t.Error("expected successful apply") } - if ident, ok := ret.Results[0].(*ast.Ident); !ok || ident.Name != "nil" { - t.Error("expected result replaced with nil") + if len(ret.Results) != 2 { + t.Fatalf("results = %d, want one per declared result (2)", len(ret.Results)) + } + if _, ok := ret.Results[0].(*ast.StarExpr); !ok { + t.Error("expected result replaced with *new(T)") } } func TestApplyReturnMutation_WrongNodeType(t *testing.T) { ident := &ast.Ident{Name: "x"} - if applyReturnMutation(ident) { + if applyReturnMutation(ident, intResults(1)) { t.Error("expected false for non-ReturnStmt") } } +func TestApplyReturnMutation_NoResults(t *testing.T) { + ret := &ast.ReturnStmt{Results: []ast.Expr{ast.NewIdent("x")}} + if applyReturnMutation(ret, nil) || applyReturnMutation(ret, &ast.FuncType{}) { + t.Error("expected false when the enclosing function declares no results") + } +} + func TestApplyIncDecMutation_Inc(t *testing.T) { stmt := &ast.IncDecStmt{Tok: token.INC} if !applyIncDecMutation(stmt) { @@ -170,14 +190,6 @@ func TestTryApplyMutation_Bool(t *testing.T) { } } -func TestTryApplyMutation_Return(t *testing.T) { - ret := &ast.ReturnStmt{Results: []ast.Expr{&ast.Ident{Name: "x", NamePos: 1}}} - site := lang.MutantSite{Operator: "return_value"} - if !tryApplyMutation(ret, site) { - t.Error("expected successful apply") - } -} - func TestTryApplyMutation_Unknown(t *testing.T) { ident := &ast.Ident{Name: "x"} site := lang.MutantSite{Operator: "unknown_operator"} @@ -312,14 +324,105 @@ func f() {} } func TestZeroValueExpr(t *testing.T) { - original := &ast.Ident{Name: "x", NamePos: 42} - result := zeroValueExpr(original) - ident, ok := result.(*ast.Ident) - if !ok { - t.Fatal("expected *ast.Ident") + var buf strings.Builder + if err := printer.Fprint(&buf, token.NewFileSet(), zeroValueExpr(ast.NewIdent("error"))); err != nil { + t.Fatal(err) } - if ident.Name != "nil" { - t.Errorf("name = %q, want nil", ident.Name) + if buf.String() != "*new(error)" { + t.Errorf("zero value = %q, want *new(error)", buf.String()) + } +} + +func TestResultTypes_ExpandsGroupedNames(t *testing.T) { + fn := &ast.FuncType{Results: &ast.FieldList{List: []*ast.Field{ + {Names: []*ast.Ident{ast.NewIdent("a"), ast.NewIdent("b")}, Type: ast.NewIdent("int")}, + {Type: ast.NewIdent("error")}, + }}} + if got := len(resultTypes(fn)); got != 3 { + t.Errorf("resultTypes = %d, want 3", got) + } + if resultTypes(nil) != nil || resultTypes(&ast.FuncType{}) != nil { + t.Error("expected nil for a function without results") + } +} + +// applyAt generates the mutants of code, applies the one matching operator +// whose line is `line` and whose index among those is nth, and returns the +// mutated source. +func applyAt(t *testing.T, code, operator string, line, nth int) string { + t.Helper() + fp := filepath.Join(t.TempDir(), "test.go") + if err := os.WriteFile(fp, []byte(code), 0644); err != nil { + t.Fatal(err) + } + fc := diff.FileChange{Path: "test.go", Regions: []diff.ChangedRegion{{StartLine: 1, EndLine: 1000}}} + sites, err := mutantGeneratorImpl{}.GenerateMutants(fp, fc, nil) + if err != nil { + t.Fatal(err) + } + for _, s := range sites { + if s.Operator != operator || s.Line != line { + continue + } + if nth > 0 { + nth-- + continue + } + out, _ := mutantApplierImpl{}.ApplyMutation(fp, s) + if out == nil { + t.Fatalf("mutation %+v was not applied", s) + } + return string(out) + } + t.Fatalf("no %s mutant on line %d", operator, line) + return "" +} + +// Two sites on one line must each mutate their own node. Matching by line +// alone mutated the first one twice and never tested the second. +func TestApplyMutation_SecondSiteOnLine(t *testing.T) { + code := "package test\n\nfunc f(a, b int) bool {\n\treturn a == 1 || b == 2\n}\n" + first := applyAt(t, code, "negate_conditional", 4, 0) + second := applyAt(t, code, "negate_conditional", 4, 1) + if !strings.Contains(first, "a != 1 || b == 2") { + t.Errorf("first site: got\n%s", first) + } + if !strings.Contains(second, "a == 1 || b != 2") { + t.Errorf("second site: got\n%s", second) + } +} + +func TestApplyMutation_ChainedOperatorsAreDistinctSites(t *testing.T) { + code := "package test\n\nfunc f(a, b, c int) int {\n\treturn a - b - c\n}\n" + if got := applyAt(t, code, "math_operator", 4, 1); !strings.Contains(got, "a + b - c") { + t.Errorf("inner subtraction: got\n%s", got) + } + if got := applyAt(t, code, "math_operator", 4, 0); !strings.Contains(got, "a - b + c") { + t.Errorf("outer subtraction: got\n%s", got) + } +} + +// A zeroed return must compile for any result types, including when the +// original returns a multi-value call. +func TestApplyMutation_ReturnZeroValuesAreTyped(t *testing.T) { + code := "package test\n\nfunc g() (string, error) { return \"x\", nil }\n\nfunc f() (string, error) {\n\treturn g()\n}\n" + got := applyAt(t, code, "return_value", 6, 0) + if !strings.Contains(got, "return *new(string), *new(error)") { + t.Errorf("got\n%s", got) + } +} + +func TestApplyMutation_ReturnInsideFuncLitUsesItsSignature(t *testing.T) { + code := "package test\n\nfunc f() error {\n\tg := func() int {\n\t\treturn 7\n\t}\n\t_ = g\n\treturn nil\n}\n" + if got := applyAt(t, code, "return_value", 5, 0); !strings.Contains(got, "return *new(int)") { + t.Errorf("got\n%s", got) + } +} + +func TestApplyMutation_StatementDeletionInCaseClause(t *testing.T) { + code := "package test\n\nfunc f(x int) {\n\tswitch x {\n\tcase 1:\n\t\tdoThing()\n\t}\n}\n\nfunc doThing() {}\n" + if got := applyAt(t, code, "statement_deletion", 6, 0); strings.Contains(got, "\t\tdoThing()") { + t.Errorf("call not removed:\n%s", got) } } @@ -343,3 +446,15 @@ func TestParseMutationOp(t *testing.T) { } } } + +// Two boolean literals on one line are separate sites; each mutant must +// flip its own literal. +func TestApplyMutation_SecondIdentifierOnLine(t *testing.T) { + code := "package test\n\nfunc f() (bool, bool) {\n\treturn true, true\n}\n" + if got := applyAt(t, code, "boolean_substitution", 4, 0); !strings.Contains(got, "return false, true") { + t.Errorf("first literal: got\n%s", got) + } + if got := applyAt(t, code, "boolean_substitution", 4, 1); !strings.Contains(got, "return true, false") { + t.Errorf("second literal: got\n%s", got) + } +} diff --git a/internal/lang/goanalyzer/mutation_generate.go b/internal/lang/goanalyzer/mutation_generate.go index 8a4503b..ec6d42a 100644 --- a/internal/lang/goanalyzer/mutation_generate.go +++ b/internal/lang/goanalyzer/mutation_generate.go @@ -35,7 +35,11 @@ func (mutantGeneratorImpl) GenerateMutants(absPath string, fc diff.FileChange, d if !fc.ContainsLine(line) || disabled[line] { return true } - mutants = append(mutants, mutantsFor(fc.Path, line, n)...) + offset := fset.Position(anchorPos(n)).Offset + for _, m := range mutantsFor(fc.Path, line, n) { + m.Offset = offset + mutants = append(mutants, m) + } return true }) return mutants, nil @@ -113,15 +117,14 @@ func boolMutants(file string, line int, ident *ast.Ident) []lang.MutantSite { // returnMutants generates zero-value return mutations. // -// Returns whose every result is already the literal identifier `nil` are -// skipped: the zero-value mutation rewrites each result to `nil`, producing -// an identical AST and therefore an equivalent mutant that can never be -// killed. +// Returns whose every result is already a zero literal (nil, false, 0, "", T{}) +// are skipped: the zero-value mutation would produce an equivalent mutant +// that can never be killed. func returnMutants(file string, line int, ret *ast.ReturnStmt) []lang.MutantSite { if len(ret.Results) == 0 { return nil } - if allLiteralNil(ret.Results) { + if allZeroLiterals(ret.Results) { return nil } return []lang.MutantSite{{ @@ -132,16 +135,27 @@ func returnMutants(file string, line int, ret *ast.ReturnStmt) []lang.MutantSite }} } -func allLiteralNil(exprs []ast.Expr) bool { +func allZeroLiterals(exprs []ast.Expr) bool { for _, e := range exprs { - ident, ok := e.(*ast.Ident) - if !ok || ident.Name != "nil" { + if !isZeroLiteral(e) { return false } } return true } +func isZeroLiteral(e ast.Expr) bool { + switch v := e.(type) { + case *ast.Ident: + return v.Name == "nil" || v.Name == "false" + case *ast.BasicLit: + return v.Value == "0" || v.Value == `""` + case *ast.CompositeLit: + return len(v.Elts) == 0 + } + return false +} + // incdecMutants swaps ++ with -- and vice versa. func incdecMutants(file string, line int, stmt *ast.IncDecStmt) []lang.MutantSite { var newTok token.Token diff --git a/internal/lang/goanalyzer/mutation_generate_test.go b/internal/lang/goanalyzer/mutation_generate_test.go index 3ecd8cf..4672d79 100644 --- a/internal/lang/goanalyzer/mutation_generate_test.go +++ b/internal/lang/goanalyzer/mutation_generate_test.go @@ -2,6 +2,7 @@ package goanalyzer import ( "go/ast" + "go/parser" "go/token" "os" "path/filepath" @@ -311,3 +312,36 @@ func f(x int) bool { t.Error("expected mutants on un-annotated line 8") } } + +func TestIsZeroLiteral(t *testing.T) { + cases := map[string]bool{ + "nil": true, "false": true, "0": true, `""`: true, "T{}": true, "[]int{}": true, + "true": false, "1": false, `"x"`: false, "x": false, "T{A: 1}": false, "f()": false, + } + for src, want := range cases { + expr, err := parser.ParseExpr(src) + if err != nil { + t.Fatal(err) + } + if got := isZeroLiteral(expr); got != want { + t.Errorf("isZeroLiteral(%s) = %v, want %v", src, got, want) + } + } +} + +// A return that is already all zero values has no observable zero-value +// mutant; one with any non-zero result does. +func TestReturnMutants_SkipsZeroValueReturns(t *testing.T) { + for src, want := range map[string]int{ + "return nil, false": 0, "return 0, T{}": 0, "return nil, err": 1, "return 1": 1, + } { + f, err := parser.ParseFile(token.NewFileSet(), "", "package p\nfunc f() {"+src+"}", 0) + if err != nil { + t.Fatal(err) + } + ret := f.Decls[0].(*ast.FuncDecl).Body.List[0].(*ast.ReturnStmt) + if got := len(returnMutants("f.go", 1, ret)); got != want { + t.Errorf("%q: %d mutants, want %d", src, got, want) + } + } +} diff --git a/internal/lang/goanalyzer/mutation_locate.go b/internal/lang/goanalyzer/mutation_locate.go new file mode 100644 index 0000000..7bce6b8 --- /dev/null +++ b/internal/lang/goanalyzer/mutation_locate.go @@ -0,0 +1,170 @@ +package goanalyzer + +import ( + "go/ast" + "go/token" + "strings" + + "golang.org/x/tools/go/ast/astutil" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// anchorPos is the position that identifies a node as a mutation site. A +// binary expression is anchored at its operator: `a - b - c` holds two +// subtractions that start at the same position but have distinct operators. +func anchorPos(n ast.Node) token.Pos { + if b, ok := n.(*ast.BinaryExpr); ok { + return b.OpPos + } + return n.Pos() +} + +// siteVisitor mutates the node under the cursor for sites[site] and reports +// whether it did. fn is the innermost enclosing function's type, or nil. +type siteVisitor func(c *astutil.Cursor, site int, fn *ast.FuncType) bool + +// siteLocator walks a file and hands each mutation site's node to a visitor. +type siteLocator struct { + fset *token.FileSet + sites []lang.MutantSite + // byOffset and byLine index the sites by where their node is anchored: + // sites carrying an offset match exactly, sites without one match the + // first fitting node on their line. + byOffset map[int][]int + byLine map[int][]int + applied []bool + funcs []*ast.FuncType + visit siteVisitor +} + +// locateSites visits the node of every site in f, innermost nodes first, and +// reports which sites the visitor applied. Each site is applied at most once. +func locateSites(fset *token.FileSet, f *ast.File, sites []lang.MutantSite, visit siteVisitor) []bool { + l := &siteLocator{ + fset: fset, + sites: sites, + byOffset: map[int][]int{}, + byLine: map[int][]int{}, + applied: make([]bool, len(sites)), + visit: visit, + } + for i, site := range sites { + if site.Offset != 0 { + l.byOffset[site.Offset] = append(l.byOffset[site.Offset], i) + } else { + l.byLine[site.Line] = append(l.byLine[site.Line], i) + } + } + astutil.Apply(f, l.pre, l.post) + return l.applied +} + +func (l *siteLocator) pre(c *astutil.Cursor) bool { + if fn := funcTypeOf(c.Node()); fn != nil { + l.funcs = append(l.funcs, fn) + } + return true +} + +func (l *siteLocator) post(c *astutil.Cursor) bool { + n := c.Node() + if n == nil { + return true + } + l.visitSites(c, n, l.byOffset[l.fset.Position(anchorPos(n)).Offset]) + l.visitSites(c, n, l.byLine[l.fset.Position(n.Pos()).Line]) + if funcTypeOf(n) != nil { + l.funcs = l.funcs[:len(l.funcs)-1] + } + return true +} + +// visitSites offers n to each candidate site that has not been applied yet +// and whose operator mutates this kind of node. +func (l *siteLocator) visitSites(c *astutil.Cursor, n ast.Node, candidates []int) { + for _, i := range candidates { + if !l.applied[i] && operatorFits(n, l.sites[i]) { + l.applied[i] = l.visit(c, i, l.enclosingFunc()) + } + } +} + +func (l *siteLocator) enclosingFunc() *ast.FuncType { + if len(l.funcs) == 0 { + return nil + } + return l.funcs[len(l.funcs)-1] +} + +func funcTypeOf(n ast.Node) *ast.FuncType { + switch fn := n.(type) { + case *ast.FuncDecl: + return fn.Type + case *ast.FuncLit: + return fn.Type + } + return nil +} + +// operatorFits reports whether n is the kind of node site's operator +// mutates. For binary operators the source operator must match too. +func operatorFits(n ast.Node, site lang.MutantSite) bool { + switch node := n.(type) { + case *ast.BinaryExpr: + from, to := parseMutationOp(site.Description) + return to != token.ILLEGAL && node.Op == from && isBinaryOperator(site.Operator) + case *ast.Ident: + return site.Operator == "boolean_substitution" && strings.HasPrefix(site.Description, node.Name+" ->") + case *ast.ReturnStmt: + return site.Operator == "return_value" + case *ast.IncDecStmt: + return site.Operator == "incdec" + case *ast.IfStmt: + return site.Operator == "branch_removal" && node.Body != nil + case *ast.ExprStmt: + _, isCall := node.X.(*ast.CallExpr) + return site.Operator == "statement_deletion" && isCall + } + return false +} + +func isBinaryOperator(op string) bool { + return op == "conditional_boundary" || op == "negate_conditional" || op == "math_operator" +} + +// resultTypes returns one type expression per result of fn, expanding +// grouped names (`(a, b int)` yields int twice). +func resultTypes(fn *ast.FuncType) []ast.Expr { + if fn == nil || fn.Results == nil { + return nil + } + var types []ast.Expr + for _, field := range fn.Results.List { + n := len(field.Names) + if n == 0 { + n = 1 + } + for i := 0; i < n; i++ { + types = append(types, field.Type) + } + } + return types +} + +// zeroValueExpr returns `*new(T)`, an expression that is the zero value of +// any type T without needing type information. +func zeroValueExpr(typ ast.Expr) ast.Expr { + return &ast.StarExpr{X: &ast.CallExpr{Fun: ast.NewIdent("new"), Args: []ast.Expr{typ}}} +} + +// zeroResults returns the zero-value results for a return in fn, or nil if +// fn has no results to zero. +func zeroResults(fn *ast.FuncType) []ast.Expr { + types := resultTypes(fn) + zeros := make([]ast.Expr, len(types)) + for i, t := range types { + zeros[i] = zeroValueExpr(t) + } + return zeros +} diff --git a/internal/lang/goanalyzer/proc.go b/internal/lang/goanalyzer/proc.go new file mode 100644 index 0000000..6bae6c3 --- /dev/null +++ b/internal/lang/goanalyzer/proc.go @@ -0,0 +1,78 @@ +package goanalyzer + +import ( + "bytes" + "context" + "errors" + "os" + "os/exec" + "time" +) + +// outputTail is how much of a child's output is kept for reports. +const outputTail = 4 << 10 + +// pipeGrace is how long a finished child's output pipes may stay open. +const pipeGrace = 2000 * time.Millisecond + +// procResult is the outcome of one child process. +type procResult struct { + err error + output string + duration time.Duration + timedOut bool +} + +// proc describes a child process to run. +type proc struct { + dir string + env []string // appended to the parent's environment + timeout time.Duration + name string + args []string + // keep is how many trailing bytes of output to return; zero means + // outputTail. + keep int +} + +// run executes the process, killing it when timeout elapses or ctx is done. +// timedOut is set only for the timeout: a cancelled ctx is the caller's to +// detect, since it means the result must be discarded. +func (p proc) run(ctx context.Context) procResult { + runCtx, cancel := context.WithTimeout(ctx, p.timeout) + defer cancel() + + cmd := exec.CommandContext(runCtx, p.name, p.args...) + cmd.Dir = p.dir + // A child must not inherit this process's own mutant selection, which + // is set when diffguard's tests run under mutation testing themselves. + cmd.Env = append(os.Environ(), mutantEnv+"=", traceEnv+"=") + cmd.Env = append(cmd.Env, p.env...) + if p.dir != "" { + // The go tool takes its working directory from PWD. Left at the + // parent's value it resolves symlinks itself, and overlay paths + // written with the unresolved directory stop matching. + cmd.Env = append(cmd.Env, "PWD="+p.dir) + } + // A test that leaves a child holding the pipes must not hang the run. + cmd.WaitDelay = pipeGrace + var out bytes.Buffer + cmd.Stdout = &out + cmd.Stderr = &out + + start := time.Now() + err := cmd.Run() + return procResult{ + err: err, + output: tail(out.Bytes(), p.keep), + duration: time.Since(start), + timedOut: ctx.Err() == nil && errors.Is(runCtx.Err(), context.DeadlineExceeded), + } +} + +func tail(b []byte, n int) string { + if n <= 0 { + n = outputTail + } + return string(b[max(0, len(b)-n):]) +} diff --git a/internal/lang/goanalyzer/schemata.go b/internal/lang/goanalyzer/schemata.go new file mode 100644 index 0000000..971347a --- /dev/null +++ b/internal/lang/goanalyzer/schemata.go @@ -0,0 +1,379 @@ +package goanalyzer + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "strconv" + "strings" + + "golang.org/x/tools/go/ast/astutil" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// Mutant schemata: instead of compiling one program per mutant, every mutant +// of a package is compiled into a single program behind a runtime switch. +// The test binary is built once; a mutant is selected per run through an +// environment variable. +const ( + // mutantEnv selects the active mutant id; unset or 0 runs unmutated code. + mutantEnv = "DIFFGUARD_MUTANT" + // traceEnv names a file that receives the id of every mutation point + // the run reaches, one per line. + traceEnv = "DIFFGUARD_TRACE" + // schemataFileName is the helper file added to an instrumented package. + schemataFileName = "zz_diffguard_schemata.go" + schemataPrefix = "__dg" + switchFunc = schemataPrefix + "On" +) + +// binaryHelpers maps an operator to the helper that evaluates it, or its +// mutation when the helper's mutant is active. Operands are evaluated once, +// in source order, exactly as the original expression would. +var binaryHelpers = map[token.Token]string{ + token.GTR: schemataPrefix + "Gt", + token.GEQ: schemataPrefix + "Ge", + token.LSS: schemataPrefix + "Lt", + token.LEQ: schemataPrefix + "Le", + token.ADD: schemataPrefix + "Add", + token.SUB: schemataPrefix + "Sub", + token.MUL: schemataPrefix + "Mul", + token.QUO: schemataPrefix + "Quo", +} + +// instrumentFile returns the source of absPath with each site guarded by +// the switch for its id, plus which sites could be embedded. Sites that +// cannot be expressed as a guarded mutation are left for the overlay path. +func instrumentFile(absPath string, sites []lang.MutantSite, ids []int) (src []byte, embedded []bool, pkgName string, err error) { + fset, f, err := parseFile(absPath, parser.ParseComments) + if err != nil { + return nil, nil, "", err + } + // Synthesized nodes carry no positions, which lets the printer misplace + // ordinary comments into invalid spots. Only directives affect the build. + f.Comments = directiveComments(f.Comments) + embedded = locateSites(fset, f, sites, func(c *astutil.Cursor, i int, fn *ast.FuncType) bool { + return embedMutant(c, sites[i].Operator, ids[i], fn) + }) + return renderFile(fset, f), embedded, f.Name.Name, nil +} + +func directiveComments(groups []*ast.CommentGroup) []*ast.CommentGroup { + var kept []*ast.CommentGroup + for _, g := range groups { + if hasDirective(g) { + kept = append(kept, g) + } + } + return kept +} + +func hasDirective(g *ast.CommentGroup) bool { + for _, c := range g.List { + for _, prefix := range []string{"//go:", "// +build", "//export ", "//line "} { + if strings.HasPrefix(c.Text, prefix) { + return true + } + } + } + return false +} + +func embedMutant(c *astutil.Cursor, operator string, id int, fn *ast.FuncType) bool { + switch operator { + case "negate_conditional": + c.Replace(toggled(c.Node().(ast.Expr), id)) + return true + case "conditional_boundary", "math_operator": + return embedBinary(c, id) + case "boolean_substitution": + return embedBool(c, id) + case "return_value": + return embedReturn(c, id, fn) + case "incdec": + return embedIncDec(c, id) + case "branch_removal": + stmt := c.Node().(*ast.IfStmt) + stmt.Body = block(&ast.IfStmt{Cond: not(switchCall(id)), Body: stmt.Body}) + return true + case "statement_deletion": + return embedDeletion(c, id) + } + return false +} + +// toggled returns `((e) != __dgOn(id))`: e, negated while the mutant is +// active. The result stays an untyped boolean, so it fits wherever e did. +func toggled(e ast.Expr, id int) ast.Expr { + return paren(&ast.BinaryExpr{X: paren(e), Op: token.NEQ, Y: switchCall(id)}) +} + +func embedBinary(c *astutil.Cursor, id int) bool { + expr := c.Node().(*ast.BinaryExpr) + if isLiteral(expr.X) && isLiteral(expr.Y) { + // Constant arithmetic is exact; a runtime helper would not be. + return false + } + c.Replace(call(binaryHelpers[expr.Op], intLit(id), expr.X, expr.Y)) + return true +} + +func isLiteral(e ast.Expr) bool { + _, ok := e.(*ast.BasicLit) + return ok +} + +func embedBool(c *astutil.Cursor, id int) bool { + switch c.Name() { + case "Sel", "Name", "Names", "Label": + // An identifier slot, not an expression: `true` here is a name. + return false + } + c.Replace(toggled(c.Node().(ast.Expr), id)) + return true +} + +func embedReturn(c *astutil.Cursor, id int, fn *ast.FuncType) bool { + zeros := zeroResults(fn) + if c.Index() < 0 || len(zeros) == 0 { + return false + } + c.Replace(&ast.IfStmt{ + Cond: switchCall(id), + Body: block(&ast.ReturnStmt{Results: zeros}), + Else: block(c.Node().(ast.Stmt)), + }) + return true +} + +func embedIncDec(c *astutil.Cursor, id int) bool { + stmt := c.Node().(*ast.IncDecStmt) + helper := schemataPrefix + "Inc" + if stmt.Tok == token.DEC { + helper = schemataPrefix + "Dec" + } + c.Replace(&ast.ExprStmt{X: call(helper, intLit(id), &ast.UnaryExpr{Op: token.AND, X: stmt.X})}) + return true +} + +func embedDeletion(c *astutil.Cursor, id int) bool { + if c.Index() < 0 { + return false + } + c.Replace(&ast.IfStmt{Cond: not(switchCall(id)), Body: block(c.Node().(ast.Stmt))}) + return true +} + +func switchCall(id int) ast.Expr { return call(switchFunc, intLit(id)) } + +func call(fn string, args ...ast.Expr) *ast.CallExpr { + return &ast.CallExpr{Fun: ast.NewIdent(fn), Args: args} +} + +func intLit(n int) ast.Expr { + return &ast.BasicLit{Kind: token.INT, Value: strconv.Itoa(n)} +} + +func paren(e ast.Expr) ast.Expr { return &ast.ParenExpr{X: e} } + +func not(e ast.Expr) ast.Expr { return &ast.UnaryExpr{Op: token.NOT, X: e} } + +func block(stmts ...ast.Stmt) *ast.BlockStmt { return &ast.BlockStmt{List: stmts} } + +// blamedMutants returns the ids of the mutants responsible for a compile +// error at line:col of instrumented source, or nil if none can be blamed. +// +// An error inside a helper call or a zeroed return belongs to that mutant. +// Any other error (typically "missing return") comes from a statement that +// was wrapped in a guard, so every guard in the enclosing function is blamed. +func blamedMutants(src []byte, line, col int) []int { + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, "", src, 0) + if err != nil { + return nil + } + tf := fset.File(f.Pos()) + if line < 1 || line > tf.LineCount() { + return nil + } + pos := tf.LineStart(line) + token.Pos(col-1) + path, _ := astutil.PathEnclosingInterval(f, pos, pos) + for _, n := range path { + if id, ok := owningMutant(n); ok { + return []int{id} + } + } + for _, n := range path { + if fn, ok := n.(*ast.FuncDecl); ok { + return guardIDs(fn) + } + } + return nil +} + +// owningMutant reports the mutant a node was synthesized for: a helper +// call, or the if statement that selects a zeroed return. +func owningMutant(n ast.Node) (int, bool) { + if stmt, ok := n.(*ast.IfStmt); ok { + n = stmt.Cond + } + c, ok := n.(*ast.CallExpr) + if !ok || len(c.Args) == 0 { + return 0, false + } + fn, ok := c.Fun.(*ast.Ident) + lit, isLit := c.Args[0].(*ast.BasicLit) + if !ok || !isLit || !strings.HasPrefix(fn.Name, schemataPrefix) { + return 0, false + } + id, err := strconv.Atoi(lit.Value) + return id, err == nil +} + +// guardIDs returns the ids of every `!__dgOn(id)` guard in fn. +func guardIDs(fn *ast.FuncDecl) []int { + var ids []int + ast.Inspect(fn, func(n ast.Node) bool { + u, ok := n.(*ast.UnaryExpr) + if !ok || u.Op != token.NOT { + return true + } + if id, ok := owningMutant(u.X); ok { + ids = append(ids, id) + } + return true + }) + return ids +} + +// schemataHelperSource returns the helper file for an instrumented package. +// Imports are aliased so they cannot collide with the package's own names. +func schemataHelperSource(pkgName string) []byte { + return []byte(fmt.Sprintf(schemataHelperTemplate, pkgName, mutantEnv, traceEnv)) +} + +const schemataHelperTemplate = `// Code generated by diffguard for mutation testing. DO NOT EDIT. + +package %s + +import ( + __dgos "os" + __dgstrconv "strconv" + __dgsync "sync" +) + +type __dgNum interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | + ~float32 | ~float64 +} + +type __dgOrd interface { + __dgNum | ~string +} + +var ( + __dgActive = func() int { + n, _ := __dgstrconv.Atoi(__dgos.Getenv(%q)) + return n + }() + __dgTrace = __dgos.Getenv(%q) + __dgMu __dgsync.Mutex + __dgSeen __dgsync.Map +) + +func __dgOn(k int) bool { + if __dgTrace != "" { + __dgRecord(k) + } + return __dgActive == k +} + +func __dgRecord(k int) { + if _, seen := __dgSeen.LoadOrStore(k, true); seen { + return + } + __dgMu.Lock() + defer __dgMu.Unlock() + f, err := __dgos.OpenFile(__dgTrace, __dgos.O_APPEND|__dgos.O_CREATE|__dgos.O_WRONLY, 0o644) + if err != nil { + return + } + f.WriteString(__dgstrconv.Itoa(k) + "\n") + f.Close() +} + +func __dgGt[T __dgOrd](k int, a, b T) bool { + if __dgOn(k) { + return a >= b + } + return a > b +} + +func __dgGe[T __dgOrd](k int, a, b T) bool { + if __dgOn(k) { + return a > b + } + return a >= b +} + +func __dgLt[T __dgOrd](k int, a, b T) bool { + if __dgOn(k) { + return a <= b + } + return a < b +} + +func __dgLe[T __dgOrd](k int, a, b T) bool { + if __dgOn(k) { + return a < b + } + return a <= b +} + +func __dgAdd[T __dgNum](k int, a, b T) T { + if __dgOn(k) { + return a - b + } + return a + b +} + +func __dgSub[T __dgNum](k int, a, b T) T { + if __dgOn(k) { + return a + b + } + return a - b +} + +func __dgMul[T __dgNum](k int, a, b T) T { + if __dgOn(k) { + return a / b + } + return a * b +} + +func __dgQuo[T __dgNum](k int, a, b T) T { + if __dgOn(k) { + return a * b + } + return a / b +} + +func __dgInc[T __dgNum](k int, p *T) { + if __dgOn(k) { + *p-- + return + } + *p++ +} + +func __dgDec[T __dgNum](k int, p *T) { + if __dgOn(k) { + *p++ + return + } + *p-- +} +` diff --git a/internal/lang/goanalyzer/schemata_test.go b/internal/lang/goanalyzer/schemata_test.go new file mode 100644 index 0000000..6c145a5 --- /dev/null +++ b/internal/lang/goanalyzer/schemata_test.go @@ -0,0 +1,247 @@ +package goanalyzer + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// instrumentSource instruments every mutant of code and returns the result +// with the sites, numbering mutants from 1 in generation order. +func instrumentSource(t *testing.T, code string) (string, []lang.MutantSite, []bool) { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "test.go"), []byte(code), 0o644); err != nil { + t.Fatal(err) + } + sites := sitesOf(t, dir, "test.go") + ids := make([]int, len(sites)) + for i := range ids { + ids[i] = i + 1 + } + src, embedded, pkg, err := instrumentFile(filepath.Join(dir, "test.go"), sites, ids) + if err != nil { + t.Fatal(err) + } + if pkg != "test" { + t.Errorf("package name = %q, want test", pkg) + } + return string(src), sites, embedded +} + +func TestInstrumentFile_GuardsEachOperator(t *testing.T) { + src, _, embedded := instrumentSource(t, `package test + +func f(a, b int) (int, bool) { + if a > b { + a++ + b-- + note() + } + return a * b, a == b +} + +func note() {} +`) + for _, want := range []string{ + "if __dgGt(2, a, b) {\n\t\tif !__dgOn(1) {", + "__dgInc(3, &a)", + "__dgDec(4, &b)", + "if !__dgOn(5) {\n\t\t\t\tnote()", + "if __dgOn(6) {\n\t\treturn *new(int), *new(bool)\n\t} else {", + "return __dgMul(7, a, b), ((a == b) != __dgOn(8))", + } { + if !strings.Contains(src, want) { + t.Errorf("instrumented source is missing %q:\n%s", want, src) + } + } + for i, ok := range embedded { + if !ok { + t.Errorf("mutant %d was not embedded", i+1) + } + } +} + +func TestInstrumentFile_BooleanLiteralStaysUntyped(t *testing.T) { + src, _, _ := instrumentSource(t, "package test\n\ntype flag bool\n\nfunc f() flag {\n\tvar on flag = true\n\treturn on\n}\n") + if !strings.Contains(src, "var on flag = ((true) != __dgOn(1))") { + t.Errorf("got:\n%s", src) + } +} + +// Arithmetic on two literals is folded exactly by the compiler; routing it +// through a runtime helper could change the unmutated result. +func TestInstrumentFile_LeavesLiteralArithmeticToTheOverlayPath(t *testing.T) { + src, sites, embedded := instrumentSource(t, "package test\n\nfunc f() float64 {\n\tx := 0.1 + 0.2\n\treturn x\n}\n") + for i, s := range sites { + if s.Operator == "math_operator" && embedded[i] { + t.Errorf("literal arithmetic was embedded:\n%s", src) + } + } + if !strings.Contains(src, "x := 0.1 + 0.2") { + t.Errorf("literal arithmetic was rewritten:\n%s", src) + } +} + +func TestInstrumentFile_KeepsOnlyDirectiveComments(t *testing.T) { + src, _, _ := instrumentSource(t, "//go:build !never\n\npackage test\n\n// f is documented.\n//\n//go:noinline\nfunc f(a int) bool {\n\t// plain comment\n\treturn a == 1\n}\n") + if !strings.Contains(src, "//go:build !never") || !strings.Contains(src, "//go:noinline") { + t.Errorf("directives were dropped:\n%s", src) + } + if strings.Contains(src, "plain comment") { + t.Errorf("ordinary comments should be dropped:\n%s", src) + } +} + +func TestInstrumentFile_ParseError(t *testing.T) { + path := filepath.Join(t.TempDir(), "bad.go") + os.WriteFile(path, []byte("package"), 0o644) + if _, _, _, err := instrumentFile(path, nil, nil); err == nil { + t.Error("want a parse error") + } +} + +func TestHasDirective(t *testing.T) { + src, _, _ := instrumentSource(t, "package test\n\n//export f\nfunc f() {}\n\n// +build ignore\nvar a = 1\n\n//line x.go:1\nvar b = 2\n\n// go: not a directive\nvar c = 3\n") + for _, want := range []string{"//export f", "// +build ignore", "//line x.go:1"} { + if !strings.Contains(src, want) { + t.Errorf("missing %q in:\n%s", want, src) + } + } + if strings.Contains(src, "not a directive") { + t.Errorf("non-directive kept:\n%s", src) + } +} + +func lineCol(src, needle string) (int, int) { + i := strings.Index(src, needle) + before := src[:i] + return strings.Count(before, "\n") + 1, i - strings.LastIndex(before, "\n") +} + +func TestBlamedMutants(t *testing.T) { + src := `package test + +func f(a, b string, n int) (string, error) { + if !__dgOn(1) { + note() + } + if __dgOn(2) { + return *new(string), *new(error) + } else { + return __dgAdd(3, a, b), nil + } +} + +func g(n int) int { + if n > 0 { + if !__dgOn(4) { + return 1 + } + } + if !__dgOn(5) { + panic("x") + } +} + +var top = 1 +` + at := func(needle string) []int { + line, col := lineCol(src, needle) + return blamedMutants([]byte(src), line, col) + } + if got := at("a, b), nil"); !reflect.DeepEqual(got, []int{3}) { + t.Errorf("error in a helper call's argument: got %v, want [3]", got) + } + if got := at("*new(string)"); !reflect.DeepEqual(got, []int{2}) { + t.Errorf("error in a zeroed return: got %v, want [2]", got) + } + // "missing return" is reported at the function's closing brace. + closing := strings.Index(src, "}\n\nvar top") + line := strings.Count(src[:closing], "\n") + 1 + if got := blamedMutants([]byte(src), line, 1); !reflect.DeepEqual(got, []int{4, 5}) { + t.Errorf("unattributed error in g: got %v, want every guard in g [4 5]", got) + } + if got := at("top = 1"); got != nil { + t.Errorf("error outside any function: got %v, want nil", got) + } + if got := blamedMutants([]byte(src), 999, 1); got != nil { + t.Errorf("line out of range: got %v", got) + } + if got := blamedMutants([]byte(src), 0, 1); got != nil { + t.Errorf("line zero: got %v", got) + } + if got := blamedMutants([]byte("not go"), 1, 1); got != nil { + t.Errorf("unparseable source: got %v", got) + } +} + +func TestSchemataHelperSource(t *testing.T) { + src := string(schemataHelperSource("widgets")) + for _, want := range []string{"package widgets\n", `Getenv("DIFFGUARD_MUTANT")`, `Getenv("DIFFGUARD_TRACE")`, "func __dgOn(k int) bool"} { + if !strings.Contains(src, want) { + t.Errorf("helper source is missing %q", want) + } + } +} + +func TestMutationFingerprint(t *testing.T) { + root := writeModule(t, sampleSource, sampleTests) + l := &Language{} + print := func() string { + t.Helper() + p, err := l.MutationFingerprint(root, "p/p.go") + if err != nil { + t.Fatal(err) + } + return p + } + base := print() + if base == "" || base != print() { + t.Fatal("the fingerprint must be stable for unchanged code") + } + + changes := map[string]string{ + "p/p_test.go": sampleTests + "\n// changed\n", + "p/testdata/in/a.txt": "fixture", + "go.mod": "module example.com/sample\n\ngo 1.25\n", + "p/p.go": sampleSource + "\n// changed\n", + } + seen := map[string]bool{base: true} + for _, name := range []string{"p/p_test.go", "p/testdata/in/a.txt", "go.mod", "p/p.go"} { + path := filepath.Join(root, name) + os.MkdirAll(filepath.Dir(path), 0o755) + if err := os.WriteFile(path, []byte(changes[name]), 0o644); err != nil { + t.Fatal(err) + } + if p := print(); seen[p] { + t.Errorf("changing %s did not change the fingerprint", name) + } else { + seen[p] = true + } + } + + // A file outside the package's build, such as an unrelated package, + // leaves the fingerprint alone. + before := print() + os.MkdirAll(filepath.Join(root, "q"), 0o755) + os.WriteFile(filepath.Join(root, "q/q.go"), []byte("package q\n"), 0o644) + if print() != before { + t.Error("an unrelated package changed the fingerprint") + } + + if _, err := l.MutationFingerprint(root, "missing/x.go"); err == nil { + t.Error("want an error for a package that cannot be listed") + } +} + +func TestRepoDirs(t *testing.T) { + got := repoDirs("/repo", "/repo/b\n/repo/a\n/elsewhere/c\n/repo/b\n/repository/x\n/repo\n") + if want := []string{"/repo", "/repo/a", "/repo/b"}; !reflect.DeepEqual(got, want) { + t.Errorf("got %v, want %v", got, want) + } +} diff --git a/internal/lang/goanalyzer/session.go b/internal/lang/goanalyzer/session.go new file mode 100644 index 0000000..1b79e83 --- /dev/null +++ b/internal/lang/goanalyzer/session.go @@ -0,0 +1,317 @@ +package goanalyzer + +import ( + "context" + "fmt" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// slowTestThreshold splits the tests that reach a mutant into a fast group, +// run first, and a slow group run only if the fast one did not kill it. +const slowTestThreshold = time.Second + +// goSession tests the mutants of one run. Each package is prepared once, in +// the background: its mutants are compiled into a single test binary per +// test package, and one traced run of every test records which mutants that +// test reaches. A mutant is then tested by running only those tests. +// +// A mutant that cannot be compiled into the shared binary, or a package +// whose shared build or baseline fails, is tested the slow way: one +// `go test -overlay` per mutant. +type goSession struct { + cfg lang.SessionConfig + sites []lang.MutantSite + pkgOf []*mutantPackage + pkgs []*mutantPackage + slots chan struct{} + cancel context.CancelFunc +} + +// NewMutationSession implements lang.SessionRunner. +func (*Language) NewMutationSession(ctx context.Context, cfg lang.SessionConfig, sites []lang.MutantSite) (lang.MutationSession, error) { + ctx, cancel := context.WithCancel(ctx) + s := &goSession{ + cfg: cfg, + sites: sites, + pkgOf: make([]*mutantPackage, len(sites)), + slots: make(chan struct{}, max(cfg.Workers, 1)), + cancel: cancel, + } + byDir := map[string]*mutantPackage{} + for i, site := range sites { + dir := filepath.Join(cfg.RepoPath, filepath.Dir(site.File)) + p := byDir[dir] + if p == nil { + p = &mutantPackage{session: s, dir: dir, work: filepath.Join(cfg.WorkDir, "pkg"+strconv.Itoa(len(s.pkgs))), ready: make(chan struct{})} + byDir[dir] = p + s.pkgs = append(s.pkgs, p) + } + p.sites = append(p.sites, i) + s.pkgOf[i] = p + } + for _, p := range s.pkgs { + go func() { + defer close(p.ready) + p.prepare(ctx) + }() + } + return s, nil +} + +// Run implements lang.MutationSession. +func (s *goSession) Run(ctx context.Context, idx int) lang.MutantResult { + p := s.pkgOf[idx] + select { + case <-p.ready: + case <-ctx.Done(): + } + if ctx.Err() != nil { + return lang.MutantResult{Outcome: lang.OutcomeNotRun} + } + if !p.embedded[idx] { + return p.runOverlay(ctx, idx) + } + return p.runSchemata(ctx, idx+1) +} + +// Close stops any preparation still running and waits for it to exit, so +// the work directory can be removed. +func (s *goSession) Close() { + s.cancel() + for _, p := range s.pkgs { + <-p.ready + } +} + +func (s *goSession) logf(format string, args ...any) { + if s.cfg.Log != nil { + fmt.Fprintf(s.cfg.Log, "mutation: "+format+"\n", args...) + } +} + +// acquire takes a slot bounding the child processes preparation runs at +// once; the returned func releases it. +func (s *goSession) acquire() func() { + s.slots <- struct{}{} + return func() { <-s.slots } +} + +// mutantPackage is the per-package state of a session. +type mutantPackage struct { + session *goSession + dir string + work string + sites []int + ready chan struct{} + + // embedded marks the sites compiled into bins. Empty when the shared + // build is unavailable, which routes every site to the overlay path. + embedded map[int]bool + bins []*testBinary + + baselineOnce sync.Once + baselineOK bool + baselineTook time.Duration +} + +// runSchemata tests mutant id against every test that reaches it. +func (p *mutantPackage) runSchemata(ctx context.Context, id int) lang.MutantResult { + covered := false + for _, b := range p.bins { + for _, g := range b.groupsReaching(id) { + covered = true + if res := b.runGroup(ctx, g, id, p.session.cfg); res.Outcome != lang.OutcomeSurvived { + return res + } + } + } + if !covered { + return lang.MutantResult{Outcome: lang.OutcomeNotCovered} + } + return lang.MutantResult{Outcome: lang.OutcomeSurvived} +} + +// runOverlay tests one mutant with its own build: the mutated file replaces +// the original through a build overlay. +func (p *mutantPackage) runOverlay(ctx context.Context, idx int) lang.MutantResult { + p.baselineOnce.Do(func() { p.overlayBaseline(ctx) }) + if !p.baselineOK { + return lang.MutantResult{Outcome: lang.OutcomeNotRun} + } + cfg := p.session.cfg + site := p.session.sites[idx] + original := filepath.Join(cfg.RepoPath, site.File) + mutated, _ := mutantApplierImpl{}.ApplyMutation(original, site) + if mutated == nil { + return lang.MutantResult{Outcome: lang.OutcomeNotApplied} + } + mutantFile := filepath.Join(cfg.WorkDir, fmt.Sprintf("m%d.go", idx)) + overlay := filepath.Join(cfg.WorkDir, fmt.Sprintf("m%d-overlay.json", idx)) + if os.WriteFile(mutantFile, mutated, 0o644) != nil || writeOverlayJSON(overlay, original, mutantFile) != nil { + return lang.MutantResult{Outcome: lang.OutcomeNotApplied} + } + + build := p.goCmd(ctx, time.Minute+cfg.Timeout, "build", "-overlay="+overlay, "-o", os.DevNull, ".") + if build.err != nil { + return classify(ctx, build, lang.OutcomeBuildFailed) + } + // The process deadline is the one timeout: go test's own is set past it + // so that a hang is reported as a timeout, not as a failing test. + timeout := overlayTimeout(p.baselineTook, cfg.Timeout) + args := buildTestArgs(lang.TestRunConfig{Timeout: timeout + time.Minute, TestPattern: cfg.TestPattern}, overlay) + return classify(ctx, p.goCmd(ctx, timeout, args...), lang.OutcomeKilled) +} + +// overlayBaseline runs the package's unmutated tests once. If they fail, +// every result would read as a kill, so the package's mutants are not run. +func (p *mutantPackage) overlayBaseline(ctx context.Context) { + args := []string{"test", "-count=1"} + if pattern := p.session.cfg.TestPattern; pattern != "" { + args = append(args, "-run", pattern) + } + res := p.goCmd(ctx, baselineTimeout(p.session.cfg), append(args, "./...")...) + p.baselineOK = res.err == nil + p.baselineTook = res.duration + if !p.baselineOK && ctx.Err() == nil { + p.session.logf("tests fail without any mutation in %s; its mutants were not run\n%s", p.dir, res.output) + } +} + +func (p *mutantPackage) goCmd(ctx context.Context, timeout time.Duration, args ...string) procResult { + return proc{dir: p.dir, timeout: timeout, name: "go", args: args, keep: 1 << 20}.run(ctx) +} + +// classify maps a finished child process to an outcome; onFailure is the +// outcome of a non-zero exit. +func classify(ctx context.Context, res procResult, onFailure lang.MutantOutcome) lang.MutantResult { + switch { + case ctx.Err() != nil: + return lang.MutantResult{Outcome: lang.OutcomeNotRun} + case res.timedOut: + return lang.MutantResult{Outcome: lang.OutcomeTimedOut, Output: tail([]byte(res.output), 0)} + case res.err != nil: + return lang.MutantResult{Outcome: onFailure, Output: tail([]byte(res.output), 0)} + } + return lang.MutantResult{Outcome: lang.OutcomeSurvived} +} + +// overlayTimeout bounds one mutant's `go test` on the overlay path, whose +// unmutated run took baseline: the configured ceiling, raised if a healthy +// run could not finish within it. +func overlayTimeout(baseline, ceiling time.Duration) time.Duration { + return max(ceiling, 3*baseline+30*time.Second) +} + +// baselineTimeout bounds an unmutated test run, which has no earlier +// measurement to derive a tighter limit from. +func baselineTimeout(cfg lang.SessionConfig) time.Duration { + return max(cfg.Timeout, 10*time.Minute) +} + +// mutantTimeout bounds a mutant's run of tests that took baseline without +// the mutation. A mutant that loops forever should cost a small multiple of +// the real run, not the configured ceiling; but the ceiling must never be +// so low that a healthy run cannot finish. +func mutantTimeout(baseline, ceiling time.Duration) time.Duration { + limit := 4*baseline + 5*time.Second + return min(limit, max(ceiling, 2*baseline+5*time.Second)) +} + +// testBinary is one compiled test package with the mutants built in. +type testBinary struct { + path string + dir string + // tests holds one traced run per test when every test passes on its + // own; otherwise whole holds a single traced run of the full suite. + tests []tracedTest + whole *tracedTest +} + +// tracedTest is an unmutated test run and the mutants it reached. +type tracedTest struct { + name string + duration time.Duration + reach map[int]bool +} + +// testGroup is a set of tests to run against one mutant. A nil names slice +// means the whole suite. +type testGroup struct { + names []string + baseline time.Duration +} + +// groupsReaching returns the test groups that execute mutant id, cheapest +// first. +func (b *testBinary) groupsReaching(id int) []testGroup { + if b.whole != nil { + if !b.whole.reach[id] { + return nil + } + return []testGroup{{baseline: b.whole.duration}} + } + fast, slow := b.testsReaching(id) + var groups []testGroup + for _, g := range []testGroup{fast, slow} { + if g.names != nil { + groups = append(groups, g) + } + } + return groups +} + +// testsReaching splits the tests that execute mutant id into those faster +// than slowTestThreshold and the rest. +func (b *testBinary) testsReaching(id int) (fast, slow testGroup) { + for _, t := range b.tests { + switch { + case !t.reach[id]: + case t.duration < slowTestThreshold: + fast.add(t) + default: + slow.add(t) + } + } + return fast, slow +} + +func (g *testGroup) add(t tracedTest) { + g.names = append(g.names, t.name) + g.baseline += t.duration +} + +func (b *testBinary) runGroup(ctx context.Context, g testGroup, id int, cfg lang.SessionConfig) lang.MutantResult { + args := append([]string{"-test.count=1", "-test.failfast"}, runFilter(g.names, cfg.TestPattern)...) + res := proc{ + dir: b.dir, + env: []string{mutantEnv + "=" + strconv.Itoa(id)}, + timeout: mutantTimeout(g.baseline, cfg.Timeout), + name: b.path, + args: args, + }.run(ctx) + return classify(ctx, res, lang.OutcomeKilled) +} + +// runFilter returns the -test.run flag selecting names, or the user's +// pattern when names is nil. +func runFilter(names []string, pattern string) []string { + if names == nil { + if pattern == "" { + return nil + } + return []string{"-test.run", pattern} + } + quoted := make([]string, len(names)) + for i, n := range names { + quoted[i] = regexp.QuoteMeta(n) + } + return []string{"-test.run", "^(" + strings.Join(quoted, "|") + ")$"} +} diff --git a/internal/lang/goanalyzer/session_prepare.go b/internal/lang/goanalyzer/session_prepare.go new file mode 100644 index 0000000..e88ef08 --- /dev/null +++ b/internal/lang/goanalyzer/session_prepare.go @@ -0,0 +1,390 @@ +package goanalyzer + +import ( + "context" + "fmt" + "maps" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "time" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// maxRepairs bounds the build-drop-rebuild loop of a shared build. +const maxRepairs = 6 + +// compileError matches a Go compiler diagnostic: path:line:col: message. +var compileError = regexp.MustCompile(`(?m)^(\S+\.go):(\d+):(\d+): `) + +// prepare builds the package's shared test binaries and traces its tests. +// On any failure it leaves embedded empty, so the package's mutants take +// the overlay path instead. +func (p *mutantPackage) prepare(ctx context.Context) { + if err := os.MkdirAll(p.work, 0o755); err != nil { + return + } + in, ok := p.buildSchemata(ctx) + if !ok { + p.fallback(ctx, "its mutants cannot share one build") + return + } + bins, ok := p.buildTestBinaries(ctx, in.overlayPath) + if !ok { + p.fallback(ctx, "its instrumented tests do not build") + return + } + if !p.baselineAll(ctx, bins) { + p.fallback(ctx, "its instrumented tests do not pass") + return + } + p.embedded, p.bins = in.embedded, bins +} + +func (p *mutantPackage) fallback(ctx context.Context, why string) { + if ctx.Err() == nil { + p.session.logf("%s: %s; testing its %d mutants one build at a time", p.dir, why, len(p.sites)) + } +} + +// buildSchemata instruments the package's mutated files and compiles the +// package, dropping the mutants the compiler rejects until it builds. +func (p *mutantPackage) buildSchemata(ctx context.Context) (*instrumentation, bool) { + in := newInstrumentation(p) + for range maxRepairs { + if err := in.write(); err != nil { + return nil, false + } + release := p.session.acquire() + res := p.goCmd(ctx, baselineTimeout(p.session.cfg), "build", "-overlay="+in.overlayPath, "-gcflags=-e", "-o", os.DevNull, ".") + release() + if res.err == nil { + return in, true + } + if !in.dropBlamed(res.output) { + break + } + } + return nil, false +} + +// instrumentation is the schemata build of one package: the instrumented +// copy of each mutated file, wired in through a build overlay. +type instrumentation struct { + pkg *mutantPackage + overlayPath string + files []string // mutated source files, sorted + sitesOf map[string][]int // source file -> site indexes + sources map[string][]byte + excluded map[int]bool + embedded map[int]bool +} + +func newInstrumentation(p *mutantPackage) *instrumentation { + in := &instrumentation{ + pkg: p, + overlayPath: filepath.Join(p.work, "overlay.json"), + sitesOf: map[string][]int{}, + excluded: map[int]bool{}, + } + for _, idx := range p.sites { + file := filepath.Join(p.session.cfg.RepoPath, p.session.sites[idx].File) + in.sitesOf[file] = append(in.sitesOf[file], idx) + } + in.files = slices.Sorted(maps.Keys(in.sitesOf)) + return in +} + +// write instruments every file with its non-excluded sites and writes the +// overlay that swaps the results, plus the helper file, into the package. +func (in *instrumentation) write() error { + replace := map[string]string{} + in.sources = map[string][]byte{} + in.embedded = map[int]bool{} + pkgName := "" + for n, file := range in.files { + out := filepath.Join(in.pkg.work, fmt.Sprintf("f%d.go", n)) + name, err := in.instrument(file, out) + if err != nil { + return err + } + replace[file], pkgName = out, name + } + helper := filepath.Join(in.pkg.work, schemataFileName) + if err := os.WriteFile(helper, schemataHelperSource(pkgName), 0o644); err != nil { + return err + } + replace[filepath.Join(in.pkg.dir, schemataFileName)] = helper + return writeOverlayMap(in.overlayPath, replace) +} + +// instrument writes the instrumented copy of file to out, records which of +// its sites were embedded, and returns the file's package name. +func (in *instrumentation) instrument(file, out string) (string, error) { + var sites []lang.MutantSite + var ids []int + for _, idx := range in.sitesOf[file] { + if !in.excluded[idx] { + sites = append(sites, in.pkg.session.sites[idx]) + ids = append(ids, idx+1) + } + } + src, embedded, pkgName, err := instrumentFile(file, sites, ids) + if err != nil { + return "", err + } + for i, ok := range embedded { + in.embedded[ids[i]-1] = ok + } + in.sources[out] = src + return pkgName, os.WriteFile(out, src, 0o644) +} + +// dropBlamed excludes the mutants responsible for the compile errors in +// output and reports whether it excluded any new ones. +func (in *instrumentation) dropBlamed(output string) bool { + before := len(in.excluded) + for _, m := range compileError.FindAllStringSubmatch(output, -1) { + path := m[1] + if !filepath.IsAbs(path) { + path = filepath.Join(in.pkg.dir, path) + } + line, _ := strconv.Atoi(m[2]) + col, _ := strconv.Atoi(m[3]) + // A path that is not an instrumented file has no source here, and + // blames nothing. + for _, id := range blamedMutants(in.sources[filepath.Clean(path)], line, col) { + in.excluded[id-1] = true + } + } + return len(in.excluded) > before +} + +// baselineAll runs every binary's unmutated baseline concurrently and +// reports whether all of them passed. +func (p *mutantPackage) baselineAll(ctx context.Context, bins []*testBinary) bool { + passed := make([]bool, len(bins)) + var wg sync.WaitGroup + for i, b := range bins { + wg.Add(1) + go func() { + defer wg.Done() + passed[i] = b.baseline(ctx, p.session) + }() + } + wg.Wait() + return !slices.Contains(passed, false) +} + +// buildTestBinaries compiles, concurrently, one instrumented test binary +// for the package and for each package beneath it whose tests depend on it. +// It fails only if the package's own tests do not build. +func (p *mutantPackage) buildTestBinaries(ctx context.Context, overlay string) ([]*testBinary, bool) { + pkgs := p.testPackages(ctx) + built := make([]*testBinary, len(pkgs)) + failed := make([]bool, len(pkgs)) + var wg sync.WaitGroup + for n, tp := range pkgs { + wg.Add(1) + go func() { + defer wg.Done() + built[n], failed[n] = p.buildTestBinary(ctx, overlay, tp, n) + }() + } + wg.Wait() + + var bins []*testBinary + for n, tp := range pkgs { + if failed[n] && tp.own { + return nil, false + } + if built[n] != nil { + bins = append(bins, built[n]) + } + } + return bins, true +} + +// buildTestBinary compiles tp's test binary. It returns nil without failure +// for a package that has no test files, for which go test -c writes nothing. +func (p *mutantPackage) buildTestBinary(ctx context.Context, overlay string, tp testPackage, n int) (bin *testBinary, failed bool) { + // The .exe suffix is required on Windows and harmless elsewhere. + path := filepath.Join(p.work, fmt.Sprintf("t%d.test.exe", n)) + defer p.session.acquire()() + res := proc{dir: tp.dir, timeout: baselineTimeout(p.session.cfg), name: "go", + args: []string{"test", "-c", "-overlay=" + overlay, "-o", path, "."}}.run(ctx) + if res.err != nil { + return nil, true + } + if _, err := os.Stat(path); err != nil { + return nil, false + } + return &testBinary{path: path, dir: tp.dir}, false +} + +// testPackage is a package whose tests can observe the mutated package. +type testPackage struct { + dir string + own bool // the mutated package itself +} + +// testPackages returns the mutated package and the packages beneath it +// whose test binaries link it. If they cannot be listed, the mutated +// package alone is used. +func (p *mutantPackage) testPackages(ctx context.Context) []testPackage { + own := []testPackage{{dir: p.dir, own: true}} + self := p.goCmd(ctx, time.Minute, "list", "-f", "{{.ImportPath}}", ".") + if self.err != nil { + return own + } + list := p.goCmd(ctx, 5*time.Minute, "list", "-test", "-f", `{{.ImportPath}}|{{.Dir}}|{{join .Deps ","}}`, "./...") + if list.err != nil { + return own + } + return parseTestPackages(strings.TrimSpace(self.output), list.output) +} + +// parseTestPackages picks, from `go list -test` output, the test binaries +// that link importPath. The mutated package's own tests come first. +func parseTestPackages(importPath, listOutput string) []testPackage { + var own, others []testPackage + for _, line := range strings.Split(listOutput, "\n") { + fields := strings.SplitN(line, "|", 3) + if len(fields) != 3 || !strings.HasSuffix(fields[0], ".test") { + continue + } + switch { + case fields[0] == importPath+".test": + own = append(own, testPackage{dir: fields[1], own: true}) + case dependsOn(fields[2], importPath): + others = append(others, testPackage{dir: fields[1]}) + } + } + return append(own, others...) +} + +// dependsOn reports whether a comma-separated dependency list names +// importPath, either plainly or as a variant recompiled for a test +// ("path [other.test]"). +func dependsOn(deps, importPath string) bool { + for _, dep := range strings.Split(deps, ",") { + if dep == importPath || strings.HasPrefix(dep, importPath+" [") { + return true + } + } + return false +} + +// baseline runs the binary's tests unmutated, recording which mutants each +// reaches. It prefers one run per test, which lets a mutant be tested by +// only the tests that reach it; if a test fails on its own (tests that +// depend on each other), it falls back to a single run of the whole suite. +// It reports false if the suite does not pass even then. +func (b *testBinary) baseline(ctx context.Context, s *goSession) bool { + names, ok := b.listTests(ctx, s.cfg) + if ok { + if tests, ok := b.traceEach(ctx, s, names); ok { + b.tests = tests + return true + } + } + for range 2 { + release := s.acquire() + whole, ok := b.trace(ctx, s.cfg, "") + release() + if ok { + b.whole = &whole + return true + } + } + return false +} + +// testName matches the top-level tests a binary lists that -test.run can +// select. Benchmarks are listed too but never run. +var testName = regexp.MustCompile(`^(Test|Example|Fuzz)\S*$`) + +func (b *testBinary) listTests(ctx context.Context, cfg lang.SessionConfig) ([]string, bool) { + pattern := cfg.TestPattern + if pattern == "" { + pattern = ".*" + } + res := proc{dir: b.dir, timeout: baselineTimeout(cfg), name: b.path, args: []string{"-test.list", pattern}, keep: 1 << 20}.run(ctx) + if res.err != nil { + return nil, false + } + var names []string + for _, line := range strings.Split(res.output, "\n") { + if testName.MatchString(line) { + names = append(names, line) + } + } + return names, true +} + +// traceEach traces every test in its own process. It reports false, and +// stops starting further traces, as soon as one of them fails. +func (b *testBinary) traceEach(ctx context.Context, s *goSession, names []string) ([]tracedTest, bool) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + tests := make([]tracedTest, len(names)) + passed := make([]bool, len(names)) + var wg sync.WaitGroup + for i, name := range names { + release := s.acquire() + if ctx.Err() != nil { + release() + break + } + wg.Add(1) + go func() { + defer wg.Done() + defer release() + if tests[i], passed[i] = b.trace(ctx, s.cfg, name); !passed[i] { + cancel() + } + }() + } + wg.Wait() + return tests, !slices.Contains(passed, false) +} + +// trace runs one test (or, with an empty name, the whole suite) unmutated +// and returns what it reached. +func (b *testBinary) trace(ctx context.Context, cfg lang.SessionConfig, name string) (tracedTest, bool) { + traceFile := b.path + "." + name + ".trace" + os.Remove(traceFile) + var names []string + if name != "" { + names = []string{name} + } + res := proc{ + dir: b.dir, + env: []string{traceEnv + "=" + traceFile}, + timeout: baselineTimeout(cfg), + name: b.path, + args: append([]string{"-test.count=1"}, runFilter(names, cfg.TestPattern)...), + }.run(ctx) + if res.err != nil { + return tracedTest{}, false + } + return tracedTest{name: name, duration: res.duration, reach: readTrace(traceFile)}, true +} + +// readTrace returns the mutant ids recorded in a trace file. A missing file +// means the run reached no mutation point. +func readTrace(path string) map[int]bool { + reach := map[int]bool{} + data, _ := os.ReadFile(path) + for _, line := range strings.Fields(string(data)) { + if id, err := strconv.Atoi(line); err == nil { + reach[id] = true + } + } + return reach +} diff --git a/internal/lang/goanalyzer/session_test.go b/internal/lang/goanalyzer/session_test.go new file mode 100644 index 0000000..ce45424 --- /dev/null +++ b/internal/lang/goanalyzer/session_test.go @@ -0,0 +1,696 @@ +package goanalyzer + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/0xPolygon/diffguard/internal/diff" + "github.com/0xPolygon/diffguard/internal/lang" +) + +const sampleSource = `package p + +import "errors" + +var calls int + +func note() { calls++ } + +func Cmp(a, b int) bool { return a > b } + +func Eq(a, b int) bool { return a == b } + +func Add(a, b int) int { return a + b } + +func Flag() bool { return true } + +func Count(n int) int { + c := 0 + for range n { + c++ + } + return c +} + +func Guard(x int) (int, error) { + if x < 0 { + return 0, errors.New("negative") + } + note() + return x, nil +} + +func Join(a string) string { return a + "!" } + +func Untested(a, b int) bool { return a != b } + +func Loose(a int) int { + if a > 100 { + println() + } + return a +} +` + +const sampleTests = `package p + +import "testing" + +func TestCmp(t *testing.T) { + if Cmp(1, 1) || !Cmp(2, 1) { + t.Fatal("Cmp") + } +} + +func TestEq(t *testing.T) { + if !Eq(1, 1) || Eq(1, 2) { + t.Fatal("Eq") + } +} + +func TestAdd(t *testing.T) { + if Add(2, 3) != 5 { + t.Fatal("Add") + } +} + +func TestFlag(t *testing.T) { + if !Flag() { + t.Fatal("Flag") + } +} + +func TestCount(t *testing.T) { + if Count(3) != 3 { + t.Fatal("Count") + } +} + +func TestGuard(t *testing.T) { + if _, err := Guard(-1); err == nil { + t.Fatal("Guard(-1)") + } + calls = 0 + if v, err := Guard(0); v != 0 || err != nil || calls != 1 { + t.Fatal("Guard(0)") + } + if v, _ := Guard(7); v != 7 { + t.Fatal("Guard(7)") + } +} + +func TestJoin(t *testing.T) { + if Join("a") != "a!" { + t.Fatal("Join") + } +} + +func TestLoose(t *testing.T) { + if Loose(1) != 1 { + t.Fatal("Loose") + } +} +` + +// writeModule creates a throwaway module with one package "p" and returns +// the module root. +func writeModule(t *testing.T, source, tests string) string { + t.Helper() + root := t.TempDir() + files := map[string]string{ + "go.mod": "module example.com/sample\n\ngo 1.24\n", + "p/p.go": source, + "p/p_test.go": tests, + } + for name, content := range files { + path := filepath.Join(root, name) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + return root +} + +func sitesOf(t *testing.T, root, file string) []lang.MutantSite { + t.Helper() + fc := diff.FileChange{Path: file, Regions: []diff.ChangedRegion{{StartLine: 1, EndLine: 1 << 20}}} + sites, err := mutantGeneratorImpl{}.GenerateMutants(filepath.Join(root, file), fc, nil) + if err != nil { + t.Fatal(err) + } + return sites +} + +// runSession tests every mutant of p/p.go and returns the outcome of each, +// keyed by "line operator". +func runSession(t *testing.T, root string, cfg lang.SessionConfig) (map[string]lang.MutantOutcome, *goSession) { + t.Helper() + sites := sitesOf(t, root, "p/p.go") + cfg.RepoPath, cfg.WorkDir, cfg.Workers = root, t.TempDir(), 4 + if cfg.Timeout == 0 { + cfg.Timeout = time.Minute + } + session, err := (&Language{}).NewMutationSession(context.Background(), cfg, sites) + if err != nil { + t.Fatal(err) + } + defer session.Close() + got := map[string]lang.MutantOutcome{} + for i, s := range sites { + got[lineOp(root, s)] = session.Run(context.Background(), i).Outcome + } + return got, session.(*goSession) +} + +// lineOp names a site by the text of its source line and its operator, so +// expectations survive edits to the sample. +func lineOp(root string, s lang.MutantSite) string { + data, _ := os.ReadFile(filepath.Join(root, s.File)) + return strings.TrimSpace(strings.Split(string(data), "\n")[s.Line-1]) + " | " + s.Operator +} + +func TestSession_ClassifiesEveryOutcome(t *testing.T) { + root := writeModule(t, sampleSource, sampleTests) + got, session := runSession(t, root, lang.SessionConfig{}) + + want := map[string]lang.MutantOutcome{ + "func note() { calls++ } | incdec": lang.OutcomeKilled, + "func Cmp(a, b int) bool { return a > b } | conditional_boundary": lang.OutcomeKilled, + "func Cmp(a, b int) bool { return a > b } | return_value": lang.OutcomeKilled, + "func Eq(a, b int) bool { return a == b } | negate_conditional": lang.OutcomeKilled, + "func Eq(a, b int) bool { return a == b } | return_value": lang.OutcomeKilled, + "func Add(a, b int) int { return a + b } | math_operator": lang.OutcomeKilled, + "func Add(a, b int) int { return a + b } | return_value": lang.OutcomeKilled, + "func Flag() bool { return true } | boolean_substitution": lang.OutcomeKilled, + "func Flag() bool { return true } | return_value": lang.OutcomeKilled, + "c++ | incdec": lang.OutcomeKilled, + "return c | return_value": lang.OutcomeKilled, + "if x < 0 { | branch_removal": lang.OutcomeKilled, + "if x < 0 { | conditional_boundary": lang.OutcomeKilled, + "return 0, errors.New(\"negative\") | return_value": lang.OutcomeKilled, + "note() | statement_deletion": lang.OutcomeKilled, + "return x, nil | return_value": lang.OutcomeKilled, + // string - string does not compile. + "func Join(a string) string { return a + \"!\" } | math_operator": lang.OutcomeBuildFailed, + "func Join(a string) string { return a + \"!\" } | return_value": lang.OutcomeKilled, + "func Untested(a, b int) bool { return a != b } | negate_conditional": lang.OutcomeNotCovered, + "func Untested(a, b int) bool { return a != b } | return_value": lang.OutcomeNotCovered, + "if a > 100 { | branch_removal": lang.OutcomeNotCovered, // the guard sits inside the branch, which no test enters + "println() | statement_deletion": lang.OutcomeNotCovered, + "if a > 100 { | conditional_boundary": lang.OutcomeSurvived, + "return a | return_value": lang.OutcomeKilled, + } + if !reflect.DeepEqual(got, want) { + for k, w := range want { + if got[k] != w { + t.Errorf("%s: got %v, want %v", k, got[k], w) + } + } + for k := range got { + if _, ok := want[k]; !ok { + t.Errorf("unexpected mutant %s = %v", k, got[k]) + } + } + } + + p := session.pkgs[0] + if len(p.bins) != 1 || p.bins[0].whole != nil || len(p.bins[0].tests) != 8 { + t.Fatalf("want one binary traced per test (8 tests), got %+v", p.bins) + } + embedded := 0 + for _, ok := range p.embedded { + if ok { + embedded++ + } + } + if embedded != len(want)-1 { + t.Errorf("embedded %d mutants, want all but the one that cannot compile (%d)", embedded, len(want)-1) + } +} + +// Tests that only pass when run together still get their mutants tested, +// through a single trace of the whole suite. +func TestSession_InterdependentTestsUseWholeSuite(t *testing.T) { + tests := `package p + +import "testing" + +var ready bool + +func TestA(t *testing.T) { ready = true } + +func TestB(t *testing.T) { + if !ready || Add(2, 3) != 5 { + t.Fatal("B") + } +} +` + root := writeModule(t, "package p\n\nfunc Add(a, b int) int { return a + b }\n\nfunc Other(a int) int { return a * 2 }\n", tests) + got, session := runSession(t, root, lang.SessionConfig{}) + if b := session.pkgs[0].bins[0]; b.whole == nil || b.tests != nil { + t.Fatalf("want whole-suite mode, got %+v", b) + } + if got["func Add(a, b int) int { return a + b } | math_operator"] != lang.OutcomeKilled { + t.Errorf("Add mutant: %v", got) + } + if got["func Other(a int) int { return a * 2 } | math_operator"] != lang.OutcomeNotCovered { + t.Errorf("Other mutant: %v", got) + } +} + +// If the tests fail before any mutation, every mutant would look killed. +// They must be reported as not run instead. +func TestSession_FailingBaselineRunsNothing(t *testing.T) { + root := writeModule(t, "package p\n\nfunc Add(a, b int) int { return a + b }\n", + "package p\n\nimport \"testing\"\n\nfunc TestRed(t *testing.T) { t.Fatal(Add(1, 1)) }\n") + var log bytes.Buffer + got, _ := runSession(t, root, lang.SessionConfig{Log: &log}) + for k, o := range got { + if o != lang.OutcomeNotRun { + t.Errorf("%s: got %v, want not_run", k, o) + } + } + if !strings.Contains(log.String(), "tests fail without any mutation") { + t.Errorf("the failing baseline must be reported, log:\n%s", log.String()) + } +} + +func TestSession_TestPatternLimitsTheTests(t *testing.T) { + root := writeModule(t, sampleSource, sampleTests) + got, session := runSession(t, root, lang.SessionConfig{TestPattern: "TestAdd"}) + if n := len(session.pkgs[0].bins[0].tests); n != 1 { + t.Fatalf("traced %d tests, want only TestAdd", n) + } + if got["func Add(a, b int) int { return a + b } | math_operator"] != lang.OutcomeKilled { + t.Error("TestAdd still kills the Add mutant") + } + if got["func Cmp(a, b int) bool { return a > b } | conditional_boundary"] != lang.OutcomeNotCovered { + t.Error("with TestCmp filtered out, nothing covers the Cmp mutant") + } +} + +func TestSession_PackageWithoutTests(t *testing.T) { + root := writeModule(t, "package p\n\nfunc Add(a, b int) int { return a + b }\n", "package p\n") + os.Remove(filepath.Join(root, "p/p_test.go")) + got, _ := runSession(t, root, lang.SessionConfig{}) + for k, o := range got { + if o != lang.OutcomeNotCovered { + t.Errorf("%s: got %v, want not_covered", k, o) + } + } +} + +func TestSession_CancelledRunReportsNotRun(t *testing.T) { + root := writeModule(t, sampleSource, sampleTests) + sites := sitesOf(t, root, "p/p.go") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + session, _ := (&Language{}).NewMutationSession(ctx, lang.SessionConfig{RepoPath: root, WorkDir: t.TempDir(), Workers: 2, Timeout: time.Minute}, sites) + defer session.Close() + if got := session.Run(ctx, 0).Outcome; got != lang.OutcomeNotRun { + t.Errorf("outcome = %v, want not_run", got) + } +} + +// A test in a package below the mutated one counts, as it did when every +// mutant ran `go test ./...` from the mutated package's directory. +func TestSession_SubpackageTestsKillMutants(t *testing.T) { + root := writeModule(t, "package p\n\nfunc Add(a, b int) int { return a + b }\n", "package p\n") + os.Remove(filepath.Join(root, "p/p_test.go")) + sub := filepath.Join(root, "p/sub") + os.MkdirAll(sub, 0o755) + os.WriteFile(filepath.Join(sub, "sub_test.go"), []byte("package sub\n\nimport (\n\t\"testing\"\n\n\t\"example.com/sample/p\"\n)\n\nfunc TestAdd(t *testing.T) {\n\tif p.Add(2, 3) != 5 {\n\t\tt.Fatal()\n\t}\n}\n"), 0o644) + os.WriteFile(filepath.Join(sub, "sub.go"), []byte("package sub\n"), 0o644) + other := filepath.Join(root, "p/unrelated") + os.MkdirAll(other, 0o755) + os.WriteFile(filepath.Join(other, "u_test.go"), []byte("package unrelated\n\nimport \"testing\"\n\nfunc TestU(t *testing.T) {}\n"), 0o644) + + got, session := runSession(t, root, lang.SessionConfig{}) + if got["func Add(a, b int) int { return a + b } | math_operator"] != lang.OutcomeKilled { + t.Errorf("got %v", got) + } + if n := len(session.pkgs[0].bins); n != 1 { + t.Errorf("built %d test binaries, want 1: the unrelated package does not link p", n) + } +} + +func TestParseTestPackages(t *testing.T) { + out := strings.Join([]string{ + "example.com/m/p|/src/p|fmt,os", + "example.com/m/p.test|/src/p|example.com/m/p [example.com/m/p.test],testing", + "example.com/m/p [example.com/m/p.test]|/src/p|fmt", + "example.com/m/p/sub.test|/src/p/sub|example.com/m/p,testing", + "example.com/m/p/far.test|/src/p/far|example.com/m/pp,testing", + "garbage line", + "", + }, "\n") + got := parseTestPackages("example.com/m/p", out) + want := []testPackage{{dir: "/src/p", own: true}, {dir: "/src/p/sub"}} + if !reflect.DeepEqual(got, want) { + t.Errorf("got %+v, want %+v", got, want) + } +} + +func TestDependsOn(t *testing.T) { + deps := "a/b [a/b.test],a/bc,x" + if !dependsOn(deps, "a/b") || !dependsOn(deps, "x") { + t.Error("plain and test-variant dependencies both count") + } + if dependsOn(deps, "a") || dependsOn("a/bc", "a/b") { + t.Error("a path prefix is not a dependency") + } +} + +func TestRunFilter(t *testing.T) { + if got := runFilter(nil, ""); got != nil { + t.Errorf("whole suite, no pattern: %v", got) + } + if got := runFilter(nil, "TestX"); !reflect.DeepEqual(got, []string{"-test.run", "TestX"}) { + t.Errorf("whole suite with pattern: %v", got) + } + if got := runFilter([]string{"TestA", "Test.B"}, "ignored"); !reflect.DeepEqual(got, []string{"-test.run", `^(TestA|Test\.B)$`}) { + t.Errorf("named tests: %v", got) + } +} + +func TestGroupsReaching(t *testing.T) { + b := &testBinary{tests: []tracedTest{ + {name: "TestFast", duration: 10 * time.Millisecond, reach: map[int]bool{1: true, 2: true}}, + {name: "TestSlow", duration: slowTestThreshold, reach: map[int]bool{1: true}}, + {name: "TestOther", duration: time.Millisecond, reach: map[int]bool{3: true}}, + {name: "TestFast2", duration: 5 * time.Millisecond, reach: map[int]bool{1: true}}, + }} + got := b.groupsReaching(1) + want := []testGroup{ + {names: []string{"TestFast", "TestFast2"}, baseline: 15 * time.Millisecond}, + {names: []string{"TestSlow"}, baseline: slowTestThreshold}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("got %+v, want fast tests first, then slow: %+v", got, want) + } + if got := b.groupsReaching(2); len(got) != 1 || len(got[0].names) != 1 { + t.Errorf("mutant 2: %+v", got) + } + if b.groupsReaching(9) != nil { + t.Error("an unreached mutant has no groups") + } + + whole := &testBinary{whole: &tracedTest{duration: time.Second, reach: map[int]bool{4: true}}} + if got := whole.groupsReaching(4); len(got) != 1 || got[0].names != nil || got[0].baseline != time.Second { + t.Errorf("whole mode: %+v", got) + } + if whole.groupsReaching(5) != nil { + t.Error("whole mode: unreached mutant") + } +} + +func TestMutantTimeout(t *testing.T) { + cases := []struct{ baseline, ceiling, want time.Duration }{ + {0, time.Minute, 5 * time.Second}, + {time.Second, time.Minute, 9 * time.Second}, + {20 * time.Second, time.Minute, time.Minute}, // capped by the ceiling + {60 * time.Second, 30 * time.Second, 125 * time.Second}, // ceiling too low for a healthy run + } + for _, c := range cases { + if got := mutantTimeout(c.baseline, c.ceiling); got != c.want { + t.Errorf("mutantTimeout(%v, %v) = %v, want %v", c.baseline, c.ceiling, got, c.want) + } + } +} + +func TestBaselineTimeout(t *testing.T) { + if got := baselineTimeout(lang.SessionConfig{Timeout: time.Second}); got != 10*time.Minute { + t.Errorf("got %v, want the 10m floor", got) + } + if got := baselineTimeout(lang.SessionConfig{Timeout: time.Hour}); got != time.Hour { + t.Errorf("got %v, want the configured timeout", got) + } +} + +func TestClassify(t *testing.T) { + failed := errors.New("exit 1") + cancelled, cancel := context.WithCancel(context.Background()) + cancel() + cases := []struct { + ctx context.Context + res procResult + want lang.MutantOutcome + }{ + {context.Background(), procResult{}, lang.OutcomeSurvived}, + {context.Background(), procResult{err: failed}, lang.OutcomeBuildFailed}, + {context.Background(), procResult{err: failed, timedOut: true}, lang.OutcomeTimedOut}, + {cancelled, procResult{err: failed, timedOut: true}, lang.OutcomeNotRun}, + } + for _, c := range cases { + if got := classify(c.ctx, c.res, lang.OutcomeBuildFailed).Outcome; got != c.want { + t.Errorf("classify(%+v) = %v, want %v", c.res, got, c.want) + } + } + if got := classify(context.Background(), procResult{err: failed, output: "why"}, lang.OutcomeKilled); got.Output != "why" { + t.Errorf("a failure keeps its output, got %q", got.Output) + } +} + +func TestReadTrace(t *testing.T) { + path := filepath.Join(t.TempDir(), "trace") + os.WriteFile(path, []byte("3\n17\nnoise\n3\n"), 0o644) + if got := readTrace(path); !reflect.DeepEqual(got, map[int]bool{3: true, 17: true}) { + t.Errorf("got %v", got) + } + if got := readTrace(path + ".missing"); len(got) != 0 { + t.Errorf("missing file: got %v, want empty", got) + } +} + +func TestProcRun(t *testing.T) { + ok := proc{timeout: time.Minute, name: "go", args: []string{"version"}}.run(context.Background()) + if ok.err != nil || ok.timedOut || !strings.Contains(ok.output, "go version") { + t.Errorf("go version: %+v", ok) + } + bad := proc{timeout: time.Minute, name: "go", args: []string{"no-such-command"}}.run(context.Background()) + if bad.err == nil || bad.timedOut { + t.Errorf("failing command: %+v", bad) + } + slow := proc{timeout: time.Nanosecond, name: "go", args: []string{"version"}}.run(context.Background()) + if slow.err == nil || !slow.timedOut { + t.Errorf("a run past its timeout must report timedOut: %+v", slow) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + gone := proc{timeout: time.Minute, name: "go", args: []string{"version"}}.run(ctx) + if gone.err == nil || gone.timedOut { + t.Errorf("a cancelled run is not a timeout: %+v", gone) + } + env := proc{timeout: time.Minute, name: "go", args: []string{"env", "GOFLAGS"}, env: []string{"GOFLAGS=-mod=mod"}}.run(context.Background()) + if strings.TrimSpace(env.output) != "-mod=mod" { + t.Errorf("env not passed to the child: %q", env.output) + } +} + +func TestTail(t *testing.T) { + if got := tail([]byte("abcdef"), 3); got != "def" { + t.Errorf("got %q", got) + } + if got := tail([]byte("abc"), 3); got != "abc" { + t.Errorf("got %q", got) + } + long := bytes.Repeat([]byte("x"), outputTail+10) + if got := tail(long, 0); len(got) != outputTail { + t.Errorf("default keep = %d, want %d", len(got), outputTail) + } +} + +func TestOverlayTimeout(t *testing.T) { + if got := overlayTimeout(time.Second, time.Minute); got != time.Minute { + t.Errorf("got %v, want the configured ceiling", got) + } + if got := overlayTimeout(time.Minute, time.Minute); got != 210*time.Second { + t.Errorf("got %v, want 3x the baseline plus 30s", got) + } +} + +// newTestSession prepares a session over the given sites and waits for +// every package to be ready. +func newTestSession(t *testing.T, root string, cfg lang.SessionConfig, sites []lang.MutantSite) *goSession { + t.Helper() + cfg.RepoPath, cfg.WorkDir, cfg.Workers, cfg.Timeout = root, t.TempDir(), 2, time.Minute + session, err := (&Language{}).NewMutationSession(context.Background(), cfg, sites) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + s := session.(*goSession) + for _, p := range s.pkgs { + <-p.ready + } + return s +} + +// A site the applier cannot locate is reported as not applied, not as a +// surviving mutant. +func TestSession_UnlocatableSiteIsNotApplied(t *testing.T) { + root := writeModule(t, sampleSource, sampleTests) + bogus := lang.MutantSite{File: "p/p.go", Line: 1, Offset: 3, Operator: "incdec", Description: "++ -> --"} + s := newTestSession(t, root, lang.SessionConfig{}, []lang.MutantSite{bogus}) + if got := s.Run(context.Background(), 0).Outcome; got != lang.OutcomeNotApplied { + t.Errorf("outcome = %v, want not_applied", got) + } +} + +// The user's test pattern scopes the unmutated run too: a failing test +// outside the pattern must not stop the package's mutants from running. +func TestSession_TestPatternScopesTheBaseline(t *testing.T) { + tests := sampleTests + "\nfunc TestRed(t *testing.T) { t.Fatal(\"red\") }\n" + root := writeModule(t, sampleSource, tests) + got, _ := runSession(t, root, lang.SessionConfig{TestPattern: "TestJoin"}) + if o := got["func Join(a string) string { return a + \"!\" } | return_value"]; o != lang.OutcomeKilled { + t.Errorf("schemata path: got %v, want killed", o) + } + // This mutant cannot share the build, so it takes the overlay path and + // its own baseline run. + if o := got["func Join(a string) string { return a + \"!\" } | math_operator"]; o != lang.OutcomeBuildFailed { + t.Errorf("overlay path: got %v, want build_failed", o) + } +} + +func TestSession_TestsThatDoNotCompileRunNothing(t *testing.T) { + root := writeModule(t, "package p\n\nfunc Add(a, b int) int { return a + b }\n", + "package p\n\nimport \"testing\"\n\nfunc TestAdd(t *testing.T) { undefined() }\n") + var log bytes.Buffer + got, _ := runSession(t, root, lang.SessionConfig{Log: &log}) + for k, o := range got { + if o != lang.OutcomeNotRun { + t.Errorf("%s: got %v, want not_run", k, o) + } + } + if !strings.Contains(log.String(), "its instrumented tests do not build; testing its 2 mutants one build at a time") { + t.Errorf("the fallback must be explained, log:\n%s", log.String()) + } +} + +func TestSession_CancelledPreparationLogsNothing(t *testing.T) { + root := writeModule(t, sampleSource, sampleTests) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + var log bytes.Buffer + session, _ := (&Language{}).NewMutationSession(ctx, lang.SessionConfig{RepoPath: root, WorkDir: t.TempDir(), Workers: 2, Timeout: time.Minute, Log: &log}, sitesOf(t, root, "p/p.go")) + session.Close() + if log.Len() != 0 { + t.Errorf("a cancelled run is not a package problem, log:\n%s", log.String()) + } +} + +func TestTestPackages_FallsBackToThePackageItself(t *testing.T) { + dir := t.TempDir() // not inside any module, so go list fails + p := &mutantPackage{session: &goSession{cfg: lang.SessionConfig{Timeout: time.Minute}}, dir: dir} + got := p.testPackages(context.Background()) + if want := []testPackage{{dir: dir, own: true}}; !reflect.DeepEqual(got, want) { + t.Errorf("got %+v, want %+v", got, want) + } +} + +func TestInstrumentation_WriteErrors(t *testing.T) { + root := writeModule(t, sampleSource, sampleTests) + sites := sitesOf(t, root, "p/p.go") + s := &goSession{cfg: lang.SessionConfig{RepoPath: root}, sites: sites} + p := &mutantPackage{session: s, dir: filepath.Join(root, "p"), work: filepath.Join(t.TempDir(), "missing"), sites: []int{0}} + if err := newInstrumentation(p).write(); err == nil { + t.Error("want an error when the work directory does not exist") + } + os.WriteFile(filepath.Join(root, "p/p.go"), []byte("package"), 0o644) + p.work = t.TempDir() + if err := newInstrumentation(p).write(); err == nil { + t.Error("want an error when a mutated file does not parse") + } +} + +func TestInstrumentation_DropBlamed(t *testing.T) { + root := writeModule(t, sampleSource, sampleTests) + sites := sitesOf(t, root, "p/p.go") + all := make([]int, len(sites)) + for i := range all { + all[i] = i + } + s := &goSession{cfg: lang.SessionConfig{RepoPath: root}, sites: sites} + p := &mutantPackage{session: s, dir: filepath.Join(root, "p"), work: t.TempDir(), sites: all} + in := newInstrumentation(p) + if err := in.write(); err != nil { + t.Fatal(err) + } + out := filepath.Join(p.work, "f0.go") + line, col := lineCol(string(in.sources[out]), "a, \"!\")") + id, err := strconv.Atoi(strings.Split(strings.Split(string(in.sources[out]), "__dgAdd(")[2], ",")[0]) + if err != nil { + t.Fatal(err) + } + + diag := fmt.Sprintf("# example.com/sample/p\n%s:%d:%d: string does not satisfy __dgNum\nother.go:1:1: unrelated\n", out, line, col) + if !in.dropBlamed(diag) { + t.Fatal("the blamed mutant should be dropped") + } + if len(in.excluded) != 1 || !in.excluded[id-1] { + t.Errorf("excluded = %v, want only site %d", in.excluded, id-1) + } + if in.dropBlamed(diag) { + t.Error("blaming an already dropped mutant is not progress") + } + if in.dropBlamed("no diagnostics here") { + t.Error("nothing to blame") + } + + // A path relative to the package directory resolves to the same file. + rel, _ := filepath.Rel(p.dir, out) + fresh := newInstrumentation(p) + fresh.write() + if !fresh.dropBlamed(fmt.Sprintf("%s:%d:%d: msg\n", rel, line, col)) { + t.Error("a relative diagnostic path should resolve against the package directory") + } + + if err := in.write(); err != nil { + t.Fatal(err) + } + if in.embedded[id-1] { + t.Error("an excluded mutant must not be embedded again") + } +} + +func TestHashPackageDir(t *testing.T) { + if err := hashPackageDir(io.Discard, filepath.Join(t.TempDir(), "missing")); err == nil { + t.Error("want an error for an unreadable directory") + } + dir := t.TempDir() + os.MkdirAll(filepath.Join(dir, "testdata/deep"), 0o755) + os.MkdirAll(filepath.Join(dir, "other"), 0o755) + os.WriteFile(filepath.Join(dir, "a.go"), []byte("package a\n"), 0o644) + os.WriteFile(filepath.Join(dir, "testdata/deep/x.txt"), []byte("x"), 0o644) + os.WriteFile(filepath.Join(dir, "other/y.txt"), []byte("y"), 0o644) + var buf bytes.Buffer + if err := hashPackageDir(&buf, dir); err != nil { + t.Fatal(err) + } + got := buf.String() + if !strings.Contains(got, "a.go\x00package a\n\x0010\x00") { + t.Errorf("a file contributes its path, content and size: %q", got) + } + if !strings.Contains(got, "x.txt") || strings.Contains(got, "y.txt") { + t.Errorf("testdata is hashed recursively, other subdirectories are not: %q", got) + } + buf.Reset() + hashFile(&buf, filepath.Join(dir, "gone")) + if !strings.HasSuffix(buf.String(), "gone\x00") { + t.Errorf("an unreadable file contributes only its path: %q", buf.String()) + } +} diff --git a/internal/lang/goanalyzer/testrunner.go b/internal/lang/goanalyzer/testrunner.go index 090714b..a6f0994 100644 --- a/internal/lang/goanalyzer/testrunner.go +++ b/internal/lang/goanalyzer/testrunner.go @@ -48,10 +48,17 @@ func (testRunnerImpl) RunTest(cfg lang.TestRunConfig) (bool, string, error) { // writeOverlayJSON writes a go build overlay file mapping originalPath to // mutantPath. See `go help build` -overlay flag for format details. func writeOverlayJSON(path, originalPath, mutantPath string) error { + return writeOverlayMap(path, map[string]string{originalPath: mutantPath}) +} + +// writeOverlayMap writes a go build overlay file with the given +// original-path to replacement-path entries. An entry whose original path +// does not exist adds a file to that directory's package. +func writeOverlayMap(path string, replace map[string]string) error { overlay := struct { Replace map[string]string `json:"Replace"` }{ - Replace: map[string]string{originalPath: mutantPath}, + Replace: replace, } data, err := json.Marshal(overlay) if err != nil { @@ -67,7 +74,7 @@ func buildTestArgs(cfg lang.TestRunConfig, overlayPath string) []string { if timeout <= 0 { timeout = defaultGoTestTimeout } - args := []string{"test", "-overlay=" + overlayPath, "-count=1", "-timeout", timeout.String()} + args := []string{"test", "-overlay=" + overlayPath, "-count=1", "-failfast", "-timeout", timeout.String()} if cfg.TestPattern != "" { args = append(args, "-run", cfg.TestPattern) } diff --git a/internal/lang/lang.go b/internal/lang/lang.go index 03d680a..c77d1fc 100644 --- a/internal/lang/lang.go +++ b/internal/lang/lang.go @@ -11,6 +11,8 @@ package lang import ( + "context" + "io" "time" "github.com/0xPolygon/diffguard/internal/diff" @@ -125,6 +127,106 @@ type MutantSite struct { Line int Description string Operator string + // Offset is the byte offset of the mutated token, when the language can + // supply one. It tells apart several sites on one line; zero means the + // language identifies sites by line only. + Offset int +} + +// MutantOutcome is the result of testing one mutant. +type MutantOutcome int + +const ( + // OutcomeUnset means no session reported a result (legacy runners). + OutcomeUnset MutantOutcome = iota + // OutcomeKilled: at least one test failed against the mutant. + OutcomeKilled + // OutcomeSurvived: every test that ran passed. + OutcomeSurvived + // OutcomeTimedOut: the tests exceeded their deadline. Counted as killed. + OutcomeTimedOut + // OutcomeNotCovered: no test executes the mutated code. Counted as survived. + OutcomeNotCovered + // OutcomeBuildFailed: the mutant does not compile. Excluded from scores. + OutcomeBuildFailed + // OutcomeNotApplied: the mutation could not be produced. Excluded. + OutcomeNotApplied + // OutcomeNotRun: the budget ran out or the run was cancelled. Excluded. + OutcomeNotRun + // OutcomeStoppedEarly: skipped because the tier's verdict was already + // statistically settled. Excluded. + OutcomeStoppedEarly +) + +var outcomeNames = map[MutantOutcome]string{ + OutcomeKilled: "killed", + OutcomeSurvived: "survived", + OutcomeTimedOut: "timed_out", + OutcomeNotCovered: "not_covered", + OutcomeBuildFailed: "build_failed", + OutcomeNotApplied: "not_applied", + OutcomeNotRun: "not_run", + OutcomeStoppedEarly: "stopped_early", +} + +// String returns the snake_case name used in reports and the result cache. +func (o MutantOutcome) String() string { + if name, ok := outcomeNames[o]; ok { + return name + } + return "unset" +} + +// ParseMutantOutcome is the inverse of String; unknown names yield +// OutcomeUnset. +func ParseMutantOutcome(name string) MutantOutcome { + for o, n := range outcomeNames { + if n == name { + return o + } + } + // mutator-disable-next-line (OutcomeUnset is the zero value: zeroing the return changes nothing) + return OutcomeUnset +} + +// MutantResult is what a MutationSession reports for one mutant. +type MutantResult struct { + Outcome MutantOutcome + Output string +} + +// SessionConfig carries the run-wide settings a MutationSession needs. +type SessionConfig struct { + RepoPath string + WorkDir string + // Timeout caps a single mutant's test run. + Timeout time.Duration + TestPattern string + Workers int + // Log receives warnings about packages that could not be tested as + // planned. Nil discards them. + Log io.Writer +} + +// MutationSession tests mutants of one run. Run may be called concurrently; +// idx indexes the sites slice the session was created with. +type MutationSession interface { + Run(ctx context.Context, idx int) MutantResult + Close() +} + +// SessionRunner is an optional Language capability: the language tests a +// whole batch of mutants itself, so it can share builds and pick tests per +// mutant. Languages without it are driven through MutantApplier/TestRunner. +type SessionRunner interface { + NewMutationSession(ctx context.Context, cfg SessionConfig, sites []MutantSite) (MutationSession, error) +} + +// Fingerprinter is an optional Language capability used by the result +// cache: the fingerprint must change whenever anything that can alter a +// mutant's outcome in file's package changes. +type Fingerprinter interface { + MutationFingerprint(repoPath, file string) (string, error) } // TestRunConfig carries the parameters needed to run tests against a single diff --git a/internal/lang/lang_test.go b/internal/lang/lang_test.go index 85ed81c..2cae978 100644 --- a/internal/lang/lang_test.go +++ b/internal/lang/lang_test.go @@ -64,3 +64,22 @@ func TestFileFilter_NilIsTestFile(t *testing.T) { t.Error("with nil IsTestFile, everything with matching ext should be included") } } + +func TestMutantOutcomeNamesRoundTrip(t *testing.T) { + all := []MutantOutcome{OutcomeKilled, OutcomeSurvived, OutcomeTimedOut, OutcomeNotCovered, + OutcomeBuildFailed, OutcomeNotApplied, OutcomeNotRun, OutcomeStoppedEarly} + seen := map[string]bool{} + for _, o := range all { + name := o.String() + if name == "unset" || seen[name] { + t.Errorf("outcome %d has no distinct name (%q)", o, name) + } + seen[name] = true + if ParseMutantOutcome(name) != o { + t.Errorf("ParseMutantOutcome(%q) != %d", name, o) + } + } + if OutcomeUnset.String() != "unset" || ParseMutantOutcome("nonsense") != OutcomeUnset || ParseMutantOutcome("") != OutcomeUnset { + t.Error("unknown names map to OutcomeUnset") + } +} diff --git a/internal/mutation/cache.go b/internal/mutation/cache.go new file mode 100644 index 0000000..57165c2 --- /dev/null +++ b/internal/mutation/cache.go @@ -0,0 +1,130 @@ +package mutation + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// resultCache persists mutant outcomes between runs. Entries are grouped by +// the language's package fingerprint, so any change that could alter an +// outcome in a package invalidates that package's entries and nothing else. +// A nil *resultCache is a valid, disabled cache. +type resultCache struct { + dir string + repoPath string + salt string + fp lang.Fingerprinter + files map[string]string // package dir -> cache file path ("" = unavailable) +} + +func openCache(opts Options, repoPath string, l lang.Language) *resultCache { + fp, ok := l.(lang.Fingerprinter) + if opts.CacheDir == "" || !ok { + return nil + } + return &resultCache{ + dir: opts.CacheDir, + repoPath: repoPath, + salt: l.Name() + "\x00" + opts.TestPattern, + fp: fp, + files: map[string]string{}, + } +} + +// load fills in the outcome of every mutant with a cached result. +func (c *resultCache) load(mutants []Mutant) { + if c == nil { + return + } + entries := map[string]map[string]string{} + for i := range mutants { + path := c.fileFor(mutants[i].File) + if _, read := entries[path]; !read { + entries[path] = readCacheFile(path) + } + o := lang.ParseMutantOutcome(entries[path][cacheKey(mutants[i])]) + if !cacheable(o) { + continue + } + mutants[i].setResult(lang.MutantResult{Outcome: o}) + mutants[i].Cached = true + } +} + +// store writes every definitive outcome back, merged with what is on disk. +func (c *resultCache) store(mutants []Mutant) { + if c == nil { + return + } + entries := map[string]map[string]string{} + for _, m := range mutants { + path := c.fileFor(m.File) + if path == "" || !cacheable(m.outcome()) || m.Outcome == lang.OutcomeUnset { + continue + } + if entries[path] == nil { + entries[path] = readCacheFile(path) + } + entries[path][cacheKey(m)] = m.Outcome.String() + } + for path, e := range entries { + writeCacheFile(path, e) + } +} + +// fileFor returns the cache file for the package containing file, or "" if +// the package cannot be fingerprinted (in which case it is never cached). +func (c *resultCache) fileFor(file string) string { + pkg := filepath.Dir(file) + if path, ok := c.files[pkg]; ok { + return path + } + path := "" + if print, err := c.fp.MutationFingerprint(c.repoPath, file); err == nil && print != "" { + sum := sha256.Sum256([]byte(c.salt + "\x00" + print)) + path = filepath.Join(c.dir, hex.EncodeToString(sum[:])+".json") + } + c.files[pkg] = path + return path +} + +func cacheKey(m Mutant) string { + s := m.site() + return fmt.Sprintf("%s|%d|%d|%s|%s", s.File, s.Line, s.Offset, s.Operator, s.Description) +} + +// cacheable reports whether an outcome is a property of the code rather +// than of this run: timeouts and not-run mutants must be tried again. +func cacheable(o lang.MutantOutcome) bool { + switch o { + case lang.OutcomeKilled, lang.OutcomeSurvived, lang.OutcomeNotCovered, + lang.OutcomeBuildFailed, lang.OutcomeNotApplied: + return true + } + return false +} + +func readCacheFile(path string) map[string]string { + entries := map[string]string{} + if data, err := os.ReadFile(path); err == nil { + _ = json.Unmarshal(data, &entries) + } + return entries +} + +func writeCacheFile(path string, entries map[string]string) { + data, err := json.Marshal(entries) + if err != nil { + return + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return + } + _ = os.WriteFile(path, data, 0o644) +} diff --git a/internal/mutation/cache_test.go b/internal/mutation/cache_test.go new file mode 100644 index 0000000..2377890 --- /dev/null +++ b/internal/mutation/cache_test.go @@ -0,0 +1,140 @@ +package mutation + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +func cachedRun(t *testing.T, dir string, l *sessionLanguage, opts Options) []Mutant { + t.Helper() + opts.CacheDir = dir + mutants := numbered(4, "negate_conditional") + cache := openCache(opts, "/repo", l) + cache.load(mutants) + if err := runMutantsParallel("/repo", mutants, l, opts, t.TempDir()); err != nil { + t.Fatal(err) + } + cache.store(mutants) + return mutants +} + +func TestCache_ReusesDefinitiveOutcomesOnly(t *testing.T) { + dir := t.TempDir() + outcomes := byLine(lang.OutcomeKilled, lang.OutcomeSurvived, lang.OutcomeTimedOut, lang.OutcomeNotRun) + first := &sessionLanguage{outcome: outcomes, fingerprint: "v1"} + cachedRun(t, dir, first, Options{}) + if first.runs.Load() != 4 { + t.Fatalf("first run tested %d mutants, want 4", first.runs.Load()) + } + + second := &sessionLanguage{outcome: outcomes, fingerprint: "v1"} + mutants := cachedRun(t, dir, second, Options{}) + if second.runs.Load() != 2 { + t.Errorf("second run tested %d mutants; want 2: a timeout and a not-run mutant must be retried", second.runs.Load()) + } + if !mutants[0].Cached || !mutants[0].Killed || !mutants[1].Cached || mutants[1].Outcome != lang.OutcomeSurvived { + t.Errorf("cached results not restored: %+v", mutants[:2]) + } + if mutants[2].Cached || mutants[3].Cached { + t.Error("non-definitive outcomes must not come from the cache") + } +} + +func TestCache_InvalidatedByFingerprintAndTestPattern(t *testing.T) { + dir := t.TempDir() + killed := func(lang.MutantSite) lang.MutantOutcome { return lang.OutcomeKilled } + cachedRun(t, dir, &sessionLanguage{outcome: killed, fingerprint: "v1"}, Options{}) + + changed := &sessionLanguage{outcome: killed, fingerprint: "v2"} + cachedRun(t, dir, changed, Options{}) + if changed.runs.Load() != 4 { + t.Errorf("a changed fingerprint must re-test everything; ran %d", changed.runs.Load()) + } + + scoped := &sessionLanguage{outcome: killed, fingerprint: "v1"} + cachedRun(t, dir, scoped, Options{TestPattern: "TestOnlyThis"}) + if scoped.runs.Load() != 4 { + t.Errorf("a different test pattern must not reuse results; ran %d", scoped.runs.Load()) + } +} + +func TestCache_Disabled(t *testing.T) { + if openCache(Options{}, "/repo", &sessionLanguage{}) != nil { + t.Error("no cache dir means no cache") + } + if openCache(Options{CacheDir: t.TempDir()}, "/repo", &fakeLanguage{}) != nil { + t.Error("a language without a fingerprint cannot be cached") + } + var c *resultCache + c.load(nil) + c.store(nil) +} + +func TestCache_UnfingerprintablePackageIsNeverCached(t *testing.T) { + dir := t.TempDir() + killed := func(lang.MutantSite) lang.MutantOutcome { return lang.OutcomeKilled } + for _, l := range []*sessionLanguage{ + {outcome: killed, fpErr: errors.New("go list failed")}, + {outcome: killed, fingerprint: ""}, + } { + cachedRun(t, dir, l, Options{}) + again := &sessionLanguage{outcome: killed, fingerprint: l.fingerprint, fpErr: l.fpErr} + cachedRun(t, dir, again, Options{}) + if again.runs.Load() != 4 { + t.Errorf("ran %d, want 4: nothing may be cached without a fingerprint", again.runs.Load()) + } + } + if entries, _ := os.ReadDir(dir); len(entries) != 0 { + t.Errorf("cache dir has %d files, want none", len(entries)) + } +} + +func TestCache_KeyDistinguishesSites(t *testing.T) { + a := Mutant{File: "a.go", Line: 1, Offset: 10, Operator: "op", Description: "d"} + for _, b := range []Mutant{ + {File: "b.go", Line: 1, Offset: 10, Operator: "op", Description: "d"}, + {File: "a.go", Line: 2, Offset: 10, Operator: "op", Description: "d"}, + {File: "a.go", Line: 1, Offset: 11, Operator: "op", Description: "d"}, + {File: "a.go", Line: 1, Offset: 10, Operator: "other", Description: "d"}, + {File: "a.go", Line: 1, Offset: 10, Operator: "op", Description: "e"}, + } { + if cacheKey(a) == cacheKey(b) { + t.Errorf("key collision between %+v and %+v", a, b) + } + } +} + +func TestCache_StoreMergesWithExistingFile(t *testing.T) { + dir := t.TempDir() + l := &sessionLanguage{fingerprint: "v1"} + c := openCache(Options{CacheDir: filepath.Join(dir, "nested")}, "/repo", l) + first := numbered(1, "negate_conditional") + first[0].setResult(lang.MutantResult{Outcome: lang.OutcomeKilled}) + c.store(first) + + second := []Mutant{{File: "a.go", Line: 2, Operator: "negate_conditional"}} + second[0].setResult(lang.MutantResult{Outcome: lang.OutcomeBuildFailed}) + c.store(second) + + both := numbered(2, "negate_conditional") + openCache(Options{CacheDir: filepath.Join(dir, "nested")}, "/repo", l).load(both) + if both[0].Outcome != lang.OutcomeKilled || both[1].Outcome != lang.OutcomeBuildFailed { + t.Errorf("a later store must not drop earlier entries: %+v", both) + } +} + +func TestCacheable(t *testing.T) { + for o, want := range map[lang.MutantOutcome]bool{ + lang.OutcomeKilled: true, lang.OutcomeSurvived: true, lang.OutcomeNotCovered: true, + lang.OutcomeBuildFailed: true, lang.OutcomeNotApplied: true, + lang.OutcomeTimedOut: false, lang.OutcomeNotRun: false, lang.OutcomeStoppedEarly: false, lang.OutcomeUnset: false, + } { + if cacheable(o) != want { + t.Errorf("cacheable(%v) = %v, want %v", o, !want, want) + } + } +} diff --git a/internal/mutation/earlystop.go b/internal/mutation/earlystop.go new file mode 100644 index 0000000..8626da9 --- /dev/null +++ b/internal/mutation/earlystop.go @@ -0,0 +1,107 @@ +package mutation + +import ( + "math" + "sync" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// earlyStopMinSamples is the fewest scored mutants a tier needs before its +// verdict can be called early; below it the interval is too wide to trust. +const earlyStopMinSamples = 30 + +// earlyStop decides, per gating tier, when enough mutants have been tested +// that the kill rate is above or below the tier's threshold with the +// configured confidence. A nil *earlyStop never stops anything. +type earlyStop struct { + mu sync.Mutex + z float64 + tiers map[Tier]*tierTally +} + +// tierTally is the running evidence for one gating tier. +type tierTally struct { + threshold float64 + scored int + killed int + settled bool +} + +func newEarlyStop(opts Options) *earlyStop { + if opts.Confidence <= 0 || opts.Confidence >= 1 { + return nil + } + e := &earlyStop{z: zScore(opts.Confidence), tiers: map[Tier]*tierTally{}} + for _, t := range []Tier{TierLogic, TierSemantic, TierObservability} { + if threshold, gated := gatingThreshold(t, opts); gated { + e.tiers[t] = &tierTally{threshold: threshold} + } + } + return e +} + +// observe records one result and settles the tier once the Wilson interval +// of its kill rate no longer straddles the threshold. +func (e *earlyStop) observe(t Tier, o lang.MutantOutcome) { + if e == nil || (!isKill(o) && !isSurvivor(o)) { + return + } + e.mu.Lock() + defer e.mu.Unlock() + tally := e.tiers[t] + if tally == nil { + return + } + tally.scored++ + if isKill(o) { + tally.killed++ + } + if tally.scored < earlyStopMinSamples { + return + } + lo, hi := wilson(tally.killed, tally.scored, e.z) + // mutator-disable-next-line (a bound exactly on the threshold has measure zero) + if lo*100 >= tally.threshold || hi*100 < tally.threshold { + tally.settled = true + } +} + +func (e *earlyStop) isSettled(t Tier) bool { + if e == nil { + return false + } + e.mu.Lock() + defer e.mu.Unlock() + tally := e.tiers[t] + return tally != nil && tally.settled +} + +// wilson returns the Wilson score interval for k successes in n trials. +func wilson(k, n int, z float64) (lo, hi float64) { + if n == 0 { + return 0, 1 + } + p := float64(k) / float64(n) + nf := float64(n) + denom := 1 + z*z/nf + center := (p + z*z/(2*nf)) / denom + half := z * math.Sqrt(p*(1-p)/nf+z*z/(4*nf*nf)) / denom + return center - half, center + half +} + +// zScore returns the two-sided normal quantile for the confidence level, +// found by bisection on the error function. +func zScore(confidence float64) float64 { + lo, hi := 0.0, 10.0 + for range 60 { + mid := (lo + hi) / 2 + // mutator-disable-next-line (the quantile is a limit; < and <= converge to it alike) + if math.Erf(mid/math.Sqrt2) < confidence { + lo = mid + } else { + hi = mid + } + } + return (lo + hi) / 2 +} diff --git a/internal/mutation/earlystop_test.go b/internal/mutation/earlystop_test.go new file mode 100644 index 0000000..a4ccefa --- /dev/null +++ b/internal/mutation/earlystop_test.go @@ -0,0 +1,102 @@ +package mutation + +import ( + "math" + "testing" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +func TestZScore(t *testing.T) { + for confidence, want := range map[float64]float64{0.95: 1.95996, 0.99: 2.57583} { + if got := zScore(confidence); math.Abs(got-want) > 1e-4 { + t.Errorf("zScore(%v) = %v, want %v", confidence, got, want) + } + } +} + +func TestWilson(t *testing.T) { + lo, hi := wilson(0, 0, 1.96) + if lo != 0 || hi != 1 { + t.Errorf("no trials: got [%v, %v], want [0, 1]", lo, hi) + } + // Reference values for 45/50 at 95%. + lo, hi = wilson(45, 50, 1.959964) + if math.Abs(lo-0.7864) > 1e-3 || math.Abs(hi-0.9565) > 1e-3 { + t.Errorf("45/50: got [%.4f, %.4f], want [0.7864, 0.9565]", lo, hi) + } +} + +func TestNewEarlyStop_DisabledOutsideOpenInterval(t *testing.T) { + for _, c := range []float64{0, -1, 1, 2} { + if newEarlyStop(Options{Confidence: c}) != nil { + t.Errorf("confidence %v should disable early stopping", c) + } + } + var e *earlyStop + e.observe(TierLogic, lang.OutcomeKilled) + if e.isSettled(TierLogic) { + t.Error("a disabled early stop never settles") + } +} + +func observeN(e *earlyStop, tier Tier, o lang.MutantOutcome, n int) { + for i := 0; i < n; i++ { + e.observe(tier, o) + } +} + +func TestEarlyStop_SettlesWhenClearlyPassing(t *testing.T) { + e := newEarlyStop(Options{Confidence: 0.95, Tier1Threshold: 80}) + observeN(e, TierLogic, lang.OutcomeKilled, earlyStopMinSamples-1) + if e.isSettled(TierLogic) { + t.Fatal("must not settle below the minimum sample size, even at 100%") + } + e.observe(TierLogic, lang.OutcomeTimedOut) + if !e.isSettled(TierLogic) { + t.Fatal("30/30 killed is clearly above an 80% threshold") + } + if e.isSettled(TierSemantic) { + t.Error("tiers settle independently") + } +} + +func TestEarlyStop_SettlesWhenClearlyFailing(t *testing.T) { + e := newEarlyStop(Options{Confidence: 0.95, Tier1Threshold: 80}) + observeN(e, TierLogic, lang.OutcomeSurvived, 15) + observeN(e, TierLogic, lang.OutcomeNotCovered, 15) + if !e.isSettled(TierLogic) { + t.Error("0/30 killed is clearly below an 80% threshold") + } +} + +func TestEarlyStop_StaysOpenNearThreshold(t *testing.T) { + e := newEarlyStop(Options{Confidence: 0.95, Tier1Threshold: 80}) + for i := 0; i < 8; i++ { + observeN(e, TierLogic, lang.OutcomeKilled, 4) + e.observe(TierLogic, lang.OutcomeSurvived) + } + if e.isSettled(TierLogic) { + t.Error("32/40 = 80% sits on the threshold; the verdict is not settled") + } +} + +func TestEarlyStop_IgnoresUnscoredOutcomesAndUngatedTier(t *testing.T) { + e := newEarlyStop(Options{Confidence: 0.95, Tier1Threshold: 80}) + observeN(e, TierLogic, lang.OutcomeBuildFailed, 100) + observeN(e, TierObservability, lang.OutcomeKilled, 100) + if e.isSettled(TierLogic) || e.isSettled(TierObservability) { + t.Error("excluded outcomes carry no evidence, and tier 3 is never gated") + } + if e.tiers[TierLogic].scored != 0 { + t.Errorf("scored = %d, want 0", e.tiers[TierLogic].scored) + } +} + +func TestEarlyStop_UsesTier2Threshold(t *testing.T) { + e := newEarlyStop(Options{Confidence: 0.95, Tier1Threshold: 99, Tier2Threshold: 50}) + observeN(e, TierSemantic, lang.OutcomeKilled, 30) + if !e.isSettled(TierSemantic) { + t.Error("30/30 clears a 50% tier-2 threshold") + } +} diff --git a/internal/mutation/mutation.go b/internal/mutation/mutation.go index aa3af2b..a405c8c 100644 --- a/internal/mutation/mutation.go +++ b/internal/mutation/mutation.go @@ -1,19 +1,17 @@ // Package mutation orchestrates mutation testing across a diff's changed // files. The AST-level work (generating mutants, applying them, scanning -// annotations, running tests) is provided by the language back-end via -// lang.MutantGenerator / lang.MutantApplier / lang.AnnotationScanner / -// lang.TestRunner. This package owns the scheduling, tiering, and report -// formatting — pieces that don't depend on any particular language. +// annotations, running tests) is provided by the language back-end. This +// package owns planning, scheduling, tiering, caching and report formatting +// — pieces that don't depend on any particular language. package mutation import ( + "context" "fmt" - "math/rand" + "io" "os" "path/filepath" "runtime" - "strings" - "sync" "time" "github.com/0xPolygon/diffguard/internal/diff" @@ -25,10 +23,51 @@ import ( type Mutant struct { File string Line int + Offset int Description string Operator string Killed bool - TestOutput string + // Outcome is the classified result. Unset means "derive from Killed", + // which keeps hand-built mutants in tests and legacy runners working. + Outcome lang.MutantOutcome + Cached bool + TestOutput string +} + +func (m Mutant) outcome() lang.MutantOutcome { + if m.Outcome != lang.OutcomeUnset { + return m.Outcome + } + if m.Killed { + return lang.OutcomeKilled + } + return lang.OutcomeSurvived +} + +func (m *Mutant) setResult(r lang.MutantResult) { + m.Outcome = r.Outcome + m.Killed = isKill(r.Outcome) + if m.Killed { + m.TestOutput = r.Output + } +} + +func (m Mutant) site() lang.MutantSite { + return lang.MutantSite{ + File: m.File, + Line: m.Line, + Offset: m.Offset, + Description: m.Description, + Operator: m.Operator, + } +} + +func isKill(o lang.MutantOutcome) bool { + return o == lang.OutcomeKilled || o == lang.OutcomeTimedOut +} + +func isSurvivor(o lang.MutantOutcome) bool { + return o == lang.OutcomeSurvived || o == lang.OutcomeNotCovered } // Options configures a mutation testing run. @@ -52,6 +91,26 @@ type Options struct { // Workers caps the number of mutants processed concurrently. Zero or // negative means use runtime.NumCPU(). Workers int + // Context cancels the run; mutants not yet tested are reported as not + // run. Nil means context.Background(). + Context context.Context + // Budget caps the wall-clock time of the run. Zero means no cap. + Budget time.Duration + // Seed drives sampling and early-stop ordering. Zero means 1, so runs + // are reproducible by default. + Seed int64 + // ShardIndex/ShardCount select the 1-based ShardIndex-th of ShardCount + // slices of the mutant list. ShardCount <= 1 disables sharding. + ShardIndex int + ShardCount int + // CacheDir, if non-empty, stores outcomes keyed by package fingerprint + // so unchanged packages are not re-tested. + CacheDir string + // Confidence (0-1), if positive, stops a gating tier early once its + // pass/fail verdict is settled at this confidence level. + Confidence float64 + // Progress receives periodic status lines. Nil disables them. + Progress io.Writer } const ( @@ -88,18 +147,33 @@ func (o Options) workers() int { return o.Workers } +func (o Options) seed() int64 { + if o.Seed == 0 { + return 1 + } + return o.Seed +} + +// runContext returns the context mutants run under: the caller's context, +// bounded by the budget when one is set. +func (o Options) runContext() (context.Context, context.CancelFunc) { + ctx := o.Context + if ctx == nil { + ctx = context.Background() + } + if o.Budget <= 0 { + return context.WithCancel(ctx) + } + return context.WithTimeout(ctx, o.Budget) +} + // Analyze applies mutation operators to changed code (via the language's -// MutantGenerator/Applier) and runs the language's TestRunner against each -// mutant. -// -// Parallelism is controlled by Options.Workers; concurrency safety is the -// TestRunner's responsibility (Go's overlay-based runner is safe to call -// concurrently; temp-copy runners for other languages must serialize -// per-file internally). +// MutantGenerator) and tests each mutant, through the language's +// SessionRunner when it has one and its MutantApplier/TestRunner otherwise. func Analyze(repoPath string, d *diff.Result, l lang.Language, opts Options) (report.Section, error) { - allMutants := collectMutants(repoPath, d, l) + mutants := planMutants(collectMutants(repoPath, d, l), opts) - if len(allMutants) == 0 { + if len(mutants) == 0 { return report.Section{ Name: "Mutation Testing", Summary: "No mutants generated from changed code", @@ -107,18 +181,19 @@ func Analyze(repoPath string, d *diff.Result, l lang.Language, opts Options) (re }, nil } - if opts.SampleRate < 100 { - allMutants = sampleMutants(allMutants, opts.SampleRate) - } - workDir, err := os.MkdirTemp("", "diffguard-mutation-") if err != nil { return report.Section{}, fmt.Errorf("creating mutation work dir: %w", err) } defer os.RemoveAll(workDir) - killed := runMutantsParallel(repoPath, allMutants, l, opts, workDir) - return buildSection(allMutants, killed, opts), nil + cache := openCache(opts, repoPath, l) + cache.load(mutants) + if err := runMutantsParallel(repoPath, mutants, l, opts, workDir); err != nil { + return report.Section{}, err + } + cache.store(mutants) + return buildSection(mutants, opts), nil } // collectMutants gathers mutation sites for every changed file, honoring @@ -143,6 +218,7 @@ func collectMutants(repoPath string, d *diff.Result, l lang.Language) []Mutant { all = append(all, Mutant{ File: s.File, Line: s.Line, + Offset: s.Offset, Description: s.Description, Operator: s.Operator, }) @@ -150,245 +226,3 @@ func collectMutants(repoPath string, d *diff.Result, l lang.Language) []Mutant { } return all } - -// runMutantsParallel processes mutants in two phases: -// -// 1. Prepare: ApplyMutation for every mutant and write the mutated bytes -// to a temp file. Runs before any RunTest so ApplyMutation always sees -// pristine source on disk — critical for temp-copy runners (Rust, TS) -// that swap the mutant over the real file during RunTest. If we -// interleaved apply + test, a concurrent worker's ApplyMutation could -// read a file that another worker's RunTest had temporarily mutated, -// produce the wrong mutant (or fail to locate its target), and get -// silently reported as SURVIVED. -// 2. Test: RunTest for each prepared mutant, capped at opts.workers(). -// The TestRunner is responsible for per-file isolation (Go uses overlay, -// non-Go runners serialize same-file mutants via a mutex). -func runMutantsParallel(repoPath string, mutants []Mutant, l lang.Language, opts Options, workDir string) int { - applier := l.MutantApplier() - runner := l.TestRunner() - - prepared := prepareMutants(repoPath, mutants, applier, workDir, opts.workers()) - - var wg sync.WaitGroup - sem := make(chan struct{}, opts.workers()) - - for i := range mutants { - if prepared[i] == "" { - continue - } - wg.Add(1) - sem <- struct{}{} - go func(idx int) { - defer wg.Done() - defer func() { <-sem }() - mutants[idx].Killed = runPreparedMutant(repoPath, &mutants[idx], prepared[idx], runner, opts, workDir, idx) - }(i) - } - wg.Wait() - - killed := 0 - for i := range mutants { - if mutants[i].Killed { - killed++ - } - } - return killed -} - -// prepareMutants applies every mutation to pristine source and stores the -// mutated bytes in per-mutant temp files. Returns a parallel slice of -// mutantFile paths; an empty string marks a skipped mutant (the applier -// declined to produce bytes — parse error, no target, equivalence, …). -// -// Apply is parallelized across mutants because no RunTest has fired yet, -// so the source files on disk are still pristine and safe for concurrent -// reads. -func prepareMutants(repoPath string, mutants []Mutant, applier lang.MutantApplier, workDir string, workers int) []string { - prepared := make([]string, len(mutants)) - var wg sync.WaitGroup - sem := make(chan struct{}, workers) - - for i := range mutants { - wg.Add(1) - sem <- struct{}{} - go func(idx int) { - defer wg.Done() - defer func() { <-sem }() - prepared[idx] = prepareMutant(repoPath, mutants[idx], applier, workDir, idx) - }(i) - } - wg.Wait() - return prepared -} - -// prepareMutant runs ApplyMutation and writes the resulting bytes to a -// mutant-specific temp file. Returns the temp file path on success, or -// "" if the mutant was skipped (apply error / nil bytes / write error). -func prepareMutant(repoPath string, m Mutant, applier lang.MutantApplier, workDir string, idx int) string { - absPath := filepath.Join(repoPath, m.File) - - mutated, err := applier.ApplyMutation(absPath, lang.MutantSite{ - File: m.File, - Line: m.Line, - Description: m.Description, - Operator: m.Operator, - }) - if err != nil || mutated == nil { - return "" - } - - mutantFile := filepath.Join(workDir, fmt.Sprintf("m%d%s", idx, filepath.Ext(absPath))) - if err := os.WriteFile(mutantFile, mutated, 0644); err != nil { - return "" - } - return mutantFile -} - -// runPreparedMutant hands an already-written mutant file to the language's -// TestRunner. The runner returns (killed, output, err); on runner error we -// skip the mutant. -func runPreparedMutant(repoPath string, m *Mutant, mutantFile string, runner lang.TestRunner, opts Options, workDir string, idx int) bool { - absPath := filepath.Join(repoPath, m.File) - - killed, output, err := runner.RunTest(lang.TestRunConfig{ - RepoPath: repoPath, - MutantFile: mutantFile, - OriginalFile: absPath, - Timeout: opts.timeout(), - TestPattern: opts.TestPattern, - WorkDir: workDir, - Index: idx, - }) - if err != nil { - return false - } - if killed { - m.TestOutput = output - } - return killed -} - -func sampleMutants(mutants []Mutant, rate float64) []Mutant { - if rate >= 100 { - return mutants - } - rng := rand.New(rand.NewSource(time.Now().UnixNano())) - n := int(float64(len(mutants)) * rate / 100) - if n == 0 { - n = 1 - } - rng.Shuffle(len(mutants), func(i, j int) { - mutants[i], mutants[j] = mutants[j], mutants[i] - }) - return mutants[:n] -} - -func buildSection(mutants []Mutant, killed int, opts Options) report.Section { - total := len(mutants) - survived := total - killed - - score := 0.0 - if total > 0 { - score = float64(killed) / float64(total) * 100 - } - - tiers := computeTierStats(mutants) - sev := tieredSeverity(tiers, opts) - findings := survivedFindings(mutants) - - summary := buildTieredSummary(score, killed, total, survived, tiers) - - return report.Section{ - Name: "Mutation Testing", - Summary: summary, - Severity: sev, - Findings: findings, - Stats: map[string]any{ - "total": total, - "killed": killed, - "survived": survived, - "score": score, - "tiers": tiers, - "tier1_threshold": opts.tier1Threshold(), - "tier2_threshold": opts.tier2Threshold(), - }, - } -} - -// tieredSeverity classifies the run using per-tier thresholds: -// - Tier 1 below threshold → FAIL (logic gaps are real bugs-in-waiting). -// - Tier 2 below threshold → WARN (semantic gaps are often but not always -// real, and equivalent mutants are possible). -// - Tier 3 is informational only — its score is reported but does not -// contribute to severity, because log/metric mutations are untestable -// by design in most Go code. -// -// Tiers with zero mutants are treated as passing (nothing to gate on). -func tieredSeverity(tiers []TierStats, opts Options) report.Severity { - sev := report.SeverityPass - for _, ts := range tiers { - if ts.Total == 0 { - continue - } - switch tierSeverity(ts, opts) { - case report.SeverityFail: - return report.SeverityFail - case report.SeverityWarn: - sev = report.SeverityWarn - } - } - return sev -} - -// tierSeverity returns the severity contribution of a single tier: FAIL for -// Tier 1 below its threshold, WARN for Tier 2 below its threshold, PASS -// otherwise (including Tier 3, which is report-only). -func tierSeverity(ts TierStats, opts Options) report.Severity { - switch ts.Tier { - case TierLogic: - if ts.Score < opts.tier1Threshold() { - return report.SeverityFail - } - case TierSemantic: - if ts.Score < opts.tier2Threshold() { - return report.SeverityWarn - } - } - return report.SeverityPass -} - -// buildTieredSummary formats the one-line summary with overall score plus -// per-tier scores. Tiers with zero mutants are omitted to keep the line -// readable on small diffs. -func buildTieredSummary(score float64, killed, total, survived int, tiers []TierStats) string { - parts := []string{ - fmt.Sprintf("Score: %.1f%% (%d/%d killed, %d survived)", - score, killed, total, survived), - } - for _, ts := range tiers { - if ts.Total == 0 { - continue - } - parts = append(parts, - fmt.Sprintf("T%d %s: %.1f%% (%d/%d)", - int(ts.Tier), ts.Tier, ts.Score, ts.Killed, ts.Total)) - } - return strings.Join(parts, " | ") -} - -func survivedFindings(mutants []Mutant) []report.Finding { - var findings []report.Finding - for _, m := range mutants { - if m.Killed { - continue - } - findings = append(findings, report.Finding{ - File: m.File, - Line: m.Line, - Message: fmt.Sprintf("SURVIVED: %s (%s)", m.Description, m.Operator), - Severity: report.SeverityFail, - }) - } - return findings -} diff --git a/internal/mutation/mutation_extra_test.go b/internal/mutation/mutation_extra_test.go index 8c9e87b..784f29f 100644 --- a/internal/mutation/mutation_extra_test.go +++ b/internal/mutation/mutation_extra_test.go @@ -17,7 +17,7 @@ func TestBuildSection_HighScore(t *testing.T) { {File: "a.go", Line: 4, Killed: true, Operator: "negate_conditional"}, {File: "a.go", Line: 5, Killed: true, Operator: "negate_conditional"}, } - s := buildSection(mutants, 5, Options{}) + s := buildSection(mutants, Options{}) if s.Severity != report.SeverityPass { t.Errorf("severity = %v, want PASS", s.Severity) } @@ -33,7 +33,7 @@ func TestBuildSection_LowScore(t *testing.T) { {File: "a.go", Line: 4, Killed: false, Description: "mut", Operator: "negate_conditional"}, {File: "a.go", Line: 5, Killed: false, Description: "mut", Operator: "negate_conditional"}, } - s := buildSection(mutants, 1, Options{}) + s := buildSection(mutants, Options{}) if s.Severity != report.SeverityFail { t.Errorf("severity = %v, want FAIL", s.Severity) } @@ -52,14 +52,14 @@ func TestBuildSection_MediumScore(t *testing.T) { for i := killed; i < 10; i++ { mutants[i] = Mutant{File: "a.go", Line: i, Killed: false, Description: "mut", Operator: "boolean_substitution"} } - s := buildSection(mutants, killed, Options{}) + s := buildSection(mutants, Options{}) if s.Severity != report.SeverityWarn { t.Errorf("severity = %v, want WARN", s.Severity) } } func TestBuildSection_ZeroMutants(t *testing.T) { - s := buildSection(nil, 0, Options{}) + s := buildSection(nil, Options{}) if s.Severity != report.SeverityPass { t.Errorf("severity = %v, want PASS", s.Severity) } diff --git a/internal/mutation/plan.go b/internal/mutation/plan.go new file mode 100644 index 0000000..84be0b9 --- /dev/null +++ b/internal/mutation/plan.go @@ -0,0 +1,68 @@ +package mutation + +import ( + "math/rand" + "sort" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// planMutants turns the raw generated list into the ordered work list: +// duplicates dropped, the shard and sample applied, and gating tiers first +// so a budget or cancellation costs the least important results. +func planMutants(mutants []Mutant, opts Options) []Mutant { + mutants = dedupeMutants(mutants) + mutants = shardMutants(mutants, opts.ShardIndex, opts.ShardCount) + // Sampling keeps a random subset; early stopping reads a prefix of each + // tier as a random sample. Both need the same seeded shuffle. + if opts.SampleRate < 100 || opts.Confidence > 0 { + shuffleMutants(mutants, opts.seed()) + } + mutants = sampleMutants(mutants, opts.SampleRate) + sort.SliceStable(mutants, func(i, j int) bool { + return operatorTier(mutants[i].Operator) < operatorTier(mutants[j].Operator) + }) + return mutants +} + +// dedupeMutants drops mutants identical in every identifying field: testing +// the same mutation twice costs a run and double-counts its result. +func dedupeMutants(mutants []Mutant) []Mutant { + seen := make(map[lang.MutantSite]bool, len(mutants)) + out := mutants[:0:0] + for _, m := range mutants { + if seen[m.site()] { + continue + } + seen[m.site()] = true + out = append(out, m) + } + return out +} + +// shardMutants keeps every count-th mutant starting at the 1-based index, +// so `count` jobs with indexes 1..count partition the list. +func shardMutants(mutants []Mutant, index, count int) []Mutant { + if count < 2 || index < 1 || index > count { + return mutants + } + var out []Mutant + for i := index - 1; i < len(mutants); i += count { + out = append(out, mutants[i]) + } + return out +} + +func shuffleMutants(mutants []Mutant, seed int64) { + rng := rand.New(rand.NewSource(seed)) + rng.Shuffle(len(mutants), func(i, j int) { + mutants[i], mutants[j] = mutants[j], mutants[i] + }) +} + +// sampleMutants keeps the first rate percent of an already shuffled list, +// and never fewer than one mutant of a non-empty list. +func sampleMutants(mutants []Mutant, rate float64) []Mutant { + n := max(1, int(float64(len(mutants))*rate/100)) + return mutants[:min(n, len(mutants))] +} diff --git a/internal/mutation/plan_test.go b/internal/mutation/plan_test.go new file mode 100644 index 0000000..2bc620f --- /dev/null +++ b/internal/mutation/plan_test.go @@ -0,0 +1,134 @@ +package mutation + +import ( + "reflect" + "testing" +) + +func numbered(n int, operator string) []Mutant { + mutants := make([]Mutant, n) + for i := range mutants { + mutants[i] = Mutant{File: "a.go", Line: i + 1, Operator: operator} + } + return mutants +} + +func TestDedupeMutants(t *testing.T) { + a := Mutant{File: "a.go", Line: 3, Offset: 40, Operator: "negate_conditional", Description: "== -> !="} + sameLineOtherSite := a + sameLineOtherSite.Offset = 52 + got := dedupeMutants([]Mutant{a, sameLineOtherSite, a}) + if len(got) != 2 { + t.Fatalf("got %d mutants, want 2: an exact duplicate is dropped, a second site on the line is kept", len(got)) + } + if got[0].Offset != 40 || got[1].Offset != 52 { + t.Errorf("order not preserved: %+v", got) + } +} + +func TestShardMutants_PartitionsTheList(t *testing.T) { + mutants := numbered(10, "negate_conditional") + seen := map[int]int{} + total := 0 + for index := 1; index <= 3; index++ { + shard := shardMutants(mutants, index, 3) + total += len(shard) + for _, m := range shard { + seen[m.Line]++ + } + } + if total != 10 || len(seen) != 10 { + t.Fatalf("3 shards covered %d mutants (%d distinct), want all 10 exactly once", total, len(seen)) + } + if got := shardMutants(mutants, 2, 3); got[0].Line != 2 || got[1].Line != 5 { + t.Errorf("shard 2/3 starts %d,%d; want lines 2,5", got[0].Line, got[1].Line) + } +} + +func TestShardMutants_DisabledOrInvalid(t *testing.T) { + mutants := numbered(4, "negate_conditional") + for _, c := range [][2]int{{0, 0}, {1, 1}, {0, 3}, {4, 3}} { + if got := shardMutants(mutants, c[0], c[1]); len(got) != 4 { + t.Errorf("shard %d/%d kept %d mutants, want all 4", c[0], c[1], len(got)) + } + } +} + +func TestPlanMutants_SameSeedSameSample(t *testing.T) { + sample := func(seed int64) []Mutant { + return planMutants(numbered(50, "x"), Options{SampleRate: 20, Seed: seed}) + } + a, b, c := sample(7), sample(7), sample(8) + if !reflect.DeepEqual(a, b) { + t.Error("the same seed must select the same mutants") + } + if reflect.DeepEqual(a, c) { + t.Error("a different seed should select different mutants") + } + if len(a) != 10 { + t.Errorf("20%% of 50 = %d, want 10", len(a)) + } + if got := sampleMutants(numbered(3, "x"), 1); len(got) != 1 { + t.Errorf("a sample never rounds down to zero mutants, got %d", len(got)) + } +} + +func TestPlanMutants_GatingTiersFirst(t *testing.T) { + mutants := []Mutant{ + {File: "a.go", Line: 1, Operator: "statement_deletion"}, + {File: "a.go", Line: 2, Operator: "boolean_substitution"}, + {File: "a.go", Line: 3, Operator: "negate_conditional"}, + {File: "a.go", Line: 4, Operator: "statement_deletion"}, + {File: "a.go", Line: 5, Operator: "negate_conditional"}, + } + got := planMutants(mutants, Options{SampleRate: 100}) + var lines []int + for _, m := range got { + lines = append(lines, m.Line) + } + if want := []int{3, 5, 2, 1, 4}; !reflect.DeepEqual(lines, want) { + t.Errorf("order = %v, want %v (tier 1, tier 2, tier 3; source order within a tier)", lines, want) + } +} + +func TestPlanMutants_AppliesShardSampleAndShuffle(t *testing.T) { + if got := planMutants(numbered(40, "negate_conditional"), Options{SampleRate: 100, ShardIndex: 1, ShardCount: 4}); len(got) != 10 { + t.Errorf("shard 1/4 of 40 = %d, want 10", len(got)) + } + if got := planMutants(numbered(40, "negate_conditional"), Options{SampleRate: 50}); len(got) != 20 { + t.Errorf("50%% sample of 40 = %d, want 20", len(got)) + } + plain := planMutants(numbered(40, "negate_conditional"), Options{SampleRate: 100}) + shuffled := planMutants(numbered(40, "negate_conditional"), Options{SampleRate: 100, Confidence: 0.95}) + if plain[0].Line != 1 || plain[39].Line != 40 { + t.Error("without early stopping, source order is kept") + } + if reflect.DeepEqual(plain, shuffled) { + t.Error("early stopping needs a shuffled order so a prefix is a random sample") + } +} + +func TestShardMutants_TwoShards(t *testing.T) { + mutants := numbered(5, "x") + if got := shardMutants(mutants, 1, 2); len(got) != 3 { + t.Errorf("shard 1/2 of 5 = %d, want 3", len(got)) + } + if got := shardMutants(mutants, 2, 2); len(got) != 2 { + t.Errorf("shard 2/2 of 5 = %d, want 2", len(got)) + } +} + +func TestSampleMutants_Bounds(t *testing.T) { + if got := sampleMutants(nil, 20); len(got) != 0 { + t.Errorf("sampling nothing yields nothing, got %d", len(got)) + } + if got := sampleMutants(numbered(7, "x"), 100); len(got) != 7 { + t.Errorf("100%% keeps everything, got %d", len(got)) + } + if got := sampleMutants(numbered(7, "x"), 250); len(got) != 7 { + t.Errorf("a rate above 100 keeps everything, got %d", len(got)) + } + if got := planMutants(nil, Options{SampleRate: 20}); len(got) != 0 { + t.Errorf("planning an empty list yields nothing, got %d", len(got)) + } +} diff --git a/internal/mutation/run.go b/internal/mutation/run.go new file mode 100644 index 0000000..6caf08c --- /dev/null +++ b/internal/mutation/run.go @@ -0,0 +1,275 @@ +package mutation + +import ( + "context" + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "time" + + "github.com/0xPolygon/diffguard/internal/lang" +) + +// progressInterval is how often a status line is written while mutants run. +var progressInterval = 15000 * time.Millisecond + +// executor tests the pos-th pending mutant of a run. +type executor interface { + run(ctx context.Context, pos int) lang.MutantResult + close() +} + +// runMutantsParallel tests every mutant that has no outcome yet (cached +// results are left alone), capped at opts.workers() at a time. Mutants the +// budget or a cancellation never reached are marked not run rather than +// dropped. +func runMutantsParallel(repoPath string, mutants []Mutant, l lang.Language, opts Options, workDir string) error { + ctx, cancel := opts.runContext() + defer cancel() + + pending := pendingIndexes(mutants) + exec, err := newExecutor(ctx, repoPath, mutants, pending, l, opts, workDir) + if err != nil { + return err + } + defer exec.close() + + run := &mutantRun{ctx: ctx, mutants: mutants, exec: exec, stop: newEarlyStop(opts), start: time.Now()} + stopProgress := run.reportProgress(opts, len(pending)) + run.dispatch(pending, opts.workers()) + stopProgress() + return nil +} + +func pendingIndexes(mutants []Mutant) []int { + var pending []int + for i := range mutants { + if mutants[i].Outcome == lang.OutcomeUnset { + pending = append(pending, i) + } + } + return pending +} + +// mutantRun is the shared state of one scheduling pass. +type mutantRun struct { + ctx context.Context + mutants []Mutant + exec executor + stop *earlyStop + start time.Time + + // done and killed feed the progress line. + done atomic.Int64 + killed atomic.Int64 +} + +func (r *mutantRun) dispatch(pending []int, workers int) { + var wg sync.WaitGroup + sem := make(chan struct{}, workers) + for pos, idx := range pending { + wg.Add(1) + sem <- struct{}{} + go func() { + defer wg.Done() + defer func() { <-sem }() + r.runOne(pos, idx) + }() + } + wg.Wait() +} + +func (r *mutantRun) runOne(pos, idx int) { + m := &r.mutants[idx] + tier := operatorTier(m.Operator) + res := lang.MutantResult{Outcome: r.skipReason(tier)} + if res.Outcome == lang.OutcomeUnset { + res = r.exec.run(r.ctx, pos) + } + m.setResult(res) + r.stop.observe(tier, res.Outcome) + + r.done.Add(1) + if m.Killed { + r.killed.Add(1) + } +} + +// skipReason returns the outcome to record without testing the mutant, or +// OutcomeUnset if it should be tested. +func (r *mutantRun) skipReason(tier Tier) lang.MutantOutcome { + if r.ctx.Err() != nil { + return lang.OutcomeNotRun + } + if r.stop.isSettled(tier) { + return lang.OutcomeStoppedEarly + } + // mutator-disable-next-line (OutcomeUnset is the zero value: zeroing the return changes nothing) + return lang.OutcomeUnset +} + +// reportProgress writes a status line every progressInterval until the +// returned func is called, which also writes the final line. +func (r *mutantRun) reportProgress(opts Options, total int) func() { + if opts.Progress == nil { + return func() {} + } + line := func() { + fmt.Fprintf(opts.Progress, "mutation: %d/%d mutants done, %d killed, %s elapsed\n", + r.done.Load(), total, r.killed.Load(), time.Since(r.start).Round(time.Second)) + } + quit := make(chan struct{}) + finished := make(chan struct{}) + go func() { + defer close(finished) + ticker := time.NewTicker(progressInterval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + line() + case <-quit: + return + } + } + }() + return func() { + close(quit) + <-finished + line() + } +} + +func newExecutor(ctx context.Context, repoPath string, mutants []Mutant, pending []int, l lang.Language, opts Options, workDir string) (executor, error) { + sr, ok := l.(lang.SessionRunner) + if !ok { + return newLegacyExecutor(repoPath, mutants, pending, l, opts, workDir), nil + } + sites := make([]lang.MutantSite, len(pending)) + for pos, idx := range pending { + sites[pos] = mutants[idx].site() + } + session, err := sr.NewMutationSession(ctx, lang.SessionConfig{ + RepoPath: repoPath, + WorkDir: workDir, + Timeout: opts.timeout(), + TestPattern: opts.TestPattern, + Workers: opts.workers(), + Log: opts.Progress, + }, sites) + if err != nil { + return nil, fmt.Errorf("starting mutation session: %w", err) + } + return sessionExecutor{session}, nil +} + +// sessionExecutor adapts a language session, whose sites are the pending +// mutants in order. +type sessionExecutor struct{ session lang.MutationSession } + +func (e sessionExecutor) run(ctx context.Context, pos int) lang.MutantResult { + return e.session.Run(ctx, pos) +} + +func (e sessionExecutor) close() { e.session.Close() } + +// legacyExecutor drives languages without a SessionRunner in two phases: +// +// 1. Prepare: ApplyMutation for every mutant and write the mutated bytes +// to a temp file. Runs before any RunTest so ApplyMutation always sees +// pristine source on disk — critical for temp-copy runners (Rust, TS) +// that swap the mutant over the real file during RunTest. If we +// interleaved apply + test, a concurrent worker's ApplyMutation could +// read a file that another worker's RunTest had temporarily mutated, +// produce the wrong mutant (or fail to locate its target), and get +// silently reported as SURVIVED. +// 2. Test: RunTest for each prepared mutant. The TestRunner is responsible +// for per-file isolation (non-Go runners serialize same-file mutants +// via a mutex). +type legacyExecutor struct { + repoPath string + pending []Mutant + prepared []string // mutant file per pending mutant; "" = not applied + runner lang.TestRunner + opts Options + workDir string +} + +func newLegacyExecutor(repoPath string, mutants []Mutant, pending []int, l lang.Language, opts Options, workDir string) *legacyExecutor { + e := &legacyExecutor{repoPath: repoPath, runner: l.TestRunner(), opts: opts, workDir: workDir} + for _, idx := range pending { + e.pending = append(e.pending, mutants[idx]) + } + e.prepared = prepareMutants(repoPath, e.pending, l.MutantApplier(), workDir, opts.workers()) + return e +} + +func (e *legacyExecutor) close() {} + +func (e *legacyExecutor) run(_ context.Context, pos int) lang.MutantResult { + if e.prepared[pos] == "" { + return lang.MutantResult{Outcome: lang.OutcomeNotApplied} + } + killed, output, err := e.runner.RunTest(lang.TestRunConfig{ + RepoPath: e.repoPath, + MutantFile: e.prepared[pos], + OriginalFile: filepath.Join(e.repoPath, e.pending[pos].File), + Timeout: e.opts.timeout(), + TestPattern: e.opts.TestPattern, + WorkDir: e.workDir, + Index: pos, + }) + switch { + case err != nil: + return lang.MutantResult{Outcome: lang.OutcomeNotRun} + case killed: + return lang.MutantResult{Outcome: lang.OutcomeKilled, Output: output} + } + return lang.MutantResult{Outcome: lang.OutcomeSurvived} +} + +// prepareMutants applies every mutation to pristine source and stores the +// mutated bytes in per-mutant temp files. Returns a parallel slice of +// mutantFile paths; an empty string marks a skipped mutant (the applier +// declined to produce bytes — parse error, no target, equivalence, …). +// +// Apply is parallelized across mutants because no RunTest has fired yet, +// so the source files on disk are still pristine and safe for concurrent +// reads. +func prepareMutants(repoPath string, mutants []Mutant, applier lang.MutantApplier, workDir string, workers int) []string { + prepared := make([]string, len(mutants)) + var wg sync.WaitGroup + sem := make(chan struct{}, workers) + + for i := range mutants { + wg.Add(1) + sem <- struct{}{} + go func(idx int) { + defer wg.Done() + defer func() { <-sem }() + prepared[idx] = prepareMutant(repoPath, mutants[idx], applier, workDir, idx) + }(i) + } + wg.Wait() + return prepared +} + +// prepareMutant runs ApplyMutation and writes the resulting bytes to a +// mutant-specific temp file. Returns the temp file path on success, or +// "" if the mutant was skipped (apply error / nil bytes / write error). +func prepareMutant(repoPath string, m Mutant, applier lang.MutantApplier, workDir string, idx int) string { + absPath := filepath.Join(repoPath, m.File) + + mutated, err := applier.ApplyMutation(absPath, m.site()) + if err != nil || mutated == nil { + return "" + } + + mutantFile := filepath.Join(workDir, fmt.Sprintf("m%d%s", idx, filepath.Ext(absPath))) + if err := os.WriteFile(mutantFile, mutated, 0644); err != nil { + return "" + } + return mutantFile +} diff --git a/internal/mutation/run_test.go b/internal/mutation/run_test.go new file mode 100644 index 0000000..e4c2519 --- /dev/null +++ b/internal/mutation/run_test.go @@ -0,0 +1,476 @@ +package mutation + +import ( + "bytes" + "context" + "errors" + "os" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/0xPolygon/diffguard/internal/diff" + "github.com/0xPolygon/diffguard/internal/lang" + "github.com/0xPolygon/diffguard/internal/report" +) + +// sessionLanguage is a fakeLanguage that also offers a mutation session and +// a fingerprint, the two optional capabilities the orchestrator probes for. +type sessionLanguage struct { + fakeLanguage + // outcome decides each mutant's result from its site. + outcome func(lang.MutantSite) lang.MutantOutcome + // onRun, if set, is called at the start of every Run. + onRun func(ctx context.Context) + startErr error + fingerprint string + fpErr error + + runs atomic.Int64 + closed atomic.Bool + gotCfg lang.SessionConfig +} + +func (l *sessionLanguage) NewMutationSession(_ context.Context, cfg lang.SessionConfig, sites []lang.MutantSite) (lang.MutationSession, error) { + if l.startErr != nil { + return nil, l.startErr + } + l.gotCfg = cfg + return &fakeSession{lang: l, sites: sites}, nil +} + +func (l *sessionLanguage) MutationFingerprint(string, string) (string, error) { + return l.fingerprint, l.fpErr +} + +type fakeSession struct { + lang *sessionLanguage + sites []lang.MutantSite +} + +func (s *fakeSession) Run(ctx context.Context, idx int) lang.MutantResult { + s.lang.runs.Add(1) + if s.lang.onRun != nil { + s.lang.onRun(ctx) + } + return lang.MutantResult{Outcome: s.lang.outcome(s.sites[idx]), Output: "out"} +} + +func (s *fakeSession) Close() { s.lang.closed.Store(true) } + +func killedCount(mutants []Mutant) int { + n := 0 + for _, m := range mutants { + if m.Killed { + n++ + } + } + return n +} + +// byLine maps a mutant's line number to its outcome. +func byLine(outcomes ...lang.MutantOutcome) func(lang.MutantSite) lang.MutantOutcome { + return func(s lang.MutantSite) lang.MutantOutcome { return outcomes[s.Line-1] } +} + +func TestRunMutantsParallel_SessionOutcomes(t *testing.T) { + l := &sessionLanguage{outcome: byLine(lang.OutcomeKilled, lang.OutcomeSurvived, lang.OutcomeTimedOut, lang.OutcomeBuildFailed)} + mutants := numbered(4, "negate_conditional") + err := runMutantsParallel("/repo", mutants, l, Options{Workers: 2, TestPattern: "TestX", TestTimeout: time.Minute}, "/work") + killed := killedCount(mutants) + if err != nil { + t.Fatal(err) + } + if killed != 2 { + t.Errorf("killed = %d, want 2 (a kill and a timeout)", killed) + } + if !mutants[0].Killed || mutants[0].TestOutput != "out" { + t.Errorf("killed mutant should keep its output: %+v", mutants[0]) + } + if mutants[1].Killed || mutants[1].TestOutput != "" { + t.Errorf("survivor should carry no output: %+v", mutants[1]) + } + if mutants[3].Outcome != lang.OutcomeBuildFailed || mutants[3].Killed { + t.Errorf("build failure must not count as a kill: %+v", mutants[3]) + } + if !l.closed.Load() { + t.Error("the session must be closed") + } + want := lang.SessionConfig{RepoPath: "/repo", WorkDir: "/work", Timeout: time.Minute, TestPattern: "TestX", Workers: 2} + if l.gotCfg != want { + t.Errorf("session config = %+v, want %+v", l.gotCfg, want) + } +} + +func TestRunMutantsParallel_SkipsMutantsThatAlreadyHaveAnOutcome(t *testing.T) { + l := &sessionLanguage{outcome: byLine(lang.OutcomeUnset, lang.OutcomeSurvived, lang.OutcomeUnset)} + mutants := numbered(3, "negate_conditional") + mutants[0].setResult(lang.MutantResult{Outcome: lang.OutcomeKilled}) + mutants[2].setResult(lang.MutantResult{Outcome: lang.OutcomeKilled}) + _ = runMutantsParallel("/repo", mutants, l, Options{Workers: 1}, t.TempDir()) + killed := killedCount(mutants) + if l.runs.Load() != 1 { + t.Errorf("ran %d mutants, want only the 1 without a cached outcome", l.runs.Load()) + } + if killed != 2 || mutants[1].Outcome != lang.OutcomeSurvived { + t.Errorf("killed = %d, mutants = %+v", killed, mutants) + } +} + +func TestRunMutantsParallel_SessionStartError(t *testing.T) { + l := &sessionLanguage{startErr: errors.New("boom")} + err := runMutantsParallel("/repo", numbered(1, "x"), l, Options{}, t.TempDir()) + if err == nil || !strings.Contains(err.Error(), "boom") { + t.Errorf("err = %v, want the session error", err) + } +} + +// When the budget runs out, mutants that never started are reported as not +// run; they are neither dropped nor counted as survivors. +func TestRunMutantsParallel_BudgetMarksRestNotRun(t *testing.T) { + l := &sessionLanguage{outcome: byLine(make([]lang.MutantOutcome, 6)...)} + l.outcome = func(lang.MutantSite) lang.MutantOutcome { return lang.OutcomeKilled } + l.onRun = func(ctx context.Context) { <-ctx.Done() } + mutants := numbered(6, "negate_conditional") + err := runMutantsParallel("/repo", mutants, l, Options{Workers: 1, Budget: 30 * time.Millisecond}, t.TempDir()) + killed := killedCount(mutants) + if err != nil { + t.Fatal(err) + } + if l.runs.Load() != 1 || killed != 1 { + t.Errorf("runs = %d, killed = %d; want exactly the one mutant in flight", l.runs.Load(), killed) + } + for _, m := range mutants[1:] { + if m.Outcome != lang.OutcomeNotRun { + t.Errorf("mutant on line %d: outcome %v, want not_run", m.Line, m.Outcome) + } + } +} + +func TestRunMutantsParallel_CancelledContext(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + l := &sessionLanguage{outcome: func(lang.MutantSite) lang.MutantOutcome { return lang.OutcomeKilled }} + mutants := numbered(3, "negate_conditional") + _ = runMutantsParallel("/repo", mutants, l, Options{Context: ctx}, t.TempDir()) + killed := killedCount(mutants) + if killed != 0 || l.runs.Load() != 0 { + t.Errorf("killed = %d, runs = %d; a cancelled run tests nothing", killed, l.runs.Load()) + } +} + +func TestRunMutantsParallel_EarlyStopSkipsSettledTier(t *testing.T) { + l := &sessionLanguage{outcome: func(lang.MutantSite) lang.MutantOutcome { return lang.OutcomeKilled }} + mutants := append(numbered(100, "negate_conditional"), Mutant{File: "a.go", Line: 500, Operator: "statement_deletion"}) + runMutantsParallel("/repo", mutants, l, Options{Workers: 1, Confidence: 0.95, Tier1Threshold: 80}, t.TempDir()) + if got := l.runs.Load(); got != earlyStopMinSamples+1 { + t.Errorf("ran %d mutants, want %d tier-1 then the tier-3 one", got, earlyStopMinSamples+1) + } + if mutants[earlyStopMinSamples].Outcome != lang.OutcomeStoppedEarly { + t.Errorf("outcome = %v, want stopped_early", mutants[earlyStopMinSamples].Outcome) + } + if mutants[100].Outcome != lang.OutcomeKilled { + t.Error("the ungated tier still runs") + } +} + +func TestRunMutantsParallel_RespectsWorkerLimit(t *testing.T) { + var mu sync.Mutex + running, peak := 0, 0 + l := &sessionLanguage{outcome: func(lang.MutantSite) lang.MutantOutcome { return lang.OutcomeKilled }} + l.onRun = func(context.Context) { + mu.Lock() + running++ + peak = max(peak, running) + mu.Unlock() + time.Sleep(5 * time.Millisecond) + mu.Lock() + running-- + mu.Unlock() + } + runMutantsParallel("/repo", numbered(12, "x"), l, Options{Workers: 3}, t.TempDir()) + if peak != 3 { + t.Errorf("peak concurrency = %d, want exactly the 3 workers", peak) + } +} + +func TestRunMutantsParallel_Progress(t *testing.T) { + old := progressInterval + progressInterval = time.Millisecond + defer func() { progressInterval = old }() + + var buf syncBuffer + l := &sessionLanguage{outcome: byLine(lang.OutcomeKilled, lang.OutcomeSurvived)} + l.onRun = func(context.Context) { time.Sleep(20 * time.Millisecond) } + runMutantsParallel("/repo", numbered(2, "x"), l, Options{Workers: 1, Progress: &buf}, t.TempDir()) + out := buf.String() + if !strings.Contains(out, "mutation: 0/2 mutants done, 0 killed") { + t.Errorf("missing a periodic line while mutants run:\n%s", out) + } + if !strings.HasSuffix(out, "mutation: 2/2 mutants done, 1 killed, 0s elapsed\n") { + t.Errorf("missing the final line:\n%s", out) + } +} + +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +type bytesApplier struct{} + +func (bytesApplier) ApplyMutation(string, lang.MutantSite) ([]byte, error) { + return []byte("mutant"), nil +} + +type nilApplier struct{} + +func (nilApplier) ApplyMutation(string, lang.MutantSite) ([]byte, error) { return nil, nil } + +type scriptedRunner struct { + killed bool + err error +} + +func (r scriptedRunner) RunTest(lang.TestRunConfig) (bool, string, error) { + return r.killed, "out", r.err +} + +func TestLegacyExecutor_Outcomes(t *testing.T) { + cases := []struct { + name string + applier lang.MutantApplier + runner scriptedRunner + want lang.MutantOutcome + }{ + {"applier declines", nilApplier{}, scriptedRunner{killed: true}, lang.OutcomeNotApplied}, + {"killed", bytesApplier{}, scriptedRunner{killed: true}, lang.OutcomeKilled}, + {"survived", bytesApplier{}, scriptedRunner{}, lang.OutcomeSurvived}, + {"runner error", bytesApplier{}, scriptedRunner{killed: true, err: errors.New("x")}, lang.OutcomeNotRun}, + } + for _, c := range cases { + dir := t.TempDir() + mutants := numbered(1, "negate_conditional") + l := &fakeLanguage{applier: c.applier, runner: c.runner} + runMutantsParallel(dir, mutants, l, Options{Workers: 1}, dir) + if mutants[0].Outcome != c.want { + t.Errorf("%s: outcome = %v, want %v", c.name, mutants[0].Outcome, c.want) + } + } +} + +func TestOptionsSeedAndRunContext(t *testing.T) { + if (Options{}).seed() != 1 || (Options{Seed: 9}).seed() != 9 { + t.Error("seed defaults to 1 and honors an explicit value") + } + ctx, cancel := Options{}.runContext() + if _, bounded := ctx.Deadline(); bounded { + t.Error("no budget means no deadline") + } + cancel() + ctx, cancel = Options{Budget: time.Hour}.runContext() + defer cancel() + if _, bounded := ctx.Deadline(); !bounded { + t.Error("a budget sets a deadline") + } +} + +func TestBuildSection_ExcludesUnscoredOutcomes(t *testing.T) { + mutants := numbered(6, "negate_conditional") + for i, o := range []lang.MutantOutcome{lang.OutcomeKilled, lang.OutcomeTimedOut, lang.OutcomeSurvived, lang.OutcomeNotCovered, lang.OutcomeBuildFailed, lang.OutcomeNotApplied} { + mutants[i].setResult(lang.MutantResult{Outcome: o}) + } + mutants[0].Cached = true + s := buildSection(mutants, Options{Tier1Threshold: 50}) + stats := s.Stats.(map[string]any) + if stats["total"] != 4 || stats["killed"] != 2 || stats["survived"] != 2 || stats["score"] != 50.0 { + t.Errorf("stats = %v; want 2 killed of 4 scored", stats) + } + outcomes := stats["outcomes"].(map[string]int) + if stats["generated"] != 6 || stats["cached"] != 1 || outcomes["build_failed"] != 1 || outcomes["timed_out"] != 1 || outcomes["killed"] != 1 { + t.Errorf("stats = %v", stats) + } + for _, want := range []string{"Score: 50.0% (2/4 killed, 2 survived)", "1 timed out", "1 not covered", "1 do not compile (excluded)", "1 not applied (excluded)", "1 from cache"} { + if !strings.Contains(s.Summary, want) { + t.Errorf("summary %q is missing %q", s.Summary, want) + } + } + if strings.Contains(s.Summary, "NOT RUN") || strings.Contains(s.Summary, "settled early") { + t.Errorf("summary mentions outcomes that did not occur: %q", s.Summary) + } + if s.Severity != report.SeverityPass { + t.Errorf("severity = %v, want PASS at exactly the threshold", s.Severity) + } + if len(s.Findings) != 2 || !strings.HasPrefix(s.Findings[0].Message, "SURVIVED:") || !strings.HasPrefix(s.Findings[1].Message, "NOT COVERED:") { + t.Errorf("findings = %+v", s.Findings) + } +} + +func TestBuildSection_FindingsSortedByFileThenLine(t *testing.T) { + mutants := []Mutant{ + {File: "b.go", Line: 9, Operator: "statement_deletion"}, + {File: "a.go", Line: 7, Operator: "negate_conditional"}, + {File: "a.go", Line: 2, Operator: "statement_deletion"}, + } + f := buildSection(mutants, Options{}).Findings + if f[0].Line != 2 || f[1].Line != 7 || f[2].File != "b.go" { + t.Errorf("findings out of order: %+v", f) + } +} + +// A gating tier with mutants that never ran cannot pass silently, but an +// unfinished report-only tier, or a tier stopped early on purpose, can. +func TestBuildSection_IncompleteGatingTierWarns(t *testing.T) { + section := func(operator string, o lang.MutantOutcome) report.Section { + mutants := numbered(2, operator) + mutants[0].setResult(lang.MutantResult{Outcome: lang.OutcomeKilled}) + mutants[1].setResult(lang.MutantResult{Outcome: o}) + return buildSection(mutants, Options{}) + } + if s := section("negate_conditional", lang.OutcomeNotRun); s.Severity != report.SeverityWarn || !strings.Contains(s.Summary, "1 NOT RUN") { + t.Errorf("tier 1 not run: %v %q", s.Severity, s.Summary) + } + if s := section("boolean_substitution", lang.OutcomeNotRun); s.Severity != report.SeverityWarn { + t.Errorf("tier 2 not run: severity = %v, want WARN", s.Severity) + } + if s := section("statement_deletion", lang.OutcomeNotRun); s.Severity != report.SeverityPass { + t.Errorf("tier 3 not run: severity = %v, want PASS", s.Severity) + } + if s := section("negate_conditional", lang.OutcomeStoppedEarly); s.Severity != report.SeverityPass || !strings.Contains(s.Summary, "1 skipped (verdict settled early)") { + t.Errorf("stopped early: %v %q", s.Severity, s.Summary) + } +} + +func TestTierSeverity_FailBeatsIncomplete(t *testing.T) { + ts := TierStats{Tier: TierLogic, Total: 10, Killed: 1, Score: 10, NotRun: 5} + if got := tierSeverity(ts, Options{}); got != report.SeverityFail { + t.Errorf("severity = %v, want FAIL", got) + } + empty := TierStats{Tier: TierLogic, NotRun: 3} + if got := tierSeverity(empty, Options{}); got != report.SeverityWarn { + t.Errorf("nothing scored, some not run: severity = %v, want WARN", got) + } +} + +func TestMutantOutcomeDerivedFromKilled(t *testing.T) { + if (Mutant{Killed: true}).outcome() != lang.OutcomeKilled || (Mutant{}).outcome() != lang.OutcomeSurvived { + t.Error("a mutant without an explicit outcome derives it from Killed") + } + if (Mutant{Killed: true, Outcome: lang.OutcomeBuildFailed}).outcome() != lang.OutcomeBuildFailed { + t.Error("an explicit outcome wins") + } +} + +func TestBuildSection_NothingScored(t *testing.T) { + mutants := numbered(1, "negate_conditional") + mutants[0].setResult(lang.MutantResult{Outcome: lang.OutcomeBuildFailed}) + s := buildSection(mutants, Options{}) + if score := s.Stats.(map[string]any)["score"]; score != 0.0 { + t.Errorf("score = %v, want 0 when no mutant was scored", score) + } + if s.Severity != report.SeverityPass { + t.Errorf("severity = %v, want PASS", s.Severity) + } +} + +func TestTierSeverity_PassValues(t *testing.T) { + for _, ts := range []TierStats{ + {Tier: TierObservability, Total: 10, Score: 0, NotRun: 4}, + {Tier: TierLogic, Total: 10, Killed: 10, Score: 100}, + {Tier: TierSemantic}, + } { + if got := tierSeverity(ts, Options{}); got != report.SeverityPass { + t.Errorf("tierSeverity(%+v) = %q, want PASS", ts, got) + } + } + if got := tierSeverity(TierStats{Tier: TierSemantic, Total: 10, Score: 10}, Options{}); got != report.SeverityWarn { + t.Errorf("tier 2 below threshold = %q, want WARN", got) + } +} + +func TestGatingThreshold(t *testing.T) { + opts := Options{Tier1Threshold: 81, Tier2Threshold: 62} + if th, ok := gatingThreshold(TierLogic, opts); th != 81 || !ok { + t.Errorf("tier 1: %v %v", th, ok) + } + if th, ok := gatingThreshold(TierSemantic, opts); th != 62 || !ok { + t.Errorf("tier 2: %v %v", th, ok) + } + if _, ok := gatingThreshold(TierObservability, opts); ok { + t.Error("tier 3 is not gated") + } +} + +// analyzableLanguage adds a generator and annotation scanner to +// sessionLanguage so Analyze can run end to end. +type analyzableLanguage struct { + sessionLanguage + sites []lang.MutantSite +} + +func (l *analyzableLanguage) MutantGenerator() lang.MutantGenerator { return l } +func (l *analyzableLanguage) AnnotationScanner() lang.AnnotationScanner { return l } + +func (l *analyzableLanguage) ScanAnnotations(string) (map[int]bool, error) { return nil, nil } + +func (l *analyzableLanguage) GenerateMutants(string, diff.FileChange, map[int]bool) ([]lang.MutantSite, error) { + return l.sites, nil +} + +func TestAnalyze(t *testing.T) { + d := &diff.Result{Files: []diff.FileChange{{Path: "a.go"}}} + l := &analyzableLanguage{sites: []lang.MutantSite{ + {File: "a.go", Line: 1, Offset: 5, Operator: "negate_conditional", Description: "== -> !="}, + {File: "a.go", Line: 2, Offset: 9, Operator: "negate_conditional", Description: "== -> !="}, + {File: "a.go", Line: 2, Offset: 9, Operator: "negate_conditional", Description: "== -> !="}, + }} + l.fingerprint = "v1" + l.outcome = byLine(lang.OutcomeKilled, lang.OutcomeSurvived) + cacheDir := t.TempDir() + + s, err := Analyze("/repo", d, l, Options{SampleRate: 100, CacheDir: cacheDir}) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(s.Summary, "Score: 50.0% (1/2 killed, 1 survived)") || s.Severity != report.SeverityFail { + t.Errorf("first run: %q [%s]; want the duplicate site dropped and 1 of 2 killed", s.Summary, s.Severity) + } + if l.gotCfg.WorkDir == "" { + t.Error("the session needs a work directory") + } + if _, err := os.Stat(l.gotCfg.WorkDir); !os.IsNotExist(err) { + t.Error("the work directory must be removed after the run") + } + + again, err := Analyze("/repo", d, l, Options{SampleRate: 100, CacheDir: cacheDir}) + if err != nil { + t.Fatal(err) + } + if l.runs.Load() != 2 || !strings.Contains(again.Summary, "2 from cache") { + t.Errorf("second run should come from the cache: runs = %d, summary %q", l.runs.Load(), again.Summary) + } + + l.startErr = errors.New("boom") + if _, err := Analyze("/repo", d, l, Options{}); err == nil { + t.Error("a session that cannot start is an error") + } + + none, err := Analyze("/repo", d, &analyzableLanguage{}, Options{}) + if err != nil || none.Summary != "No mutants generated from changed code" || none.Severity != report.SeverityPass { + t.Errorf("no mutants: %+v, %v", none, err) + } +} diff --git a/internal/mutation/section.go b/internal/mutation/section.go new file mode 100644 index 0000000..3c7b496 --- /dev/null +++ b/internal/mutation/section.go @@ -0,0 +1,187 @@ +package mutation + +import ( + "cmp" + "fmt" + "slices" + "strings" + + "github.com/0xPolygon/diffguard/internal/lang" + "github.com/0xPolygon/diffguard/internal/report" +) + +// buildSection formats the run. Scores cover only mutants that compiled and +// were tested: a mutant that cannot build says nothing about the tests, and +// one that never ran is reported as missing rather than guessed at. +func buildSection(mutants []Mutant, opts Options) report.Section { + counts := countOutcomes(mutants) + killed := counts[lang.OutcomeKilled] + counts[lang.OutcomeTimedOut] + survived := counts[lang.OutcomeSurvived] + counts[lang.OutcomeNotCovered] + total := killed + survived + + score := 0.0 + if total > 0 { + score = float64(killed) / float64(total) * 100 + } + + tiers := computeTierStats(mutants) + stats := map[string]any{ + "total": total, + "killed": killed, + "survived": survived, + "score": score, + "tiers": tiers, + "tier1_threshold": opts.tier1Threshold(), + "tier2_threshold": opts.tier2Threshold(), + "generated": len(mutants), + "cached": countCached(mutants), + "outcomes": outcomeStats(counts), + } + + return report.Section{ + Name: "Mutation Testing", + Summary: buildTieredSummary(score, killed, total, survived, tiers) + outcomeNotes(counts, countCached(mutants)), + Severity: tieredSeverity(tiers, opts), + Findings: survivedFindings(mutants), + Stats: stats, + } +} + +func countOutcomes(mutants []Mutant) map[lang.MutantOutcome]int { + counts := map[lang.MutantOutcome]int{} + for _, m := range mutants { + counts[m.outcome()]++ + } + return counts +} + +// outcomeStats keys the per-outcome counts by name for the JSON report. +func outcomeStats(counts map[lang.MutantOutcome]int) map[string]int { + out := make(map[string]int, len(counts)) + for o, n := range counts { + out[o.String()] = n + } + return out +} + +func countCached(mutants []Mutant) int { + n := 0 + for _, m := range mutants { + if m.Cached { + n++ + } + } + return n +} + +// outcomeNotes lists the outcomes that are not plain kills or survivals, so +// a reader can see what the score leaves out. +func outcomeNotes(counts map[lang.MutantOutcome]int, cached int) string { + notes := []struct { + n int + label string + }{ + {counts[lang.OutcomeTimedOut], "timed out"}, + {counts[lang.OutcomeNotCovered], "not covered"}, + {counts[lang.OutcomeBuildFailed], "do not compile (excluded)"}, + {counts[lang.OutcomeNotApplied], "not applied (excluded)"}, + {counts[lang.OutcomeNotRun], "NOT RUN (budget or cancelled)"}, + {counts[lang.OutcomeStoppedEarly], "skipped (verdict settled early)"}, + {cached, "from cache"}, + } + var sb strings.Builder + for _, note := range notes { + if note.n > 0 { + fmt.Fprintf(&sb, " | %d %s", note.n, note.label) + } + } + return sb.String() +} + +// tieredSeverity classifies the run using per-tier thresholds: +// - Tier 1 below threshold → FAIL (logic gaps are real bugs-in-waiting). +// - Tier 2 below threshold → WARN (semantic gaps are often but not always +// real, and equivalent mutants are possible). +// - Tier 3 is informational only — its score is reported but does not +// contribute to severity, because log/metric mutations are untestable +// by design in most Go code. +// - A gating tier with mutants that never ran → at least WARN: the gate +// did not see everything it was asked to judge. +// +// Tiers with zero mutants are treated as passing (nothing to gate on). +func tieredSeverity(tiers []TierStats, opts Options) report.Severity { + sev := report.SeverityPass + for _, ts := range tiers { + switch tierSeverity(ts, opts) { + case report.SeverityFail: + return report.SeverityFail + case report.SeverityWarn: + sev = report.SeverityWarn + } + } + return sev +} + +// tierSeverity returns the severity contribution of a single tier: FAIL for +// Tier 1 below its threshold, WARN for Tier 2 below its threshold or for an +// incomplete gating tier, PASS otherwise (including Tier 3, which is +// report-only). +func tierSeverity(ts TierStats, opts Options) report.Severity { + threshold, gated := gatingThreshold(ts.Tier, opts) + if !gated { + return report.SeverityPass + } + if ts.Total > 0 && ts.Score < threshold { + if ts.Tier == TierLogic { + return report.SeverityFail + } + return report.SeverityWarn + } + if ts.NotRun > 0 { + return report.SeverityWarn + } + return report.SeverityPass +} + +// buildTieredSummary formats the one-line summary with overall score plus +// per-tier scores. Tiers with zero mutants are omitted to keep the line +// readable on small diffs. +func buildTieredSummary(score float64, killed, total, survived int, tiers []TierStats) string { + parts := []string{ + fmt.Sprintf("Score: %.1f%% (%d/%d killed, %d survived)", + score, killed, total, survived), + } + for _, ts := range tiers { + if ts.Total == 0 { + continue + } + parts = append(parts, + fmt.Sprintf("T%d %s: %.1f%% (%d/%d)", + int(ts.Tier), ts.Tier, ts.Score, ts.Killed, ts.Total)) + } + return strings.Join(parts, " | ") +} + +func survivedFindings(mutants []Mutant) []report.Finding { + var findings []report.Finding + for _, m := range mutants { + label := "SURVIVED" + switch m.outcome() { + case lang.OutcomeSurvived: + case lang.OutcomeNotCovered: + label = "NOT COVERED" + default: + continue + } + findings = append(findings, report.Finding{ + File: m.File, + Line: m.Line, + Message: fmt.Sprintf("%s: %s (%s)", label, m.Description, m.Operator), + Severity: report.SeverityFail, + }) + } + slices.SortStableFunc(findings, func(a, b report.Finding) int { + return cmp.Or(strings.Compare(a.File, b.File), cmp.Compare(a.Line, b.Line)) + }) + return findings +} diff --git a/internal/mutation/tiers.go b/internal/mutation/tiers.go index f733fc4..7e38809 100644 --- a/internal/mutation/tiers.go +++ b/internal/mutation/tiers.go @@ -1,5 +1,7 @@ package mutation +import "github.com/0xPolygon/diffguard/internal/lang" + // Tier classifies mutation operators by how much signal a surviving mutant // carries. // @@ -87,6 +89,8 @@ type TierStats struct { Total int `json:"total"` Killed int `json:"killed"` Survived int `json:"survived"` + // NotRun counts mutants the budget or a cancellation never reached. + NotRun int `json:"not_run,omitempty"` // Score is killed / total * 100; 0 when total == 0. Score float64 `json:"score"` } @@ -104,11 +108,15 @@ func computeTierStats(mutants []Mutant) []TierStats { for _, m := range mutants { s := stats[operatorTier(m.Operator)] - s.Total++ - if m.Killed { + switch o := m.outcome(); { + case isKill(o): + s.Total++ s.Killed++ - } else { + case isSurvivor(o): + s.Total++ s.Survived++ + case o == lang.OutcomeNotRun: + s.NotRun++ } } @@ -122,3 +130,15 @@ func computeTierStats(mutants []Mutant) []TierStats { } return out } + +// gatingThreshold returns the kill-rate threshold a tier is gated on, and +// whether it is gated at all. Tier 3 is report-only. +func gatingThreshold(t Tier, opts Options) (float64, bool) { + switch t { + case TierLogic: + return opts.tier1Threshold(), true + case TierSemantic: + return opts.tier2Threshold(), true + } + return 0, false +} diff --git a/internal/mutation/tiers_test.go b/internal/mutation/tiers_test.go index a91bd0f..b85c667 100644 --- a/internal/mutation/tiers_test.go +++ b/internal/mutation/tiers_test.go @@ -187,7 +187,7 @@ func TestBuildSection_TierSummaryIncluded(t *testing.T) { {Operator: "negate_conditional", Killed: true}, {Operator: "boolean_substitution", Killed: false, Description: "true -> false"}, } - s := buildSection(mutants, 1, Options{}) + s := buildSection(mutants, Options{}) // Summary should include both the overall score and per-tier breakdowns. for _, want := range []string{"Score:", "T1 logic:", "T2 semantic:"} {