Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 1 addition & 4 deletions crates/adapters/query/prometheus-http/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::collections::BTreeMap;
use serde::{Serialize, Serializer};
use serde_json::{json, Value};

use common::{Answer, LabelSet, ResultSample, MAX_TIME_MS};
use common::{Answer, LabelSet, ResultSample, MAX_RANGE_STEPS, MAX_TIME_MS};

pub mod fallback;

Expand Down Expand Up @@ -53,9 +53,6 @@ impl InstantQuery {
}
}

/// The most steps one range query may have, as Prometheus allows.
const MAX_RANGE_STEPS: i64 = 11_000;

/// Parameters of a range query: evaluated at `start_ms` and every
/// `step_ms` after, up to and including `end_ms`.
#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down
3 changes: 0 additions & 3 deletions crates/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,3 @@ asap-types.workspace = true
# object safe; native `async fn` in traits is not.
async-trait.workspace = true
thiserror.workspace = true

[dev-dependencies]
tokio.workspace = true
7 changes: 7 additions & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ pub use query_result::{
/// represent. Leaves room for any window offset.
pub const MAX_TIME_MS: i64 = i64::MAX / 4;

/// The most steps after its start one range query may have, as Prometheus
/// allows (`(end - start) / step`). The plan never evaluates a longer
/// range: the Prometheus routes refuse it with 400, and
/// `ExecutorQueryEngine::execute` with an error (the ClickHouse and
/// Elasticsearch routes send it instant queries only today).
pub const MAX_RANGE_STEPS: i64 = 11_000;

/// One series' labels, name to value, `__name__` included, as query results
/// carry them.
pub type LabelSet = std::collections::BTreeMap<String, String>;
Expand Down
38 changes: 0 additions & 38 deletions crates/common/tests/trait_shapes.rs

This file was deleted.

5 changes: 5 additions & 0 deletions crates/control-plane/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ name = "control_plane"
version.workspace = true
edition.workspace = true

[features]
# `test_support`: a plan for the other crates' unit tests; enabled by their
# dev-dependency on this crate only.
test-support = []

[dependencies]
asap-planner.workspace = true
futures = "0.3"
Expand Down
3 changes: 3 additions & 0 deletions crates/control-plane/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

use std::path::Path;

#[cfg(feature = "test-support")]
pub mod test_support;

use asap_planner::{
plan_installable, CostInputs, DeploymentCapabilities, FrontendInput, InstallablePlan,
InstallablePlanError, PlanningModels, PlanningWorkload, SelectedPlanReport, UserInput,
Expand Down
29 changes: 29 additions & 0 deletions crates/control-plane/src/test_support.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//! A plan for the other crates' unit tests (the `test-support` feature,
//! which they enable as a dev-dependency only).

use asap_planner::InstallablePlan;

use crate::DeploymentInputs;

/// The plan of `query`, evaluated every 10 s over the gauge `data` (one
/// series, one sample a second), for a deployment that keeps raw data or
/// not.
pub fn one_query_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"}}}},
}))
.expect("a valid workload");
let mut inputs = DeploymentInputs::default();
inputs.deployment_capabilities.raw_data_retained = raw_data_retained;
crate::plan_workload(&workload, &inputs)
.expect("the workload plans")
.0
}
2 changes: 1 addition & 1 deletion crates/data-plane/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ form_urlencoded = "1"
asap-planner.workspace = true
asap-executor.workspace = true
futures = "0.3"
control_plane.workspace = true
control_plane = { workspace = true, features = ["test-support"] }
asap_sketchlib.workspace = true
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
Expand Down
93 changes: 42 additions & 51 deletions crates/data-plane/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,8 @@ use common::{
};
use query::{ExecutorQueryEngine, Unanswered};

/// The dispatcher's verdict on one query.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum QueryOutcome<T> {
/// The plan answered.
Ready(T),
NotAnswerable(NotAnswerableReason),
}

/// Why the plan did not answer a query; the query falls back.
/// Why the plan did not answer a query (the dispatcher's `Err`); the query
/// falls back.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum NotAnswerableReason {
/// No plan is installed, or its query texts hold no such query.
Expand Down Expand Up @@ -134,14 +127,18 @@ impl QueryDispatcher {
}

/// `query` at `time_ms`.
pub(crate) async fn instant(&self, query: &str, time_ms: i64) -> QueryOutcome<Answer> {
pub(crate) async fn instant(
&self,
query: &str,
time_ms: i64,
) -> Result<Answer, NotAnswerableReason> {
let (Some(source), Some(engine)) = (self.resolve(query), self.engine.installed()) else {
return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched);
return Err(NotAnswerableReason::Unmatched);
};
match engine.instant(&source, query, time_ms).await {
Ok(result) => QueryOutcome::Ready(result),
Err(unanswered) => QueryOutcome::NotAnswerable(NotAnswerableReason::new(unanswered)),
}
engine
.instant(&source, query, time_ms)
.await
.map_err(NotAnswerableReason::new)
}

/// `query` at each of `times_ms`: every step's answer, or why some step
Expand All @@ -150,36 +147,37 @@ impl QueryDispatcher {
&self,
query: &str,
times_ms: impl Iterator<Item = i64>,
) -> QueryOutcome<Vec<(i64, Answer)>> {
) -> Result<Vec<(i64, Answer)>, NotAnswerableReason> {
let (Some(source), Some(engine)) = (self.resolve(query), self.engine.installed()) else {
return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched);
return Err(NotAnswerableReason::Unmatched);
};
match engine.range(&source, query, times_ms).await {
Ok(result) => QueryOutcome::Ready(result),
Err(unanswered) => QueryOutcome::NotAnswerable(NotAnswerableReason::new(unanswered)),
}
engine
.range(&source, query, times_ms)
.await
.map_err(NotAnswerableReason::new)
}

/// `request` through [`ExecutorQueryEngine::execute`]. Only a PromQL query can
/// be the plan's: the control plane plans PromQL workloads only, and
/// the data plane stores time series only, which SQL and Query DSL
/// plans do not read. A query in another language is unmatched, even
/// when its text equals a planned query's.
pub async fn dispatch(&self, request: &QueryRequest) -> QueryOutcome<QueryResult> {
pub async fn dispatch(
&self,
request: &QueryRequest,
) -> Result<QueryResult, NotAnswerableReason> {
if request.language != QueryLanguage::PromQL {
return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched);
return Err(NotAnswerableReason::Unmatched);
}
let Some(source) = self.resolve(&request.query) else {
return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched);
return Err(NotAnswerableReason::Unmatched);
};
match self.engine.execute(&source, request).await {
Ok(EngineQueryResult::Ready { result }) => QueryOutcome::Ready(result),
Ok(EngineQueryResult::NotReady) => {
QueryOutcome::NotAnswerable(NotAnswerableReason::NotReady(
"the stored data does not cover the query, or the plan changed".into(),
))
}
Err(error) => QueryOutcome::NotAnswerable(NotAnswerableReason::EngineError(error)),
Ok(EngineQueryResult::Ready { result }) => Ok(result),
Ok(EngineQueryResult::NotReady) => Err(NotAnswerableReason::NotReady(
"the stored data does not cover the query, or the plan changed".into(),
)),
Err(error) => Err(NotAnswerableReason::EngineError(error)),
}
}
}
Expand All @@ -191,6 +189,7 @@ mod tests {
use super::*;
use crate::engine::EngineHandle;
use crate::test_support;
use control_plane::test_support::one_query_plan;

const QUERY: &str = "sum_over_time(data[10s])";

Expand All @@ -209,19 +208,15 @@ mod tests {
/// 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 engine = engine(&one_query_plan(QUERY, false)).await;
let dispatcher = engine.dispatcher();
let QueryOutcome::Ready(answer) = dispatcher.instant(&format!(" {QUERY} "), 30_000).await
else {
let Ok(answer) = dispatcher.instant(&format!(" {QUERY} "), 30_000).await else {
panic!("not answered");
};
let values: Vec<f64> = 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!(unmatched, Err(NotAnswerableReason::Unmatched));
assert_eq!(
Fallback::new(NotAnswerableReason::Unmatched, "up", false),
Fallback::Forward { reason: None }
Expand All @@ -232,10 +227,10 @@ mod tests {
/// 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 engine = engine(&one_query_plan(QUERY, false)).await;
let dispatcher = engine.dispatcher();
let outcome = dispatcher.instant(QUERY, 60_000).await;
let QueryOutcome::NotAnswerable(reason @ NotAnswerableReason::NotReady(_)) = outcome else {
let Err(reason @ NotAnswerableReason::NotReady(_)) = outcome else {
panic!("expected not ready, got {outcome:?}");
};
assert_eq!(
Expand All @@ -245,10 +240,7 @@ mod tests {
}
);
let range = dispatcher.range(QUERY, [30_000, 40_000].into_iter()).await;
assert!(matches!(
range,
QueryOutcome::NotAnswerable(NotAnswerableReason::NotReady(_))
));
assert!(matches!(range, Err(NotAnswerableReason::NotReady(_))));
}

/// A planned query whose run does not compile is an engine error:
Expand All @@ -257,7 +249,7 @@ mod tests {
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 mut plan = one_query_plan(QUERY, true);
let scan = plan
.dag
.nodes
Expand All @@ -270,8 +262,7 @@ mod tests {
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 {
let Err(reason @ NotAnswerableReason::EngineError(_)) = outcome else {
panic!("expected an engine error, got {outcome:?}");
};
let message = reason.clone().into_message(QUERY);
Expand All @@ -291,14 +282,14 @@ mod tests {
/// unmatched.
#[tokio::test]
async fn dispatches_a_query_request_by_language() {
let engine = engine(&test_support::plan(QUERY, false)).await;
let engine = engine(&one_query_plan(QUERY, false)).await;
let dispatcher = engine.dispatcher();
let request = |language, time_ms| QueryRequest {
language,
query: QUERY.into(),
eval: common::QueryEval::Instant { time_ms },
};
let QueryOutcome::Ready(QueryResult::Vector(vector)) = dispatcher
let Ok(QueryResult::Vector(vector)) = dispatcher
.dispatch(&request(QueryLanguage::PromQL, 30_000))
.await
else {
Expand All @@ -310,12 +301,12 @@ mod tests {
dispatcher
.dispatch(&request(QueryLanguage::PromQL, 60_000))
.await,
QueryOutcome::NotAnswerable(NotAnswerableReason::NotReady(_))
Err(NotAnswerableReason::NotReady(_))
));
let sql = QueryLanguage::SQL(common::SqlDialect::ClickhouseSQL);
assert_eq!(
dispatcher.dispatch(&request(sql, 30_000)).await,
QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched)
Err(NotAnswerableReason::Unmatched)
);
}

Expand Down
Loading