Skip to content

fix(blocks): métricas OTLP em delta e sem service.instance.id - #751

Merged
igoramf merged 2 commits into
7.xfrom
fix/otel-metrics-cardinality
Oct 22, 2026
Merged

igoramf merged 2 commits into
7.xfrom
fix/otel-metrics-cardinality

Conversation

@igoramf

@igoramf igoramf commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Refs #750

Problema

otel_metrics_histogram está com ~462 GB no stats-lake: 24,9 bilhões de linhas em 90 dias, cerca de 600 milhões por dia. A causa está no meter OTLP do 7.x (sdk/otelHttpMeter.ts + sdk/otel.ts):

  1. Cumulativo, com buffer que nunca zera. Todo flush, a cada ~5s, serializa o Map inteiro. Um isolate que já atendeu N combinações de rota×status×região grava N linhas a cada 5s até morrer, mesmo das séries que ficaram paradas.
  2. service.instance.id = crypto.randomUUID() no resource das métricas. Com cumulativo, o id é obrigatório para não misturar totais de isolates diferentes. Só que os isolates do Workers giram o tempo todo (5.273 ids distintos em 1h num único site), então cada isolate abre o seu próprio conjunto de séries e nada se agrega.

Exemplo do efeito: deco.loader.duration, com só 20 combinações de atributos, gera 30 milhões de linhas por dia num único tenant.

Mudança

  • otelHttpMeter.ts: temporalidade DELTA (aggregationTemporality: 1), igual ao v8/telemetry.ts do main. O flush tira um snapshot do buffer e o zera de forma síncrona, antes do primeiro await. Assim, o que for gravado durante o POST cai na janela seguinte. O startTimeUnixNano de counters e histogramas passa a ser o início da janela (o último flush), e não mais o boot do isolate. Séries paradas deixam de ser reenviadas.
  • otel.ts: o resource das métricas não leva mais service.instance.id. Pontos delta de isolates diferentes devem ser somados, e o UUID os separaria de novo. Logs e traces continuam com o id.

Trade-off: se o POST falhar, a janela dele se perde (≤ minFlushIntervalMs, 5s por padrão de um isolate) em vez de voltar para o buffer. No modo cumulativo, a perda se recuperava no flush seguinte. Deixei um comentário ponytail: no ponto; dá para adicionar um buffer de retry se a perda aparecer.

Atenção na revisão: quem consome

Antes do merge, verificar consultas e dashboards no ClickHouse/Grafana que leem otel_metrics_histogram/otel_metrics_sum assumindo cumulativo, por exemplo diferença entre linhas consecutivas ou max(Count) por série. Com delta, o certo é sum(Count) e sumForEach(BucketCounts) na janela. Dados antigos (AggTemp = 2) e novos (AggTemp = 1) vão conviver até o TTL vencer; dá para filtrar por AggregationTemporality. Também confirmar que o deco-otel-ingest/collector não tem um cumulativetodelta que esperava o id.

Fora deste PR, ficam na #750:

  • http.route ainda vaza segmentos de uma palavra só;
  • deco.http.region (166 valores) no histograma; mexer nisso esbarra no fan-out para o AE, que quer a região;
  • a coluna _block_offset materializada e o TTL de 90 dias (infra).

Testes

  • otelHttpMeter.test.ts:
    • as asserções de temporalidade foram para 1;
    • o teste de cooldown agora afirma que o buffer zera depois do flush;
    • teste novo: a 2ª janela leva só a série que recebeu dado, com count só da janela e startTimeUnixNano = flush anterior; a série parada não é reenviada.
  • bunx vitest run packages/blocks/src/sdk/: 501/501.
  • tsc --noEmit em packages/blocks: limpo.
  • biome check nos 3 arquivos: 3 erros de formatação que já existem no 7.x sem este PR.
  • Não validei em preview/produção a contagem de linhas depois da mudança. Isso fica para depois do deploy num site, comparando linhas/dia por ServiceName.

Summary by cubic

Fixes the stats-lake bloat in otel_metrics_histogram (~600M rows/day) by switching the OTLP meter from cumulative to delta aggregation and dropping the per-isolate service.instance.id from metrics resources. Previously, each ~5s flush re-exported every series the isolate had ever seen, and since Workers isolates rotate constantly, every one opened its own series set and nothing aggregated.

Bug Fixes

  • otelHttpMeter.ts now exports with AggregationTemporality = DELTA; each flush snapshots the buffer and clears it synchronously, so idle series are not re-sent and startTimeUnixNano becomes the window start instead of isolate boot.
  • Metric kinds are tracked in a map that survives the flush reset, so a name can't reappear as a different kind in a later window.
  • Metrics resources drop service.instance.id while logs and traces keep it. A failed POST now loses at most minFlushIntervalMs (5s) of data instead of recovering it on the next flush.

Migration

  • Dashboards and queries reading otel_metrics_histogram/otel_metrics_sum as cumulative (max(Count), row-to-row differences) must switch to sum() over the window.
  • Old cumulative rows (AggregationTemporality = 2) and new delta rows (= 1) coexist until TTL expires; filter by that column if needed.

Refs decocms/blocks#750.

Written for commit c7e26cc. Summary will update on new commits.

View guided diff Turn on auto-fix

O meter OTLP exportava cumulativo com buffer que nunca zerava: cada flush
(~5s) reenviava toda série que o isolate já tinha visto, e o UUID por
isolate no resource impedia somar isolates. Resultado: ~600M linhas/dia
em otel_metrics_histogram.

Refs #750
@igoramf

igoramf commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

Verdict: LGTM — the snapshot/clear and the DELTA switch are correct, and I found nothing in this repo that breaks (round 1)

Blocking

None.

Worth fixing

  • docs/runbooks/{http-latency-spike,commerce-upstream-slow,cache-hit-drop,http-error-spike}.md: these runbooks query otel_metrics_* with count() of rows and per-row Sum/Count. Under cumulative they were already wrong (counting rows measures flush frequency, not traffic). Under delta, sum(Value) and sum(Sum)/sum(Count) become the correct forms, so this PR does not make them worse. They should still be rewritten once, with an AggregationTemporality = 1 filter for the window where old and new rows coexist. → file an issue
  • otel.ts:931 ("Cumulative temporality, per-isolate buffer") and otelHttpTracer.ts:24 ("metrics (CUMULATIVE temporality, lifelong buffer)") are stale now. The comment in flush() ("already snapshotted the buffer at its enqueue time") is accurate now; before this change it was not. → file an issue (comment only)
  • otelHttpMeter.ts checkAdmissibility: after metrics.clear(), the kind registered for a name is forgotten. A name recorded as a counter in window N and as a histogram in window N+1 goes out as both kinds instead of the second one being dropped. That needs a caller bug to trigger and the ingest side separates by table, so it doesn't matter in practice. → file an issue if anyone cares

Not verifiable from this repo

  • I couldn't check deco-otel-ingest or the collector config from here. Nothing in this repo runs a cumulativetodelta / deltatocumulative step or depends on service.instance.id for metrics. Two isolates can now send rows with identical attributes and timestamps. That is correct only if the otel_metrics_* tables are plain MergeTree (the clickhouseexporter default), not Replacing/Collapsing. Confirm that before rollout.

Checked, fine

  • Snapshot and race: the snapshot plus clear() happen before the first await, and inflight dedupe means no double-send. Points recorded during the POST land in the next window.
  • Overflow cap: the cap now counts per window, which is the intent.
  • Gauges: gauges are cleared after each send. The only caller of gaugeSet is the smoke script, so no "last value" gauge goes missing.
  • Forced flush: flush(force) (instrumentWorkflowRun) is unaffected.
  • startTimeUnixNano: it equals the previous flush time, and points created mid-window keep the window start, which is valid DELTA.
  • Resource attributes: service.instance.id is removed only from the copy passed to the metrics resource. The floor object used by logs and traces is not mutated.
  • Lint: the _instanceId local is fine. Biome ignores names starting with _, and knip doesn't check locals.

@igoramf

igoramf commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

Verdict: LGTM: the round-1 kind-mismatch gap is closed correctly and nothing in the fix commit regresses (round 2)

Previously raised

  • otelHttpMeter.ts kind-mismatch forgotten after metrics.clear(): fixed. kinds outlives the reset, checkAdmissibility checks it before metrics, and materializeEntry is the only writer. Because of that, a name dropped by the overflow cap is never registered, so the cap behaves as before. The new test covers the flush-then-different-kind path.
  • Stale "cumulative" comments in otel.ts and otelHttpTracer.ts: fixed.
  • Runbooks: deferred to a separate issue, which is fine. They query metric names that don't exist in the code, so they were already broken regardless of temporality.
  • ClickHouse engine: the author confirmed out-of-band that it is SharedMergeTree, so duplicate delta rows from different isolates are kept. That was the open question, and it is resolved.

Blocking

None.

Worth fixing

  • otelHttpMeter.ts kinds has no bound, unlike the per-window overflow cap. That is safe only while names stay framework constants. If a name is ever built from runtime input, this map leaks for the lifetime of the isolate. → file an issue (no current trigger)

Checked, fine

  • The overflow cap does not register a kind for dropped names.
  • An existing entry is still returned within a window.
  • The test asserts that the buffer is empty after the rejected record and that only one POST is sent.

@igoramf
igoramf merged commit dc3d300 into 7.x Oct 22, 2026
1 check passed
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 7.81.4 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant