Skip to content

test: fix a race in TestReinit #17902

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

Merged
merged 1 commit into from
May 19, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions coderd/workspaceagents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2650,8 +2650,8 @@ func TestReinit(t *testing.T) {

db, ps := dbtestutil.NewDB(t)
pubsubSpy := pubsubReinitSpy{
Pubsub: ps,
subscribed: make(chan string),
Pubsub: ps,
triedToSubscribe: make(chan string),
}
client := coderdtest.New(t, &coderdtest.Options{
Database: db,
Expand All @@ -2664,9 +2664,9 @@ func TestReinit(t *testing.T) {
OwnerID: user.UserID,
}).WithAgent().Do()

pubsubSpy.Mutex.Lock()
pubsubSpy.Lock()
pubsubSpy.expectedEvent = agentsdk.PrebuildClaimedChannel(r.Workspace.ID)
pubsubSpy.Mutex.Unlock()
pubsubSpy.Unlock()

agentCtx := testutil.Context(t, testutil.WaitShort)
agentClient := agentsdk.New(client.URL)
Expand All @@ -2681,7 +2681,7 @@ func TestReinit(t *testing.T) {

// We need to subscribe before we publish, lest we miss the event
ctx := testutil.Context(t, testutil.WaitShort)
testutil.TryReceive(ctx, t, pubsubSpy.subscribed) // Wait for the appropriate subscription
testutil.TryReceive(ctx, t, pubsubSpy.triedToSubscribe)

// Now that we're subscribed, publish the event
err := prebuilds.NewPubsubWorkspaceClaimPublisher(ps).PublishWorkspaceClaim(agentsdk.ReinitializationEvent{
Expand All @@ -2699,15 +2699,16 @@ func TestReinit(t *testing.T) {
type pubsubReinitSpy struct {
pubsub.Pubsub
sync.Mutex
subscribed chan string
expectedEvent string
triedToSubscribe chan string
expectedEvent string
}

func (p *pubsubReinitSpy) Subscribe(event string, listener pubsub.Listener) (cancel func(), err error) {
cancel, err = p.Pubsub.Subscribe(event, listener)
p.Lock()
Comment on lines +2707 to 2708
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it not make more sense to move the subscribe call after we lock the spy's mutex?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so; the mutex is protecting the expectedEvent and triedToSubscribe, not the underlying pubsub.

if p.expectedEvent != "" && event == p.expectedEvent {
close(p.subscribed)
close(p.triedToSubscribe)
}
p.Unlock()
return p.Pubsub.Subscribe(event, listener)
return cancel, err
}
Loading