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

Metrics concurrency bug #318

Merged
merged 9 commits into from
Aug 16, 2023
Merged

Conversation

CoreyCook8
Copy link
Contributor

@CoreyCook8 CoreyCook8 commented Aug 15, 2023

There is a race condition under certain situations when using the FromContext function call and then updating metrics.

Each call to FromContext, when a tagsContainer is present, will return a childRegistry with the tags field set to the same location in memory.

In the case where these tag slices have a capacity > length and concurrent calls to append are made on the slice (Such as two processes calling Gauge at the same time), the tags slice will be populated with the first caller's new tags, and then overwritten by the second caller. If this happens before the tags are copied in registerMetric, the first caller will have the name of the first caller and the tags of the second caller.

In this test case, since we add tags to the context one by one for a total of 3. The tags slice will have a length of 3 and a capacity of 4. Because of that we see the behavior described above.

Gauge is called with prefix1 and tag {"name": prefix1}. The append call does not create a new array since the memory is allocated to fit this 1 tag. Then, before the tags are copied, Gauge is called with prefix2 and tag {"name":prefix2}. The amend in this case overwrites the {"name":prefix1} since this is done on the same slice, and then by the time the prefix1 tags are being copied the contents contain {"name":prefix2} and not {"name":prefix1}.


This change is Reviewable

@@ -52,8 +52,11 @@ func AddTags(ctx context.Context, tags ...Tag) context.Context {
if !ok || container == nil {
container = &tagsContainer{}
}
newTags := make(Tags, len(container.Tags), len(container.Tags)+len(tags))
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's use copy for both input slices:

newTags := make(Tags, len(container.Tags)+len(tags))
copy(newTags, container.Tags)
copy(newTags[len(container.Tags):], tags)

Copy link
Contributor

@bmoylan bmoylan left a comment

Choose a reason for hiding this comment

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

Thanks for the root-causing and contribution!

@bulldozer-bot bulldozer-bot bot merged commit 36b323d into palantir:master Aug 16, 2023
64 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants