Skip to content

feat: VictoriaMetrics Remote Write and OTLP ingest adapters (layout step 7) - #882

Draft
zzylol wants to merge 4 commits into
refactor/layout-adaptersfrom
refactor/layout-ingest-adapters
Draft

zzylol wants to merge 4 commits into
refactor/layout-adaptersfrom
refactor/layout-ingest-adapters

Conversation

@zzylol

@zzylol zzylol commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: ASAPQuery ingests VictoriaMetrics Remote Write (zstd-compressed Remote Write protobuf, POST /api/v1/import) and OTLP metrics (POST /v1/metrics); the backend ingests only Prometheus Remote Write. Step 7 of docs/design/repo-layout.md (docs(design): repository layout and engine boundaries #874) brings both over as adapter crates.
  • Change:
    • crates/adapters/ingest/victoriametrics-remote-write (victoriametrics_remote_write): decompresses zstd and hands the protobuf to the Remote Write decoder through a new prometheus_remote_write::Decoder::decode_uncompressed. There is no second protobuf decoder: samples are built into the caller's types (SampleBuilder), with the same validation, limits and series cache.
    • crates/adapters/ingest/otlp (otlp): OTLP/HTTP metrics (protobuf, gzip optional) into one Point per sample, converted as ASAPQuery's receiver converts them.
    • data-plane serves both on ASAPQuery's routes and feeds the engine as /api/v1/write does (the same RawSamples and try_ingest, the same 400/503/500).
    • Ported read-only from ASAPQuery's main. refactor(query-engine): extract asap-adapters crate ASAPQuery#936 and #937 are still open; names follow #936 (OTLP ingest, the VictoriaMetrics decoder), and neither adapter needs #937's QueryRequest.
  • Effect:

Review guide

  • Base: refactor/layout-adapters (refactor: Remote Write and Prometheus HTTP API into crates/adapters (layout step 6) #881). Stacked draft.
  • Commits:
    1. The two crates, the routes, the end-to-end test and the README.
    2. Review fixes: one push for every OTLP metric type; one-pass zstd; no test-only public items; the decoder-identity test.
    3. ingest returns the refusal (clippy result_large_err).
    4. #[inline(always)] on the shared request loop (see Benchmarks).
  • Read first:
    1. crates/data-plane/src/remote_write.rs (the seam).
    2. Decoder in crates/adapters/ingest/victoriametrics-remote-write/src/lib.rs.
    3. points in crates/adapters/ingest/otlp/src/lib.rs.
    4. write_victoriametrics, write_otlp, ingest and router in crates/data-plane/src/lib.rs.

Dependency graph

victoriametrics_remote_write ──► prometheus_remote_write (its protobuf), zstd, prost, thiserror
otlp ──────────────────────────► (no workspace crate) opentelemetry-proto (messages only), prost, flate2, thiserror
prometheus_remote_write ───────► (no workspace crate), unchanged
data_plane ──► + victoriametrics_remote_write, otlp   (dev: + flate2, prost)
  • The VictoriaMetrics crate depends on the Remote Write adapter. Its wire format is that adapter's protobuf, and the alternatives are worse:

    • Composing zstd and decode_uncompressed in data-plane would put protocol knowledge, the zstd-bomb limit and a reused buffer in the wiring crate.
    • Putting SampleBuilder in common would make every ingest adapter pull in asap-planner.

    The docs(design): repository layout and engine boundaries #874 doc now states the rule: an adapter depends on common, on nothing, or on the adapter whose wire format it extends.

  • opentelemetry-proto 0.28 (ASAPQuery's version) with only gen-tonic-messages and metrics. There is no gRPC server, but tonic's codegen types and the OpenTelemetry SDK still compile: 12 new lockfile packages, no new runtime services.

Behavior: before → after

Request Before After
POST /api/v1/write, every query route, /metrics, /api/v1/status/asap, /-/ready, the watermark byte-identical (see Parity)
POST /api/v1/import (zstd Remote Write) 404; forward mode: proxied 204 once ingested; 400 bad body; 503 busy; 500 engine stopped. Forward mode: proxied, as before
POST /v1/metrics (OTLP protobuf, Content-Encoding: gzip optional) 404; forward mode: proxied 200 {"rejected":0} (ASAPQuery's answer); 400 / 503 / 500 as above. Forward mode: proxied, as before

OTLP conversion, as ASAPQuery's otlp_to_metric_points_and_sketches:

  • Labels: __name__ is the metric name. The scope's attributes come first, the resource's override them, and the point's override both.
  • Gauges and sums give one sample each.
  • Histograms and exponential histograms give <name>_sum (when set) and <name>_count. Summaries always give both.
  • Points that carry a kll./cms./countsketch.sketch_payload attribute, and metrics with no name, are skipped.
  • A point with no value reads 0.
  • Timestamps are converted from ns to ms.

Interfaces

crates/adapters/ingest/prometheus-remote-write/src/lib.rs

 impl<B: SampleBuilder> Decoder<B> {
     pub fn decode(&mut self, body: &[u8], limits: &Limits) -> Result<Vec<B::Sample>, RemoteWriteError>;
+    /// An uncompressed `WriteRequest`, as `decode` reads a decompressed body.
+    pub fn decode_uncompressed(&mut self, request: &[u8], limits: &Limits) -> Result<Vec<B::Sample>, RemoteWriteError>;
 }
-const KEPT_DECOMPRESSED_BYTES: usize = 32 * 1024 * 1024;
+pub const KEPT_DECOMPRESSED_BYTES: usize = 32 * 1024 * 1024;

crates/adapters/ingest/victoriametrics-remote-write/src/lib.rs (new)

+pub enum VictoriaMetricsRemoteWriteError { Zstd(String), RemoteWrite(RemoteWriteError) }
+pub struct Decoder<B: SampleBuilder> { /* zstd context, buffer, prometheus_remote_write::Decoder<B> */ }
+impl<B: SampleBuilder> Decoder<B> {
+    pub fn new(builder: B) -> Self;
+    pub fn decode(&mut self, body: &[u8], limits: &prometheus_remote_write::Limits)
+        -> Result<Vec<B::Sample>, VictoriaMetricsRemoteWriteError>;
+}
+pub fn encode(request: &prometheus_remote_write::WriteRequest) -> Vec<u8>;   // as a sender: zstd, size in the frame

crates/adapters/ingest/otlp/src/lib.rs (new)

+pub struct Limits { pub max_decompressed_bytes: usize, pub max_points: usize }
+pub enum OtlpError { Gzip(String), DecompressedTooLarge(usize), Protobuf(String), TooManyPoints(usize) }
+pub struct Point { pub labels: Vec<(String, String)>, pub timestamp_ms: i64, pub value: f64 }   // labels sorted, `__name__` included
+pub fn decode(body: &[u8], content_encoding: Option<&str>, limits: &Limits) -> Result<Vec<Point>, OtlpError>;
+pub use opentelemetry_proto::tonic as proto;   // the messages, for senders and tests

crates/data-plane/src/remote_write.rs

 pub fn decode_samples(body: &[u8], limits: &Limits) -> Result<Vec<RawSample>, RemoteWriteError>;
+pub fn decode_victoriametrics_samples(body: &[u8], limits: &Limits) -> Result<Vec<RawSample>, VictoriaMetricsRemoteWriteError>;
+pub fn decode_otlp_samples(body: &[u8], content_encoding: Option<&str>, limits: &Limits) -> Result<Vec<RawSample>, otlp::OtlpError>;

crates/data-plane/src/lib.rs routes (outside forward mode)

 .route("/api/v1/write", post(write).layer(write_body_limit))
+.route("/api/v1/import", post(write_victoriametrics).layer(write_body_limit))
+.route("/v1/metrics", post(write_otlp).layer(write_body_limit))

Tests

  • victoriametrics_remote_write (6):
    • Two ported from ASAPQuery: test_zstd_decode_single_sample and test_decode_invalid_zstd.
    • The same samples as the snappy body, with the series cache kept across requests.
    • Bodies with no size in the frame and multi-frame bodies.
    • Invalid series.
    • Compressed, decompressed and sample limits, including a 64 MiB zstd bomb that keeps no large buffer.
  • otlp (5):
    • Gauges and sums, and label precedence, modelled on ASAPQuery's OTLP test exporter (counter, up-down counter).
    • _sum/_count for histogram, exponential histogram and summary.
    • Skipped sketch points and skipped unnamed metrics.
    • gzip.
    • Malformed and oversized bodies.
  • prometheus_remote_write (+1): decode_uncompressed equals decode, and enforces the size limit.
  • data_plane tests/ingest_protocols.rs (+3):
    • The same plan fed through /api/v1/write, /api/v1/import and /v1/metrics (plain and gzip) gives byte-identical planned answers over the last minute, and the same samples_accepted.
    • The three decoders give the same interned series (pointer-equal &'static Series), timestamps and value bits.
    • Malformed bodies get 400 and ingest nothing.

Gate on the restacked head (11a1c3a): cargo fmt --all -- --check and cargo clippy --workspace --all-targets --locked -- -D warnings clean, cargo test --workspace --locked: 218 passed, 0 failed, 3 ignored (51 suites) (#881: 203 passed, 0 failed, 3 ignored (46 suites; planner_executor_parity::push_precompute_stores_the_window_paths_view_rows failed once under load and passed alone); +15 new). forward_mode::refused_deliveries_are_retried_until_accepted failed once under load (a race between the mock raw store counting the accepted delivery and the forwarder counting it; code this PR does not touch) and passed 5 of 5 reruns and in the full run.

Parity

This uses the uncommitted dump test from #880/#881, with additions:

  • a malformed body and an empty body to /api/v1/write;
  • /api/v1/status/asap.

The fixture is the plan of sum by (job) (sum_over_time(data[10s])) with 3 series written through 60 s. The dump records:

  • planned instant and range queries, cached steps, not-ready and unplanned queries, each with and without --no-forward;
  • headers except date;
  • the /metrics names and label sets.

The dump is byte-identical to #881's head (32,039 bytes both).

Benchmarks

ingest_bench 10000 120 views 1 persist and decode_bench, release builds, same host, cores 0–15, #881's head and this branch alternating.

#881 head this PR
ingest: writes acknowledged (samples/s, 9 runs) 6.70–6.95 M, median 6.84 M 6.45–6.90 M, median 6.78 M
ingest: every window refreshed (s) 8.60–10.63 (one outlier), median 8.67 8.59–9.76, median 8.65
decode, one series per sample (µs/sample) 0.080–0.081 0.080 (5 runs, final head)
decode, 100 samples per series (µs/sample) 0.020 0.020

The write-acknowledged spread is noise: 1.2 M samples are written in 0.17–0.19 s, at a 10 ms resolution. With #[inline] only on the shared request loop, one series per sample decoded at 0.082 µs (6 of 6 runs, about +2%). With #[inline(always)] (commit 4) it decodes at 0.080 µs, the same as the base, in 5 of 5 interleaved runs.

Deviations

  • Forward mode does not serve the new routes. Forward mode delivers accepted Remote Write bodies to the raw store, which then answers what the plan does not. VictoriaMetrics and OTLP samples would reach the engine but not the raw store. Rather than answer wrongly, those paths keep today's behavior (proxied to the raw store). Re-encoding their samples as Remote Write for the tee is deferred.
  • OTLP over gRPC (ASAPQuery's port 4317) is not ported. It would need a tonic server and a second listener. Only OTLP/HTTP POST /v1/metrics is served.
  • Stricter than ASAPQuery. A VictoriaMetrics series with no __name__ or with a label twice is rejected with 400, as a Prometheus Remote Write series is (ASAPQuery's decoder accepted both). An OTLP point attribute named __name__ is replaced by the metric name.
  • OTLP labels are copied. Each point's labels come back as strings and are interned per point. OTLP is not on a measured path; a SampleBuilder-style interface for OTLP is deferred until it is.
  • No decode timing for the new routes. remote_write_decode keeps counting Prometheus Remote Write only, so /metrics is unchanged.
  • Label names are as sent. Attribute names such as service.name are not sanitized into Prometheus label names, as in ASAPQuery.
  • Doc. docs(design): repository layout and engine boundaries #874's doc is updated on its branch: the adapter dependency rule, Answer/ResultSample in common, why ingest adapters decode into caller types and not a boundary batch, and the verbatim forward, with FallbackClient as the seam for step 8.

@zzylol zzylol added area: data plane Runtime ingestion, storage, and query-serving data paths area: query engine PromQL lowering, execution, result shaping, and fallback behavior feature: PromQL PromQL compatibility and execution semantics labels Nov 26, 2026
@zzylol zzylol added enhancement New feature or request and removed feature: PromQL PromQL compatibility and execution semantics area: query engine PromQL lowering, execution, result shaping, and fallback behavior labels Nov 27, 2026
Two ingest adapters ported from ASAPQuery's main, as crates under
crates/adapters/ingest/, served by the data plane on ASAPQuery's routes:

- victoriametrics_remote_write: the Remote Write protobuf, zstd-compressed.
  Its Decoder decompresses and hands the protobuf to the Remote Write
  decoder (new Decoder::decode_uncompressed), so samples decode into the
  caller's types with the same validation and series cache.
  POST /api/v1/import.
- otlp: OTLP/HTTP metrics (protobuf, gzip optional) into one point per
  sample, as ASAPQuery's receiver reads them. POST /v1/metrics, answering
  {"rejected":0}.

Both feed the engine as Remote Write does (same 400/503/500), and are not
served in forward mode, which delivers only Remote Write bodies to the raw
store. Existing endpoints are unchanged.
- otlp: one push per data point for every metric type; drop encode and
  Limits' Default (test-only); error text as ASAPQuery's.
- victoriametrics_remote_write: one-pass zstd when the frame states its
  size, streaming otherwise with the window capped by the size limit;
  reuse the Remote Write decoder's buffer cap; no re-exports.
- data-plane: VictoriaMetrics decodes no longer counted as Remote Write
  decode time; OTLP limits mapped in decode_otlp_samples; a test that the
  three decoders give the same interned series and samples.
@zzylol
zzylol force-pushed the refactor/layout-adapters branch from a64b54c to 5d5b323 Compare November 28, 2026 00:56
@zzylol
zzylol force-pushed the refactor/layout-ingest-adapters branch from 93d4d49 to 11a1c3a Compare November 28, 2026 00:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: data plane Runtime ingestion, storage, and query-serving data paths enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant