Skip to content

test: wait for goroutines to exit before the leak check - #603

Draft
mafredri wants to merge 2 commits into
masterfrom
mafredri/testmain-goroutine-wait
Draft

mafredri wants to merge 2 commits into
masterfrom
mafredri/testmain-goroutine-wait

Conversation

@mafredri

@mafredri mafredri commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

TestMain counted goroutines once, right after m.Run, so a goroutine that had finished its work but not yet returned was reported as a leak. os/exec's watchCtx goroutine is one: Cmd.Wait returns once watchCtx has sent its result, and watchCtx returns only when the scheduler runs it again. Every failing run showed that goroutine as runnable at that point (exec.go:797 on Go 1.26.10). TestMain now counts again every 10ms for up to 5 seconds, and reports a leak only if extra goroutines are still there.

GOMAXPROCS=1 AUTOBAHN=fast go test -run '^TestAutobahn$' . failed the check in 9 of 10 runs on master and passed 20 of 20 on this branch. The full package did not hit the check here on either branch: 0 leak-check failures in 40 -race runs, 10 with GOMAXPROCS=1 AUTOBAHN=fast, and 24 with 8 copies running at once (load average 37).

Verification
  • With timing added, 9 of 10 TestAutobahn runs had a first count of 2, and every one counted 1 after a single 10ms wait.
  • A test that starts a goroutine blocked forever still fails with goroutine leak detected, expected 1 but got 2 goroutines and its stack, after the 5 second wait.
  • make lint passed.
Decision log
  • Count again instead of waiting for watchCtx in the tests that use os/exec: any goroutine can be in this state when m.Run returns, and the check should not depend on which test started it.
  • No go.uber.org/goleak: the module has no dependencies, and a loop is enough for one count at the end of the run.
  • 5 seconds: the wait ends as soon as the count matches, so a passing run usually waits one 10ms poll, and only a run with an extra goroutine waits the full 5 seconds. The cost is that a leaked goroutine that a timer ends within 5 seconds is no longer reported.

🤖 This PR was created with the help of Coder Agents.

TestMain counted goroutines once, right after m.Run. A goroutine that
has finished its work but has not been scheduled to return yet was
counted as a leak. os/exec's watchCtx goroutine is one: Cmd.Wait
returns once watchCtx has sent its result, before watchCtx itself
returns. Running TestAutobahn alone with GOMAXPROCS=1 failed the check
in 9 of 10 runs.

TestMain now counts again every 10ms for up to 5 seconds and reports a
leak only if extra goroutines are still there.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant