flaky

package
v1.21.2 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: GPL-3.0 Imports: 15 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package flaky is CommitBrief's deterministic, static flaky-test anti-pattern detector (ADR-0022). Unlike the LLM review path it produces reproducible findings from the diff alone: it scans the added lines of changed test files for high-precision anti-patterns (hard-coded sleeps, unseeded randomness, …) and emits standard render.Finding values — no JSON-schema change, no provider call. Recall is intentionally secondary to precision: a noisy commit-stage gate erodes trust.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Annotate added in v1.12.0

func Annotate(cat *i18n.Catalog, f render.Finding, r RerunResult) render.Finding

Annotate folds a rerun verdict into an existing static flaky finding without touching the JSON schema (locked at v1, ADR-0014): the localized verdict line is appended to the finding's Suggestion, and the finding's Severity is adjusted to reflect empirical truth:

  • flaky → keep the finding; the rerun upgrades it from "suspected" to "confirmed" (text only; severity unchanged).
  • real_failure → this is a genuinely red test, not flakiness; the static anti-pattern note still applies but must not masquerade as a flake, so the verdict line says so plainly.
  • transient → the flake did not reproduce; downgraded to info so a one-off does not block a commit-stage gate, with a line saying it passed every rerun.
  • inconclusive → returned unchanged (no rerun was observed).

Annotate never drops a finding — the static signal is preserved either way; the rerun only refines how it is presented. cat localizes the verdict line to the resolved output language (ADR-0021).

func EnclosingTest added in v1.14.0

func EnclosingTest(path string, line int) (string, bool)

EnclosingTest resolves the name of the Go test function containing line (1-indexed) in the file at path, by parsing the file with go/parser and walking its declarations for the *ast.FuncDecl whose position range contains line.

Go only (round 3 of ADR-0033 §8/§10's helper). Resolving every language required a hand-rolled, multi-language regex-and-scan implementation that went through three rounds of distinct lexical bugs -- ASCII-only identifier classes, braces inside string/comment spans, an unescaped backtick in a JS template literal -- each fix correct and each followed by another, with no evidence of convergence: a slow-motion reimplementation of a lexer, one edge case at a time. go/parser is the real Go compiler frontend, so strings, comments, raw literals, escapes, and Unicode identifiers are all handled exactly, by construction, not approximated.

This is a deliberate, approved reduction in scope for every other language, not a regression: EnclosingTest now always returns ("", false) for non-Go files. Non-Go test files keep full static flaky detection (internal/flaky's rule-based Detector, unaffected by this file); they simply never get sandbox-rerun confirmation, which is exactly the fallback ADR-0033 §10 already specifies for an unresolved name -- skip the rerun for that finding, keep the bare static finding, unannotated.

It reads the WORKING TREE, not the staged snapshot (ADR-0033 §8): the command a caller binds will run against the worktree too, so resolving against the same bytes keeps the name and the execution consistent.

Returns ok=false — never a guess — when the file cannot be read, is not a Go *_test.go file, fails to parse, line falls outside every function's body, or falls inside a function that is not one `go test -run '^NAME$'` can actually select and re-execute on its own (see isRerunnableTestFunc). A wrong name would run the wrong test and yield a confident, wrong verdict, which is worse than no verdict (ADR-0033 §10).

The _test.go suffix check (round 4) matters beyond the obvious: `go test` only ever compiles *_test.go files into the test binary, so a Test-shaped function resolved from any other .go file renders a `-run` pattern that matches zero tests -- exit 0, a false VerdictTransient, the same failure chain ADR-0033 §10 exists to prevent. This is reachable, not theoretical: flaky.isTestFile's directory-based rule (any "tests/", "test/", "spec/", "e2e/", "cypress/", "__tests__/" path segment) lets the static detector scan an ordinary, non-_test.go Go file and hand this function exactly that path.

Round 5: the suffix check validates the *file name*, not whether the toolchain actually *compiles* the file. go/parser applies no build constraints at all, so a `//go:build integration` file, a GOOS/GOARCH filename suffix that doesn't match the host, or an underscore/dot-prefixed file all still parse cleanly and can still yield a real-looking test name -- and then, exactly like round 4's non-_test.go case, `-run '^NAME$'` matches zero tests in the actual `go test` invocation: exit 0, a false VerdictTransient, the same lie ADR-0033 §10 exists to prevent. Build-tagged integration tests are exactly where hard-coded sleeps live, so this is a likely input, not an exotic one. go/build's own build.Default.MatchFile answers "would the toolchain actually compile this file" without reimplementing any of that logic. It does NOT, however, know about testdata/ -- the go tool excludes testdata by skipping the whole directory during package discovery, not by rejecting individual files within it, so MatchFile alone reports true for a file living under a testdata/ segment. That gap is closed by a separate, explicit path check.

Types

type Detector

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

Detector turns a parsed diff into deterministic flaky-test findings. The catalog localizes finding text to the resolved output language (ADR-0021); the Severity value stays the English wire vocabulary, as for LLM findings.

func New

func New(cat *i18n.Catalog) *Detector

New returns a Detector that localizes finding text via cat.

func (*Detector) Detect

func (d *Detector) Detect(parsed diff.Diff) []render.Finding

Detect scans the added lines of every changed test file in parsed and returns the matched anti-patterns as findings. The returned slice is non-nil only when there are findings; order follows file → hunk → line.

type Executor added in v1.12.0

type Executor func(ctx context.Context, t Target) (passed bool, err error)

Executor runs a single, already-isolated test once and reports whether it passed. The error channel is reserved for harness failures that are NOT a test result — the runner could not be launched, the context was cancelled, the test binary did not compile. A test that runs and fails its assertions is `passed == false, err == nil`; only an inability to OBSERVE a result is an error. t is opaque to the orchestrator: it is whatever handle the caller's runner understands.

Implementations must be safe to call repeatedly for the same Target — each call is one independent rerun.

type RerunResult added in v1.12.0

type RerunResult struct {
	// Verdict is the empirical classification (see the Verdict constants).
	Verdict Verdict
	// Passes and Fails are the observed counts across the reruns that
	// produced a result. Errored attempts (Executor returned a non-nil error)
	// are counted in neither — they are tallied in Errors instead.
	Passes int
	Fails  int
	// Errors is the number of attempts that could not be observed (Executor
	// returned an error). A campaign that errors on every attempt is
	// Inconclusive.
	Errors int
	// Runs is the number of attempts actually made. With early exit it can be
	// fewer than the requested N (we stop as soon as a mixed pass+fail proves
	// flakiness), so callers can report "confirmed after k of N runs".
	Runs int
}

RerunResult is the outcome of a sandbox rerun campaign for one test.

func Rerun added in v1.12.0

func Rerun(ctx context.Context, exec Executor, t Target, runs int) RerunResult

Rerun re-runs a single flagged test up to runs times via exec and classifies the result. It is a pure function of exec's behaviour: given the same exec it returns the same verdict, so it is trivially testable with a fake.

Contract:

  • mixed pass+fail → VerdictFlaky (confirmed)
  • all observed fail → VerdictRealFailure (genuine red — do not quarantine)
  • all observed pass → VerdictTransient (did not reproduce)
  • nothing observed → VerdictInconclusive

Early exit: as soon as BOTH a pass and a fail have been seen the verdict can no longer change (flaky is terminal), so Rerun stops and returns without burning the remaining attempts. Errored attempts never short-circuit the loop — a flickering runner should not be mistaken for a flaky test — but they are recorded so a wholly-unobservable campaign is reported honestly.

runs <= 0 yields an Inconclusive result with no calls to exec. A nil exec is treated the same way (defensive: the seam is unbound), so the orchestrator is safe to call even when the caller never bound a runner.

func (RerunResult) Confirmed added in v1.12.0

func (r RerunResult) Confirmed() bool

Confirmed reports whether the rerun empirically confirmed flakiness. It is the predicate a caller uses to decide whether to keep treating the candidate as flaky after the rerun (true) or to step back from the static finding (a real failure or a non-reproducing transient).

type Target added in v1.14.0

type Target struct {
	File string // repo-relative, slash-normalized
	Line int
	Test string
}

Target identifies the single test a rerun campaign re-runs. It is a struct rather than an opaque id because a caller-bound runner needs the parts addressable: a configured command template renders {{.File}}, {{.Line}}, and {{.Test}} into its argv. Test is the enclosing test function name and is "" when it could not be resolved — a runner that needs it must check.

type Verdict added in v1.12.0

type Verdict string

Verdict is the empirical classification produced by re-running a flagged test in isolation. It is intentionally a small closed vocabulary so the rendered/​localized text and any future machine surface stay stable.

const (
	// VerdictFlaky means the reruns produced BOTH a pass and a fail: the test
	// is non-deterministic under identical conditions — confirmed flaky.
	VerdictFlaky Verdict = "flaky"
	// VerdictRealFailure means every rerun failed: the test fails
	// deterministically, so it is a genuine failure, not flakiness. Such a
	// test must NOT be quarantined as flaky — it is correctly red.
	VerdictRealFailure Verdict = "real_failure"
	// VerdictTransient means every rerun passed: the original signal did not
	// reproduce. The flake (if any) was a one-off / already resolved.
	VerdictTransient Verdict = "transient"
	// VerdictInconclusive means no rerun was observed (runs <= 0, or every
	// attempt errored before yielding a result), so no classification can be
	// made. The caller should fall back to the static finding alone.
	VerdictInconclusive Verdict = "inconclusive"
)

Jump to

Keyboard shortcuts

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