Skip to content

fix(telemetry): delta metrics from one process can reach the collector out of order #792

Closed

Description

@dan-petty

Context & Rationale

Item 3 of #664 was not addressed by #675. The metric exporter in telemetry/tracer.py has three properties that together let delta points arrive out of order:

  • it runs with max_workers=2 (:1222);
  • it stamps points with a raw time_ns() (:928-931);
  • it keeps the host-derived service.instance.id (:805).

Two concurrent increments of one series put two exports in flight, and in a repro they arrived out of time order. With delta temporality, the collector can then drop or misorder points, and totals come out low.

Scope & Deliverables

Strategic Alignment

  • Milestone: Backlog (no release)
  • Design: none
  • Depends on: none

Generated by Claude Code

Monitoring cleanup amendment (2026-10-03): evidence and scope

Over 24h, Prometheus rejected 219 remote-write requests as out of order. Grouped by metric, the rejected series were target_info 189, devops_cli_subprocess_seconds 19 and up 4. Grouped by job, devops-cli accounted for 211. Each rejection drops a whole Alloy batch, about 15.3k samples in total.

Scope (added). target_info is in scope: every CLI process emits it with the same series identity (the host-derived instance id), so two processes' resource metrics interleave out of order.

#1132 adds the receiver-side out_of_order_time_window and removes the Alloy hop. This item remains the sender-side fix. Related to #1128, not a child.

Amended 2026-10-04: metrics go through the OTel SDK, with exponential histograms

Library-first scope, from a latency investigation on 2026-10-04.

  • The review p95 panel showed nearly 30 minutes, but the slowest review took 16.5 minutes.

    • The panel computes histogram_quantile(0.95, … increase(devops_cli_review_duration_seconds_bucket[1h])) (k8s/monitoring/dashboards/devops-cli.json:67). The review buckets jump from 900 s to 1,800 s (telemetry/instruments.py:44).
    • histogram_quantile spreads values evenly inside a bucket. With N reviews in the hour, one 992 s review is drawn as 900 + 900 × (1 − 0.05N): between 1,575 and 1,755 s.
    • About 43% of the plotted value came from the bucket math alone. The night before, 591–679 s reviews were drawn as 825–885 s.
    • The command-duration panel tops out at 600 s (_SECONDS, instruments.py:43), so a 20-minute gate draws as a flat line.
  • The hand-built exporter is the root of both this and the ordering problem above. telemetry/tracer.py builds OTLP metric payloads by hand, with fixed bucket tuples, its own worker pool and raw time_ns() stamps. The OpenTelemetry SDK is already a dependency.

  • Metrics go through the SDK. Metrics are emitted through the SDK's MeterProvider, with DELTA temporality, and flushed once when the command ends. The hand-built metric payload, its worker pool and its timestamping are removed from tracer.py. This replaces the "one ordered lane" deliverable above: each process sends one export.

  • Histograms are exponential. Duration histograms use an ExponentialBucketHistogramAggregation view, and the fixed bucket tuples in instruments.py are removed.

  • Prometheus stores native histograms. The collector's remote write sends them as native histograms, and Prometheus ingests them; the receiver side is fix(telemetry): devops-cli metrics reach prometheus in one hop, a late sample no longer drops a whole batch, and the collector runs only what its pipelines use #1132's file, k8s/otel/values.yaml. Before building, check that the deployed Prometheus version accepts native histograms over remote write. If it does not, record that and keep explicit buckets on this criterion only.

  • Duration panels stay honest at low counts. The duration panels in devops-cli.json show the p95, a mean line (increase(_sum) / increase(_count)) and the sample count, so a quantile drawn from one or two samples reads as such.

  • The idle-hour gap is fixed or recorded. deltatocumulative's max_stale: 1h (k8s/otel/values.yaml:61) hides the first review after an idle hour from every increase() window. Fix it here if the SDK path changes it; otherwise record it as fix(telemetry): devops-cli metrics reach prometheus in one hop, a late sample no longer drops a whole batch, and the collector runs only what its pipelines use #1132's.

  • Tests. An export of one 992 s review, read back through a fake OTLP receiver, is an exponential histogram whose bucket holding 992 s has a width under 10% of its value. The existing collector-export tests pass, offline.

Activity

  1. added
    type/bug
    scope/telemetry
    priority/p2-medium
    on Oct 1, 2026
  2. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Folded here instead of a new issue: the agent filing quota (#1153) is spent for this cycle, and this refactor shares this item's change surface. It is recorded here in full so it is not lost.

    refactor(telemetry): /metrics is rendered and scraped metrics are parsed by prometheus-client

    Problem

    Lines cited at 05e9388 (release/v0.2.29).

    • Three hand-written exposition writers.
      • InMemoryMetricsRegistry.export_prometheus_text (telemetry/metrics.py:174-197). The roadmap service serves it as is (server/service.py:458-463).
      • The API's /metrics route, which prepends hand-formatted families (server/routes/telemetry.py:60-90).
      • The AI-spend exporter (ai/spend/prometheus.py:24-120).
      • Label escaping exists twice (metrics.py:29-38, ai/spend/prometheus.py:12-22).
      • server/routes/telemetry.py:74 interpolates __version__ into a label unescaped.
    • Histograms are not histograms.
      • metrics.py:188-195 writes # TYPE <name> histogram followed only by _count and _sum. There are no _bucket series and no le="+Inf", which the text format requires.
      • So histogram_quantile cannot be applied to, for example, devops_cli_argo_target_sync_duration_seconds (argo/fleet.py:90).
      • The registry keeps up to 10,000 raw observations per series (_MAX_HISTOGRAM_SAMPLES, metrics.py:23), only to sum and count them.
    • The sandbox scrape parses with regular expressions. parse_prometheus_exposition (sandbox/metrics.py:312-383) has two defects:
      • The line pattern \{(?P<labels>[^}]*)\} (:32-34) drops any sample whose label value contains }. Such a value is legal, for example path="/api/{id}".
      • Types are looked up by sample name (:367), so a histogram's _sum is typed gauge and its _count counter (:377-383).
      • The scrape itself uses a raw httpx2.Client (:433).
    • The gateway benchmark reads vLLM's exposition with a regex (ai/gateway_bench.py:76-85: _VLLM_CACHE and an inline label regex).

    Proposed remedy

    • Library. Add prometheus-client to the dependencies (Prometheus Authors; 0.26.0, 2026-07-24).
    • Registry. One CollectorRegistry replaces InMemoryMetricsRegistry's storage and text export. GLOBAL_METRICS callers keep their call shape over Counter, Gauge and Histogram, with buckets from telemetry/instruments.py or the library defaults.
    • AI spend and service families.
      • The AI-spend snapshot becomes a custom collector yielding GaugeMetricFamily and CounterMetricFamily.
      • devops_cli_info becomes an Info; uptime and telemetry-enabled become gauges.
    • Endpoints. Both /metrics routes return generate_latest(registry) with CONTENT_TYPE_LATEST.
    • Sandbox scrape. sandbox/metrics.py parses with prometheus_client.parser.text_string_to_metric_families and scrapes through the egress factory (refactor(cli): Unify HTTP and DNS seams with shared fakes #1314).
    • ai/gateway_bench.py stays standard-library only.
      • Its module docstring requires it: the module's source runs in an ephemeral Python container attached to the gateway pod, and that container has none of this project's dependencies.
      • It reads one known sample, vllm:cache_config_info. Its existing regex is kept as the single exception and pinned by a recorded vLLM exposition fixture. No fuller hand-written parser is added there.
      • Every other Prometheus text in devops-cli goes through prometheus-client.

    Acceptance criteria

    • rg -n '"# (TYPE|HELP)' src/devops_cli prints nothing.
    • Every histogram family on /metrics exposes _bucket series including le="+Inf", plus _sum and _count. The registry keeps no raw observations.
    • Rendering then parsing a sample whose label value holds }, ", \ and a newline returns the same value. A histogram's _sum and _count samples come back under the histogram family.
    • Registering one family name from two sources fails at registration (prometheus-client's duplicate check), and a test covers it.
    • ai/gateway_bench.py imports only the standard library. A test reads num_gpu_blocks and block_size from a recorded vLLM /metrics fixture.
    • Tests run offline with fakes only at process and HTTP edges; each new test runs under 1 s.
    • changelog.d/<n>.md records the change; CHANGELOG.md and docs/ROADMAP.md are not edited.
    • uv run devops ci passes.

    Related: #792, #1132, #974, #569, #1335, #1314, #1334.

    Found by the 2026-10-08 client-library audit.

  3. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Linked: #1319 and #813. Each replaces part of the hand-built OTLP in telemetry/tracer.py with the SDK: metrics here, spans and the exporter seam in #1319, logs in #813. Found by the 2026-10-08 backlog review.

  4. dan-petty commented on Oct 9, 2026

    @dan-petty
    OwnerAuthor

    Finding: v0.2.29 Service gap assessment (2026-10-09)

    _send_metric posts one OTLP payload per data point, and httpx logs each POST at INFO: in the v0.2.29 pod, 7,721 metrics POST lines and 4,362 traces POST lines in 3 hours, about two thirds of the log. Many concurrent sends also make the out-of-order delta points this item describes more likely. Proposed: in the single ordered export lane planned here, send one request per emission with all its points, and set the httpx logger to WARNING in the Service.

  5. added this to the v0.2.36 milestone on Oct 14, 2026
  6. dan-petty commented on Oct 14, 2026

    @dan-petty
    OwnerAuthor

    Moved to v0.2.36: v0.2.36 started with fewer than its 16 items and was topped up to 16 from Ready items, critical fixes and P0 features first. (devops roadmap reprioritize)

  7. added
    status/in-progress
    status/in-review
    and removed
    status/in-progress
    on Oct 17, 2026
  8. dan-petty commented on Oct 17, 2026

    @dan-petty
    OwnerAuthor

    What changed

    #1612, merged into release/v0.2.36 as 6e12759.

    Summary

    Fixes #792 (including the 2026-10-04 OpenTelemetry SDK / exponential histogram amendment, the 2026-10-09 Service httpx logger amendment, and the folded-in prometheus-client exposition and parser refactor from #1147).

    • OpenTelemetry SDK MeterProvider & ExponentialBucketHistogramAggregation (src/devops_cli/telemetry/tracer.py, src/devops_cli/telemetry/instruments.py, src/devops_cli/main.py):
      • Replaced per-point _build_metrics_payload, _send_metric, _delta_interval, and _metric_resource_attributes on OTelTelemetryClient with a lazily initialized OpenTelemetry SDK MeterProvider (InMemoryMetricReader with AggregationTemporality.DELTA for Counter, Histogram, and _Gauge, and View(instrument_type=Histogram, aggregation=ExponentialBucketHistogramAggregation())) that aggregates every counter, histogram, and gauge recording over a process run and flushes one OTLP /v1/metrics batch in main._delegate's finally: block and OTelTelemetryClient.shutdown().
      • Removed fixed bucket tuples (_SECONDS, _REVIEW_SECONDS, _RAG_MILLISECONDS, _DAYS) and Instrument.bounds.
    • Prometheus Native Histograms & Dashboard Mean / Sample Count Targets (k8s/monitoring/prometheus-values.yaml, k8s/monitoring/dashboards/devops-cli.json, k8s/monitoring/dashboards/project-metrics.json, src/devops_cli/docs/generator.py, docs/TELEMETRY.md):
      • Enabled enable-feature: native-histograms in k8s/monitoring/prometheus-values.yaml…

    30 file(s) changed.

    How it was verified

    Check runs at 94151ef:

    • Prune PR DevContainer Images: pass
    • Audit Defect PR Hardening: skipping
    • devops-cli: pass
    • zizmor: pass
    • bandit: pass
    • CodeQL: pass
    • Rule Pack Tests: pass
    • Fail-to-Pass Self-Check: pass
    • Changed-Test Independence: pass
    • Tests & Coverage: pass
    • Analyze (python): pass
    • Fail-to-Pass Check: pass
    • Analyze (actions): pass
    • Static Analysis: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-792-telemetry-delta-metrics-and-prometheus-client.md:

    No Acceptance Criteria section.

  9. removed
    status/in-review
    on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/telemetrytype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions