You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2026/09/07 07:12:08 UTC
(skywalking-ai-sessionizer) branch main updated: Hold the derived token metric to a capture of Claude Code's own exporter
This is an automated email from the ASF dual-hosted git repository.
wu-sheng pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-ai-sessionizer.git
The following commit(s) were added to refs/heads/main by this push:
new 9f1795e Hold the derived token metric to a capture of Claude Code's own exporter
9f1795e is described below
commit 9f1795ec5fb36e1fd7e4f928a38afaaef4f6c75e
Author: Wu Sheng <wu...@foxmail.com>
AuthorDate: Mon Sep 7 15:10:51 2026 +0800
Hold the derived token metric to a capture of Claude Code's own exporter
The parity fixture the review asked for: what Claude Code 2.1.260 sent to
asz's receiver from one short non-interactive Opus session, over gRPC,
kept under internal/metrics/testdata with every value naming a person, an
account, an organisation or a session replaced. It settled what the
documentation had taken from the runtime's manual: the exporter's token
points are doubles, it writes a point for every type, zero included, the
auxiliary call is the Haiku call that names a session, terminal.type and
effort are labels a transcript never carries, the resource carries the
host and operating system, and the scope is com.anthropic.claude_code
versioned as the runtime.
The derivation now writes doubles and a point for every type as the
exporter does, and a test holds a derived request to the capture: the
same name, unit, description, kind, value encoding and token types, the
same session, model, query source and type labels, and a difference that
is exactly the labels and the metrics the export page lists as not
derived. A newer runtime that sends another label or metric fails that
test, and the page is updated. tools/otlpdump prints a spooled request as
the protocol's JSON, redacted when asked, which is how the fixture was
made and how another capture is read.
---
CLAUDE.md | 2 +-
docs/en/adapters/claude-code.md | 10 +-
docs/en/changes/changes-0.3.0.md | 7 +
docs/en/setup/export-otlp.md | 16 +-
internal/metrics/metrics.go | 28 +-
internal/metrics/metrics_test.go | 31 +-
internal/metrics/parity_test.go | 199 +++++
.../testdata/claude-code-2.1.260-metrics.json | 826 +++++++++++++++++++++
.../testdata/claude-code-2.1.260-metrics.pb | Bin 0 -> 3840 bytes
.../testdata/claude-code-2.1.260-session.json | 115 +++
.../testdata/claude-code-2.1.260-session.pb | Bin 0 -> 502 bytes
internal/scenario/run/push.go | 8 +-
otlpdump | Bin 0 -> 16030290 bytes
tools/collectorcheck/main.go | 10 +-
tools/otlpdump/main.go | 106 +++
15 files changed, 1329 insertions(+), 29 deletions(-)
diff --git a/CLAUDE.md b/CLAUDE.md
index 80c57e8..23152c8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -64,7 +64,7 @@ internal/verify/ contiguity and digest checks over landed data
internal/view/ reads a conversation and serves it as a page
internal/view/conversation-view/ Horizon's conversation renderer, built from the pinned commit in HORIZON_COMMIT; never edited here
internal/export/otlp/ sends landed files and rounds to an OpenTelemetry logs receiver, one record per file, and the metrics spool
-internal/metrics/ derives the runtime's own metric family from landed Session Data into the spool; collector side
+internal/metrics/ derives the runtime's token metric from landed Session Data into the spool; collector side; testdata holds a redacted capture of the runtime's exporter
internal/repack/ re-cuts landed files into a new root under another budget
internal/adapters/claudecode/ the claude-code-local adapter
internal/adapters/claudecodeotlp/ the claude-code-otlp adapter: a receiver for the runtime's own exporter, metrics into the spool
diff --git a/docs/en/adapters/claude-code.md b/docs/en/adapters/claude-code.md
index 58e650c..4587f07 100644
--- a/docs/en/adapters/claude-code.md
+++ b/docs/en/adapters/claude-code.md
@@ -326,10 +326,12 @@ family from what it landed, under the exporter's metric name, so a receiver hold
whichever produced the points. Phase one is `claude_code.token.usage`: the usage of a call is its
last fragment's in line order, as the assembler reads it, and only a finished call counts;
`query_source` is `main` for the session's own transcript and `subagent` for a child's; `model`
-is `message.model`; `session.id` is the session. The exporter's account, organisation, speed,
-effort and attribution labels are not on a transcript and are not added, and neither are its
-auxiliary calls. Points are monotonic delta sums per minute whose windows never overlap, and a
-call is counted once however many landed files its records reach.
+is `message.model`; `session.id` is the session. The exporter's account, organisation, terminal,
+speed, effort and attribution labels are not on a transcript and are not added, and neither are
+its auxiliary calls. Points are monotonic delta sums per minute whose windows never overlap, a
+double for every type as the exporter writes them, and a call is counted once however many
+landed files its records reach. A capture of the exporter's own request is the parity fixture
+the derivation is tested against.
What the transcripts do not carry is not derived: cost, per-request latency, tool execution time,
active time, lines of code, commits, pull requests, the session start type, and the tokens of the
diff --git a/docs/en/changes/changes-0.3.0.md b/docs/en/changes/changes-0.3.0.md
index 2816884..131fea0 100644
--- a/docs/en/changes/changes-0.3.0.md
+++ b/docs/en/changes/changes-0.3.0.md
@@ -43,6 +43,13 @@
- A receiver's partial success is a success the protocol says not to retry: the rejected records
or points are counted on the pass line as `rejected`, and the files are marked sent.
+- A capture of what Claude Code 2.1.260 itself sent to the receiver, with every identifying value
+ replaced, is the parity fixture: a test holds the derived token metric to it, the same name,
+ unit, description, kind, value encoding and token types, the same session, model, query source
+ and type labels, and a difference that is exactly the labels and metrics the export page lists
+ as not derived. The derivation now writes doubles and a point for every type, zero included, as
+ the exporter does. `tools/otlpdump` prints a spooled request as the protocol's JSON.
+
- `claude-code-otlp` is a second adapter for the runtime: an OpenTelemetry receiver its own
exporter is pointed at, gRPC and HTTP with protobuf on one `listen` port. Phase one lands the
metrics requests it receives in the same spool, bytes as received, for `asz push`; logs and
diff --git a/docs/en/setup/export-otlp.md b/docs/en/setup/export-otlp.md
index fe59c14..9c371b7 100644
--- a/docs/en/setup/export-otlp.md
+++ b/docs/en/setup/export-otlp.md
@@ -137,14 +137,20 @@ copy of it, and this table says exactly which part:
| | The runtime's exporter | Derived from the transcripts |
| --- | --- | --- |
| metric | `claude_code.token.usage`, `Number of tokens used`, unit `tokens`, a monotonic delta sum | the same name, description, unit and kind |
-| `type` | `input`, `output`, `cacheRead`, `cacheCreation` | the same four |
-| `query_source` | `main`, `subagent`, `auxiliary` | `main` and `subagent`, from the stream the call was made on; the auxiliary calls never reach a transcript |
+| `type` | `input`, `output`, `cacheRead`, `cacheCreation`, a point for each even when zero | the same four, zero included |
+| `query_source` | `main`, `subagent`, `auxiliary` | `main` and `subagent`, from the stream the call was made on; the auxiliary calls, such as the Haiku call that names a session, never reach a transcript |
| `model`, `session.id` | yes | yes |
-| account, organisation, user, `speed`, `effort`, agent, skill, plugin and MCP attribution | yes | no; a transcript does not carry them |
+| `user.id`, `user.email`, `user.account_uuid`, `user.account_id`, `organization.id`, `terminal.type`, `effort`, `speed`, and the agent, skill, plugin and MCP attribution | yes | no; a transcript does not carry them |
| the other seven metrics: cost, active time, lines of code, commits, pull requests, sessions started, edit decisions | yes | no, and never estimated |
-| instrumentation scope | `com.anthropic.claude_code` | asz's own, so a receiver that keys on the scope sees two streams of one name; the OAP keys on the name and the labels |
+| resource | `service.name` `claude-code`, `service.version`, `host.arch`, `os.type`, `os.version` | `service.name` `claude-code`; asz normalises both on the way out |
+| instrumentation scope | `com.anthropic.claude_code`, versioned as the runtime | asz's own, so a receiver that keys on the scope sees two streams of one name; the OAP keys on the name and the labels |
| a point's window | the exporter's export interval, wall clock | the minute the call's last fragment ended, see below |
-| value | as the exporter encodes it | an integer |
+| value | a double | a double |
+
+The right-hand column is held to a capture of what Claude Code 2.1.260 sent to asz's receiver
+from one short session, kept under `internal/metrics/testdata` with every identifying value
+replaced, by a test that fails when the exporter sends a label or a metric this table does not
+account for. `go run ./tools/otlpdump -redact FILE.pb` prints any spooled request the same way.
With `metrics: true` on the `claude-code-local` adapter, the collector derives the points from
the landed files by the assembler's own rule: the usage of a call is its last fragment's in line
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go
index e5d818c..cb1783e 100644
--- a/internal/metrics/metrics.go
+++ b/internal/metrics/metrics.go
@@ -92,6 +92,24 @@ const (
TypeCacheCreation = "cacheCreation"
)
+// Labels the exporter puts on its token points that a transcript cannot
+// supply, so the derivation leaves them out. The parity test holds the
+// difference between the derived point and a captured one to this list.
+var NotDerivedLabels = []string{
+ "user.id", "user.email", "user.account_uuid", "user.account_id", "organization.id",
+ "terminal.type", "effort", "speed",
+ "agent.name", "skill.name", "plugin.name", "marketplace.name", "mcp_server.name", "mcp_tool.name",
+}
+
+// NotDerivedMetrics are the exporter's other metrics, which a transcript
+// cannot supply and which are never estimated. The parity test fails when
+// a capture carries a metric that is on neither list.
+var NotDerivedMetrics = []string{
+ "claude_code.session.count", "claude_code.lines_of_code.count", "claude_code.pull_request.count",
+ "claude_code.commit.count", "claude_code.cost.usage", "claude_code.code_edit_tool.decision",
+ "claude_code.active_time.total",
+}
+
// The query sources the transcripts can tell apart. The exporter's third,
// auxiliary, is a call that never reaches a transcript.
const (
@@ -392,13 +410,13 @@ func deriveFile(lf storage.LandedFile, next *storage.LandedFile, since time.Time
if !since.IsZero() && minute.Add(time.Minute).Before(since) {
continue
}
+ // A point for every type, zero included: the exporter writes all
+ // four for each call, and a receiver reading one family should not
+ // see a type appear and vanish by source.
for typ, n := range map[string]int{
TypeInput: c.usage.Input, TypeOutput: c.usage.Output,
TypeCacheRead: c.usage.CacheRead, TypeCacheCreation: c.usage.CacheWrite,
} {
- if n == 0 {
- continue
- }
k := point{series: series{model: c.model, source: c.source, typ: typ}, session: hdr.Session, minute: minute}
sums[k] += int64(n)
}
@@ -499,11 +517,13 @@ func request(points []point, version string) *collmetricspb.ExportMetricsService
if p.series.model != "" {
attrs = append(attrs, str("model", p.series.model))
}
+ // A double, as the exporter's SDK encodes its counters, so a
+ // receiver reads one value kind from both sources.
dps = append(dps, &metricspb.NumberDataPoint{
Attributes: attrs,
StartTimeUnixNano: uint64(p.start.UnixNano()),
TimeUnixNano: uint64(p.end.UnixNano()),
- Value: &metricspb.NumberDataPoint_AsInt{AsInt: p.value},
+ Value: &metricspb.NumberDataPoint_AsDouble{AsDouble: float64(p.value)},
})
}
return &collmetricspb.ExportMetricsServiceRequest{ResourceMetrics: []*metricspb.ResourceMetrics{{
diff --git a/internal/metrics/metrics_test.go b/internal/metrics/metrics_test.go
index fc119f0..42f6fc1 100644
--- a/internal/metrics/metrics_test.go
+++ b/internal/metrics/metrics_test.go
@@ -115,7 +115,7 @@ func aged(t *testing.T, path string, at time.Time) {
}
type got struct {
- value int64
+ value float64
start, end time.Time
}
@@ -153,7 +153,10 @@ func points(t *testing.T, z *storage.Zone) (map[string][]got, int) {
for _, dp := range sum.DataPoints {
a := otlptest.Attrs(dp.Attributes)
k := a["query_source"] + "/" + a["type"] + "/" + a["model"] + "#" + a["session.id"]
- out[k] = append(out[k], got{value: dp.GetAsInt(), start: time.Unix(0, int64(dp.StartTimeUnixNano)).UTC(), end: time.Unix(0, int64(dp.TimeUnixNano)).UTC()})
+ if _, ok := dp.Value.(*metricspb.NumberDataPoint_AsDouble); !ok {
+ t.Fatalf("a derived point is not a double, as the exporter encodes its counters")
+ }
+ out[k] = append(out[k], got{value: dp.GetAsDouble(), start: time.Unix(0, int64(dp.StartTimeUnixNano)).UTC(), end: time.Unix(0, int64(dp.TimeUnixNano)).UTC()})
}
}
}
@@ -162,14 +165,26 @@ func points(t *testing.T, z *storage.Zone) (map[string][]got, int) {
return out, len(files)
}
-func total(ps []got) int64 {
- var n int64
+func total(ps []got) float64 {
+ var n float64
for _, p := range ps {
n += p.value
}
return n
}
+// nonzero keeps the series that carry tokens: the exporter and the
+// derivation both write a point for every type, zero included.
+func nonzero(m map[string][]got) map[string][]got {
+ out := map[string][]got{}
+ for k, ps := range m {
+ if total(ps) != 0 {
+ out[k] = ps
+ }
+ }
+ return out
+}
+
var base = time.Date(2026, 9, 7, 10, 0, 0, 0, time.UTC)
func deriver(z *storage.Zone, now time.Time, opts metrics.Options) *metrics.Deriver {
@@ -202,7 +217,7 @@ func TestUsageIsTheLastFragmentOfAFinishedCall(t *testing.T) {
t.Fatalf("derived %d files into %d requests, want 2 and 2", st.Files, st.Requests)
}
got, _ := points(t, z)
- want := map[string]int64{
+ want := map[string]float64{
"main/input/claude-opus-5#s1": 15, "main/output/claude-opus-5#s1": 120,
"main/cacheRead/claude-opus-5#s1": 1900, "main/cacheCreation/claude-opus-5#s1": 50,
"main/input/claude-sonnet-5#s1": 7, "main/output/claude-sonnet-5#s1": 30,
@@ -210,11 +225,11 @@ func TestUsageIsTheLastFragmentOfAFinishedCall(t *testing.T) {
}
for k, v := range want {
if total(got[k]) != v {
- t.Fatalf("%s = %d, want %d; all: %v", k, total(got[k]), v, got)
+ t.Fatalf("%s = %v, want %v; all: %v", k, total(got[k]), v, got)
}
}
- if len(got) != len(want) {
- t.Fatalf("%d series, want %d: an unfinished call must not count: %v", len(got), len(want), got)
+ if len(nonzero(got)) != len(want) {
+ t.Fatalf("%d series with tokens, want %d: an unfinished call must not count: %v", len(nonzero(got)), len(want), got)
}
// A second pass derives nothing; a new file is derived whole.
if st, err = d.Pass(nil); err != nil || st.Files != 0 || st.Requests != 0 {
diff --git a/internal/metrics/parity_test.go b/internal/metrics/parity_test.go
new file mode 100644
index 0000000..0a50c1f
--- /dev/null
+++ b/internal/metrics/parity_test.go
@@ -0,0 +1,199 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package metrics_test
+
+import (
+ "os"
+ "path/filepath"
+ "sort"
+ "testing"
+ "time"
+
+ collmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
+ metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
+ "google.golang.org/protobuf/proto"
+
+ "github.com/apache/skywalking-ai-sessionizer/internal/export/otlp/otlptest"
+ "github.com/apache/skywalking-ai-sessionizer/internal/metrics"
+ "github.com/apache/skywalking-ai-sessionizer/internal/storage"
+)
+
+// The parity fixture: what Claude Code 2.1.260 sent to asz's receiver from
+// one short non-interactive Opus session on 2026-09-07, over gRPC, with
+// the values of every attribute naming a person, an account, an
+// organisation or a session replaced. testdata/claude-code-2.1.260-metrics.json
+// is the same request as the protocol's JSON.
+func capture(t *testing.T) *collmetricspb.ExportMetricsServiceRequest {
+ t.Helper()
+ data, err := os.ReadFile(filepath.Join("testdata", "claude-code-2.1.260-metrics.pb"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var req collmetricspb.ExportMetricsServiceRequest
+ if err := proto.Unmarshal(data, &req); err != nil {
+ t.Fatal(err)
+ }
+ return &req
+}
+
+func find(req *collmetricspb.ExportMetricsServiceRequest, name string) *metricspb.Metric {
+ for _, rm := range req.ResourceMetrics {
+ for _, sm := range rm.ScopeMetrics {
+ for _, m := range sm.Metrics {
+ if m.Name == name {
+ return m
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func keysOf(dp *metricspb.NumberDataPoint) []string {
+ var out []string
+ for _, kv := range dp.Attributes {
+ out = append(out, kv.Key)
+ }
+ sort.Strings(out)
+ return out
+}
+
+func contains(list []string, s string) bool {
+ for _, x := range list {
+ if x == s {
+ return true
+ }
+ }
+ return false
+}
+
+// What the derivation writes matches the exporter's token metric where the
+// export page says it does, and differs exactly where the page says it
+// differs: the same name, description, unit, temporality, monotonicity,
+// value kind and token types; the same session, model, query source and
+// type labels; and, missing from a derived point, only the labels the
+// page lists as not derived. Every other metric the exporter sent is on
+// the page's list of metrics not derived. A newer runtime that sends
+// another label or another metric fails here, and the page is updated.
+func TestDerivedPointsMatchTheCapturedExporter(t *testing.T) {
+ theirs := find(capture(t), metrics.TokenUsage)
+ if theirs == nil {
+ t.Fatal("the capture carries no token metric")
+ }
+
+ z := storage.NewZone(t.TempDir())
+ land(t, z, "s1", "main", 1, []call{{id: "c1", model: "claude-opus-5", at: base, frags: 2, in: 2, out: 4, read: 0, wr: 0}})
+ d := deriver(z, base.Add(time.Hour), metrics.Options{})
+ if _, err := d.Pass(nil); err != nil {
+ t.Fatal(err)
+ }
+ files, _ := storage.NewSpool(z).List()
+ data, err := os.ReadFile(files[0].Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var mine collmetricspb.ExportMetricsServiceRequest
+ if err := proto.Unmarshal(data, &mine); err != nil {
+ t.Fatal(err)
+ }
+ ours := find(&mine, metrics.TokenUsage)
+ if ours == nil {
+ t.Fatal("the derivation wrote no token metric")
+ }
+
+ // The metric itself.
+ if ours.Name != theirs.Name || ours.Unit != theirs.Unit || ours.Description != theirs.Description {
+ t.Fatalf("metric: derived %q %q %q, exporter %q %q %q", ours.Name, ours.Unit, ours.Description, theirs.Name, theirs.Unit, theirs.Description)
+ }
+ if ours.GetSum().GetAggregationTemporality() != theirs.GetSum().GetAggregationTemporality() || ours.GetSum().GetIsMonotonic() != theirs.GetSum().GetIsMonotonic() {
+ t.Fatalf("sum: derived %v %v, exporter %v %v", ours.GetSum().GetAggregationTemporality(), ours.GetSum().GetIsMonotonic(), theirs.GetSum().GetAggregationTemporality(), theirs.GetSum().GetIsMonotonic())
+ }
+
+ // The points: value kind, the token types, and the labels.
+ theirTypes, theirSources, theirKeys := map[string]bool{}, map[string]bool{}, map[string]bool{}
+ for _, dp := range theirs.GetSum().GetDataPoints() {
+ if _, ok := dp.GetValue().(*metricspb.NumberDataPoint_AsDouble); !ok {
+ t.Fatalf("the exporter's point is not a double: %v", dp.GetValue())
+ }
+ a := otlptest.Attrs(dp.Attributes)
+ theirTypes[a["type"]] = true
+ theirSources[a["query_source"]] = true
+ for _, k := range keysOf(dp) {
+ theirKeys[k] = true
+ }
+ }
+ ourTypes := map[string]bool{}
+ for _, dp := range ours.GetSum().GetDataPoints() {
+ if _, ok := dp.GetValue().(*metricspb.NumberDataPoint_AsDouble); !ok {
+ t.Fatalf("a derived point is not a double, as the exporter's are")
+ }
+ a := otlptest.Attrs(dp.Attributes)
+ ourTypes[a["type"]] = true
+ if !theirSources[a["query_source"]] {
+ t.Fatalf("a derived point names query_source %q, which the exporter never sent", a["query_source"])
+ }
+ for _, k := range keysOf(dp) {
+ if !theirKeys[k] {
+ t.Fatalf("a derived point carries %q, a label the exporter does not send", k)
+ }
+ }
+ // Every label the exporter sends and the derivation does not is on
+ // the export page's list, and nothing on that list is derived.
+ for k := range theirKeys {
+ if !contains(keysOf(dp), k) && !contains(metrics.NotDerivedLabels, k) {
+ t.Fatalf("the exporter sends %q and the derivation does not, and the export page does not say so", k)
+ }
+ if contains(keysOf(dp), k) && contains(metrics.NotDerivedLabels, k) {
+ t.Fatalf("%q is derived and listed as not derived", k)
+ }
+ }
+ }
+ for typ := range theirTypes {
+ if !ourTypes[typ] {
+ t.Fatalf("the exporter sends type %q and the derivation does not", typ)
+ }
+ }
+ for typ := range ourTypes {
+ if !theirTypes[typ] {
+ t.Fatalf("the derivation writes type %q, which the exporter never sent", typ)
+ }
+ }
+ // The exporter's auxiliary calls never reach a transcript; the capture
+ // has one, so the page's claim about them stays measured.
+ if !theirSources["auxiliary"] {
+ t.Fatal("the capture carries no auxiliary call; the page's claim about them is no longer measured")
+ }
+
+ // Every other metric in the capture is one the page says is not derived.
+ for _, rm := range capture(t).ResourceMetrics {
+ for _, sm := range rm.ScopeMetrics {
+ if sm.GetScope().GetName() != "com.anthropic.claude_code" {
+ t.Fatalf("the exporter's scope is %q; the export page names another", sm.GetScope().GetName())
+ }
+ for _, m := range sm.Metrics {
+ if m.Name != metrics.TokenUsage && !contains(metrics.NotDerivedMetrics, m.Name) {
+ t.Fatalf("the exporter sent %s, which is neither derived nor listed as not derived", m.Name)
+ }
+ }
+ }
+ res := otlptest.Attrs(rm.GetResource().GetAttributes())
+ if res["service.name"] != metrics.RuntimeService {
+ t.Fatalf("the exporter's service is %q; the derivation names %q", res["service.name"], metrics.RuntimeService)
+ }
+ }
+}
diff --git a/internal/metrics/testdata/claude-code-2.1.260-metrics.json b/internal/metrics/testdata/claude-code-2.1.260-metrics.json
new file mode 100644
index 0000000..fd97899
--- /dev/null
+++ b/internal/metrics/testdata/claude-code-2.1.260-metrics.json
@@ -0,0 +1,826 @@
+{
+ "resourceMetrics": [
+ {
+ "resource": {
+ "attributes": [
+ {
+ "key": "host.arch",
+ "value": {
+ "stringValue": "arm64"
+ }
+ },
+ {
+ "key": "os.type",
+ "value": {
+ "stringValue": "darwin"
+ }
+ },
+ {
+ "key": "os.version",
+ "value": {
+ "stringValue": "25.6.0"
+ }
+ },
+ {
+ "key": "service.name",
+ "value": {
+ "stringValue": "claude-code"
+ }
+ },
+ {
+ "key": "service.version",
+ "value": {
+ "stringValue": "2.1.260"
+ }
+ }
+ ]
+ },
+ "scopeMetrics": [
+ {
+ "scope": {
+ "name": "com.anthropic.claude_code",
+ "version": "2.1.260"
+ },
+ "metrics": [
+ {
+ "name": "claude_code.cost.usage",
+ "description": "Cost of the Claude Code session",
+ "unit": "USD",
+ "sum": {
+ "dataPoints": [
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-haiku-4-5-20251001"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "auxiliary"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764583456000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 0.000954
+ },
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-opus-5"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "main"
+ }
+ },
+ {
+ "key": "effort",
+ "value": {
+ "stringValue": "xhigh"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764584487000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 0.1340525
+ }
+ ],
+ "aggregationTemporality": "AGGREGATION_TEMPORALITY_DELTA",
+ "isMonotonic": true
+ }
+ },
+ {
+ "name": "claude_code.token.usage",
+ "description": "Number of tokens used",
+ "unit": "tokens",
+ "sum": {
+ "dataPoints": [
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-haiku-4-5-20251001"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "auxiliary"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "input"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764583457000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 899
+ },
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-haiku-4-5-20251001"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "auxiliary"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "output"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764583457000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 11
+ },
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-haiku-4-5-20251001"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "auxiliary"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "cacheRead"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764583457000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 0
+ },
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-haiku-4-5-20251001"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "auxiliary"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "cacheCreation"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764583457000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 0
+ },
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-opus-5"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "main"
+ }
+ },
+ {
+ "key": "effort",
+ "value": {
+ "stringValue": "xhigh"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "input"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764584487000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 2
+ },
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-opus-5"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "main"
+ }
+ },
+ {
+ "key": "effort",
+ "value": {
+ "stringValue": "xhigh"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "output"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764584487000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 4
+ },
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-opus-5"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "main"
+ }
+ },
+ {
+ "key": "effort",
+ "value": {
+ "stringValue": "xhigh"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "cacheRead"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764584487000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 22965
+ },
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "model",
+ "value": {
+ "stringValue": "claude-opus-5"
+ }
+ },
+ {
+ "key": "query_source",
+ "value": {
+ "stringValue": "main"
+ }
+ },
+ {
+ "key": "effort",
+ "value": {
+ "stringValue": "xhigh"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "cacheCreation"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764584487000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 12246
+ }
+ ],
+ "aggregationTemporality": "AGGREGATION_TEMPORALITY_DELTA",
+ "isMonotonic": true
+ }
+ },
+ {
+ "name": "claude_code.active_time.total",
+ "description": "Total active time in seconds",
+ "unit": "s",
+ "sum": {
+ "dataPoints": [
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "type",
+ "value": {
+ "stringValue": "cli"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764584491000000",
+ "timeUnixNano": "1788764584505000000",
+ "asDouble": 2.456
+ }
+ ],
+ "aggregationTemporality": "AGGREGATION_TEMPORALITY_DELTA",
+ "isMonotonic": true
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/internal/metrics/testdata/claude-code-2.1.260-metrics.pb b/internal/metrics/testdata/claude-code-2.1.260-metrics.pb
new file mode 100644
index 0000000..8f64253
Binary files /dev/null and b/internal/metrics/testdata/claude-code-2.1.260-metrics.pb differ
diff --git a/internal/metrics/testdata/claude-code-2.1.260-session.json b/internal/metrics/testdata/claude-code-2.1.260-session.json
new file mode 100644
index 0000000..5227da4
--- /dev/null
+++ b/internal/metrics/testdata/claude-code-2.1.260-session.json
@@ -0,0 +1,115 @@
+{
+ "resourceMetrics": [
+ {
+ "resource": {
+ "attributes": [
+ {
+ "key": "host.arch",
+ "value": {
+ "stringValue": "arm64"
+ }
+ },
+ {
+ "key": "os.type",
+ "value": {
+ "stringValue": "darwin"
+ }
+ },
+ {
+ "key": "os.version",
+ "value": {
+ "stringValue": "25.6.0"
+ }
+ },
+ {
+ "key": "service.name",
+ "value": {
+ "stringValue": "claude-code"
+ }
+ },
+ {
+ "key": "service.version",
+ "value": {
+ "stringValue": "2.1.260"
+ }
+ }
+ ]
+ },
+ "scopeMetrics": [
+ {
+ "scope": {
+ "name": "com.anthropic.claude_code",
+ "version": "2.1.260"
+ },
+ "metrics": [
+ {
+ "name": "claude_code.session.count",
+ "description": "Count of CLI sessions started",
+ "sum": {
+ "dataPoints": [
+ {
+ "attributes": [
+ {
+ "key": "user.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "session.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "organization.id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.email",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_uuid",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "user.account_id",
+ "value": {
+ "stringValue": "redacted"
+ }
+ },
+ {
+ "key": "terminal.type",
+ "value": {
+ "stringValue": "non-interactive"
+ }
+ },
+ {
+ "key": "start_type",
+ "value": {
+ "stringValue": "fresh"
+ }
+ }
+ ],
+ "startTimeUnixNano": "1788764580903000000",
+ "timeUnixNano": "1788764582903000000",
+ "asDouble": 1
+ }
+ ],
+ "aggregationTemporality": "AGGREGATION_TEMPORALITY_DELTA",
+ "isMonotonic": true
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/internal/metrics/testdata/claude-code-2.1.260-session.pb b/internal/metrics/testdata/claude-code-2.1.260-session.pb
new file mode 100644
index 0000000..08f762d
Binary files /dev/null and b/internal/metrics/testdata/claude-code-2.1.260-session.pb differ
diff --git a/internal/scenario/run/push.go b/internal/scenario/run/push.go
index db4aafb..55c298c 100644
--- a/internal/scenario/run/push.go
+++ b/internal/scenario/run/push.go
@@ -303,7 +303,7 @@ func pushOver(protocol, out, session string, f scenario.Format, want *expect.Pus
}
for _, dp := range m.GetSum().GetDataPoints() {
a := otlptest.Attrs(dp.GetAttributes())
- got[a["query_source"]+"/"+a["type"]] += dp.GetAsInt()
+ got[a["query_source"]+"/"+a["type"]] += int64(dp.GetAsDouble())
}
}
}
@@ -315,7 +315,7 @@ func pushOver(protocol, out, session string, f scenario.Format, want *expect.Pus
}
}
for k, v := range got {
- if _, planned := tokens[k]; !planned {
+ if _, planned := tokens[k]; !planned && v != 0 {
bad("metrics: %s on the wire is %d, the plan has no such tokens", k, v)
}
}
@@ -420,8 +420,8 @@ func tokensOnTheWire(rcv *otlptest.Receiver, session string) (out []string) {
if a["session.id"] != session || a["type"] == "" || (a["query_source"] != metrics.SourceMain && a["query_source"] != metrics.SourceSubagent) || a["model"] == "" {
bad("request %d: a point carries %v", i, a)
}
- if dp.GetTimeUnixNano() <= dp.GetStartTimeUnixNano() || dp.GetAsInt() <= 0 {
- bad("request %d: a point is not a positive window of a positive count", i)
+ if _, ok := dp.GetValue().(*metricspb.NumberDataPoint_AsDouble); !ok || dp.GetTimeUnixNano() <= dp.GetStartTimeUnixNano() || dp.GetAsDouble() < 0 {
+ bad("request %d: a point is not a positive window of a double count", i)
}
key := a["query_source"] + "/" + a["type"] + "/" + a["model"]
windows[key] = append(windows[key], window{dp.GetStartTimeUnixNano(), dp.GetTimeUnixNano()})
diff --git a/otlpdump b/otlpdump
new file mode 100755
index 0000000..70fce28
Binary files /dev/null and b/otlpdump differ
diff --git a/tools/collectorcheck/main.go b/tools/collectorcheck/main.go
index 95ff84e..3381fc2 100644
--- a/tools/collectorcheck/main.go
+++ b/tools/collectorcheck/main.go
@@ -57,8 +57,9 @@ type export struct {
AggregationTemporality any `json:"aggregationTemporality"`
IsMonotonic bool `json:"isMonotonic"`
DataPoints []struct {
- AsInt string `json:"asInt"`
- Attributes []attr `json:"attributes"`
+ AsInt string `json:"asInt"`
+ AsDouble float64 `json:"asDouble"`
+ Attributes []attr `json:"attributes"`
} `json:"dataPoints"`
} `json:"sum"`
} `json:"metrics"`
@@ -161,7 +162,10 @@ func run(root, logs string) error {
}
for _, dp := range m.Sum.DataPoints {
a := attrs(dp.Attributes)
- n, _ := strconv.ParseInt(dp.AsInt, 10, 64)
+ n := int64(dp.AsDouble)
+ if dp.AsInt != "" {
+ n, _ = strconv.ParseInt(dp.AsInt, 10, 64)
+ }
if a["sender"] == "telemetrygen" {
// Received from the exporter and forwarded as sent:
// the unit is the exporter's to set, and this one
diff --git a/tools/otlpdump/main.go b/tools/otlpdump/main.go
new file mode 100644
index 0000000..87aff31
--- /dev/null
+++ b/tools/otlpdump/main.go
@@ -0,0 +1,106 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Command otlpdump prints one spooled OTLP metrics request as JSON, the
+// protocol's own JSON mapping, so what a runtime's exporter sent can be
+// read and compared. With -redact the values of the attributes that name a
+// person, an account, an organisation or a session are replaced, so a
+// capture can be kept as a test fixture.
+//
+// go run ./tools/otlpdump [-redact] FILE.pb
+package main
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "strings"
+
+ collmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
+)
+
+// Redacted names the attributes whose values identify a person, an account,
+// an organisation or a session. Their values are replaced, their presence
+// is kept: a parity test needs to see that the exporter sends them.
+var Redacted = []string{"user.", "organization.", "session.id", "prompt.id", "host.name", "service.instance.id"}
+
+func main() {
+ redact := flag.Bool("redact", false, "replace the values of identifying attributes")
+ out := flag.String("o", "", "write the (redacted) request as protobuf to this file")
+ flag.Parse()
+ if flag.NArg() != 1 {
+ fmt.Fprintln(os.Stderr, "usage: otlpdump [-redact] [-o FILE.pb] FILE.pb")
+ os.Exit(2)
+ }
+ data, err := os.ReadFile(flag.Arg(0))
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ var req collmetricspb.ExportMetricsServiceRequest
+ if err := proto.Unmarshal(data, &req); err != nil {
+ fmt.Fprintln(os.Stderr, "not an ExportMetricsServiceRequest:", err)
+ os.Exit(1)
+ }
+ if *redact {
+ for _, rm := range req.ResourceMetrics {
+ redactAttrs(rm.GetResource().GetAttributes())
+ for _, sm := range rm.ScopeMetrics {
+ for _, m := range sm.Metrics {
+ for _, dp := range m.GetSum().GetDataPoints() {
+ redactAttrs(dp.Attributes)
+ }
+ for _, dp := range m.GetGauge().GetDataPoints() {
+ redactAttrs(dp.Attributes)
+ }
+ for _, dp := range m.GetHistogram().GetDataPoints() {
+ redactAttrs(dp.Attributes)
+ }
+ }
+ }
+ }
+ }
+ if *out != "" {
+ b, err := proto.Marshal(&req)
+ if err == nil {
+ err = os.WriteFile(*out, b, 0o644)
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ }
+ js, err := protojson.MarshalOptions{Multiline: true, Indent: " "}.Marshal(&req)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ fmt.Println(string(js))
+}
+
+func redactAttrs(kvs []*commonpb.KeyValue) {
+ for _, kv := range kvs {
+ for _, prefix := range Redacted {
+ if strings.HasPrefix(kv.GetKey(), prefix) {
+ kv.Value = &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: "redacted"}}
+ }
+ }
+ }
+}