diff --git a/Cargo.lock b/Cargo.lock index c7fb056fa..3e7efb8ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -876,6 +876,7 @@ dependencies = [ "asap-planner", "asap-types", "async-trait", + "serde", "thiserror 1.0.69", ] @@ -905,7 +906,9 @@ version = "0.1.0" dependencies = [ "anyhow", "asap-planner", + "asap-types", "clap", + "common", "futures", "serde", "serde_json", diff --git a/README.md b/README.md index 617cc175b..c117ee413 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,20 @@ data kept by the data plane, and no query-time result kept across evaluations. For example `{"raw_data_retained": false}` makes the Planner build every input at ingestion time. +Collector views (docs/design/collector-sketch-ingest.md): with +`--collector-capabilities caps.json` (what the collector prints with +`asap_sketches --print-capabilities`) and `--emit-collector-views cv.json`, +the control plane also writes the part of the plan the collector runs: the views it builds instead of the data plane, the plan id, which metrics the +data plane still reads raw (the collector stops forwarding the others), and +prints why each other node is not on the collector. `--plan plan.json` reads a plan written +before instead of planning `--workload`. The data +plane started with `--collector-views cv.json` does not build those views: +their states arrive from the collector on `/v1/metrics`, in metrics named +`.asap_view.`, and each window is committed when the +request carrying its states ends; later states of a committed window merge +into it within retention (`asap_collector_states_*` on `/metrics`). It +refuses a file of another plan. + `--cost-inputs costs.json` replaces the Planner's default `CostInputs` (Stage 3's cost model, resource speed and measured operation costs); an omitted field keeps its default, cost model 1 with illustrative unit costs. diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 1814d7267..513636681 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -15,4 +15,6 @@ asap-types.workspace = true # `FallbackClient` is used as `Arc`, so its async method must be # object safe; native `async fn` in traits is not. async-trait.workspace = true +# The collector-views file (`CollectorViewsFile`) is read and written as JSON. +serde.workspace = true thiserror.workspace = true diff --git a/crates/common/src/collector_views_file.rs b/crates/common/src/collector_views_file.rs new file mode 100644 index 000000000..8ccbde673 --- /dev/null +++ b/crates/common/src/collector_views_file.rs @@ -0,0 +1,30 @@ +//! The collector-views file (docs/design/collector-sketch-ingest.md, §2): +//! the part of the installed plan the collector runs, which the control +//! plane writes and both the collector and the data plane load. Here +//! because the control plane writes it and the data plane reads it. + +use std::collections::BTreeMap; + +use asap_types::plan::physical_asap_dag::PhysicalASAPDAG; +use serde::{Deserialize, Serialize}; + +use crate::PhysicalASAPNodeId; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CollectorViewsFile { + /// `INSTALLABLE_PLAN_WIRE_VERSION` of the planner that wrote `dag`. + pub planner_wire_version: u32, + /// `PhysicalASAPDAG::plan_id()` of the installed plan. + pub plan_id: String, + /// Per metric a `Scan` of the plan reads: whether the backend still + /// reads its raw samples (a `Scan` of it feeds a node off the + /// collector, or runs at query time). + pub backend_reads_raw: BTreeMap, + /// The collector views: the sub-DAG's outputs whose states the backend + /// ingests. + pub outputs: Vec, + /// The collector sub-DAG, nodes and edges as in the installed plan; + /// `roots = outputs`. + pub dag: PhysicalASAPDAG, +} diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 0eafe4f2c..2f4e0f79d 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -1,13 +1,15 @@ //! The data plane's boundary types and the `FallbackClient` trait, with the //! names and shapes of ASAPQuery's engine-boundary design -//! (docs/design/repo-layout.md). Adapters and engines meet here; this crate -//! holds no implementation. +//! (docs/design/repo-layout.md). Adapters and engines meet here, and the +//! control plane meets the data plane in the collector-views file it writes +//! (`CollectorViewsFile`); this crate holds no implementation. //! //! It names ASAPPlanner's plan types only (`InstallablePlan`, the DAG's node //! ids, `QueryLanguage`) and no executor item. //! `asap-planner`, which defines `InstallablePlan`, still brings the //! executor and the frontends in at compile time. +mod collector_views_file; mod fallback; mod plan; mod query_engine; @@ -15,6 +17,7 @@ mod query_request; mod query_result; mod view_states; +pub use collector_views_file::CollectorViewsFile; pub use fallback::{FallbackClient, FallbackError, FallbackResponse}; pub use plan::{InstallError, InstalledPlan, PlanId}; pub use query_engine::{AnswerSource, EngineQueryResult, QueryEngineError}; diff --git a/crates/control-plane/Cargo.toml b/crates/control-plane/Cargo.toml index 61ff051af..391b1e4a8 100644 --- a/crates/control-plane/Cargo.toml +++ b/crates/control-plane/Cargo.toml @@ -10,6 +10,10 @@ test-support = [] [dependencies] asap-planner.workspace = true +# The plan IR the collector view rule reads (operators, predicates, +# summary inputs), which `asap-planner` does not re-export. +asap-types.workspace = true +common.workspace = true futures = "0.3" serde.workspace = true serde_json.workspace = true diff --git a/crates/control-plane/src/collector_views.rs b/crates/control-plane/src/collector_views.rs new file mode 100644 index 000000000..da12d3aa1 --- /dev/null +++ b/crates/control-plane/src/collector_views.rs @@ -0,0 +1,734 @@ +//! Which part of the installed plan the collector runs +//! (docs/design/collector-sketch-ingest.md, §1 and §2): the collector's +//! declared capabilities ([`CollectorCapabilities`]), the bottom-up rule +//! that assigns plan nodes to it ([`collector_sub_dag`]), and the +//! collector-views file both the collector and the data plane load +//! ([`common::CollectorViewsFile`]). +//! +//! A node is assigned to the collector if and only if (a) its operator and +//! arguments are within the capabilities, (b) every input is assigned (a +//! raw `Scan` is assigned by (a) alone), (c) it runs at ingestion, and (d) +//! it is correct on one collector instance's partition of the series. The +//! assigned nodes whose output leaves the collector (the producers of cut +//! edges) are its outputs: a `Scan` output is the raw path, any other must +//! be a materialized view, or it and every assigned node above it are +//! unassigned, until each output is a `Scan` or a view. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use asap_planner::{ + DeploymentCapabilities, ExecutionTiming, InstallablePlan, InstallablePlanError, + PhysicalASAPDAG, PhysicalASAPNodeId, SupportedSummary, INSTALLABLE_PLAN_WIRE_VERSION, +}; +use asap_types::ir::operator::arguments::{Reduction, Source}; +use asap_types::ir::operator::kind::OperatorKind; +use asap_types::ir::scalar::{ColumnRef, CompareOpKind, ScalarValue}; +use asap_types::ir::schema::FieldDataType; +use asap_types::ir::{ASAPOp, NonASAPOp, Operator, ScalarExpr}; +use asap_types::plan::physical_asap_dag::PhysicalASAPDAGNode; +use asap_types::summary_type::{SketchAlgorithm, SummaryInputExpr, SummaryUpdate}; +use common::CollectorViewsFile; +use serde::Deserialize; + +/// The `capabilities_version` this control plane reads. +const CAPABILITIES_VERSION: u32 = 1; + +/// What `asap_sketches --print-capabilities` prints: what the collector can +/// run, in the planner's vocabulary, each capability stated once. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CollectorCapabilities { + pub capabilities_version: u32, + pub executor: CollectorExecutor, + /// Comparisons of a label column with a `Utf8` literal the collector + /// evaluates, for every operator that takes a predicate. + pub predicate_ops: Vec, + pub operators: Vec, + pub placement: Placement, + /// The longest time after a window's end before the collector emits it. + pub window_close_delay_ms: u64, +} + +/// `executor`: the planner's `DeploymentCapabilities` with its serde, +/// except that each `supported_summaries` entry is a [`CollectorSummary`]. +#[derive(Debug, Clone, PartialEq)] +pub struct CollectorExecutor { + pub supported_summaries: Vec, + /// Every other field, with the planner's serde (unknown fields + /// refused); its own `supported_summaries` is `None`. The rule reads + /// none of them yet. + pub rest: DeploymentCapabilities, +} + +/// By hand, not `#[serde(flatten)]`: `DeploymentCapabilities` denies +/// unknown fields, which a flattened struct cannot. +impl<'de> Deserialize<'de> for CollectorExecutor { + fn deserialize>(deserializer: D) -> Result { + use serde::de::Error; + let mut fields = serde_json::Map::deserialize(deserializer)?; + let summaries = fields + .remove("supported_summaries") + .ok_or_else(|| D::Error::missing_field("supported_summaries"))?; + Ok(Self { + supported_summaries: serde_json::from_value(summaries).map_err(D::Error::custom)?, + rest: serde_json::from_value(serde_json::Value::Object(fields)) + .map_err(D::Error::custom)?, + }) + } +} + +/// An entry of `executor.supported_summaries`: the planner's +/// `SupportedSummary`, unchanged, and what only the collector states. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CollectorSummary { + pub summary: SupportedSummary, + pub input: SummaryInputKind, + /// The ranges of θ's parameters the collector accepts, by name. + pub parameters: BTreeMap, +} + +/// What a summary is built from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SummaryInputKind { + /// Each sample's value: `{"item": null, "weight": {"Column": "SampleValue"}}`. + Value, + /// One label column as the item. + Label, +} + +/// A parameter's accepted range; an absent bound does not bind. +#[derive(Debug, Clone, Copy, PartialEq, Default, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ParameterRange { + pub gt: Option, + pub ge: Option, + pub lt: Option, + pub le: Option, +} + +impl ParameterRange { + fn contains(&self, value: f64) -> bool { + self.gt.is_none_or(|bound| value > bound) + && self.ge.is_none_or(|bound| value >= bound) + && self.lt.is_none_or(|bound| value < bound) + && self.le.is_none_or(|bound| value <= bound) + } +} + +/// One operator the collector runs, with the limits of that operator only. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperatorCapability { + pub kind: OperatorKind, + /// `Scan`: the source variants it reads, e.g. `TimeSeries`. + #[serde(default)] + pub sources: Vec, + /// `SummaryTumblingWindowChain` and `SummaryAgg`: the `Reduction` + /// variants it builds (`PerEntity`, `Reduce`). + #[serde(default)] + pub reductions: Vec, +} + +impl OperatorCapability { + /// `Err` for a limit that does not apply to its kind or names no + /// variant. + fn check(&self) -> Result<(), String> { + let summary_build = matches!( + self.kind, + OperatorKind::SummaryTumblingWindowChain | OperatorKind::SummaryAgg + ); + if !self.sources.is_empty() && self.kind != OperatorKind::Scan { + return Err(format!("sources on {:?}", self.kind)); + } + if !self.reductions.is_empty() && !summary_build { + return Err(format!("reductions on {:?}", self.kind)); + } + if let Some(unknown) = self + .sources + .iter() + .find(|s| !["TimeSeries", "Table"].contains(&s.as_str())) + { + return Err(format!("unknown source {unknown}")); + } + if let Some(unknown) = self + .reductions + .iter() + .find(|r| !["PerEntity", "Reduce"].contains(&r.as_str())) + { + return Err(format!("unknown reduction {unknown}")); + } + Ok(()) + } +} + +/// How series are partitioned across collector instances. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Placement { + pub partitioned_by: PartitionedBy, +} + +/// `"series"`: all samples of one series reach one instance. +/// `{"labels": [..]}`: all series with equal values of those labels do. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PartitionedBy { + Series, + Labels(Vec), +} + +/// Why a node is not on the collector, for the command's report. +#[derive(Debug, Clone, PartialEq)] +pub enum NotOnCollector { + /// Rule (a), with what is outside the capabilities. + NotInCapabilities(String), + /// Rule (b). + InputNotOnCollector, + /// Rule (c). + NotAtIngestion, + /// Rule (d). + NotLocalToPartition, + /// v1: an output that is not a materialized view, or a node above one. + OutputNotAView, + /// Rule (e): its states depend on the order of their samples (a + /// counter's, an instant rate's), so the backend computes its windows + /// again from raw samples when late ones come, whatever the + /// capabilities declare. + OrderSensitive, +} + +/// Whether `node`'s output holds a state whose value depends on the order +/// of its samples (`rate`/`increase`'s counter, `irate`'s last two). +fn order_sensitive(node: &PhysicalASAPDAGNode) -> bool { + node.output_schema.fields.iter().any(|field| { + matches!( + field.dtype, + FieldDataType::ExactAggregate( + asap_types::summary_type::ExactKind::Counter + | asap_types::summary_type::ExactKind::IRate, + _ + ) + ) + }) +} + +/// Errors reading the capabilities. +#[derive(Debug, thiserror::Error)] +pub enum CapabilitiesError { + #[error("capabilities_version {0} is not {CAPABILITIES_VERSION}")] + Version(u32), + #[error("{0}")] + Parse(#[from] serde_json::Error), + #[error("operators: {0}")] + Operators(String), +} + +impl CollectorCapabilities { + /// The capabilities in `text` (JSON); refuses a version this control + /// plane does not know. + pub fn from_json(text: &str) -> Result { + let capabilities: Self = serde_json::from_str(text)?; + if capabilities.capabilities_version != CAPABILITIES_VERSION { + return Err(CapabilitiesError::Version( + capabilities.capabilities_version, + )); + } + let mut kinds = BTreeSet::new(); + for operator in &capabilities.operators { + operator.check().map_err(CapabilitiesError::Operators)?; + if !kinds.insert(format!("{:?}", operator.kind)) { + return Err(CapabilitiesError::Operators(format!( + "{:?} listed twice", + operator.kind + ))); + } + } + Ok(capabilities) + } + + fn operator(&self, kind: OperatorKind) -> Option<&OperatorCapability> { + self.operators.iter().find(|op| op.kind == kind) + } +} + +/// The installed plan's collector sub-DAG, as the collector-views file +/// carries it, and why each other node is not on the collector (in node +/// order; the first rule it fails, in the order (a)–(d)). Errs for a plan +/// whose views do not derive, or whose cut does not stand as a DAG of its +/// own. +pub fn collector_sub_dag( + plan: &InstallablePlan, + capabilities: &CollectorCapabilities, +) -> Result< + ( + CollectorViewsFile, + Vec<(PhysicalASAPNodeId, NotOnCollector)>, + ), + InstallablePlanError, +> { + let dag = &plan.dag; + let index = Index::new(dag); + let views: BTreeSet = plan + .materialized_views()? + .into_iter() + .map(|view| view.node_id) + .collect(); + let mut assigned: BTreeSet = BTreeSet::new(); + let mut reasons: BTreeMap = BTreeMap::new(); + for &id in &index.bottom_up { + let node = index.nodes[&id]; + let reason = order_sensitive(node) + .then_some(NotOnCollector::OrderSensitive) + .or_else(|| { + within_capabilities(node, &index, capabilities) + .err() + .map(NotOnCollector::NotInCapabilities) + }) + .or_else(|| { + (!index + .inputs(id) + .iter() + .all(|input| assigned.contains(input))) + .then_some(NotOnCollector::InputNotOnCollector) + }) + .or_else(|| { + (node.output_state.timing != ExecutionTiming::IngestionTime) + .then_some(NotOnCollector::NotAtIngestion) + }) + .or_else(|| { + (!local_to_partition(node, &index, &capabilities.placement.partitioned_by)) + .then_some(NotOnCollector::NotLocalToPartition) + }); + match reason { + Some(reason) => { + reasons.insert(id, reason); + } + None => { + assigned.insert(id); + } + } + } + // v1: every output that is not a `Scan` must be a view; otherwise it + // and every assigned node above it go back to the backend. + loop { + let bad = assigned.iter().copied().find(|&id| { + !index.is_scan(id) && index.is_output(id, &assigned) && !views.contains(&id) + }); + let Some(bad) = bad else { break }; + for id in index.above(bad) { + if assigned.remove(&id) { + reasons.insert(id, NotOnCollector::OutputNotAView); + } + } + } + let outputs: Vec = assigned + .iter() + .copied() + .filter(|&id| !index.is_scan(id) && index.is_output(id, &assigned)) + .collect(); + // The sub-DAG: the assigned nodes other than `Scan`s, and the `Scan`s + // that feed one. + let on_collector: BTreeSet = assigned + .iter() + .copied() + .filter(|&id| { + !index.is_scan(id) + || index + .consumers(id) + .iter() + .any(|c| assigned.contains(c) && !index.is_scan(*c)) + }) + .collect(); + let sub_dag = PhysicalASAPDAG { + nodes: dag + .nodes + .iter() + .filter(|node| on_collector.contains(&node.id)) + .cloned() + .collect(), + edges: dag + .edges + .iter() + .filter(|edge| { + on_collector.contains(&edge.producer) && on_collector.contains(&edge.consumer) + }) + .cloned() + .collect(), + roots: outputs.clone(), + scalar_roots: Vec::new(), + }; + // A metric is still read raw when one of its `Scan`s feeds a node off + // the collector (or is a root), or runs at query time. + let mut backend_reads_raw: BTreeMap = BTreeMap::new(); + for node in &dag.nodes { + if let Operator::NonASAP(NonASAPOp::Scan { + source: Source::TimeSeries { metric }, + .. + }) = &node.payload + { + let read_here = node.output_state.timing != ExecutionTiming::IngestionTime + || !assigned.contains(&node.id) + || index.roots.contains(&node.id) + || index + .consumers(node.id) + .iter() + .any(|c| !on_collector.contains(c)); + *backend_reads_raw.entry(metric.clone()).or_default() |= read_here; + } + } + if !sub_dag.roots.is_empty() { + // The collector loads it into the planner's types (decision 18). + sub_dag + .materialized_views() + .map_err(InstallablePlanError::from)?; + } + let file = CollectorViewsFile { + planner_wire_version: INSTALLABLE_PLAN_WIRE_VERSION, + plan_id: dag.plan_id(), + backend_reads_raw, + outputs, + dag: sub_dag, + }; + Ok((file, reasons.into_iter().collect())) +} + +/// The DAG's nodes by id, each node's inputs and consumers, and the nodes +/// in bottom-up order (every input before its consumers). +struct Index<'a> { + nodes: HashMap, + inputs: HashMap>, + consumers: HashMap>, + bottom_up: Vec, + /// The query roots, operator and scalar: their outputs leave the DAG. + roots: BTreeSet, +} + +impl<'a> Index<'a> { + fn new(dag: &'a PhysicalASAPDAG) -> Self { + let mut inputs: HashMap> = HashMap::new(); + let mut consumers: HashMap> = HashMap::new(); + for edge in &dag.edges { + inputs.entry(edge.consumer).or_default().push(edge.producer); + consumers + .entry(edge.producer) + .or_default() + .push(edge.consumer); + } + // Depth-first postorder over the inputs: a valid DAG has no cycle. + let mut bottom_up = Vec::with_capacity(dag.nodes.len()); + let mut placed = BTreeSet::new(); + fn visit( + id: PhysicalASAPNodeId, + inputs: &HashMap>, + placed: &mut BTreeSet, + order: &mut Vec, + ) { + if !placed.insert(id) { + return; + } + for &input in inputs.get(&id).into_iter().flatten() { + visit(input, inputs, placed, order); + } + order.push(id); + } + for node in &dag.nodes { + visit(node.id, &inputs, &mut placed, &mut bottom_up); + } + let roots = dag + .roots + .iter() + .copied() + .chain( + dag.scalar_roots + .iter() + .flat_map(|(_, expr)| expr.operator_refs()) + .copied(), + ) + .collect(); + Self { + nodes: dag.nodes.iter().map(|node| (node.id, node)).collect(), + inputs, + consumers, + bottom_up, + roots, + } + } + + fn inputs(&self, id: PhysicalASAPNodeId) -> &[PhysicalASAPNodeId] { + self.inputs.get(&id).map_or(&[], Vec::as_slice) + } + + fn consumers(&self, id: PhysicalASAPNodeId) -> &[PhysicalASAPNodeId] { + self.consumers.get(&id).map_or(&[], Vec::as_slice) + } + + fn is_scan(&self, id: PhysicalASAPNodeId) -> bool { + matches!( + self.nodes[&id].payload, + Operator::NonASAP(NonASAPOp::Scan { .. }) + ) + } + + /// Whether assigned node `id`'s output leaves the collector: a consumer + /// is not assigned, or it is a query root. + fn is_output(&self, id: PhysicalASAPNodeId, assigned: &BTreeSet) -> bool { + self.roots.contains(&id) || self.consumers(id).iter().any(|c| !assigned.contains(c)) + } + + /// `id` and every node above it. + fn above(&self, id: PhysicalASAPNodeId) -> BTreeSet { + let mut seen = BTreeSet::new(); + let mut pending = vec![id]; + while let Some(id) = pending.pop() { + if seen.insert(id) { + pending.extend_from_slice(self.consumers(id)); + } + } + seen + } + + /// The output column names of node `id`. + fn column_names(&self, id: PhysicalASAPNodeId) -> Vec<&str> { + self.nodes[&id] + .output_schema + .fields + .iter() + .map(|field| field.name.as_str()) + .collect() + } +} + +/// Rule (a): `node`'s operator is listed, with its arguments within that +/// entry's limits and `predicate_ops`, and any summary it builds or reads +/// within `executor.supported_summaries`. `Err` names what is not. +fn within_capabilities( + node: &PhysicalASAPDAGNode, + index: &Index, + capabilities: &CollectorCapabilities, +) -> Result<(), String> { + let kind = OperatorKind::of(&node.payload); + let operator = capabilities + .operator(kind) + .ok_or_else(|| format!("operator {kind:?}"))?; + let predicate = |predicate: &ScalarExpr| { + literal_comparisons_only(predicate, &capabilities.predicate_ops) + }; + let reduction = |reduction: &Reduction| { + let name = match reduction { + Reduction::PerEntity => "PerEntity", + Reduction::Reduce(_) => "Reduce", + }; + if operator.reductions.iter().any(|listed| listed == name) { + Ok(()) + } else { + Err(format!("reduction {name} of {kind:?}")) + } + }; + match &node.payload { + Operator::NonASAP(NonASAPOp::Scan { + source, predicates, .. + }) => { + let name = match source { + Source::TimeSeries { .. } => "TimeSeries", + Source::Table { .. } => "Table", + }; + if !operator.sources.iter().any(|listed| listed == name) { + return Err(format!("source {name}")); + } + predicates.iter().try_for_each(|p| predicate(&p.0)) + } + Operator::NonASAP(NonASAPOp::Filter { pred, .. }) => predicate(&pred.0), + Operator::ASAP( + ASAPOp::SummaryTumblingWindowChain { + summary_type, + input, + reduction: r, + filter, + .. + } + | ASAPOp::SummaryAgg { + summary_type, + input, + reduction: r, + filter, + .. + }, + ) => { + reduction(r)?; + if let Some(filter) = filter { + predicate(&filter.0)?; + } + within_summaries(summary_type, input, node, capabilities) + } + Operator::ASAP(ASAPOp::SummaryEstimate { + summary_input, + query, + }) => { + let algorithm = index.nodes[summary_input] + .output_schema + .fields + .iter() + .find_map(|field| match field.dtype { + FieldDataType::Sketch(algorithm) => Some(algorithm), + _ => None, + }) + .ok_or("an estimate of no sketch")?; + let entry = summary_entry(algorithm, capabilities)?; + if entry.summary.readouts.contains(&query.kind()) { + Ok(()) + } else { + Err(format!("readout {:?} of {algorithm:?}", query.kind())) + } + } + _ => Ok(()), + } +} + +/// The capabilities' entry of sketch `algorithm`. +fn summary_entry( + algorithm: SketchAlgorithm, + capabilities: &CollectorCapabilities, +) -> Result<&CollectorSummary, String> { + capabilities + .executor + .supported_summaries + .iter() + .find(|entry| entry.summary.summary_type == algorithm) + .ok_or_else(|| format!("summary {algorithm:?}")) +} + +/// A summary build's type, input and θ (`node.parameters`) within the +/// capabilities' summaries. +fn within_summaries( + summary_type: &FieldDataType, + input: &SummaryUpdate, + node: &PhysicalASAPDAGNode, + capabilities: &CollectorCapabilities, +) -> Result<(), String> { + let FieldDataType::Sketch(algorithm) = summary_type else { + return Err(format!("summary {summary_type:?}")); + }; + let entry = summary_entry(*algorithm, capabilities)?; + let input_kind = match (&input.item, &input.weight) { + (None, SummaryInputExpr::Column(ColumnRef::SampleValue)) => Some(SummaryInputKind::Value), + (Some(SummaryInputExpr::Column(ColumnRef::Named(_))), _) => Some(SummaryInputKind::Label), + _ => None, + }; + if input_kind != Some(entry.input) { + return Err(format!("input {input:?} of {algorithm:?}")); + } + // θ by parameter name through its serde form, `{"": + // {"": value, ..}}`: the planner's `SketchParams` has no + // accessor by name. + let theta = serde_json::to_value(&node.parameters).map_err(|e| e.to_string())?; + let values = theta + .as_object() + .and_then(|by_algorithm| by_algorithm.values().next()) + .and_then(serde_json::Value::as_object); + for (name, range) in &entry.parameters { + let value = values + .and_then(|values| values.get(name)) + .and_then(serde_json::Value::as_f64) + .ok_or_else(|| format!("{algorithm:?} without parameter {name}"))?; + if !range.contains(value) { + return Err(format!("{algorithm:?} {name} = {value}")); + } + } + Ok(()) +} + +/// A predicate the collector evaluates: a conjunction of comparisons of a +/// column with a `Utf8` literal (a label matcher), each with an op of +/// `ops`. +fn literal_comparisons_only( + predicate: &ScalarExpr, + ops: &[CompareOpKind], +) -> Result<(), String> { + match predicate { + ScalarExpr::BoolAnd(all) => all + .iter() + .try_for_each(|part| literal_comparisons_only(part, ops)), + ScalarExpr::Compare { + left, op, right, .. + } => match (&**left, &**right) { + (ScalarExpr::Column(_), ScalarExpr::Literal(ScalarValue::Utf8(_))) + | (ScalarExpr::Literal(ScalarValue::Utf8(_)), ScalarExpr::Column(_)) + if ops.contains(op) => + { + Ok(()) + } + _ => Err(format!("predicate op {op:?}")), + }, + _ => Err("a predicate that is not a conjunction of label comparisons".into()), + } +} + +/// Rule (d): whether `node` is correct on one instance's series, as +/// `partitioned_by` places them. Operators that keep each series' rows to +/// that series are; one grouping series into groups `G` only when each +/// group is on one instance (`{"labels": L}` with `L ⊆ G`); any other +/// operator (joins, binary operators, sorting, limits, populations, ...) +/// is not. +fn local_to_partition( + node: &PhysicalASAPDAGNode, + index: &Index, + partitioned_by: &PartitionedBy, +) -> bool { + // The input grouped and the group keys' column indexes in it. + let (child, keys, without): (PhysicalASAPNodeId, Vec, bool) = match &node.payload { + Operator::NonASAP( + NonASAPOp::Scan { .. } + | NonASAPOp::Filter { .. } + | NonASAPOp::Project { .. } + | NonASAPOp::TimeRange { .. } + | NonASAPOp::TimeShift { .. } + | NonASAPOp::TimeRangeCover { .. }, + ) + | Operator::ASAP( + ASAPOp::SummaryEstimate { .. } + | ASAPOp::FinalizeExactAccumulator { .. } + | ASAPOp::SummaryMergeWindows { .. } + | ASAPOp::SummaryMerge { group_by: None, .. }, + ) => return true, + Operator::NonASAP(NonASAPOp::Aggregate { + reduction, child, .. + }) + | Operator::ASAP( + ASAPOp::SummaryTumblingWindowChain { + reduction, child, .. + } + | ASAPOp::SummaryAgg { + reduction, child, .. + }, + ) => match reduction { + Reduction::PerEntity => return true, + Reduction::Reduce(keys) => (*child, keys.keys().to_vec(), keys.is_without()), + }, + Operator::ASAP(ASAPOp::SummaryMerge { + children, + group_by: Some(keys), + }) => match children.as_slice() { + [child] => (*child, keys.clone(), false), + _ => return false, + }, + _ => return false, + }; + let PartitionedBy::Labels(labels) = partitioned_by else { + return false; + }; + let columns = index.column_names(child); + let named: BTreeSet<&str> = keys + .iter() + .filter_map(|&column| columns.get(column).copied()) + .collect(); + labels.iter().all(|label| { + let in_keys = named.contains(label.as_str()); + if without { + columns.contains(&label.as_str()) && !in_keys + } else { + in_keys + } + }) +} diff --git a/crates/control-plane/src/lib.rs b/crates/control-plane/src/lib.rs index 3b5295dd1..80ed494e7 100644 --- a/crates/control-plane/src/lib.rs +++ b/crates/control-plane/src/lib.rs @@ -10,6 +10,7 @@ use std::path::Path; +pub mod collector_views; #[cfg(feature = "test-support")] pub mod test_support; diff --git a/crates/control-plane/src/main.rs b/crates/control-plane/src/main.rs index c5e138516..ca35ff8ed 100644 --- a/crates/control-plane/src/main.rs +++ b/crates/control-plane/src/main.rs @@ -1,16 +1,39 @@ use std::path::{Path, PathBuf}; use anyhow::Context; -use asap_planner::PlanningWorkload; +use asap_planner::{InstallablePlan, PlanningWorkload}; use clap::Parser; -use control_plane::{plan_workload, save_plan, save_report, DeploymentInputs}; +use control_plane::collector_views::{collector_sub_dag, CollectorCapabilities}; +use control_plane::{load_plan, plan_workload, save_plan, save_report, DeploymentInputs}; -/// Plan a workload with ASAPPlanner and write the selected plan. +/// Plan a workload with ASAPPlanner and write the selected plan; or, with +/// `--plan`, read a plan written before. With `--collector-capabilities`, +/// also write the part of the plan the collector runs +/// (`--emit-collector-views`). #[derive(Parser)] struct Args { /// Planner `PlanningWorkload` (JSON). - #[arg(long)] - workload: PathBuf, + #[arg(long, required_unless_present = "plan", requires = "out")] + workload: Option, + /// A plan this command wrote before, in place of planning `--workload`: + /// only its collector views are written. + #[arg( + long, + requires = "collector_capabilities", + conflicts_with_all = [ + "workload", "out", "report", "deployment_capabilities", "cost_inputs", + "measured_operation_costs", "ignore_accuracy_guarantees", + ] + )] + plan: Option, + /// What the collector runs (`asap_sketches --print-capabilities`): + /// the views it can build in place of the data plane. + #[arg(long, requires = "emit_collector_views")] + collector_capabilities: Option, + /// Where to write the collector-views file the collector and the data + /// plane (`--collector-views`) load. + #[arg(long, requires = "collector_capabilities")] + emit_collector_views: Option, /// Planner `DeploymentCapabilities` (JSON); defaults to what this /// backend's data plane executes and keeps. #[arg(long)] @@ -32,7 +55,7 @@ struct Args { ignore_accuracy_guarantees: bool, /// Where to write the plan the data plane installs. #[arg(long)] - out: PathBuf, + out: Option, /// Where to write Stage 3's report of the selected plan: its cost and /// predicted resource usage, per node and per query. #[arg(long)] @@ -50,7 +73,37 @@ fn main() -> anyhow::Result<()> { .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .init(); let args = Args::parse(); - let workload: PlanningWorkload = read_json(&args.workload)?; + let plan = match (&args.plan, &args.workload, &args.out) { + (Some(path), _, _) => load_plan(path)?, + (None, Some(workload), Some(out)) => plan(&args, workload, out)?, + _ => anyhow::bail!("give --plan, or --workload and --out"), + }; + if let (Some(capabilities), Some(out)) = + (&args.collector_capabilities, &args.emit_collector_views) + { + let text = std::fs::read_to_string(capabilities) + .with_context(|| format!("reading {}", capabilities.display()))?; + let capabilities = CollectorCapabilities::from_json(&text) + .with_context(|| format!("parsing {}", capabilities.display()))?; + let (file, not_on_collector) = collector_sub_dag(&plan, &capabilities)?; + let text = serde_json::to_string_pretty(&file)?; + std::fs::write(out, text).with_context(|| format!("writing {}", out.display()))?; + for (node, reason) in ¬_on_collector { + println!("not on the collector: node {node}: {reason:?}"); + } + println!( + "wrote {} (collector views {:?}, backend reads raw {:?})", + out.display(), + file.outputs, + file.backend_reads_raw, + ); + } + Ok(()) +} + +/// Plans `workload` as the arguments say and writes the plan to `out`. +fn plan(args: &Args, workload: &Path, out: &Path) -> anyhow::Result { + let workload: PlanningWorkload = read_json(workload)?; let mut inputs = DeploymentInputs::default(); if let Some(path) = &args.deployment_capabilities { // The file's fields over this backend's own capabilities: a field it @@ -72,7 +125,7 @@ fn main() -> anyhow::Result<()> { } inputs.ignore_accuracy_guarantees = args.ignore_accuracy_guarantees; let (plan, report) = plan_workload(&workload, &inputs)?; - save_plan(&plan, &args.out)?; + save_plan(&plan, out)?; if let Some(path) = &args.report { save_report(&report, path)?; } @@ -81,9 +134,9 @@ fn main() -> anyhow::Result<()> { } println!( "wrote {} ({} queries, {} nodes)", - args.out.display(), + out.display(), plan.query_texts.len(), plan.dag.nodes.len() ); - Ok(()) + Ok(plan) } diff --git a/crates/control-plane/tests/collector_views.rs b/crates/control-plane/tests/collector_views.rs new file mode 100644 index 000000000..42f2949df --- /dev/null +++ b/crates/control-plane/tests/collector_views.rs @@ -0,0 +1,374 @@ +//! The collector view rule (docs/design/collector-sketch-ingest.md, §1): +//! which nodes of an installed plan the collector runs, from its declared +//! capabilities, and the collector-views file written from them. + +use std::path::Path; + +use asap_planner::{InstallablePlan, PhysicalASAPNodeId}; +use control_plane::collector_views::{collector_sub_dag, CollectorCapabilities, NotOnCollector}; +use control_plane::{plan_workload, DeploymentInputs}; +use serde_json::{json, Value}; + +/// Today's collector's capabilities, as the design document prints them. +fn capabilities() -> Value { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/collector-capabilities.json"); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() +} + +fn parse(capabilities: &Value) -> CollectorCapabilities { + CollectorCapabilities::from_json(&capabilities.to_string()).unwrap() +} + +/// A deployment without multi-level window chains, unless `levels`. +fn inputs(levels: bool) -> DeploymentInputs { + let mut inputs = DeploymentInputs::default(); + inputs.deployment_capabilities.raw_data_retained = false; + if !levels { + inputs.deployment_capabilities.excluded_candidates = serde_json::from_value(json!( + [{"operator": "SummaryMergeWindows"}, {"operator": "TimeRangeCover"}] + )) + .unwrap(); + } + inputs +} + +/// The plan of `queries`, evaluated every 10 s over the gauge `data`, each +/// quantile with a 5 % error target (a DDSketch chain). +fn plan(queries: &[&str], levels: bool) -> InstallablePlan { + let entries: Vec = queries + .iter() + .map(|query| { + let requirements = if query.starts_with("quantile") { + json!({"accuracy": {"max_error": 0.05, "failure_probability": 0.3, + "accuracy_scope": "whole_result"}}) + } else { + json!({}) + }; + json!({ + "query": query, + "demand": {"fixed_interval_at": {"interval": 10000, "evaluation_phase": 0}}, + "requirements": requirements, + "predictability": {"predictable": {"known_at": null}}, + }) + }) + .collect(); + let workload = serde_json::from_value(json!({ + "query_workload": {"language": "promql", "repeating_queries": entries}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": 100000.0}}, + "sources": {"data": {"series_count": 10000, "sample_interval": 100, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + plan_workload(&workload, &inputs(levels)).unwrap().0 +} + +/// The plan's nodes of operator `operator` (`ASAP` or `NonASAP` payload +/// key), by id. +fn nodes_of(plan: &InstallablePlan, operator: &str) -> Vec { + plan.dag + .nodes + .iter() + .filter(|node| { + let payload = serde_json::to_value(&node.payload).unwrap(); + ["ASAP", "NonASAP"] + .iter() + .any(|side| !payload[side][operator].is_null()) + }) + .map(|node| node.id) + .collect() +} + +/// The plan's DDSketch chain. +fn chain(plan: &InstallablePlan) -> PhysicalASAPNodeId { + let chains = nodes_of(plan, "SummaryTumblingWindowChain"); + let [chain] = chains.as_slice() else { + panic!("chains {chains:?}") + }; + *chain +} + +fn reason( + reasons: &[(PhysicalASAPNodeId, NotOnCollector)], + node: PhysicalASAPNodeId, +) -> Option<&NotOnCollector> { + reasons.iter().find(|(id, _)| *id == node).map(|(_, r)| r) +} + +/// A quantile's leaf DDSketch chain is the one collector view; its `Scan` +/// is on the collector and every query-time node is not. With only that +/// view reading `data`, the backend no longer reads `data` raw. +#[test] +fn a_leaf_sketch_chain_is_the_collector_view() { + let plan = plan(&["quantile_over_time(0.99, data[5m])"], false); + let (file, reasons) = collector_sub_dag(&plan, &parse(&capabilities())).unwrap(); + let chain = chain(&plan); + assert_eq!(file.outputs, [chain]); + assert_eq!(file.dag.roots, [chain]); + assert_eq!(file.plan_id, plan.dag.plan_id()); + assert_eq!(file.backend_reads_raw, [("data".to_string(), false)].into()); + let scans = nodes_of(&plan, "Scan"); + let mut on_collector: Vec<_> = file.dag.nodes.iter().map(|node| node.id).collect(); + on_collector.sort(); + let mut expected = vec![chain]; + expected.extend(&scans); + expected.sort(); + assert_eq!(on_collector, expected); + for node in &plan.dag.nodes { + if !expected.contains(&node.id) { + assert!( + reason(&reasons, node.id).is_some(), + "node {} has no reason", + node.id + ); + } + } +} + +/// With an exact view over the same metric (not in the capabilities), the +/// quantile's chain is still the one collector view, and `data` is still +/// read raw by the backend. +#[test] +fn a_metric_another_view_reads_stays_raw() { + let plan = plan( + &[ + "quantile_over_time(0.99, data[5m])", + "sum_over_time(data[5m])", + ], + false, + ); + let (file, reasons) = collector_sub_dag(&plan, &parse(&capabilities())).unwrap(); + let chains = nodes_of(&plan, "SummaryTumblingWindowChain"); + assert_eq!(chains.len(), 2); + assert_eq!(file.outputs.len(), 1); + let exact = chains.iter().find(|c| !file.outputs.contains(c)).unwrap(); + assert!(matches!( + reason(&reasons, *exact), + Some(NotOnCollector::NotInCapabilities(what)) if what.contains("ExactAggregate") + )); + assert_eq!(file.backend_reads_raw, [("data".to_string(), true)].into()); +} + +/// A sketch, a parameter range or a predicate op the collector lacks +/// leaves the chain in the backend, with the reason. +#[test] +fn what_the_capabilities_lack_stays_in_the_backend() { + let quantile = plan(&["quantile_over_time(0.99, data[5m])"], false); + let not_in = |capabilities: &Value, plan: &InstallablePlan, node| { + let (file, reasons) = collector_sub_dag(plan, &parse(capabilities)).unwrap(); + assert!(file.outputs.is_empty()); + match reason(&reasons, node) { + Some(NotOnCollector::NotInCapabilities(what)) => what.clone(), + other => panic!("{other:?}"), + } + }; + let mut no_ddsketch = capabilities(); + no_ddsketch["executor"]["supported_summaries"] + .as_array_mut() + .unwrap() + .remove(0); + assert!(not_in(&no_ddsketch, &quantile, chain(&quantile)).contains("DDSketch")); + + let mut finer_alpha_only = capabilities(); + finer_alpha_only["executor"]["supported_summaries"][0]["parameters"]["alpha"] = + json!({"gt": 0, "lt": 0.01}); + assert!(not_in(&finer_alpha_only, &quantile, chain(&quantile)).contains("alpha")); + + let regex = plan( + &[r#"quantile_over_time(0.99, data{job=~"a.*"}[5m])"#], + false, + ); + let selected = plan(&[r#"quantile_over_time(0.99, data{job="a"}[5m])"#], false); + let (file, _) = collector_sub_dag(&selected, &parse(&capabilities())).unwrap(); + assert_eq!( + file.outputs, + [chain(&selected)], + "an equality matcher is in the capabilities" + ); + let (file, reasons) = collector_sub_dag(®ex, &parse(&capabilities())).unwrap(); + assert!(file.outputs.is_empty()); + assert!( + reasons.iter().any( + |(_, r)| matches!(r, NotOnCollector::NotInCapabilities(what) if what.contains("Regex")) + ), + "{reasons:?}" + ); +} + +/// A chain reducing series to groups is local to a partition only when +/// each group is on one instance: never with series placement, and with +/// `{"labels": L}` when `L` is among its group keys. The plan's chain is +/// made a `Reduce` by its `job` label for the rule alone. +#[test] +fn a_reducing_chain_is_local_only_when_its_groups_are() { + let mut plan = plan(&["quantile_over_time(0.99, data[5m])"], false); + let chain = chain(&plan); + let scan = nodes_of(&plan, "Scan")[0]; + let scan_columns: Vec = plan + .dag + .nodes + .iter() + .find(|node| node.id == scan) + .unwrap() + .output_schema + .fields + .iter() + .map(|field| field.name.clone()) + .collect(); + let node = plan + .dag + .nodes + .iter_mut() + .find(|node| node.id == chain) + .unwrap(); + let mut payload = serde_json::to_value(&node.payload).unwrap(); + // Group by the scan's first column, named by the placement below. + payload["ASAP"]["SummaryTumblingWindowChain"]["reduction"] = json!({"Reduce": [0]}); + node.payload = serde_json::from_value(payload).unwrap(); + let mut reducing = capabilities(); + reducing["operators"][2]["reductions"] = json!(["PerEntity", "Reduce"]); + + let (_, reasons) = collector_sub_dag(&plan, &parse(&reducing)).unwrap(); + assert_eq!( + reason(&reasons, chain), + Some(&NotOnCollector::NotLocalToPartition) + ); + reducing["placement"] = json!({"partitioned_by": {"labels": [scan_columns[0]]}}); + let (_, reasons) = collector_sub_dag(&plan, &parse(&reducing)).unwrap(); + assert!( + !matches!( + reason(&reasons, chain), + Some(NotOnCollector::NotLocalToPartition | NotOnCollector::NotInCapabilities(_)) + ), + "{:?}", + reason(&reasons, chain) + ); + reducing["placement"] = json!({"partitioned_by": {"labels": ["no_such_label"]}}); + let (_, reasons) = collector_sub_dag(&plan, &parse(&reducing)).unwrap(); + assert_eq!( + reason(&reasons, chain), + Some(&NotOnCollector::NotLocalToPartition) + ); +} + +/// One more operator line moves the cut up: with `SummaryMergeWindows` in +/// the capabilities, a wider level merged from the chain at ingestion is a +/// collector view too. +#[test] +fn an_operator_line_moves_the_cut_up() { + let plan = plan(&["quantile_over_time(0.99, data[5m])"], true); + let levels = nodes_of(&plan, "SummaryMergeWindows"); + assert!(!levels.is_empty(), "the plan has no wider level"); + let (file, reasons) = collector_sub_dag(&plan, &parse(&capabilities())).unwrap(); + assert_eq!(file.outputs, [chain(&plan)]); + assert!(matches!( + reason(&reasons, levels[0]), + Some(NotOnCollector::NotInCapabilities(what)) if what.contains("SummaryMergeWindows") + )); + let mut merging = capabilities(); + merging["operators"] + .as_array_mut() + .unwrap() + .push(json!({"kind": "SummaryMergeWindows"})); + let (file, _) = collector_sub_dag(&plan, &parse(&merging)).unwrap(); + for level in &levels { + assert!(file.outputs.contains(level), "{:?}", file.outputs); + } +} + +/// The written file reads back equal, and its sub-DAG is valid on its own: +/// its materialized views have the installed plan's view state keys. +#[test] +fn the_file_reads_back_and_its_views_keep_their_keys() { + let plan = plan(&["quantile_over_time(0.99, data[5m])"], false); + let (file, _) = collector_sub_dag(&plan, &parse(&capabilities())).unwrap(); + let text = serde_json::to_string(&file).unwrap(); + let read: common::CollectorViewsFile = serde_json::from_str(&text).unwrap(); + // Equal as written (the nodes' in-memory provenance is not in the file). + assert_eq!(serde_json::to_string(&read).unwrap(), text); + let installed = plan.materialized_views().unwrap(); + for view in read.dag.materialized_views().unwrap() { + let same = installed + .iter() + .find(|v| v.node_id == view.node_id) + .unwrap(); + assert_eq!(view.view_state_key(), same.view_state_key()); + } +} + +/// Capabilities of another version, with an unknown field, or with an +/// operator limit that does not apply to its kind or names no variant, are +/// refused. +#[test] +fn unknown_capabilities_are_refused() { + let mut newer = capabilities(); + newer["capabilities_version"] = json!(2); + assert!(CollectorCapabilities::from_json(&newer.to_string()).is_err()); + let mut unknown = capabilities(); + unknown["operators"][0]["reductions_typo"] = json!([]); + assert!(CollectorCapabilities::from_json(&unknown.to_string()).is_err()); + for (operator, limits) in [ + (2, json!({"reductions": ["PerEnity"]})), + (0, json!({"reductions": ["PerEntity"]})), + (1, json!({"sources": ["TimeSeries"]})), + ] { + let mut wrong = capabilities(); + for (limit, value) in limits.as_object().unwrap() { + wrong["operators"][operator][limit] = value.clone(); + } + assert!( + CollectorCapabilities::from_json(&wrong.to_string()).is_err(), + "{limits}" + ); + } + let mut twice = capabilities(); + twice["operators"] + .as_array_mut() + .unwrap() + .push(json!({"kind": "Filter"})); + assert!(CollectorCapabilities::from_json(&twice.to_string()).is_err()); +} + +/// A view whose states depend on the order of their samples (a counter's, +/// for `rate`/`increase`) stays in the backend whatever the collector's +/// capabilities, so a late sample can still compute its window again from +/// raw samples: the plan of a `rate` gets no collector view, and its +/// metric is still read raw. +#[test] +fn an_order_sensitive_view_stays_in_the_backend() { + let workload = serde_json::from_value(json!({ + "query_workload": {"language": "promql", "repeating_queries": [{ + "query": "sum by (job) (rate(data_total[5m]))", + "demand": {"fixed_interval_at": {"interval": 10000, "evaluation_phase": 0}}, + "requirements": {}, + "predictability": {"predictable": {"known_at": null}}, + }]}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": 100000.0}}, + "sources": {"data_total": {"series_count": 10000, "sample_interval": 100, + "metric_type": "counter", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let plan = plan_workload(&workload, &inputs(false)).unwrap().0; + let counters: Vec = plan + .dag + .nodes + .iter() + .filter(|node| { + serde_json::to_string(&node.output_schema) + .unwrap() + .contains("\"Counter\"") + && node.is_view() + }) + .map(|node| node.id) + .collect(); + assert!(!counters.is_empty(), "the plan keeps a counter view"); + let (file, reasons) = collector_sub_dag(&plan, &parse(&capabilities())).unwrap(); + assert!(file.outputs.is_empty(), "{:?}", file.outputs); + assert!(file.backend_reads_raw["data_total"]); + for counter in counters { + let reason = reasons + .iter() + .find(|(id, _)| *id == counter) + .map(|(_, r)| r); + assert_eq!(format!("{reason:?}"), "Some(OrderSensitive)", "{reasons:?}"); + } +} diff --git a/crates/control-plane/tests/data/collector-capabilities.json b/crates/control-plane/tests/data/collector-capabilities.json new file mode 100644 index 000000000..22a010392 --- /dev/null +++ b/crates/control-plane/tests/data/collector-capabilities.json @@ -0,0 +1,21 @@ +{"capabilities_version": 1, + "executor": { + "supported_summaries": [ + {"summary": {"summary_type": "DDSketch", "readouts": []}, "input": "value", "parameters": {"alpha": {"gt": 0, "lt": 1}}}, + {"summary": {"summary_type": "KLL", "readouts": []}, "input": "value", "parameters": {"k": {"ge": 8, "le": 2147483647}}}, + {"summary": {"summary_type": "HLL", "readouts": []}, "input": "label", "parameters": {"precision": {"ge": 14, "le": 14}}}, + {"summary": {"summary_type": "CountSketch", "readouts": []}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, + {"summary": {"summary_type": "CountMinSketch", "readouts": []}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, + {"summary": {"summary_type": "CountMinSketchWithHeap", "readouts": []}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}, "heap_size": {"ge": 1}}}], + "raw_data_retained": false, + "query_time_results_retained": false, + "counter_semantics": {"reset_handling": false, "extrapolation": false}, + "state_not_mergeable_across_windows": [], + "excluded_candidates": []}, + "predicate_ops": ["Eq", "Ne"], + "operators": [ + {"kind": "Scan", "sources": ["TimeSeries"]}, + {"kind": "Filter"}, + {"kind": "SummaryTumblingWindowChain", "reductions": ["PerEntity"]}], + "placement": {"partitioned_by": "series"}, + "window_close_delay_ms": 6000} diff --git a/crates/data-plane/src/main.rs b/crates/data-plane/src/main.rs index da8ce63f7..a908dabe2 100644 --- a/crates/data-plane/src/main.rs +++ b/crates/data-plane/src/main.rs @@ -2,6 +2,7 @@ use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; +use anyhow::Context; use clap::Parser; /// jemalloc: Remote Write decoding and query runs allocate many small, @@ -21,6 +22,7 @@ static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0,narenas:8\0"; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane, DEFAULT_FORWARD_TIMEOUT}; +use precompute::collector::CollectorViewOptions; use precompute::engine::PrecomputeMode; use precompute::ingestion::IngestionOptions; use storage::persist::ViewRead; @@ -113,6 +115,12 @@ struct Args { /// `--no-forward`. #[arg(long, conflicts_with = "no_forward")] raw_store_url: Option, + /// The collector-views file the control plane wrote for the plan + /// (`--emit-collector-views`): its views are built by the collector, + /// whose states arrive on `/v1/metrics`, not by this data plane. + /// Refused when it is of another plan. + #[arg(long)] + collector_views: Option, /// A ClickHouse server's HTTP interface base URL: serves ClickHouse's /// query route, `/clickhouse/query`, which forwards every query the plan /// does not answer to it. Cannot be used with `--no-forward`. @@ -207,6 +215,16 @@ async fn main() -> anyhow::Result<()> { .init(); let args = Args::parse(); let plan = std::fs::read_to_string(&args.plan)?; + let collector = match &args.collector_views { + Some(path) => { + let text = std::fs::read_to_string(path) + .with_context(|| format!("reading {}", path.display()))?; + let file: common::CollectorViewsFile = serde_json::from_str(&text) + .with_context(|| format!("parsing {}", path.display()))?; + CollectorViewOptions::from(&file) + } + None => CollectorViewOptions::default(), + }; let forward_timeout = Duration::from_secs(args.forward_timeout_seconds); let mut state = DataPlane::with_options( plan, @@ -244,6 +262,7 @@ async fn main() -> anyhow::Result<()> { max_samples: args.push_batch_samples, max_age_ms: args.push_batch_max_ms, }, + collector, ..EngineOptions::default() }, )? diff --git a/crates/data-plane/tests/collector_views.rs b/crates/data-plane/tests/collector_views.rs index f0c05dc30..fef365144 100644 --- a/crates/data-plane/tests/collector_views.rs +++ b/crates/data-plane/tests/collector_views.rs @@ -21,6 +21,7 @@ use asap_sketchlib::DdSketch; use axum::body::Body; use axum::http::{header, Request, StatusCode}; use axum::Router; +use control_plane::collector_views::{collector_sub_dag, CollectorCapabilities}; use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane}; @@ -118,6 +119,7 @@ fn collector_data_plane(plan: &InstallablePlan, node: usize) -> (Router, Arc, edit: impl FnOnce(&mut Metric)) -> Vec { edit(&mut request.resource_metrics[0].scope_metrics[0].metrics[0]); prost::Message::encode_to_vec(&request) } + +/// The collector-views file the control plane writes for the plan, from +/// today's collector's capabilities, read back as the data plane reads +/// `--collector-views`, makes the chain a collector view: the data plane +/// does not build it (the samples of `data`, which only it reads, are not +/// kept) and answers from the collector's states as it does from its own +/// view. +#[tokio::test(flavor = "multi_thread")] +async fn the_collector_views_file_makes_the_chain_a_collector_view() { + let (plan, node, width_ms, alpha) = plan(); + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../control-plane/tests/data/collector-capabilities.json"); + let capabilities = + CollectorCapabilities::from_json(&std::fs::read_to_string(path).unwrap()).unwrap(); + let (file, _) = collector_sub_dag(&plan, &capabilities).unwrap(); + let file: ::common::CollectorViewsFile = + serde_json::from_str(&serde_json::to_string(&file).unwrap()).unwrap(); + assert_eq!(file.outputs, [node]); + let collector = CollectorViewOptions::from(&file); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + let (app, state) = data_plane( + &plan, + EngineOptions { + collector, + ..no_forward(0) + }, + ); + let states = states(alpha, width_ms, time_ms); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let committed = + format!("asap_collector_states_windows_total{{view=\"{node}\",outcome=\"committed\"}}"); + wait_for(&state, &committed, (RANGE_MS / width_ms) as f64).await; + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); + // `data`'s samples are not kept: only the collector view reads them. + common::remote_write( + &app, + vec![TimeSeries { + labels: vec![Label { + name: "__name__".into(), + value: "data".into(), + }], + samples: vec![Sample { + timestamp: time_ms, + value: 1.0, + }], + }], + ) + .await; + for _ in 0..100 { + if state.engine.stats().samples_unrouted == 1 { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!(state.engine.stats().samples_unrouted, 1); +} + +/// A collector-views file of another plan is refused at install. +#[test] +fn a_collector_views_file_of_another_plan_is_refused() { + let (plan, node, _, _) = plan(); + let options = EngineOptions { + collector: CollectorViewOptions { + plan_id: Some("another plan".into()), + views: BTreeSet::from([node]), + ..CollectorViewOptions::default() + }, + ..no_forward(0) + }; + let plan = serde_json::to_string(&plan).unwrap(); + let refused = DataPlane::with_options(plan, "http://127.0.0.1:1".into(), options) + .err() + .expect("refused"); + assert!( + format!("{refused:#}").contains("another plan"), + "{refused:#}" + ); +} diff --git a/crates/precompute/src/collector.rs b/crates/precompute/src/collector.rs index 6542d0a7f..46b289d5f 100644 --- a/crates/precompute/src/collector.rs +++ b/crates/precompute/src/collector.rs @@ -46,6 +46,9 @@ use crate::ingestion::{ClockReading, ClosedWindow, Computed, DagIndex, Ingestion /// a window's end, with no state arriving, it closes on the clock. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CollectorViewOptions { + /// The plan the views were cut from (`PhysicalASAPDAG::plan_id()`): + /// installing another plan is refused. `None`: not checked. + pub plan_id: Option, pub views: BTreeSet, /// While no state arrives, a window closes once its end plus this has /// passed on the monotonic clock, counted from the newest state's @@ -59,12 +62,26 @@ impl Default for CollectorViewOptions { /// end, and 2 s are allowed for clock skew. fn default() -> Self { Self { + plan_id: None, views: BTreeSet::new(), idle_close_ms: 8_000, } } } +impl From<&common::CollectorViewsFile> for CollectorViewOptions { + /// The collector views a collector-views file lists, of its plan. + /// The file does not carry the collector's close delay: windows close + /// on the clock after the default allowance. + fn from(file: &common::CollectorViewsFile) -> Self { + Self { + plan_id: Some(file.plan_id.clone()), + views: file.outputs.iter().copied().collect(), + ..Self::default() + } + } +} + /// Why a state was rejected, as `asap_collector_states_rejected_total`'s /// `reason`. pub mod reject { @@ -646,6 +663,7 @@ mod tests { let views = plan.materialized_views().unwrap(); let chain = views[0].node_id; let collector = CollectorViewOptions { + plan_id: None, views: BTreeSet::from([chain]), ..CollectorViewOptions::default() }; @@ -696,6 +714,7 @@ mod tests { let views = plan.materialized_views().unwrap(); let chain = views[0].node_id; let options = CollectorViewOptions { + plan_id: None, views: BTreeSet::from([chain]), ..CollectorViewOptions::default() }; diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index acac19334..bf07384d8 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -359,6 +359,13 @@ impl PrecomputeEngine { /// Compiles `plan`'s ingestion and starts its threads. fn start(&self, plan: &InstallablePlan) -> anyhow::Result { + if let Some(collector_plan) = &self.options.collector.plan_id { + let installed = plan.dag.plan_id(); + anyhow::ensure!( + *collector_plan == installed, + "the collector views are of plan {collector_plan}, not of the plan installed ({installed})" + ); + } let views = plan.materialized_views()?; let groups = plan.ingestion_refresh_groups()?; tracing::info!(