Fix read/write race condition for edge case #1038
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What?
The mutex that is added in this PR is only needed in an edge case where we have multiple instances of k6 connecting to the same chrome instance.
Data race stack trace
Why?
In this case when a page is created by the first k6 instance, the second instance of k6 will also receive an onAttachedToTarget event, causing it to try to create a new page instance in the second k6 instance too. At this point the second instance of k6 tries to recover a
browserContext
with the given ID from the CDP async message. If there is nobrowserContext
with the given id (which there shouldn't be in the second k6 instance) it will fall back to using the defaultBrowserContext. This is where the read part of the race condition occurs.When this occurs there's a small chance that at the same time a NewContext is being actioned on by the second k6 instance, and this is where the write part of the race condition occurs.
This mutex solely protects the read/write race condition for this one case.
Checklist
Related PR(s)/Issue(s)
Linked CI test failure where this issue was discovered: https://github.com/grafana/xk6-browser/actions/runs/6222592947/job/16886846565?pr=1034, and the test that failed was TestMultiConnectToSingleBrowser. I was able to reproduce the issue when stress testing this one integration test locally. After the fix the problem didn't surface again.