Skip to content

Commit 6fef8e0

Browse files
committed
feat(metrics): collapse batch method labels into bounded signatures
A JSON-RPC batch has no single method, so batch parsing synthesizes an api name by joining every sub-method with "&" (chainlib/jsonRPC.go). That joined string reached the `method` label verbatim, so each distinct batch composition minted its own permanent series — 51,083 series observed on atlas-prd, nearly all sitting at value 1, multiplied across ~15 metric families that share the label. The label now carries a batch signature: the sorted set of distinct sub-methods, prefixed `batch:`. Order and repetition are what made the raw name unbounded (permutations, and one series per batch length) while the set is what identifies the type of batch and is what client code determines. The magnitude repetition used to encode moves to a size histogram. Because the signature rides the existing label, per-batch-type success rate, latency, and provider breakdown come for free — none of which was visible before, since batched traffic never appeared under its own methods at all. Normalization is applied at every recorder boundary, not just the request-group family: cross-validation, incident, cache, and endpoint families all carried the same raw `method`. - signature is order- and repetition-invariant, and idempotent, so the recorders that delegate to one another can each normalize defensively - bounded by a per-spec cap (64 signatures) and a per-signature width limit (8 distinct methods); overflow lands in `batch:other` and is counted, so a lossy breakdown is detectable rather than silent - admission never evicts, which keeps the in-flight gauge's paired Add/Sub on the same series instead of leaking a stuck value - batch size observed once per completed relay only, on the two entry points that are not reached via another recorder - single-method traffic is untouched, so existing dashboards keep working No allowlist is needed on sub-methods: getSupportedApi hard-fails the parse on unknown methods before any batch name is built, so the joined name only ever contains spec-declared api names. New metrics: smartrouter_batch_size, smartrouter_batch_signature_overflow_total.
1 parent 075baef commit 6fef8e0

4 files changed

Lines changed: 603 additions & 0 deletions

File tree

‎docs/METRICS.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,49 @@ with read/write.
130130
| `smartrouter_requests_archive_total` | Counter | `spec`, `apiInterface`, `provider_address`, `method` | Archive requests. |
131131
| `smartrouter_requests_batch_total` | Counter | `spec`, `apiInterface`, `provider_address`, `method` | Batch requests. |
132132

133+
#### Batch requests and the `method` label
134+
135+
For a batch request there is no single method, so the `method` label carries a
136+
**batch signature**: the sorted set of distinct sub-methods, prefixed with `batch:`.
137+
138+
```
139+
[eth_call ×30, eth_getBalance] → method="batch:eth_call+eth_getBalance"
140+
[eth_call ×3] → method="batch:eth_call"
141+
```
142+
143+
Order and repetition are deliberately dropped. They are what a raw joined label would
144+
encode, and they make cardinality unbounded — order contributes permutations, repetition
145+
contributes one series per batch length. The set is the part that identifies the *type*
146+
of batch, and it is what client code actually determines. The magnitude that repetition
147+
used to encode moves to `smartrouter_batch_size`.
148+
149+
Because the signature carries the method label on the whole request-breakdown family,
150+
per-batch-type success rate, latency, and provider breakdown all work:
151+
152+
```promql
153+
# error rate per batch type
154+
sum by (method) (rate(smartrouter_requests_failed_total{method=~"batch:.*"}[5m]))
155+
/ sum by (method) (rate(smartrouter_requests_total{method=~"batch:.*"}[5m]))
156+
```
157+
158+
Single-method requests are untouched — `method="eth_call"` means exactly what it always
159+
did, so a `method=~"batch:.*"` / `method!~"batch:.*"` pair cleanly splits batch from
160+
single traffic.
161+
162+
Two bounds keep the label space finite. A spec may register at most **64** distinct
163+
signatures, and one signature may name at most **8** distinct methods; anything beyond
164+
either lands in `method="batch:other"`. Both are declared in
165+
[`batch_method_label.go`](../protocol/metrics/batch_method_label.go).
166+
167+
| Metric | Type | Labels | Description |
168+
| --- | --- | --- | --- |
169+
| `smartrouter_batch_size` | Histogram | `spec`, `apiInterface` | Sub-requests per batch. Single-element batches produce no separator in the api name, so they are indistinguishable from single requests here and are not observed. |
170+
| `smartrouter_batch_signature_overflow_total` | Counter | `spec`, `reason` | Normalizations that fell into `batch:other`. `reason="cap"`: the spec exhausted its 64-signature budget. `reason="wide"`: one batch spanned more than 8 distinct methods. |
171+
172+
**Alert on the overflow counter.** While it is zero, batch-type breakdowns are complete.
173+
Once it is non-zero they are lossy — some batch types are being merged into `batch:other`
174+
— which is a signal to raise the cap, not to distrust the other series.
175+
133176
#### Errors
134177

135178
| Metric | Type | Labels | Description |
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
package metrics
2+
3+
import (
4+
"sort"
5+
"strings"
6+
"sync"
7+
)
8+
9+
const (
10+
// batchMethodSeparator mirrors chainlib's SEP — the token batch parsing uses to
11+
// join every sub-method into one synthetic api name (protocol/chainlib/jsonRPC.go,
12+
// protocol/chainlib/tendermintRPC.go). It is redeclared here rather than imported
13+
// because chainlib already imports this package; importing back would be a cycle.
14+
batchMethodSeparator = "&"
15+
16+
// BatchMethodPrefix namespaces every collapsed batch label value so dashboards can
17+
// separate batch traffic from single-method traffic with a prefix match
18+
// (method=~"batch:.*") rather than an allowlist of method names.
19+
BatchMethodPrefix = "batch:"
20+
21+
// BatchMethodOther is the overflow bucket, emitted when a batch's signature is past
22+
// the per-spec cap or spans more distinct methods than maxBatchSignatureElements.
23+
// It is what makes the `method` label bounded no matter what a client sends.
24+
BatchMethodOther = BatchMethodPrefix + "other"
25+
26+
// batchSignatureElementSeparator joins sub-methods inside a signature. It is
27+
// deliberately NOT batchMethodSeparator: that is what keeps normalization
28+
// idempotent, since an already-collapsed value then carries no separator.
29+
batchSignatureElementSeparator = "+"
30+
31+
// maxBatchSignaturesPerSpec caps how many distinct signatures one spec may
32+
// register. Distinct method SETS are 2^N in theory but a handful in practice —
33+
// batch shapes are emitted by customer code, not drawn at random. The cap is the
34+
// backstop for when that assumption is wrong, and
35+
// smartrouter_batch_signature_overflow_total reports when it binds.
36+
maxBatchSignaturesPerSpec = 64
37+
38+
// maxBatchSignatureElements caps how many distinct methods a single signature may
39+
// name, so one pathological batch can't mint a kilobyte-long label value.
40+
maxBatchSignatureElements = 8
41+
)
42+
43+
// Reasons for the smartrouter_batch_signature_overflow_total `reason` label.
44+
const (
45+
batchOverflowReasonCap = "cap"
46+
batchOverflowReasonWide = "wide"
47+
)
48+
49+
// buildBatchSignature turns a raw joined batch api name into an order-invariant and
50+
// repetition-invariant signature: the sorted SET of its sub-methods.
51+
//
52+
// Dropping order and repetition is the entire point. They are what made the raw name
53+
// unbounded — order contributes permutations, repetition contributes length variants —
54+
// while the set is what a client's code actually determines. So
55+
//
56+
// eth_call&eth_call&…&eth_call&eth_getBalance → batch:eth_call+eth_getBalance
57+
//
58+
// collapses thousands of observed series onto one, and the magnitude that repetition
59+
// used to (uselessly) encode is recovered from the smartrouter_batch_size histogram.
60+
//
61+
// Sub-methods need no allowlist check: chainlib resolves every element against the spec
62+
// through getSupportedApi and hard-fails the parse before any batch name is built, so a
63+
// name reaching here only ever contains spec-declared api names, never raw client input.
64+
//
65+
// size is the batch's element count including repeats. tooWide reports a batch spanning
66+
// more than maxBatchSignatureElements distinct methods, for which the caller emits
67+
// BatchMethodOther instead of an unwieldy label value.
68+
func buildBatchSignature(apiName string) (signature string, size int, tooWide bool) {
69+
parts := strings.Split(apiName, batchMethodSeparator)
70+
seen := make(map[string]struct{}, len(parts))
71+
distinct := make([]string, 0, len(parts))
72+
73+
for _, part := range parts {
74+
part = strings.TrimSpace(part)
75+
if part == "" {
76+
continue
77+
}
78+
size++
79+
if _, duplicate := seen[part]; duplicate {
80+
continue
81+
}
82+
seen[part] = struct{}{}
83+
distinct = append(distinct, part)
84+
}
85+
86+
if len(distinct) == 0 || len(distinct) > maxBatchSignatureElements {
87+
return BatchMethodOther, size, true
88+
}
89+
90+
sort.Strings(distinct)
91+
return BatchMethodPrefix + strings.Join(distinct, batchSignatureElementSeparator), size, false
92+
}
93+
94+
// batchSignatureRegistry bounds the set of batch signatures allowed to become label
95+
// values, tracked per spec so a chatty chain can't consume another chain's budget.
96+
type batchSignatureRegistry struct {
97+
lock sync.RWMutex
98+
admitted map[string]map[string]struct{} // spec -> set of admitted signatures
99+
}
100+
101+
func newBatchSignatureRegistry() *batchSignatureRegistry {
102+
return &batchSignatureRegistry{admitted: make(map[string]map[string]struct{})}
103+
}
104+
105+
// admit reports whether signature may be used as a label value for spec.
106+
//
107+
// Admission is monotone: an admitted signature stays admitted, and a full cap stays
108+
// full. That is what keeps paired call sites consistent — the in-flight gauge's Add at
109+
// relay start and Sub at relay end normalize the same api name to the same string, so
110+
// the gauge cannot leak a stuck non-zero series.
111+
func (r *batchSignatureRegistry) admit(spec, signature string) bool {
112+
if r == nil {
113+
return false
114+
}
115+
116+
r.lock.RLock()
117+
if signatures, ok := r.admitted[spec]; ok {
118+
if _, alreadyAdmitted := signatures[signature]; alreadyAdmitted {
119+
r.lock.RUnlock()
120+
return true
121+
}
122+
}
123+
r.lock.RUnlock()
124+
125+
r.lock.Lock()
126+
defer r.lock.Unlock()
127+
128+
signatures, ok := r.admitted[spec]
129+
if !ok {
130+
signatures = make(map[string]struct{}, maxBatchSignaturesPerSpec)
131+
r.admitted[spec] = signatures
132+
}
133+
if _, alreadyAdmitted := signatures[signature]; alreadyAdmitted {
134+
return true
135+
}
136+
if len(signatures) >= maxBatchSignaturesPerSpec {
137+
return false
138+
}
139+
signatures[signature] = struct{}{}
140+
return true
141+
}
142+
143+
// normalizeMethodLabel collapses a raw batch api name into a bounded signature and
144+
// returns single-method names untouched.
145+
//
146+
// It is idempotent, because a collapsed value carries no batchMethodSeparator. That
147+
// matters: the public recorders delegate to one another (RecordDirectRelayEnd →
148+
// RecordRelaySuccess → AddEndpointRelayServiced), and each normalizes at its own
149+
// boundary so that calling any of them directly is still safe.
150+
func (m *SmartRouterMetricsManager) normalizeMethodLabel(spec, method string) string {
151+
if m == nil || !strings.Contains(method, batchMethodSeparator) {
152+
return method
153+
}
154+
155+
signature, _, tooWide := buildBatchSignature(method)
156+
if tooWide {
157+
m.recordBatchSignatureOverflow(spec, batchOverflowReasonWide)
158+
return BatchMethodOther
159+
}
160+
if !m.batchSignatures.admit(spec, signature) {
161+
m.recordBatchSignatureOverflow(spec, batchOverflowReasonCap)
162+
return BatchMethodOther
163+
}
164+
return signature
165+
}
166+
167+
func (m *SmartRouterMetricsManager) recordBatchSignatureOverflow(spec, reason string) {
168+
if m == nil || m.batchSignatureOverflow == nil {
169+
return
170+
}
171+
m.batchSignatureOverflow.WithLabelValues(spec, reason).Inc()
172+
}
173+
174+
// observeBatchSize records how many sub-requests a batch carried — the magnitude that
175+
// the collapsed `method` label deliberately no longer encodes.
176+
//
177+
// This must be called from exactly ONE place (RecordDirectRelayEnd, once per completed
178+
// relay). The other recorders normalize but must not observe, or a single request would
179+
// be counted once per recorder it passes through.
180+
//
181+
// Single-element batches carry no separator in their api name, so they are
182+
// indistinguishable from single requests here and are not observed.
183+
func (m *SmartRouterMetricsManager) observeBatchSize(spec, apiInterface, method string) {
184+
if m == nil || m.batchSize == nil || !strings.Contains(method, batchMethodSeparator) {
185+
return
186+
}
187+
188+
_, size, _ := buildBatchSignature(method)
189+
if size == 0 {
190+
return
191+
}
192+
m.batchSize.WithLabelValues(spec, apiInterface).Observe(float64(size))
193+
}

0 commit comments

Comments
 (0)