Files
tailscale/cmd/testwrapper/testwrapper.go
T
Tom Proctor 8bcc919dcf 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 <[email protected]>
2026-11-24 18:33:45 +00:00

1165 lines
38 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// testwrapper is a wrapper for go test that automatically retries failing
// tests to detect flakiness.
//
// Any failed test is treated as potentially flaky and re-run within a per-test
// time budget (see the perAttempt* and perTestBudget constants). A test that
// 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.
package main
import (
"bufio"
"bytes"
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"time"
"tailscale.com/cmd/testwrapper/flakytest"
)
// Per-test retry policy. See package doc comment.
const (
// perAttemptCap is the upper bound on the per-retry-attempt -timeout we set
// when running a single failed test.
perAttemptCap = 5 * time.Minute
// perAttemptFloor is the lower bound on the per-retry-attempt -timeout, to
// give the test binary time to start.
perAttemptFloor = 30 * time.Second
// maxRetries caps the number of retry attempts for a single test. It
// guards against re-running a very fast test thousands of times within
// perTestBudget.
maxRetries = 10
// raceDetectorMarkerLine is the first line of every Go race
// detector report, emitted at column 0. We look for it as a
// whole line (not as a substring) so that we don't false-fire
// on tests that legitimately print the same text indented in
// their own logs — for example, this package's own race tests,
// which exec a child testwrapper and dump its captured output.
raceDetectorMarkerLine = "WARNING: DATA RACE\n"
// defaultGoTestTimeout is go test's default -timeout.
defaultGoTestTimeout = 10 * time.Minute
// goToolTimeout bounds go commands other than tests, such as "go list".
goToolTimeout = 10 * time.Minute
// retryBuildSlack is extra time allowed beyond a retry attempt's -timeout
// for go test to rebuild the test binary.
retryBuildSlack = 5 * time.Minute
// waitDelay is how long to wait for a killed go command's I/O to finish.
waitDelay = 10 * time.Second
)
// Tunables for the per-test retry budget. These default to production values
// but can be overridden via env vars, primarily for tests of testwrapper
// itself.
var (
// perTestBudget is the total wall-clock time we are willing to spend
// retrying a single test before giving up. Override via
// TS_TESTWRAPPER_BUDGET (a time.Duration string).
perTestBudget = envDuration("TS_TESTWRAPPER_BUDGET", 10*time.Minute)
// minRetries is the minimum number of retry attempts we make for a failed
// test, regardless of perTestBudget. Override via TS_TESTWRAPPER_MIN_RETRIES.
minRetries = envInt("TS_TESTWRAPPER_MIN_RETRIES", 2)
// maxRetryTime is the maximum wall-clock time we are willing to spend on the
// whole retry phase. It ensures a run with many flakes or real failures
// doesn't block for an unreasonable amount of time. Override via
// TS_TESTWRAPPER_MAX_RETRY_TIME (a time.Duration string).
maxRetryTime = envDuration("TS_TESTWRAPPER_MAX_RETRY_TIME", 10*time.Minute)
// idleMargin is how much longer than the go test -timeout we wait for
// any output from go test before deciding it's hung. The -timeout only
// bounds running test binaries, not compiling and linking them.
// Override via TS_TESTWRAPPER_IDLE_MARGIN (a time.Duration string).
idleMargin = envDuration("TS_TESTWRAPPER_IDLE_MARGIN", 5*time.Minute)
)
func envDuration(key string, def time.Duration) time.Duration {
s := os.Getenv(key)
if s == "" {
return def
}
d, err := time.ParseDuration(s)
if err != nil {
log.Panicf("invalid %s=%q: %v", key, s, err)
}
return d
}
func envInt(key string, def int) int {
s := os.Getenv(key)
if s == "" {
return def
}
n, err := strconv.Atoi(s)
if err != nil {
log.Panicf("invalid %s=%q: %v", key, s, err)
}
return n
}
// flakeUnknownIssueSlug is the trailing path of the fake GitHub issue URL we
// record for tests that turned out flaky but were not explicitly marked with
// flakytest.Mark. flakeapp records this as a flake occurrence with no real
// issue.
const flakeUnknownIssueSlug = "/issues/UNKNOWN"
// testOutcome is the outcome of a single test (or package) run. Its string
// values match the Action field in `go test -json` output.
type testOutcome string
const (
outcomeUnknown testOutcome = ""
outcomePass testOutcome = "pass"
outcomeFail testOutcome = "fail"
outcomeSkip testOutcome = "skip"
)
type testAttempt struct {
pkg string // "tailscale.com/types/key"
testName string // "TestFoo"
outcome testOutcome // outcomePass, outcomeFail, outcomeSkip, or outcomeUnknown
cached bool // whether package-level (non-testName specific) was pass due to being cached
logs bytes.Buffer
start, end time.Time
isMarkedFlaky bool // set if the test is marked as flaky
issueURL string // set if the test is marked as flaky
inferredFail bool // outcome assumed because the package died, not reported by `go test`
// raceDetected is true on a per-test event if that test's output
// contained a race report, and true on a pkgFinished event if any
// 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.
type failedTest struct {
pkg, testName string
firstFailDuration time.Duration
issueURL string // non-empty iff the test called flakytest.Mark
attempts int // number of retry attempts run so far
totalRetryElapsed time.Duration // total time spent across retry attempts
everPassed bool // a retry attempt passed
// 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.
// It's also JSON-marshalled to output for analysis tools to parse,
// so the fields are all exported.
// TODO(bradfitz): move this type to its own types package?
type packageTests struct {
// Pattern is the package Pattern to run.
// Must be a single Pattern, not a list of patterns.
Pattern string // "./...", "./types/key"
// Tests is a list of Tests to run. If empty, all Tests in the package are
// run.
Tests []string // ["TestFoo", "TestBar"]
// IssueURLs maps from a test name to a URL tracking its flake.
IssueURLs map[string]string // "TestFoo" => "https://github.com/foo/bar/issue/123"
}
type goTestOutput struct {
Time time.Time
Action string
ImportPath string
Package string
Test string
Output string
}
var debug = os.Getenv("TS_TESTWRAPPER_DEBUG") != ""
// testsForShard returns the test names in pkg that belong to the given shard
// spec (e.g. "2/3"). It uses "go list -json" to find test source files (no
// compilation) and scans them for top-level test function names, assigning
// each to a shard by hashing. Returns nil if the spec is invalid or if
// listing fails (the main run will surface the error).
func testsForShard(ctx context.Context, pkg, shardSpec string) ([]string, error) {
a, b, ok := strings.Cut(shardSpec, "/")
if !ok {
return nil, nil
}
wantShard, err := strconv.Atoi(a)
if err != nil || wantShard < 1 {
return nil, nil
}
shards, err := strconv.Atoi(b)
if err != nil || shards < 1 {
return nil, nil
}
ctx, cancel := context.WithTimeout(ctx, goToolTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "go", "list", "-json", pkg)
cmd.WaitDelay = waitDelay
out, err := cmd.Output()
if err != nil {
// Errors will be surfaced by the main test run.
return nil, nil
}
type pkgJSON struct {
Dir string
TestGoFiles []string
XTestGoFiles []string
}
seen := map[string]bool{}
var result []string
dec := json.NewDecoder(bytes.NewReader(out))
for dec.More() {
var p pkgJSON
if err := dec.Decode(&p); err != nil {
break
}
for _, f := range append(p.TestGoFiles, p.XTestGoFiles...) {
names, err := testFuncNames(filepath.Join(p.Dir, f))
if err != nil {
continue
}
for _, name := range names {
if seen[name] {
continue
}
seen[name] = true
h := fnv.New32a()
io.WriteString(h, name)
if int(h.Sum32()%uint32(shards)) == wantShard-1 {
result = append(result, name)
}
}
}
}
return result, nil
}
// testFuncNames scans a Go source file and returns the names of all top-level
// test functions (Test*, Benchmark*, Example*, Fuzz*).
func testFuncNames(path string) ([]string, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var names []string
sc := bufio.NewScanner(f)
for sc.Scan() {
rest, ok := strings.CutPrefix(sc.Text(), "func ")
if !ok {
continue
}
for _, prefix := range []string{"Test", "Benchmark", "Example", "Fuzz"} {
if strings.HasPrefix(rest, prefix) {
if i := strings.IndexByte(rest, '('); i > 0 {
names = append(names, rest[:i])
}
break
}
}
}
return names, sc.Err()
}
// runTests runs the tests in the packages matching patterns in a single
// "go test" invocation and sends the results on ch. It sends a testAttempt
// for each test and a final testAttempt per pkg with pkgFinished set to
// true. Package build errors will not emit a testAttempt (as no valid JSON
// is produced) but the [os/exec.ExitError] will be returned.
// It calls close(ch) when it's done.
func runTests(ctx context.Context, attempt int, patterns []string, goTestArgs, testArgs []string, ch chan<- *testAttempt) error {
defer close(ch)
args := []string{"test"}
args = append(args, goTestArgs...)
args = append(args, patterns...)
if shardSpec := os.Getenv("TS_TEST_SHARD"); shardSpec != "" {
// Automatic test-name sharding: list tests and filter by hash.
if len(patterns) != 1 {
return fmt.Errorf("TS_TEST_SHARD requires a single package pattern per go test invocation; got %q", patterns)
}
pattern := patterns[0]
shardTests, err := testsForShard(ctx, pattern, shardSpec)
if err != nil {
return err
}
if len(shardTests) == 0 {
ch <- &testAttempt{pkg: pattern, outcome: outcomeSkip, pkgFinished: true}
return nil
}
quoted := make([]string, len(shardTests))
for i, name := range shardTests {
quoted[i] = regexp.QuoteMeta(name)
}
args = append(args, "--run", "^("+strings.Join(quoted, "|")+")$")
}
args = append(args, testArgs...)
args = append(args, "-json")
if debug {
fmt.Println("running", strings.Join(args, " "))
}
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
cmd := exec.CommandContext(ctx, "go", args...)
cmd.WaitDelay = waitDelay
r, err := cmd.StdoutPipe()
if err != nil {
log.Printf("error creating stdout pipe: %v", err)
}
defer r.Close()
cmd.Stderr = os.Stderr
// Kill go test if it goes quiet for longer than any single test binary
// may run. That means something else, like the linker, is stuck.
var watchdog *time.Timer
var idle time.Duration
if t := goTestTimeout(goTestArgs, testArgs); t > 0 {
idle = t + idleMargin
watchdog = time.AfterFunc(idle, func() {
log.Printf("testwrapper: no output from go test in %v; killing it", idle)
dumpProcesses()
cancel(fmt.Errorf("go test produced no output for %v", idle))
})
defer watchdog.Stop()
}
cmd.Env = slices.DeleteFunc(os.Environ(), func(s string) bool {
return strings.HasPrefix(s, "TS_TEST_SHARD=")
})
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%d", flakytest.FlakeAttemptEnv, attempt))
if err := cmd.Start(); err != nil {
log.Printf("error starting test: %v", err)
os.Exit(1)
}
pkgCached := map[string]bool{}
s := bufio.NewScanner(r)
resultMap := make(map[string]map[string]*testAttempt) // pkg -> test -> testAttempt
for s.Scan() {
if watchdog != nil && ctx.Err() == nil {
watchdog.Reset(idle)
}
var goOutput goTestOutput
if err := json.Unmarshal(s.Bytes(), &goOutput); err != nil {
return fmt.Errorf("failed to parse go test output %q: %w", s.Bytes(), err)
}
pkg := cmp.Or(
goOutput.Package,
"build:"+goOutput.ImportPath, // can be "./cmd" while Package is "tailscale.com/cmd" so use separate namespace
)
pkgTests := resultMap[pkg]
if pkgTests == nil {
pkgTests = map[string]*testAttempt{
"": {}, // Used for start time and build logs.
}
resultMap[pkg] = pkgTests
}
if goOutput.Test == "" {
// Detect output lines like:
// ok \ttailscale.com/cmd/testwrapper\t(cached)
// ok \ttailscale.com/cmd/testwrapper\t(cached)\tcoverage: 17.0% of statements
if goOutput.Package != "" && strings.Contains(goOutput.Output, fmt.Sprintf("%s\t(cached)", goOutput.Package)) {
pkgCached[goOutput.Package] = true
}
switch goOutput.Action {
case "start":
pkgTests[""].start = goOutput.Time
case "build-output":
pkgTests[""].logs.WriteString(goOutput.Output)
case "build-fail", "fail", "pass", "skip":
for _, test := range pkgTests {
if test.testName != "" && test.outcome == outcomeUnknown {
test.outcome = outcomeFail
test.inferredFail = true
ch <- test
}
}
outcome := testOutcome(goOutput.Action)
if goOutput.Action == "build-fail" {
outcome = outcomeFail
}
pkgTests[""].logs.WriteString(goOutput.Output)
// If a data race was detected anywhere in this
// package's output -- whether at the package level or
// attributed to a specific test -- consolidate all
// per-test logs into the package-level logs so the
// full race report is visible regardless of which
// test test2json happened to attribute it to. The
// pkgFinished testAttempt also carries raceDetected
// so the main loop can suppress flaky-test retries.
raceDetected := pkgTests[""].raceDetected
if !raceDetected {
for _, t := range pkgTests {
if t.raceDetected {
raceDetected = true
break
}
}
}
if raceDetected {
var ts []*testAttempt
for _, t := range pkgTests {
if t.testName != "" && t.logs.Len() > 0 {
ts = append(ts, t)
}
}
slices.SortFunc(ts, func(a, b *testAttempt) int {
return a.start.Compare(b.start)
})
for _, t := range ts {
pkgTests[""].logs.Write(t.logs.Bytes())
}
}
ch <- &testAttempt{
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
// "FAIL tailscale.io/control 0.684s" line, as
// printPkgOutcome will output a similar line
if !strings.HasPrefix(goOutput.Output, fmt.Sprintf("FAIL\t%s\t", goOutput.Package)) {
pkgTests[""].logs.WriteString(goOutput.Output)
switch goOutput.Output {
case raceDetectorMarkerLine:
pkgTests[""].raceDetected = true
case "PASS\n", "FAIL\n":
pkgTests[""].binaryFinished = true
}
}
}
continue
}
testName := goOutput.Test
if test, _, isSubtest := strings.Cut(goOutput.Test, "/"); isSubtest {
testName = test
if goOutput.Action == "output" {
resultMap[pkg][testName].logs.WriteString(goOutput.Output)
if goOutput.Output == raceDetectorMarkerLine {
resultMap[pkg][testName].raceDetected = true
}
}
continue
}
switch goOutput.Action {
case "start":
// ignore
case "run":
pkgTests[testName] = &testAttempt{
pkg: pkg,
testName: testName,
start: goOutput.Time,
}
case "skip", "pass", "fail":
pkgTests[testName].end = goOutput.Time
pkgTests[testName].outcome = testOutcome(goOutput.Action)
ch <- pkgTests[testName]
case "output":
if suffix, ok := strings.CutPrefix(strings.TrimSpace(goOutput.Output), flakytest.FlakyTestLogMessage); ok {
pkgTests[testName].isMarkedFlaky = true
pkgTests[testName].issueURL = strings.TrimPrefix(suffix, ": ")
} else {
pkgTests[testName].logs.WriteString(goOutput.Output)
if goOutput.Output == raceDetectorMarkerLine {
pkgTests[testName].raceDetected = true
}
}
}
}
if err := cmd.Wait(); err != nil {
if cause := context.Cause(ctx); cause != nil {
return cause
}
return err
}
if err := s.Err(); err != nil {
return fmt.Errorf("reading go test stdout: %w", err)
}
return nil
}
// goTestTimeout returns the go test -timeout set in any of argLists, or go
// test's default if none is set. Zero means no timeout.
func goTestTimeout(argLists ...[]string) time.Duration {
t := defaultGoTestTimeout
for _, args := range argLists {
for i := 0; i < len(args); i++ {
name, val, hasEq := strings.Cut(strings.TrimLeft(args[i], "-"), "=")
if name != "timeout" && name != "test.timeout" {
continue
}
if !hasEq && i+1 < len(args) {
i++
val = args[i]
}
if d, err := time.ParseDuration(val); err == nil {
t = d
}
}
}
return t
}
// listShardPackages returns the packages in shard nOfM (e.g. "1/2") of ./...
func listShardPackages(ctx context.Context, nOfM string) []string {
ctx, cancel := context.WithTimeout(ctx, goToolTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "go", "run", "tailscale.com/tool/listpkgs", "-shard", nOfM, "./...")
cmd.WaitDelay = waitDelay
out, err := cmd.Output()
if err != nil {
log.Fatalf("failed to list packages for sharded test: %v", err)
}
return strings.Split(strings.TrimSpace(string(out)), "\n")
}
// dumpProcesses logs testwrapper's descendant processes on Linux, to show
// what a hung go test was waiting on.
func dumpProcesses() {
if runtime.GOOS != "linux" {
return
}
children := map[string][]string{} // ppid -> pids
stats, _ := filepath.Glob("/proc/[0-9]*/stat")
for _, f := range stats {
b, err := os.ReadFile(f)
if err != nil {
continue
}
// The fields after the parenthesized command name are state, then ppid.
_, rest, ok := bytes.Cut(b, []byte(") "))
if fields := strings.Fields(string(rest)); ok && len(fields) > 1 {
children[fields[1]] = append(children[fields[1]], filepath.Base(filepath.Dir(f)))
}
}
var pids []string
queue := []string{strconv.Itoa(os.Getpid())}
for len(queue) > 0 {
p := queue[0]
queue = queue[1:]
pids = append(pids, p)
queue = append(queue, children[p]...)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, "ps", "--forest", "-o", "pid,etime,stat,args", "-p", strings.Join(pids, ",")).CombinedOutput()
log.Printf("testwrapper: process tree (err=%v):\n%s", err, out)
}
// runOneTest runs a single test in a single package via `go test -run` with a
// per-attempt -timeout. It returns the test's outcome (outcomePass /
// outcomeFail / outcomeSkip), the wall-clock time spent on this attempt
// (used for the per-test retry budget), and any captured test logs.
//
// On panic, timeout, or any other failure mode where the test does not emit a
// pass/fail/skip JSON event, outcome is reported as outcomeFail.
func runOneTest(ctx context.Context, pkg, testName string, perAttemptTimeout time.Duration, attemptNum int, goTestArgs, testArgs []string) (outcome testOutcome, wallDur time.Duration, logs bytes.Buffer, err error) {
goTestArgs, perAttemptTimeout = extractTimeout(goTestArgs, perAttemptTimeout)
testArgs, perAttemptTimeout = extractTimeout(testArgs, perAttemptTimeout)
args := []string{"test", "-json"}
args = append(args, goTestArgs...)
args = append(args, "-timeout", perAttemptTimeout.String())
args = append(args, pkg)
args = append(args, "--run", "^("+regexp.QuoteMeta(testName)+")$")
args = append(args, testArgs...)
if debug {
fmt.Println("running", strings.Join(args, " "))
}
ctx, cancel := context.WithTimeout(ctx, perAttemptTimeout+retryBuildSlack)
defer cancel()
cmd := exec.CommandContext(ctx, "go", args...)
cmd.WaitDelay = waitDelay
// Strip TS_TEST_SHARD so the child doesn't try to shard inside a
// single-test retry — we are telling it exactly what to run.
cmd.Env = slices.DeleteFunc(os.Environ(), func(s string) bool {
return strings.HasPrefix(s, "TS_TEST_SHARD=")
})
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%d", flakytest.FlakeAttemptEnv, attemptNum))
r, perr := cmd.StdoutPipe()
if perr != nil {
return "", 0, logs, fmt.Errorf("stdout pipe: %w", perr)
}
defer r.Close()
cmd.Stderr = os.Stderr
wallStart := time.Now()
if err := cmd.Start(); err != nil {
return "", 0, logs, fmt.Errorf("starting go test: %w", err)
}
s := bufio.NewScanner(r)
for s.Scan() {
var ev goTestOutput
if err := json.Unmarshal(s.Bytes(), &ev); err != nil {
continue
}
if ev.Test == "" {
continue // package-level events ignored for single-test runs
}
// Collapse subtests to parent.
parent, _, _ := strings.Cut(ev.Test, "/")
if parent != testName {
continue
}
switch ev.Action {
case "pass", "fail", "skip":
if ev.Test == testName {
outcome = testOutcome(ev.Action)
}
case "output":
logs.WriteString(ev.Output)
}
}
waitErr := cmd.Wait()
wallDur = time.Since(wallStart)
if scanErr := s.Err(); scanErr != nil && err == nil {
err = fmt.Errorf("reading go test stdout: %w", scanErr)
}
if outcome == outcomeUnknown {
// Test never emitted a pass/fail/skip — likely a panic, timeout, or
// build error. Treat as fail.
outcome = outcomeFail
}
if waitErr != nil && err == nil && outcome == outcomePass {
// A non-zero exit when outcome==outcomePass is unexpected; surface it.
err = waitErr
}
return outcome, wallDur, logs, err
}
// extractTimeout returns args with any -timeout / -test.timeout flags
// stripped, and the smaller of cap and the user-supplied timeout (if any).
// This lets retries use the testwrapper-computed per-attempt timeout, but
// never exceed an explicit -timeout the user passed on the command line.
func extractTimeout(args []string, cap time.Duration) (stripped []string, t time.Duration) {
t = cap
stripped = make([]string, 0, len(args))
for i := 0; i < len(args); i++ {
a := args[i]
bare := strings.TrimLeft(a, "-")
name, val, hasEq := strings.Cut(bare, "=")
if name == "timeout" || name == "test.timeout" {
var raw string
if hasEq {
raw = val
} else if i+1 < len(args) {
raw = args[i+1]
i++
}
if d, err := time.ParseDuration(raw); err == nil && d < t {
t = d
}
continue
}
stripped = append(stripped, a)
}
return stripped, t
}
// computePerAttemptTimeout returns the -timeout we use for each retry attempt
// of a test that first failed in firstFail.
//
// It is the smaller of perAttemptCap (5 min) and 1.5*firstFail, but never
// smaller than perAttemptFloor (30 s).
func computePerAttemptTimeout(firstFail time.Duration) time.Duration {
t := time.Duration(float64(firstFail) * 1.5)
return max(perAttemptFloor, min(perAttemptCap, t))
}
// retryFailedTest runs the per-test retry loop for ft. It updates ft in place.
func retryFailedTest(ctx context.Context, ft *failedTest, goTestArgs, testArgs []string, deadline time.Time) {
perAttempt := computePerAttemptTimeout(ft.firstFailDuration)
for {
if ft.everPassed {
return
}
if ft.attempts >= maxRetries {
return
}
if ft.attempts >= minRetries && ft.totalRetryElapsed >= perTestBudget {
return
}
if remaining := time.Until(deadline); remaining < perAttempt {
// perAttempt represents a reasonable guess of how long the test might take
// to run, so don't even attempt to retry a test that is likely to take us
// past our overall deadline.
log.Printf("testwrapper: not retrying %s.%s because its timeout (%.1fs) would exceed the remaining max retry time (%.1fs)",
ft.pkg, ft.testName, perAttempt.Seconds(), remaining.Seconds())
return
}
// FlakeAttemptEnv is 1-indexed counting the first pass as attempt 1.
// Retry attempt N is FlakeAttemptEnv = 1 + N.
attemptNum := 1 + ft.attempts + 1
outcome, dur, logs, err := runOneTest(ctx, ft.pkg, ft.testName, perAttempt, attemptNum, goTestArgs, testArgs)
ft.attempts++
ft.totalRetryElapsed += dur
fmt.Printf(" [retry %d] %s.%s: %s (%.3fs)\n",
ft.attempts, ft.pkg, ft.testName, strings.ToUpper(string(outcome)), dur.Seconds())
if err != nil {
log.Printf("testwrapper: error running %s.%s: %v", ft.pkg, ft.testName, err)
}
if testingVerbose || outcome == outcomeFail {
io.Copy(os.Stdout, &logs)
}
if outcome == outcomePass {
ft.everPassed = true
ft.binaryFailed = err != nil
}
}
}
// detectRepo returns the GitHub "owner/repo" we're running in, used in the
// fake issue URL recorded for unmarked flaky tests.
//
// It checks GITHUB_REPOSITORY (set by GitHub Actions), then `git config --get
// remote.origin.url`, then falls back to "tailscale/tailscale".
func detectRepo() string {
if r := os.Getenv("GITHUB_REPOSITORY"); r != "" {
return r
}
out, err := exec.Command("git", "config", "--get", "remote.origin.url").Output()
if err == nil {
if r := parseGitRemote(strings.TrimSpace(string(out))); r != "" {
return r
}
}
return "tailscale/tailscale"
}
// parseGitRemote pulls "owner/repo" out of common git remote URL forms:
// - [email protected]:owner/repo.git
// - https://github.com/owner/repo.git
// - https://github.com/owner/repo
func parseGitRemote(url string) string {
url = strings.TrimSuffix(url, ".git")
// SSH form
if rest, ok := strings.CutPrefix(url, "[email protected]:"); ok {
return rest
}
// HTTPS form
for _, p := range []string{"https://github.com/", "http://github.com/"} {
if rest, ok := strings.CutPrefix(url, p); ok {
return rest
}
}
return ""
}
// fakeIssueURL returns the fake GitHub issue URL we record for unmarked tests
// that turn out to be flaky.
func fakeIssueURL(repo string) string {
return "https://github.com/" + repo + flakeUnknownIssueSlug
}
// writeFlakeSummary appends a markdown summary of flaky tests to path,
// creating it if needed. In practice path is the GitHub Actions runner's
// $GITHUB_STEP_SUMMARY, which testwrapper auto-detects. It logs and
// continues on errors, as a CI write failure should not poison the test
// run's exit status.
func writeFlakeSummary(path string, flaky []*failedTest, repo string) {
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
log.Printf("testwrapper: opening summary file %s: %v", path, err)
return
}
defer f.Close()
if len(flaky) == 0 {
fmt.Fprintln(f, "_No flaky tests detected._")
return
}
fmt.Fprintln(f, "### Flaky tests detected")
fmt.Fprintln(f)
fmt.Fprintln(f, "Tests that failed at least once and then passed on retry. Rows tagged 🆕 were not annotated with flakytest.Mark; testwrapper auto-detected the flake.")
fmt.Fprintln(f)
fmt.Fprintln(f, "| Package | Test | Retries | Retry time | Issue |")
fmt.Fprintln(f, "|---------|------|--------:|-----------:|-------|")
for _, ft := range flaky {
url := ft.issueURL
if url == "" {
url = fakeIssueURL(repo)
}
var tag string
if ft.issueURL == "" {
tag = " 🆕"
}
fmt.Fprintf(f, "| `%s` | `%s`%s | %d | %.1fs | [link](%s) |\n",
ft.pkg, ft.testName, tag, ft.attempts, ft.totalRetryElapsed.Seconds(), url)
}
}
// writeResultsSummary renders the per-test results panel and JSON for the Windows results feature.
func writeResultsSummary(summaryPath, jsonPath, pkgOnly string, results map[string]testOutcome, retried map[string]bool, pkgFatal bool) {
type result struct {
Package string
Test string
Outcome string
}
var rows []result
for key, outcome := range results {
pkg, test, _ := strings.Cut(key, "\t")
if pkgOnly != "" && pkg != pkgOnly {
continue
}
out := string(outcome)
if outcome == outcomeFail && retried[key] {
out = "retried"
}
rows = append(rows, result{Package: pkg, Test: test, Outcome: out})
}
slices.SortFunc(rows, func(a, b result) int {
return strings.Compare(a.Test, b.Test)
})
if jsonPath != "" {
if j, err := json.Marshal(rows); err != nil {
log.Printf("testwrapper: marshaling results JSON: %v", err)
} else if err := os.WriteFile(jsonPath, j, 0o644); err != nil {
log.Printf("testwrapper: writing results JSON %s: %v", jsonPath, err)
}
}
f, err := os.OpenFile(summaryPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
log.Printf("testwrapper: opening summary file %s: %v", summaryPath, err)
return
}
defer f.Close()
title := "Windows integration test results"
if pkgOnly == "" {
title = "Test results"
}
fmt.Fprintf(f, "\n### %s\n\n", title)
if len(rows) == 0 {
fmt.Fprintln(f, "_No tests ran._")
if pkgFatal {
fmt.Fprintln(f, "\n_⚠️ A package did not complete (build error or timeout); results may be partial._")
}
return
}
var pass, fail, skip int
fmt.Fprintln(f, "| Result | Test |")
fmt.Fprintln(f, "|--------|------|")
for _, r := range rows {
var icon string
switch r.Outcome {
case "pass":
icon, pass = "✅", pass+1
case "retried":
icon, pass = "✅ (retried)", pass+1
case "skip":
icon, skip = "⚠️", skip+1
default:
icon, fail = "❌", fail+1
}
fmt.Fprintf(f, "| %s | `%s` |\n", icon, r.Test)
}
fmt.Fprintf(f, "\n**%d passed, %d failed, %d skipped**\n", pass, fail, skip)
if pkgFatal {
fmt.Fprintln(f, "\n_⚠️ A package did not complete (build error or timeout); results may be partial._")
}
}
// buildPackageTests groups failedTests by package into the wire format
// flakeapp expects.
//
// If fakeRepo is non-empty, tests with no real issue URL (i.e. not marked via
// flakytest.Mark) get a fake URL of the form
// https://github.com/{fakeRepo}/issues/UNKNOWN. If fakeRepo is empty, those
// tests are simply omitted from the IssueURLs map.
func buildPackageTests(fts []*failedTest, fakeRepo string) []packageTests {
byPkg := map[string][]*failedTest{}
for _, ft := range fts {
byPkg[ft.pkg] = append(byPkg[ft.pkg], ft)
}
pkgs := make([]string, 0, len(byPkg))
for p := range byPkg {
pkgs = append(pkgs, p)
}
sort.Strings(pkgs)
out := make([]packageTests, 0, len(pkgs))
for _, p := range pkgs {
group := byPkg[p]
slices.SortFunc(group, func(a, b *failedTest) int { return strings.Compare(a.testName, b.testName) })
pt := packageTests{Pattern: p, IssueURLs: map[string]string{}}
for _, ft := range group {
pt.Tests = append(pt.Tests, ft.testName)
url := ft.issueURL
if url == "" && fakeRepo != "" {
url = fakeIssueURL(fakeRepo)
}
if url != "" {
pt.IssueURLs[ft.testName] = url
}
}
out = append(out, pt)
}
return out
}
// isGoFile reports whether arg names a Go source file rather than a
// package pattern.
func isGoFile(arg string) bool {
return strings.HasSuffix(arg, ".go")
}
func main() {
goTestArgs, packages, testArgs, err := splitArgs(os.Args[1:])
if err != nil {
log.Fatal(err)
return
}
if len(packages) == 0 {
fmt.Println("testwrapper: no packages specified")
return
}
ctx := context.Background()
// As a special case, if the packages looks like "sharded:1/2" then shell out to
// ./tool/listpkgs to cut up the package list pieces for each sharded builder.
if nOfM, ok := strings.CutPrefix(packages[0], "sharded:"); ok && len(packages) == 1 {
packages = listShardPackages(ctx, nOfM)
}
repo := detectRepo()
printPkgOutcome := func(pkg string, outcome testOutcome, cached bool, testDur time.Duration) {
if pkg == "" {
return // We reach this path on a build error.
}
if outcome == outcomeSkip {
fmt.Printf("?\t%s [skipped/no tests] \n", pkg)
return
}
label := string(outcome)
if outcome == outcomePass {
label = "ok"
}
if outcome == outcomeFail {
label = "FAIL"
}
var lastCol string
if cached {
lastCol = "(cached)"
} else {
lastCol = fmt.Sprintf("%.3fs", testDur.Seconds())
}
fmt.Printf("%s\t%s\t%v\n", label, pkg, lastCol)
}
// First pass: run every package once, collect failed tests for retry.
//
// All package patterns go to one "go test" invocation so the go
// command can build, link, and run them in parallel, exactly as it
// does for a single "./..." pattern. Test-name sharding lists tests
// per package, and .go file arguments each form their own
// "command-line-arguments" package, so those keep one invocation
// per argument.
batches := [][]string{packages}
if os.Getenv("TS_TEST_SHARD") != "" || slices.ContainsFunc(packages, isGoFile) {
batches = nil
for _, p := range packages {
batches = append(batches, []string{p})
}
}
var failed []*failedTest
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{}
for _, patterns := range batches {
ch := make(chan *testAttempt)
runErrCh := make(chan error, 1)
go func() {
defer close(runErrCh)
runErrCh <- runTests(ctx, 1, patterns, goTestArgs, testArgs, ch)
}()
// 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
// convenient for us to specify files in tests, so fix tr.pkg
// so that subsequent testwrapper attempts run correctly. File
// arguments always run one per batch, so the batch's only
// pattern is the file.
if tr.pkg == "command-line-arguments" {
tr.pkg = patterns[0]
}
if tr.pkgFinished {
if testingVerbose || tr.outcome == outcomeFail {
io.Copy(os.Stdout, &tr.logs)
}
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 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
}
pkgFailedTests = append(pkgFailedTests, &failedTest{
pkg: tr.pkg,
testName: tr.testName,
firstFailDuration: tr.end.Sub(tr.start),
issueURL: tr.issueURL, // real if Mark()'d, else "".
})
}
failed = append(failed, pkgFailedTests...)
if err := <-runErrCh; err != nil {
// ExitCode is -1 if go test was killed by a signal, which
// must not be mistaken for success.
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. 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)
pkgFatal = true
}
}
}
// Second pass: retry each failed test serially with its per-test budget.
if len(failed) > 0 {
deadline := time.Now().Add(maxRetryTime)
fmt.Printf("\n\nRetrying %d failed test(s) to detect flakiness...\n\n", len(failed))
for _, ft := range failed {
retryFailedTest(ctx, ft, goTestArgs, testArgs, deadline)
}
}
// 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 {
permanent = append(permanent, ft)
}
}
if len(flaky) > 0 {
j, _ := json.Marshal(buildPackageTests(flaky, repo))
fmt.Printf("\nflakytest failures JSON: %s\n", j)
}
if path := os.Getenv("GITHUB_STEP_SUMMARY"); path != "" {
writeFlakeSummary(path, flaky, repo)
if resultsSummary {
retried := map[string]bool{}
for _, ft := range flaky {
retried[ft.pkg+"\t"+ft.testName] = true
}
writeResultsSummary(path, os.Getenv("TS_TESTWRAPPER_RESULTS_JSON"), os.Getenv("TS_TESTWRAPPER_RESULTS_PKG"), allResults, retried, pkgFatal)
}
}
if len(permanent) > 0 {
j, _ := json.Marshal(buildPackageTests(permanent, ""))
fmt.Printf("\npermanent test failures JSON: %s\n", j)
}
if pkgFatal || len(permanent) > 0 {
os.Exit(cmp.Or(goTestExitCode, 1))
}
}