Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/vet: add check for sync.WaitGroup abuse #18022

Open
dsnet opened this issue Nov 22, 2016 · 53 comments
Open

cmd/vet: add check for sync.WaitGroup abuse #18022

dsnet opened this issue Nov 22, 2016 · 53 comments
Assignees
Labels
Analysis Issues related to static analysis (vet, x/tools/go/analysis) Proposal-Accepted
Milestone

Comments

@dsnet
Copy link
Member

dsnet commented Nov 22, 2016

The API for WaitGroup is very easy for people to misuse. The documentation for Add says:

calls to Add should execute before the statement creating the goroutine or other event to be waited for.

However, it is very common to see this incorrect pattern:

var wg sync.WaitGroup
defer wg.Wait()

go func() {
	wg.Add(1)
	defer wg.Done()
}()

This usage is fundamentally racy and probably does not do what the user wanted. Worse yet, is that it is not detectable by the race detector.

Since the above pattern is common, I propose that we add a method Go that essentially does the Add(1) and subsequent call to Done in the correct way. That is:

func (wg *WaitGroup) Go(f func()) {
	wg.Add(1)
	go func() {
		defer wg.Done()
		f()
	}()
}
@dsnet dsnet added the Proposal label Nov 22, 2016
@dsnet dsnet added this to the Proposal milestone Nov 22, 2016
@cznic
Copy link
Contributor

cznic commented Nov 23, 2016

I don't like the idea. It's IMHO perhaps a task for go vet, if not implemented already. Also, the proposed method would add a(nother) closure layer when the go-ed function has parameters.

@minux
Copy link
Member

minux commented Nov 23, 2016 via email

@dsnet
Copy link
Member Author

dsnet commented Nov 23, 2016

A go vet check seems pretty reasonable. I just tried it right now on the following:

func main() {
	var wg sync.WaitGroup
	defer wg.Wait()
	go func() {
		wg.Add(1)
		defer wg.Done()
	}()
}

and vet doesn't report anything.

In terms of vet's requirements:

  • Correctness: The problem is clearly a race.
  • Frequency: My gut feeling is that this is fairly common. A number of internal bugs that I've fixed is of this nature. So it subjective feels common enough. I don't have hard numbers.
  • Precision: I don't have an algorithm in mind that can accurately identify the pattern and I can imagine some number of false positives.

@dominikh , staticcheck does report a problem:
main.go:10:3: should call wg.Add(1) before starting the goroutine to avoid a race (SA2000)
I'm wondering how accurate the check is and whether it is worth adding to vet.

@mvdan
Copy link
Member

mvdan commented Nov 23, 2016

As far as the proposal goes, I don't like how it limits the func signature to func().

@dominikh
Copy link
Member

@dsnet The check in staticcheck has no (known) false positives. It shouldn't have a significant number of false negatives, either. The implementation is a simple pattern-based check, detecting go with function literals where the first statement is a call to wg.Add – this avoids flagging wg.Add calls further down the goroutine, which tend to be valid uses.

I'm -1 on the proposed Go function. I'd prefer not having to read code with an unnecessary level of nesting that looks callback-esque and reminds me of JavaScript.

@mvdan
Copy link
Member

mvdan commented Nov 23, 2016

@dominikh I don't see any extra level of nesting here, though (assuming any func signature is allowed).

To be nitpicky, another thing that stands out from the proposal is how wg.Go() will create a goroutine even though go is never directly used by the user. I don't know if the standard library does this anywhere else, but I would prefer if it was left explicit.

@dominikh
Copy link
Member

@mvdan The extra level of nesting would come from a predicted usage that looks something like this:

wg.Go(func() {
  // do stuff
})

as opposed to

go func() {
  // do stuff
}()

Admittedly the same level of indentation, but syntactically it's one extra level of nesting.

@mvdan
Copy link
Member

mvdan commented Nov 23, 2016

Ah yes, I was thinking indentation there.

@cznic
Copy link
Contributor

cznic commented Nov 23, 2016

The problematic case is that

wg.Add(1)
go func(i int) { ... }(42)

// becomes

wg.Go(func() {
        go func(i int) { ... }(42)
})

@mvdan
Copy link
Member

mvdan commented Nov 23, 2016

@cznic if you mean without the extra go, this would be solved if the restriction on the func() signature was removed.

@dominikh
Copy link
Member

@mvdan Do you mean by allowing something like the following?

wg.Go(func(x, y int) { ...}, v1, v2)

IMHO that's way too much interface{} and not enough type safety.

@mattn
Copy link
Member

mattn commented Nov 23, 2016

panic is recovered?

@mvdan
Copy link
Member

mvdan commented Nov 23, 2016

@dominikh true; I was simply pointing at the issue without contemplating a solution :)

@rsc
Copy link
Contributor

rsc commented Nov 28, 2016

The API change here has the problems identified above with argument evaluation. Also, in general the libraries do not typically phrase functionality in terms of callbacks. If we're going to start using callbacks broadly, that should be a separate decision (and not one to make today). For both these reasons, it seems like .Go is not a clear win.

It would be nice to have a vet check that we trust (no false positives). Perhaps it is enough to look for two statements

wg.Add(1)
defer wg.Done()

back to back and reject that always. Thoughts about how to make vet catch this reliably?

@renannprado
Copy link

I agree that vet is better place for this. The proposed API reminds of JavaScript, which will force us many times to wrap the code or function within a function with no arguments, while you could have just go func()....
Still nothing can stop you from creating such a helper methid, even though I don't see the need for it.

@rsc
Copy link
Contributor

rsc commented Dec 5, 2016

It sounds like we are deciding to make go vet check this and not add new API here. Any arguments against that?

@dsnet
Copy link
Member Author

dsnet commented Dec 5, 2016

SGTM

@dsnet dsnet changed the title proposal: sync: add Go method to WaitGroup cmd/vet: add check for sync.WaitGroup abuse Dec 5, 2016
@dsnet dsnet removed the Proposal label Dec 9, 2016
@rsc
Copy link
Contributor

rsc commented Aug 5, 2020

I've added this proposal to the proposal process bin, but it's blocked on someone figuring out how to implement a useful check. Is anyone interested in doing that?

@dominikh
Copy link
Member

dominikh commented Aug 6, 2020

Staticcheck has a fairly trivial check: for a GoStmt of a FuncLit, if the first statement in the FuncLit is a call to (*sync.WaitGroup).Add, we flag it. That has potential for false positives, but none have been reported in all the years that the check has existed.

The check could be trivially hardened by

  1. looking for an immediately following defer of (*sync.WaitGroup).Done and comparing the two receivers.
  2. checking that the argument to Add is 1, not some other number.

Edit: which is pretty much what you have suggested in #18022 (comment)

@lpxz
Copy link

lpxz commented Dec 6, 2024

since there is an active discussion here, I would like to bring to your attention that SA2000 in staticcheck misses real bugs.

If you run staticcheck against the following, it fails to find the bug. If you comment the fmt.Print in front of wg.Add(), it finds the bug. In general, as long as there is some code between go func(){ and wg.Add(), SA2000 fails to fire alarm.

// main.go
package main

import (
	"fmt"
	"sync"
)


func  somefunc() error {
   var  wg sync.WaitGroup
   go func() {
        fmt.Println("hi")
	wg.Add(1)
	defer wg.Done()
    }()
   return nil
}

func main(){
   fmt.Println("starting")
   somefunc()
}

$ go install honnef.co/go/tools/cmd/staticcheck@latest
$ staticcheck main.go

SA2000 code is self-explanatory on why this happens.

I wrote a linter to address this. Will move to staticcheck github repo to first discuss whether such improvement is welcome or negligible.

@adonovan
Copy link
Member

adonovan commented Dec 6, 2024

SA2000 in staticcheck misses real bugs.

Yes, SA2000 and the port of it in https://go.dev/cl/633704 are intentionally very limited in the patterns they match, to avoid false positives. I suspect that relaxing the "wg.Add must be the first statement" rule would cause the analyzer to report a spurious diagnostic for this program:

func  f() error {
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()

		...

		// Create another goroutine.
		wg.Add(1) // waitgroup: "WaitGroup.Add called from inside new goroutine"
		go func() {
			defer wg.Done()
			...
		}()
	}()
	return nil
}

I am sure there is room for improvement, but in general our inclination is to optimize for fewer false positives, even at the expense of true positives. If you have concrete suggestions (or code) for better algorithms, we can easily test them out on the corpus of the Module Mirror.

@lpxz
Copy link

lpxz commented Dec 6, 2024

@adonovan yes, you spotted a valid false positive.

Here is my linter that uses the golang analysis, not based on staticcheck. It also has fixing logic btw.

I scanned our code at Uber, it led to two false positives, which look exactly like what you described. All other reports are true positives.

It found one more true positive that SA2000 missed, which is arguably marginal :)

@adonovan
Copy link
Member

Thanks @lpxz. I ran your linter on a sample of 16,193 modules from the Go Module Mirror corpus, and got 73 diagnostics (see attached file).

waitgroup.txt

A random sample of 10 are shown below. Of those, three are true positives that would not otherwise have been caught:

and zero are false positives (though I did notice false positives in a larger sample). That's good. Would you care to inspect a larger sample to classify them as (false, true existing, true new)? Thanks.

https://go-mod-viewer.appspot.com/github.com/jtzjtz/[email protected]/conn/rabbitmq_pool/rabbitmq_pool.go#L121: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/getlantern/[email protected]/eventual_test.go#L102: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/itering/[email protected]/types/customType_test.go#L18: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/starskim/[email protected]/lsp/bilibili/concern.go#L110: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/cgrates/[email protected]/cmd/cgr-tester/parallel/parallel.go#L37: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/omniscale/[email protected]/parser/pbf/parser_test.go#L336: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/omniscale/[email protected]/parser/pbf/parser_test.go#L266: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/xlab/[email protected]/process.go#L123: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/operator-framework/[email protected]/test/e2e/subscription_e2e_test.go#L580: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/github.com/zhufuyi/[email protected]/pkg/ws/server_test.go#L88: Add and Done should not both exist inside the same goroutine block

@lpxz
Copy link

lpxz commented Dec 10, 2024

@adonovan
thanks for spending efforts in trying it out!

yep, I can take a look.
could you clarify the difference between "true existing" vs "true new"?

@Groxx
Copy link

Groxx commented Dec 11, 2024

From skimming a couple as well (maybe I'll get interested enough to be exhaustive):

https://go-mod-viewer.appspot.com/golang.org/x/[email protected]/ssh/session_test.go#L678: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/golang.org/x/[email protected]/ssh/session_test.go#L698: Add and Done should not both exist inside the same goroutine block
https://go-mod-viewer.appspot.com/golang.org/x/[email protected]/ssh/session_test.go#L871: Add and Done should not both exist inside the same goroutine block

These are false positives, the same exception @adonovan pointed out. They could also be written like this though, and I believe it'd incorrectly trigger SA2000 as well:

func  f() {
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		wg.Add(1)
		defer wg.Done() // done setting up work
		...
		go func() {
			defer wg.Done() // done doing work
			...
		}()
	}()
}

but I suspect that's less common code in practice. "defer Done() first" is a very strong pattern as far as I can tell.

I've been trying to think of a check that'd be better at allowing these, because I like "same block" a fair bit, but the closest I can come up with is something like "Add(1) plus includes a deeper nested Done() == ignore". Basically "valid inside invalid is fine". It would definitely miss some, but it might be a good enough sign of "perhaps this is complex enough code that it can be ignored".


This one is a bit interesting:

https://go-mod-viewer.appspot.com/github.com/getlantern/[email protected]/eventual_test.go#L102: Add and Done should not both exist inside the same goroutine block

It's essentially inverted, and it's... arguably fine:

var wg sync.WaitGroup
wg.Add(1)
// Do some concurrent setting to make sure that it works
for i := 0; i < concurrency; i++ {
	go func() {
		// Wait for waitGroup so that all goroutines run at basically the same
		// time.
		wg.Wait()
		v.Set("hi")
		atomic.AddInt32(&sets, 1)
	}()
}
wg.Done()

I've used similar constructs to try to maximize racing, but I'm fairly sure this one is ineffective since in practice the Done() may run before any of the Wait()s. It's almost guaranteed with GOMAXPROCS=1 iirc. My pattern has been:

var ready, started, complete sync.WaitGroup
ready.Add(1)
started.Add(concurrency)
complete.Add(concurrency)
for i := 0; i < concurrency; i++ {
	go func() {	
		started.Done()        // inform that this goroutine has been started
		ready.Wait()          // wait for all to be started
		atomic.AddInt32(&sets, 1)
		complete.Done()       // this goroutine has finished its work	
	}()
}
started.Wait()  // wait for all goroutines to have been started, and likely at or near Wait
ready.Done()    // unblock all ~simultaneously
complete.Wait() // wait for them all to finish

which has so far been the most effective way to trigger real races that I've found, by quite a large margin, across various GOMAXPROCS. And doesn't take long to figure out when you see it.

I suspect this would also trigger the linter, on the ready waitgroup (which could easily be a close(chan) instead, and I generally do that in practice)

@aclements
Copy link
Member

The proposal committee is on board with adding this check to vet. We'll let the domain experts hash out exactly what the right heuristic is. :)

@lpxz
Copy link

lpxz commented Dec 12, 2024

@adonovan @Groxx
given we only saw one false positive pattern for my linter, i can improve it to avoid that false positive.

Then we can rerun analysis again.

@lpxz
Copy link

lpxz commented Dec 12, 2024

@adonovan done with the manual analysis, see https://gist.github.com/lpxz/10b2cd9c3d390064f0a51267daa80575.

My linter has these:
FALSE: 12
TRUE EXISTING: 46,
TRUE NEW: 11, which cannot be found by SA2000 in staticcheck.

See the improved version here please.
It reduced the false positives from 12 to 0, without comprising true positives.

could you rerun it, and then I do another manual inspection?

@adonovan
Copy link
Member

Impressive! Some of these new finds are really great.

But I'm not sure that all of the new positives are true: Consider this one:
https://go-mod-viewer.appspot.com/github.com/status-im/[email protected]/protocol/messenger_handler.go#L1762

m.shutdownWaitGroup.Add(1)
defer m.shutdownWaitGroup.Done()

I can't see the full context (and nor can the tool), but it looks like it is temporarily bumping up a reference count, which seems like a reasonable thing to do. I wonder how many are of this form, and if there's a rule to exclude them.

https://go-mod-viewer.appspot.com/github.com/getlantern/[email protected]/eventual_test.go#L102 is a delightful muddle! ;-)

@lpxz
Copy link

lpxz commented Dec 12, 2024

https://go-mod-viewer.appspot.com/github.com/getlantern/[email protected]/eventual_test.go#L102 is a delightful muddle! ;-)

ok, the improved linter will still false positive on this, until we use inspect() to recursively look into all sibling nodes (may not be worthy the machine cost)

But I'm not sure that all of the new positives are true: Consider this one:
https://go-mod-viewer.appspot.com/github.com/status-im/[email protected]/protocol/messenger_handler.go#L1762

m.shutdownWaitGroup.Add(1)
defer m.shutdownWaitGroup.Done()

I think it is true positive, given this pattern, the goroutine may not start yet, when the shutdownWaitGroup.Wait() is reached, leaving that goroutine leaky. Did I miss some subtlety here?

A relevant question, what is the next step then? :)

@adonovan
Copy link
Member

adonovan commented Dec 12, 2024

https://go-mod-viewer.appspot.com/github.com/getlantern/[email protected]/eventual_test.go#L102 is a delightful muddle

To be clear, I meant that the code here is wrong in more ways than I can count; your linter algorithm is absolutely right to flag it.

https://go-mod-viewer.appspot.com/github.com/status-im/[email protected]/protocol/messenger_handler.go#L1762
m.shutdownWaitGroup.Add(1)
defer m.shutdownWaitGroup.Done()
I think it is true positive, given this pattern, the goroutine may not start yet, when the shutdownWaitGroup.Wait() is reached, leaving that goroutine leaky. Did I miss some subtlety here?

A WaitGroup is a counting semaphore. The most common use is to count unfinished goroutines, but in this case I think it is counting various "holds" that prevent the program from completing its shutdown (like electricians each padlocking the main breaker so that they know they are safe while they are working). That is, the goroutines are already running, and any of them may temporarily increment the counter, far from where they are created. Presumably at the end the main goroutine will wait for the counter to fall to zero.

The clue to recognizing this pattern is that there is no nearby Add; go func() { ... Done; } (); Wait structure (or bungled attempt at that structure).

A relevant question, what is the next step then? :)

We should probably reclassify the new positives in light of these observations. Ideally the false positive rate should be 5% or less.

@Groxx
Copy link

Groxx commented Dec 13, 2024

re https://go-mod-viewer.appspot.com/github.com/status-im/[email protected]/protocol/messenger_handler.go#L1762 :

Since it's a semaphore that is incorrect to use to Wait() and then Add() and nothing seems to guarantee that goroutine is scheduled before shutdown, I think that can be called "true". Nothing related to that goroutine is passed anywhere after it is created, nor any references to it (afaict) in that method that could lead to "wait for it to start m. downloadAndImportHistoryArchives before allowing shutdown".

(obviously this is worth verifying, but it seems extremely unlikely to be guaranteed-safe to me)

@lpxz
Copy link

lpxz commented Dec 13, 2024

I agree with @Groxx on this,

If the goroutines want to declare they are live, why do not they do so at the beginning or even better before goroutine starts. I am not sure why they do so in the middle.

By flagging this, we suggest developers to move add to an earlier point. This can only improve quality, at least will not degrade quality.

I may miss some points, please let me know.

@egonelbre
Copy link
Contributor

But I'm not sure that all of the new positives are true: Consider this one: https://go-mod-viewer.appspot.com/github.com/status-im/[email protected]/protocol/messenger_handler.go#L1762

That's definitely a bug. (As other people already deduced). The easiest way to see this is to imagine a time.Sleep(10*time.Second) before line m.shutdownWaitGroup.Add(1) or task.Waiter.Add(1)... then any task.Waiter.Wait() or m.shutdownWaitGroup.Wait() may miss the first add and hence the wait is unnecessary.

@adonovan
Copy link
Member

adonovan commented Dec 13, 2024

Thanks, you have all convinced me that this is indeed a bug (and thus a true positive of the new algorithm).

@lpxz, would you like to send me a CL to incorporate the new algorithm into the waitgroup analyzer (currently in gopls, but eventually to be promoted to vet too)? The CL should included a test for each distinct case you encountered (and false positives too, since they document the limitations). Thanks for improving this analyzer!

@lpxz
Copy link

lpxz commented Dec 13, 2024

@adonovan great, happy to make the contributions!

Will create a CL and add tests.
It may not be ready until early next January, let me know if this is more urgent.

Peng

@aclements
Copy link
Member

Based on the discussion above, this proposal seems like a likely accept.

The proposal is to add a vet check for sync.WaitGroup misuse where Add can race with Wait, such as in:

var wg sync.WaitGroup
defer wg.Wait()

go func() {
        wg.Add(1)
        defer wg.Done()
}()

While complex heuristics are certainly possible here, for now we're going to limit this to checking for wg.Add on the first line of a closure. This has a zero false positive rate on the data we sampled, and is simple to implement.

@aclements aclements moved this from Active to Likely Accept in Proposals Jan 16, 2025
@lpxz
Copy link

lpxz commented Jan 16, 2025

I am in progress of creating the cl, which has no false positive, fewer false negatives and is also simple.

Feel free to let me know if the final decision is to move on with the first line approach which is a fine approach).

@adonovan
Copy link
Member

Feel free to let me know if the final decision is to move on with the first line approach which is a fine approach).

This proposal is about adding the basic functionality into vet, which can likely proceed for go1.25.

Independent of that, you should feel free to improve the algorithm; any improvements can be used immediately by gopls, and eventually by vet (without needing a separate proposal process), assuming they meet the usual criteria for precision and frequency.

@aclements
Copy link
Member

No change in consensus, so accepted. 🎉
This issue now tracks the work of implementing the proposal.
— aclements for the proposal review group

The proposal is to add a vet check for sync.WaitGroup misuse where Add can race with Wait, such as in:

var wg sync.WaitGroup
defer wg.Wait()

go func() {
        wg.Add(1)
        defer wg.Done()
}()

While complex heuristics are certainly possible here, for now we're going to limit this to checking for wg.Add on the first line of a closure. This has a zero false positive rate on the data we sampled, and is simple to implement.

@aclements aclements moved this from Likely Accept to Accepted in Proposals Jan 23, 2025
@aclements aclements changed the title proposal: cmd/vet: add check for sync.WaitGroup abuse cmd/vet: add check for sync.WaitGroup abuse Jan 23, 2025
@aclements aclements modified the milestones: Proposal, Backlog Jan 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Analysis Issues related to static analysis (vet, x/tools/go/analysis) Proposal-Accepted
Projects
Status: Accepted
Development

No branches or pull requests