From 45d83a8485cd27154f44af1033ddd505ba8fc54c Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 11:09:22 +0000 Subject: [PATCH 1/4] feat: engines behind common's traits; PlanInstaller and QueryDispatcher PrecomputeEngine implements IngestEngine and ExecutorQueryEngine implements QueryEngine: both are created before any plan, and their install compiles the plan and starts their threads (v1: once). The data plane installs the plan file through PlanInstaller (query engine, ingest engine, dispatcher, stopping at the first failure), and the HTTP query routes run through QueryDispatcher, which matches the query text and decides the fallback. Each planned query's measurements move from Metrics to the query engine; /metrics is unchanged. --- Cargo.lock | 5 + benchmarks/micro/range_bench.rs | 7 +- crates/data-plane/Cargo.toml | 3 +- crates/data-plane/src/dispatcher.rs | 273 +++++++++++++++++ crates/data-plane/src/engine.rs | 170 ++++------- crates/data-plane/src/installer.rs | 205 +++++++++++++ crates/data-plane/src/lib.rs | 156 ++++------ crates/data-plane/src/metrics_endpoint.rs | 26 +- crates/data-plane/src/test_support.rs | 52 ++++ crates/internal-metrics/src/lib.rs | 16 +- crates/precompute/Cargo.toml | 2 + crates/precompute/src/engine.rs | 221 +++++++++++++- crates/query/Cargo.toml | 5 + crates/query/src/engine.rs | 350 ++++++++++++++++++++++ crates/query/src/lib.rs | 82 +++-- crates/query/src/result_cache.rs | 2 +- crates/query/src/workers.rs | 196 ++++++++---- 17 files changed, 1433 insertions(+), 338 deletions(-) create mode 100644 crates/data-plane/src/dispatcher.rs create mode 100644 crates/data-plane/src/installer.rs create mode 100644 crates/data-plane/src/test_support.rs create mode 100644 crates/query/src/engine.rs diff --git a/Cargo.lock b/Cargo.lock index 17fdac859..b8f21a193 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -966,6 +966,7 @@ dependencies = [ "asap-executor", "asap-planner", "asap_sketchlib", + "async-trait", "axum", "clap", "common", @@ -2839,6 +2840,7 @@ version = "0.1.0" dependencies = [ "anyhow", "asap-executor", + "async-trait", "clap", "common", "control_plane", @@ -2923,7 +2925,9 @@ version = "0.1.0" dependencies = [ "anyhow", "asap-executor", + "async-trait", "common", + "control_plane", "futures", "internal_metrics", "serde_json", @@ -3513,6 +3517,7 @@ dependencies = [ "asap-executor", "asap_sketchlib", "clap", + "common", "futures", "internal_metrics", "libc", diff --git a/benchmarks/micro/range_bench.rs b/benchmarks/micro/range_bench.rs index 03a137ba1..ae5ef47af 100644 --- a/benchmarks/micro/range_bench.rs +++ b/benchmarks/micro/range_bench.rs @@ -258,10 +258,9 @@ async fn request(app: &Router, state: &DataPlane, queries: &[String], end_ms: i6 fn steps_cached(state: &DataPlane) -> u64 { state .engine - .metrics() - .queries - .values() - .map(|m| { + .query_metrics() + .iter() + .map(|(_, m)| { m.range_steps_cached .load(std::sync::atomic::Ordering::Relaxed) }) diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index 83f8d7989..9eb71215a 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -31,10 +31,11 @@ axum.workspace = true reqwest.workspace = true prost = "0.13" snap = "1.1" -futures = "0.3" form_urlencoded = "1" [dev-dependencies] +async-trait.workspace = true +futures = "0.3" control_plane.workspace = true asap_sketchlib.workspace = true tower = { version = "0.5", features = ["util"] } diff --git a/crates/data-plane/src/dispatcher.rs b/crates/data-plane/src/dispatcher.rs new file mode 100644 index 000000000..5e418517e --- /dev/null +++ b/crates/data-plane/src/dispatcher.rs @@ -0,0 +1,273 @@ +//! [`QueryDispatcher`]: resolves each query against the installed plan's +//! query texts, runs it on the query engine, and says how a query the plan +//! does not answer falls back ([`Fallback`]). +//! +//! The Prometheus routes run queries through the query engine's own +//! answers ([`query::result_cache::Answer`]: labels shared with the +//! interned series and the result cache), not through +//! [`common::QueryEngine`]'s [`common::QueryResult`], which would copy +//! every series' labels per query. + +use std::sync::{Arc, OnceLock}; + +use common::{AnswerSource, InstalledPlan, PhysicalASAPNodeId, PlanId}; +use query::result_cache::Answer; +use query::{ExecutorQueryEngine, Unanswered}; + +/// The dispatcher's verdict on one query. +#[derive(Debug, Clone, PartialEq)] +pub enum QueryOutcome { + /// The plan answered. + Ready(T), + NotAnswerable(NotAnswerableReason), +} + +/// Why the plan did not answer a query; the query falls back. +#[derive(Debug, Clone, PartialEq)] +pub enum NotAnswerableReason { + /// No plan is installed, or its query texts hold no such query. + Unmatched, + /// The stored data does not cover the query, or the plan changed since + /// it was resolved: why. + NotReady(String), + /// The engine failed to run the query: the error. + EngineError(String), +} + +impl NotAnswerableReason { + fn new(unanswered: Unanswered) -> Self { + match unanswered { + Unanswered::MissingRows(_) | Unanswered::PlanChanged => { + Self::NotReady(unanswered.to_string()) + } + Unanswered::Unsupported(_) | Unanswered::Execution(_) => { + Self::EngineError(unanswered.to_string()) + } + } + } + + /// What a client is told: `query` was not answered because of this. + pub fn message(&self, query: &str) -> String { + match self { + Self::Unmatched => format!("the installed plan has no query {:?}", query.trim()), + Self::NotReady(reason) | Self::EngineError(reason) => reason.clone(), + } + } +} + +/// How a query the plan does not answer is answered. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Fallback { + /// Forwarded to the backend (Prometheus, or the raw store in forward + /// mode), with why the plan did not answer when it planned the query. + Forward { reason: Option }, + /// Refused (`--no-forward`), with why. + Refuse { reason: String }, +} + +impl Fallback { + /// For `query`, not answered because of `reason`, when the data plane + /// may forward or not (`no_forward`). + pub fn new(reason: &NotAnswerableReason, query: &str, no_forward: bool) -> Self { + match reason { + _ if no_forward => Self::Refuse { + reason: reason.message(query), + }, + NotAnswerableReason::Unmatched => Self::Forward { reason: None }, + NotAnswerableReason::NotReady(_) | NotAnswerableReason::EngineError(_) => { + Self::Forward { + reason: Some(reason.message(query)), + } + } + } + } +} + +/// The installed plan as the dispatcher matches it. +struct Planned { + id: PlanId, + /// Each query text, trimmed, and its root, in plan order. + queries: Vec<(String, PhysicalASAPNodeId)>, +} + +/// Resolves and runs queries; set up by the plan installer. +pub struct QueryDispatcher { + engine: Arc, + plan: OnceLock, +} + +impl QueryDispatcher { + pub fn new(engine: Arc) -> Self { + Self { + engine, + plan: OnceLock::new(), + } + } + + /// Matches queries against `plan` from now on (v1: the first plan). + pub(crate) fn install(&self, plan: &InstalledPlan) { + let queries = plan + .plan + .query_texts + .iter() + .zip(&plan.plan.dag.roots) + .map(|(query, &root)| (query.trim().to_string(), root)) + .collect(); + let _ = self.plan.set(Planned { + id: plan.id, + queries, + }); + } + + /// The plan root answering `query`: the first query text equal to it, + /// both trimmed. + pub(crate) fn resolve(&self, query: &str) -> Option { + let plan = self.plan.get()?; + let query = query.trim(); + let (_, root) = plan.queries.iter().find(|(planned, _)| planned == query)?; + Some(AnswerSource::Planned { + plan: plan.id, + root: *root, + }) + } + + /// `query` at `time_ms`. + pub async fn instant(&self, query: &str, time_ms: i64) -> QueryOutcome { + let (Some(source), Some(engine)) = (self.resolve(query), self.engine.installed()) else { + return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched); + }; + match engine.instant(&source, query, time_ms).await { + Ok(result) => QueryOutcome::Ready(result), + Err(unanswered) => QueryOutcome::NotAnswerable(NotAnswerableReason::new(unanswered)), + } + } + + /// `query` at each of `times_ms`: every step's answer, or why some step + /// has none. + pub async fn range( + &self, + query: &str, + times_ms: impl Iterator, + ) -> QueryOutcome> { + let (Some(source), Some(engine)) = (self.resolve(query), self.engine.installed()) else { + return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched); + }; + match engine.range(&source, query, times_ms).await { + Ok(result) => QueryOutcome::Ready(result), + Err(unanswered) => QueryOutcome::NotAnswerable(NotAnswerableReason::new(unanswered)), + } + } +} + +#[cfg(test)] +mod tests { + use asap_executor::planner::ir::{NonASAPOp, Operator, Predicate, ScalarExpr}; + + use super::*; + use crate::engine::EngineHandle; + use crate::test_support; + + const QUERY: &str = "sum_over_time(data[10s])"; + + /// An engine with `plan` installed and samples through 30 s committed. + async fn engine(plan: &common::InstallablePlan) -> EngineHandle { + let plan_json = serde_json::to_string(plan).unwrap(); + let (engine, _) = EngineHandle::spawn(plan_json, test_support::options()).unwrap(); + engine + .try_ingest(test_support::samples(30_000, 1.0)) + .unwrap(); + engine.advance_watermark(30_000).await.unwrap(); + engine + } + + /// A planned query is answered from its views, and its text is matched + /// trimmed; another text is unmatched, and forwarded without a reason. + #[tokio::test] + async fn answers_a_planned_query_and_leaves_others_unmatched() { + let engine = engine(&test_support::plan(QUERY, false)).await; + let dispatcher = engine.dispatcher(); + let QueryOutcome::Ready(answer) = dispatcher.instant(&format!(" {QUERY} "), 30_000).await + else { + panic!("not answered"); + }; + let values: Vec = answer.iter().map(|sample| sample.value).collect(); + assert_eq!(values, [10.0]); + let unmatched = dispatcher.instant("up", 30_000).await; + assert_eq!( + unmatched, + QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched) + ); + assert_eq!( + Fallback::new(&NotAnswerableReason::Unmatched, "up", false), + Fallback::Forward { reason: None } + ); + } + + /// A planned query at a time whose window is not stored yet is not + /// ready; a range with such a step is not ready either. + #[tokio::test] + async fn a_window_not_stored_yet_is_not_ready() { + let engine = engine(&test_support::plan(QUERY, false)).await; + let dispatcher = engine.dispatcher(); + let outcome = dispatcher.instant(QUERY, 60_000).await; + let QueryOutcome::NotAnswerable(reason @ NotAnswerableReason::NotReady(_)) = outcome else { + panic!("expected not ready, got {outcome:?}"); + }; + assert_eq!( + Fallback::new(&reason, QUERY, false), + Fallback::Forward { + reason: Some(reason.message(QUERY)) + } + ); + let range = dispatcher.range(QUERY, [30_000, 40_000].into_iter()).await; + assert!(matches!( + range, + QueryOutcome::NotAnswerable(NotAnswerableReason::NotReady(_)) + )); + } + + /// A planned query whose run does not compile is an engine error: + /// forwarded with the error, or refused with it under `--no-forward`. + #[tokio::test] + async fn a_query_the_engine_cannot_run_is_an_engine_error() { + // Raw data kept, so the query runs read the `Scan`, and a predicate + // on a column it does not have. + let mut plan = test_support::plan(QUERY, true); + let scan = plan + .dag + .nodes + .iter_mut() + .find(|n| matches!(n.payload, Operator::NonASAP(NonASAPOp::Scan { .. }))) + .unwrap(); + let Operator::NonASAP(NonASAPOp::Scan { predicates, .. }) = &mut scan.payload else { + unreachable!(); + }; + predicates.push(Predicate(ScalarExpr::Column(99))); + let engine = engine(&plan).await; + let outcome = engine.dispatcher().instant(QUERY, 30_000).await; + let QueryOutcome::NotAnswerable(reason @ NotAnswerableReason::EngineError(_)) = outcome + else { + panic!("expected an engine error, got {outcome:?}"); + }; + let message = reason.message(QUERY); + assert!( + message.starts_with("the data plane cannot run this query"), + "{message}" + ); + assert_eq!( + Fallback::new(&reason, QUERY, true), + Fallback::Refuse { reason: message } + ); + } + + /// Under `--no-forward` an unmatched query is refused, naming it. + #[test] + fn an_unmatched_query_is_refused_without_forwarding() { + assert_eq!( + Fallback::new(&NotAnswerableReason::Unmatched, " up ", true), + Fallback::Refuse { + reason: "the installed plan has no query \"up\"".into() + } + ); + } +} diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index bf8c5b25f..741d6ae1c 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -1,26 +1,27 @@ -//! The engine: the installed plan, compiled once when it is installed, -//! and the precompute and query engines that execute it -//! ([`precompute::engine`], [`query::workers`]), wired to one published -//! store. +//! The engine: the precompute and query engines, wired to one published +//! store, with the plan file installed into them +//! ([`crate::installer::PlanInstaller`]), and the dispatcher the HTTP +//! routes run queries through. use std::sync::Arc; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; -use asap_executor::runtime::Limits; use asap_planner::InstallablePlan; -use internal_metrics::Metrics; +use internal_metrics::{Metrics, QueryMetrics}; use precompute::engine::{ - IngestError, PersistedViews, PrecomputeEngine, PrecomputeMode, PrecomputeOptions, SlowRefresh, + IngestError, InstalledPrecompute, PersistedViews, PrecomputeEngine, PrecomputeMode, + PrecomputeOptions, SlowRefresh, }; -use precompute::ingestion::{Ingestion, IngestionOptions, IngestionStats, Precompute}; -use query::result_cache::{Answer, ResultCache}; +use precompute::ingestion::{IngestionOptions, IngestionStats}; use query::workers::QueryWorkers; -use query::{QueryEngine, Snapshot, Unanswered}; +use query::{ExecutorQueryEngine, QueryOptions, Unanswered}; use storage::persist::{plan_hash, ViewRead}; use storage::persist_pool::PersistOptions; use storage::store::{PublishedStore, QueryTimeResults, RawSample, ViewTier}; use storage::window_cache::WindowCache; +use crate::dispatcher::QueryDispatcher; +use crate::installer::PlanInstaller; use crate::metrics_endpoint::Gauges; /// How the engine ingests samples and runs queries. @@ -187,8 +188,9 @@ impl Default for EngineOptions { /// The HTTP side of the engine. #[derive(Clone)] pub struct EngineHandle { - precompute: PrecomputeEngine, + precompute: InstalledPrecompute, query: QueryWorkers, + dispatcher: Arc, /// The views' cold tier, when they are persisted. view_tier: Option>, } @@ -198,7 +200,8 @@ impl EngineHandle { /// compiled once, and returns the plan's queries. Fails if the plan is /// invalid or the data plane cannot execute it. pub fn spawn(plan_json: String, options: EngineOptions) -> anyhow::Result<(Self, Vec)> { - let (ingestion, precompute, query, query_texts) = install(&plan_json, &options)?; + let plan = InstallablePlan::from_json(&plan_json)?; + let query_texts = plan.query_texts.clone(); let view_tier = options .view_dir .is_some() @@ -221,76 +224,51 @@ impl EngineHandle { tier, }); let published = Arc::new(PublishedStore::new(Arc::default())); - let precompute = PrecomputeEngine::start( - ingestion, - precompute, - &query_texts, - &options.precompute(), + let precompute = Arc::new(PrecomputeEngine::new( + options.precompute(), persisted, published.clone(), - )?; - let query = QueryWorkers::start( - query, - published, - precompute.metrics().clone(), - options.query_threads, - )?; + )); + let query = Arc::new(ExecutorQueryEngine::new(options.query(), published)); + let dispatcher = Arc::new(QueryDispatcher::new(query.clone())); + PlanInstaller::new(precompute.clone(), query.clone(), dispatcher.clone()).install(plan)?; let handle = Self { - precompute, - query, + precompute: precompute.installed().expect("installed").clone(), + query: query.installed().expect("installed").clone(), + dispatcher, view_tier, }; Ok((handle, query_texts)) } - /// Queues `samples` for ingestion; see [`PrecomputeEngine::try_ingest`]. + /// Queues `samples` for ingestion; see [`InstalledPrecompute::try_ingest`]. pub fn try_ingest(&self, samples: Vec) -> Result<(), IngestError> { self.precompute.try_ingest(samples) } - /// Answers the planned `query` at `time_ms` on a query worker; see - /// [`QueryWorkers::evaluate`]. - pub async fn evaluate(&self, query: String, time_ms: i64) -> Result { - self.query.evaluate(query, time_ms).await + /// What the HTTP routes run queries through. + pub fn dispatcher(&self) -> &QueryDispatcher { + &self.dispatcher } - /// Evaluates one step of a range query over `snapshot`; see - /// [`QueryWorkers::evaluate_range_step`]. - pub async fn evaluate_range_step( - &self, - query: String, - time_ms: i64, - snapshot: Arc, - ) -> Result { - self.query - .evaluate_range_step(query, time_ms, snapshot) - .await - } - - /// The newest published store, for the steps of one range request. - pub fn snapshot(&self) -> Arc { + /// The newest published store: what a query starting now reads. + pub fn snapshot(&self) -> Arc { self.query.snapshot() } - /// The result cache's answer to the planned `query` at `time_ms`, if - /// it keeps one ([`QueryEngine::cached`]). - pub fn cached(&self, query: &str, time_ms: i64) -> Option { - self.query.cached(query, time_ms) - } - - /// The query worker threads: the most query runs at once. - pub fn query_threads(&self) -> usize { - self.query.threads() + /// Each planned query's measurements, by query text. + pub fn query_metrics(&self) -> &[(String, QueryMetrics)] { + self.query.compiled().metrics() } /// How many query-time `OneEvaluation` nodes several queries share. pub fn shared_nodes(&self) -> usize { - self.query.engine().shared_nodes().len() + self.query.compiled().shared_nodes().len() } /// The query-time partition of the view store. pub fn query_time_results(&self) -> &QueryTimeResults { - self.query.engine().query_time_results() + self.query.compiled().query_time_results() } /// The engine's measurements. @@ -302,6 +280,7 @@ impl EngineHandle { /// format. pub fn render_metrics(&self) -> String { let persist_backlog = self.precompute.persist_backlog(); + let compiled = self.query.compiled(); crate::metrics_endpoint::render( self.metrics(), &Gauges { @@ -311,8 +290,9 @@ impl EngineHandle { persist_backlog: persist_backlog.windows(), persist_backlog_bytes: persist_backlog.bytes(), now_ms: precompute::ingestion::wall_clock_ms(), - query_time_results: self.query_time_results(), - result_cache: self.query.engine().result_cache(), + queries: compiled.metrics(), + query_time_results: compiled.query_time_results(), + result_cache: compiled.result_cache(), view_tier: self.view_tier.as_deref(), }, ) @@ -339,12 +319,12 @@ impl EngineHandle { } /// Queues an event-time barrier and waits for it; see - /// [`PrecomputeEngine::advance_watermark`]. + /// [`InstalledPrecompute::advance_watermark`]. pub async fn advance_watermark(&self, barrier_ms: i64) -> Result { self.precompute.advance_watermark(barrier_ms).await } - /// For tests: stops ingestion; see [`PrecomputeEngine::stop`]. + /// For tests: stops ingestion; see [`InstalledPrecompute::stop`]. #[doc(hidden)] pub fn stop(&self) { self.precompute.stop() @@ -362,6 +342,7 @@ impl EngineOptions { fn precompute(&self) -> PrecomputeOptions { PrecomputeOptions { ingestion: self.ingestion, + run_memory_limit_bytes: self.run_memory_limit_bytes, max_queued_samples: self.max_queued_samples, max_precompute_backlog: self.max_precompute_backlog, ingest_threads: self.ingest_threads, @@ -375,62 +356,21 @@ impl EngineOptions { panic_in_combine_of_window_end_ms: self.panic_in_combine_of_window_end_ms, } } -} -/// Reads, checks and compiles the plan file `plan_json`: its ingestion, -/// refresh runs, queries and query texts. -fn install( - plan_json: &str, - options: &EngineOptions, -) -> anyhow::Result<(Ingestion, Precompute, QueryEngine, Vec)> { - let plan = InstallablePlan::from_json(plan_json)?; - plan.validate()?; - let views = plan.materialized_views()?; - let groups = plan.ingestion_refresh_groups()?; - let limits = Limits { - max_bytes: options.run_memory_limit_bytes, - }; - tracing::info!( - views = views.len(), - refresh_groups = groups.len(), - "materialized views" - ); - let results = QueryTimeResults::new( - storage::store::millis(options.query_time_results_retention_ms), - options.query_time_results_max_bytes, - ); - let query = QueryEngine::new( - &plan, - &views, - limits.clone(), - results, - options.share_one_evaluation_results, - options.result_cache.then(|| { - ResultCache::new( - ResultCache::horizon_ms(&plan.dag, options.ingestion.view_retention_margin_ms), - options.result_cache_max_bytes, - ) - }), - )?; - tracing::info!( - shared = ?query.shared_nodes(), - "query-time OneEvaluation nodes shared across queries" - ); - let unexecutable = query.unexecutable(); - if options.no_forward && !unexecutable.is_empty() { - let reasons: Vec = unexecutable - .iter() - .map(|(query, reason)| format!("{query:?}: {reason}")) - .collect(); - anyhow::bail!( - "--no-forward refuses a plan with queries the data plane cannot run: {}", - reasons.join("; ") - ); + /// The options of the query engine. + fn query(&self) -> QueryOptions { + QueryOptions { + run_memory_limit_bytes: self.run_memory_limit_bytes, + threads: self.query_threads, + share_one_evaluation_results: self.share_one_evaluation_results, + query_time_results_retention_ms: self.query_time_results_retention_ms, + query_time_results_max_bytes: self.query_time_results_max_bytes, + result_cache: self.result_cache, + result_cache_max_bytes: self.result_cache_max_bytes, + view_retention_margin_ms: self.ingestion.view_retention_margin_ms, + refuse_unexecutable: self.no_forward, + } } - let (ingestion, precompute) = - Ingestion::new(&plan.dag, &views, groups, options.ingestion, limits)?; - tracing::info!(pane_width_ms = ingestion.pane_width_ms(), "raw data panes"); - Ok((ingestion, precompute, query, plan.query_texts.clone())) } /// The cold tier of a data plane persisting its views: the window cache diff --git a/crates/data-plane/src/installer.rs b/crates/data-plane/src/installer.rs new file mode 100644 index 000000000..79508ac2c --- /dev/null +++ b/crates/data-plane/src/installer.rs @@ -0,0 +1,205 @@ +//! [`PlanInstaller`]: installs a plan into the query engine, the ingest +//! engine and the dispatcher, all or nothing. + +use std::sync::{Arc, Mutex}; + +use common::{IngestEngine, InstallError, InstallablePlan, InstalledPlan, PlanId, QueryEngine}; + +use crate::dispatcher::QueryDispatcher; + +/// Installs plans. v1 installs one: the plan file at startup. +pub struct PlanInstaller { + ingest: Arc, + query: Arc, + dispatcher: Arc, + /// The installed plan's id; `None` before the first install. + installed: Mutex>, +} + +impl PlanInstaller { + pub fn new( + ingest: Arc, + query: Arc, + dispatcher: Arc, + ) -> Self { + Self { + ingest, + query, + dispatcher, + installed: Mutex::new(None), + } + } + + /// Validates `plan`, then installs it into the query engine, the ingest + /// engine and the dispatcher, in that order, stopping at the first + /// failure. Queries reach a plan only through the dispatcher, which + /// gets it last: on any failure the current plan stays the one queries + /// are answered from. The query engine goes first because its install + /// only compiles and starts idle workers; the ingest engine's starts + /// ingestion. Refused once a plan is installed. + pub fn install(&self, plan: InstallablePlan) -> Result { + let mut installed = self.installed.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(id) = *installed { + return Err(InstallError::new(format!( + "plan {} is installed, and the data plane installs one plan", + id.0 + ))); + } + plan.validate() + .map_err(|error| InstallError::new(format!("{:#}", anyhow::Error::from(error))))?; + let plan = InstalledPlan { + id: PlanId(1), + plan, + }; + self.query.install(plan.clone())?; + self.ingest.install(plan.clone())?; + self.dispatcher.install(&plan); + *installed = Some(plan.id); + Ok(plan.id) + } +} + +#[cfg(test)] +mod tests { + use async_trait::async_trait; + use common::{ + AnswerSource, EngineQueryResult, IngestError, QueryEngineError, QueryRequest, RawDataBatch, + }; + use query::ExecutorQueryEngine; + use storage::store::PublishedStore; + + use super::*; + use crate::test_support; + + /// Records the plans installed into it; refuses every plan when + /// `refuses`. + #[derive(Default)] + struct Fake { + refuses: bool, + installed: Mutex>, + } + + impl Fake { + fn refusing() -> Arc { + Arc::new(Self { + refuses: true, + ..Self::default() + }) + } + + fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { + if self.refuses { + return Err(InstallError::new("refused")); + } + self.installed.lock().unwrap().push(plan.id); + Ok(()) + } + + fn installed(&self) -> Vec { + self.installed.lock().unwrap().clone() + } + } + + #[async_trait] + impl IngestEngine for Fake { + fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { + Fake::install(self, plan) + } + async fn ingest(&self, _batch: RawDataBatch) -> Result<(), IngestError> { + Ok(()) + } + fn shutdown(&self) {} + } + + #[async_trait] + impl QueryEngine for Fake { + fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { + Fake::install(self, plan) + } + async fn execute_batch( + &self, + queries: &[(AnswerSource, QueryRequest)], + ) -> Vec> { + vec![Ok(EngineQueryResult::NotReady); queries.len()] + } + } + + fn dispatcher() -> Arc { + let options = query::QueryOptions { + run_memory_limit_bytes: 1 << 20, + threads: 1, + share_one_evaluation_results: true, + query_time_results_retention_ms: 0, + query_time_results_max_bytes: 0, + result_cache: false, + result_cache_max_bytes: 0, + view_retention_margin_ms: 0, + refuse_unexecutable: false, + }; + let published = Arc::new(PublishedStore::new(Arc::default())); + let engine = Arc::new(ExecutorQueryEngine::new(options, published)); + Arc::new(QueryDispatcher::new(engine)) + } + + const QUERY: &str = "sum_over_time(data[10s])"; + + /// A plan installs into both engines and the dispatcher as plan 1; a + /// second plan is refused and the first stays. + #[test] + fn installs_one_plan_into_both_engines_and_the_dispatcher() { + let (ingest, query, dispatcher) = ( + Arc::new(Fake::default()), + Arc::new(Fake::default()), + dispatcher(), + ); + let installer = PlanInstaller::new(ingest.clone(), query.clone(), dispatcher.clone()); + let plan = test_support::plan(QUERY, false); + let root = plan.dag.roots[0]; + assert_eq!(installer.install(plan), Ok(PlanId(1))); + let other = test_support::plan("count_over_time(data[10s])", false); + assert!(installer.install(other).is_err()); + assert_eq!(ingest.installed(), [PlanId(1)]); + assert_eq!(query.installed(), [PlanId(1)]); + assert_eq!( + dispatcher.resolve(QUERY), + Some(AnswerSource::Planned { + plan: PlanId(1), + root + }) + ); + assert_eq!(dispatcher.resolve("count_over_time(data[10s])"), None); + } + + /// An invalid plan, or one either engine refuses, reaches no later + /// step: the dispatcher matches no query, and a later plan can still + /// install. + #[test] + fn a_failed_install_leaves_the_plan_as_it_was() { + let mut invalid = test_support::plan(QUERY, false); + invalid.query_texts.push("up".into()); + for (ingest, query, plan) in [ + ( + Arc::new(Fake::default()), + Arc::new(Fake::default()), + invalid, + ), + ( + Arc::new(Fake::default()), + Fake::refusing(), + test_support::plan(QUERY, false), + ), + ( + Fake::refusing(), + Arc::new(Fake::default()), + test_support::plan(QUERY, false), + ), + ] { + let dispatcher = dispatcher(); + let installer = PlanInstaller::new(ingest.clone(), query.clone(), dispatcher.clone()); + assert!(installer.install(plan).is_err()); + assert!(ingest.installed().is_empty()); + assert!(dispatcher.resolve(QUERY).is_none()); + assert!(installer.installed.lock().unwrap().is_none()); + } + } +} diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index 4fa052255..d2eaedfd0 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -14,13 +14,16 @@ //! then answers every query the plan does not and every other API path //! (labels, series, metadata), proxied with `x-asap-execution: forwarded`. +pub mod dispatcher; pub mod engine; +pub mod installer; mod metrics_endpoint; pub mod prometheus; pub mod raw_forward; pub mod remote_write; +#[cfg(test)] +mod test_support; -use std::sync::atomic::Ordering; use std::sync::Arc; use std::time::Duration; @@ -30,6 +33,7 @@ use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::Router; +use dispatcher::{Fallback, NotAnswerableReason, QueryOutcome}; use engine::{EngineHandle, EngineOptions}; use precompute::engine::IngestError; use prometheus::{InstantQuery, RangeQuery}; @@ -342,41 +346,32 @@ async fn query( return (StatusCode::BAD_REQUEST, body).into_response(); } }; - let reason = match answer(&state, instant).await { - Ok(response) => { + // At its time, or now. + let time_ms = instant + .time_ms + .unwrap_or_else(precompute::ingestion::wall_clock_ms); + let dispatcher = state.engine.dispatcher(); + let reason = match dispatcher.instant(&instant.query, time_ms).await { + QueryOutcome::Ready(samples) => { + let response = prometheus::VectorResponse { time_ms, samples }; let mut response = axum::Json(response).into_response(); response .headers_mut() .insert(EXECUTION_HEADER, HeaderValue::from_static("plan")); return response; } - Err(reason) if state.no_forward => return not_answered(&reason.to_string()), - Err(Unanswered::NotPlanned(_)) => None, - Err(reason) => { - tracing::debug!(%reason, "forwarding a planned query"); - Some(header_value(&reason.to_string())) - } + QueryOutcome::NotAnswerable(reason) => reason, }; - let mut response = forward(state, "query", method, query, headers, body).await; - if let Some(reason) = reason { - response.headers_mut().insert(FORWARD_REASON_HEADER, reason); + match Fallback::new(&reason, &instant.query, state.no_forward) { + Fallback::Refuse { reason } => not_answered(&reason), + Fallback::Forward { reason } => { + if let Some(reason) = &reason { + tracing::debug!(%reason, "forwarding a planned query"); + } + let response = forward(state, "query", method, query, headers, body).await; + with_forward_reason(response, reason) + } } - response -} - -/// Runs a planned instant query at its time, or now. -async fn answer( - state: &DataPlane, - query: InstantQuery, -) -> Result { - let time_ms = query - .time_ms - .unwrap_or_else(precompute::ingestion::wall_clock_ms); - let samples = match state.engine.cached(&query.query, time_ms) { - Some(samples) => samples, - None => state.engine.evaluate(query.query, time_ms).await?, - }; - Ok(prometheus::VectorResponse { time_ms, samples }) } /// Answers a planned range query from the plan, one evaluation per step; @@ -401,7 +396,7 @@ async fn query_range( return (StatusCode::BAD_REQUEST, body).into_response(); } }; - let reason = match answer_range(&state, range).await { + let reason = match answer_range(&state, &range).await { Ok(body) => { let mut response = ( [( @@ -416,75 +411,46 @@ async fn query_range( .insert(EXECUTION_HEADER, HeaderValue::from_static("plan")); return response; } - Err(reason) if state.no_forward => return not_answered(&reason.to_string()), - Err(Unanswered::NotPlanned(_)) => None, - Err(reason) => { - tracing::debug!(%reason, "forwarding a planned range query"); - Some(header_value(&reason.to_string())) - } + Err(reason) => reason, }; - let mut response = forward(state, "query_range", method, query, headers, body).await; + match Fallback::new(&reason, &range.query, state.no_forward) { + Fallback::Refuse { reason } => not_answered(&reason), + Fallback::Forward { reason } => { + if let Some(reason) = &reason { + tracing::debug!(%reason, "forwarding a planned range query"); + } + let response = forward(state, "query_range", method, query, headers, body).await; + with_forward_reason(response, reason) + } + } +} + +/// A forwarded response, with why the plan did not answer its planned +/// query (`x-asap-forward-reason`). +fn with_forward_reason(mut response: Response, reason: Option) -> Response { if let Some(reason) = reason { - response.headers_mut().insert(FORWARD_REASON_HEADER, reason); + response + .headers_mut() + .insert(FORWARD_REASON_HEADER, header_value(&reason)); } response } -/// Runs a planned query at every step of `range`, the steps in parallel on -/// the query workers; unanswered if any step is. -async fn answer_range(state: &DataPlane, range: RangeQuery) -> Result, Unanswered> { - use futures::StreamExt; - let started = std::time::Instant::now(); - let query = &range.query; - // The steps the result cache answers; only the others run. - let cached: Vec<(i64, Option<_>)> = range - .times_ms() - .map(|time_ms| (time_ms, state.engine.cached(query, time_ms))) - .collect(); - let from_cache = cached.iter().filter(|(_, hit)| hit.is_some()).count(); - // Every step reads the same snapshot, so the raw data they share is - // converted once ([`store::RawReads`]). - let snapshot = state.engine.snapshot(); - // At most one step per query worker in flight, so a long range neither - // floods the workers' queue nor starves instant queries; the client - // going away drops the rest unrun. Every step runs even when one fails: - // with `final_query_results_cached` the plan keeps a step's inputs only - // for the refresh interval, so the older steps of a span are answered - // from the result cache, and a request whose older steps are not cached - // yet (the first span after a start) still caches the steps it can - // answer; a dashboard refreshing the range fills the cache within one - // span. - let results: Vec> = futures::stream::iter(cached) - .map(|(time_ms, hit)| { - let snapshot = snapshot.clone(); - async move { - let samples = match hit { - Some(samples) => samples, - None => { - state - .engine - .evaluate_range_step(query.clone(), time_ms, snapshot) - .await? - } - }; - Ok::<_, Unanswered>((time_ms, samples)) - } - }) - .buffered(state.engine.query_threads()) - .collect() - .await; - let steps: Vec<_> = results.into_iter().collect::>()?; - if let Some(metrics) = state.engine.metrics().query(query) { - metrics - .range_latency - .observe(started.elapsed().as_secs_f64()); - metrics - .range_steps_cached - .fetch_add(from_cache as u64, Ordering::Relaxed); - metrics - .range_steps - .fetch_add(steps.len() as u64, Ordering::Relaxed); - } +/// Runs a planned query at every step of `range` through the dispatcher +/// and writes the response body; why not, if any step is unanswered. +async fn answer_range( + state: &DataPlane, + range: &RangeQuery, +) -> Result, NotAnswerableReason> { + let steps = match state + .engine + .dispatcher() + .range(&range.query, range.times_ms()) + .await + { + QueryOutcome::Ready(steps) => steps, + QueryOutcome::NotAnswerable(reason) => return Err(reason), + }; // Grouping every step's answer by series and writing the JSON takes // long for a long range of many series (241 steps of 2,800 series: // about 0.85 s), all of it without an await, even when every step is @@ -492,12 +458,14 @@ async fn answer_range(state: &DataPlane, range: RangeQuery) -> Result, U // on that worker, instant queries and Remote Write included, and with // every worker so busy no timer or socket is polled: built on the // blocking pool instead. + let failed = + |error: String| NotAnswerableReason::EngineError(Unanswered::Execution(error).to_string()); tokio::task::spawn_blocking(move || { prometheus::range_response_body(&steps) - .map_err(|error| Unanswered::Execution(format!("the range response: {error}"))) + .map_err(|error| failed(format!("the range response: {error}"))) }) .await - .map_err(|error| Unanswered::Execution(format!("building the range response: {error}")))? + .map_err(|error| failed(format!("building the range response: {error}")))? } /// With `--no-forward`, the answer to a query the plan does not answer: a diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs index a6b5a9889..e8e97f57c 100644 --- a/crates/data-plane/src/metrics_endpoint.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -1,6 +1,7 @@ -//! `GET /metrics`: the engine's measurements ([`internal_metrics::Metrics`]) -//! and the gauges it reads from the stores, the ingestion counters and the -//! result cache, in the Prometheus text format. +//! `GET /metrics`: the engine's measurements ([`internal_metrics::Metrics`] +//! and each planned query's [`QueryMetrics`]) and the gauges it reads from +//! the stores, the ingestion counters and the result cache, in the +//! Prometheus text format. use std::fmt::Write; use std::sync::atomic::{AtomicU64, Ordering}; @@ -20,6 +21,8 @@ pub(crate) struct Gauges<'a> { pub persist_backlog: u64, pub persist_backlog_bytes: u64, pub now_ms: i64, + /// Each planned query's measurements, by query text, sorted. + pub queries: &'a [(String, QueryMetrics)], pub query_time_results: &'a QueryTimeResults, /// `None` when the result cache is off. pub result_cache: Option<&'a ResultCache>, @@ -65,7 +68,7 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { if let Some(push) = &metrics.push { push.render(&mut out); } - for (query, query_metrics) in &metrics.queries { + for (query, query_metrics) in gauges.queries { let labels = format!("phase=\"query\",query=\"{}\"", escape(query)); query_metrics.run.render(&mut out, &labels); let labels = format!("phase=\"query_range_step\",query=\"{}\"", escape(query)); @@ -78,7 +81,7 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { "histogram", "Planned instant query latency in the engine, queueing for a worker included.", ); - for (query, query_metrics) in &metrics.queries { + for (query, query_metrics) in gauges.queries { let labels = format!("query=\"{}\"", escape(query)); query_metrics .latency @@ -90,7 +93,7 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { "histogram", "Planned range query latency, every step included.", ); - for (query, query_metrics) in &metrics.queries { + for (query, query_metrics) in gauges.queries { let labels = format!("query=\"{}\"", escape(query)); query_metrics .range_latency @@ -109,7 +112,7 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { ), ] { family(&mut out, name, "counter", help); - for (query, query_metrics) in &metrics.queries { + for (query, query_metrics) in gauges.queries { let _ = writeln!( out, "{name}{{query=\"{}\"}} {}", @@ -493,15 +496,14 @@ mod tests { /// The text format names each phase and query. #[test] fn renders_phases_and_queries() { - let metrics = Metrics::new( - &[(10_000, vec!["3".into(), "5".into()])], - &["sum(x)".to_string()], - ); + let metrics = Metrics::new(&[(10_000, vec!["3".into(), "5".into()])]); metrics.append.record(Timer::start()); - metrics.query("sum(x) ").unwrap().latency.observe(0.003); + let queries = [("sum(x)".to_string(), QueryMetrics::default())]; + queries[0].1.latency.observe(0.003); let text = render( &metrics, &Gauges { + queries: &queries, stats: IngestionStats::default(), samples_queued: 0, precompute_backlog: 2, diff --git a/crates/data-plane/src/test_support.rs b/crates/data-plane/src/test_support.rs new file mode 100644 index 000000000..8110eb65c --- /dev/null +++ b/crates/data-plane/src/test_support.rs @@ -0,0 +1,52 @@ +//! Plans and options for the unit tests. + +use asap_planner::InstallablePlan; +use precompute::ingestion::IngestionOptions; +use storage::store::RawSample; + +use crate::engine::EngineOptions; + +/// The plan of `query`, evaluated every 10 s over the gauge `data` (one +/// sample a second), for a deployment that keeps raw data or not. +pub(crate) fn plan(query: &str, raw_data_retained: bool) -> InstallablePlan { + let workload = serde_json::from_value(serde_json::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": 1.0}}, + "sources": {"data": {"series_count": 1, "sample_interval": 1000, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let mut inputs = control_plane::DeploymentInputs::default(); + inputs.deployment_capabilities.raw_data_retained = raw_data_retained; + control_plane::plan_workload(&workload, &inputs).unwrap().0 +} + +/// Options that refresh every window: no allowed lateness, and the stream +/// starting at 0. +pub(crate) fn options() -> EngineOptions { + EngineOptions { + ingestion: IngestionOptions { + allowed_lateness_ms: 0, + stream_start_ms: Some(0), + ..IngestionOptions::default() + }, + ..EngineOptions::default() + } +} + +/// One sample of `data{job="a"}` with `value` every second of `(0, end_ms]`. +pub(crate) fn samples(end_ms: i64, value: f64) -> Vec { + let series = storage::series_ids::intern_pairs(&[("__name__", "data"), ("job", "a")]); + (1..=end_ms / 1000) + .map(|second| RawSample { + labels: series, + timestamp_ms: second * 1000, + value, + }) + .collect() +} diff --git a/crates/internal-metrics/src/lib.rs b/crates/internal-metrics/src/lib.rs index abaa112f6..adf040e5f 100644 --- a/crates/internal-metrics/src/lib.rs +++ b/crates/internal-metrics/src/lib.rs @@ -300,8 +300,6 @@ pub struct Metrics { pub precompute_busy_ns: AtomicU64, /// Threads computing windows (`--precompute-threads`). pub precompute_threads: AtomicU64, - /// Each planned query's runs, by query text. - pub queries: BTreeMap, /// The watermark, `i64::MIN` before the first. pub watermark_ms: AtomicI64, pub raw_data_bytes: AtomicU64, @@ -326,8 +324,9 @@ pub struct Metrics { impl Metrics { /// Measurements for refresh groups described by `groups` (window width - /// and view ids) and the planned `queries`. - pub fn new(groups: &[(i64, Vec)], queries: &[String]) -> Self { + /// and view ids). The planned queries' measurements are the query + /// engine's ([`QueryMetrics`]). + pub fn new(groups: &[(i64, Vec)]) -> Self { Self { push: None, remote_write_decode: PhaseStats::default(), @@ -346,10 +345,6 @@ impl Metrics { precompute_windows: groups.iter().map(|_| WindowLatency::default()).collect(), precompute_busy_ns: AtomicU64::new(0), precompute_threads: AtomicU64::new(1), - queries: queries - .iter() - .map(|query| (query.trim().to_string(), QueryMetrics::default())) - .collect(), watermark_ms: AtomicI64::new(i64::MIN), raw_data_bytes: AtomicU64::new(0), raw_data_samples: AtomicU64::new(0), @@ -364,11 +359,6 @@ impl Metrics { view_segments_marked_cold: AtomicU64::new(0), } } - - /// The query's measurements, if it is planned. - pub fn query(&self, query: &str) -> Option<&QueryMetrics> { - self.queries.get(query.trim()) - } } /// The process's resident set size, from `/proc/self/statm`. diff --git a/crates/precompute/Cargo.toml b/crates/precompute/Cargo.toml index 38da74d04..c12fe6c8e 100644 --- a/crates/precompute/Cargo.toml +++ b/crates/precompute/Cargo.toml @@ -11,6 +11,8 @@ common.workspace = true internal_metrics.workspace = true storage.workspace = true anyhow.workspace = true +# `common::IngestEngine`'s async methods. +async-trait.workspace = true # `PrecomputeMode` is a command-line value of the data plane # (`--precompute-mode`). clap.workspace = true diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 6fb252ecc..304899286 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -26,11 +26,14 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, RwLock}; use std::time::Instant; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; +use asap_executor::runtime::Limits; use asap_executor::values::Batch; +use async_trait::async_trait; +use common::{InstallError, InstallablePlan, InstalledPlan, RawDataBatch}; use internal_metrics::{Metrics, PushMetrics, Timer}; use storage::memory_budget::serve_view_cache; use storage::persist::ViewFiles; @@ -212,6 +215,8 @@ impl Drop for RunningGuard { pub struct PrecomputeOptions { /// Lateness, future bound and first-window checks of ingestion. pub ingestion: IngestionOptions, + /// The most bytes one ingestion run may hold. + pub run_memory_limit_bytes: usize, /// Samples queued for the ingest shards beyond which `try_ingest` is /// `Busy`. pub max_queued_samples: u64, @@ -241,6 +246,7 @@ pub struct PrecomputeOptions { /// Where the views are persisted, when they are: the view files' /// directory, what names them, how they are synced and rolled, the /// persist threads, and the cold tier windows are read back through. +#[derive(Clone)] pub struct PersistedViews { pub dir: std::path::PathBuf, /// The installed plan file's hash ([`storage::persist::plan_hash`]): @@ -252,11 +258,125 @@ pub struct PersistedViews { pub tier: Arc, } -/// The precompute engine: the `ingest-N` shards, the `ingest` -/// coordinator, the precompute pool and committer, and (with persisted -/// views) the `persist-N` threads and the `view-cache` monitor. -#[derive(Clone)] +/// The precompute engine: created before any plan; its install compiles +/// the plan's ingestion and starts the threads ([`InstalledPrecompute`]). +/// v1 installs one plan. pub struct PrecomputeEngine { + options: PrecomputeOptions, + persisted: Option, + published: Arc, + /// Held while a plan is installed, so two installs do not both start. + installing: Mutex<()>, + installed: OnceLock, +} + +impl PrecomputeEngine { + /// An engine with no plan, which will publish what query runs read to + /// `published`, and persist the views as `persisted` says. + pub fn new( + options: PrecomputeOptions, + persisted: Option, + published: Arc, + ) -> Self { + Self { + options, + persisted, + published, + installing: Mutex::new(()), + installed: OnceLock::new(), + } + } + + /// The threads running the installed plan; `None` before the install. + pub fn installed(&self) -> Option<&InstalledPrecompute> { + self.installed.get() + } + + /// Compiles `plan`'s ingestion and starts its threads. + fn start(&self, plan: &InstallablePlan) -> anyhow::Result { + let views = plan.materialized_views()?; + let groups = plan.ingestion_refresh_groups()?; + tracing::info!( + views = views.len(), + refresh_groups = groups.len(), + "materialized views" + ); + let limits = Limits { + max_bytes: self.options.run_memory_limit_bytes, + }; + let (ingestion, precompute) = + Ingestion::new(&plan.dag, &views, groups, self.options.ingestion, limits)?; + tracing::info!(pane_width_ms = ingestion.pane_width_ms(), "raw data panes"); + InstalledPrecompute::start( + ingestion, + precompute, + &self.options, + self.persisted.clone(), + self.published.clone(), + ) + } +} + +#[async_trait] +impl common::IngestEngine for PrecomputeEngine { + fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { + let _installing = self.installing.lock().unwrap_or_else(|e| e.into_inner()); + if self.installed().is_some() { + return Err(InstallError::new( + "the precompute engine has a plan installed and installs one plan", + )); + } + let installed = self + .start(&plan.plan) + .map_err(|error| InstallError::new(format!("{error:#}")))?; + let _ = self.installed.set(installed); + Ok(()) + } + + /// Interns each series and queues its samples, waiting while the queues + /// are full; discards the batch before the install. + async fn ingest(&self, batch: RawDataBatch) -> Result<(), common::IngestError> { + let Some(installed) = self.installed() else { + return Ok(()); + }; + let RawDataBatch::TimeSeries { series } = batch; + let mut samples = Vec::new(); + for (labels, points) in &series { + let pairs: Vec<(&String, &String)> = labels.iter().collect(); + let series = storage::series_ids::intern_pairs(&pairs); + samples.extend(points.iter().map(|&(timestamp_ms, value)| RawSample { + labels: series, + timestamp_ms, + value, + })); + } + loop { + match installed.try_ingest(samples.clone()) { + Ok(()) => return Ok(()), + Err(IngestError::Busy) => tokio::time::sleep(BUSY_RETRY).await, + Err(error @ IngestError::Stopped) => { + return Err(common::IngestError::new(error.to_string())) + } + } + } + } + + fn shutdown(&self) { + if let Some(installed) = self.installed() { + installed.stop(); + } + } +} + +/// How long [`common::IngestEngine::ingest`] waits before offering a batch +/// the queues refused again. +const BUSY_RETRY: std::time::Duration = std::time::Duration::from_millis(10); + +/// The threads running the installed plan: the `ingest-N` shards, the +/// `ingest` coordinator, the precompute pool and committer, and (with +/// persisted views) the `persist-N` threads and the `view-cache` monitor. +#[derive(Clone)] +pub struct InstalledPrecompute { commands: Sender, /// Each ingest shard's queue; a sample goes to the shard of its series. shards: Vec>, @@ -264,15 +384,14 @@ pub struct PrecomputeEngine { max_queued_samples: u64, } -impl PrecomputeEngine { +impl InstalledPrecompute { /// Starts the threads that run `ingestion` and `precompute`, compiled - /// from the installed plan, whose queries are `query_texts`; they - /// publish what query runs read to `published`. With `persisted`, the - /// views stored in its files are indexed first. - pub fn start( + /// from the installed plan; they publish what query runs read to + /// `published`. With `persisted`, the views stored in its files are + /// indexed first. + fn start( mut ingestion: Ingestion, precompute: Precompute, - query_texts: &[String], options: &PrecomputeOptions, persisted: Option, published: Arc, @@ -336,7 +455,7 @@ impl PrecomputeEngine { .into_iter() .map(|(width_ms, views)| (width_ms, views.iter().map(ToString::to_string).collect())) .collect(); - let mut metrics = Metrics::new(&groups, query_texts); + let mut metrics = Metrics::new(&groups); if options.precompute_mode == PrecomputeMode::Push { metrics.push = Some(PushMetrics::new(groups.len(), shard_count)); } @@ -2068,4 +2187,82 @@ mod tests { let routed = ingestion.routing().route(vec![sample], 25_000); assert_eq!(routed.accepted.len(), 1, "{:?}", routed.stats); } + + fn plan(query: &str) -> InstallablePlan { + let workload = serde_json::from_value(serde_json::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": 1.0}}, + "sources": {"data": {"series_count": 1, "sample_interval": 1000, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let mut inputs = control_plane::DeploymentInputs::default(); + inputs.deployment_capabilities.raw_data_retained = false; + control_plane::plan_workload(&workload, &inputs).unwrap().0 + } + + fn engine() -> PrecomputeEngine { + let options = PrecomputeOptions { + ingestion: IngestionOptions { + allowed_lateness_ms: 0, + stream_start_ms: Some(0), + ..Default::default() + }, + run_memory_limit_bytes: 1 << 30, + max_queued_samples: 1000, + max_precompute_backlog: 16, + ingest_threads: 2, + precompute_threads: 1, + slow_refreshes: Vec::new(), + check_task_inputs: false, + shard_delay_ms: 0, + precompute_mode: PrecomputeMode::Window, + push_batching: crate::push::MorselBatching::default(), + precompute_memory_budget_bytes: None, + panic_in_combine_of_window_end_ms: None, + }; + PrecomputeEngine::new(options, None, Arc::new(PublishedStore::new(Arc::default()))) + } + + fn batch(seconds: i64) -> RawDataBatch { + let labels = [("__name__", "data"), ("job", "a")] + .map(|(name, value)| (name.to_string(), value.to_string())) + .into(); + let points = (1..=seconds).map(|s| (s * 1000, 1.0)).collect(); + RawDataBatch::TimeSeries { + series: vec![(labels, points)], + } + } + + /// Through `IngestEngine`: a batch before the install is discarded; the + /// plan installs once; batches after it are ingested; `shutdown` stops + /// the engine. + #[tokio::test] + async fn the_ingest_engine_installs_once_and_ingests_after_it() { + use common::{IngestEngine as _, PlanId}; + let engine = engine(); + assert_eq!(engine.ingest(batch(5)).await, Ok(())); + let installed = |id| InstalledPlan { + id: PlanId(id), + plan: plan("sum_over_time(data[10s])"), + }; + assert_eq!(engine.install(installed(1)), Ok(())); + assert!(engine.install(installed(2)).is_err()); + assert_eq!(engine.ingest(batch(20)).await, Ok(())); + let running = engine.installed().unwrap(); + running.advance_watermark(20_000).await.unwrap(); + assert_eq!(running.stats().samples_accepted, 20); + assert!(running.stats().windows_refreshed > 0); + engine.shutdown(); + let stopped = Instant::now(); + while running.is_running() { + assert!(stopped.elapsed() < std::time::Duration::from_secs(10)); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } } diff --git a/crates/query/Cargo.toml b/crates/query/Cargo.toml index ab0eff9fa..b2c1cd13b 100644 --- a/crates/query/Cargo.toml +++ b/crates/query/Cargo.toml @@ -11,8 +11,13 @@ common.workspace = true internal_metrics.workspace = true storage.workspace = true anyhow.workspace = true +# `common::QueryEngine`'s async methods. +async-trait.workspace = true futures = "0.3" serde_json.workspace = true thiserror.workspace = true tokio.workspace = true tracing.workspace = true + +[dev-dependencies] +control_plane.workspace = true diff --git a/crates/query/src/engine.rs b/crates/query/src/engine.rs new file mode 100644 index 000000000..a2f76e066 --- /dev/null +++ b/crates/query/src/engine.rs @@ -0,0 +1,350 @@ +//! [`ExecutorQueryEngine`]: the query engine over the Planner's executor, +//! behind [`common::QueryEngine`]. It is created before any plan; its +//! install compiles the plan's queries and starts the query workers. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex, OnceLock}; + +use asap_executor::runtime::Limits; +use async_trait::async_trait; +use common::{ + AnswerSource, EngineQueryResult, InstallError, InstalledPlan, InstantVector, + InstantVectorElement, LabelSet, QueryEngineError, QueryEval, QueryRequest, QueryResult, + RangeVector, RangeVectorElement, Sample, +}; +use storage::store::{PublishedStore, QueryTimeResults}; + +use crate::result_cache::{Answer, ResultCache}; +use crate::workers::QueryWorkers; +use crate::{CompiledQueries, Unanswered}; + +/// How the query engine compiles and runs the plan's queries; the data +/// plane's `EngineOptions` describes each field. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QueryOptions { + pub run_memory_limit_bytes: usize, + pub threads: usize, + pub share_one_evaluation_results: bool, + pub query_time_results_retention_ms: u64, + pub query_time_results_max_bytes: usize, + pub result_cache: bool, + pub result_cache_max_bytes: usize, + /// How much longer than the plan's retention views are kept, which + /// bounds how far back the result cache keeps answers. + pub view_retention_margin_ms: u64, + /// Refuse a plan with a query the engine cannot run (`--no-forward`). + pub refuse_unexecutable: bool, +} + +/// The query engine: answers the installed plan's queries on the `query-N` +/// workers, over the snapshots the precompute engine publishes. v1 +/// installs one plan. +pub struct ExecutorQueryEngine { + options: QueryOptions, + published: Arc, + /// Held while a plan is installed, so two installs do not both start. + installing: Mutex<()>, + installed: OnceLock, +} + +impl ExecutorQueryEngine { + /// An engine with no plan, which will read what `published` holds. + pub fn new(options: QueryOptions, published: Arc) -> Self { + Self { + options, + published, + installing: Mutex::new(()), + installed: OnceLock::new(), + } + } + + /// The installed plan's queries and workers; `None` before the install. + pub fn installed(&self) -> Option<&QueryWorkers> { + self.installed.get() + } + + /// Compiles `plan`'s queries and starts the workers. + fn start(&self, plan: &InstalledPlan) -> anyhow::Result { + let options = &self.options; + let views = plan.plan.materialized_views()?; + let limits = Limits { + max_bytes: options.run_memory_limit_bytes, + }; + let results = QueryTimeResults::new( + storage::store::millis(options.query_time_results_retention_ms), + options.query_time_results_max_bytes, + ); + let compiled = CompiledQueries::new( + &plan.plan, + &views, + limits, + results, + options.share_one_evaluation_results, + options.result_cache.then(|| { + ResultCache::new( + ResultCache::horizon_ms(&plan.plan.dag, options.view_retention_margin_ms), + options.result_cache_max_bytes, + ) + }), + )?; + tracing::info!( + shared = ?compiled.shared_nodes(), + "query-time OneEvaluation nodes shared across queries" + ); + let unexecutable = compiled.unexecutable(); + if options.refuse_unexecutable && !unexecutable.is_empty() { + let reasons: Vec = unexecutable + .iter() + .map(|(query, reason)| format!("{query:?}: {reason}")) + .collect(); + anyhow::bail!( + "--no-forward refuses a plan with queries the data plane cannot run: {}", + reasons.join("; ") + ); + } + Ok(QueryWorkers::start( + plan.id, + compiled, + self.published.clone(), + options.threads, + )?) + } + + /// One request's answer, as the boundary reports it. + async fn execute_one( + &self, + source: &AnswerSource, + request: &QueryRequest, + ) -> Result { + let Some(workers) = self.installed() else { + return Ok(EngineQueryResult::NotReady); + }; + let result = match request.eval { + QueryEval::Instant { time_ms } => workers + .instant(source, &request.query, time_ms) + .await + .map(|answer| QueryResult::Vector(instant_vector(time_ms, &answer))), + QueryEval::Range { + start_ms, + end_ms, + step_ms, + } => { + if step_ms <= 0 { + return Err(QueryEngineError::new(format!( + "range step {step_ms} ms is not positive" + ))); + } + let times = (0..) + .map_while(|i: i64| i.checked_mul(step_ms)?.checked_add(start_ms)) + .take_while(|time_ms| *time_ms <= end_ms); + workers + .range(source, &request.query, times) + .await + .map(|steps| QueryResult::Matrix(range_vector(&steps))) + } + }; + match result { + Ok(result) => Ok(EngineQueryResult::Ready { result }), + Err(Unanswered::MissingRows(_) | Unanswered::PlanChanged) => { + Ok(EngineQueryResult::NotReady) + } + Err(error) => Err(QueryEngineError::new(error.to_string())), + } + } +} + +#[async_trait] +impl common::QueryEngine for ExecutorQueryEngine { + fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { + let _installing = self.installing.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(installed) = self.installed() { + return Err(InstallError::new(format!( + "the query engine has plan {} installed and installs one plan", + installed.plan().0 + ))); + } + let workers = self + .start(&plan) + .map_err(|error| InstallError::new(format!("{error:#}")))?; + let _ = self.installed.set(workers); + Ok(()) + } + + async fn execute_batch( + &self, + queries: &[(AnswerSource, QueryRequest)], + ) -> Vec> { + let mut results = Vec::with_capacity(queries.len()); + for (source, request) in queries { + results.push(self.execute_one(source, request).await); + } + results + } +} + +/// `answer` as an instant vector at `time_ms`. +fn instant_vector(time_ms: i64, answer: &Answer) -> InstantVector { + InstantVector { + timestamp_ms: time_ms, + series: answer + .iter() + .map(|sample| InstantVectorElement { + labels: (*sample.labels).clone(), + value: sample.value, + }) + .collect(), + } +} + +/// Each series' value at each step it has one, series sorted by labels. +fn range_vector(steps: &[(i64, Answer)]) -> RangeVector { + let mut series: BTreeMap<&LabelSet, Vec> = BTreeMap::new(); + for (time_ms, answer) in steps { + for sample in answer.iter() { + series.entry(&*sample.labels).or_default().push(Sample { + timestamp_ms: *time_ms, + value: sample.value, + }); + } + } + RangeVector { + series: series + .into_iter() + .map(|(labels, samples)| RangeVectorElement { + labels: labels.clone(), + samples, + }) + .collect(), + } +} + +#[cfg(test)] +mod tests { + use common::{PlanId, QueryEngine as _, QueryLanguage}; + + use super::*; + + fn plan(query: &str) -> common::InstallablePlan { + let workload = serde_json::from_value(serde_json::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": 1.0}}, + "sources": {"data": {"series_count": 1, "sample_interval": 1000, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let mut inputs = control_plane::DeploymentInputs::default(); + inputs.deployment_capabilities.raw_data_retained = false; + control_plane::plan_workload(&workload, &inputs).unwrap().0 + } + + const QUERY: &str = "sum_over_time(data[10s])"; + + /// Through `QueryEngine`: nothing is ready before the install, the plan + /// installs once, a query resolved against another plan is not ready, + /// and neither is one whose views are not stored yet. + #[tokio::test] + async fn the_query_engine_installs_once_and_reports_not_ready() { + let options = QueryOptions { + run_memory_limit_bytes: 1 << 30, + threads: 1, + share_one_evaluation_results: true, + query_time_results_retention_ms: 60_000, + query_time_results_max_bytes: 1 << 20, + result_cache: true, + result_cache_max_bytes: 1 << 20, + view_retention_margin_ms: 60_000, + refuse_unexecutable: false, + }; + let engine = + ExecutorQueryEngine::new(options, Arc::new(PublishedStore::new(Arc::default()))); + let plan = plan(QUERY); + let root = plan.dag.roots[0]; + let source = |id| AnswerSource::Planned { + plan: PlanId(id), + root, + }; + let request = |eval| QueryRequest { + language: QueryLanguage::PromQL, + query: QUERY.into(), + eval, + }; + let instant = request(QueryEval::Instant { time_ms: 30_000 }); + assert_eq!( + engine.execute(&source(1), &instant).await, + Ok(EngineQueryResult::NotReady) + ); + let installed = |id| InstalledPlan { + id: PlanId(id), + plan: plan.clone(), + }; + assert_eq!(engine.install(installed(1)), Ok(())); + assert!(engine.install(installed(2)).is_err()); + let range = request(QueryEval::Range { + start_ms: 10_000, + end_ms: 30_000, + step_ms: 10_000, + }); + let results = engine + .execute_batch(&[ + (source(2), instant.clone()), + (source(1), instant), + (source(1), range), + ]) + .await; + assert_eq!(results, vec![Ok(EngineQueryResult::NotReady); 3]); + } + + /// Answers become an instant vector, and steps a matrix of each + /// series' samples, series sorted by labels. + #[test] + fn answers_convert_to_boundary_results() { + let labels = |job: &str| Arc::new(LabelSet::from([("job".to_string(), job.to_string())])); + let (a, b) = (labels("a"), labels("b")); + let sample = |labels: &Arc, value| crate::ResultSample { + labels: labels.clone(), + value, + }; + let first: Answer = Arc::new(vec![sample(&b, 1.0), sample(&a, 2.0)]); + let second: Answer = Arc::new(vec![sample(&a, 3.0)]); + assert_eq!( + instant_vector(10, &first), + InstantVector { + timestamp_ms: 10, + series: vec![ + InstantVectorElement { + labels: (*b).clone(), + value: 1.0 + }, + InstantVectorElement { + labels: (*a).clone(), + value: 2.0 + }, + ], + } + ); + let point = |timestamp_ms, value| Sample { + timestamp_ms, + value, + }; + assert_eq!( + range_vector(&[(10, first), (20, second)]), + RangeVector { + series: vec![ + RangeVectorElement { + labels: (*a).clone(), + samples: vec![point(10, 2.0), point(20, 3.0)], + }, + RangeVectorElement { + labels: (*b).clone(), + samples: vec![point(10, 1.0)], + }, + ], + } + ); + } +} diff --git a/crates/query/src/lib.rs b/crates/query/src/lib.rs index 4ed4579a4..bc27aa9c3 100644 --- a/crates/query/src/lib.rs +++ b/crates/query/src/lib.rs @@ -17,6 +17,10 @@ //! slots, and each `Scan` it reaches outside them as a raw data slot. A //! query the engine cannot answer returns [`Unanswered`]; the caller then //! forwards it to Prometheus (or refuses it). +//! +//! [`ExecutorQueryEngine`] runs the compiled queries ([`CompiledQueries`]) +//! on the `query-N` workers ([`workers`]) and implements +//! [`common::QueryEngine`]. use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; @@ -33,13 +37,17 @@ use asap_executor::values::{Batch, Value}; use common::InstallablePlan; use futures::executor::block_on; use futures::StreamExt; +use internal_metrics::QueryMetrics; use storage::store::{PublishedStore, QueryTimeResults, RawReads, RawShards, RunStore, ViewStore}; use crate::result_cache::{Answer, ResultCache}; +mod engine; pub mod result_cache; pub mod workers; +pub use engine::{ExecutorQueryEngine, QueryOptions}; + /// One series of an instant-query result. #[derive(Debug, Clone, PartialEq)] pub struct ResultSample { @@ -54,8 +62,9 @@ pub struct ResultSample { /// Why the engine does not answer a query. #[derive(Debug, Clone, PartialEq, thiserror::Error)] pub enum Unanswered { - #[error("the installed plan has no query {0:?}")] - NotPlanned(String), + /// The query was resolved against another plan than the one installed. + #[error("the plan changed since the query was resolved")] + PlanChanged, #[error("the data plane cannot run this query: {0}")] Unsupported(String), /// Rows the run reads are not stored: a view's window (e.g. the first @@ -74,9 +83,15 @@ struct Run { reads: Vec, } -pub struct QueryEngine { +/// The installed plan's queries, compiled. +pub struct CompiledQueries { /// Each query and its root, or why it cannot run. roots: Vec<(String, Result)>, + /// Each planned root: whether its run, and every shared node's run it + /// reads, compiled. + runnable: HashMap>, + /// Each planned query's measurements, by query text (trimmed), sorted. + metrics: Vec<(String, QueryMetrics)>, /// The run of each query root and shared node. runs: BTreeMap, /// The shared nodes: their outputs live in `results`. @@ -90,7 +105,7 @@ pub struct QueryEngine { result_cache: Option, } -impl QueryEngine { +impl CompiledQueries { /// Compiles each query's root of `plan`, whose views are `views`, and /// each query-time `OneEvaluation` node shared by several queries' /// runs, whose outputs `results` keeps. With `share_one_evaluation` @@ -144,7 +159,7 @@ impl QueryEngine { .map_err(|e| e.to_string()); compiled.insert(node, run); } - let roots = plan + let roots: Vec<(String, Result)> = plan .query_texts .iter() .zip(&dag.roots) @@ -153,12 +168,24 @@ impl QueryEngine { (query.trim().to_string(), runnable) }) .collect(); + let runnable_roots = dag + .roots + .iter() + .map(|&root| (root, runnable(root, &compiled))) + .collect(); + let metrics: BTreeSet<&String> = roots.iter().map(|(query, _)| query).collect(); + let metrics = metrics + .into_iter() + .map(|query| (query.clone(), QueryMetrics::default())) + .collect(); let runs = compiled .into_iter() .filter_map(|(node, run)| Some((node, run.ok()?))) .collect(); Ok(Self { roots, + runnable: runnable_roots, + metrics, runs, shared, results, @@ -186,23 +213,34 @@ impl QueryEngine { &self.shared } - /// The planned `query`'s root. - fn root(&self, query: &str) -> Result { + /// Each planned query's measurements, by query text, sorted. + pub fn metrics(&self) -> &[(String, QueryMetrics)] { + &self.metrics + } + + /// Where the planned `query`'s measurements are in [`Self::metrics`]. + pub fn metrics_index(&self, query: &str) -> Option { let query = query.trim(); - Ok(*self - .roots - .iter() - .find(|(planned, _)| planned == query) - .ok_or_else(|| Unanswered::NotPlanned(query.to_string()))? - .1 - .as_ref() - .map_err(|reason| Unanswered::Unsupported(reason.clone()))?) + self.metrics + .binary_search_by(|(planned, _)| planned.as_str().cmp(query)) + .ok() + } + + /// Planned root `root`, if its run compiled; `PlanChanged` if it is no + /// root of this plan. + fn root(&self, root: PhysicalASAPNodeId) -> Result { + match self.runnable.get(&root) { + Some(Ok(())) => Ok(root), + Some(Err(reason)) => Err(Unanswered::Unsupported(reason.clone())), + None => Err(Unanswered::PlanChanged), + } } - /// The result cache's answer to `query` at `time_ms`, if it keeps one. - pub fn cached(&self, query: &str, time_ms: i64) -> Option { + /// The result cache's answer at `time_ms` of the query planned at + /// `root`, if it keeps one. + pub fn cached(&self, root: PhysicalASAPNodeId, time_ms: i64) -> Option { let cache = self.result_cache.as_ref()?; - cache.get(self.root(query).ok()?, time_ms) + cache.get(self.root(root).ok()?, time_ms) } /// The result cache, when it is on. @@ -227,7 +265,7 @@ impl QueryEngine { } } - /// Answers `query` at `time_ms` from `snapshot`, and keeps the answer in the result cache when it is final: the run + /// Answers the query planned at `root` at `time_ms` from `snapshot`, and keeps the answer in the result cache when it is final: the run /// succeeded, so every view window it read was stored (a window is /// appended once, when the watermark closes it, and never changes), /// and, when the root reads raw data through a `Scan`, `time_ms` is at @@ -236,11 +274,11 @@ impl QueryEngine { /// read here: callers read it first ([`Self::cached`]). pub fn evaluate( &self, - query: &str, + root: PhysicalASAPNodeId, time_ms: i64, snapshot: &Snapshot, ) -> Result { - let root = self.root(query)?; + let root = self.root(root)?; let watermark_ms = snapshot.watermark_ms; let batches = self.output(root, time_ms, snapshot)?; let compiled = &self.runs[&root].compiled; @@ -310,7 +348,7 @@ impl QueryEngine { #[allow(dead_code)] fn assert_send_sync() {} const _: fn() = || { - assert_send_sync::(); + assert_send_sync::(); assert_send_sync::(); }; diff --git a/crates/query/src/result_cache.rs b/crates/query/src/result_cache.rs index e8f2f260c..943d285b8 100644 --- a/crates/query/src/result_cache.rs +++ b/crates/query/src/result_cache.rs @@ -4,7 +4,7 @@ //! An instant query at `T` and a range step at `T` share one entry. //! //! Only a final answer is kept: one whose inputs can no longer change -//! ([`crate::QueryEngine`] decides). Entries are dropped once `T` +//! ([`crate::CompiledQueries`] decides). Entries are dropped once `T` //! falls further behind the watermark than any planned evaluation reaches //! back (the plan's longest retention plus the view retention margin), and //! the least recently used while more than `max_bytes` are held. diff --git a/crates/query/src/workers.rs b/crates/query/src/workers.rs index bdf2a8678..4904d7fd9 100644 --- a/crates/query/src/workers.rs +++ b/crates/query/src/workers.rs @@ -3,101 +3,165 @@ //! run's output stream is not `Send`, so a run never moves between //! threads. +use std::sync::atomic::Ordering; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::{Arc, Mutex}; -use internal_metrics::{Metrics, Timer}; +use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; +use common::{AnswerSource, PlanId}; +use internal_metrics::Timer; use storage::store::PublishedStore; use tokio::sync::oneshot; use crate::result_cache::Answer; -use crate::{QueryEngine, Snapshot, Unanswered}; +use crate::{CompiledQueries, Snapshot, Unanswered}; type Reply = oneshot::Sender>; -/// The query workers and the compiled queries they run. +/// The installed plan's compiled queries and the workers that run them. #[derive(Clone)] pub struct QueryWorkers { + /// The plan the queries were compiled from. + plan: PlanId, /// Queries for the worker threads. queries: Sender, - query: Arc, + compiled: Arc, threads: usize, published: Arc, - metrics: Arc, } impl QueryWorkers { - /// Starts `threads` workers running `query`'s queries over the - /// snapshots `published` holds, recording into `metrics`. - pub fn start( - query: QueryEngine, + /// Starts `threads` workers running `compiled`, plan `plan`'s queries, + /// over the snapshots `published` holds. + pub(crate) fn start( + plan: PlanId, + compiled: CompiledQueries, published: Arc, - metrics: Arc, threads: usize, ) -> std::io::Result { let threads = threads.max(1); - let query = Arc::new(query); + let compiled = Arc::new(compiled); let (queries, jobs) = channel::(); - spawn_query_workers( - query.clone(), - published.clone(), - metrics.clone(), - jobs, - threads, - )?; + spawn_query_workers(compiled.clone(), published.clone(), jobs, threads)?; Ok(Self { + plan, queries, - query, + compiled, threads, published, - metrics, }) } - /// Answers the planned `query` at `time_ms` on a query worker, from - /// the newest snapshot published when the run starts; see - /// [`QueryEngine::evaluate`]. Two queries at one evaluation time may - /// read different snapshots. A query does not wait for writes - /// acknowledged before it; an event-time barrier does + /// The root `source` names, if it was resolved against this plan. + fn root(&self, source: &AnswerSource) -> Result { + match *source { + AnswerSource::Planned { plan, root } if plan == self.plan => Ok(root), + AnswerSource::Planned { .. } => Err(Unanswered::PlanChanged), + } + } + + /// Answers `query`, resolved to `source`, at `time_ms`: from the result + /// cache, or on a query worker from the newest snapshot published when + /// the run starts ([`CompiledQueries::evaluate`]). Two queries at one + /// evaluation time may read different snapshots. A query does not wait + /// for writes acknowledged before it; an event-time barrier does /// (`advance_watermark` of the precompute engine). - pub async fn evaluate(&self, query: String, time_ms: i64) -> Result { + pub async fn instant( + &self, + source: &AnswerSource, + query: &str, + time_ms: i64, + ) -> Result { + let root = self.root(source)?; + if let Some(answer) = self.compiled.cached(root, time_ms) { + return Ok(answer); + } let started = std::time::Instant::now(); - let metrics = self.metrics.query(&query); - let answer = self.run_on_worker(query, time_ms, None).await; - if let Some(metrics) = metrics { + let metrics = self.compiled.metrics_index(query); + let answer = self.run_on_worker(root, metrics, time_ms, None).await; + if let Some(index) = metrics { + let metrics = &self.compiled.metrics()[index].1; metrics.latency.observe(started.elapsed().as_secs_f64()); } answer } - /// Evaluates one step of a range query over `snapshot`, which every - /// step of the request reads ([`Self::snapshot`]): as - /// [`Self::evaluate`], counted as a range step rather than an instant - /// query. A step whose future is dropped before a worker takes it (the - /// range failed or its client went away) is not run. - pub async fn evaluate_range_step( + /// Answers `query`, resolved to `source`, at every time of `times_ms`, + /// the steps in parallel on the query workers; unanswered if any step + /// is. + pub async fn range( &self, - query: String, - time_ms: i64, - snapshot: Arc, - ) -> Result { - self.run_on_worker(query, time_ms, Some(snapshot)).await + source: &AnswerSource, + query: &str, + times_ms: impl Iterator, + ) -> Result, Unanswered> { + use futures::StreamExt; + let root = self.root(source)?; + let started = std::time::Instant::now(); + let metrics = self.compiled.metrics_index(query); + // The steps the result cache answers; only the others run. + let cached: Vec<(i64, Option)> = times_ms + .map(|time_ms| (time_ms, self.compiled.cached(root, time_ms))) + .collect(); + let from_cache = cached.iter().filter(|(_, hit)| hit.is_some()).count(); + // Every step reads the same snapshot, so the raw data they share is + // converted once ([`storage::store::RawReads`]). + let snapshot = self.snapshot(); + // At most one step per query worker in flight, so a long range neither + // floods the workers' queue nor starves instant queries; the client + // going away drops the rest unrun. Every step runs even when one fails: + // with `final_query_results_cached` the plan keeps a step's inputs only + // for the refresh interval, so the older steps of a span are answered + // from the result cache, and a request whose older steps are not cached + // yet (the first span after a start) still caches the steps it can + // answer; a dashboard refreshing the range fills the cache within one + // span. + let results: Vec> = futures::stream::iter(cached) + .map(|(time_ms, hit)| { + let snapshot = snapshot.clone(); + async move { + let samples = match hit { + Some(samples) => samples, + None => { + self.run_on_worker(root, metrics, time_ms, Some(snapshot)) + .await? + } + }; + Ok::<_, Unanswered>((time_ms, samples)) + } + }) + .buffered(self.threads) + .collect() + .await; + let steps: Vec<_> = results.into_iter().collect::>()?; + if let Some(index) = metrics { + let metrics = &self.compiled.metrics()[index].1; + metrics + .range_latency + .observe(started.elapsed().as_secs_f64()); + metrics + .range_steps_cached + .fetch_add(from_cache as u64, Ordering::Relaxed); + metrics + .range_steps + .fetch_add(steps.len() as u64, Ordering::Relaxed); + } + Ok(steps) } /// The newest published store, for the steps of one range request. pub fn snapshot(&self) -> Arc { - Arc::new(self.query.snapshot(&self.published)) - } - - /// The result cache's answer to the planned `query` at `time_ms`, if - /// it keeps one ([`QueryEngine::cached`]). - pub fn cached(&self, query: &str, time_ms: i64) -> Option { - self.query.cached(query, time_ms) + Arc::new(self.compiled.snapshot(&self.published)) } + /// Runs `root` at `time_ms` on a worker, over `range_step`'s snapshot + /// (one step of a range query) or the newest; `metrics` indexes the + /// query's measurements. A step whose future is dropped before a worker + /// takes it (the range failed or its client went away) is not run. async fn run_on_worker( &self, - query: String, + root: PhysicalASAPNodeId, + metrics: Option, time_ms: i64, range_step: Option>, ) -> Result { @@ -105,7 +169,8 @@ impl QueryWorkers { let (reply, answer) = oneshot::channel(); self.queries .send(QueryJob { - query, + root, + metrics, time_ms, range_step, reply, @@ -114,20 +179,27 @@ impl QueryWorkers { answer.await.map_err(|_| stopped())? } + /// The plan the queries were compiled from. + pub fn plan(&self) -> PlanId { + self.plan + } + /// The query worker threads: the most query runs at once. pub fn threads(&self) -> usize { self.threads } /// The compiled queries. - pub fn engine(&self) -> &QueryEngine { - &self.query + pub fn compiled(&self) -> &CompiledQueries { + &self.compiled } } /// One query for a worker thread. struct QueryJob { - query: String, + root: PhysicalASAPNodeId, + /// The query's measurements in [`CompiledQueries::metrics`], if planned. + metrics: Option, time_ms: i64, /// One step of a range query, and the snapshot every step reads. range_step: Option>, @@ -137,20 +209,14 @@ struct QueryJob { /// Starts `threads` workers `query-0`, `query-1`, …, each running one query /// at a time to completion from `jobs`; more queries wait in `jobs`. fn spawn_query_workers( - query: Arc, + compiled: Arc, published: Arc, - metrics: Arc, jobs: Receiver, threads: usize, ) -> std::io::Result<()> { let jobs = Arc::new(Mutex::new(jobs)); for index in 0..threads { - let (query, published, metrics, jobs) = ( - query.clone(), - published.clone(), - metrics.clone(), - jobs.clone(), - ); + let (compiled, published, jobs) = (compiled.clone(), published.clone(), jobs.clone()); std::thread::Builder::new() .name(format!("query-{index}")) .spawn(move || loop { @@ -164,14 +230,15 @@ fn spawn_query_workers( continue; } let timer = Timer::start(); + let metrics = job.metrics.map(|index| &compiled.metrics()[index]); // A bug in one run must not take the worker down: it // answers that run with the error and keeps serving. let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let snapshot = match &job.range_step { Some(snapshot) => snapshot.clone(), - None => Arc::new(query.snapshot(&published)), + None => Arc::new(compiled.snapshot(&published)), }; - query.evaluate(&job.query, job.time_ms, &snapshot) + compiled.evaluate(job.root, job.time_ms, &snapshot) })) .unwrap_or_else(|panic| { let reason = panic @@ -179,10 +246,11 @@ fn spawn_query_workers( .map(ToString::to_string) .or_else(|| panic.downcast_ref::().cloned()) .unwrap_or_default(); - tracing::error!(query = %job.query, time_ms = job.time_ms, %reason, "query run panicked"); + let query = metrics.map_or("", |(query, _)| query.as_str()); + tracing::error!(query, root = job.root, time_ms = job.time_ms, %reason, "query run panicked"); Err(Unanswered::Execution(format!("the query run panicked: {reason}"))) }); - if let Some(metrics) = metrics.query(&job.query) { + if let Some((_, metrics)) = metrics { match job.range_step { None => metrics.run.record(timer), Some(_) => metrics.range_step_run.record(timer), From 4dda2727aea8e49d978ebba7dddf6c7b2aeedf5c Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 11:23:12 +0000 Subject: [PATCH 2/4] refactor: review fixes for the engine traits, installer and dispatcher - PlanInstaller takes only the first install call (the engines install once too); its test checks the query engine keeps the plan unused after the ingest engine refuses it. - NotAnswerableReason::EngineError holds a QueryEngineError; one Unanswered::is_not_ready rule for the dispatcher and the trait path; Fallback takes the reason by value, so a forward reason is built once. - CompiledQueries keeps the unexecutable queries instead of every root; QueryWorkers is InstalledQueries; its unused threads() is gone. - RawSample::from_batch interns a RawDataBatch for both the ingest engine and the raw-data store adapter; the store helpers the adapters use are pub(crate). - data-plane names InstallablePlan and node ids through common; the Planner crates are dev-dependencies. - QueryOptions documents its fields; test- and benchmark-only accessors are doc(hidden). --- crates/data-plane/Cargo.toml | 5 ++- crates/data-plane/src/dispatcher.rs | 45 +++++++++++----------- crates/data-plane/src/engine.rs | 14 ++++--- crates/data-plane/src/installer.rs | 55 +++++++++++++++------------ crates/data-plane/src/lib.rs | 23 +++++------ crates/data-plane/src/test_support.rs | 2 +- crates/precompute/src/engine.rs | 15 ++------ crates/query/src/engine.rs | 34 +++++++++++------ crates/query/src/lib.rs | 46 ++++++++++++---------- crates/query/src/workers.rs | 12 ++---- 10 files changed, 131 insertions(+), 120 deletions(-) diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index 9eb71215a..b7e87ca97 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -4,8 +4,6 @@ version.workspace = true edition.workspace = true [dependencies] -asap-planner.workspace = true -asap-executor.workspace = true common.workspace = true internal_metrics.workspace = true precompute.workspace = true @@ -34,6 +32,9 @@ snap = "1.1" form_urlencoded = "1" [dev-dependencies] +# Plans and IR the tests and the micro benchmarks build. +asap-planner.workspace = true +asap-executor.workspace = true async-trait.workspace = true futures = "0.3" control_plane.workspace = true diff --git a/crates/data-plane/src/dispatcher.rs b/crates/data-plane/src/dispatcher.rs index 5e418517e..c55fa7aaf 100644 --- a/crates/data-plane/src/dispatcher.rs +++ b/crates/data-plane/src/dispatcher.rs @@ -10,7 +10,7 @@ use std::sync::{Arc, OnceLock}; -use common::{AnswerSource, InstalledPlan, PhysicalASAPNodeId, PlanId}; +use common::{AnswerSource, InstalledPlan, PhysicalASAPNodeId, PlanId, QueryEngineError}; use query::result_cache::Answer; use query::{ExecutorQueryEngine, Unanswered}; @@ -30,34 +30,33 @@ pub enum NotAnswerableReason { /// The stored data does not cover the query, or the plan changed since /// it was resolved: why. NotReady(String), - /// The engine failed to run the query: the error. - EngineError(String), + /// The engine failed to run the query. + EngineError(QueryEngineError), } impl NotAnswerableReason { - fn new(unanswered: Unanswered) -> Self { - match unanswered { - Unanswered::MissingRows(_) | Unanswered::PlanChanged => { - Self::NotReady(unanswered.to_string()) - } - Unanswered::Unsupported(_) | Unanswered::Execution(_) => { - Self::EngineError(unanswered.to_string()) - } + /// Why `unanswered` was not answered, as the dispatcher reports it. + pub(crate) fn new(unanswered: Unanswered) -> Self { + if unanswered.is_not_ready() { + Self::NotReady(unanswered.to_string()) + } else { + Self::EngineError(QueryEngineError::new(unanswered.to_string())) } } /// What a client is told: `query` was not answered because of this. - pub fn message(&self, query: &str) -> String { + pub fn into_message(self, query: &str) -> String { match self { Self::Unmatched => format!("the installed plan has no query {:?}", query.trim()), - Self::NotReady(reason) | Self::EngineError(reason) => reason.clone(), + Self::NotReady(reason) => reason, + Self::EngineError(error) => error.message, } } } /// How a query the plan does not answer is answered. #[derive(Debug, Clone, PartialEq, Eq)] -pub enum Fallback { +pub(crate) enum Fallback { /// Forwarded to the backend (Prometheus, or the raw store in forward /// mode), with why the plan did not answer when it planned the query. Forward { reason: Option }, @@ -68,15 +67,15 @@ pub enum Fallback { impl Fallback { /// For `query`, not answered because of `reason`, when the data plane /// may forward or not (`no_forward`). - pub fn new(reason: &NotAnswerableReason, query: &str, no_forward: bool) -> Self { + pub(crate) fn new(reason: NotAnswerableReason, query: &str, no_forward: bool) -> Self { match reason { _ if no_forward => Self::Refuse { - reason: reason.message(query), + reason: reason.into_message(query), }, NotAnswerableReason::Unmatched => Self::Forward { reason: None }, NotAnswerableReason::NotReady(_) | NotAnswerableReason::EngineError(_) => { Self::Forward { - reason: Some(reason.message(query)), + reason: Some(reason.into_message(query)), } } } @@ -198,7 +197,7 @@ mod tests { QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched) ); assert_eq!( - Fallback::new(&NotAnswerableReason::Unmatched, "up", false), + Fallback::new(NotAnswerableReason::Unmatched, "up", false), Fallback::Forward { reason: None } ); } @@ -214,9 +213,9 @@ mod tests { panic!("expected not ready, got {outcome:?}"); }; assert_eq!( - Fallback::new(&reason, QUERY, false), + Fallback::new(reason.clone(), QUERY, false), Fallback::Forward { - reason: Some(reason.message(QUERY)) + reason: Some(reason.into_message(QUERY)) } ); let range = dispatcher.range(QUERY, [30_000, 40_000].into_iter()).await; @@ -249,13 +248,13 @@ mod tests { else { panic!("expected an engine error, got {outcome:?}"); }; - let message = reason.message(QUERY); + let message = reason.clone().into_message(QUERY); assert!( message.starts_with("the data plane cannot run this query"), "{message}" ); assert_eq!( - Fallback::new(&reason, QUERY, true), + Fallback::new(reason, QUERY, true), Fallback::Refuse { reason: message } ); } @@ -264,7 +263,7 @@ mod tests { #[test] fn an_unmatched_query_is_refused_without_forwarding() { assert_eq!( - Fallback::new(&NotAnswerableReason::Unmatched, " up ", true), + Fallback::new(NotAnswerableReason::Unmatched, " up ", true), Fallback::Refuse { reason: "the installed plan has no query \"up\"".into() } diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index 741d6ae1c..72fa354ad 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -5,15 +5,14 @@ use std::sync::Arc; -use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; -use asap_planner::InstallablePlan; +use common::{InstallablePlan, PhysicalASAPNodeId}; use internal_metrics::{Metrics, QueryMetrics}; use precompute::engine::{ IngestError, InstalledPrecompute, PersistedViews, PrecomputeEngine, PrecomputeMode, PrecomputeOptions, SlowRefresh, }; use precompute::ingestion::{IngestionOptions, IngestionStats}; -use query::workers::QueryWorkers; +use query::workers::InstalledQueries; use query::{ExecutorQueryEngine, QueryOptions, Unanswered}; use storage::persist::{plan_hash, ViewRead}; use storage::persist_pool::PersistOptions; @@ -189,7 +188,7 @@ impl Default for EngineOptions { #[derive(Clone)] pub struct EngineHandle { precompute: InstalledPrecompute, - query: QueryWorkers, + query: InstalledQueries, dispatcher: Arc, /// The views' cold tier, when they are persisted. view_tier: Option>, @@ -251,12 +250,15 @@ impl EngineHandle { &self.dispatcher } - /// The newest published store: what a query starting now reads. + /// For tests: the newest published store, what a query starting now + /// reads. + #[doc(hidden)] pub fn snapshot(&self) -> Arc { self.query.snapshot() } - /// Each planned query's measurements, by query text. + /// For benchmarks: each planned query's measurements, by query text. + #[doc(hidden)] pub fn query_metrics(&self) -> &[(String, QueryMetrics)] { self.query.compiled().metrics() } diff --git a/crates/data-plane/src/installer.rs b/crates/data-plane/src/installer.rs index 79508ac2c..d8dd33dfe 100644 --- a/crates/data-plane/src/installer.rs +++ b/crates/data-plane/src/installer.rs @@ -12,8 +12,9 @@ pub struct PlanInstaller { ingest: Arc, query: Arc, dispatcher: Arc, - /// The installed plan's id; `None` before the first install. - installed: Mutex>, + /// Whether an install was tried: v1 takes only the first, whether it + /// installs or fails. + tried: Mutex, } impl PlanInstaller { @@ -26,7 +27,7 @@ impl PlanInstaller { ingest, query, dispatcher, - installed: Mutex::new(None), + tried: Mutex::new(false), } } @@ -34,19 +35,22 @@ impl PlanInstaller { /// engine and the dispatcher, in that order, stopping at the first /// failure. Queries reach a plan only through the dispatcher, which /// gets it last: on any failure the current plan stays the one queries - /// are answered from. The query engine goes first because its install - /// only compiles and starts idle workers; the ingest engine's starts - /// ingestion. Refused once a plan is installed. + /// are answered from (none, in v1). The query engine goes first because + /// its install only compiles and starts idle workers; the ingest + /// engine's starts ingestion. v1 installs once: only the first call is + /// taken, as the engines install once too (after the ingest engine + /// refused a plan, the query engine keeps it, unused). A failed install + /// at startup ends the data plane. pub fn install(&self, plan: InstallablePlan) -> Result { - let mut installed = self.installed.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(id) = *installed { - return Err(InstallError::new(format!( - "plan {} is installed, and the data plane installs one plan", - id.0 - ))); + let mut tried = self.tried.lock().unwrap_or_else(|e| e.into_inner()); + if std::mem::replace(&mut *tried, true) { + return Err(InstallError::new( + "the data plane installs one plan, and an install was tried already", + )); } plan.validate() .map_err(|error| InstallError::new(format!("{:#}", anyhow::Error::from(error))))?; + // #935's plan id counts installs; v1's one install is plan 1. let plan = InstalledPlan { id: PlanId(1), plan, @@ -54,7 +58,6 @@ impl PlanInstaller { self.query.install(plan.clone())?; self.ingest.install(plan.clone())?; self.dispatcher.install(&plan); - *installed = Some(plan.id); Ok(plan.id) } } @@ -171,35 +174,37 @@ mod tests { } /// An invalid plan, or one either engine refuses, reaches no later - /// step: the dispatcher matches no query, and a later plan can still - /// install. + /// step, the dispatcher matches no query, and no later plan installs. #[test] fn a_failed_install_leaves_the_plan_as_it_was() { let mut invalid = test_support::plan(QUERY, false); invalid.query_texts.push("up".into()); - for (ingest, query, plan) in [ + // Each case: the ingest and query engines, the plan, and the plans + // the query engine got before the failure. + type Case = (Arc, Arc, InstallablePlan, &'static [PlanId]); + let cases: [Case; 3] = [ + (Arc::default(), Arc::default(), invalid, &[]), ( - Arc::new(Fake::default()), - Arc::new(Fake::default()), - invalid, - ), - ( - Arc::new(Fake::default()), + Arc::default(), Fake::refusing(), test_support::plan(QUERY, false), + &[], ), ( Fake::refusing(), - Arc::new(Fake::default()), + Arc::default(), test_support::plan(QUERY, false), + &[PlanId(1)], ), - ] { + ]; + for (ingest, query, plan, query_got) in cases { let dispatcher = dispatcher(); let installer = PlanInstaller::new(ingest.clone(), query.clone(), dispatcher.clone()); assert!(installer.install(plan).is_err()); + assert!(installer.install(test_support::plan(QUERY, false)).is_err()); assert!(ingest.installed().is_empty()); + assert_eq!(query.installed(), query_got); assert!(dispatcher.resolve(QUERY).is_none()); - assert!(installer.installed.lock().unwrap().is_none()); } } } diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index d2eaedfd0..097f64929 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -2,12 +2,14 @@ //! the Prometheus query API for an installed plan. //! //! The installed plan is ASAPPlanner's `InstallablePlan`: one selected -//! physical ASAP DAG. The engine's ingest shards store the raw samples its -//! `Scan`s read, its precompute pool refreshes the materialized views in -//! ingestion runs, and query worker threads answer the plan's instant and -//! range 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`). +//! physical ASAP DAG. The precompute engine's ingest shards store the raw +//! samples its `Scan`s read and its precompute pool refreshes the +//! materialized views in ingestion runs ([`precompute`]); the query +//! engine's worker threads answer the plan's instant and range queries +//! with query runs ([`query`]), all through the Planner's executor. The +//! HTTP routes run queries through the [`dispatcher`]: every other query, +//! and any planned query the plan 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 @@ -16,7 +18,7 @@ pub mod dispatcher; pub mod engine; -pub mod installer; +mod installer; mod metrics_endpoint; pub mod prometheus; pub mod raw_forward; @@ -362,7 +364,7 @@ async fn query( } QueryOutcome::NotAnswerable(reason) => reason, }; - match Fallback::new(&reason, &instant.query, state.no_forward) { + match Fallback::new(reason, &instant.query, state.no_forward) { Fallback::Refuse { reason } => not_answered(&reason), Fallback::Forward { reason } => { if let Some(reason) = &reason { @@ -413,7 +415,7 @@ async fn query_range( } Err(reason) => reason, }; - match Fallback::new(&reason, &range.query, state.no_forward) { + match Fallback::new(reason, &range.query, state.no_forward) { Fallback::Refuse { reason } => not_answered(&reason), Fallback::Forward { reason } => { if let Some(reason) = &reason { @@ -458,8 +460,7 @@ async fn answer_range( // on that worker, instant queries and Remote Write included, and with // every worker so busy no timer or socket is polled: built on the // blocking pool instead. - let failed = - |error: String| NotAnswerableReason::EngineError(Unanswered::Execution(error).to_string()); + let failed = |error: String| NotAnswerableReason::new(Unanswered::Execution(error)); tokio::task::spawn_blocking(move || { prometheus::range_response_body(&steps) .map_err(|error| failed(format!("the range response: {error}"))) diff --git a/crates/data-plane/src/test_support.rs b/crates/data-plane/src/test_support.rs index 8110eb65c..e9989d4b7 100644 --- a/crates/data-plane/src/test_support.rs +++ b/crates/data-plane/src/test_support.rs @@ -1,6 +1,6 @@ //! Plans and options for the unit tests. -use asap_planner::InstallablePlan; +use common::InstallablePlan; use precompute::ingestion::IngestionOptions; use storage::store::RawSample; diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 304899286..b639a9b6c 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -339,17 +339,10 @@ impl common::IngestEngine for PrecomputeEngine { let Some(installed) = self.installed() else { return Ok(()); }; - let RawDataBatch::TimeSeries { series } = batch; - let mut samples = Vec::new(); - for (labels, points) in &series { - let pairs: Vec<(&String, &String)> = labels.iter().collect(); - let series = storage::series_ids::intern_pairs(&pairs); - samples.extend(points.iter().map(|&(timestamp_ms, value)| RawSample { - labels: series, - timestamp_ms, - value, - })); - } + let samples = RawSample::from_batch(&batch); + // `try_ingest` takes the samples, so each attempt gets a copy: this + // path is for adapters (no HTTP route calls it); Remote Write calls + // `try_ingest` directly and answers 503 instead of waiting. loop { match installed.try_ingest(samples.clone()) { Ok(()) => return Ok(()), diff --git a/crates/query/src/engine.rs b/crates/query/src/engine.rs index a2f76e066..6ab855d30 100644 --- a/crates/query/src/engine.rs +++ b/crates/query/src/engine.rs @@ -15,19 +15,26 @@ use common::{ use storage::store::{PublishedStore, QueryTimeResults}; use crate::result_cache::{Answer, ResultCache}; -use crate::workers::QueryWorkers; -use crate::{CompiledQueries, Unanswered}; +use crate::workers::InstalledQueries; +use crate::CompiledQueries; -/// How the query engine compiles and runs the plan's queries; the data -/// plane's `EngineOptions` describes each field. +/// How the query engine compiles and runs the plan's queries. #[derive(Debug, Clone, PartialEq, Eq)] pub struct QueryOptions { + /// The most bytes one query run may hold. pub run_memory_limit_bytes: usize, + /// Query worker threads: the most query runs at once. pub threads: usize, + /// Compute each query-time `OneEvaluation` node several queries read + /// once per evaluation time; `false` computes it in every query's run. pub share_one_evaluation_results: bool, + /// How long a query-time result is kept after its evaluation time. pub query_time_results_retention_ms: u64, + /// The most bytes of query-time results kept. pub query_time_results_max_bytes: usize, + /// Keep each planned query's final answer at each evaluation time. pub result_cache: bool, + /// The most bytes of answers the result cache keeps. pub result_cache_max_bytes: usize, /// How much longer than the plan's retention views are kept, which /// bounds how far back the result cache keeps answers. @@ -44,7 +51,7 @@ pub struct ExecutorQueryEngine { published: Arc, /// Held while a plan is installed, so two installs do not both start. installing: Mutex<()>, - installed: OnceLock, + installed: OnceLock, } impl ExecutorQueryEngine { @@ -59,12 +66,12 @@ impl ExecutorQueryEngine { } /// The installed plan's queries and workers; `None` before the install. - pub fn installed(&self) -> Option<&QueryWorkers> { + pub fn installed(&self) -> Option<&InstalledQueries> { self.installed.get() } /// Compiles `plan`'s queries and starts the workers. - fn start(&self, plan: &InstalledPlan) -> anyhow::Result { + fn start(&self, plan: &InstalledPlan) -> anyhow::Result { let options = &self.options; let views = plan.plan.materialized_views()?; let limits = Limits { @@ -102,7 +109,7 @@ impl ExecutorQueryEngine { reasons.join("; ") ); } - Ok(QueryWorkers::start( + Ok(InstalledQueries::start( plan.id, compiled, self.published.clone(), @@ -145,9 +152,7 @@ impl ExecutorQueryEngine { }; match result { Ok(result) => Ok(EngineQueryResult::Ready { result }), - Err(Unanswered::MissingRows(_) | Unanswered::PlanChanged) => { - Ok(EngineQueryResult::NotReady) - } + Err(unanswered) if unanswered.is_not_ready() => Ok(EngineQueryResult::NotReady), Err(error) => Err(QueryEngineError::new(error.to_string())), } } @@ -246,7 +251,8 @@ mod tests { /// Through `QueryEngine`: nothing is ready before the install, the plan /// installs once, a query resolved against another plan is not ready, - /// and neither is one whose views are not stored yet. + /// and neither is one whose views are not stored yet. Its measurements + /// are found by its trimmed text. #[tokio::test] async fn the_query_engine_installs_once_and_reports_not_ready() { let options = QueryOptions { @@ -284,6 +290,10 @@ mod tests { }; assert_eq!(engine.install(installed(1)), Ok(())); assert!(engine.install(installed(2)).is_err()); + // The query's measurements are found by its text, trimmed. + let compiled = engine.installed().unwrap().compiled(); + assert_eq!(compiled.metrics_index(&format!(" {QUERY} ")), Some(0)); + assert_eq!(compiled.metrics_index("up"), None); let range = request(QueryEval::Range { start_ms: 10_000, end_ms: 30_000, diff --git a/crates/query/src/lib.rs b/crates/query/src/lib.rs index bc27aa9c3..33c5c0788 100644 --- a/crates/query/src/lib.rs +++ b/crates/query/src/lib.rs @@ -76,6 +76,14 @@ pub enum Unanswered { Execution(String), } +impl Unanswered { + /// Whether the query only lacks data, or was resolved against another + /// plan (the boundary's `NotReady`), rather than failing to run. + pub fn is_not_ready(&self) -> bool { + matches!(self, Self::MissingRows(_) | Self::PlanChanged) + } +} + /// One compiled query run: of a query's root, or of a shared node. struct Run { compiled: CompiledPhysicalDAG, @@ -85,8 +93,8 @@ struct Run { /// The installed plan's queries, compiled. pub struct CompiledQueries { - /// Each query and its root, or why it cannot run. - roots: Vec<(String, Result)>, + /// Each planned query (trimmed) the engine cannot run, with why. + unexecutable: Vec<(String, String)>, /// Each planned root: whether its run, and every shared node's run it /// reads, compiled. runnable: HashMap>, @@ -159,31 +167,30 @@ impl CompiledQueries { .map_err(|e| e.to_string()); compiled.insert(node, run); } - let roots: Vec<(String, Result)> = plan - .query_texts - .iter() - .zip(&dag.roots) - .map(|(query, &root)| { - let runnable = runnable(root, &compiled).map(|()| root); - (query.trim().to_string(), runnable) - }) - .collect(); - let runnable_roots = dag + let runnable_roots: HashMap> = dag .roots .iter() .map(|&root| (root, runnable(root, &compiled))) .collect(); - let metrics: BTreeSet<&String> = roots.iter().map(|(query, _)| query).collect(); + let queries = || plan.query_texts.iter().map(|query| query.trim()); + let unexecutable = queries() + .zip(&dag.roots) + .filter_map(|(query, root)| { + let reason = runnable_roots[root].as_ref().err()?; + Some((query.to_string(), reason.clone())) + }) + .collect(); + let metrics: BTreeSet<&str> = queries().collect(); let metrics = metrics .into_iter() - .map(|query| (query.clone(), QueryMetrics::default())) + .map(|query| (query.to_string(), QueryMetrics::default())) .collect(); let runs = compiled .into_iter() .filter_map(|(node, run)| Some((node, run.ok()?))) .collect(); Ok(Self { - roots, + unexecutable, runnable: runnable_roots, metrics, runs, @@ -196,11 +203,8 @@ impl CompiledQueries { } /// The planned queries the engine cannot run, with why. - pub fn unexecutable(&self) -> Vec<(String, String)> { - self.roots - .iter() - .filter_map(|(query, root)| Some((query.clone(), root.as_ref().err()?.clone()))) - .collect() + pub fn unexecutable(&self) -> &[(String, String)] { + &self.unexecutable } /// The query-time partition of the view store. @@ -219,7 +223,7 @@ impl CompiledQueries { } /// Where the planned `query`'s measurements are in [`Self::metrics`]. - pub fn metrics_index(&self, query: &str) -> Option { + pub(crate) fn metrics_index(&self, query: &str) -> Option { let query = query.trim(); self.metrics .binary_search_by(|(planned, _)| planned.as_str().cmp(query)) diff --git a/crates/query/src/workers.rs b/crates/query/src/workers.rs index 4904d7fd9..7369265b8 100644 --- a/crates/query/src/workers.rs +++ b/crates/query/src/workers.rs @@ -18,9 +18,10 @@ use crate::{CompiledQueries, Snapshot, Unanswered}; type Reply = oneshot::Sender>; -/// The installed plan's compiled queries and the workers that run them. +/// The installed plan's compiled queries and the `query-N` workers that +/// run them. #[derive(Clone)] -pub struct QueryWorkers { +pub struct InstalledQueries { /// The plan the queries were compiled from. plan: PlanId, /// Queries for the worker threads. @@ -30,7 +31,7 @@ pub struct QueryWorkers { published: Arc, } -impl QueryWorkers { +impl InstalledQueries { /// Starts `threads` workers running `compiled`, plan `plan`'s queries, /// over the snapshots `published` holds. pub(crate) fn start( @@ -184,11 +185,6 @@ impl QueryWorkers { self.plan } - /// The query worker threads: the most query runs at once. - pub fn threads(&self) -> usize { - self.threads - } - /// The compiled queries. pub fn compiled(&self) -> &CompiledQueries { &self.compiled From 93477ef65896337aea4817d5ea47108d9f66984b Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 11:25:03 +0000 Subject: [PATCH 3/4] docs: the result cache's final-answer rule is CompiledQueries::evaluate --- docs/design/data-plane-demo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/data-plane-demo.md b/docs/design/data-plane-demo.md index 6dc7a45c5..385d6d871 100644 --- a/docs/design/data-plane-demo.md +++ b/docs/design/data-plane-demo.md @@ -632,7 +632,7 @@ keeps a rollup result cache for this; the data plane keeps one too - Key and value: (planned query root, evaluation time T) → the answer vector (`Arc`). An instant query at T and a range step at T share the entry. Not aligned start/end are still correct, with fewer hits. -- Only final answers are kept (`QueryEngine::evaluate`): the run succeeded, +- Only final answers are kept (`CompiledQueries::evaluate`): the run succeeded, so every view window it read was stored (a window is appended once, when the watermark closes it, and never changes; a missing one fails the run); and, when the root reaches a `Scan` without passing a view (it reads raw From 7683fc939d218ba37ec3cd99b67fd3bb5450b060 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 22:45:26 +0000 Subject: [PATCH 4/4] refactor: engines without trait objects; whole-stack review fixes The stores and engines have one implementation each, so they are concrete types (a trait is added with its second implementation): - storage::boundary (BoundaryViewStore, BoundaryRawDataStore) and the store helpers only it used (RawData::samples, ViewStore::windows, evict_before, time_ranges, RawSample::from_batch) are not added; storage does not depend on common. - PrecomputeEngine::install and ExecutorQueryEngine::{install, execute} are inherent. IngestEngine::ingest, shutdown and execute_batch are gone (no production caller; every ingest route calls try_ingest). - PlanInstaller holds the two engines, not trait objects, and loses tried: it is built and dropped in one expression, and the engines refuse a second plan. Its tests make the real engines refuse by installing a plan into them first. Its field is precompute, as EngineHandle names the engine. - pub(crate): PlanInstaller; the dispatcher module and its items (no caller outside the crate); precompute's Ingestion, Precompute and the types their methods return; query's unexecutable and horizon_ms. - async-trait leaves precompute, query and data-plane. --- Cargo.lock | 4 - crates/data-plane/Cargo.toml | 1 - crates/data-plane/src/dispatcher.rs | 18 +-- crates/data-plane/src/engine.rs | 6 +- crates/data-plane/src/installer.rs | 207 ++++++++++------------------ crates/data-plane/src/lib.rs | 2 +- crates/precompute/Cargo.toml | 2 - crates/precompute/src/engine.rs | 69 +++------- crates/precompute/src/ingestion.rs | 12 +- crates/query/Cargo.toml | 2 - crates/query/src/engine.rs | 49 +++---- crates/query/src/lib.rs | 5 +- crates/query/src/result_cache.rs | 2 +- 13 files changed, 130 insertions(+), 249 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b8f21a193..4149c4849 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -966,7 +966,6 @@ dependencies = [ "asap-executor", "asap-planner", "asap_sketchlib", - "async-trait", "axum", "clap", "common", @@ -2840,7 +2839,6 @@ version = "0.1.0" dependencies = [ "anyhow", "asap-executor", - "async-trait", "clap", "common", "control_plane", @@ -2925,7 +2923,6 @@ version = "0.1.0" dependencies = [ "anyhow", "asap-executor", - "async-trait", "common", "control_plane", "futures", @@ -3517,7 +3514,6 @@ dependencies = [ "asap-executor", "asap_sketchlib", "clap", - "common", "futures", "internal_metrics", "libc", diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index b7e87ca97..034249bf0 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -35,7 +35,6 @@ form_urlencoded = "1" # Plans and IR the tests and the micro benchmarks build. asap-planner.workspace = true asap-executor.workspace = true -async-trait.workspace = true futures = "0.3" control_plane.workspace = true asap_sketchlib.workspace = true diff --git a/crates/data-plane/src/dispatcher.rs b/crates/data-plane/src/dispatcher.rs index c55fa7aaf..36842961f 100644 --- a/crates/data-plane/src/dispatcher.rs +++ b/crates/data-plane/src/dispatcher.rs @@ -5,8 +5,8 @@ //! The Prometheus routes run queries through the query engine's own //! answers ([`query::result_cache::Answer`]: labels shared with the //! interned series and the result cache), not through -//! [`common::QueryEngine`]'s [`common::QueryResult`], which would copy -//! every series' labels per query. +//! [`ExecutorQueryEngine::execute`]'s [`common::QueryResult`], which would +//! copy every series' labels per query. use std::sync::{Arc, OnceLock}; @@ -16,7 +16,7 @@ use query::{ExecutorQueryEngine, Unanswered}; /// The dispatcher's verdict on one query. #[derive(Debug, Clone, PartialEq)] -pub enum QueryOutcome { +pub(crate) enum QueryOutcome { /// The plan answered. Ready(T), NotAnswerable(NotAnswerableReason), @@ -24,7 +24,7 @@ pub enum QueryOutcome { /// Why the plan did not answer a query; the query falls back. #[derive(Debug, Clone, PartialEq)] -pub enum NotAnswerableReason { +pub(crate) enum NotAnswerableReason { /// No plan is installed, or its query texts hold no such query. Unmatched, /// The stored data does not cover the query, or the plan changed since @@ -45,7 +45,7 @@ impl NotAnswerableReason { } /// What a client is told: `query` was not answered because of this. - pub fn into_message(self, query: &str) -> String { + pub(crate) fn into_message(self, query: &str) -> String { match self { Self::Unmatched => format!("the installed plan has no query {:?}", query.trim()), Self::NotReady(reason) => reason, @@ -90,13 +90,13 @@ struct Planned { } /// Resolves and runs queries; set up by the plan installer. -pub struct QueryDispatcher { +pub(crate) struct QueryDispatcher { engine: Arc, plan: OnceLock, } impl QueryDispatcher { - pub fn new(engine: Arc) -> Self { + pub(crate) fn new(engine: Arc) -> Self { Self { engine, plan: OnceLock::new(), @@ -131,7 +131,7 @@ impl QueryDispatcher { } /// `query` at `time_ms`. - pub async fn instant(&self, query: &str, time_ms: i64) -> QueryOutcome { + pub(crate) async fn instant(&self, query: &str, time_ms: i64) -> QueryOutcome { let (Some(source), Some(engine)) = (self.resolve(query), self.engine.installed()) else { return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched); }; @@ -143,7 +143,7 @@ impl QueryDispatcher { /// `query` at each of `times_ms`: every step's answer, or why some step /// has none. - pub async fn range( + pub(crate) async fn range( &self, query: &str, times_ms: impl Iterator, diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index 72fa354ad..68daa08f4 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -246,7 +246,7 @@ impl EngineHandle { } /// What the HTTP routes run queries through. - pub fn dispatcher(&self) -> &QueryDispatcher { + pub(crate) fn dispatcher(&self) -> &QueryDispatcher { &self.dispatcher } @@ -341,7 +341,7 @@ impl EngineHandle { impl EngineOptions { /// The options of the precompute engine. - fn precompute(&self) -> PrecomputeOptions { + pub(crate) fn precompute(&self) -> PrecomputeOptions { PrecomputeOptions { ingestion: self.ingestion, run_memory_limit_bytes: self.run_memory_limit_bytes, @@ -360,7 +360,7 @@ impl EngineOptions { } /// The options of the query engine. - fn query(&self) -> QueryOptions { + pub(crate) fn query(&self) -> QueryOptions { QueryOptions { run_memory_limit_bytes: self.run_memory_limit_bytes, threads: self.query_threads, diff --git a/crates/data-plane/src/installer.rs b/crates/data-plane/src/installer.rs index d8dd33dfe..2f9a6c937 100644 --- a/crates/data-plane/src/installer.rs +++ b/crates/data-plane/src/installer.rs @@ -1,33 +1,32 @@ //! [`PlanInstaller`]: installs a plan into the query engine, the ingest -//! engine and the dispatcher, all or nothing. +//! engine and the dispatcher; queries see it only after every engine +//! accepted it. -use std::sync::{Arc, Mutex}; +use std::sync::Arc; -use common::{IngestEngine, InstallError, InstallablePlan, InstalledPlan, PlanId, QueryEngine}; +use common::{InstallError, InstallablePlan, InstalledPlan, PlanId}; +use precompute::engine::PrecomputeEngine; +use query::ExecutorQueryEngine; use crate::dispatcher::QueryDispatcher; /// Installs plans. v1 installs one: the plan file at startup. -pub struct PlanInstaller { - ingest: Arc, - query: Arc, +pub(crate) struct PlanInstaller { + precompute: Arc, + query: Arc, dispatcher: Arc, - /// Whether an install was tried: v1 takes only the first, whether it - /// installs or fails. - tried: Mutex, } impl PlanInstaller { - pub fn new( - ingest: Arc, - query: Arc, + pub(crate) fn new( + precompute: Arc, + query: Arc, dispatcher: Arc, ) -> Self { Self { - ingest, + precompute, query, dispatcher, - tried: Mutex::new(false), } } @@ -37,17 +36,10 @@ impl PlanInstaller { /// gets it last: on any failure the current plan stays the one queries /// are answered from (none, in v1). The query engine goes first because /// its install only compiles and starts idle workers; the ingest - /// engine's starts ingestion. v1 installs once: only the first call is - /// taken, as the engines install once too (after the ingest engine - /// refused a plan, the query engine keeps it, unused). A failed install - /// at startup ends the data plane. - pub fn install(&self, plan: InstallablePlan) -> Result { - let mut tried = self.tried.lock().unwrap_or_else(|e| e.into_inner()); - if std::mem::replace(&mut *tried, true) { - return Err(InstallError::new( - "the data plane installs one plan, and an install was tried already", - )); - } + /// engine's starts ingestion. v1 installs once: the engines refuse a + /// second plan (after the ingest engine refused a plan, the query engine + /// keeps it, unused). A failed install at startup ends the data plane. + pub(crate) fn install(&self, plan: InstallablePlan) -> Result { plan.validate() .map_err(|error| InstallError::new(format!("{:#}", anyhow::Error::from(error))))?; // #935's plan id counts installs; v1's one install is plan 1. @@ -56,7 +48,7 @@ impl PlanInstaller { plan, }; self.query.install(plan.clone())?; - self.ingest.install(plan.clone())?; + self.precompute.install(plan.clone())?; self.dispatcher.install(&plan); Ok(plan.id) } @@ -64,105 +56,50 @@ impl PlanInstaller { #[cfg(test)] mod tests { - use async_trait::async_trait; - use common::{ - AnswerSource, EngineQueryResult, IngestError, QueryEngineError, QueryRequest, RawDataBatch, - }; - use query::ExecutorQueryEngine; + use common::AnswerSource; use storage::store::PublishedStore; use super::*; use crate::test_support; - /// Records the plans installed into it; refuses every plan when - /// `refuses`. - #[derive(Default)] - struct Fake { - refuses: bool, - installed: Mutex>, - } - - impl Fake { - fn refusing() -> Arc { - Arc::new(Self { - refuses: true, - ..Self::default() - }) - } - - fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { - if self.refuses { - return Err(InstallError::new("refused")); - } - self.installed.lock().unwrap().push(plan.id); - Ok(()) - } - - fn installed(&self) -> Vec { - self.installed.lock().unwrap().clone() - } - } - - #[async_trait] - impl IngestEngine for Fake { - fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { - Fake::install(self, plan) - } - async fn ingest(&self, _batch: RawDataBatch) -> Result<(), IngestError> { - Ok(()) - } - fn shutdown(&self) {} - } - - #[async_trait] - impl QueryEngine for Fake { - fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { - Fake::install(self, plan) - } - async fn execute_batch( - &self, - queries: &[(AnswerSource, QueryRequest)], - ) -> Vec> { - vec![Ok(EngineQueryResult::NotReady); queries.len()] - } - } + const QUERY: &str = "sum_over_time(data[10s])"; - fn dispatcher() -> Arc { - let options = query::QueryOptions { - run_memory_limit_bytes: 1 << 20, - threads: 1, - share_one_evaluation_results: true, - query_time_results_retention_ms: 0, - query_time_results_max_bytes: 0, - result_cache: false, - result_cache_max_bytes: 0, - view_retention_margin_ms: 0, - refuse_unexecutable: false, - }; + /// The two engines, over one published store, and the dispatcher. + fn parts() -> ( + Arc, + Arc, + Arc, + ) { + let options = test_support::options(); let published = Arc::new(PublishedStore::new(Arc::default())); - let engine = Arc::new(ExecutorQueryEngine::new(options, published)); - Arc::new(QueryDispatcher::new(engine)) + let precompute = Arc::new(PrecomputeEngine::new( + options.precompute(), + None, + published.clone(), + )); + let query = Arc::new(ExecutorQueryEngine::new(options.query(), published)); + let dispatcher = Arc::new(QueryDispatcher::new(query.clone())); + (precompute, query, dispatcher) } - const QUERY: &str = "sum_over_time(data[10s])"; + /// The plan the engine holds, if any. + fn plan_of(query: &ExecutorQueryEngine) -> Option { + query.installed().map(|installed| installed.plan()) + } /// A plan installs into both engines and the dispatcher as plan 1; a /// second plan is refused and the first stays. #[test] fn installs_one_plan_into_both_engines_and_the_dispatcher() { - let (ingest, query, dispatcher) = ( - Arc::new(Fake::default()), - Arc::new(Fake::default()), - dispatcher(), - ); - let installer = PlanInstaller::new(ingest.clone(), query.clone(), dispatcher.clone()); + let (precompute, query, dispatcher) = parts(); + let installer = PlanInstaller::new(precompute.clone(), query.clone(), dispatcher.clone()); let plan = test_support::plan(QUERY, false); let root = plan.dag.roots[0]; assert_eq!(installer.install(plan), Ok(PlanId(1))); let other = test_support::plan("count_over_time(data[10s])", false); assert!(installer.install(other).is_err()); - assert_eq!(ingest.installed(), [PlanId(1)]); - assert_eq!(query.installed(), [PlanId(1)]); + assert!(precompute.installed().is_some()); + assert_eq!(plan_of(&query), Some(PlanId(1))); assert_eq!( dispatcher.resolve(QUERY), Some(AnswerSource::Planned { @@ -173,38 +110,38 @@ mod tests { assert_eq!(dispatcher.resolve("count_over_time(data[10s])"), None); } - /// An invalid plan, or one either engine refuses, reaches no later - /// step, the dispatcher matches no query, and no later plan installs. + /// An invalid plan, or one either engine refuses (each refuses once it + /// holds a plan), reaches no later step, and the dispatcher matches no + /// query. #[test] fn a_failed_install_leaves_the_plan_as_it_was() { + let held = || InstalledPlan { + id: PlanId(7), + plan: test_support::plan("count_over_time(data[10s])", false), + }; let mut invalid = test_support::plan(QUERY, false); invalid.query_texts.push("up".into()); - // Each case: the ingest and query engines, the plan, and the plans - // the query engine got before the failure. - type Case = (Arc, Arc, InstallablePlan, &'static [PlanId]); - let cases: [Case; 3] = [ - (Arc::default(), Arc::default(), invalid, &[]), - ( - Arc::default(), - Fake::refusing(), - test_support::plan(QUERY, false), - &[], - ), - ( - Fake::refusing(), - Arc::default(), - test_support::plan(QUERY, false), - &[PlanId(1)], - ), - ]; - for (ingest, query, plan, query_got) in cases { - let dispatcher = dispatcher(); - let installer = PlanInstaller::new(ingest.clone(), query.clone(), dispatcher.clone()); - assert!(installer.install(plan).is_err()); - assert!(installer.install(test_support::plan(QUERY, false)).is_err()); - assert!(ingest.installed().is_empty()); - assert_eq!(query.installed(), query_got); - assert!(dispatcher.resolve(QUERY).is_none()); - } + // An invalid plan: neither engine gets it. + let (precompute, query, dispatcher) = parts(); + let installer = PlanInstaller::new(precompute.clone(), query.clone(), dispatcher.clone()); + assert!(installer.install(invalid).is_err()); + assert!(precompute.installed().is_none()); + assert_eq!(plan_of(&query), None); + assert!(dispatcher.resolve(QUERY).is_none()); + // The query engine refuses: the ingest engine does not get it. + let (precompute, query, dispatcher) = parts(); + query.install(held()).unwrap(); + let installer = PlanInstaller::new(precompute.clone(), query.clone(), dispatcher.clone()); + assert!(installer.install(test_support::plan(QUERY, false)).is_err()); + assert!(precompute.installed().is_none()); + assert_eq!(plan_of(&query), Some(PlanId(7))); + assert!(dispatcher.resolve(QUERY).is_none()); + // The ingest engine refuses: the query engine keeps the plan, unused. + let (precompute, query, dispatcher) = parts(); + precompute.install(held()).unwrap(); + let installer = PlanInstaller::new(precompute.clone(), query.clone(), dispatcher.clone()); + assert!(installer.install(test_support::plan(QUERY, false)).is_err()); + assert_eq!(plan_of(&query), Some(PlanId(1))); + assert!(dispatcher.resolve(QUERY).is_none()); } } diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index 097f64929..ad9e48398 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -16,7 +16,7 @@ //! then answers every query the plan does not and every other API path //! (labels, series, metadata), proxied with `x-asap-execution: forwarded`. -pub mod dispatcher; +mod dispatcher; pub mod engine; mod installer; mod metrics_endpoint; diff --git a/crates/precompute/Cargo.toml b/crates/precompute/Cargo.toml index c12fe6c8e..38da74d04 100644 --- a/crates/precompute/Cargo.toml +++ b/crates/precompute/Cargo.toml @@ -11,8 +11,6 @@ common.workspace = true internal_metrics.workspace = true storage.workspace = true anyhow.workspace = true -# `common::IngestEngine`'s async methods. -async-trait.workspace = true # `PrecomputeMode` is a command-line value of the data plane # (`--precompute-mode`). clap.workspace = true diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index b639a9b6c..a53964327 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -32,8 +32,7 @@ use std::time::Instant; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::runtime::Limits; use asap_executor::values::Batch; -use async_trait::async_trait; -use common::{InstallError, InstallablePlan, InstalledPlan, RawDataBatch}; +use common::{InstallError, InstallablePlan, InstalledPlan}; use internal_metrics::{Metrics, PushMetrics, Timer}; use storage::memory_budget::serve_view_cache; use storage::persist::ViewFiles; @@ -315,11 +314,10 @@ impl PrecomputeEngine { self.published.clone(), ) } -} -#[async_trait] -impl common::IngestEngine for PrecomputeEngine { - fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { + /// Compiles `plan`'s ingestion and starts its threads. v1 installs one + /// plan: a second is refused and the first keeps running. + pub fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { let _installing = self.installing.lock().unwrap_or_else(|e| e.into_inner()); if self.installed().is_some() { return Err(InstallError::new( @@ -332,39 +330,8 @@ impl common::IngestEngine for PrecomputeEngine { let _ = self.installed.set(installed); Ok(()) } - - /// Interns each series and queues its samples, waiting while the queues - /// are full; discards the batch before the install. - async fn ingest(&self, batch: RawDataBatch) -> Result<(), common::IngestError> { - let Some(installed) = self.installed() else { - return Ok(()); - }; - let samples = RawSample::from_batch(&batch); - // `try_ingest` takes the samples, so each attempt gets a copy: this - // path is for adapters (no HTTP route calls it); Remote Write calls - // `try_ingest` directly and answers 503 instead of waiting. - loop { - match installed.try_ingest(samples.clone()) { - Ok(()) => return Ok(()), - Err(IngestError::Busy) => tokio::time::sleep(BUSY_RETRY).await, - Err(error @ IngestError::Stopped) => { - return Err(common::IngestError::new(error.to_string())) - } - } - } - } - - fn shutdown(&self) { - if let Some(installed) = self.installed() { - installed.stop(); - } - } } -/// How long [`common::IngestEngine::ingest`] waits before offering a batch -/// the queues refused again. -const BUSY_RETRY: std::time::Duration = std::time::Duration::from_millis(10); - /// The threads running the installed plan: the `ingest-N` shards, the /// `ingest` coordinator, the precompute pool and committer, and (with /// persisted views) the `persist-N` threads and the `view-cache` monitor. @@ -2222,36 +2189,36 @@ mod tests { PrecomputeEngine::new(options, None, Arc::new(PublishedStore::new(Arc::default()))) } - fn batch(seconds: i64) -> RawDataBatch { - let labels = [("__name__", "data"), ("job", "a")] - .map(|(name, value)| (name.to_string(), value.to_string())) - .into(); - let points = (1..=seconds).map(|s| (s * 1000, 1.0)).collect(); - RawDataBatch::TimeSeries { - series: vec![(labels, points)], - } + fn samples(seconds: i64) -> Vec { + let series = storage::series_ids::intern_pairs(&[("__name__", "data"), ("job", "a")]); + (1..=seconds) + .map(|s| RawSample { + labels: series, + timestamp_ms: s * 1000, + value: 1.0, + }) + .collect() } - /// Through `IngestEngine`: a batch before the install is discarded; the - /// plan installs once; batches after it are ingested; `shutdown` stops + /// The plan installs once; samples after it are ingested; `stop` stops /// the engine. #[tokio::test] async fn the_ingest_engine_installs_once_and_ingests_after_it() { - use common::{IngestEngine as _, PlanId}; + use common::PlanId; let engine = engine(); - assert_eq!(engine.ingest(batch(5)).await, Ok(())); + assert!(engine.installed().is_none()); let installed = |id| InstalledPlan { id: PlanId(id), plan: plan("sum_over_time(data[10s])"), }; assert_eq!(engine.install(installed(1)), Ok(())); assert!(engine.install(installed(2)).is_err()); - assert_eq!(engine.ingest(batch(20)).await, Ok(())); let running = engine.installed().unwrap(); + assert_eq!(running.try_ingest(samples(20)), Ok(())); running.advance_watermark(20_000).await.unwrap(); assert_eq!(running.stats().samples_accepted, 20); assert!(running.stats().windows_refreshed > 0); - engine.shutdown(); + running.stop(); let stopped = Instant::now(); while running.is_running() { assert!(stopped.elapsed() < std::time::Duration::from_secs(10)); diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index a0e00946e..cc2d76e14 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -112,7 +112,7 @@ pub struct IngestionStats { /// Why a plan cannot be ingested. #[derive(Debug, thiserror::Error)] -pub enum IngestionError { +pub(crate) enum IngestionError { #[error("{0}")] Unsupported(String), #[error("refresh group of views {views:?}: {error}")] @@ -129,7 +129,7 @@ const MAX_PANE_WIDTH_MS: i64 = 60_000; /// A refresh group's window `(end_ms - W, end_ms]` that the watermark has /// passed, to refresh; `group` indexes the plan's ingestion refresh groups. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ClosedWindow { +pub(crate) struct ClosedWindow { pub group: usize, pub end_ms: i64, } @@ -174,7 +174,7 @@ impl RefreshGroup { } } -pub struct Ingestion { +pub(crate) struct Ingestion { groups: Vec, /// Every metric a `Scan` reads; samples of others are not stored. scanned_metrics: Arc>, @@ -702,7 +702,7 @@ impl Ingestion { /// What an ingest shard routes samples by: a snapshot of the ingestion's /// state, published after every change. #[derive(Debug, Clone, Default)] -pub struct Routing { +pub(crate) struct Routing { scanned_metrics: Arc>, max_future_ms: i64, /// Each scanned metric's eviction cutoff (`None`: all are kept). @@ -828,7 +828,7 @@ pub enum Refreshed { /// A window's ingestion run, computed and not yet stored. #[derive(Debug)] -pub enum Computed { +pub(crate) enum Computed { /// The rows of each view of the group that did not store the window /// yet, by its index in the group. Ran(Vec<(usize, Vec)>), @@ -919,7 +919,7 @@ fn carries_state_across_windows(operator: &Operator) -> bool { } /// The ingestion runs of the plan's refresh groups. -pub struct Precompute { +pub(crate) struct Precompute { runs: Vec, tasks: RefreshTaskGraph, limits: Limits, diff --git a/crates/query/Cargo.toml b/crates/query/Cargo.toml index b2c1cd13b..90dc7fdb5 100644 --- a/crates/query/Cargo.toml +++ b/crates/query/Cargo.toml @@ -11,8 +11,6 @@ common.workspace = true internal_metrics.workspace = true storage.workspace = true anyhow.workspace = true -# `common::QueryEngine`'s async methods. -async-trait.workspace = true futures = "0.3" serde_json.workspace = true thiserror.workspace = true diff --git a/crates/query/src/engine.rs b/crates/query/src/engine.rs index 6ab855d30..c3fe2374e 100644 --- a/crates/query/src/engine.rs +++ b/crates/query/src/engine.rs @@ -1,12 +1,11 @@ -//! [`ExecutorQueryEngine`]: the query engine over the Planner's executor, -//! behind [`common::QueryEngine`]. It is created before any plan; its -//! install compiles the plan's queries and starts the query workers. +//! [`ExecutorQueryEngine`]: the query engine over the Planner's executor. +//! It is created before any plan; its install compiles the plan's queries +//! and starts the query workers. use std::collections::BTreeMap; use std::sync::{Arc, Mutex, OnceLock}; use asap_executor::runtime::Limits; -use async_trait::async_trait; use common::{ AnswerSource, EngineQueryResult, InstallError, InstalledPlan, InstantVector, InstantVectorElement, LabelSet, QueryEngineError, QueryEval, QueryRequest, QueryResult, @@ -117,8 +116,10 @@ impl ExecutorQueryEngine { )?) } - /// One request's answer, as the boundary reports it. - async fn execute_one( + /// One query's answer, resolved by the dispatcher to `source`: not + /// ready before the install, for another plan, or while its data is + /// not stored yet. + pub async fn execute( &self, source: &AnswerSource, request: &QueryRequest, @@ -156,11 +157,10 @@ impl ExecutorQueryEngine { Err(error) => Err(QueryEngineError::new(error.to_string())), } } -} -#[async_trait] -impl common::QueryEngine for ExecutorQueryEngine { - fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { + /// Compiles `plan`'s queries and starts the workers. v1 installs one + /// plan: a second is refused and the first stays. + pub fn install(&self, plan: InstalledPlan) -> Result<(), InstallError> { let _installing = self.installing.lock().unwrap_or_else(|e| e.into_inner()); if let Some(installed) = self.installed() { return Err(InstallError::new(format!( @@ -174,17 +174,6 @@ impl common::QueryEngine for ExecutorQueryEngine { let _ = self.installed.set(workers); Ok(()) } - - async fn execute_batch( - &self, - queries: &[(AnswerSource, QueryRequest)], - ) -> Vec> { - let mut results = Vec::with_capacity(queries.len()); - for (source, request) in queries { - results.push(self.execute_one(source, request).await); - } - results - } } /// `answer` as an instant vector at `time_ms`. @@ -225,7 +214,7 @@ fn range_vector(steps: &[(i64, Answer)]) -> RangeVector { #[cfg(test)] mod tests { - use common::{PlanId, QueryEngine as _, QueryLanguage}; + use common::{PlanId, QueryLanguage}; use super::*; @@ -249,7 +238,7 @@ mod tests { const QUERY: &str = "sum_over_time(data[10s])"; - /// Through `QueryEngine`: nothing is ready before the install, the plan + /// Nothing is ready before the install, the plan /// installs once, a query resolved against another plan is not ready, /// and neither is one whose views are not stored yet. Its measurements /// are found by its trimmed text. @@ -299,14 +288,12 @@ mod tests { end_ms: 30_000, step_ms: 10_000, }); - let results = engine - .execute_batch(&[ - (source(2), instant.clone()), - (source(1), instant), - (source(1), range), - ]) - .await; - assert_eq!(results, vec![Ok(EngineQueryResult::NotReady); 3]); + for (plan, request) in [(2, &instant), (1, &instant), (1, &range)] { + assert_eq!( + engine.execute(&source(plan), request).await, + Ok(EngineQueryResult::NotReady) + ); + } } /// Answers become an instant vector, and steps a matrix of each diff --git a/crates/query/src/lib.rs b/crates/query/src/lib.rs index 33c5c0788..66716fa60 100644 --- a/crates/query/src/lib.rs +++ b/crates/query/src/lib.rs @@ -19,8 +19,7 @@ //! forwards it to Prometheus (or refuses it). //! //! [`ExecutorQueryEngine`] runs the compiled queries ([`CompiledQueries`]) -//! on the `query-N` workers ([`workers`]) and implements -//! [`common::QueryEngine`]. +//! on the `query-N` workers ([`workers`]). use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; @@ -203,7 +202,7 @@ impl CompiledQueries { } /// The planned queries the engine cannot run, with why. - pub fn unexecutable(&self) -> &[(String, String)] { + pub(crate) fn unexecutable(&self) -> &[(String, String)] { &self.unexecutable } diff --git a/crates/query/src/result_cache.rs b/crates/query/src/result_cache.rs index 943d285b8..b4b431f60 100644 --- a/crates/query/src/result_cache.rs +++ b/crates/query/src/result_cache.rs @@ -79,7 +79,7 @@ impl ResultCache { /// longest retention (every view and raw-data `Scan` keeps its rows /// that far back from the newest evaluation time) plus `margin_ms`; /// `None` when a `Scan` reads its rows unbounded. - pub fn horizon_ms(dag: &PhysicalASAPDAG, margin_ms: u64) -> Option { + pub(crate) fn horizon_ms(dag: &PhysicalASAPDAG, margin_ms: u64) -> Option { let unbounded_scan = dag.nodes.iter().any(|node| { node.retention_ms.is_none() && matches!(node.payload, Operator::NonASAP(NonASAPOp::Scan { .. }))