promql/extension_plan/series_execution.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//! The in-process handover between two adjacent native PromQL operators.
16//!
17//! Two native operators pass each other a `SeriesFrame` record batch today: the producer packs its
18//! chunks into one and the consumer unpacks them again, only because
19//! [`ExecutionPlan::execute`] answers a `SendableRecordBatchStream`. No DataFusion operator stands
20//! between them, so the frame is written and read back for nobody: a transport type used for a
21//! function call.
22//!
23//! [`SeriesExecutionPlan`] is that call. A native operator that can answer its chunks as they are
24//! implements the trait, and a native consumer that receives one calls
25//! [`SeriesExecutionPlan::execute_series`] instead of decoding a frame. The chunk is the internal
26//! value the operator already holds - a [`RawSeriesChunk`] read from a region, an
27//! [`EvaluatedChunk`] a tree settled on its grid, or a [`StateChunk`] a `Partial` folded - so the
28//! handover reuses the buffers instead of encoding them. Every content a native node publishes
29//! travels this way; there is no second path for one of them to be left on.
30//!
31//! What keeps the shortcut structural, rather than a convention an operator has to remember, is
32//! that the capability is a type: [`series_execution_plan`] answers for the operators this crate
33//! implements it on and for nothing else. A plan that produces frames is not one of them - a
34//! network exchange, a remote scan, or any node reading a frame it received answers `None` - so no
35//! chunk reaches a consumer across a boundary this way. The question is asked once per input and
36//! answered by the input alone: calling [`execute_series`](SeriesExecutionPlan::execute_series) is
37//! how a consumer says it reads that input's chunks, and calling
38//! [`ExecutionPlan::execute`] is how it says it reads its frames. There is no second decision to
39//! keep in step with the first.
40//!
41//! Which edge this is, and which edge it is not:
42//!
43//! - In process: the two ends are nodes of one plan in one process, and the consumer called
44//! [`execute_series`](SeriesExecutionPlan::execute_series) on the operator it was handed as an
45//! input. That is the whole of where a chunk can travel.
46//! - Still bytes: every edge that leaves the process, or reaches a node this crate does not own. A
47//! region's scan and the scan a merge sits on still publish `RecordBatch`es, a remote scan answers
48//! frames, and a root output still converts series back into a batch (`series_to_record_batch`).
49//! No chunk is serialized and none is sent anywhere, so nothing about the wire changes here.
50//!
51//! Two things the frame path does are not skipped, because they are not about the encoding:
52//!
53//! - The sequence is checked. [`SequenceValidator`] and [`EvaluatedSequenceValidator`] are what a
54//! frame consumer runs while it decodes; [`checked_series_stream`] runs the same validators over
55//! the same sequence of chunks, so a producer whose chains are malformed is refused here exactly
56//! as it is through a frame. An exported state row has no such chain - its frame consumer runs no
57//! cross-row validator either - so there is nothing for that content to skip.
58//! - The memory is charged for as long as it is held. A producer that merges an identity reserves
59//! the bytes it merges into and hands them over with the value ([`SeriesCharge`]), so the pool
60//! sees them until the consumer drops the chunk that carries them - not until a packer flushed a
61//! batch, and not for longer either.
62//!
63//! What a consumer records does not change with the representation. The figures a native node keeps
64//! are recorded per chunk it was fed, and both paths feed it the producer's chunks: a frame carries
65//! a chunk as a row, and decoding it yields the chunk back. The one figure that can differ is the
66//! count of those chunks, and only for a chunk whose field is itself split into segments - a frame
67//! row never spans two segments of one field, so such a chunk is one chunk in process and several
68//! rows in a frame. Nothing else, and in particular no sample, value or closed-series count, is
69//! recorded on one path and not the other.
70
71use std::any::Any;
72use std::pin::Pin;
73use std::sync::Arc;
74use std::task::{Context, Poll};
75
76use common_error::ext::BoxedError;
77use common_query::series_frame::{EvaluatedSequenceValidator, SequenceValidator};
78use datafusion::error::Result as DataFusionResult;
79use datafusion::execution::context::TaskContext;
80use datafusion::execution::memory_pool::MemoryReservation;
81use datafusion::physical_plan::ExecutionPlan;
82use datatypes::series::SeriesOrdering;
83use datatypes::series::raw::RawSeriesChunk;
84use futures::Stream;
85
86use crate::evaluated::EvaluatedChunk;
87use crate::extension_plan::RawSeriesSourceExec;
88use crate::extension_plan::fused_series::FusedSeriesExec;
89use crate::extension_plan::series_repartition::SeriesRepartitionExec;
90use crate::native::state::StateChunk;
91
92/// One piece of one series, handed from one native operator to the next.
93///
94/// The variants are the three contents the native chain passes between its nodes: raw samples read
95/// from a region, values a tree evaluated on the grid its output declares, and one group's exported
96/// aggregate state. [`EvaluatedChunk`] is [`Series`](datatypes::series::samples::Series) plus the
97/// finality of the chunk, so it is the evaluated half of this enum rather than a `Series` alone: a
98/// chunk that cannot say whether it closes its series would make the consumer guess, and "no value
99/// here" and "nothing more here" would become the same thing.
100///
101/// [`SeriesChunk::State`] is the chunk a producer's aggregate already produces, with no conversion
102/// on the way: a `Partial` hands over the groups it folded, on the layout it exported them with, and
103/// a `Final` merges that chunk exactly as it merges the row a region's frame decodes to - the two
104/// sources meet inside the merge kernel, not at this boundary.
105#[derive(Debug)]
106pub enum SeriesChunk {
107 /// One scan series, with its own timestamps and its finality.
108 Raw(RawSeriesChunk),
109 /// Values a producer already evaluated on the grid its frame declares.
110 Evaluated(EvaluatedChunk),
111 /// The aggregate state its producer exported: the groups a `Partial` folded, or the row a
112 /// frame-fed producer decoded, as [`StateChunk`] carries them.
113 State(StateChunk),
114}
115
116/// What one handed chunk is charged to, released when the chunk is.
117///
118/// A producer that holds a value on behalf of a consumer has to hold the pool's reservation for it
119/// too: the bytes are live, so the pool must not hand them to anybody else. The frame path keeps
120/// them in the packer's handoff until the batch they back is flushed; a chunk handed over in
121/// process keeps them here, so they are released exactly when the consumer drops the value they
122/// account for - never earlier, which would let the pool over-commit, and never for longer, which
123/// would hold memory for a chunk nobody has.
124///
125/// Two shapes of reservation make up that total. An owner reserves the charges its inputs carried,
126/// the descriptor naming the identity, and the workspace it merged or reconstructed into - all of
127/// them its own. A state export reserves one batch that several rows are cut from, so those rows
128/// share it instead of each holding a copy: that is what [`SeriesCharge::shared`] is, and it is
129/// released when the last chunk holding it is dropped. Dropping this value is the whole of what
130/// makes either release correct - there is no call to forget - which is why the fields are named as
131/// fields nothing reads: holding them is the entire job. The packer's handoff named its own
132/// reservations the same way, for the same reason.
133#[derive(Debug)]
134pub struct SeriesCharge {
135 /// The reservations this publication holds outright.
136 _owned: Vec<MemoryReservation>,
137 /// The reservations it shares with the other chunks cut from the same publication.
138 _shared: Vec<Arc<MemoryReservation>>,
139}
140
141impl SeriesCharge {
142 /// The charge of one owner publication.
143 pub(crate) fn new(
144 fragments: Vec<MemoryReservation>,
145 descriptor: MemoryReservation,
146 workspace: Option<MemoryReservation>,
147 ) -> Self {
148 let mut owned = fragments;
149 owned.push(descriptor);
150 owned.extend(workspace);
151 Self {
152 _owned: owned,
153 _shared: Vec::new(),
154 }
155 }
156
157 /// The charge of a publication that several chunks are cut from.
158 ///
159 /// Each of those chunks holds a clone of every reservation here, so the bytes stay charged for
160 /// as long as any of them is alive and are released when the last one is dropped.
161 pub(crate) fn shared(shared: Vec<Arc<MemoryReservation>>) -> Self {
162 Self {
163 _owned: Vec::new(),
164 _shared: shared,
165 }
166 }
167
168 /// Every reservation this charge holds, as references a publication can be cut into.
169 ///
170 /// A consumer that receives a publication and hands its parts on - a router that routes each
171 /// group to its owner - cannot keep the charge itself: the charge has to travel with the parts,
172 /// or the bytes it accounts for would be released while the parts are still held. This is the
173 /// one conversion that makes that possible from outside this type, whose fields stay private so
174 /// nothing else can drop a reservation early either.
175 pub(crate) fn into_shared(self) -> Vec<Arc<MemoryReservation>> {
176 let mut shared = self._shared;
177 shared.extend(self._owned.into_iter().map(Arc::new));
178 shared
179 }
180}
181
182/// One chunk handed over in process, and what it is charged to.
183///
184/// The charge travels with the value rather than beside the stream, so a consumer cannot release a
185/// chunk's reservation while it still holds the chunk, and cannot drop the chunk while keeping the
186/// reservation either. A consumer that only reads the chunk and forgets it leaks nothing.
187#[derive(Debug)]
188pub struct HandedSeriesChunk {
189 chunk: SeriesChunk,
190 charge: Option<SeriesCharge>,
191}
192
193impl HandedSeriesChunk {
194 /// A chunk nothing is charged to.
195 ///
196 /// A producer that holds no reservation of its own - a decode of scan output, whose read is
197 /// charged where it happens - hands its values over like this.
198 pub fn uncharged(chunk: SeriesChunk) -> Self {
199 Self {
200 chunk,
201 charge: None,
202 }
203 }
204
205 /// A chunk the producer reserved `charge` for, held until this value is dropped.
206 pub fn charged(chunk: SeriesChunk, charge: SeriesCharge) -> Self {
207 Self {
208 chunk,
209 charge: Some(charge),
210 }
211 }
212
213 /// The chunk itself, borrowed for a check that keeps the charge in place.
214 pub fn chunk(&self) -> &SeriesChunk {
215 &self.chunk
216 }
217
218 /// The chunk and the charge it carries, both to be held as long as the consumer reads it.
219 pub fn into_parts(self) -> (SeriesChunk, Option<SeriesCharge>) {
220 (self.chunk, self.charge)
221 }
222}
223
224/// One partition's output as internal series, not as an encoded frame.
225///
226/// The error is the boxed error the internal series streams already report, so a chunk stream
227/// composes with [`SendableRawSeriesStream`] and
228/// [`SendableEvaluatedSeriesStream`](common_query::series_frame::SendableEvaluatedSeriesStream)
229/// without translating it.
230///
231/// [`SendableRawSeriesStream`]: store_api::region_engine::SendableRawSeriesStream
232pub type SendableSeriesStream =
233 Pin<Box<dyn Stream<Item = Result<HandedSeriesChunk, BoxedError>> + Send>>;
234
235/// A native operator that can hand its output over in-process without encoding a frame.
236///
237/// Implementing this is a statement about what the operator *is*: it runs in the same process as
238/// its consumer, and what it produces is an internal value rather than a message. A node that reads
239/// or writes a frame as its contract - a scan answering another process, an output boundary - must
240/// not implement it, and [`series_execution_plan`] is the one place a consumer asks.
241///
242/// [`ExecutionPlan::execute`] stays the whole answer for every consumer that is not native: an
243/// implementor still publishes its frames, packed from what it hands over here, so a plan with a
244/// foreign operator in the middle keeps working and is merely slower.
245pub trait SeriesExecutionPlan: ExecutionPlan {
246 /// This plan as [`Any`], so a plan reached through this trait can still be asked which
247 /// concrete operator it is.
248 ///
249 /// The obvious spelling of that question - `downcast_ref::<dyn SeriesExecutionPlan>()` on a
250 /// `&dyn Any` - cannot be written, and not because of anything this trait does:
251 /// [`Any::downcast_ref`] requires `T: Sized` and compares the type id of a concrete type, so a
252 /// trait object is not a target it accepts. The standard answer is the one here: the trait
253 /// exposes its object as `dyn Any` and the caller names the concrete type it wants, which is
254 /// sized by construction. This is the same shape [`ExecutionPlan`] uses for its own downcasts,
255 /// and it is a method on the trait rather than a `where Self: Sized` helper because it has to
256 /// be callable on the trait object - the caller is a consumer holding
257 /// `&dyn SeriesExecutionPlan`, which is exactly the value that is not sized.
258 fn as_any(&self) -> &dyn Any;
259
260 /// One partition's output as internal series, not as a `RecordBatch`.
261 ///
262 /// The stream carries each chunk with what it is charged to
263 /// ([`HandedSeriesChunk`]), so nothing a producer reserved is released behind the consumer's
264 /// back: a consumer holds the reservation exactly as long as it holds the chunk.
265 fn execute_series(
266 &self,
267 partition: usize,
268 ctx: Arc<TaskContext>,
269 ) -> DataFusionResult<SendableSeriesStream>;
270}
271
272/// `plan` as a native series operator, when it is one.
273///
274/// This is the guard a native consumer asks before it decides how to read its input, and it is
275/// deliberately the list of operators this crate implements the trait on: a plan that is not in
276/// the list is read as frames, so a consumer's fast path can never outrun the operators that
277/// support it. It is the *only* place that decision is made - a consumer that asks this per input
278/// has nothing to keep in step with it, and no plan is read in process because something else said
279/// so.
280///
281/// The obvious spelling - erasing the plan and asking it for `dyn SeriesExecutionPlan` - cannot be
282/// written, and not because of the DataFusion this crate builds against:
283/// [`Any::downcast_ref`] wants `T: Sized` and compares the type id of a concrete type, so a trait
284/// object can never be its target and the call would not compile anywhere. The check therefore
285/// names the concrete implementors it accepts, one `downcast_ref` per operator, which is why the
286/// trait exposes [`SeriesExecutionPlan::as_any`] and why the question below starts from `dyn Any`
287/// rather than from `dyn ExecutionPlan`: this DataFusion's [`ExecutionPlan`] declares no `as_any`,
288/// but it is [`Any`], so the view is one upcast away. The decision stays in this one function: a
289/// new implementor is added here, and until it is, a consumer reads that plan as frames.
290pub fn series_execution_plan(plan: &dyn ExecutionPlan) -> Option<&dyn SeriesExecutionPlan> {
291 let plan: &dyn Any = plan;
292 if let Some(source) = plan.downcast_ref::<RawSeriesSourceExec>() {
293 return Some(source as &dyn SeriesExecutionPlan);
294 }
295 // A router is asked for every content it publishes: an owner's merged raw identity, the series
296 // an owner settled on its grid, and the groups an owner exported are all values this crate
297 // holds, so all three are read in process and none of them is left on a frame path.
298 if let Some(router) = plan.downcast_ref::<SeriesRepartitionExec>() {
299 return Some(router as &dyn SeriesExecutionPlan);
300 }
301 // A fused node answers with a frame - of values, or of the state a `Partial` folded - and that
302 // is a chunk another native operator reads. A node answering a row table is the query's answer
303 // instead, and only `execute` hands that out.
304 plan.downcast_ref::<FusedSeriesExec>()
305 .filter(|fused| fused.hands_over_series())
306 .map(|fused| fused as &dyn SeriesExecutionPlan)
307}
308
309/// `chunks` with the sequence check the frame path runs, applied to each chunk as it arrives.
310///
311/// A consumer that decodes a frame validates the sequence it receives - a chain that never closes,
312/// a key that recurs after its final chunk, timestamps that go back across chunks, keys that go back
313/// under key-then-time order - because the frame may have been written by another process.
314/// [`pack_raw_series`](common_query::series_frame::pack_raw_series) and
315/// [`unpack_raw_series`](common_query::series_frame::unpack_raw_series) run that check on both ends,
316/// and the evaluated packer and unpacker run its evaluated counterpart. A consumer handed the
317/// chunks themselves has no frame to decode and no other process to distrust, but the producer can
318/// still be wrong: a router publishes what its owners merged, and a second publication of one
319/// identity would be as wrong in process as it is across a frame. So the same validators run here,
320/// over the same sequence, and the shortcut refuses what the frame would have refused.
321///
322/// A state publication is the one content with no such check to run, on either path: the frame
323/// consumer's state stream decodes each exported row and hands it on, so there is nothing it would
324/// refuse that the handover must refuse too. What both paths do enforce is enforced where the row is
325/// decoded - in the producer's handover stream - and this stream passes state rows through.
326///
327/// `raw_ordering` is the ordering the producer declares for its raw frames - the one a decoding
328/// consumer would read out of the frame schema. It is not inferred from the chunks.
329pub fn checked_series_stream(
330 chunks: SendableSeriesStream,
331 raw_ordering: SeriesOrdering,
332) -> SendableSeriesStream {
333 Box::pin(CheckedSeries {
334 chunks: Some(chunks),
335 raw: SequenceValidator::new(raw_ordering),
336 evaluated: EvaluatedSequenceValidator::new(),
337 })
338}
339
340/// The handover stream, with the frame path's sequence check in front of the consumer.
341struct CheckedSeries {
342 /// The producer's stream, or `None` once this one ended.
343 chunks: Option<SendableSeriesStream>,
344 /// The check a raw consumer of this input would run, at this input's declared ordering.
345 raw: SequenceValidator,
346 /// The check an evaluated consumer of this input would run.
347 evaluated: EvaluatedSequenceValidator,
348}
349
350impl Stream for CheckedSeries {
351 type Item = Result<HandedSeriesChunk, BoxedError>;
352
353 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
354 let this = &mut *self;
355 let Some(chunks) = this.chunks.as_mut() else {
356 return Poll::Ready(None);
357 };
358 let handed = match chunks.as_mut().poll_next(cx) {
359 Poll::Pending => return Poll::Pending,
360 Poll::Ready(Some(Err(error))) => {
361 this.chunks = None;
362 return Poll::Ready(Some(Err(error)));
363 }
364 // The producer ended, so the check that only an end can make is made here: a chain
365 // still open when the stream stopped is the failure the frame path reports as well.
366 Poll::Ready(None) => {
367 this.chunks = None;
368 let checked = this.raw.finish().and_then(|()| this.evaluated.finish());
369 return Poll::Ready(checked.err().map(|error| Err(checked_error(error))));
370 }
371 Poll::Ready(Some(Ok(handed))) => handed,
372 };
373 let checked = match handed.chunk() {
374 SeriesChunk::Raw(chunk) => this.raw.validate(chunk),
375 SeriesChunk::Evaluated(chunk) => this.evaluated.validate(&chunk.series, chunk.is_last),
376 // A state publication has no chain of chunks to check, on either path: the frame
377 // consumer's state stream decodes each exported row and hands it on, running no
378 // cross-row validator at all, so there is nothing it would refuse that this would
379 // accept. What both paths do enforce - the declaration is this revision's, the batch
380 // carries the declared schema, and the declared ordering is contiguous - is enforced
381 // where the row is decoded, in the producer's handover stream.
382 SeriesChunk::State(_) => Ok(()),
383 };
384 match checked {
385 Ok(()) => Poll::Ready(Some(Ok(handed))),
386 Err(error) => {
387 // Nothing more is read from a producer whose sequence is broken: the frame path
388 // drops its decoder at the same point.
389 this.chunks = None;
390 Poll::Ready(Some(Err(checked_error(error))))
391 }
392 }
393 }
394}
395
396/// The error a broken chunk sequence is reported as, in the handover's own error type.
397fn checked_error(error: datafusion::error::DataFusionError) -> BoxedError {
398 BoxedError::new(common_query::error::Error::from(error))
399}
400
401#[cfg(test)]
402mod tests;