Skip to main content

common_query/
series_frame.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//! Streaming boundary between finite raw-series chunks and DataFusion record batches.
16//!
17//! Schema fields identify the ordered logical payload fields and codec layout; additional
18//! application metadata is permitted when stable across the stream. A key-encoded frame also
19//! declares its own label decode description, and the frame is the sole source of decode
20//! information: [`unpack_raw_series`] reads the fields, the label mode, the description, and the
21//! producer ordering from the received schema, keeps the description on the returned stream, and
22//! therefore needs no [`RawLabelSource`]. A caller that holds a scan-bound identity — the physical
23//! region key layout a decoded identity came from — compares that identity's declared label
24//! decode layout with [`ensure_frame_matches_label_source`] instead of passing it as a decode
25//! input; that comparison is equality of the description alone and proves nothing about region
26//! identity or provenance, and neither side is authenticated as field provenance. This adapter
27//! preserves
28//! scan candidates only; it is not a residual filter, authorization check, remote transport, or
29//! compaction boundary. Raw frames accept all three [`SeriesOrdering`] declarations, while evaluated
30//! frames accept only `Contiguous`. Raw `Interleaved` supports independently closed producer
31//! fragment chains in sequence, including recurring keys; it does not multiplex open chains.
32//!
33//! An evaluated frame is the same physical family: [`pack_evaluated_series`] and
34//! [`unpack_evaluated_series`] carry computed values under complete labels and grid positions, so a
35//! compute consumer needs neither a storage key nor a scan binding to read them.
36
37use std::future::Future;
38use std::pin::Pin;
39use std::sync::Arc;
40use std::task::{Context, Poll};
41use std::time::Duration;
42
43use common_error::ext::BoxedError;
44use common_recordbatch::{DfRecordBatch, DfSendableRecordBatchStream};
45use datafusion_common::DataFusionError;
46use datatypes::arrow::datatypes::{Schema as ArrowSchema, SchemaRef as ArrowSchemaRef};
47use datatypes::error::InvalidSeriesSnafu;
48use datatypes::series::aggregate_state::{AggregateStateSchema, StateSeries};
49use datatypes::series::frame::{
50    FrameContent, FrameLabelMode, LABEL_DECODE_VERSION, LabelDecodeColumn, LabelDecodeEncoding,
51    LabelDecodeSpec, LabelDecodeTag, SeriesFrameBuilder, SeriesFrameCursor, SeriesFrameDeclaration,
52    SeriesFrameDecoder, StateFrameRow, series_frame_label_decode, series_frame_schema,
53};
54use datatypes::series::raw::RawSeriesChunk;
55use datatypes::series::samples::{Series, SeriesSchema};
56use datatypes::series::{SeriesLabels, SeriesOrdering};
57use futures_util::Stream;
58use store_api::codec::PrimaryKeyEncoding;
59use store_api::region_engine::{
60    NO_BOUND_LABEL_SOURCE, RawLabelSource, RawSeriesStream, SendableRawSeriesStream,
61};
62use tokio::time::{Instant, Sleep};
63
64#[cfg(test)]
65mod tests;
66
67const ORDERING_KEY: &str = "greptime.series.ordering";
68
69/// A stream of evaluated series chunks and their finality.
70///
71/// The pair is what an evaluated producer has and an evaluated consumer needs: the values on their
72/// absolute grid positions, and whether this chunk closed the chain it belongs to. It is deliberately
73/// not a third runtime chunk type - `Series` is the runtime value, and finality is the one fact a
74/// chunk has to carry besides it.
75pub type SendableEvaluatedSeriesStream =
76    Pin<Box<dyn Stream<Item = Result<(Series, bool), BoxedError>> + Send>>;
77
78/// A stream of aggregate-state chunks and their producer-local finality.
79///
80/// Export accepts the existing field-major [`StateSeries`] representation and columnarises each
81/// chunk once. Import is intentionally asymmetric: [`SendableStateFrameStream`] retains typed Arrow
82/// handles so consumers do not rebuild a nested state tree.
83pub type SendableStateSeriesStream =
84    Pin<Box<dyn Stream<Item = Result<(StateSeries, bool), BoxedError>> + Send>>;
85
86/// A stream of decoded state rows retaining typed handles into their Arrow batch.
87pub type SendableStateFrameStream =
88    Pin<Box<dyn Stream<Item = Result<StateFrameRow, BoxedError>> + Send>>;
89
90/// Builds the canonical raw frame schema with the producer's label binding and ordering.
91///
92/// Ordering records a producer guarantee; it is not inferred from frame contents. The label binding
93/// determines both the label mode and, for a primary-key binding, the self-describing label decode
94/// description written into the schema, so a frame can never declare a label layout it does not
95/// describe.
96pub fn raw_series_frame_schema_with_ordering(
97    schema: &SeriesSchema,
98    label_source: &RawLabelSource,
99    ordering: SeriesOrdering,
100) -> datafusion_common::Result<ArrowSchemaRef> {
101    if schema.eval_grid.is_some() {
102        return Err(invalid(
103            "a raw frame cannot carry a schema with an evaluation grid",
104        ));
105    }
106    frame_schema_with(
107        schema,
108        label_mode(label_source),
109        label_decode_spec(label_source).as_ref(),
110        ordering,
111    )
112}
113
114/// Assembles a declared frame schema from an explicit label mode and decode description.
115///
116/// The mode and description pair is checked by [`series_frame_schema`], so a key mode without a
117/// description and an explicit mode with one are both rejected here instead of reaching the wire.
118/// A node that re-declares its child's frame and publishes under that declaration uses this: the
119/// declaration has to survive the round trip, and this is the one place that decides what it is.
120pub fn frame_schema_with(
121    schema: &SeriesSchema,
122    mode: FrameLabelMode,
123    decode: Option<&LabelDecodeSpec>,
124    ordering: SeriesOrdering,
125) -> datafusion_common::Result<ArrowSchemaRef> {
126    // An evaluated frame has no storage key to be ordered by, so the only claim it can honour is
127    // that each chain is contiguous. Writing a stronger one would produce a frame the reader refuses
128    // and a plan that fails where it could have been refused.
129    if schema.eval_grid.is_some() {
130        ensure_contiguous_ordering(ordering)?;
131    }
132    let ordering = match ordering {
133        SeriesOrdering::Contiguous => "contiguous",
134        SeriesOrdering::KeyThenTime => "read_key_then_time",
135        SeriesOrdering::Interleaved => "interleaved",
136    };
137    let schema = series_frame_schema(schema, mode, decode).map_err(codec_error)?;
138    let mut metadata = schema.metadata().clone();
139    metadata.insert(ORDERING_KEY.to_string(), ordering.to_string());
140    Ok(Arc::new(ArrowSchema::new_with_metadata(
141        schema.fields().clone(),
142        metadata,
143    )))
144}
145
146/// Derives the label decode description a frame must carry for this binding.
147///
148/// A primary-key binding reduces to exactly what decoding reads: the metric name, the primary-key
149/// encoding, the ordered key columns with their physical types, and the logical tags. Region
150/// metadata guarantees the key list holds every tag column and nothing else, so the description
151/// needs no per-column role. Explicit bindings already carry complete labels and declare no
152/// description.
153///
154/// The result is canonical: its logical tags are in [`LabelDecodeSpec::canonicalize`] order, which
155/// is what the writer serializes, so a derived description and a received one for the same labels
156/// are the same value and the same text. Derivation cannot fail, because a physical type is copied
157/// rather than translated; a description a reader cannot honour is rejected when it is read, and a
158/// decoder rejects the tags it cannot bind.
159pub fn label_decode_spec(source: &RawLabelSource) -> Option<LabelDecodeSpec> {
160    let RawLabelSource::PrimaryKey {
161        metric_name,
162        physical_metadata,
163        logical_tags,
164    } = source
165    else {
166        return None;
167    };
168    let primary_key = physical_metadata
169        .primary_key_columns()
170        .map(|column| LabelDecodeColumn {
171            column_id: column.column_id,
172            name: column.column_schema.name.clone(),
173            physical_type: column.column_schema.data_type.clone(),
174        })
175        .collect();
176    let mut description = LabelDecodeSpec {
177        version: LABEL_DECODE_VERSION,
178        metric_name: metric_name.to_string(),
179        encoding: match physical_metadata.primary_key_encoding {
180            PrimaryKeyEncoding::Dense => LabelDecodeEncoding::Dense,
181            PrimaryKeyEncoding::Sparse => LabelDecodeEncoding::Sparse,
182        },
183        primary_key,
184        logical_tags: logical_tags
185            .iter()
186            .map(|tag| LabelDecodeTag {
187                column_id: tag.column_id,
188                name: tag.name.to_string(),
189            })
190            .collect(),
191    };
192    description.canonicalize();
193    Some(description)
194}
195
196/// Reads the producer ordering declared by a complete v2 frame schema.
197///
198/// Ordering is mandatory stream metadata; it is never inferred from frame contents.
199pub fn series_frame_ordering(schema: &ArrowSchema) -> datafusion_common::Result<SeriesOrdering> {
200    match schema.metadata().get(ORDERING_KEY).map(String::as_str) {
201        Some("contiguous") => Ok(SeriesOrdering::Contiguous),
202        Some("read_key_then_time") => Ok(SeriesOrdering::KeyThenTime),
203        Some("interleaved") => Ok(SeriesOrdering::Interleaved),
204        None | Some(_) => Err(invalid("missing or unknown series ordering")),
205    }
206}
207
208/// Packs a storage raw-series stream into DataFusion record batches incrementally.
209///
210/// Rows accumulate across chunks into batches bounded by the builder's row and estimated payload
211/// limits; one legal oversized row may be emitted alone, and these limits are a work bound, not a
212/// resident-memory cap. A ready batch is yielded without polling the source again.
213///
214/// Buffered rows are published as soon as the source reports `Pending`, i.e. this constructor needs
215/// no timer and works on any executor. A caller that knows its poller is a Tokio runtime with the
216/// time driver enabled may hold buffered rows across a pending period with
217/// [`pack_raw_series_with`].
218///
219/// Even under [`SeriesOrdering::Interleaved`], each producer fragment chain must close before
220/// another starts; arbitrary multiplexing of open chains is rejected. Closed fragment chains may
221/// recur with the same key and overlapping timestamps. Finality closes a producer fragment, not
222/// necessarily the logical series. For `Contiguous`, validation checks adjacent chunk conditions
223/// but does not certify nonadjacent recurrence.
224///
225/// The stream's own declaration is the only decode input: a frame unpacked without a scan-bound
226/// [`RawLabelSource`] round trips unchanged instead of being re-declared from a binding it does not
227/// have, and nothing is derived from a binding here. The declaration also decides the frame's label
228/// mode, so a chunk whose labels disagree with it is rejected when that chunk is coded.
229pub fn pack_raw_series(
230    source: SendableRawSeriesStream,
231) -> datafusion_common::Result<DfSendableRecordBatchStream> {
232    pack_raw_series_with(source, PendingBatching::Immediate)
233}
234
235/// Packs a storage raw-series stream with the pending batching its poller can support.
236///
237/// [`PendingBatching::Immediate`] behaves exactly like [`pack_raw_series`]. [`PendingBatching`]
238/// explains what a caller has to know before asking for a deadline.
239pub fn pack_raw_series_with(
240    source: SendableRawSeriesStream,
241    batching: PendingBatching,
242) -> datafusion_common::Result<DfSendableRecordBatchStream> {
243    let ordering = source.ordering();
244    let schema = source.schema().clone();
245    let decode = source.label_decode_spec().cloned();
246    let labels = declared_label_mode(&decode);
247    // The declared frame schema carries the producer ordering and the label decode description;
248    // every ready batch is published under it, including when no row is ever produced.
249    let frame_schema = frame_schema_with(&schema, labels, decode.as_ref(), ordering)?;
250    let builder = SeriesFrameBuilder::try_new(
251        &schema,
252        labels,
253        decode.as_ref(),
254        SeriesFrameBuilder::DEFAULT_MAX_ROWS,
255        SeriesFrameBuilder::DEFAULT_MAX_BYTES,
256    )
257    .map_err(codec_error)?;
258    Ok(Box::pin(PackStream {
259        source: Some(source),
260        schema,
261        labels,
262        batches: PackBatches::new(builder, frame_schema),
263        ordering,
264        validator: SequenceValidator::new(ordering),
265        pending: PendingFlush::new(batching),
266    }))
267}
268
269/// Packs a stream of evaluated chunks into DataFusion record batches incrementally.
270///
271/// An evaluated frame names its series by their complete labels and addresses time on the evaluation
272/// grid `schema` declares, so there is nothing to decode and no storage key to carry: the frame
273/// declares `explicit` identity and `grid_spans` time, and the grid is written once instead of
274/// repeating timestamps on every row.
275///
276/// Only [`SeriesOrdering::Contiguous`] is declared, because that is the one ordering this layer can
277/// promise and check: each chunk chain is contiguous with itself. A caller that has reason to claim
278/// [`SeriesOrdering::KeyThenTime`] about computed values would have to justify it, and a consumer
279/// must never infer it from the presence of labels.
280///
281/// Bounds, backpressure, and error handling are the raw path's: rows accumulate into batches bounded
282/// by the builder's row and estimated payload limits, a ready batch is yielded before the source is
283/// polled again, and a `Pending` source still delivers what is buffered.
284pub fn pack_evaluated_series(
285    source: SendableEvaluatedSeriesStream,
286    schema: Arc<SeriesSchema>,
287) -> datafusion_common::Result<DfSendableRecordBatchStream> {
288    if schema.eval_grid.is_none() {
289        return Err(invalid(
290            "an evaluated frame needs a schema with an evaluation grid",
291        ));
292    }
293    let frame_schema = frame_schema_with(
294        &schema,
295        FrameLabelMode::Explicit,
296        None,
297        SeriesOrdering::Contiguous,
298    )?;
299    let builder = SeriesFrameBuilder::try_new(
300        &schema,
301        FrameLabelMode::Explicit,
302        None,
303        SeriesFrameBuilder::DEFAULT_MAX_ROWS,
304        SeriesFrameBuilder::DEFAULT_MAX_BYTES,
305    )
306    .map_err(codec_error)?;
307    Ok(Box::pin(PackEvaluatedStream {
308        source: Some(source),
309        schema,
310        batches: PackBatches::new(builder, frame_schema),
311        validator: EvaluatedSequenceValidator::new(),
312    }))
313}
314
315/// Packs aggregate-state chunks into bounded DataFusion record batches.
316///
317/// The producer supplies one [`StateSeries`] per group chunk; the cursor columnarises it into the
318/// frame once. Aggregate state requires a grid, explicit labels and contiguous ordering. The state
319/// schema is revalidated with its own constructor before any stream is returned.
320pub fn pack_aggregate_state(
321    source: SendableStateSeriesStream,
322    state: Arc<AggregateStateSchema>,
323    schema: Arc<SeriesSchema>,
324) -> datafusion_common::Result<DfSendableRecordBatchStream> {
325    if schema.eval_grid.is_none() {
326        return Err(invalid("an aggregate state frame needs an evaluation grid"));
327    }
328    AggregateStateSchema::try_new(state.kind, state.components.to_vec()).map_err(codec_error)?;
329    let frame_schema = datatypes::series::frame::aggregate_state_frame_schema(
330        &state,
331        &schema,
332        FrameLabelMode::Explicit,
333    )
334    .map_err(codec_error)?;
335    let mut metadata = frame_schema.metadata().clone();
336    metadata.insert(ORDERING_KEY.to_string(), "contiguous".to_string());
337    let frame_schema = Arc::new(ArrowSchema::new_with_metadata(
338        frame_schema.fields().clone(),
339        metadata,
340    ));
341    let builder = SeriesFrameBuilder::try_new_aggregate_state(
342        &state,
343        &schema,
344        FrameLabelMode::Explicit,
345        SeriesFrameBuilder::DEFAULT_MAX_ROWS,
346        SeriesFrameBuilder::DEFAULT_MAX_BYTES,
347    )
348    .map_err(codec_error)?;
349    let decoder =
350        SeriesFrameDecoder::try_new_aggregate_state(&state, &schema, FrameLabelMode::Explicit)
351            .map_err(codec_error)?;
352    // Decoding the empty batch validates the exact declared layout before publishing this stream.
353    decoder
354        .decode_aggregate_state(&DfRecordBatch::new_empty(frame_schema.clone()))
355        .map_err(codec_error)?;
356    Ok(Box::pin(PackStateStream {
357        source: Some(source),
358        state,
359        schema,
360        batches: PackBatches::new(builder, frame_schema),
361    }))
362}
363
364/// Unpacks aggregate-state frames while retaining Arrow-backed state rows.
365///
366/// Kind and ordered components must both agree: the kind describes the accumulator semantics while
367/// components describe its physical values. Expected fields and grid are checked independently.
368pub fn unpack_aggregate_state(
369    source: DfSendableRecordBatchStream,
370    expected_state: Option<Arc<AggregateStateSchema>>,
371    expected_series: Option<Arc<SeriesSchema>>,
372) -> datafusion_common::Result<SendableStateFrameStream> {
373    let frame_schema = source.schema();
374    let declaration = SeriesFrameDeclaration::parse(frame_schema.as_ref()).map_err(codec_error)?;
375    if declaration.content() != FrameContent::AggregateState {
376        return Err(invalid(format!(
377            "expected an aggregate state frame, found {}",
378            declaration.content().as_str()
379        )));
380    }
381    ensure_contiguous_ordering(series_frame_ordering(frame_schema.as_ref())?)?;
382    let state = declaration
383        .aggregate_state()
384        .ok_or_else(|| invalid("aggregate state declaration has no aggregate state"))?;
385    if let Some(expected) = expected_state {
386        if state.kind != expected.kind {
387            return Err(invalid(
388                "aggregate state kind does not match expected state",
389            ));
390        }
391        if state.components != expected.components {
392            return Err(invalid(
393                "aggregate state components do not match expected state",
394            ));
395        }
396    }
397    let schema = Arc::new(declaration.series().clone());
398    if let Some(expected) = expected_series {
399        if expected.fields.len() != schema.fields.len()
400            || expected
401                .fields
402                .iter()
403                .zip(schema.fields.iter())
404                .any(|(a, b)| a.name != b.name)
405        {
406            return Err(invalid(
407                "aggregate state fields do not match expected series",
408            ));
409        }
410        if expected.eval_grid.as_ref().map(|grid| grid.spec())
411            != schema.eval_grid.as_ref().map(|grid| grid.spec())
412        {
413            return Err(invalid(
414                "aggregate state grid does not match expected series",
415            ));
416        }
417    }
418    let decoder =
419        SeriesFrameDecoder::try_new_aggregate_state(state, &schema, FrameLabelMode::Explicit)
420            .map_err(codec_error)?;
421    // Validate even empty streams before returning them, rather than deferring declaration errors.
422    decoder
423        .decode_aggregate_state(&DfRecordBatch::new_empty(frame_schema.clone()))
424        .map_err(codec_error)?;
425    Ok(Box::pin(UnpackStateStream {
426        source: Some(source),
427        frame_schema,
428        pending: Vec::new().into_iter(),
429        decoder,
430    }))
431}
432
433/// Unpacks DataFusion batches declared by [`pack_raw_series`].
434///
435/// The frame is the sole source of decode information: the payload fields, the label mode, the
436/// label decode description, and the producer ordering are all read from the stream's own schema,
437/// so unpacking a frame a producer wrote needs no local copy of its binding. Like packing, unpacking
438/// accepts `Interleaved` only when every producer fragment chain closes before the next starts; it
439/// rejects multiplexed open chains. Closed fragment chains may recur with the same key and overlapping
440/// timestamps. Validation does not certify nonadjacent recurrence for `Contiguous` ordering.
441///
442/// Every frame is validated here, unconditionally. The declared layout must be this revision's, the
443/// label decode description must parse, name a known version, and agree with the declared label
444/// mode - a key frame must declare one and an explicit frame must not, since explicit labels are
445/// already complete. The declared fields and the empty batch are then decoded once, so a stream that
446/// could not be decoded is rejected before it is returned.
447///
448/// A frame that declares evaluated content is refused here, before anything is read: a raw consumer
449/// reads timestamps rather than grid positions, so the two contents are not interchangeable.
450///
451/// `expected` is a check, never an input. When it is given it must name the same logical fields in
452/// the same order and the same evaluation grid as the frame declares - which for a raw frame is that
453/// both sides carry none - and a mismatch is an error. The decoder and the returned stream's schema
454/// are built from the frame either way, so a caller cannot supply a field layout the frame does not
455/// declare.
456pub fn unpack_raw_series(
457    source: DfSendableRecordBatchStream,
458    expected: Option<Arc<SeriesSchema>>,
459) -> datafusion_common::Result<SendableRawSeriesStream> {
460    let frame_schema = source.schema();
461    let declaration = SeriesFrameDeclaration::parse(frame_schema.as_ref()).map_err(codec_error)?;
462    if declaration.content() != FrameContent::Raw {
463        return Err(invalid("expected a raw frame, found an evaluated one"));
464    }
465    let labels = declaration.labels();
466    let declared = declaration.label_decode().cloned();
467    let schema = Arc::new(declaration.series().clone());
468    if let Some(expected) = &expected {
469        ensure_declared_schema(&schema, expected)?;
470    }
471    let ordering = series_frame_ordering(frame_schema.as_ref())?;
472    let decoder =
473        SeriesFrameDecoder::try_new(&schema, labels, declared.as_ref()).map_err(codec_error)?;
474    // Validate even empty streams' declared schema and layout before returning the stream.
475    let empty = DfRecordBatch::new_empty(frame_schema.clone());
476    decoder.decode_raw(&empty).map_err(codec_error)?;
477    Ok(Box::pin(UnpackStream {
478        source: Some(source),
479        schema,
480        frame_schema,
481        label_decode_spec: declared,
482        ordering,
483        validator: SequenceValidator::new(ordering),
484        pending: Vec::new().into_iter(),
485        decoder,
486    }))
487}
488
489/// Unpacks DataFusion batches declared by [`pack_evaluated_series`].
490///
491/// The frame declares its grid, its field list, and its label mode, so the returned stream carries
492/// the [`SeriesSchema`] the rows are addressed on and needs no planning-side copy of it. The grid is
493/// the frame's own declaration: the timestamps stay unmaterialized until a consumer asks for one.
494///
495/// A frame that declares raw samples, keyed identity, or an ordering other than `contiguous` is
496/// refused before the stream is returned, as is a grid the declaration check cannot make sense of.
497/// `expected` is a check and never an input, exactly as on the raw path: when given it must name the
498/// same fields and the same grid the frame declares.
499pub fn unpack_evaluated_series(
500    source: DfSendableRecordBatchStream,
501    expected: Option<Arc<SeriesSchema>>,
502) -> datafusion_common::Result<SendableEvaluatedSeriesStream> {
503    let frame_schema = source.schema();
504    let declaration = SeriesFrameDeclaration::parse(frame_schema.as_ref()).map_err(codec_error)?;
505    if declaration.content() != FrameContent::Evaluated {
506        return Err(invalid(format!(
507            "expected an evaluated frame, found {}",
508            declaration.content().as_str()
509        )));
510    }
511    ensure_contiguous_ordering(series_frame_ordering(frame_schema.as_ref())?)?;
512    let schema = Arc::new(declaration.series().clone());
513    if let Some(expected) = &expected {
514        ensure_declared_schema(&schema, expected)?;
515    }
516    let decoder = SeriesFrameDecoder::try_new(&schema, FrameLabelMode::Explicit, None)
517        .map_err(codec_error)?;
518    let empty = DfRecordBatch::new_empty(frame_schema.clone());
519    decoder.decode_evaluated(&empty).map_err(codec_error)?;
520    Ok(Box::pin(UnpackEvaluatedStream {
521        source: Some(source),
522        frame_schema,
523        validator: EvaluatedSequenceValidator::new(),
524        pending: Vec::new().into_iter(),
525        decoder,
526    }))
527}
528
529/// Rejects an `expected` series schema the frame does not declare.
530///
531/// Only the two things a caller can get wrong are checked, because those are the only two things
532/// [`SeriesSchema`] holds: the logical fields and their order, and the evaluation grid. A raw frame
533/// carries no grid and an evaluated one carries exactly its own, so the grid comparison is also what
534/// keeps a raw expectation from decoding an evaluated frame.
535fn ensure_declared_schema(
536    declared: &SeriesSchema,
537    expected: &SeriesSchema,
538) -> datafusion_common::Result<()> {
539    if expected.fields.len() != declared.fields.len()
540        || expected
541            .fields
542            .iter()
543            .zip(declared.fields.iter())
544            .any(|(expected, declared)| expected.name != declared.name)
545    {
546        return Err(invalid(
547            "frame fields do not match the expected series schema",
548        ));
549    }
550    match (&expected.eval_grid, &declared.eval_grid) {
551        (None, None) => Ok(()),
552        (Some(expected), Some(declared)) if expected.spec() == declared.spec() => Ok(()),
553        _ => Err(invalid(
554            "frame evaluation grid does not match the expected series schema",
555        )),
556    }
557}
558
559/// Checks that a frame declares the label decode layout a scan-bound binding describes.
560///
561/// This compares one thing: the description parsed from the frame's
562/// `greptime.series.label_decode` metadata against the description derived from `label_source`, by
563/// plain equality. A difference in the version, the metric name, the primary-key encoding, the
564/// ordered key columns and their physical types, or the logical tags is a mismatch. Nothing else is
565/// compared, so agreeing descriptions do **not** establish that these are the region's chunks: no
566/// region id, table id, or provenance is part of either side, and two regions whose tags have the
567/// same ids, names, and types produce equal descriptions. The check answers "does this frame describe
568/// the label layout this binding expects", never "is this the region I asked for".
569///
570/// It belongs to the caller that holds both sides: a frame describes its own labels, so
571/// [`unpack_raw_series`] decodes it without a binding, and a caller that received the frame from a
572/// peer compares the declaration here instead of decoding under whichever side it trusts.
573///
574/// The comparison is plain equality. The writer canonicalizes the description (see
575/// [`LabelDecodeSpec::canonicalize`]), so a description that reaches a reader already has one
576/// spelling and equality says everything there is to say about it.
577pub fn ensure_frame_matches_label_source(
578    frame: &ArrowSchema,
579    label_source: &RawLabelSource,
580) -> datafusion_common::Result<()> {
581    let declared = series_frame_label_decode(frame).map_err(codec_error)?;
582    if declared != label_decode_spec(label_source) {
583        return Err(invalid(
584            "raw frame label decode description does not match the supplied binding",
585        ));
586    }
587    Ok(())
588}
589
590fn label_mode(source: &RawLabelSource) -> FrameLabelMode {
591    match source {
592        RawLabelSource::PrimaryKey { .. } => FrameLabelMode::Key,
593        RawLabelSource::Explicit => FrameLabelMode::Explicit,
594    }
595}
596
597/// Returns the label mode a frame declares: a key frame describes its key, an explicit frame
598/// carries complete labels and declares no description.
599fn declared_label_mode(declared: &Option<LabelDecodeSpec>) -> FrameLabelMode {
600    match declared {
601        Some(_) => FrameLabelMode::Key,
602        None => FrameLabelMode::Explicit,
603    }
604}
605
606/// Rejects an evaluated frame that claims more order than its producer promised.
607///
608/// Computed values have no storage key to be ordered by, so `read_key_then_time` is not a claim this
609/// layer can honour; `Interleaved` is not supported for evaluated frames. Treating either as
610/// `contiguous` would silently weaken a guarantee a consumer may rely on.
611fn ensure_contiguous_ordering(ordering: SeriesOrdering) -> datafusion_common::Result<()> {
612    match ordering {
613        SeriesOrdering::Contiguous => Ok(()),
614        SeriesOrdering::KeyThenTime => Err(invalid(
615            "an evaluated frame cannot claim key-then-time ordering",
616        )),
617        SeriesOrdering::Interleaved => Err(invalid("interleaved series ordering is not supported")),
618    }
619}
620
621fn codec_error(error: datatypes::error::Error) -> DataFusionError {
622    DataFusionError::External(Box::new(BoxedError::new(error)))
623}
624
625fn upstream_error(error: BoxedError) -> DataFusionError {
626    DataFusionError::External(Box::new(error))
627}
628
629fn invalid(reason: impl Into<String>) -> DataFusionError {
630    DataFusionError::External(Box::new(BoxedError::new(
631        InvalidSeriesSnafu {
632            reason: reason.into(),
633        }
634        .build(),
635    )))
636}
637
638/// Cross-chunk validation state for raw producer fragment chains. Every chain's chunks must be
639/// contiguous, including for `Interleaved`; this validator checks adjacent chunks only and retains
640/// the previous owned key (not an Arrow buffer), timestamp, metric, and finality. An `Interleaved`
641/// chain releases that state on closure, so later fragment chains may recur with the same key,
642/// labels, and timestamps independently.
643///
644/// Both frame streams run it - [`pack_raw_series`] over what a producer publishes and
645/// [`unpack_raw_series`] over what a consumer receives - and it is reachable on its own for the one
646/// reader that has neither a frame nor a batch in between: a consumer handed the chunks in process
647/// runs exactly this check over exactly the same sequence, so the shortcut validates what the frame
648/// would have carried instead of trusting it.
649pub struct SequenceValidator {
650    ordering: SeriesOrdering,
651    previous_key: Option<Vec<u8>>,
652    previous_timestamp: Option<i64>,
653    previous_metric: Option<SeriesLabels>,
654    previous_is_last: bool,
655}
656
657impl SequenceValidator {
658    /// A validator for a raw stream that declares `ordering`.
659    pub fn new(ordering: SeriesOrdering) -> Self {
660        Self {
661            ordering,
662            previous_key: None,
663            previous_timestamp: None,
664            previous_metric: None,
665            previous_is_last: false,
666        }
667    }
668
669    /// Checks that the stream ended between chains, and not inside one.
670    pub fn finish(&self) -> datafusion_common::Result<()> {
671        if self.previous_key.is_some() && !self.previous_is_last {
672            return Err(invalid("raw series stream ended before key was final"));
673        }
674        Ok(())
675    }
676
677    /// Checks `chunk` against the chain this validator has read so far.
678    pub fn validate(&mut self, chunk: &RawSeriesChunk) -> datafusion_common::Result<()> {
679        let key = chunk.primary_key.as_slice();
680        let timestamp = chunk
681            .time
682            .len()
683            .checked_sub(1)
684            .and_then(|last| chunk.time.timestamp(last))
685            .ok_or_else(|| invalid("empty raw series chunk"))?;
686        if let Some(previous) = &self.previous_key {
687            match previous.as_slice().cmp(key) {
688                std::cmp::Ordering::Equal => {
689                    if self.previous_is_last {
690                        return Err(invalid("raw series key recurred after final chunk"));
691                    }
692                    if self.previous_metric != chunk.metric {
693                        return Err(invalid("raw series metric changed within key"));
694                    }
695                    let first = chunk
696                        .time
697                        .timestamp(0)
698                        .ok_or_else(|| invalid("empty raw series chunk"))?;
699                    if self.previous_timestamp.is_some_and(|last| first <= last) {
700                        return Err(invalid(
701                            "raw series timestamps are not increasing across chunks",
702                        ));
703                    }
704                }
705                _ => {
706                    if !self.previous_is_last {
707                        return Err(invalid("raw series key changed before final chunk"));
708                    }
709                    if self.ordering == SeriesOrdering::KeyThenTime && previous.as_slice() > key {
710                        return Err(invalid("raw series keys are not ordered"));
711                    }
712                }
713            }
714        }
715        if self.ordering == SeriesOrdering::Interleaved && chunk.is_last {
716            self.previous_key = None;
717            self.previous_timestamp = None;
718            self.previous_metric = None;
719            self.previous_is_last = false;
720        } else {
721            self.previous_key = Some(key.to_vec());
722            self.previous_timestamp = Some(timestamp);
723            self.previous_metric = chunk.metric.clone();
724            self.previous_is_last = chunk.is_last;
725        }
726        Ok(())
727    }
728}
729
730/// Cross-chunk validation state for evaluated chains.
731///
732/// This is a **chain-local** validator. It checks exactly three things: that a chunk does not change
733/// identity while its chain is open, that a chain closes exactly once, and that the positions of an
734/// open chain keep increasing across adjacent chunks. It keeps at most the one open chain, so it
735/// never certifies that a complete identity does not recur later in the stream; that global
736/// non-recurrence is a producer contract enforced where identities are completed (the repartition
737/// owner), not here.
738///
739/// `is_last` closes one chunk chain and nothing more. It is not the end of a label set: a range
740/// function or a label rewrite can make two input series show the same complete labels, and each of
741/// them closes itself, so a closed chain may be followed by another chain whose labels happen to be
742/// equal. Only the still-open chain is remembered, which is what keeps such a contribution from being
743/// refused as a re-opened series while still refusing a chain that changes identity before it closes.
744///
745/// Like [`SequenceValidator`] it is the check both evaluated frame streams run and is reachable on
746/// its own for a consumer that is handed the chunks in process.
747pub struct EvaluatedSequenceValidator {
748    /// The labels of the open chain and the last grid position it carried.
749    open: Option<(SeriesLabels, usize)>,
750}
751
752impl Default for EvaluatedSequenceValidator {
753    fn default() -> Self {
754        Self::new()
755    }
756}
757
758impl EvaluatedSequenceValidator {
759    /// A validator with no open chain.
760    pub fn new() -> Self {
761        Self { open: None }
762    }
763
764    /// Checks that the stream ended between chains, and not inside one.
765    pub fn finish(&self) -> datafusion_common::Result<()> {
766        if self.open.is_some() {
767            return Err(invalid(
768                "evaluated series stream ended before a chain closed",
769            ));
770        }
771        Ok(())
772    }
773
774    /// Checks `series` against the chain this validator has read so far.
775    pub fn validate(&mut self, series: &Series, is_last: bool) -> datafusion_common::Result<()> {
776        let (Some(first), Some(last)) = (series.time.first_position(), series.time.last_position())
777        else {
778            // No carried position: only a closing chunk may be empty, and it closes the chain it
779            // belongs to without advancing it.
780            if !is_last {
781                return Err(invalid(
782                    "an evaluated chunk without positions must close its series",
783                ));
784            }
785            match &self.open {
786                Some((labels, _)) if labels == &series.metric => self.open = None,
787                Some(_) => {
788                    return Err(invalid(
789                        "evaluated series identity changed before its chain closed",
790                    ));
791                }
792                None => {}
793            }
794            return Ok(());
795        };
796        if let Some((labels, previous)) = &self.open {
797            if labels != &series.metric {
798                return Err(invalid(
799                    "evaluated series identity changed before its chain closed",
800                ));
801            }
802            if first <= *previous {
803                return Err(invalid(
804                    "evaluated series positions are not increasing across chunks",
805                ));
806            }
807        }
808        self.open = (!is_last).then(|| (series.metric.clone(), last));
809        Ok(())
810    }
811}
812
813/// The batching half of a pack stream: the builder, the cursor installed in it, and the declared
814/// schema every ready batch is published under.
815struct PackBatches {
816    frame_schema: ArrowSchemaRef,
817    builder: Option<SeriesFrameBuilder>,
818    cursor: Option<SeriesFrameCursor>,
819}
820
821impl PackBatches {
822    fn new(builder: SeriesFrameBuilder, frame_schema: ArrowSchemaRef) -> Self {
823        Self {
824            frame_schema,
825            builder: Some(builder),
826            cursor: None,
827        }
828    }
829
830    /// Installs the cursor of the chunk just read, replacing whatever was left of the previous one.
831    fn install(&mut self, cursor: SeriesFrameCursor) {
832        self.cursor = Some(cursor);
833    }
834
835    /// Advances the installed cursor until it yields one ready batch or is exhausted, dropping an
836    /// exhausted cursor. `None` means no batch is ready, so the source may be polled again.
837    fn advance(&mut self) -> datatypes::error::Result<Option<DfRecordBatch>> {
838        let ready = match (self.cursor.as_mut(), self.builder.as_mut()) {
839            (Some(cursor), Some(builder)) => cursor.append_to(builder)?,
840            _ => return Ok(None),
841        };
842        match ready {
843            Some(batch) => Ok(Some(batch)),
844            None => {
845                self.cursor = None;
846                Ok(None)
847            }
848        }
849    }
850
851    /// Flushes the rows buffered so far, if any, so a pending source can still deliver data.
852    fn flush(&mut self) -> datatypes::error::Result<Option<DfRecordBatch>> {
853        match self.builder.as_mut() {
854            Some(builder) => builder.flush(),
855            None => Ok(None),
856        }
857    }
858
859    /// Releases the buffered owners, leaving the stream terminal; batches already yielded are
860    /// unaffected.
861    fn release(&mut self) {
862        self.cursor = None;
863        self.builder = None;
864    }
865
866    /// Publishes one ready batch under the declared frame schema, which is the builder's own layout
867    /// plus the producer's ordering metadata. A batch whose fields cannot be declared releases the
868    /// stream instead of yielding rows with an undeclared layout.
869    fn declare(
870        &mut self,
871        batch: DfRecordBatch,
872    ) -> Poll<Option<datafusion_common::Result<DfRecordBatch>>> {
873        match DfRecordBatch::try_new(self.frame_schema.clone(), batch.columns().to_vec()) {
874            Ok(batch) => Poll::Ready(Some(Ok(batch))),
875            Err(error) => {
876                self.release();
877                Poll::Ready(Some(Err(DataFusionError::from(error))))
878            }
879        }
880    }
881}
882
883/// How long a pending source may keep buffered rows before they are published as a batch of their
884/// own.
885///
886/// One fixed short delay bounds how long a partially filled batch is held, so a slow producer costs
887/// at most this latency per pending period instead of one batch per series.
888const PENDING_FLUSH_DELAY: Duration = Duration::from_millis(1);
889
890/// How a pack stream treats the rows it has buffered when its source reports `Pending`.
891///
892/// The choice belongs to the code that builds the stream, because that is the only place that knows
893/// how the stream will be polled. Nothing is probed at run time: the only way to ask Tokio whether
894/// a time driver exists is to create a timer and catch the panic, and that unwind still runs the
895/// panic hook, logs an error, and counts a panic, so it is not a capability test.
896#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
897pub enum PendingBatching {
898    /// Publish the buffered rows as the pending period begins.
899    ///
900    /// Needs no timer, so a Tokio runtime with or without the time driver, and an executor with no
901    /// runtime at all, may poll the stream. This is the default because a stream built in one place
902    /// is not necessarily polled by the runtime that built it.
903    #[default]
904    Immediate,
905    /// Keep buffering across pending periods until the builder is full or a short deadline
906    /// elapses.
907    ///
908    /// The deadline is a Tokio timer, so the stream must be polled by a runtime whose time driver
909    /// is enabled (`Builder::enable_time()`, or `enable_all()` as every
910    /// `common_runtime::Runtime` does). A poller with no runtime context, and a poller on a
911    /// different runtime than the one that armed the deadline, fall back to publishing
912    /// immediately; only a runtime without a time driver has no fallback and panics inside
913    /// `sleep_until`, exactly like any other Tokio timer.
914    Deadline,
915}
916
917/// Bounded batching across a pending raw source.
918///
919/// The first pending period that has buffered rows publishes them immediately, so a stream whose
920/// source delivers one chunk at a time keeps its original first-batch latency. Every later pending
921/// period keeps accumulating rows until the builder is full - which [`PackBatches::advance`] reports
922/// on its own - or until [`PENDING_FLUSH_DELAY`] elapses, whichever comes first. One deadline serves
923/// the whole pending period, so rows arriving meanwhile extend the batch instead of restarting the
924/// wait, and a pending source with nothing buffered arms no timer at all.
925///
926/// Only [`PendingBatching::Deadline`] arms a timer; [`PendingBatching::Immediate`] publishes at
927/// every pending period and never touches the time driver.
928struct PendingFlush {
929    /// The batching the stream's builder asked for.
930    batching: PendingBatching,
931    /// Whether the buffered rows of the first pending period were already published immediately.
932    first_flushed: bool,
933    /// Whether the builder may hold rows, i.e. whether a deadline would have anything to publish.
934    ///
935    /// A flush leaves the builder empty and no source wake refills it, so waiting there would only
936    /// spin a timer. The estimate is exact after every flush and errs to `true` between installing
937    /// a chunk and the flush that publishes it, which costs at most one empty timer per chunk that
938    /// happened to fill a batch exactly.
939    maybe_buffered: bool,
940    /// End of the pending period the stream is in, while a timer is armed.
941    deadline: Option<Instant>,
942    /// The timer that wakes the stream at `deadline`; polling it registers this stream's waker.
943    ///
944    /// A [`Sleep`] belongs to the time driver that was current when it was created, so this one is
945    /// only polled while [`PendingFlush::timer_runtime`] is still the current runtime, and it is
946    /// dropped with the stream. Dropping a timer after its runtime shut down only deregisters the
947    /// entry, which Tokio supports; polling one there panics, which is why the deadline is disarmed
948    /// instead of polled when the poller is not the runtime that armed it.
949    timer: Option<Pin<Box<Sleep>>>,
950    /// The runtime that owns `timer`, i.e. the one that was current when the deadline was armed.
951    timer_runtime: Option<tokio::runtime::Id>,
952}
953
954impl PendingFlush {
955    fn new(batching: PendingBatching) -> Self {
956        Self {
957            batching,
958            first_flushed: false,
959            maybe_buffered: false,
960            deadline: None,
961            timer: None,
962            timer_runtime: None,
963        }
964    }
965
966    /// Releases the deadline, leaving no timer registered with the runtime.
967    fn disarm(&mut self) {
968        self.deadline = None;
969        self.timer = None;
970        self.timer_runtime = None;
971    }
972
973    /// Records that the builder published everything it had, so it is empty again.
974    fn flushed(&mut self) {
975        self.maybe_buffered = false;
976        self.disarm();
977    }
978
979    /// Records that a chunk was installed, which may buffer rows.
980    fn installed(&mut self) {
981        self.maybe_buffered = true;
982    }
983
984    /// Polls the armed deadline and reports whether it elapsed, or whether waiting for it became
985    /// impossible.
986    ///
987    /// Polling the timer is what registers this stream's waker with the runtime, so an elapsed
988    /// deadline wakes the stream by itself instead of waiting for the source to wake it first. The
989    /// report is `true` in either case, so the caller publishes the buffered rows now: a deadline
990    /// that belongs to another runtime would never wake this poller, and polling it after its
991    /// runtime shut down would panic.
992    fn elapsed(&mut self, cx: &mut Context<'_>) -> bool {
993        if self.timer.is_none() {
994            return false;
995        }
996        if self.timer_runtime != current_runtime_id() {
997            self.disarm();
998            return true;
999        }
1000        let Some(timer) = self.timer.as_mut() else {
1001            return false;
1002        };
1003        if timer.as_mut().poll(cx).is_pending() {
1004            return false;
1005        }
1006        self.disarm();
1007        true
1008    }
1009
1010    /// Arms the deadline for a later pending period, keeping an armed one as it is.
1011    ///
1012    /// Returns `false` when there is nothing to wait for: the caller asked for
1013    /// [`PendingBatching::Immediate`], no rows are buffered, or this stream is polled outside a
1014    /// Tokio runtime. The caller then publishes the buffered rows immediately instead of waiting for
1015    /// a deadline that would never fire.
1016    ///
1017    /// # Panics
1018    ///
1019    /// Panics inside `sleep_until`, like any other Tokio timer, when the runtime polling the stream
1020    /// has no time driver. That is the one environment a probe could not detect and an unwind only
1021    /// hides, so [`PendingBatching::Deadline`] is an explicit promise of the code that builds the
1022    /// stream.
1023    fn arm(&mut self, cx: &mut Context<'_>) -> bool {
1024        if self.batching == PendingBatching::Immediate {
1025            return false;
1026        }
1027        if self.deadline.is_some() {
1028            return true;
1029        }
1030        if !self.maybe_buffered {
1031            return false;
1032        }
1033        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
1034            return false;
1035        };
1036        let deadline = Instant::now() + PENDING_FLUSH_DELAY;
1037        let mut timer = Box::pin(tokio::time::sleep_until(deadline));
1038        // Polling a fresh sleep registers the waker, and it cannot be ready at once.
1039        if timer.as_mut().poll(cx).is_ready() {
1040            return false;
1041        }
1042        self.deadline = Some(deadline);
1043        self.timer = Some(timer);
1044        self.timer_runtime = Some(runtime.id());
1045        true
1046    }
1047}
1048
1049/// The runtime that would own a timer armed by the current poll, if there is one.
1050fn current_runtime_id() -> Option<tokio::runtime::Id> {
1051    tokio::runtime::Handle::try_current()
1052        .ok()
1053        .map(|handle| handle.id())
1054}
1055
1056struct PackStream {
1057    source: Option<SendableRawSeriesStream>,
1058    schema: Arc<SeriesSchema>,
1059    labels: FrameLabelMode,
1060    batches: PackBatches,
1061    ordering: SeriesOrdering,
1062    validator: SequenceValidator,
1063    pending: PendingFlush,
1064}
1065
1066impl PackStream {
1067    /// Releases the source and drops every buffered owner, leaving the stream terminal.
1068    fn finish(&mut self) {
1069        self.source = None;
1070        self.batches.release();
1071        self.validator = SequenceValidator::new(self.ordering);
1072        self.pending.disarm();
1073    }
1074
1075    /// Publishes the rows buffered so far, or returns to waiting on the source when there are none.
1076    fn publish_buffered(&mut self) -> Poll<Option<datafusion_common::Result<DfRecordBatch>>> {
1077        match self.batches.flush() {
1078            Ok(Some(batch)) => {
1079                self.pending.flushed();
1080                self.batches.declare(batch)
1081            }
1082            Ok(None) => {
1083                // Nothing to publish, so the pending source stays the only wakeup.
1084                self.pending.flushed();
1085                Poll::Pending
1086            }
1087            Err(error) => {
1088                self.finish();
1089                Poll::Ready(Some(Err(codec_error(error))))
1090            }
1091        }
1092    }
1093
1094    /// Decides what a pending source yields once its own waker is registered.
1095    ///
1096    /// The first buffered pending still publishes at once, keeping the first-batch latency of a
1097    /// source that delivers one chunk at a time; every later pending period hands the decision to
1098    /// the deadline or to the builder filling up, when the stream's [`PendingBatching`] allows a
1099    /// deadline at all.
1100    fn poll_pending(
1101        &mut self,
1102        cx: &mut Context<'_>,
1103    ) -> Poll<Option<datafusion_common::Result<DfRecordBatch>>> {
1104        if !self.pending.first_flushed {
1105            return match self.batches.flush() {
1106                Ok(Some(batch)) => {
1107                    self.pending.first_flushed = true;
1108                    self.pending.flushed();
1109                    self.batches.declare(batch)
1110                }
1111                // Nothing is buffered, so the first buffered pending is still to come.
1112                Ok(None) => Poll::Pending,
1113                Err(error) => {
1114                    self.finish();
1115                    Poll::Ready(Some(Err(codec_error(error))))
1116                }
1117            };
1118        }
1119        if self.pending.arm(cx) {
1120            return Poll::Pending;
1121        }
1122        // Either nothing is buffered here, or this stream may not wait for a deadline where it is
1123        // polled, so publishing now is the only bounded choice.
1124        self.publish_buffered()
1125    }
1126}
1127
1128impl Stream for PackStream {
1129    type Item = datafusion_common::Result<DfRecordBatch>;
1130
1131    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1132        let this = &mut *self;
1133        loop {
1134            // The deadline is checked before the source is read again: rows it already promised to
1135            // publish are not postponed by a source that keeps waking, and polling the timer here is
1136            // what keeps this stream's waker registered with the runtime.
1137            if this.pending.elapsed(cx) {
1138                match this.batches.flush() {
1139                    Ok(Some(batch)) => {
1140                        this.pending.flushed();
1141                        return this.batches.declare(batch);
1142                    }
1143                    // The deadline was armed on rows that the builder already published, so reading
1144                    // the source again is what the buffered estimate allows.
1145                    Ok(None) => this.pending.flushed(),
1146                    Err(error) => {
1147                        this.finish();
1148                        return Poll::Ready(Some(Err(codec_error(error))));
1149                    }
1150                }
1151            }
1152            match this.batches.advance() {
1153                Ok(Some(batch)) => return this.batches.declare(batch),
1154                Ok(None) => {}
1155                Err(error) => {
1156                    this.finish();
1157                    return Poll::Ready(Some(Err(codec_error(error))));
1158                }
1159            }
1160            let polled = match this.source.as_mut() {
1161                Some(source) => source.as_mut().poll_next(cx),
1162                None => return Poll::Ready(None),
1163            };
1164            match polled {
1165                // The source registered its waker above, so a later chunk, EOF, or error still wakes
1166                // this stream even while the buffered rows wait for the deadline.
1167                Poll::Pending => return this.poll_pending(cx),
1168                Poll::Ready(None) => {
1169                    if let Err(error) = this.validator.finish() {
1170                        this.finish();
1171                        return Poll::Ready(Some(Err(error)));
1172                    }
1173                    let flushed = this.batches.flush();
1174                    // The declared schema is read before the release below, so the last batch is
1175                    // published under the same schema as every batch before it.
1176                    let declared = this.batches.frame_schema.clone();
1177                    this.finish();
1178                    return match flushed {
1179                        Ok(Some(batch)) => {
1180                            match DfRecordBatch::try_new(declared, batch.columns().to_vec()) {
1181                                Ok(batch) => Poll::Ready(Some(Ok(batch))),
1182                                Err(error) => Poll::Ready(Some(Err(DataFusionError::from(error)))),
1183                            }
1184                        }
1185                        Ok(None) => Poll::Ready(None),
1186                        Err(error) => Poll::Ready(Some(Err(codec_error(error)))),
1187                    };
1188                }
1189                Poll::Ready(Some(Err(error))) => {
1190                    this.finish();
1191                    return Poll::Ready(Some(Err(upstream_error(error))));
1192                }
1193                Poll::Ready(Some(Ok(chunk))) => {
1194                    if let Err(error) = this.validator.validate(&chunk) {
1195                        this.finish();
1196                        return Poll::Ready(Some(Err(error)));
1197                    }
1198                    match SeriesFrameCursor::try_new_raw(&this.schema, this.labels, chunk) {
1199                        Ok(cursor) => {
1200                            this.batches.install(cursor);
1201                            this.pending.installed();
1202                        }
1203                        Err(error) => {
1204                            this.finish();
1205                            return Poll::Ready(Some(Err(codec_error(error))));
1206                        }
1207                    }
1208                }
1209            }
1210        }
1211    }
1212}
1213
1214impl datafusion::physical_plan::RecordBatchStream for PackStream {
1215    fn schema(&self) -> ArrowSchemaRef {
1216        self.batches.frame_schema.clone()
1217    }
1218}
1219
1220/// The pack stream of [`pack_aggregate_state`].
1221struct PackStateStream {
1222    source: Option<SendableStateSeriesStream>,
1223    state: Arc<AggregateStateSchema>,
1224    schema: Arc<SeriesSchema>,
1225    batches: PackBatches,
1226}
1227
1228impl PackStateStream {
1229    fn finish(&mut self) {
1230        self.source = None;
1231        self.batches.release();
1232    }
1233}
1234
1235impl Stream for PackStateStream {
1236    type Item = datafusion_common::Result<DfRecordBatch>;
1237
1238    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1239        let this = &mut *self;
1240        loop {
1241            match this.batches.advance() {
1242                Ok(Some(batch)) => return this.batches.declare(batch),
1243                Ok(None) => {}
1244                Err(error) => {
1245                    this.finish();
1246                    return Poll::Ready(Some(Err(codec_error(error))));
1247                }
1248            }
1249            let polled = match this.source.as_mut() {
1250                Some(source) => source.as_mut().poll_next(cx),
1251                None => return Poll::Ready(None),
1252            };
1253            match polled {
1254                Poll::Pending => {
1255                    return match this.batches.flush() {
1256                        Ok(Some(batch)) => this.batches.declare(batch),
1257                        Ok(None) => Poll::Pending,
1258                        Err(error) => {
1259                            this.finish();
1260                            Poll::Ready(Some(Err(codec_error(error))))
1261                        }
1262                    };
1263                }
1264                Poll::Ready(None) => {
1265                    let flushed = this.batches.flush();
1266                    let declared = this.batches.frame_schema.clone();
1267                    this.finish();
1268                    return match flushed {
1269                        Ok(Some(batch)) => {
1270                            match DfRecordBatch::try_new(declared, batch.columns().to_vec()) {
1271                                Ok(batch) => Poll::Ready(Some(Ok(batch))),
1272                                Err(error) => Poll::Ready(Some(Err(DataFusionError::from(error)))),
1273                            }
1274                        }
1275                        Ok(None) => Poll::Ready(None),
1276                        Err(error) => Poll::Ready(Some(Err(codec_error(error)))),
1277                    };
1278                }
1279                Poll::Ready(Some(Err(error))) => {
1280                    this.finish();
1281                    return Poll::Ready(Some(Err(upstream_error(error))));
1282                }
1283                Poll::Ready(Some(Ok((series, is_last)))) => {
1284                    match SeriesFrameCursor::try_new_aggregate_state(
1285                        &this.state,
1286                        &this.schema,
1287                        series,
1288                        is_last,
1289                    ) {
1290                        Ok(cursor) => this.batches.install(cursor),
1291                        Err(error) => {
1292                            this.finish();
1293                            return Poll::Ready(Some(Err(codec_error(error))));
1294                        }
1295                    }
1296                }
1297            }
1298        }
1299    }
1300}
1301
1302impl datafusion::physical_plan::RecordBatchStream for PackStateStream {
1303    fn schema(&self) -> ArrowSchemaRef {
1304        self.batches.frame_schema.clone()
1305    }
1306}
1307
1308/// The unpack stream of [`unpack_aggregate_state`].
1309struct UnpackStateStream {
1310    source: Option<DfSendableRecordBatchStream>,
1311    frame_schema: ArrowSchemaRef,
1312    pending: std::vec::IntoIter<StateFrameRow>,
1313    decoder: SeriesFrameDecoder,
1314}
1315
1316impl UnpackStateStream {
1317    fn finish(&mut self) {
1318        self.source = None;
1319        self.pending = Vec::new().into_iter();
1320    }
1321}
1322
1323impl Stream for UnpackStateStream {
1324    type Item = Result<StateFrameRow, BoxedError>;
1325
1326    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1327        let this = &mut *self;
1328        let mut empty_batches = 0;
1329        loop {
1330            if let Some(row) = this.pending.next() {
1331                return Poll::Ready(Some(Ok(row)));
1332            }
1333            let polled = match this.source.as_mut() {
1334                Some(source) => source.as_mut().poll_next(cx),
1335                None => return Poll::Ready(None),
1336            };
1337            match polled {
1338                Poll::Pending => return Poll::Pending,
1339                Poll::Ready(None) => {
1340                    this.finish();
1341                    return Poll::Ready(None);
1342                }
1343                Poll::Ready(Some(Err(error))) => {
1344                    this.finish();
1345                    return Poll::Ready(Some(Err(BoxedError::new(
1346                        crate::error::Error::GeneralDataFusion {
1347                            error,
1348                            location: snafu::Location::default(),
1349                        },
1350                    ))));
1351                }
1352                Poll::Ready(Some(Ok(batch))) => {
1353                    let result = if batch.schema() != this.frame_schema {
1354                        Err(invalid("aggregate state frame schema mismatch"))
1355                    } else {
1356                        this.decoder
1357                            .decode_aggregate_state(&batch)
1358                            .map_err(codec_error)
1359                    };
1360                    match result {
1361                        Ok(rows) if rows.is_empty() => {
1362                            empty_batches += 1;
1363                            if empty_batches == MAX_EMPTY_BATCHES_PER_POLL {
1364                                cx.waker().wake_by_ref();
1365                                return Poll::Pending;
1366                            }
1367                        }
1368                        Ok(rows) => this.pending = rows.into_iter(),
1369                        Err(error) => {
1370                            this.finish();
1371                            return Poll::Ready(Some(Err(unpack_error(error))));
1372                        }
1373                    }
1374                }
1375            }
1376        }
1377    }
1378}
1379
1380/// The pack stream of [`pack_evaluated_series`].
1381struct PackEvaluatedStream {
1382    source: Option<SendableEvaluatedSeriesStream>,
1383    schema: Arc<SeriesSchema>,
1384    batches: PackBatches,
1385    validator: EvaluatedSequenceValidator,
1386}
1387
1388impl PackEvaluatedStream {
1389    /// Releases the source and drops every buffered owner, leaving the stream terminal.
1390    fn finish(&mut self) {
1391        self.source = None;
1392        self.batches.release();
1393        self.validator = EvaluatedSequenceValidator::new();
1394    }
1395}
1396
1397impl Stream for PackEvaluatedStream {
1398    type Item = datafusion_common::Result<DfRecordBatch>;
1399
1400    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1401        let this = &mut *self;
1402        loop {
1403            match this.batches.advance() {
1404                Ok(Some(batch)) => return this.batches.declare(batch),
1405                Ok(None) => {}
1406                Err(error) => {
1407                    this.finish();
1408                    return Poll::Ready(Some(Err(codec_error(error))));
1409                }
1410            }
1411            let polled = match this.source.as_mut() {
1412                Some(source) => source.as_mut().poll_next(cx),
1413                None => return Poll::Ready(None),
1414            };
1415            match polled {
1416                Poll::Pending => {
1417                    let flushed = this.batches.flush();
1418                    return match flushed {
1419                        Ok(Some(batch)) => this.batches.declare(batch),
1420                        Ok(None) => Poll::Pending,
1421                        Err(error) => {
1422                            this.finish();
1423                            Poll::Ready(Some(Err(codec_error(error))))
1424                        }
1425                    };
1426                }
1427                Poll::Ready(None) => {
1428                    if let Err(error) = this.validator.finish() {
1429                        this.finish();
1430                        return Poll::Ready(Some(Err(error)));
1431                    }
1432                    let flushed = this.batches.flush();
1433                    // The declared schema is read before the release below, so the last batch is
1434                    // published under the same schema as every batch before it.
1435                    let declared = this.batches.frame_schema.clone();
1436                    this.finish();
1437                    return match flushed {
1438                        Ok(Some(batch)) => {
1439                            match DfRecordBatch::try_new(declared, batch.columns().to_vec()) {
1440                                Ok(batch) => Poll::Ready(Some(Ok(batch))),
1441                                Err(error) => Poll::Ready(Some(Err(DataFusionError::from(error)))),
1442                            }
1443                        }
1444                        Ok(None) => Poll::Ready(None),
1445                        Err(error) => Poll::Ready(Some(Err(codec_error(error)))),
1446                    };
1447                }
1448                Poll::Ready(Some(Err(error))) => {
1449                    this.finish();
1450                    return Poll::Ready(Some(Err(upstream_error(error))));
1451                }
1452                Poll::Ready(Some(Ok((series, is_last)))) => {
1453                    if let Err(error) = this.validator.validate(&series, is_last) {
1454                        this.finish();
1455                        return Poll::Ready(Some(Err(error)));
1456                    }
1457                    match SeriesFrameCursor::try_new_evaluated(&this.schema, series, is_last) {
1458                        Ok(cursor) => this.batches.install(cursor),
1459                        Err(error) => {
1460                            this.finish();
1461                            return Poll::Ready(Some(Err(codec_error(error))));
1462                        }
1463                    }
1464                }
1465            }
1466        }
1467    }
1468}
1469
1470impl datafusion::physical_plan::RecordBatchStream for PackEvaluatedStream {
1471    fn schema(&self) -> ArrowSchemaRef {
1472        self.batches.frame_schema.clone()
1473    }
1474}
1475
1476struct UnpackStream {
1477    source: Option<DfSendableRecordBatchStream>,
1478    schema: Arc<SeriesSchema>,
1479    frame_schema: ArrowSchemaRef,
1480    /// The description parsed from the frame schema; the only input decoding needs.
1481    label_decode_spec: Option<LabelDecodeSpec>,
1482    ordering: SeriesOrdering,
1483    validator: SequenceValidator,
1484    pending: std::vec::IntoIter<RawSeriesChunk>,
1485    decoder: SeriesFrameDecoder,
1486}
1487
1488impl RawSeriesStream for UnpackStream {
1489    fn schema(&self) -> &Arc<SeriesSchema> {
1490        &self.schema
1491    }
1492
1493    /// Returns [`NO_BOUND_LABEL_SOURCE`]: a frame establishes its own label layout and carries no
1494    /// scan-bound identity, so decoding reads [`Self::label_decode_spec`] and never this. There is
1495    /// no physical region key layout to report and none is invented from the description, which
1496    /// deliberately carries no region metadata.
1497    fn label_source(&self) -> &RawLabelSource {
1498        &NO_BOUND_LABEL_SOURCE
1499    }
1500
1501    /// Returns the label decode description the frame declared, which is what decoding reads; an
1502    /// explicit-label frame declares none.
1503    fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> {
1504        self.label_decode_spec.as_ref()
1505    }
1506
1507    fn ordering(&self) -> SeriesOrdering {
1508        self.ordering
1509    }
1510}
1511
1512impl UnpackStream {
1513    fn finish(&mut self) {
1514        self.source = None;
1515        self.pending = Vec::new().into_iter();
1516        self.validator = SequenceValidator::new(self.ordering);
1517    }
1518}
1519
1520impl Stream for UnpackStream {
1521    type Item = Result<RawSeriesChunk, BoxedError>;
1522
1523    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1524        let this = &mut *self;
1525        let mut empty_batches = 0;
1526        loop {
1527            if let Some(chunk) = this.pending.next() {
1528                return Poll::Ready(Some(Ok(chunk)));
1529            }
1530            let polled = match this.source.as_mut() {
1531                Some(source) => source.as_mut().poll_next(cx),
1532                None => return Poll::Ready(None),
1533            };
1534            match polled {
1535                Poll::Pending => return Poll::Pending,
1536                Poll::Ready(None) => {
1537                    let result = this.validator.finish();
1538                    this.finish();
1539                    return Poll::Ready(result.err().map(|error| Err(unpack_error(error))));
1540                }
1541                Poll::Ready(Some(Err(error))) => {
1542                    this.finish();
1543                    return Poll::Ready(Some(Err(BoxedError::new(
1544                        crate::error::Error::GeneralDataFusion {
1545                            error,
1546                            location: snafu::Location::default(),
1547                        },
1548                    ))));
1549                }
1550                Poll::Ready(Some(Ok(batch))) => {
1551                    let result = (|| {
1552                        if batch.schema() != this.frame_schema {
1553                            return Err(invalid("raw frame schema mismatch"));
1554                        }
1555                        this.decoder
1556                            .decode_raw(&batch)
1557                            .map_err(codec_error)
1558                            .and_then(|chunks| {
1559                                for chunk in &chunks {
1560                                    this.validator.validate(chunk)?;
1561                                }
1562                                Ok(chunks)
1563                            })
1564                    })();
1565                    match result {
1566                        Ok(chunks) => {
1567                            if chunks.is_empty() {
1568                                empty_batches += 1;
1569                                if empty_batches == MAX_EMPTY_BATCHES_PER_POLL {
1570                                    cx.waker().wake_by_ref();
1571                                    return Poll::Pending;
1572                                }
1573                            } else {
1574                                this.pending = chunks.into_iter();
1575                            }
1576                        }
1577                        Err(error) => {
1578                            this.finish();
1579                            return Poll::Ready(Some(Err(unpack_error(error))));
1580                        }
1581                    }
1582                }
1583            }
1584        }
1585    }
1586}
1587
1588/// The unpack stream of [`unpack_evaluated_series`].
1589struct UnpackEvaluatedStream {
1590    source: Option<DfSendableRecordBatchStream>,
1591    frame_schema: ArrowSchemaRef,
1592    validator: EvaluatedSequenceValidator,
1593    pending: std::vec::IntoIter<(Series, bool)>,
1594    decoder: SeriesFrameDecoder,
1595}
1596
1597impl UnpackEvaluatedStream {
1598    fn finish(&mut self) {
1599        self.source = None;
1600        self.pending = Vec::new().into_iter();
1601        self.validator = EvaluatedSequenceValidator::new();
1602    }
1603}
1604
1605impl Stream for UnpackEvaluatedStream {
1606    type Item = Result<(Series, bool), BoxedError>;
1607
1608    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1609        let this = &mut *self;
1610        let mut empty_batches = 0;
1611        loop {
1612            if let Some(chunk) = this.pending.next() {
1613                return Poll::Ready(Some(Ok(chunk)));
1614            }
1615            let polled = match this.source.as_mut() {
1616                Some(source) => source.as_mut().poll_next(cx),
1617                None => return Poll::Ready(None),
1618            };
1619            match polled {
1620                Poll::Pending => return Poll::Pending,
1621                Poll::Ready(None) => {
1622                    let result = this.validator.finish();
1623                    this.finish();
1624                    return Poll::Ready(result.err().map(|error| Err(unpack_error(error))));
1625                }
1626                Poll::Ready(Some(Err(error))) => {
1627                    this.finish();
1628                    return Poll::Ready(Some(Err(BoxedError::new(
1629                        crate::error::Error::GeneralDataFusion {
1630                            error,
1631                            location: snafu::Location::default(),
1632                        },
1633                    ))));
1634                }
1635                Poll::Ready(Some(Ok(batch))) => {
1636                    let result = (|| {
1637                        if batch.schema() != this.frame_schema {
1638                            return Err(invalid("evaluated frame schema mismatch"));
1639                        }
1640                        this.decoder
1641                            .decode_evaluated(&batch)
1642                            .map_err(codec_error)
1643                            .and_then(|chunks| {
1644                                for (series, is_last) in &chunks {
1645                                    this.validator.validate(series, *is_last)?;
1646                                }
1647                                Ok(chunks)
1648                            })
1649                    })();
1650                    match result {
1651                        Ok(chunks) => {
1652                            if chunks.is_empty() {
1653                                empty_batches += 1;
1654                                if empty_batches == MAX_EMPTY_BATCHES_PER_POLL {
1655                                    cx.waker().wake_by_ref();
1656                                    return Poll::Pending;
1657                                }
1658                            } else {
1659                                this.pending = chunks.into_iter();
1660                            }
1661                        }
1662                        Err(error) => {
1663                            this.finish();
1664                            return Poll::Ready(Some(Err(unpack_error(error))));
1665                        }
1666                    }
1667                }
1668            }
1669        }
1670    }
1671}
1672
1673/// How many empty batches one poll reads before yielding, so a stream of them cannot hold the task.
1674const MAX_EMPTY_BATCHES_PER_POLL: usize = 32;
1675
1676/// Wraps a decode or validation error as the boxed error an unpack stream reports.
1677fn unpack_error(error: DataFusionError) -> BoxedError {
1678    BoxedError::new(crate::error::Error::GeneralDataFusion {
1679        error,
1680        location: snafu::Location::default(),
1681    })
1682}