profile: keep samples with non-zero unscaled values in ScaleN (#1070)
* profile: keep samples with non-zero unscaled values in ScaleN
ScaleN decided whether to keep a sample by looking only at the values
it scaled. A sample whose scaled values round to zero was dropped even
when a value with ratio 1 was non-zero, although the doc comment says
that only samples without any non-zero value are dropped. This loses
samples when merging profiles whose units differ, with -diff_base and
with -normalize.
Check every value after scaling. Add TestScaleN, and make
TestNormalizeByDifferentProfile check the number of samples and expect
the {0, 10} sample that was dropped.
* profile: shorten the TestScaleN doc comment
diff --git a/profile/profile.go b/profile/profile.go
index 71f9bae..7a713a0 100644
--- a/profile/profile.go
+++ b/profile/profile.go
@@ -809,10 +809,9 @@
keepSample := false
for i, v := range s.Value {
if ratios[i] != 1 {
- val := int64(math.Round(float64(v) * ratios[i]))
- s.Value[i] = val
- keepSample = keepSample || val != 0
+ s.Value[i] = int64(math.Round(float64(v) * ratios[i]))
}
+ keepSample = keepSample || s.Value[i] != 0
}
if keepSample {
p.Sample[fillIdx] = s
diff --git a/profile/profile_test.go b/profile/profile_test.go
index 3089747..4cd036a 100644
--- a/profile/profile_test.go
+++ b/profile/profile_test.go
@@ -827,6 +827,59 @@
}
}
+// TestScaleN tests ScaleN().
+func TestScaleN(t *testing.T) {
+ for _, tc := range []struct {
+ desc string
+ ratios []float64
+ wantSamples [][]int64
+ }{
+ {
+ desc: "unscaled non-zero values keep samples",
+ ratios: []float64{1, 0.0001},
+ wantSamples: [][]int64{
+ {1000, 0},
+ {100, 0},
+ {10, 0},
+ {10000, 1},
+ {1, 0},
+ },
+ },
+ {
+ desc: "scaled non-zero values keep samples",
+ ratios: []float64{0.0001, 1},
+ wantSamples: [][]int64{
+ {0, 1000},
+ {0, 100},
+ {0, 10},
+ {1, 10000},
+ {0, 1},
+ },
+ },
+ {
+ desc: "samples with all values scaled to zero are dropped",
+ ratios: []float64{0.0001, 0.0001},
+ wantSamples: [][]int64{
+ {1, 1},
+ },
+ },
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ p := testProfile1.Copy()
+ if err := p.ScaleN(tc.ratios); err != nil {
+ t.Fatalf("ScaleN(%v) = %v", tc.ratios, err)
+ }
+ var gotSamples [][]int64
+ for _, s := range p.Sample {
+ gotSamples = append(gotSamples, s.Value)
+ }
+ if !reflect.DeepEqual(gotSamples, tc.wantSamples) {
+ t.Errorf("ScaleN(%v) got sample values %v, want %v", tc.ratios, gotSamples, tc.wantSamples)
+ }
+ })
+ }
+}
+
// TestMergeMain tests merge leaves the main binary in place.
func TestMergeMain(t *testing.T) {
prof := testProfile1.Copy()
@@ -1052,10 +1105,14 @@
expectedSampleValues := [][]int64{
{20, 1000},
{2, 100},
+ {0, 10},
{199, 10000},
{0, 1},
}
+ if got, want := len(p.Sample), len(expectedSampleValues); got != want {
+ t.Fatalf("got %d samples, want %d", got, want)
+ }
for i, s := range p.Sample {
for j, v := range s.Value {
if v != expectedSampleValues[i][j] {