promql/native/canonicalize.rs
1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Puts a canonical merge where a label rewrite made one necessary.
16//!
17//! A fused input hands over the pieces of a metric one scan partition holds, and a label rewrite in
18//! the tree can give two of those pieces one label set. Every consumer that answers a whole label
19//! set - a fold, a ranking, a vector match, the statement's own output - then reads two series where
20//! Prometheus reads one, or answers the sum of a group twice. [`NativeExpr::Merge`] is the node that
21//! collects the pieces of one label set into one series, and this module decides where one is
22//! needed.
23//!
24//! # What decides it
25//!
26//! Only a rewrite can alias, and only one that writes a label its input already carries or drops one
27//! its output would still be told apart by: [`duplicates_canonical_labels`] is that fact, derived
28//! from the tree and the tags each source reports. A tree with no such rewrite gains no merge at
29//! all, so a per-series query keeps every scan partition and pays nothing for this pass.
30//!
31//! Where a merge is added is a property of the consumer, and of what the operations between the
32//! consumer and the rewrite do to one sample:
33//!
34//! | consumer | merge below it? | why |
35//! | --- | --- | --- |
36//! | the root | yes | the answer names one series per label set, so two rows sharing one set are the error Prometheus reports |
37//! | `Aggregate` | yes | a fold sums the values it is handed at a point, so two pieces of one series are summed as if the query said so twice |
38//! | `Vector` | yes | ranking, presence checks and folds must read canonical series rather than duplicate fragments |
39//! | `Binary`/`Set` over two vectors | yes, on both sides | each side is matched by label, and the kernel refuses two values of one field at a point only after the pair was matched |
40//! | `Info` | yes, on both sides | it looks the info series up by identifying labels, so the pieces of one label set have to be one series first |
41//! | `Window` over an evaluated vector | yes | a window folds a range of one series, so it reads the series whole |
42//! | `Map`, `ParameterizedMap` | yes, below it | point-wise, but not sample-preserving: the histogram functions drop float samples, math ignores native histograms, and a parameterized clamp can empty a point - and the label set a point's occupancy is judged under is the rewritten one, so a merge above such a map would be handed the occupancy that is already gone |
43//! | `Timestamp`, `Instant`, a scalar broadcast | no | each rewrites the value of a sample it read and keeps that sample's position, so no occupancy is lost and the pieces are still told apart where the rewrite left them |
44//!
45//! A merge is never added below a raw scan, a scalar or aggregate state: it binds samples evaluated
46//! on a grid, and no consumer asks for one over those.
47//!
48//! A node can be a source of duplicates without rewriting a label its input carries: a range
49//! function that computes its result and `timestamp` in both of its forms drop the metadata labels -
50//! the metric name, `__type__` and `__unit__` - and hand out a set those no longer tell apart. What
51//! they produce is collected by their consumer - the root included - exactly as a rewrite of an
52//! existing label is, unless
53//! [`duplicates_canonical_labels`](crate::native::plan::duplicates_canonical_labels) proves from the
54//! labels alone that nothing they drop was telling two of their series apart: a source bound to one
55//! metric names every series it hands over, and a source whose tags carry neither `__type__` nor
56//! `__unit__` holds no series those two tell apart either. `rate(some_metric[5m])` over such a scan
57//! is then a window that streams its scan, and the same query over a selector that discovered
58//! several metrics keeps the collection it needs. The same rule is what a math or histogram map, a
59//! parameterized map and an arithmetic or `bool` scalar broadcast are judged by.
60//!
61//! The labels are the whole of that proof, and the scan's key columns are not part of it. A key
62//! column that holds `NULL` in one stored series and `''` in another decodes to an absent and to an
63//! empty label, and the drop removes the empty one with the name, leaving both under one label set -
64//! a pair that no label can state and that is deliberately outside the proof, because every tag
65//! column of a metric-engine table is nullable and collecting every name-dropping kernel over one
66//! for it costs every such statement a canonical merge. The fact is still counted
67//! ([`leaves_a_drop_to_the_storage_keys`](crate::native::plan::leaves_a_drop_to_the_storage_keys)),
68//! so the statements the pair can hide stay observable. Its other reader is the physical per-series
69//! scan, which asks it of its own binding to decide whether its partitions hand over whole series
70//! ([`keys_survive_metadata_drop`](crate::extension_plan::keys_survive_metadata_drop)) - a
71//! partition-identity question at execution, never a reason to insert a `Merge`.
72//!
73//! A drop above a merge is not asked about the empty value it removes, which is what keeps a chain of
74//! drops to one collection: [`NativeExpr::Merge`] hands over one series per canonical label set - the
75//! comparison that treats an empty label value as no label - so no drop above it can fold two of its
76//! series by dropping an empty one. The metadata labels a drop removes are another matter: a merge
77//! keeps two series that differ in `__name__`, `__type__` or `__unit__`, so the labels half of the
78//! proof is still asked above it. With that, a chain of drops - `abs(abs(rate(x[5m])))` - pays for
79//! the one merge at the bottom of the chain rather than one per drop.
80//!
81//! Canonicalizing a map's input is what makes the histogram case work: in
82//! `histogram_count(label_replace(x, "host", "same", "host", ".*"))` two scan partitions each
83//! rewrite one series to `{host="same"}` and `histogram_count` drops both - they are float samples -
84//! before anything could report that the two now share a label set at one point. The merge is
85//! inserted between the rewrite and `histogram_count`, so the canonical router judges the occupancy
86//! the rewrite created and reports the collision instead of an empty answer.
87//!
88//! Running the pass over its own output changes nothing: the node that gained a merge then answers
89//! one series per label set, so [`duplicates_canonical_labels`] is `false` for it and a second run
90//! finds nothing to add. That also makes the pass safe to apply at every segment boundary rather
91//! than only at the statement root.
92//!
93//! What this pass does *not* decide is placement: whether the merge can be answered inside one
94//! execution is the lowering's question. A merge that spans partitions uses a producer and the
95//! existing canonical router; downstream consumers read ordinary evaluated frames.
96
97use std::sync::Arc;
98
99use datafusion::error::Result as DfResult;
100
101use crate::native::plan::{
102 NativeExpr, NativeNode, NativeTree, NativeType, duplicates_canonical_labels,
103};
104
105#[cfg(test)]
106mod tests;
107
108/// Rewrites `tree` so that every consumer of a whole canonical series is handed one.
109///
110/// `source_tags` is what the caller knows about each fused input's tags, indexed by the
111/// `source_index` of the [`BoundInput`](crate::native::plan::BoundInput) each leaf was bound to; a
112/// source the caller says nothing about proves nothing, and a rewrite over it is collected. The
113/// index is what a leaf reads, so a tree with several sources is judged source by source.
114///
115/// `source_metrics` is the other half of that knowledge, indexed the same way: the one metric each
116/// source is bound to, or `None` when it may hand over several. It is what lets a kernel that drops
117/// the metadata labels keep every partition - see
118/// [`duplicates_canonical_labels`](crate::native::plan::duplicates_canonical_labels) - and a caller
119/// that cannot say collects instead.
120///
121/// Every operation binding and every `source_index` stays where it was, so the rewrite changes which
122/// series a consumer reads and not what the query computes. The result is checked by
123/// [`NativeTree::try_new`], because a merge has to sit over an evaluated vector and the pass may
124/// only put it there.
125pub fn merge_label_rewrites(
126 tree: &NativeTree,
127 source_tags: &[Vec<String>],
128 source_metrics: &[Option<Arc<str>>],
129) -> DfResult<NativeTree> {
130 let root = rewrite(tree.root(), source_tags, source_metrics)?;
131 // The root is a consumer too: whatever reads this tree reads one series per label set.
132 NativeTree::try_new(canonical(root, source_tags, source_metrics))
133}
134
135/// Wraps `node` in a [`NativeExpr::Merge`] when its pieces can share a label set.
136///
137/// Three things have to hold, and each is asked rather than assumed:
138///
139/// - the node's output is an evaluated vector, because a merge binds samples on a grid and a raw
140/// scan, a scalar and aggregate state have nothing it could take;
141/// - the node can hand over two series of one label set
142/// ([`duplicates_canonical_labels`]), because collecting pieces that are already distinct is a
143/// barrier that buys nothing;
144/// - it is not already a merge, which would collect what is already collected.
145fn canonical(
146 node: NativeNode,
147 source_tags: &[Vec<String>],
148 source_metrics: &[Option<Arc<str>>],
149) -> NativeNode {
150 if !matches!(&node.output, NativeType::Samples(schema) if schema.eval_grid.is_some()) {
151 return node;
152 }
153 if matches!(node.expr, NativeExpr::Merge { .. }) {
154 return node;
155 }
156 if !duplicates_canonical_labels(&node, source_tags, source_metrics) {
157 return node;
158 }
159 // A merge reports its input's layout: the same fields on the same grid.
160 let output = node.output.clone();
161 NativeNode {
162 expr: NativeExpr::Merge {
163 input: Box::new(node),
164 },
165 output,
166 }
167}
168
169/// Rewrites `node` bottom-up: its children first, then the merge its own consumer contract needs of
170/// them.
171fn rewrite(
172 node: &NativeNode,
173 source_tags: &[Vec<String>],
174 source_metrics: &[Option<Arc<str>>],
175) -> DfResult<NativeNode> {
176 let expr = match &node.expr {
177 // A source is the boundary it was bound to and there is nothing below it to rewrite. A
178 // constant reads nothing.
179 NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {
180 node.expr.clone()
181 }
182 // A selection reads raw samples, one whole storage series at a time, and stamps them onto a
183 // grid; a timestamp replaces each value with its sample's time. Both read each piece as it
184 // is, so neither collects what it reads.
185 NativeExpr::Instant { input, op } => NativeExpr::Instant {
186 input: Box::new(rewrite(input, source_tags, source_metrics)?),
187 op: op.clone(),
188 },
189 NativeExpr::Timestamp { input } => NativeExpr::Timestamp {
190 input: Box::new(rewrite(input, source_tags, source_metrics)?),
191 },
192 // A merge is the canonicalizer itself, so it asks nothing of its input: fragments are what it
193 // was written to receive.
194 NativeExpr::Merge { input } => NativeExpr::Merge {
195 input: Box::new(rewrite(input, source_tags, source_metrics)?),
196 },
197 // A window folds a range of one series' samples and hands the answer over as that series, so
198 // it reads the series whole. Over a raw scan the pieces are whole storage series already and
199 // the merge above is a no-op; over an evaluated vector a rewrite can have aliased them.
200 NativeExpr::Window { input, op } => NativeExpr::Window {
201 input: Box::new(canonical(
202 rewrite(input, source_tags, source_metrics)?,
203 source_tags,
204 source_metrics,
205 )),
206 op: op.clone(),
207 },
208 // A map is point-wise, but a point can drop out of its output: the histogram functions drop
209 // float samples, math drops native histograms, and a parameterized clamp can empty a point.
210 // The occupancy that tells two pieces of one label set apart is the rewritten frame's, so a
211 // merge above this map would be handed an occupancy the map may already have erased - the
212 // pieces have to be collected where they still hold their samples, below it.
213 NativeExpr::Map { input, op } => NativeExpr::Map {
214 input: Box::new(canonical(
215 rewrite(input, source_tags, source_metrics)?,
216 source_tags,
217 source_metrics,
218 )),
219 op: op.clone(),
220 },
221 // A parameterized map's parameters are scalars, rewritten but never collected - a scalar
222 // carries no label set. Its input is read point-wise like a map's and, for the same reason,
223 // its pieces are collected below it rather than above it.
224 NativeExpr::ParameterizedMap {
225 input,
226 op,
227 parameters,
228 } => NativeExpr::ParameterizedMap {
229 input: Box::new(canonical(
230 rewrite(input, source_tags, source_metrics)?,
231 source_tags,
232 source_metrics,
233 )),
234 op: *op,
235 parameters: parameters
236 .iter()
237 .map(|parameter| rewrite(parameter, source_tags, source_metrics))
238 .collect::<DfResult<Vec<_>>>()?,
239 },
240 // A fold answers its groups, so two pieces of one series in a group are summed as if the
241 // query had written them twice: the merge is what makes one series arrive as one.
242 NativeExpr::Aggregate { input, op } => NativeExpr::Aggregate {
243 input: Box::new(canonical(
244 rewrite(input, source_tags, source_metrics)?,
245 source_tags,
246 source_metrics,
247 )),
248 op: op.clone(),
249 },
250 // The same fold with its argument read per point: the pieces of one series in a group are
251 // as much a problem for a quantile as for a sum, and its parameter is a scalar, rewritten
252 // but never collected - a scalar carries no label set.
253 NativeExpr::ParameterizedAggregate {
254 input,
255 op,
256 parameter,
257 } => NativeExpr::ParameterizedAggregate {
258 input: Box::new(canonical(
259 rewrite(input, source_tags, source_metrics)?,
260 source_tags,
261 source_metrics,
262 )),
263 op: op.clone(),
264 parameter: Box::new(rewrite(parameter, source_tags, source_metrics)?),
265 },
266 // Vector operations consume canonical series: ranking counts them, and presence checks and
267 // folds must not silently consume overlapping fragments that a merge would reject.
268 NativeExpr::Vector { input, op } => NativeExpr::Vector {
269 input: Box::new(canonical(
270 rewrite(input, source_tags, source_metrics)?,
271 source_tags,
272 source_metrics,
273 )),
274 op: op.clone(),
275 },
276 // Each side of a binary or set operation is matched by label on its own, so each is
277 // canonicalized on its own. A constant side has nothing to canonicalize and a merge could not
278 // sit over one, which `canonical` leaves it as.
279 NativeExpr::Binary {
280 left,
281 right,
282 matching,
283 } => NativeExpr::Binary {
284 left: Box::new(canonical(
285 rewrite(left, source_tags, source_metrics)?,
286 source_tags,
287 source_metrics,
288 )),
289 right: Box::new(canonical(
290 rewrite(right, source_tags, source_metrics)?,
291 source_tags,
292 source_metrics,
293 )),
294 matching: matching.clone(),
295 },
296 NativeExpr::Set { left, right, op } => NativeExpr::Set {
297 left: Box::new(canonical(
298 rewrite(left, source_tags, source_metrics)?,
299 source_tags,
300 source_metrics,
301 )),
302 right: Box::new(canonical(
303 rewrite(right, source_tags, source_metrics)?,
304 source_tags,
305 source_metrics,
306 )),
307 op: op.clone(),
308 },
309 // `info` pairs each base series with the info series that share its identifying labels, so it
310 // reads both sides whole: the pieces of one label set have to be one series before they are
311 // matched.
312 NativeExpr::Info {
313 base,
314 info,
315 selector,
316 } => NativeExpr::Info {
317 base: Box::new(canonical(
318 rewrite(base, source_tags, source_metrics)?,
319 source_tags,
320 source_metrics,
321 )),
322 info: Box::new(canonical(
323 rewrite(info, source_tags, source_metrics)?,
324 source_tags,
325 source_metrics,
326 )),
327 selector: selector.clone(),
328 },
329 // `vector(s)` builds its series from a scalar, which carries no label set to collect.
330 NativeExpr::VectorOf { input } => NativeExpr::VectorOf {
331 input: Box::new(rewrite(input, source_tags, source_metrics)?),
332 },
333 // `scalar()` answers from the whole vector: a series that arrives in pieces would be seen
334 // as several samples, so the pieces are collected where they still hold their samples.
335 NativeExpr::ScalarOf { input } => NativeExpr::ScalarOf {
336 input: Box::new(canonical(
337 rewrite(input, source_tags, source_metrics)?,
338 source_tags,
339 source_metrics,
340 )),
341 },
342 // `topk` ranks the whole vector, so it counts canonical series; its parameter is a scalar,
343 // rewritten but never collected - a scalar carries no label set.
344 NativeExpr::ParameterizedTopK {
345 input,
346 op,
347 parameter,
348 } => NativeExpr::ParameterizedTopK {
349 input: Box::new(canonical(
350 rewrite(input, source_tags, source_metrics)?,
351 source_tags,
352 source_metrics,
353 )),
354 op: op.clone(),
355 parameter: Box::new(rewrite(parameter, source_tags, source_metrics)?),
356 },
357 // A histogram function folds the bucket series of one histogram, so overlapping fragments
358 // must not reach it; its parameters are scalars and only need rewriting.
359 NativeExpr::ParameterizedHistogram {
360 input,
361 op,
362 parameters,
363 } => NativeExpr::ParameterizedHistogram {
364 input: Box::new(canonical(
365 rewrite(input, source_tags, source_metrics)?,
366 source_tags,
367 source_metrics,
368 )),
369 op: op.clone(),
370 parameters: parameters
371 .iter()
372 .map(|parameter| rewrite(parameter, source_tags, source_metrics))
373 .collect::<DfResult<Vec<_>>>()?,
374 },
375 };
376 Ok(NativeNode {
377 expr,
378 output: node.output.clone(),
379 })
380}