Skip to content

fix: prevent slice aliasing in LabelValues.With#1311

Open
Yanhu007 wants to merge 1 commit intogo-kit:masterfrom
Yanhu007:fix/counter-lvs-slice-aliasing
Open

fix: prevent slice aliasing in LabelValues.With#1311
Yanhu007 wants to merge 1 commit intogo-kit:masterfrom
Yanhu007:fix/counter-lvs-slice-aliasing

Conversation

@Yanhu007
Copy link
Copy Markdown

Fixes #1296

Problem

LabelValues.With uses append directly, which reuses the underlying array when spare capacity exists. This causes sibling With calls to overwrite each other's label values:

base := counter.With("a", "1", "b", "2")
c1 := base.With("c", "3", "d", "4")
c2 := base.With("e", "5")
// c2 overwrites c1's backing array: c1 now has ["a","1","b","2","e","5","d","4"]

This affects all metrics types (Counter, Gauge, Histogram) across all providers that use LabelValues.With.

Fix

Allocate a new slice in With to prevent aliasing the parent's backing array:

result := make(LabelValues, len(lvs), len(lvs)+len(labelValues))
copy(result, lvs)
return append(result, labelValues...)

Added a test that verifies sibling With calls don't corrupt each other.

LabelValues.With used append directly, which reuses the underlying
array when capacity is available. This caused sibling With calls
to overwrite each other's label values:

    base := counter.With("a", "1")
    c1 := base.With("b", "2")  // has ["a","1","b","2"]
    c2 := base.With("c", "3")  // overwrites c1 to ["a","1","c","3"]

Fix by allocating a new slice in With to prevent aliasing.
Add test to verify sibling With calls don't corrupt each other.

Fixes go-kit#1296
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.

Potential issue with Counter internal slice management

1 participant