From 8bcc919dcfb2bd656264512869527eb84e2aea91 Mon Sep 17 00:00:00 2001 From: Tom Proctor Date: Tue, 24 Nov 2026 18:33:45 +0000 Subject: [PATCH] cmd/testwrapper: ensure unfinished tests always trigger failure (#22622) When packages timed out or panicked, we sometimes marked CI green despite not running all the tests for that package, and the tests that started but didn't finish got marked as flaky even though they were not known to be at fault. For example, all 133 recorded flakes of ipnlocal.TestNewExtensionHost were really an ipnlocal watchdog panic or a package timeout on Windows, and 129 of those jobs passed. Parse the test binary's terminal log line, and check for tests that started but never finished. If either shows that the test binary didn't complete, don't retry any of the package's tests, and fail the run. The log line check also catches a panic in a test's own goroutine, which the testing package reports as a normal test failure even though the tests after it never start. While here, fix some related problems: - A package that fails with no failed test (e.g. TestMain exits non-zero) is now fatal even if another package in the same go test invocation has a failed test to retry. Previously the check counted the failed tests of the whole batch, not of the package. - If a test passes on retry but go test still fails (e.g. TestMain exits non-zero after the tests run), fail the run. Previously we only logged the error and exited 0. - A data race now drops only the retries of its own package, not of every package in the batch. - If go test fails with nothing to retry, don't exit straight away; still retry other batches' failures and write the GitHub step summaries, then exit with go test's exit code. The results summary now shows unfinished tests as failed instead of passed. Updates tailscale/corp#52113 Signed-off-by: Tom Proctor --- cmd/testwrapper/multipkg_test.go | 251 +++++++++++++++++++++++++++++++ cmd/testwrapper/testwrapper.go | 119 ++++++++++----- 2 files changed, 331 insertions(+), 39 deletions(-) diff --git a/cmd/testwrapper/multipkg_test.go b/cmd/testwrapper/multipkg_test.go index defe6e65b..b17e66668 100644 --- a/cmd/testwrapper/multipkg_test.go +++ b/cmd/testwrapper/multipkg_test.go @@ -207,3 +207,254 @@ func TestMultiFile(t *testing.T) { t.Errorf("unexpected permanent failures:\n%s", out) } } + +// hangSrc is a package that times out on the first attempt only. When the +// timeout occurs, TestFails has failed, TestParallel is paused, TestHang +// runs, and TestNotStarted has not started. +const hangSrc = `package hang_test + +import ( + "os" + "testing" + "time" +) + +func TestParallel(t *testing.T) { t.Parallel() } + +func TestFails(t *testing.T) { + if os.Getenv("TS_TESTWRAPPER_ATTEMPT") == "1" { + t.Fatal("failing on the first attempt only") + } +} + +func TestHang(t *testing.T) { + if os.Getenv("TS_TESTWRAPPER_ATTEMPT") == "1" { + time.Sleep(time.Hour) + } +} + +func TestNotStarted(t *testing.T) {} +` + +// TestPackageTimeoutNotRetried covers a package that times out: the wrapper +// must exit non-zero and must not retry any of its tests, or report them as +// flaky, because the tests that did not start never ran. Tests in other +// packages are still retried. +func TestPackageTimeoutNotRetried(t *testing.T) { + t.Parallel() + + dir := multiPkgDir(t) + hangPkg := writePkg(t, dir, "hang", hangSrc) + flakyPkg := writePkg(t, dir, "flaky", flakySrc) + + out, err := cmdTestwrapper(t, hangPkg, flakyPkg, "-timeout=5s").CombinedOutput() + if code, ok := errExitCode(err); !ok || code != 1 { + t.Fatalf("got exit code %d, want 1 (err: %v) with output:\n%s", code, err, out) + } + for _, want := range []string{ + "panic: test timed out after 5s", + "testwrapper: " + importPath(hangPkg) + " did not complete; not retrying its tests (unfinished: TestHang TestParallel)\n", + "[retry 1] " + importPath(flakyPkg) + ".TestFlaky: PASS", + } { + if !bytes.Contains(out, []byte(want)) { + t.Errorf("output lacks %q:\n%s", want, out) + } + } + if bytes.Contains(out, []byte("[retry 1] "+importPath(hangPkg))) { + t.Errorf("tests of the package that did not complete were retried:\n%s", out) + } + flakyLine, permLine := jsonLines(out) + if strings.Contains(flakyLine, importPath(hangPkg)) || strings.Contains(permLine, importPath(hangPkg)) { + t.Errorf("tests of the package that did not complete are in the failures JSON:\nflaky: %s\npermanent: %s", flakyLine, permLine) + } + if !strings.Contains(flakyLine, "TestFlaky") { + t.Errorf("flaky failures JSON %q should name TestFlaky", flakyLine) + } +} + +// TestPackagePanicNotRetried covers a package that a panic stops. The +// wrapper must exit non-zero and must not retry the tests of the package, +// because some of its tests did not start. +func TestPackagePanicNotRetried(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + src string + want string + }{ + { + // The panicking test and the paused parallel test have no result. + name: "background-goroutine", + src: `package bgpanic_test + +import ( + "os" + "testing" +) + +func TestParallel(t *testing.T) { t.Parallel() } + +func TestPanic(t *testing.T) { + if os.Getenv("TS_TESTWRAPPER_ATTEMPT") == "1" { + go func() { panic("background goroutine panic") }() + select {} + } +} +`, + want: "did not complete; not retrying its tests (unfinished: TestPanic TestParallel)\n", + }, + { + // The testing package reports the panicking test as failed. No + // other test is in progress, but TestNotStarted never runs. + name: "test-goroutine", + src: `package testpanic_test + +import ( + "os" + "testing" +) + +func TestPanic(t *testing.T) { + if os.Getenv("TS_TESTWRAPPER_ATTEMPT") == "1" { + panic("test goroutine panic") + } +} + +func TestNotStarted(t *testing.T) {} +`, + want: "did not complete; not retrying its tests\n", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + pkg := writePkg(t, multiPkgDir(t), "panicpkg", tt.src) + out, err := cmdTestwrapper(t, pkg).CombinedOutput() + if code, ok := errExitCode(err); !ok || code != 1 { + t.Fatalf("got exit code %d, want 1 (err: %v) with output:\n%s", code, err, out) + } + if !bytes.Contains(out, []byte(tt.want)) { + t.Errorf("output lacks %q:\n%s", tt.want, out) + } + if bytes.Contains(out, []byte("[retry ")) { + t.Errorf("tests of the package that did not complete were retried:\n%s", out) + } + }) + } +} + +// TestPackageTimeoutResultsSummary covers the results summary when the only +// failure is a package that times out: the summary must be written, and +// must show the unfinished test as failed. +func TestPackageTimeoutResultsSummary(t *testing.T) { + t.Parallel() + + pkg := writePkg(t, multiPkgDir(t), "hang", hangSrc) + summaryPath := filepath.Join(t.TempDir(), "summary.md") + cmd := cmdTestwrapper(t, pkg, "-timeout=5s") + cmd.Env = append(cmd.Env, + "GITHUB_STEP_SUMMARY="+summaryPath, + "TS_TESTWRAPPER_RESULTS_SUMMARY=1", + ) + out, err := cmd.CombinedOutput() + if code, ok := errExitCode(err); !ok || code != 1 { + t.Fatalf("got exit code %d, want 1 (err: %v) with output:\n%s", code, err, out) + } + summary, err := os.ReadFile(summaryPath) + if err != nil { + t.Fatalf("reading summary: %v\noutput:\n%s", err, out) + } + for _, want := range []string{ + "_No flaky tests detected._", + "| ❌ | `TestHang` |", + "| ❌ | `TestParallel` |", + "| ❌ | `TestFails` |", + "results may be partial", + } { + if !bytes.Contains(summary, []byte(want)) { + t.Errorf("summary lacks %q:\n%s", want, summary) + } + } +} + +// TestPackageFailureNotHiddenByFlake covers a package that fails with no +// failed test (here TestMain exits non-zero) in the same go test invocation +// as a flaky test in another package. The flaky test in the other package +// must not hide the package failure. +func TestPackageFailureNotHiddenByFlake(t *testing.T) { + t.Parallel() + + dir := multiPkgDir(t) + flakyPkg := writePkg(t, dir, "flaky", flakySrc) + exitPkg := writePkg(t, dir, "mainexit", `package mainexit_test + +import ( + "os" + "testing" +) + +func TestMain(m *testing.M) { + m.Run() + os.Exit(1) +} + +func TestPass(t *testing.T) {} +`) + + // go test prints package results in command-line order, so the wrapper + // sees the failure of the flaky package before the failure of the other + // package. + out, err := cmdTestwrapper(t, flakyPkg, exitPkg).CombinedOutput() + if code, ok := errExitCode(err); !ok || code != 1 { + t.Fatalf("got exit code %d, want 1 (err: %v) with output:\n%s", code, err, out) + } + for _, want := range []string{ + "FAIL\t" + importPath(exitPkg), + "[retry 1] " + importPath(flakyPkg) + ".TestFlaky: PASS", + } { + if !bytes.Contains(out, []byte(want)) { + t.Errorf("output lacks %q:\n%s", want, out) + } + } +} + +// TestPackageFailureNotHiddenByRetry covers a package that fails after its +// tests run (here TestMain exits non-zero) and also has a flaky test. The +// flaky test passes on retry, but go test still fails, so the wrapper must +// exit non-zero. +func TestPackageFailureNotHiddenByRetry(t *testing.T) { + t.Parallel() + + pkg := writePkg(t, multiPkgDir(t), "mainexit", `package mainexit_test + +import ( + "os" + "testing" +) + +func TestMain(m *testing.M) { + m.Run() + os.Exit(1) +} + +func TestFlaky(t *testing.T) { + if os.Getenv("TS_TESTWRAPPER_ATTEMPT") == "1" { + t.Fatal("failing on the first attempt so the wrapper retries") + } +} +`) + + out, err := cmdTestwrapper(t, pkg).CombinedOutput() + if code, ok := errExitCode(err); !ok || code != 1 { + t.Fatalf("got exit code %d, want 1 (err: %v) with output:\n%s", code, err, out) + } + for _, want := range []string{ + "[retry 1] " + importPath(pkg) + ".TestFlaky: PASS", + "testwrapper: " + importPath(pkg) + ".TestFlaky passed on retry, but go test failed; failing the run", + } { + if !bytes.Contains(out, []byte(want)) { + t.Errorf("output lacks %q:\n%s", want, out) + } + } +} diff --git a/cmd/testwrapper/testwrapper.go b/cmd/testwrapper/testwrapper.go index e4ea4454e..5ae244f4a 100644 --- a/cmd/testwrapper/testwrapper.go +++ b/cmd/testwrapper/testwrapper.go @@ -9,6 +9,11 @@ // fails and then later passes is reported as flaky. A test that never passes // within the budget is a real failure and causes a non-zero exit. // +// If a package's test binary doesn't complete (for example because of a +// timeout, a panic, or a call to os.Exit), testwrapper won't retry any of its +// tests and exits non-zero; we may not have seen every test start, and so we +// can't reliably know the full set of tests that need re-running. +// // The flakytest package's Mark API is no longer required for retries — it is // kept for explicit issue tracking and for the TS_SKIP_FLAKY_TESTS skip // behavior. @@ -150,7 +155,17 @@ type testAttempt struct { // test in the package -- or the package's own output -- did. raceDetected bool + // pkgFinished is set on the final event for a package, which go test + // sends when the package ends for any reason (pass, fail, skip, or build + // failure). Such an event is about the package, not about one test. It + // does not mean that the test binary ran all of its tests; see + // binaryFinished for that. pkgFinished bool + // binaryFinished is set on a pkgFinished event if the test binary printed + // the PASS or FAIL line that testing.M.Run prints after all tests run. + // If it is not set, the binary stopped early (for example, because of a + // panic or a timeout) and some tests possibly did not start. + binaryFinished bool } // failedTest tracks per-test state across the retry phase. @@ -162,7 +177,10 @@ type failedTest struct { attempts int // number of retry attempts run so far totalRetryElapsed time.Duration // total time spent across retry attempts everPassed bool // a retry attempt passed - inferredFail bool // the first failure was assumed, not reported by `go test` + // binaryFailed is set if a retry attempt passed but go test failed (for + // example, TestMain exited non-zero after the tests ran). That is a + // package failure, which a retry can't clear. + binaryFailed bool } // packageTests describes what to run. @@ -434,14 +452,15 @@ func runTests(ctx context.Context, attempt int, patterns []string, goTestArgs, t } } ch <- &testAttempt{ - pkg: goOutput.Package, - outcome: outcome, - start: pkgTests[""].start, - end: goOutput.Time, - logs: pkgTests[""].logs, - pkgFinished: true, - cached: pkgCached[goOutput.Package], - raceDetected: raceDetected, + pkg: goOutput.Package, + outcome: outcome, + start: pkgTests[""].start, + end: goOutput.Time, + logs: pkgTests[""].logs, + pkgFinished: true, + binaryFinished: pkgTests[""].binaryFinished, + cached: pkgCached[goOutput.Package], + raceDetected: raceDetected, } case "output": // Capture all output from the package except for the final @@ -449,8 +468,11 @@ func runTests(ctx context.Context, attempt int, patterns []string, goTestArgs, t // printPkgOutcome will output a similar line if !strings.HasPrefix(goOutput.Output, fmt.Sprintf("FAIL\t%s\t", goOutput.Package)) { pkgTests[""].logs.WriteString(goOutput.Output) - if goOutput.Output == raceDetectorMarkerLine { + switch goOutput.Output { + case raceDetectorMarkerLine: pkgTests[""].raceDetected = true + case "PASS\n", "FAIL\n": + pkgTests[""].binaryFinished = true } } } @@ -733,6 +755,7 @@ func retryFailedTest(ctx context.Context, ft *failedTest, goTestArgs, testArgs [ } if outcome == outcomePass { ft.everPassed = true + ft.binaryFailed = err != nil } } } @@ -993,7 +1016,8 @@ func main() { } } var failed []*failedTest - var pkgFatal bool // a package produced a non-test fatal (build error, etc.) + var pkgFatal bool // a package produced a non-test fatal (build error, etc.) + var goTestExitCode int // exit code of a go test that failed with no retryable tests resultsSummary := os.Getenv("TS_TESTWRAPPER_RESULTS_SUMMARY") != "" allResults := map[string]testOutcome{} @@ -1005,10 +1029,11 @@ func main() { runErrCh <- runTests(ctx, 1, patterns, goTestArgs, testArgs, ch) }() - // Collect failed tests in this batch on the side; we use the count - // when a package reports a fail to decide if the failure is explained - // by retryable test failures or is a separate package-level fatal. + // Collect failed tests in this batch on the side. When a package + // finishes, we use them to decide if a failure is explained by + // retryable test failures or is a separate package-level fatal. var pkgFailedTests []*failedTest + unfinished := map[string][]string{} // pkg -> tests that started but did not finish for tr := range ch { // Go assigns the package name "command-line-arguments" when you // `go test FILE` rather than `go test PKG`. It's more @@ -1020,31 +1045,47 @@ func main() { tr.pkg = patterns[0] } if tr.pkgFinished { - if tr.raceDetected { - // A data race is never something we want to paper - // over by retrying flaky tests in the package: the - // race indicates a real bug that may not even be - // in the failing test, and a retry could hide it. - // Drop any retry plans for this pkg and fail fast. - pkgFailedTests = nil - pkgFatal = true - } if testingVerbose || tr.outcome == outcomeFail { io.Copy(os.Stdout, &tr.logs) } - if tr.outcome == outcomeFail && len(pkgFailedTests) == 0 { - // Package failed but no test failed (e.g. the package - // timed out, or a build error). Not retryable per-test. + inPkg := func(ft *failedTest) bool { return ft.pkg == tr.pkg } + hasFailedTests := slices.ContainsFunc(pkgFailedTests, inPkg) + // Only a failed package needs to check binaryFinished. A + // package can pass or skip without the binary's final PASS + // line, for example if it has no test files. + incomplete := len(unfinished[tr.pkg]) > 0 || tr.outcome == outcomeFail && !tr.binaryFinished + if incomplete && (hasFailedTests || len(unfinished[tr.pkg]) > 0) { + msg := fmt.Sprintf("testwrapper: %s did not complete; not retrying its tests", tr.pkg) + if u := unfinished[tr.pkg]; len(u) > 0 { + slices.Sort(u) + msg += " (unfinished: " + strings.Join(u, " ") + ")" + } + log.Print(msg) + } + // Retries of single tests can't clear: + // - a data race: it is a real bug that may not even be in + // the failing test, and a retry could hide it. + // - a binary that did not complete (e.g. a timeout, a panic, + // or os.Exit): some tests possibly did not start. + // - a package failure that no failed test explains (e.g. a + // build error, or TestMain exited non-zero). + if tr.raceDetected || incomplete || tr.outcome == outcomeFail && !hasFailedTests { + pkgFailedTests = slices.DeleteFunc(pkgFailedTests, inPkg) pkgFatal = true } printPkgOutcome(tr.pkg, tr.outcome, tr.cached, tr.end.Sub(tr.start)) continue } + if testingVerbose || tr.outcome == outcomeFail { + io.Copy(os.Stdout, &tr.logs) + } if resultsSummary && tr.testName != "" { allResults[tr.pkg+"\t"+tr.testName] = tr.outcome } - if testingVerbose || tr.outcome == outcomeFail { - io.Copy(os.Stdout, &tr.logs) + if tr.inferredFail { + // The test did not finish, so it has no result. + unfinished[tr.pkg] = append(unfinished[tr.pkg], tr.testName) + continue } if tr.outcome != outcomeFail { continue @@ -1054,7 +1095,6 @@ func main() { testName: tr.testName, firstFailDuration: tr.end.Sub(tr.start), issueURL: tr.issueURL, // real if Mark()'d, else "". - inferredFail: tr.inferredFail, }) } failed = append(failed, pkgFailedTests...) @@ -1064,8 +1104,11 @@ func main() { if exit, ok := errors.AsType[*exec.ExitError](err); ok && exit.ExitCode() > -1 { if len(pkgFailedTests) == 0 { // Pure exec failure with no test-level failures to retry: - // honor the original exit code. - os.Exit(exit.ExitCode()) + // honor the original exit code. Don't exit yet, so that + // we still retry other batches' failures and write the + // summaries. + goTestExitCode = exit.ExitCode() + pkgFatal = true } } else { log.Printf("testwrapper: %s", err) @@ -1086,6 +1129,10 @@ func main() { // Summarize and exit. var flaky, permanent []*failedTest for _, ft := range failed { + if ft.binaryFailed { + log.Printf("testwrapper: %s.%s passed on retry, but go test failed; failing the run", ft.pkg, ft.testName) + pkgFatal = true + } if ft.everPassed { flaky = append(flaky, ft) } else { @@ -1101,13 +1148,7 @@ func main() { if resultsSummary { retried := map[string]bool{} for _, ft := range flaky { - key := ft.pkg + "\t" + ft.testName - if ft.inferredFail { - // It never failed on its own, so it isn't a flake. - allResults[key] = outcomePass - continue - } - retried[key] = true + retried[ft.pkg+"\t"+ft.testName] = true } writeResultsSummary(path, os.Getenv("TS_TESTWRAPPER_RESULTS_JSON"), os.Getenv("TS_TESTWRAPPER_RESULTS_PKG"), allResults, retried, pkgFatal) } @@ -1118,6 +1159,6 @@ func main() { } if pkgFatal || len(permanent) > 0 { - os.Exit(1) + os.Exit(cmp.Or(goTestExitCode, 1)) } }