-
-
Notifications
You must be signed in to change notification settings - Fork 23
Adding metrics information on token usage and performance #120
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
Open
miroovh
wants to merge
1
commit into
thushan:main
Choose a base branch
from
miroovh:metrics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,269 @@ | ||
| package metrics | ||
|
|
||
| import ( | ||
| "sort" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/thushan/olla/internal/core/ports" | ||
| ) | ||
|
|
||
| const ( | ||
| // DefaultRingBufferSize stores the last N requests for querying | ||
| DefaultRingBufferSize = 4096 | ||
|
|
||
| // DefaultChannelSize is the buffer size for the async metrics channel | ||
| DefaultChannelSize = 256 | ||
| ) | ||
|
|
||
| // RequestCollector receives RequestMetrics asynchronously via a channel and stores them | ||
| // in a ring buffer for querying. Aggregated stats are computed on demand. | ||
| // | ||
| // Thread-safe and non-blocking on the producer side — the proxy hot path | ||
| // only does a non-blocking channel send. | ||
| type RequestCollector struct { | ||
| ring []RequestMetrics | ||
| ringMu sync.RWMutex | ||
| ringPos int | ||
| ringLen int | ||
| ringCap int | ||
|
|
||
| ch chan RequestMetrics | ||
| done chan struct{} | ||
| } | ||
|
|
||
| // NewRequestCollector creates a new metrics collector with default settings. | ||
| func NewRequestCollector() *RequestCollector { | ||
| return NewRequestCollectorWithConfig(DefaultRingBufferSize, DefaultChannelSize) | ||
| } | ||
|
|
||
| // NewRequestCollectorWithConfig creates a new metrics collector with custom sizes. | ||
| func NewRequestCollectorWithConfig(ringSize, channelSize int) *RequestCollector { | ||
| c := &RequestCollector{ | ||
| ring: make([]RequestMetrics, ringSize), | ||
| ringCap: ringSize, | ||
| ch: make(chan RequestMetrics, channelSize), | ||
| done: make(chan struct{}), | ||
| } | ||
| go c.consumeLoop() | ||
| return c | ||
| } | ||
|
|
||
| // RecordRequestMetrics implements ports.RequestMetricsRecorder. | ||
| // Non-blocking: if the channel is full, the event is dropped silently | ||
| // to avoid backpressure on the proxy hot path. | ||
| func (c *RequestCollector) RecordRequestMetrics(event ports.RequestMetricsEvent) { | ||
| select { | ||
| case c.ch <- event: | ||
| default: | ||
| // Channel full — drop the metric rather than block the proxy | ||
| } | ||
| } | ||
|
|
||
| // consumeLoop runs in a dedicated goroutine, draining the channel into the ring buffer. | ||
| func (c *RequestCollector) consumeLoop() { | ||
| for { | ||
| select { | ||
| case m := <-c.ch: | ||
| c.ringMu.Lock() | ||
| c.ring[c.ringPos] = m | ||
| c.ringPos = (c.ringPos + 1) % c.ringCap | ||
| if c.ringLen < c.ringCap { | ||
| c.ringLen++ | ||
| } | ||
| c.ringMu.Unlock() | ||
| case <-c.done: | ||
| return | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Shutdown stops the consumer goroutine. | ||
| func (c *RequestCollector) Shutdown() { | ||
| close(c.done) | ||
| } | ||
|
|
||
| // GetRecentRequests returns the last N request metrics, most recent first. | ||
| func (c *RequestCollector) GetRecentRequests(limit int) []RequestMetrics { | ||
| c.ringMu.RLock() | ||
| defer c.ringMu.RUnlock() | ||
|
|
||
| if limit <= 0 || limit > c.ringLen { | ||
| limit = c.ringLen | ||
| } | ||
| if limit == 0 { | ||
| return nil | ||
| } | ||
|
|
||
| result := make([]RequestMetrics, limit) | ||
| pos := c.ringPos | ||
| for i := 0; i < limit; i++ { | ||
| pos-- | ||
| if pos < 0 { | ||
| pos = c.ringCap - 1 | ||
| } | ||
| result[i] = c.ring[pos] | ||
| } | ||
| return result | ||
| } | ||
|
|
||
| // GetAggregatedStats computes summary statistics from the ring buffer. | ||
| // Optionally filtered by time window (zero time = no filter). | ||
| func (c *RequestCollector) GetAggregatedStats(since time.Time) *AggregatedStats { | ||
| c.ringMu.RLock() | ||
| defer c.ringMu.RUnlock() | ||
|
|
||
| stats := &AggregatedStats{ | ||
| ByModel: make(map[string]*ModelAggregatedStats), | ||
| ByEndpoint: make(map[string]*EndpointAggregatedStats), | ||
| WindowEnd: time.Now(), | ||
| } | ||
|
|
||
| if c.ringLen == 0 { | ||
| stats.WindowStart = stats.WindowEnd | ||
| return stats | ||
| } | ||
|
|
||
| var ttftValues []int64 | ||
| var durationValues []int64 | ||
| var tpsSum float64 | ||
| var tpsCount int64 | ||
|
|
||
| // Iterate ring buffer | ||
| pos := c.ringPos | ||
| for i := 0; i < c.ringLen; i++ { | ||
| pos-- | ||
| if pos < 0 { | ||
| pos = c.ringCap - 1 | ||
| } | ||
| m := c.ring[pos] | ||
|
|
||
| // Time filter | ||
| if !since.IsZero() && m.StartTime.Before(since) { | ||
| continue | ||
| } | ||
|
|
||
| // Track window bounds | ||
| if stats.WindowStart.IsZero() || m.StartTime.Before(stats.WindowStart) { | ||
| stats.WindowStart = m.StartTime | ||
| } | ||
|
|
||
| stats.TotalRequests++ | ||
| if m.Success { | ||
| stats.SuccessfulRequests++ | ||
| } else { | ||
| stats.FailedRequests++ | ||
| } | ||
| if m.IsStreaming { | ||
| stats.StreamingRequests++ | ||
| } | ||
|
|
||
| stats.TotalInputTokens += int64(m.InputTokens) | ||
| stats.TotalOutputTokens += int64(m.OutputTokens) | ||
|
|
||
| if m.TTFTMs > 0 { | ||
| ttftValues = append(ttftValues, m.TTFTMs) | ||
| } | ||
| durationValues = append(durationValues, m.TotalDurationMs) | ||
|
|
||
| if m.TokensPerSecond > 0 { | ||
| tpsSum += float64(m.TokensPerSecond) | ||
| tpsCount++ | ||
| } | ||
|
|
||
| // Per-model stats | ||
| if m.Model != "" { | ||
| ms, ok := stats.ByModel[m.Model] | ||
| if !ok { | ||
| ms = &ModelAggregatedStats{} | ||
| stats.ByModel[m.Model] = ms | ||
| } | ||
| ms.TotalRequests++ | ||
| ms.TotalInputTokens += int64(m.InputTokens) | ||
| ms.TotalOutputTokens += int64(m.OutputTokens) | ||
| ms.AvgTTFTMs += m.TTFTMs | ||
| ms.AvgDurationMs += m.TotalDurationMs | ||
| if m.TokensPerSecond > 0 { | ||
| ms.AvgTokensPerSec += float64(m.TokensPerSecond) | ||
| } | ||
| } | ||
|
|
||
| // Per-endpoint stats | ||
| if m.EndpointName != "" { | ||
| es, ok := stats.ByEndpoint[m.EndpointName] | ||
| if !ok { | ||
| es = &EndpointAggregatedStats{} | ||
| stats.ByEndpoint[m.EndpointName] = es | ||
| } | ||
| es.TotalRequests++ | ||
| es.TotalInputTokens += int64(m.InputTokens) | ||
| es.TotalOutputTokens += int64(m.OutputTokens) | ||
| es.AvgTTFTMs += m.TTFTMs | ||
| es.AvgDurationMs += m.TotalDurationMs | ||
| if m.TokensPerSecond > 0 { | ||
| es.AvgTokensPerSec += float64(m.TokensPerSecond) | ||
| } | ||
| } | ||
|
Comment on lines
+191
to
+206
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same TTFT averaging issue applies to per-endpoint stats. See comment on per-model stats above. The same fix pattern would apply here. 🤖 Prompt for AI Agents |
||
| } | ||
|
|
||
| // Compute averages | ||
| if stats.TotalRequests > 0 { | ||
| stats.TTFTAvgMs = avg(ttftValues) | ||
| stats.TTFTP50Ms = percentile(ttftValues, 50) | ||
| stats.TTFTP95Ms = percentile(ttftValues, 95) | ||
| stats.TTFTP99Ms = percentile(ttftValues, 99) | ||
|
|
||
| stats.DurationAvgMs = avg(durationValues) | ||
| stats.DurationP50Ms = percentile(durationValues, 50) | ||
| stats.DurationP95Ms = percentile(durationValues, 95) | ||
| stats.DurationP99Ms = percentile(durationValues, 99) | ||
| } | ||
|
|
||
| if tpsCount > 0 { | ||
| stats.AvgTokensPerSec = tpsSum / float64(tpsCount) | ||
| } | ||
|
|
||
| // Convert model/endpoint sums to averages | ||
| for _, ms := range stats.ByModel { | ||
| if ms.TotalRequests > 0 { | ||
| ms.AvgTTFTMs /= ms.TotalRequests | ||
| ms.AvgDurationMs /= ms.TotalRequests | ||
| ms.AvgTokensPerSec /= float64(ms.TotalRequests) | ||
| } | ||
| } | ||
| for _, es := range stats.ByEndpoint { | ||
| if es.TotalRequests > 0 { | ||
| es.AvgTTFTMs /= es.TotalRequests | ||
| es.AvgDurationMs /= es.TotalRequests | ||
| es.AvgTokensPerSec /= float64(es.TotalRequests) | ||
| } | ||
| } | ||
|
|
||
| return stats | ||
| } | ||
|
|
||
| func avg(values []int64) int64 { | ||
| if len(values) == 0 { | ||
| return 0 | ||
| } | ||
| var sum int64 | ||
| for _, v := range values { | ||
| sum += v | ||
| } | ||
| return sum / int64(len(values)) | ||
| } | ||
|
|
||
| func percentile(values []int64, pct int) int64 { | ||
| if len(values) == 0 { | ||
| return 0 | ||
| } | ||
| sorted := make([]int64, len(values)) | ||
| copy(sorted, values) | ||
| sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] }) | ||
|
|
||
| idx := (pct * len(sorted)) / 100 | ||
| if idx >= len(sorted) { | ||
| idx = len(sorted) - 1 | ||
| } | ||
| return sorted[idx] | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Per-model TTFT average is skewed by requests with zero TTFT.
AvgTTFTMsaccumulates all values including zeros (non-streaming requests), but divides byTotalRequestsat line 229. This differs from the globalTTFTAvgMswhich only considers non-zero values (lines 164-166, 211). Requests without TTFT data will dilute the per-model average.Consider tracking a separate count for non-zero TTFT entries per model:
Proposed fix sketch
type ModelAggregatedStats struct { // ... + ttftCount int64 // internal counter for averaging } // In accumulation: -ms.AvgTTFTMs += m.TTFTMs +if m.TTFTMs > 0 { + ms.AvgTTFTMs += m.TTFTMs + ms.ttftCount++ +} // In averaging: -ms.AvgTTFTMs /= ms.TotalRequests +if ms.ttftCount > 0 { + ms.AvgTTFTMs /= ms.ttftCount +}🤖 Prompt for AI Agents