Skip to content
Merged
Show file tree
Hide file tree
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
5 changes: 4 additions & 1 deletion internal/runtime/usage_aggregate.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package runtime

import (
"math"
"sort"
"strings"
"sync"
Expand Down Expand Up @@ -119,7 +120,9 @@ func (t *ToolUsage) Percentile(p float64) (ms int64, exceeds bool) {
if total == 0 {
return 0, false
}
target := int64(float64(total) * p)
// Nearest-rank: truncating would land one rank low for small totals and
// hide the slow tail (9 fast calls + 1 slow one would report p95 as fast).
target := int64(math.Ceil(float64(total) * p))
if target < 1 {
target = 1
}
Expand Down
20 changes: 20 additions & 0 deletions internal/runtime/usage_percentile_rank_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package runtime

import "testing"

// Nearest-rank p95 of 10 calls is the 10th fastest (ceil(9.5)); truncating to
// rank 9 reported nine fast calls plus one 3 s call as a ~30 ms p95.
func TestToolUsagePercentile_SmallTotalsUseNearestRank(t *testing.T) {
tu := &ToolUsage{LatencyBuckets: make([]int64, len(latencyBucketBoundsMs)+1)}
for i := 0; i < 9; i++ {
tu.LatencyBuckets[latencyBucketIndex(30)]++
}
tu.LatencyBuckets[latencyBucketIndex(3000)]++

if got, _ := tu.Percentile(0.95); got != 5000 {
t.Errorf("p95 = %d ms, want 5000 (bucket holding the 3000 ms call)", got)
}
if got, _ := tu.Percentile(0.50); got != 50 {
t.Errorf("p50 = %d ms, want 50", got)
}
}
Loading