{"modulePath":"github.com/CommitBrief/commitbrief","version":"v1.23.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package flaky\n\nPackage 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.\n\n## Functions\n\n```go\nfunc Annotate(cat *i18n.Catalog, f render.Finding, r RerunResult) render.Finding\n```\nAnnotate 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:\n\n  - flaky        → keep the finding; the rerun upgrades it from \"suspected\" to \"confirmed\" (text only; severity unchanged).\n  - 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.\n  - 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.\n  - inconclusive → returned unchanged (no rerun was observed).\n\nAnnotate 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).\n\n```go\nfunc EnclosingTest(path string, line int) (string, bool)\n```\nEnclosingTest 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.\n\nGo 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.\n\nThis 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.\n\nIt 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.\n\nReturns 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).\n\nThe \\_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.\n\nRound 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.\n\n## Types\n\n```go\ntype Detector struct {\n\t// contains filtered or unexported fields\n}\n```\nDetector 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.\n\n```go\nfunc New(cat *i18n.Catalog) *Detector\n```\nNew returns a Detector that localizes finding text via cat.\n\n```go\nfunc (d *Detector) Detect(parsed diff.Diff) []render.Finding\n```\nDetect 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.\n\n```go\ntype Executor func(ctx context.Context, t Target) (passed bool, err error)\n```\nExecutor 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.\n\nImplementations must be safe to call repeatedly for the same Target — each call is one independent rerun.\n\n```go\ntype RerunResult struct {\n\t// Verdict is the empirical classification (see the Verdict constants).\n\tVerdict Verdict\n\t// Passes and Fails are the observed counts across the reruns that\n\t// produced a result. Errored attempts (Executor returned a non-nil error)\n\t// are counted in neither — they are tallied in Errors instead.\n\tPasses int\n\tFails  int\n\t// Errors is the number of attempts that could not be observed (Executor\n\t// returned an error). A campaign that errors on every attempt is\n\t// Inconclusive.\n\tErrors int\n\t// Runs is the number of attempts actually made. With early exit it can be\n\t// fewer than the requested N (we stop as soon as a mixed pass+fail proves\n\t// flakiness), so callers can report \"confirmed after k of N runs\".\n\tRuns int\n}\n```\nRerunResult is the outcome of a sandbox rerun campaign for one test.\n\n```go\nfunc Rerun(ctx context.Context, exec Executor, t Target, runs int) RerunResult\n```\nRerun 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.\n\nContract:\n\n  - mixed pass+fail  → VerdictFlaky (confirmed)\n  - all observed fail → VerdictRealFailure (genuine red — do not quarantine)\n  - all observed pass → VerdictTransient (did not reproduce)\n  - nothing observed  → VerdictInconclusive\n\nEarly 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.\n\nruns \\\u003c= 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.\n\n```go\nfunc (r RerunResult) Confirmed() bool\n```\nConfirmed 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).\n\n```go\ntype Target struct {\n\tFile string // repo-relative, slash-normalized\n\tLine int\n\tTest string\n}\n```\nTarget 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.\n\n```go\ntype Verdict string\n```\nVerdict 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.\n\n```go\nconst (\n\t// VerdictFlaky means the reruns produced BOTH a pass and a fail: the test\n\t// is non-deterministic under identical conditions — confirmed flaky.\n\tVerdictFlaky Verdict = \"flaky\"\n\t// VerdictRealFailure means every rerun failed: the test fails\n\t// deterministically, so it is a genuine failure, not flakiness. Such a\n\t// test must NOT be quarantined as flaky — it is correctly red.\n\tVerdictRealFailure Verdict = \"real_failure\"\n\t// VerdictTransient means every rerun passed: the original signal did not\n\t// reproduce. The flake (if any) was a one-off / already resolved.\n\tVerdictTransient Verdict = \"transient\"\n\t// VerdictInconclusive means no rerun was observed (runs \u003c= 0, or every\n\t// attempt errored before yielding a result), so no classification can be\n\t// made. The caller should fall back to the static finding alone.\n\tVerdictInconclusive Verdict = \"inconclusive\"\n)\n```\n\n","path":"github.com/CommitBrief/commitbrief/internal/flaky","name":"flaky","synopsis":"Package flaky is CommitBrief's deterministic, static flaky-test anti-pattern detector (ADR-0022).","isRedistributable":true}
