diff --git a/Cargo.lock b/Cargo.lock index 17fdac859..4149c4849 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2924,6 +2924,7 @@ dependencies = [ "anyhow", "asap-executor", "common", + "control_plane", "futures", "internal_metrics", "serde_json", 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..034249bf0 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 @@ -31,10 +29,13 @@ axum.workspace = true reqwest.workspace = true prost = "0.13" snap = "1.1" -futures = "0.3" form_urlencoded = "1" [dev-dependencies] +# Plans and IR the tests and the micro benchmarks build. +asap-planner.workspace = true +asap-executor.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..36842961f --- /dev/null +++ b/crates/data-plane/src/dispatcher.rs @@ -0,0 +1,272 @@ +//! [`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 +//! [`ExecutorQueryEngine::execute`]'s [`common::QueryResult`], which would +//! copy every series' labels per query. + +use std::sync::{Arc, OnceLock}; + +use common::{AnswerSource, InstalledPlan, PhysicalASAPNodeId, PlanId, QueryEngineError}; +use query::result_cache::Answer; +use query::{ExecutorQueryEngine, Unanswered}; + +/// The dispatcher's verdict on one query. +#[derive(Debug, Clone, PartialEq)] +pub(crate) 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(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 + /// it was resolved: why. + NotReady(String), + /// The engine failed to run the query. + EngineError(QueryEngineError), +} + +impl NotAnswerableReason { + /// 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(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, + Self::EngineError(error) => error.message, + } + } +} + +/// How a query the plan does not answer is answered. +#[derive(Debug, Clone, PartialEq, Eq)] +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 }, + /// 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(crate) fn new(reason: NotAnswerableReason, query: &str, no_forward: bool) -> Self { + match reason { + _ if no_forward => Self::Refuse { + reason: reason.into_message(query), + }, + NotAnswerableReason::Unmatched => Self::Forward { reason: None }, + NotAnswerableReason::NotReady(_) | NotAnswerableReason::EngineError(_) => { + Self::Forward { + reason: Some(reason.into_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(crate) struct QueryDispatcher { + engine: Arc, + plan: OnceLock, +} + +impl QueryDispatcher { + pub(crate) 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(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); + }; + 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(crate) 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.clone(), QUERY, false), + Fallback::Forward { + reason: Some(reason.into_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.clone().into_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..68daa08f4 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -1,26 +1,26 @@ -//! 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 common::{InstallablePlan, PhysicalASAPNodeId}; +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 query::workers::QueryWorkers; -use query::{QueryEngine, Snapshot, Unanswered}; +use precompute::ingestion::{IngestionOptions, IngestionStats}; +use query::workers::InstalledQueries; +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 +187,9 @@ impl Default for EngineOptions { /// The HTTP side of the engine. #[derive(Clone)] pub struct EngineHandle { - precompute: PrecomputeEngine, - query: QueryWorkers, + precompute: InstalledPrecompute, + query: InstalledQueries, + dispatcher: Arc, /// The views' cold tier, when they are persisted. view_tier: Option>, } @@ -198,7 +199,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 +223,54 @@ 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(crate) 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 { + /// For tests: the newest published store, what a query starting now + /// reads. + #[doc(hidden)] + 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() + /// For benchmarks: each planned query's measurements, by query text. + #[doc(hidden)] + 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 +282,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 +292,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 +321,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() @@ -359,9 +341,10 @@ 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, max_queued_samples: self.max_queued_samples, max_precompute_backlog: self.max_precompute_backlog, ingest_threads: self.ingest_threads, @@ -375,62 +358,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. + pub(crate) 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..2f9a6c937 --- /dev/null +++ b/crates/data-plane/src/installer.rs @@ -0,0 +1,147 @@ +//! [`PlanInstaller`]: installs a plan into the query engine, the ingest +//! engine and the dispatcher; queries see it only after every engine +//! accepted it. + +use std::sync::Arc; + +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(crate) struct PlanInstaller { + precompute: Arc, + query: Arc, + dispatcher: Arc, +} + +impl PlanInstaller { + pub(crate) fn new( + precompute: Arc, + query: Arc, + dispatcher: Arc, + ) -> Self { + Self { + precompute, + query, + dispatcher, + } + } + + /// 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 (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: 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. + let plan = InstalledPlan { + id: PlanId(1), + plan, + }; + self.query.install(plan.clone())?; + self.precompute.install(plan.clone())?; + self.dispatcher.install(&plan); + Ok(plan.id) + } +} + +#[cfg(test)] +mod tests { + use common::AnswerSource; + use storage::store::PublishedStore; + + use super::*; + use crate::test_support; + + const QUERY: &str = "sum_over_time(data[10s])"; + + /// 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 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) + } + + /// 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 (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!(precompute.installed().is_some()); + assert_eq!(plan_of(&query), Some(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 (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()); + // 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 4fa052255..ad9e48398 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -2,25 +2,30 @@ //! 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 //! then answers every query the plan does not and every other API path //! (labels, series, metadata), proxied with `x-asap-execution: forwarded`. +mod dispatcher; pub mod engine; +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 +35,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 +348,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 +398,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 +413,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 +460,13 @@ 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::new(Unanswered::Execution(error)); 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..e9989d4b7 --- /dev/null +++ b/crates/data-plane/src/test_support.rs @@ -0,0 +1,52 @@ +//! Plans and options for the unit tests. + +use common::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/src/engine.rs b/crates/precompute/src/engine.rs index 6fb252ecc..a53964327 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -26,11 +26,13 @@ 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 common::{InstallError, InstallablePlan, InstalledPlan}; use internal_metrics::{Metrics, PushMetrics, Timer}; use storage::memory_budget::serve_view_cache; use storage::persist::ViewFiles; @@ -212,6 +214,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 +245,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 +257,86 @@ 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(), + ) + } + + /// 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( + "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(()) + } +} + +/// 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 +344,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 +415,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 +2147,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 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() + } + + /// 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::PlanId; + let engine = engine(); + 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()); + 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); + running.stop(); + 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/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 ab0eff9fa..90dc7fdb5 100644 --- a/crates/query/Cargo.toml +++ b/crates/query/Cargo.toml @@ -16,3 +16,6 @@ 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..c3fe2374e --- /dev/null +++ b/crates/query/src/engine.rs @@ -0,0 +1,347 @@ +//! [`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 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::InstalledQueries; +use crate::CompiledQueries; + +/// 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. + 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<&InstalledQueries> { + 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(InstalledQueries::start( + plan.id, + compiled, + self.published.clone(), + options.threads, + )?) + } + + /// 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, + ) -> 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) if unanswered.is_not_ready() => Ok(EngineQueryResult::NotReady), + Err(error) => Err(QueryEngineError::new(error.to_string())), + } + } + + /// 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!( + "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(()) + } +} + +/// `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, 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])"; + + /// 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. + #[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()); + // 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, + step_ms: 10_000, + }); + 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 + /// 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..66716fa60 100644 --- a/crates/query/src/lib.rs +++ b/crates/query/src/lib.rs @@ -17,6 +17,9 @@ //! 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`]). use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; @@ -33,13 +36,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 +61,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 @@ -67,6 +75,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, @@ -74,9 +90,15 @@ struct Run { reads: Vec, } -pub struct QueryEngine { - /// Each query and its root, or why it cannot run. - roots: Vec<(String, Result)>, +/// The installed plan's queries, compiled. +pub struct CompiledQueries { + /// 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>, + /// 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 +112,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,21 +166,32 @@ impl QueryEngine { .map_err(|e| e.to_string()); compiled.insert(node, run); } - let roots = plan - .query_texts + let runnable_roots: HashMap> = dag + .roots .iter() + .map(|&root| (root, runnable(root, &compiled))) + .collect(); + let queries = || plan.query_texts.iter().map(|query| query.trim()); + let unexecutable = queries() .zip(&dag.roots) - .map(|(query, &root)| { - let runnable = runnable(root, &compiled).map(|()| root); - (query.trim().to_string(), runnable) + .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.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, shared, results, @@ -169,11 +202,8 @@ impl QueryEngine { } /// 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(crate) fn unexecutable(&self) -> &[(String, String)] { + &self.unexecutable } /// The query-time partition of the view store. @@ -186,23 +216,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(crate) 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 +268,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 +277,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 +351,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..b4b431f60 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. @@ -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 { .. })) diff --git a/crates/query/src/workers.rs b/crates/query/src/workers.rs index bdf2a8678..7369265b8 100644 --- a/crates/query/src/workers.rs +++ b/crates/query/src/workers.rs @@ -3,101 +3,166 @@ //! 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 `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. 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, +impl InstalledQueries { + /// 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 +170,8 @@ impl QueryWorkers { let (reply, answer) = oneshot::channel(); self.queries .send(QueryJob { - query, + root, + metrics, time_ms, range_step, reply, @@ -114,20 +180,22 @@ impl QueryWorkers { answer.await.map_err(|_| stopped())? } - /// The query worker threads: the most query runs at once. - pub fn threads(&self) -> usize { - self.threads + /// The plan the queries were compiled from. + pub fn plan(&self) -> PlanId { + self.plan } /// 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 +205,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 +226,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 +242,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), 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