Skip to content

refactor: Remote Write and Prometheus HTTP API into crates/adapters (layout step 6) - #881

Draft
zzylol wants to merge 4 commits into
refactor/layout-engines-traitsfrom
refactor/layout-adapters
Draft

zzylol wants to merge 4 commits into
refactor/layout-engines-traitsfrom
refactor/layout-adapters

Conversation

@zzylol

@zzylol zzylol commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: after feat: engines as concrete types; PlanInstaller and QueryDispatcher (layout step 5b) #880 the protocol code still lives in data-plane. The Remote Write decoder (remote_write.rs) and the Prometheus HTTP API (prometheus.rs) can reach any engine or store type, and the forward-mode proxy is a set of private helpers in lib.rs. Steps 7–8 need adapter crates that depend on common only, as the design says.
  • Change: step 6 of docs/design/repo-layout.md (docs(design): repository layout and engine boundaries #874).
    • crates/adapters/ingest/prometheus-remote-write (prometheus_remote_write): the decoder. It depends on no workspace crate. It is generic over a SampleBuilder (the caller's series handle and sample type), so the data plane still decodes straight into storage's RawSample, with no copy.
    • crates/adapters/query/prometheus-http (prometheus_http): query parameters, response bodies, and fallback::PrometheusHttpFallback, the forward proxy. The routes call its forward (the request as received). It also implements common::FallbackClient for a parsed QueryRequest. It depends on common only.
    • ResultSample and Answer (Arc<Vec<ResultSample>>) move from query to common, because the response writers need them.
    • The forward-mode ingest tee (raw_forward.rs) stays in data-plane.
  • Effect: no behavior change. The fixture's HTTP answers and /metrics names are byte-identical with feat: engines as concrete types; PlanInstaller and QueryDispatcher (layout step 5b) #880's head, with and without --no-forward. Remote Write decoding is 11–12% faster per sample (see Benchmarks); a first cut was 2–10% slower, and the cause is fixed here.

Review guide

  • Base: refactor/layout-engines-traits (feat: engines as concrete types; PlanInstaller and QueryDispatcher (layout step 5b) #880). Stacked draft.
  • Commits:
    1. The move (files, crates, imports, README).
    2. The decoder's speed across the crate boundary (see Benchmarks), and SampleBuilder in place of two closures.
    3. Review fixes: forward returns the response as received; common::Answer; names; unused dependencies.
  • Read first: crates/data-plane/src/remote_write.rs (the seam, 40 lines), then Decoder and SampleBuilder at the top of crates/adapters/ingest/prometheus-remote-write/src/lib.rs, then crates/adapters/query/prometheus-http/src/fallback.rs, then forward_path in crates/data-plane/src/lib.rs.
  • Mechanical: prometheus-http/src/lib.rs is data-plane/src/prometheus.rs with imports and visibility changed (git diff -M <#880 head>..HEAD). The decoder's walk (decode_series, push_samples, Reader, SeriesCache) is the old code with the series type as a parameter. Tests and benchmarks change imports only.

Old → new

Old New
data_plane::remote_write::{WriteRequest, TimeSeries, Label, Sample, Limits, RemoteWriteError, encode} prometheus_remote_write::… (same items)
data_plane::remote_write::decode_samples (two thread-locals: buffer, series cache) data_plane::remote_write::decode_samples: one thread-local Decoder<Interned>, Interned: SampleBuilder interning into storage::series_ids
data_plane::prometheus::{InstantQuery, RangeQuery, BadParameter, VectorResponse, range_response_body, bad_data} prometheus_http::…; InstantQuery::parse, RangeQuery::parse and BadParameter are pub (were pub(crate))
lib.rs NOT_FORWARDED, forwarded_headers, forward_client, the send/read half of forward_path prometheus_http::fallback::PrometheusHttpFallback::{new, with_base_url, with_timeout, forward}
DataPlane::{prometheus_url, client} DataPlane::fallback (private)
(none) impl common::FallbackClient for PrometheusHttpFallback
query::ResultSample, query::result_cache::Answer common::ResultSample, common::Answer
asap_types::workload::SqlDialect also common::SqlDialect

Dependency graph

prometheus_remote_write ──► (no workspace crate) prost, snap, ahash, hashbrown, thiserror
prometheus_http ─────────► common             (reqwest, bytes, serde, serde_json, ryu, ahash, form_urlencoded)
data_plane ──► prometheus_remote_write, prometheus_http, precompute, query, storage, common, internal_metrics
precompute ──► common, storage, internal_metrics, asap-executor
query      ──► common, storage, internal_metrics, asap-executor
storage    ──► common, internal_metrics, asap-executor

data_plane drops ahash, hashbrown, ryu, prost, serde and thiserror (only the moved code used them); snap and ahash become dev-dependencies (a reference-decoder test and a benchmark).

Behavior: before → after

No change. The routes still forward the client's own request (method, path, URL query, body, end-to-end headers), and copy back the server's status, body and Content-Type byte for byte. With the plan of sum by (job) (sum_over_time(data[10s])), 3 series written through 60 s and the barrier at 60 s, every response below is byte-identical with #880's head (headers except date, then the body), and so are the /metrics names and label sets:

Request --no-forward forwarding (to an unreachable server)
planned instant query at time=60, and at time=50.000 with surrounding spaces 200, x-asap-execution: plan same
planned range query 20–60 s, step 10, twice (the second from the result cache) 200, plan same
planned query at time=90 (window not stored), range 50–90 s 422, refused, the reason 502 forwarding to Prometheus: …, x-asap-forward-reason
up (not planned) 422, the installed plan has no query "up" 502, no reason header

Interfaces

crates/adapters/ingest/prometheus-remote-write/src/lib.rs (new crate; the message types, Limits, RemoteWriteError and encode moved unchanged)

+/// The caller's series and sample types, which a [`Decoder`] decodes into.
+pub trait SampleBuilder {
+    /// A series handle, kept in the decoder's cache for every series seen.
+    type Series: Copy;
+    type Sample;
+    /// The handle of a series seen for the first time: its labels, parsed and validated, in request order.
+    fn intern(&mut self, labels: &[(&str, &str)]) -> Self::Series;
+    fn sample(series: Self::Series, timestamp_ms: i64, value: f64) -> Self::Sample;
+}
+/// A decoder's state, kept between requests: its decompression buffer and its series cache.
+pub struct Decoder<B: SampleBuilder> { /* decompressed: Vec<u8>, cache: SeriesCache<B> */ }
+impl<B: SampleBuilder> Decoder<B> {
+    pub fn new(builder: B) -> Self;
+    pub fn decode(&mut self, body: &[u8], limits: &Limits) -> Result<Vec<B::Sample>, RemoteWriteError>;
+}
-pub fn decode_samples(body: &[u8], limits: &Limits) -> Result<Vec<RawSample>, RemoteWriteError>; // data_plane::remote_write

crates/data-plane/src/remote_write.rs (now only the seam)

 pub fn decode_samples(body: &[u8], limits: &Limits) -> Result<Vec<RawSample>, RemoteWriteError>;
+struct Interned; // SampleBuilder: Series = &'static storage::series_ids::Series, Sample = RawSample

crates/adapters/query/prometheus-http/src/fallback.rs (new)

+/// The server's response to a forwarded request, as received.
+pub struct ForwardedResponse { pub status: StatusCode, pub content_type: Option<HeaderValue>, pub body: Bytes }
+/// Sends requests to one Prometheus-compatible server.
+pub struct PrometheusHttpFallback { /* base_url, client */ }
+impl PrometheusHttpFallback {
+    pub fn new(base_url: &str, timeout: Duration) -> Self;
+    pub fn with_base_url(self, base_url: &str) -> Self;
+    pub fn with_timeout(self, timeout: Duration) -> Self;
+    /// The request as received, end-to-end headers only (the old `forwarded_headers`).
+    pub async fn forward(&self, method: Method, path: &str, query: Option<&str>, headers: &HeaderMap,
+        body: impl Into<Body>) -> Result<ForwardedResponse, FallbackError>;
+}
+/// GET /api/v1/query (query, time) or /api/v1/query_range (query, start, end, step), seconds; PromQL or MetricsQL.
+impl FallbackClient for PrometheusHttpFallback { async fn execute(..) -> Result<FallbackResponse, FallbackError>; }

crates/common/src/query_result.rs

+/// One instant query's answer as the query engine returns it natively, one row per series.
+pub type Answer = Arc<Vec<ResultSample>>;
+/// One row of an [`Answer`]: labels shared (an `Arc`), unlike `InstantVectorElement`.
+pub struct ResultSample { pub labels: Arc<LabelSet>, pub value: f64 }

crates/data-plane/src/lib.rs

-pub mod prometheus;
 pub struct DataPlane {
-    pub prometheus_url: String,
-    pub limits: remote_write::Limits,
+    pub limits: prometheus_remote_write::Limits,
-    client: reqwest::Client,
+    fallback: PrometheusHttpFallback,
 }

Exceptions and decisions

  1. The Remote Write adapter decodes into the caller's types, not into a boundary batch. A boundary batch (#935's RawDataBatch, not in common) holds a BTreeMap<String, String> per series per request; building it, then interning it, would copy every label on the ingest hot path. The SampleBuilder parameter keeps the zero-copy decode and still keeps the adapter free of every workspace crate (it does not even need common). docs(design): repository layout and engine boundaries #874 says so.
  2. The routes do not go through FallbackClient. The trait's QueryRequest cannot carry the client's own method, extra parameters (timeout, limit, stats, …), raw times or body, and the catch-all proxy has no query at all. Sending a rebuilt request would change what Prometheus receives. So PrometheusHttpFallback::forward proxies the request as received, and FallbackClient::execute is the trait seam for callers that only have a QueryRequest (steps 7–8). Today only its tests call it.
  3. QueryOutcome and NotAnswerableReason stay in data-plane (deferred from feat: engines as concrete types; PlanInstaller and QueryDispatcher (layout step 5b) #880). No adapter needs them: the HTTP handlers that read them stay in data-plane.
  4. ResultSample and Answer move to common. prometheus_http writes them and may not depend on query; they are the native answer the design's dispatcher returns on the hot path.

Testing

Scope #880 head this PR (5d5b323)
cargo fmt --all -- --check pass pass
cargo build --workspace --all-targets --locked pass pass
cargo clippy --workspace --all-targets --locked -- -D warnings pass pass
cargo test --workspace --locked 200 passed, 0 failed, 3 ignored (42 suites) 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)

The sorted lists of passing test names differ from #880's head only by the 3 new tests below and by the 14 moved unit tests, which keep their names under their new crates' roots: prometheus::tests::* (7) and remote_write::tests::* (7) are now tests::* in prometheus_http and prometheus_remote_write. In an earlier gate run under load (another build on the same host), planner_executor_parity::push_precompute_stores_the_window_paths_view_rows failed once with a window-expiry difference; it passed when run alone on #880's head, and it passed in this PR's final gate. It depends on timing; this change does not touch it.

  • New tests (3), in prometheus_http::fallback: sends_a_parsed_query_as_a_prometheus_request (instant and range requests, seconds to the millisecond including negative times, headers passed, response passed back), refuses_sql_and_reports_an_unreachable_server, forwards_end_to_end_headers_only. The decoder's unit tests now run against a test SampleBuilder, and decoded_samples_match_the_full_decode also checks that a repeated series is interned once.
  • End to end: the uncommitted dump test of feat: engines as concrete types; PlanInstaller and QueryDispatcher (layout step 5b) #880 (zz_parity_dump, imports updated) gives byte-identical output on both trees: planned, cached, not-ready and unplanned queries, with and without --no-forward, plus the /metrics names and label sets.

Benchmarks

Same quiet host, both trees built the same way, runs interleaved.

Benchmark #880 head (4f5b4f8) this PR Change
ingest_bench 10000 120 views 1 persist (3 runs; median [min–max]): every write acknowledged 0.19 s [0.18–0.19] 0.18 s [0.17–0.18] noise
… every window refreshed 9.04 s [8.89–11.97] 8.63 s [8.62–11.64] noise (one run in three of each tree refreshes about 3 s later, as in #880)
… CPU, all threads 20.98 s [20.97–21.04] 20.79 s [20.77–20.90] −1%
decode_bench (2,000 rounds, 5 digits, 1 core, interleaved): one series per sample 90.3 ns per sample 80.5 ns −11%
… 100 samples per series 22.6–23.3 ns per sample 19.5 ns −14%

The first cut was 2–10% slower in decode_bench, with the same instruction count but lower IPC. The cause: Reader::varint_slow, an out-of-line method taking &mut Reader, became a call into another crate, so the reader escaped and its position was reloaded from the stack on every field of the first-pass loop. It is now a free function of (bytes, position), and sample_fast/sample_generic are #[inline] (the same-crate build inlined them; decode_bench's first sample of each series has value and timestamp 0, both omitted by protobuf, so it takes sample_generic).

Whole-stack review fixes

  • range_response_body's doc comment no longer names a storage internal (series_ids::result_labels): "each series' labels are one Arc shared by every step's answer".
  • impl FallbackClient for PrometheusHttpFallback stays (the design requires it; steps 7–8 reach fallbacks through the trait), though today only its tests call it.
  • Re-verified on the restacked head (5d5b323): fmt, clippy and the test count above.

Deferred to steps 7–8 and #874

  • Done: docs(design): repository layout and engine boundaries #874 lists ResultSample/Answer in common, exception 1 and the routes' verbatim forward.
  • Steps 7–8: the dispatcher reaches non-Prometheus fallbacks (ClickHouse, Elastic) through FallbackClient; VictoriaMetrics Remote Write can reuse Decoder with its own SampleBuilder.
  • Optional, measured first: a two-byte arm in Reader::varint (series of 128 bytes or more take varint_slow for their length, as before).

@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 the enhancement New feature or request label Nov 27, 2026
Step 6 of docs/design/repo-layout.md.

- crates/adapters/ingest/prometheus-remote-write (prometheus_remote_write):
  the Remote Write v1 decoder, with no workspace dependency. Decoder<S> is
  generic over the caller's series handle and sample type, so the data
  plane still decodes straight into storage's RawSample (no copy); its
  buffer and series cache move from two thread-locals into the decoder,
  which data-plane keeps in one thread-local (remote_write.rs).
- crates/adapters/query/prometheus-http (prometheus_http): query
  parameters and response bodies, depending on common only, and the
  fallback client PrometheusHttpFallback: forward() proxies a request as
  received (the routes use it, as before), and it implements
  common::FallbackClient for a parsed QueryRequest.
- ResultSample moves from query to common: the response writers need it.
- The forward-mode ingest tee stays in data-plane.
decode_bench was 2% to 10% slower per sample after the move. The cause:
Reader::varint_slow, an out-of-line method taking &mut Reader, is now a
call into another crate, so the reader escaped and its position was
reloaded from the stack on every field of the first-pass loop. It is a
free function of (bytes, position) now, and sample_fast and
sample_generic are #[inline], as the same-crate build inlined them.

The decoder takes a SampleSink (series and sample types) in place of two
closures: one type parameter, no closure arguments threaded through.
- PrometheusHttpFallback::forward returns the server's response as
  received (StatusCode, Option<HeaderValue>, Bytes): no body copy and a
  Content-Type passed through byte for byte, as before the move; only
  FallbackClient::execute converts to FallbackResponse.
- with_timeout replaces the base_url getter.
- common::Answer (Arc<Vec<ResultSample>>) replaces query's alias and the
  adapter's copy; common re-exports SqlDialect (prometheus_http drops its
  asap-types dev-dependency).
- SampleSink is SampleBuilder; Decoder::new only; adapter docs name no
  data-plane type.
- data_plane drops serde and thiserror, which only the moved code used.
…rnal

Each series' labels are one Arc shared by every step's answer; the
adapter need not know where storage builds them.
@zzylol
zzylol force-pushed the refactor/layout-engines-traits branch from 4f5b4f8 to 7683fc9 Compare November 28, 2026 00:56
@zzylol
zzylol force-pushed the refactor/layout-adapters branch from a64b54c to 5d5b323 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 area: query engine PromQL lowering, execution, result shaping, and fallback behavior enhancement New feature or request feature: PromQL PromQL compatibility and execution semantics

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant