From f09c29c43643c4cea7203df26a51c98234619516 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 22 Nov 2026 18:58:20 +0000 Subject: [PATCH 1/3] feat(data_plane): forward mode: raw samples to a VictoriaMetrics raw store, unplanned queries proxied MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --raw-store-url URL turns it on (off by default, and refused with --no-forward). With forward mode off, nothing changes. - Writes. An accepted Remote Write request is acknowledged (204) only once the engine has admitted its samples and its body is queued for the raw store. - The queue is bounded in bytes (--raw-forward-queue-bytes, default 256 MiB, in-flight bodies included). When it is full, the request gets 503 before the engine sees it, so a retry duplicates nothing in either store. - Workers on their own thread (--raw-forward-concurrency, default 4) deliver bodies unchanged to URL/api/v1/write. They retry 429, 5xx, timeouts and connection errors with a 100 ms to 5 s backoff, and drop and count any other 4xx. - Queries. Queries the plan does not answer, and every other path (labels, series, label values, metadata), are proxied to the raw store with x-asap-execution: forwarded. Planned answers keep x-asap-execution: plan. - Metrics. asap_raw_forward_* on /metrics, and raw_forward in /api/v1/status/asap. Design and test plan: docs/design/demo-plan.md §10.1. Tests F1-F8 are in tests/forward_mode.rs. --- data_plane/src/lib.rs | 108 ++++++- data_plane/src/main.rs | 27 ++ data_plane/src/raw_forward.rs | 333 ++++++++++++++++++++ data_plane/tests/forward_mode.rs | 504 +++++++++++++++++++++++++++++++ docs/design/demo-plan.md | 98 +++++- 5 files changed, 1054 insertions(+), 16 deletions(-) create mode 100644 data_plane/src/raw_forward.rs create mode 100644 data_plane/tests/forward_mode.rs diff --git a/data_plane/src/lib.rs b/data_plane/src/lib.rs index 5cf378f4..a7afeae0 100644 --- a/data_plane/src/lib.rs +++ b/data_plane/src/lib.rs @@ -8,6 +8,11 @@ //! queries with query runs, all through the Planner's executor //! ([`engine`]); every other query, and any planned query it cannot //! answer, is forwarded to Prometheus (or refused with `--no-forward`). +//! +//! Forward mode (`--raw-store-url`, [`raw_forward`]): every accepted Remote +//! Write request is also delivered to a raw store (VictoriaMetrics), which +//! then answers every query the plan does not and every other API path +//! (labels, series, metadata), proxied with `x-asap-execution: forwarded`. pub mod engine; pub mod ingestion; @@ -18,6 +23,7 @@ pub mod pipelines; pub mod prometheus; pub mod push; pub mod query; +pub mod raw_forward; pub mod remote_write; pub mod result_cache; pub mod segment; @@ -30,7 +36,7 @@ use std::sync::Arc; use std::time::Duration; use axum::body::Bytes; -use axum::extract::{DefaultBodyLimit, RawQuery, State}; +use axum::extract::{DefaultBodyLimit, OriginalUri, RawQuery, State}; use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; @@ -62,6 +68,9 @@ pub struct DataPlane { /// gets an error with the reason ([`EngineOptions::no_forward`]). pub no_forward: bool, client: reqwest::Client, + /// Forward mode: delivers accepted Remote Write bodies to the raw store, + /// which also answers what the plan does not. `None`: off. + pub raw_forward: Option, } impl DataPlane { @@ -94,9 +103,26 @@ impl DataPlane { limits: remote_write::Limits::default(), samples: AtomicU64::new(0), client: forward_client(DEFAULT_FORWARD_TIMEOUT), + raw_forward: None, }) } + /// Turns forward mode on: accepted Remote Write bodies are delivered to + /// the raw store at `options.url`, and queries the plan does not answer, + /// as well as any other path, are proxied to it (in place of + /// `prometheus_url`). Refused with `--no-forward`, which forbids proxying. + pub fn with_raw_forward( + mut self, + options: raw_forward::RawForwardOptions, + ) -> anyhow::Result { + if self.no_forward { + anyhow::bail!("--raw-store-url proxies unplanned queries, which --no-forward refuses"); + } + self.prometheus_url = options.url.clone(); + self.raw_forward = Some(raw_forward::RawForwarder::start(options)?); + Ok(self) + } + /// Bounds each forwarded query by `timeout`, from sending the request to /// reading the whole response (default [`DEFAULT_FORWARD_TIMEOUT`]). pub fn with_forward_timeout(mut self, timeout: Duration) -> Self { @@ -116,15 +142,43 @@ pub fn router(state: Arc) -> Router { // axum refuses bodies over 2 MB by default; Remote Write allows up to // `max_compressed_bytes` and answers larger bodies with 413. let write_body_limit = DefaultBodyLimit::max(state.limits.max_compressed_bytes); - Router::new() + let forward_mode = state.raw_forward.is_some(); + let router = Router::new() .route("/api/v1/write", post(write).layer(write_body_limit)) .route("/api/v1/query", get(query).post(query)) .route("/api/v1/query_range", get(query_range).post(query_range)) .route("/api/v1/status/asap", get(status)) .route("/metrics", get(metrics)) .route("/api/v1/precompute/watermark", post(watermark)) - .route("/-/ready", get(ready)) - .with_state(state) + .route("/-/ready", get(ready)); + // Forward mode: any other path (labels, series, metadata, the raw + // store's UI) is proxied to the raw store. Off: those paths are 404. + let router = if forward_mode { + router.fallback(proxy) + } else { + router + }; + router.with_state(state) +} + +/// Forward mode: proxies a request the data plane does not serve to the raw +/// store, with `x-asap-execution: forwarded`. +async fn proxy( + state: State>, + method: Method, + OriginalUri(uri): OriginalUri, + headers: HeaderMap, + body: Bytes, +) -> Response { + forward_path( + state, + uri.path(), + method, + RawQuery(uri.query().map(str::to_string)), + headers, + body, + ) + .await } async fn write(State(state): State>, body: Bytes) -> Response { @@ -136,8 +190,26 @@ async fn write(State(state): State>, body: Bytes) -> Response { if count == 0 { return StatusCode::NO_CONTENT.into_response(); } + // Forward mode: room in the raw store's queue first, so a refused + // request reaches neither store and a retry duplicates nothing. + let reservation = match &state.raw_forward { + Some(forwarder) => match forwarder.reserve(body.len() as u64) { + Some(reservation) => Some(reservation), + None => { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "the raw store's forward queue is full", + ) + .into_response() + } + }, + None => None, + }; match state.engine.try_ingest(samples) { Ok(()) => { + if let Some(reservation) = reservation { + reservation.commit(body); + } state.samples.fetch_add(count, Ordering::Relaxed); StatusCode::NO_CONTENT.into_response() } @@ -228,6 +300,7 @@ async fn status(State(state): State>) -> Response { "samples_queued": state.engine.queued_samples(), "precompute_backlog": state.engine.precompute_backlog(), "ingestion": state.engine.stats(), + "raw_forward": state.raw_forward.as_ref().map(|f| f.status()), }); ( [(header::CONTENT_TYPE, "application/json")], @@ -240,11 +313,11 @@ async fn status(State(state): State>) -> Response { /// thread CPU and wall time, query latency, counters, backlogs, watermark /// lag, bytes held and each thread's CPU time ([`metrics`]). async fn metrics(State(state): State>) -> Response { - ( - [(header::CONTENT_TYPE, "text/plain; version=0.0.4")], - state.engine.render_metrics(), - ) - .into_response() + let mut text = state.engine.render_metrics(); + if let Some(forwarder) = &state.raw_forward { + forwarder.render(&mut text); + } + ([(header::CONTENT_TYPE, "text/plain; version=0.0.4")], text).into_response() } /// `text` as a header value: characters a header cannot carry (controls and @@ -493,14 +566,27 @@ fn forwarded_headers(headers: &HeaderMap) -> HeaderMap { /// `Authorization` and tenancy headers such as `X-Scope-OrgID`) and returns /// Prometheus's status, body and `Content-Type`. async fn forward( - State(state): State>, + state: State>, endpoint: &str, method: Method, + query: RawQuery, + headers: HeaderMap, + body: Bytes, +) -> Response { + let path = format!("/api/v1/{endpoint}"); + forward_path(state, &path, method, query, headers, body).await +} + +/// [`forward`] for any `path` of the Prometheus (or raw store) server. +async fn forward_path( + State(state): State>, + path: &str, + method: Method, RawQuery(query): RawQuery, headers: HeaderMap, body: Bytes, ) -> Response { - let mut url = format!("{}/api/v1/{endpoint}", state.prometheus_url); + let mut url = format!("{}{path}", state.prometheus_url); if let Some(query) = query { url = format!("{url}?{query}"); } diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index d3bee27f..34f4860e 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -102,6 +102,20 @@ struct Args { /// with an error giving the reason. #[arg(long)] no_forward: bool, + /// Forward mode (off by default): deliver every accepted Remote Write + /// request to this raw store (a VictoriaMetrics single-node base URL), + /// which also answers every query the plan does not answer and every + /// other API path, in place of `--prometheus-url`. Cannot be used with + /// `--no-forward`. + #[arg(long, conflicts_with = "no_forward")] + raw_store_url: Option, + /// Forward mode: bytes of Remote Write bodies queued or in flight to the + /// raw store beyond which writes are refused with 503. + #[arg(long, default_value_t = data_plane::raw_forward::RawForwardOptions::new("").max_queued_bytes)] + raw_forward_queue_bytes: u64, + /// Forward mode: Remote Write requests delivered to the raw store at once. + #[arg(long, default_value_t = data_plane::raw_forward::RawForwardOptions::new("").concurrency)] + raw_forward_concurrency: usize, /// The most bytes one ingestion or query run may hold. #[arg(long, default_value_t = EngineOptions::default().run_memory_limit_bytes)] run_memory_limit_bytes: usize, @@ -219,6 +233,19 @@ async fn main() -> anyhow::Result<()> { )? .with_forward_timeout(Duration::from_secs(args.forward_timeout_seconds)), ); + let state = match &args.raw_store_url { + Some(url) => { + let mut options = data_plane::raw_forward::RawForwardOptions::new(url.clone()); + options.max_queued_bytes = args.raw_forward_queue_bytes; + options.concurrency = args.raw_forward_concurrency; + let state = Arc::try_unwrap(state) + .map_err(|_| anyhow::anyhow!("the data plane is already shared"))? + .with_raw_forward(options)?; + tracing::info!(raw_store = %url, "forward mode: raw samples and unplanned queries go to the raw store"); + Arc::new(state) + } + None => state, + }; tracing::info!(queries = state.queries.len(), "installed plan"); let listener = tokio::net::TcpListener::bind(&args.listen).await?; tracing::info!(address = %listener.local_addr()?, "listening"); diff --git a/data_plane/src/raw_forward.rs b/data_plane/src/raw_forward.rs new file mode 100644 index 00000000..ffcaf1c5 --- /dev/null +++ b/data_plane/src/raw_forward.rs @@ -0,0 +1,333 @@ +//! Forward mode (`--raw-store-url`, docs/design/demo-plan.md §10.1): every +//! Remote Write request the data plane accepts is also delivered, unchanged, +//! to a raw store (a VictoriaMetrics single-node), so queries the plan does +//! not answer can be proxied to it. +//! +//! A request is acknowledged (204) only once the engine has admitted its +//! samples and its body is queued for the raw store. The queue is bounded in +//! bytes (bodies in flight included); when it is full the request is refused +//! with 503 before the engine sees it, so a sender's retry never duplicates +//! samples in either store. Queued bodies are delivered by a few workers on +//! their own thread and retried until the raw store accepts them (2xx), with +//! an exponential backoff on 429, 5xx, timeouts and connection errors. Any +//! other answer (a 4xx: the raw store will never accept that body) drops the +//! body and counts it. The queue is in memory: a crash loses at most the +//! bytes queued. + +use std::collections::VecDeque; +use std::fmt::Write as _; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::body::Bytes; +use tokio::sync::Notify; + +/// How raw samples are forwarded. +#[derive(Debug, Clone)] +pub struct RawForwardOptions { + /// Base URL of the raw store; bodies go to `{url}/api/v1/write`. + pub url: String, + /// Bytes of request bodies queued or in flight beyond which writes are + /// refused with 503. + pub max_queued_bytes: u64, + /// Requests delivered at once. + pub concurrency: usize, + /// Bound on one delivery attempt. + pub timeout: Duration, +} + +impl RawForwardOptions { + pub fn new(url: impl Into) -> Self { + Self { + url: url.into().trim_end_matches('/').to_string(), + max_queued_bytes: 256 << 20, + concurrency: 4, + timeout: Duration::from_secs(30), + } + } +} + +/// The forwarder's counters, exported on `/metrics` and the status JSON. +#[derive(Default)] +struct Counters { + queued_bytes: AtomicU64, + queued_requests: AtomicU64, + delivered: AtomicU64, + delivered_bytes: AtomicU64, + retried: AtomicU64, + dropped: AtomicU64, + refused: AtomicU64, +} + +struct Shared { + options: RawForwardOptions, + queue: Mutex>, + ready: Notify, + counters: Counters, + /// Set when the forwarder is dropped: the workers stop. + closed: AtomicBool, +} + +/// Delivers accepted Remote Write bodies to the raw store. +pub struct RawForwarder { + shared: Arc, +} + +/// Room reserved in the queue for one body; released unless committed. +pub struct Reservation<'a> { + forwarder: &'a RawForwarder, + bytes: u64, + committed: bool, +} + +impl Reservation<'_> { + /// Queues `body` (of the reserved size) for delivery. + pub fn commit(mut self, body: Bytes) { + self.committed = true; + let shared = &self.forwarder.shared; + shared + .queue + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push_back(body); + shared + .counters + .queued_requests + .fetch_add(1, Ordering::SeqCst); + shared.ready.notify_one(); + } +} + +impl Drop for Reservation<'_> { + fn drop(&mut self) { + if !self.committed { + self.forwarder + .shared + .counters + .queued_bytes + .fetch_sub(self.bytes, Ordering::SeqCst); + } + } +} + +impl RawForwarder { + /// Starts `options.concurrency` delivery workers on a thread of their own. + pub fn start(options: RawForwardOptions) -> std::io::Result { + let shared = Arc::new(Shared { + options, + queue: Mutex::new(VecDeque::new()), + ready: Notify::new(), + counters: Counters::default(), + closed: AtomicBool::new(false), + }); + let worker_shared = shared.clone(); + std::thread::Builder::new() + .name("raw-forward".into()) + .spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a current-thread runtime"); + runtime.block_on(async move { + let client = reqwest::Client::builder() + .timeout(worker_shared.options.timeout) + .build() + .expect("reqwest client with only a timeout set"); + let workers: Vec<_> = (0..worker_shared.options.concurrency.max(1)) + .map(|_| tokio::spawn(deliver(worker_shared.clone(), client.clone()))) + .collect(); + for worker in workers { + let _ = worker.await; + } + }); + })?; + Ok(Self { shared }) + } + + /// Reserves room for a body of `bytes`; `None` (and the refusal is + /// counted) when the queue is full. An empty queue always takes one + /// body, so a bound smaller than one request cannot refuse it forever. + pub fn reserve(&self, bytes: u64) -> Option> { + let counters = &self.shared.counters; + let max = self.shared.options.max_queued_bytes; + let mut current = counters.queued_bytes.load(Ordering::SeqCst); + loop { + let total = current.saturating_add(bytes); + if current > 0 && total > max { + counters.refused.fetch_add(1, Ordering::Relaxed); + return None; + } + match counters.queued_bytes.compare_exchange( + current, + total, + Ordering::SeqCst, + Ordering::SeqCst, + ) { + Ok(_) => { + return Some(Reservation { + forwarder: self, + bytes, + committed: false, + }) + } + Err(now) => current = now, + } + } + } + + /// The raw store's base URL. + pub fn url(&self) -> &str { + &self.shared.options.url + } + + /// The counters as JSON, for `/api/v1/status/asap`. + pub fn status(&self) -> serde_json::Value { + let c = &self.shared.counters; + serde_json::json!({ + "url": self.shared.options.url, + "queued_bytes": c.queued_bytes.load(Ordering::Relaxed), + "queued_requests": c.queued_requests.load(Ordering::Relaxed), + "delivered_requests": c.delivered.load(Ordering::Relaxed), + "delivered_bytes": c.delivered_bytes.load(Ordering::Relaxed), + "retried_attempts": c.retried.load(Ordering::Relaxed), + "dropped_requests": c.dropped.load(Ordering::Relaxed), + "refused_writes": c.refused.load(Ordering::Relaxed), + }) + } + + /// The counters in the Prometheus text format. + pub fn render(&self, out: &mut String) { + let c = &self.shared.counters; + let load = |a: &AtomicU64| a.load(Ordering::Relaxed); + let _ = writeln!( + out, + "# HELP asap_raw_forward_queued_bytes Remote Write bytes queued or in flight to the raw store.\n# TYPE asap_raw_forward_queued_bytes gauge\nasap_raw_forward_queued_bytes {}", + load(&c.queued_bytes) + ); + let _ = writeln!( + out, + "# HELP asap_raw_forward_queued_requests Remote Write requests queued or in flight to the raw store.\n# TYPE asap_raw_forward_queued_requests gauge\nasap_raw_forward_queued_requests {}", + load(&c.queued_requests) + ); + let _ = writeln!( + out, + "# HELP asap_raw_forward_requests_total Remote Write requests forwarded to the raw store, by outcome.\n# TYPE asap_raw_forward_requests_total counter" + ); + for (outcome, value) in [ + ("delivered", load(&c.delivered)), + ("dropped", load(&c.dropped)), + ] { + let _ = writeln!( + out, + "asap_raw_forward_requests_total{{outcome=\"{outcome}\"}} {value}" + ); + } + for (name, help, value) in [ + ( + "asap_raw_forward_retries_total", + "Delivery attempts to the raw store that failed and were retried.", + load(&c.retried), + ), + ( + "asap_raw_forward_delivered_bytes_total", + "Remote Write bytes the raw store accepted.", + load(&c.delivered_bytes), + ), + ( + "asap_raw_forward_refused_writes_total", + "Remote Write requests refused with 503 because the forward queue was full.", + load(&c.refused), + ), + ] { + let _ = writeln!( + out, + "# HELP {name} {help}\n# TYPE {name} counter\n{name} {value}" + ); + } + } +} + +impl Drop for RawForwarder { + /// Stops the workers; bodies still queued are not delivered. + fn drop(&mut self) { + self.shared.closed.store(true, Ordering::SeqCst); + self.shared.ready.notify_waiters(); + } +} + +/// One delivery worker: takes the oldest queued body and delivers it, +/// retrying until the raw store accepts or rejects it. +async fn deliver(shared: Arc, client: reqwest::Client) { + let url = format!("{}/api/v1/write", shared.options.url); + loop { + let body = loop { + let next = shared + .queue + .lock() + .unwrap_or_else(|e| e.into_inner()) + .pop_front(); + match next { + Some(body) => break body, + None if shared.closed.load(Ordering::SeqCst) => return, + None => { + let notified = shared.ready.notified(); + if shared.closed.load(Ordering::SeqCst) { + return; + } + // Woken by a commit, or every second to see `closed`. + let _ = tokio::time::timeout(Duration::from_secs(1), notified).await; + } + } + }; + let mut backoff = Duration::from_millis(100); + loop { + let attempt = client + .post(&url) + .header("Content-Encoding", "snappy") + .header("Content-Type", "application/x-protobuf") + .header("X-Prometheus-Remote-Write-Version", "0.1.0") + .body(body.clone()) + .send() + .await; + let retry = match attempt { + Ok(response) if response.status().is_success() => { + shared.counters.delivered.fetch_add(1, Ordering::Relaxed); + shared + .counters + .delivered_bytes + .fetch_add(body.len() as u64, Ordering::Relaxed); + false + } + Ok(response) + if response.status().as_u16() == 429 || response.status().is_server_error() => + { + true + } + Ok(response) => { + tracing::warn!(status = %response.status(), "raw store rejected a Remote Write body; dropped"); + shared.counters.dropped.fetch_add(1, Ordering::Relaxed); + false + } + Err(error) => { + tracing::debug!(%error, "raw store unreachable; retrying"); + true + } + }; + if !retry || shared.closed.load(Ordering::SeqCst) { + break; + } + shared.counters.retried.fetch_add(1, Ordering::Relaxed); + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(Duration::from_secs(5)); + } + shared + .counters + .queued_bytes + .fetch_sub(body.len() as u64, Ordering::SeqCst); + shared + .counters + .queued_requests + .fetch_sub(1, Ordering::SeqCst); + } +} diff --git a/data_plane/tests/forward_mode.rs b/data_plane/tests/forward_mode.rs new file mode 100644 index 00000000..5ec1d020 --- /dev/null +++ b/data_plane/tests/forward_mode.rs @@ -0,0 +1,504 @@ +//! Forward mode (`--raw-store-url`, docs/design/demo-plan.md §10.1, tests +//! F1–F8): accepted Remote Write bodies are delivered unchanged to a raw +//! store (VictoriaMetrics in the demo, a recording mock here); queries the +//! plan does not answer, and any other path, are proxied to it with +//! `x-asap-execution: forwarded`; a full forward queue refuses writes with +//! 503 before the engine sees them, so retries duplicate nothing; failed +//! deliveries are retried until the raw store takes them. Off, the data +//! plane behaves as before. + +mod common; + +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use axum::body::{Body, Bytes}; +use axum::extract::{OriginalUri, State}; +use axum::http::{HeaderMap, Request, StatusCode}; +use axum::response::IntoResponse; +use axum::Router; +use control_plane::plan_workload; +use data_plane::engine::EngineOptions; +use data_plane::ingestion::IngestionOptions; +use data_plane::raw_forward::RawForwardOptions; +use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; +use data_plane::{router, DataPlane, EXECUTION_HEADER}; +use http_body_util::BodyExt; +use serde_json::{json, Value}; +use tokio::sync::Notify; +use tower::ServiceExt; + +const QUERY: &str = "sum by (job) (sum_over_time(data[30s]))"; + +fn plan_json() -> String { + let workload = serde_json::from_value(json!({ + "query_workload": {"language": "promql", "repeating_queries": [{ + "query": QUERY, + "demand": {"fixed_interval_at": {"interval": 10000, "evaluation_phase": 0}}, + "requirements": {}, + "predictability": {"predictable": {"known_at": null}}, + }]}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": 8.0}}, + "sources": {"data": {"series_count": 8, "sample_interval": 1000, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + serde_json::to_string(&plan_workload(&workload, &common::inputs(false)).unwrap().0).unwrap() +} + +fn options() -> EngineOptions { + EngineOptions { + ingest_threads: 2, + ingestion: IngestionOptions { + allowed_lateness_ms: 0, + stream_start_ms: Some(0), + ..IngestionOptions::default() + }, + ..EngineOptions::default() + } +} + +/// A data plane; with `raw_store`, in forward mode to it. +fn data_plane(raw_store: Option) -> (Router, Arc) { + let state = + DataPlane::with_options(plan_json(), "http://127.0.0.1:1".into(), options()).unwrap(); + let state = match raw_store { + Some(options) => state.with_raw_forward(options).unwrap(), + None => state, + }; + let state = Arc::new(state); + (router(state.clone()), state) +} + +/// What the mock raw store does with a Remote Write body. +#[derive(Clone, Copy, Debug)] +enum Answer { + Accept, + /// Answer this status this many more times, then accept. + Fail(StatusCode, usize), + /// Hold the request until `release` is notified. + Hang, +} + +/// A raw store that records what it gets. +struct Mock { + answer: Mutex, + release: Notify, + /// Each Remote Write body and its `Content-Encoding`, accepted or not. + writes: Mutex>, + /// Bodies accepted (2xx). + accepted: Mutex>, + /// Each other request: path and query. + reads: Mutex>, +} + +async fn mock_write( + State(mock): State>, + headers: HeaderMap, + body: Bytes, +) -> impl IntoResponse { + let encoding = headers + .get("content-encoding") + .map(|v| v.to_str().unwrap().to_string()) + .unwrap_or_default(); + mock.writes.lock().unwrap().push((body.clone(), encoding)); + let answer = *mock.answer.lock().unwrap(); + match answer { + Answer::Accept => { + mock.accepted.lock().unwrap().push(body); + StatusCode::NO_CONTENT + } + Answer::Fail(status, left) => { + *mock.answer.lock().unwrap() = if left > 1 { + Answer::Fail(status, left - 1) + } else { + Answer::Accept + }; + status + } + Answer::Hang => { + mock.release.notified().await; + mock.accepted.lock().unwrap().push(body); + StatusCode::NO_CONTENT + } + } +} + +async fn mock_read( + State(mock): State>, + OriginalUri(uri): OriginalUri, +) -> impl IntoResponse { + mock.reads.lock().unwrap().push(uri.to_string()); + axum::Json( + json!({"status": "success", "data": {"answered_by": "raw store", "path": uri.path()}}), + ) +} + +/// Serves a mock raw store on `listener`. +fn serve_mock(listener: tokio::net::TcpListener, answer: Answer) -> Arc { + let mock = Arc::new(Mock { + answer: Mutex::new(answer), + release: Notify::new(), + writes: Mutex::new(Vec::new()), + accepted: Mutex::new(Vec::new()), + reads: Mutex::new(Vec::new()), + }); + let app = Router::new() + .route("/api/v1/write", axum::routing::post(mock_write)) + .fallback(mock_read) + .with_state(mock.clone()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + mock +} + +async fn mock(answer: Answer) -> (Arc, String) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + (serve_mock(listener, answer), url) +} + +/// Forward options for `url` with a short retry path for tests. +fn forward_to(url: &str) -> RawForwardOptions { + let mut options = RawForwardOptions::new(url); + options.timeout = Duration::from_secs(5); + options +} + +/// The Remote Write body of series `0..8` at `seconds`. +fn body(seconds: std::ops::RangeInclusive) -> Vec { + let timeseries = (0..8) + .map(|i| TimeSeries { + labels: [ + ("__name__", "data".to_string()), + ("instance", format!("i{i}")), + ("job", format!("job{}", i % 4)), + ] + .into_iter() + .map(|(name, value)| Label { + name: name.into(), + value, + }) + .collect(), + samples: seconds + .clone() + .map(|second| Sample { + timestamp: second * 1000, + value: (second * (i + 1) % 17) as f64, + }) + .collect(), + }) + .collect(); + encode(&WriteRequest { timeseries }) +} + +async fn send(app: &Router, request: Request) -> (StatusCode, HeaderMap, Bytes) { + let response = app.clone().oneshot(request).await.unwrap(); + let (status, headers) = (response.status(), response.headers().clone()); + ( + status, + headers, + response.into_body().collect().await.unwrap().to_bytes(), + ) +} + +async fn write(app: &Router, body: Vec) -> StatusCode { + send( + app, + Request::post("/api/v1/write") + .body(Body::from(body)) + .unwrap(), + ) + .await + .0 +} + +async fn get(app: &Router, uri: &str) -> (StatusCode, HeaderMap, Value) { + let (status, headers, body) = send(app, Request::get(uri).body(Body::empty()).unwrap()).await; + ( + status, + headers, + serde_json::from_slice(&body).unwrap_or(Value::Null), + ) +} + +async fn barrier(app: &Router, time_ms: i64) { + let request = Request::post(format!("/api/v1/precompute/watermark?time_ms={time_ms}")) + .body(Body::empty()) + .unwrap(); + assert_eq!(send(app, request).await.0, StatusCode::OK); +} + +async fn wait_for(what: &str, mut done: impl FnMut() -> bool) { + let started = Instant::now(); + while !done() { + assert!( + started.elapsed() < Duration::from_secs(20), + "timed out: {what}" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +fn planned_query_uri(time_s: i64) -> String { + format!( + "/api/v1/query?query={}&time={time_s}", + form_urlencoded::byte_serialize(QUERY.as_bytes()).collect::() + ) +} + +/// F1. Off: no other path is served (404), writes and planned queries are +/// as before, and no forward counter exists. +#[tokio::test(flavor = "multi_thread")] +async fn off_behaves_as_before() { + let (app, state) = data_plane(None); + assert_eq!(write(&app, body(1..=40)).await, StatusCode::NO_CONTENT); + barrier(&app, 40_000).await; + let (status, headers, _) = get(&app, &planned_query_uri(30)).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers[EXECUTION_HEADER], "plan"); + let (status, _, _) = get(&app, "/api/v1/labels").await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert!(state.raw_forward.is_none()); + let (_, _, metrics) = send(&app, Request::get("/metrics").body(Body::empty()).unwrap()).await; + assert!(!String::from_utf8_lossy(&metrics).contains("asap_raw_forward")); +} + +/// F2. Every accepted Remote Write body reaches the raw store byte for byte +/// (snappy-encoded), and the data plane answers as it does with forwarding +/// off. +#[tokio::test(flavor = "multi_thread")] +async fn accepted_writes_reach_the_raw_store_unchanged() { + let (raw, url) = mock(Answer::Accept).await; + let (app, state) = data_plane(Some(forward_to(&url))); + let (off, _) = data_plane(None); + let bodies = [body(1..=20), body(21..=40)]; + for b in &bodies { + assert_eq!(write(&app, b.clone()).await, StatusCode::NO_CONTENT); + assert_eq!(write(&off, b.clone()).await, StatusCode::NO_CONTENT); + } + wait_for("both bodies delivered", || { + raw.accepted.lock().unwrap().len() == 2 + }) + .await; + let accepted = raw.accepted.lock().unwrap().clone(); + assert_eq!( + accepted, + bodies + .iter() + .map(|b| Bytes::from(b.clone())) + .collect::>() + ); + assert!(raw + .writes + .lock() + .unwrap() + .iter() + .all(|(_, encoding)| encoding == "snappy")); + barrier(&app, 40_000).await; + barrier(&off, 40_000).await; + for time_s in [30, 40] { + let (_, headers, answer) = get(&app, &planned_query_uri(time_s)).await; + assert_eq!(headers[EXECUTION_HEADER], "plan"); + assert_eq!( + answer, + get(&off, &planned_query_uri(time_s)).await.2, + "at {time_s}" + ); + } + let status = state.raw_forward.as_ref().unwrap().status(); + assert_eq!(status["delivered_requests"], 2); + assert_eq!(status["queued_bytes"], 0); +} + +/// F3. Planned queries are answered by the plan (`plan`); unplanned queries +/// and every other path are proxied to the raw store (`forwarded`), with +/// their query string. +#[tokio::test(flavor = "multi_thread")] +async fn unplanned_queries_and_other_paths_are_proxied() { + let (raw, url) = mock(Answer::Accept).await; + let (app, _) = data_plane(Some(forward_to(&url))); + assert_eq!(write(&app, body(1..=40)).await, StatusCode::NO_CONTENT); + barrier(&app, 40_000).await; + let (status, headers, _) = get(&app, &planned_query_uri(30)).await; + assert_eq!( + (status, &headers[EXECUTION_HEADER]), + (StatusCode::OK, &"plan".parse().unwrap()) + ); + for uri in [ + "/api/v1/query?query=up&time=30", + "/api/v1/query_range?query=up&start=0&end=30&step=10", + "/api/v1/labels", + "/api/v1/series?match%5B%5D=data", + "/api/v1/label/job/values", + ] { + let (status, headers, answer) = get(&app, uri).await; + assert_eq!(status, StatusCode::OK, "{uri}"); + assert_eq!(headers[EXECUTION_HEADER], "forwarded", "{uri}"); + assert_eq!(answer["data"]["answered_by"], "raw store", "{uri}"); + } + let reads = raw.reads.lock().unwrap().clone(); + assert!( + reads.contains(&"/api/v1/query?query=up&time=30".to_string()), + "{reads:?}" + ); + assert!( + reads.contains(&"/api/v1/series?match%5B%5D=data".to_string()), + "{reads:?}" + ); +} + +/// F4. A delivery the raw store refuses with 503 or 429 is retried until it +/// is accepted, once. +#[tokio::test(flavor = "multi_thread")] +async fn refused_deliveries_are_retried_until_accepted() { + for status in [ + StatusCode::SERVICE_UNAVAILABLE, + StatusCode::TOO_MANY_REQUESTS, + ] { + let (raw, url) = mock(Answer::Fail(status, 2)).await; + let (app, state) = data_plane(Some(forward_to(&url))); + assert_eq!(write(&app, body(1..=10)).await, StatusCode::NO_CONTENT); + wait_for("delivered after retries", || { + raw.accepted.lock().unwrap().len() == 1 + }) + .await; + let forwarder = state.raw_forward.as_ref().unwrap().status(); + assert_eq!(forwarder["delivered_requests"], 1, "{status}"); + assert_eq!(forwarder["retried_attempts"], 2, "{status}"); + assert_eq!(raw.writes.lock().unwrap().len(), 3, "{status}"); + } +} + +/// F5. While the raw store is down, accepted bodies wait in the queue and +/// are delivered once it is up. +#[tokio::test(flavor = "multi_thread")] +async fn bodies_wait_for_a_raw_store_that_is_down() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let (app, state) = data_plane(Some(forward_to(&format!("http://{address}")))); + assert_eq!(write(&app, body(1..=10)).await, StatusCode::NO_CONTENT); + assert_eq!(write(&app, body(11..=20)).await, StatusCode::NO_CONTENT); + let forwarder = state.raw_forward.as_ref().unwrap(); + wait_for("a failed attempt", || { + forwarder.status()["retried_attempts"].as_u64() >= Some(1) + }) + .await; + assert_eq!(forwarder.status()["delivered_requests"], 0); + let raw = serve_mock( + tokio::net::TcpListener::bind(address).await.unwrap(), + Answer::Accept, + ); + wait_for("both delivered", || raw.accepted.lock().unwrap().len() == 2).await; + assert_eq!(forwarder.status()["queued_bytes"], 0); +} + +/// F6. Backpressure: with the queue full (the raw store holds every request), +/// a write is refused with 503 before the engine sees it; after the raw +/// store answers again, the retried write is accepted, and each store has +/// every sample exactly once. +#[tokio::test(flavor = "multi_thread")] +async fn a_full_queue_refuses_writes_without_duplicates() { + let (raw, url) = mock(Answer::Hang).await; + let mut options = forward_to(&url); + options.max_queued_bytes = 1; + options.concurrency = 1; + let (app, state) = data_plane(Some(options)); + let (first, second) = (body(1..=10), body(11..=20)); + assert_eq!(write(&app, first.clone()).await, StatusCode::NO_CONTENT); + assert_eq!( + write(&app, second.clone()).await, + StatusCode::SERVICE_UNAVAILABLE + ); + wait_for("the first body ingested", || { + state.engine.stats().samples_accepted == 80 + }) + .await; + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!( + state.engine.stats().samples_accepted, + 80, + "the refused write reached the engine" + ); + let forwarder = state.raw_forward.as_ref().unwrap(); + assert_eq!(forwarder.status()["refused_writes"], 1); + *raw.answer.lock().unwrap() = Answer::Accept; + raw.release.notify_one(); + wait_for("the first body delivered", || { + raw.accepted.lock().unwrap().len() == 1 + }) + .await; + wait_for("room in the queue", || { + forwarder.status()["queued_bytes"] == 0 + }) + .await; + assert_eq!(write(&app, second.clone()).await, StatusCode::NO_CONTENT); + wait_for("both delivered", || raw.accepted.lock().unwrap().len() == 2).await; + wait_for("both ingested", || { + state.engine.stats().samples_accepted == 160 + }) + .await; + assert_eq!( + raw.accepted.lock().unwrap().clone(), + vec![Bytes::from(first), Bytes::from(second)] + ); +} + +/// F7. A body the raw store rejects for good (400) is dropped and counted, +/// and later bodies are still delivered. +#[tokio::test(flavor = "multi_thread")] +async fn rejected_bodies_are_dropped_and_counted() { + let (raw, url) = mock(Answer::Fail(StatusCode::BAD_REQUEST, 1)).await; + let mut options = forward_to(&url); + options.concurrency = 1; + let (app, state) = data_plane(Some(options)); + assert_eq!(write(&app, body(1..=10)).await, StatusCode::NO_CONTENT); + let forwarder = state.raw_forward.as_ref().unwrap(); + wait_for("the first body dropped", || { + forwarder.status()["dropped_requests"] == 1 + }) + .await; + assert_eq!(write(&app, body(11..=20)).await, StatusCode::NO_CONTENT); + wait_for("the second body delivered", || { + raw.accepted.lock().unwrap().len() == 1 + }) + .await; + let status = forwarder.status(); + assert_eq!( + ( + status["dropped_requests"].as_u64(), + status["retried_attempts"].as_u64() + ), + (Some(1), Some(0)) + ); + let (_, _, metrics) = send(&app, Request::get("/metrics").body(Body::empty()).unwrap()).await; + let metrics = String::from_utf8_lossy(&metrics).to_string(); + assert!( + metrics.contains("asap_raw_forward_requests_total{outcome=\"dropped\"} 1"), + "{metrics}" + ); + assert!( + metrics.contains("asap_raw_forward_requests_total{outcome=\"delivered\"} 1"), + "{metrics}" + ); +} + +/// F8. Forward mode proxies unplanned queries, which `--no-forward` refuses: +/// the two cannot be combined. +#[tokio::test(flavor = "multi_thread")] +async fn forward_mode_refuses_no_forward() { + let state = DataPlane::with_options( + plan_json(), + "http://127.0.0.1:1".into(), + EngineOptions { + no_forward: true, + ..options() + }, + ) + .unwrap(); + let error = match state.with_raw_forward(forward_to("http://127.0.0.1:1")) { + Ok(_) => panic!("forward mode accepted --no-forward"), + Err(error) => error.to_string(), + }; + assert!(error.contains("--no-forward"), "{error}"); +} diff --git a/docs/design/demo-plan.md b/docs/design/demo-plan.md index 369d2d54..cf579239 100644 --- a/docs/design/demo-plan.md +++ b/docs/design/demo-plan.md @@ -298,11 +298,7 @@ Results at 10k series and 10 Hz, 12 cores, each engine alone: Next, after the 48-core demo: -1. Forward mode (optional): the data plane forwards raw samples to a - VictoriaMetrics single-node used as the raw store; planned queries are - answered by ASAP, the rest by VictoriaMetrics. Resources are reported as - the sum of both, against VictoriaMetrics alone. With forwarding off the - demo is unchanged. +1. Forward mode: designed and implemented, see §10.1. 2. A compressed raw store, so the data plane answers any query itself: compressed blocks written by the ingest shards, a label inverted index and time-range reads. Existing options (Parquet/Arrow with DataFusion, @@ -310,3 +306,95 @@ Next, after the 48-core demo: before a design. 3. Multi-level windows under cost model 3: start from the plan solved without levels and cap the search by a node limit, reporting the gap. + +### 10.1 Forward mode + +Forward mode is an optional switch, off by default. With it on, the data plane +also sends every raw sample to a VictoriaMetrics single-node used as the raw +store. That lets the demo answer any query: planned queries are answered by +ASAP, and everything else by VictoriaMetrics. + +**Switch.** `--raw-store-url URL`, the base URL of the VictoriaMetrics instance. + +- Off (no flag), the data plane behaves exactly as before. The forwarder does + not exist, no extra route is served, and no metric is added. +- It cannot be combined with `--no-forward`, which refuses unplanned queries. +- Two settings tune it: + - `--raw-forward-queue-bytes` (default 256 MiB): the byte bound described under + Write path. + - `--raw-forward-concurrency` (default 4): how many deliveries run at once. + +**Write path.** For each Remote Write request: + +1. The data plane decodes it. A bad request is answered with 400 and is not + forwarded. +2. It reserves room for the compressed body in a forward queue, bounded in + bytes (bodies being delivered count too). If the queue is full, it answers + 503 and goes no further. +3. It hands the samples to the engine. If the engine refuses them (its own + backpressure), it releases the reserved room and answers 503. +4. It puts the body, unchanged, in the forward queue and answers 204. + +So a 204 means both stores have the request: the engine has admitted the +samples, and the raw store's copy is queued. A 503 means neither has it, so a +sender's retry never duplicates samples in either store. + +All samples go to VictoriaMetrics, including metrics no plan reads, because it +is the store for every query the plan does not cover. + +**Delivery.** A few workers on their own thread send queued bodies to +`URL/api/v1/write`: + +- They send the snappy-compressed bodies with the Remote Write headers. +- After a 429, a 5xx, a timeout or a connection error they retry the same body, + with an exponential backoff from 100 ms to 5 s. +- Any other 4xx means VictoriaMetrics will never accept that body. It is dropped + and counted. +- The order between concurrent deliveries is not kept. VictoriaMetrics accepts + samples out of order. +- The queue is in memory. A crash loses at most the queued bytes. Making it + durable would need a disk spool, which the demo does not need. + +**Queries.** Each query is answered by whichever store can answer it: + +- A planned query the plan answers gets `x-asap-execution: plan`. +- Every other query (unplanned, or a planned query the plan cannot answer) goes + to VictoriaMetrics, and so does every other path: `labels`, `series`, label + values, metadata and the VictoriaMetrics UI. +- These forwarded answers get `x-asap-execution: forwarded`. A planned query that + falls back also carries `x-asap-forward-reason`. +- This reuses the existing query forwarding: forward mode points it at the raw + store instead of `--prometheus-url`. + +**Resources.** The forward-mode arm runs the data plane and VictoriaMetrics in +two cgroups under the same total limits as the VictoriaMetrics-alone arm. +CPU, working set, anon, disk and network are reported per component and as +their sum, ASAP + VictoriaMetrics, against VictoriaMetrics alone. + +The data plane also exports these metrics: + +- `asap_raw_forward_queued_bytes` and `asap_raw_forward_queued_requests`; +- `asap_raw_forward_requests_total{outcome="delivered|dropped"}`; +- `asap_raw_forward_retries_total`; +- `asap_raw_forward_delivered_bytes_total`; +- `asap_raw_forward_refused_writes_total`. + +The same numbers appear under `raw_forward` in `/api/v1/status/asap`. + +**Test plan** (`data_plane/tests/forward_mode.rs`). The raw store is a +recording mock that can accept, fail N times or hold requests. + +| # | Behaviour | Expected | +| --- | --- | --- | +| F1 | Forward mode off | Unknown paths answer 404. Writes and planned queries behave as before. No `asap_raw_forward` metric exists. | +| F2 | Accepted writes | They reach the raw store byte for byte, snappy-encoded. ASAP's answers equal those with forwarding off. | +| F3 | Planned query | Answered by ASAP, marked `plan`. | +| F3 | Unplanned `query` and `query_range`, `labels`, `series`, label values | Proxied with their query string, marked `forwarded`. | +| F4 | Raw store answers 503 or 429 twice | The body is retried and delivered once, with 2 retries counted. | +| F5 | Raw store down, then up | Queued bodies wait, and are delivered once it is up. | +| F6 | Queue full (raw store holds requests) | The write gets 503 and the engine never sees it. After the store recovers, the retried write is accepted, and each store has every sample exactly once. | +| F7 | Raw store answers 400 | The body is dropped and counted. Later bodies are still delivered. | +| F8 | Forward mode with `--no-forward` | Refused at start. | + +All existing data plane tests run with forward mode off and must pass +unchanged. From 60181884132efc9b4c67ab2660592243bc5f1d66 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 22 Nov 2026 18:59:15 +0000 Subject: [PATCH 2/3] docs(demo-plan): forward-mode arm shares one cgroup --- docs/design/demo-plan.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/design/demo-plan.md b/docs/design/demo-plan.md index cf579239..f8d94d47 100644 --- a/docs/design/demo-plan.md +++ b/docs/design/demo-plan.md @@ -367,9 +367,10 @@ is the store for every query the plan does not cover. store instead of `--prometheus-url`. **Resources.** The forward-mode arm runs the data plane and VictoriaMetrics in -two cgroups under the same total limits as the VictoriaMetrics-alone arm. -CPU, working set, anon, disk and network are reported per component and as -their sum, ASAP + VictoriaMetrics, against VictoriaMetrics alone. +one cgroup, under the same limits as the VictoriaMetrics-alone arm. The +cgroup's memory, disk and network are therefore their sum, ASAP + +VictoriaMetrics. CPU and RSS are also reported per process. All of this is +compared against VictoriaMetrics alone. The data plane also exports these metrics: From e7dce7cfe1927d3f82f931870524e42fb3de58a8 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 22 Nov 2026 19:07:14 +0000 Subject: [PATCH 3/3] docs(demo-plan): state the forward queue's crash-loss limit (no disk spool, by decision) --- docs/design/demo-plan.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/design/demo-plan.md b/docs/design/demo-plan.md index f8d94d47..a35705c1 100644 --- a/docs/design/demo-plan.md +++ b/docs/design/demo-plan.md @@ -352,8 +352,12 @@ is the store for every query the plan does not cover. and counted. - The order between concurrent deliveries is not kept. VictoriaMetrics accepts samples out of order. -- The queue is in memory. A crash loses at most the queued bytes. Making it - durable would need a disk spool, which the demo does not need. +- The queue is in memory, and there is no disk spool, by decision. This is a + known limit: a crash of the data plane loses up to `--raw-forward-queue-bytes` + of samples it has already acknowledged, on the raw-store side only. ASAP + still holds those samples; VictoriaMetrics, which answers the unplanned + queries, does not. A smaller bound limits the loss, at the cost of more 503s + when the raw store slows down. **Queries.** Each query is answered by whichever store can answer it: