Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(exporter): scope Codex cache subsets to their own token series (#851)

Rudy Mizrahi Celekli9a6326594639
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/codex_series_scope_test.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/codex_series_scope_test.go
new file mode 100644
index 00000000..6c0c814c
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/codex_series_scope_test.go
@@ -0,0 +1,40 @@
+package beaconevent
+
+import (
+ "testing"
+
+ "go.opentelemetry.io/collector/pdata/pmetric"
+)
+
+// One export can hold several Codex series at the same timestamp (a model switch mid-interval).
+// Each input must be reduced by its own series' cache subsets, not by every subset collected then.
+func TestCodexInputSubtractsOnlyItsOwnSeriesCacheCounts(t *testing.T) {
+ metric := pmetric.NewMetric()
+ metric.SetName("codex.turn.token_usage")
+ hist := metric.SetEmptyHistogram()
+ hist.SetAggregationTemporality(pmetric.AggregationTemporalityDelta)
+ for model, values := range map[string]map[string]float64{
+ "alpha": {"input": 120, "cached_input": 90, "cache_write_input": 10},
+ "beta": {"input": 60, "cached_input": 20},
+ } {
+ for tokenType, value := range values {
+ dp := hist.DataPoints().AppendEmpty()
+ dp.SetSum(value)
+ dp.SetCount(1)
+ dp.SetTimestamp(9)
+ dp.Attributes().PutStr("model", model)
+ dp.Attributes().PutStr("token_type", tokenType)
+ }
+ }
+
+ uncached := map[string]int64{}
+ for _, event := range NewConverter(Options{}).EventsFromMetric(map[string]interface{}{"beacon.harness.name": "codex_cli"}, metric) {
+ if event.GenAI == nil || event.GenAI.Usage == nil || event.GenAI.Usage.InputTokens == nil {
+ continue
+ }
+ uncached[event.Model] += *event.GenAI.Usage.InputTokens
+ }
+ if uncached["alpha"] != 20 || uncached["beta"] != 40 {
+ t.Fatalf("uncached input by model = %v, want alpha=20 beta=40", uncached)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
index ab300eea..48daad1f 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
@@ -955,16 +955,16 @@ func (c Converter) eventsFromUsageMetric(resourceAttrs map[string]interface{}, m
var events []Event
// Codex reports input tokens inclusive of both cached_input and
// cache_write_input. Beacon's gen_ai.usage keeps uncached input, cache read,
- // and cache creation disjoint, so reduce input by both per-turn subsets;
- // otherwise totals double-count cached prompt tokens. Returns nil (no-op)
- // for every other usage metric.
- inputSubsetsByTurn := codexInputSubsetsByTimestamp(metric)
+ // and cache creation disjoint, so reduce input by both subsets of the same
+ // series; otherwise totals double-count cached prompt tokens. Returns nil
+ // (no-op) for every other usage metric.
+ inputSubsetsBySeries := codexInputSubsetsBySeries(metric)
adjustValue := func(dpAttrs pcommon.Map, ts pcommon.Timestamp, value float64) float64 {
- if inputSubsetsByTurn == nil {
+ if inputSubsetsBySeries == nil {
return value
}
- if tt := FirstString(AttrsToMap(dpAttrs), "token_type"); strings.EqualFold(tt, "input") {
- subsets := inputSubsetsByTurn[ts.AsTime().UnixNano()]
+ if scope, tokenType := tokenSeriesScope(dpAttrs, ts, codexTokenTypeAttribute); tokenType == "input" {
+ subsets := inputSubsetsBySeries[scope]
if value -= subsets.cached + subsets.cacheWrite; value < 0 {
value = 0
}
@@ -1020,26 +1020,28 @@ type codexInputSubsets struct {
cacheWrite float64
}
-// codexInputSubsetsByTimestamp collects each turn's cached and cache-write
+const codexTokenTypeAttribute = "token_type"
+
+// codexInputSubsetsBySeries collects each series' cached and cache-write
// datapoints so Codex's inclusive input count can be reduced to the canonical
// uncached remainder. Returns nil for every other metric.
-func codexInputSubsetsByTimestamp(metric pmetric.Metric) map[int64]codexInputSubsets {
+func codexInputSubsetsBySeries(metric pmetric.Metric) map[string]codexInputSubsets {
if !strings.EqualFold(strings.TrimSpace(metric.Name()), "codex.turn.token_usage") {
return nil
}
if metric.Type() != pmetric.MetricTypeHistogram {
return nil
}
- out := map[int64]codexInputSubsets{}
+ out := map[string]codexInputSubsets{}
dps := metric.Histogram().DataPoints()
- for i := 0; i < dps.Len(); i++ {
+ for i := range dps.Len() {
dp := dps.At(i)
if !dp.HasSum() {
continue
}
- key := dp.Timestamp().AsTime().UnixNano()
- subsets := out[key]
- switch strings.ToLower(FirstString(AttrsToMap(dp.Attributes()), "token_type")) {
+ scope, tokenType := tokenSeriesScope(dp.Attributes(), dp.Timestamp(), codexTokenTypeAttribute)
+ subsets := out[scope]
+ switch tokenType {
case "cached_input":
subsets.cached += dp.Sum()
case "cache_write_input":
@@ -1047,11 +1049,33 @@ func codexInputSubsetsByTimestamp(metric pmetric.Metric) map[int64]codexInputSub
default:
continue
}
- out[key] = subsets
+ out[scope] = subsets
}
return out
}
+// tokenSeriesScope returns a token-usage datapoint's series identity without its token type,
+// plus the type (lowercased). Every other attribute and the timestamp are part of the identity,
+// so sibling datapoints of one series share a scope while two sessions or two models in one
+// export never do.
+func tokenSeriesScope(attrs pcommon.Map, ts pcommon.Timestamp, typeAttribute string) (string, string) {
+ values := AttrsToMap(attrs)
+ tokenType := strings.ToLower(strings.TrimSpace(FirstString(values, typeAttribute)))
+ keys := make([]string, 0, len(values))
+ for key := range values {
+ if key != typeAttribute {
+ keys = append(keys, key)
+ }
+ }
+ sort.Strings(keys)
+ var b strings.Builder
+ fmt.Fprintf(&b, "%d", ts.AsTime().UnixNano())
+ for _, key := range keys {
+ fmt.Fprintf(&b, "\x00%s=%v", key, values[key])
+ }
+ return b.String(), tokenType
+}
+
func numberDataPointValue(dp pmetric.NumberDataPoint) float64 {
if dp.ValueType() == pmetric.NumberDataPointValueTypeInt {
return float64(dp.IntValue())
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/gemini_usage.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/gemini_usage.go
index 5e2dd28e..93b8f344 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/gemini_usage.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/gemini_usage.go
@@ -1,9 +1,7 @@
package beaconevent
import (
- "fmt"
"math"
- "sort"
"strings"
"go.opentelemetry.io/collector/pdata/pcommon"
@@ -122,7 +120,7 @@ func geminiTokenSeriesByScope(metric pmetric.Metric) geminiTokenSeries {
dps := metric.Sum().DataPoints()
for i := 0; i < dps.Len(); i++ {
dp := dps.At(i)
- scope, tokenType := geminiSeriesScope(dp.Attributes(), dp.Timestamp())
+ scope, tokenType := tokenSeriesScope(dp.Attributes(), dp.Timestamp(), geminiTokenTypeAttribute)
if out[scope] == nil {
out[scope] = map[string]float64{}
}
@@ -131,26 +129,6 @@ func geminiTokenSeriesByScope(metric pmetric.Metric) geminiTokenSeries {
return out
}
-// geminiSeriesScope returns the series identity without its type, plus the type. Every attribute
-// is part of the identity, so two sessions or two models in one export never share siblings.
-func geminiSeriesScope(attrs pcommon.Map, ts pcommon.Timestamp) (string, string) {
- values := AttrsToMap(attrs)
- tokenType := strings.ToLower(strings.TrimSpace(FirstString(values, geminiTokenTypeAttribute)))
- keys := make([]string, 0, len(values))
- for key := range values {
- if key != geminiTokenTypeAttribute {
- keys = append(keys, key)
- }
- }
- sort.Strings(keys)
- var b strings.Builder
- fmt.Fprintf(&b, "%d", ts.AsTime().UnixNano())
- for _, key := range keys {
- fmt.Fprintf(&b, "\x00%s=%v", key, values[key])
- }
- return b.String(), tokenType
-}
-
// apply replaces the usage usageEventFromDataPoint read from one datapoint's own type and value
// with the Gemini reading of it. The event keeps Gemini's type name in gen_ai.token.type, and
// raw.metric_value keeps the value as reported.
@@ -172,7 +150,7 @@ func (series geminiTokenSeries) apply(event *Event, attrs pcommon.Map, ts pcommo
// its own type, which ApplyTokenUsage leaves unmapped (raw only), because its count is already
// folded into the input series.
func (series geminiTokenSeries) adjust(attrs pcommon.Map, ts pcommon.Timestamp, value float64) (float64, string) {
- scope, tokenType := geminiSeriesScope(attrs, ts)
+ scope, tokenType := tokenSeriesScope(attrs, ts, geminiTokenTypeAttribute)
siblings := series[scope]
switch tokenType {
case geminiTokenTypeInput: