Skip to main content

datatypes/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//! One Arrow frame family for raw and evaluated series chunks.
16//!
17//! A frame carries the same thing whichever sample shape it holds: one row per chunk of one series,
18//! with that series' identity, its finality, its time axis, and one column of samples per logical
19//! field. Field names preserve the logical series schema in order. What varies is declared rather
20//! than inferred, because the receiver of a frame has no scanner, region, or planning context to
21//! infer it from:
22//!
23//! | Content | Identity | Time | Producer |
24//! | --- | --- | --- | --- |
25//! | `raw` | `key` | `timestamps` | a storage raw-series scan |
26//! | `raw` | `explicit` | `timestamps` | a raw input whose labels are already decoded |
27//! | `evaluated` | `explicit` | `grid_spans` | a compute node's evaluated output |
28//!
29//! Any other combination is rejected here, because no producer can mean it: an evaluated value's
30//! labels may be rewritten by the computation that produced it, so an evaluated frame cannot claim
31//! a storage key as its identity, and raw samples have no evaluation grid to be addressed on.
32//!
33//! Packing accumulates bounded multi-row batches: [`SeriesFrameCursor`] walks one validated chunk
34//! and [`SeriesFrameBuilder`] emits rows directly as Arrow arrays once a row or estimated byte bound
35//! is reached. Decoding reuses one prepared
36//! schema per stream through [`SeriesFrameDecoder`]. Column layout, metadata, and wire strings stay
37//! on the single `v1` contract. Raw frames may also declare `greptime.series.ordering=interleaved`;
38//! older readers that do not recognize this ordering reject it. A key-encoded frame declares a
39//! versioned
40//! [`LabelDecodeSpec`] so its labels can be decoded from the received schema alone, and an evaluated
41//! frame declares its [`GridSpec`] once instead of repeating timestamps.
42//!
43//! # Label decode description versioning
44//!
45//! The description is one `greptime.series.label_decode` metadata entry, and remote plans compare
46//! `greptime.series.*` metadata **as exact text, byte for byte**: a frontend and a datanode that
47//! write different text for the same labels disagree about the schema, and the query fails instead
48//! of falling back. The rules that follow from that are:
49//!
50//! - A reader rejects a version it does not implement, rather than guessing. This module writes and
51//!   reads [`LABEL_DECODE_VERSION`] only.
52//! - [`LABEL_DECODE_VERSION`] covers the whole text, including each key column's
53//!   [`LabelDecodeColumn::physical_type`]. That field is a [`ConcreteDataType`], so the text embeds
54//!   [`ConcreteDataType`]'s serde shape: it is not spelled here, and a change in that type's
55//!   serialization does alter this text. What keeps such a change from going unnoticed is the
56//!   frozen fixture `tests/compatibility/wire/raw_series_label_decode/v1_physical_types.json`,
57//!   which records the text of every datatype variant and fails the crate's tests when any of them
58//!   is serialized differently.
59//! - Any change to the shape of this text — a renamed or added field, a different
60//!   [`ConcreteDataType`] spelling, a different `logical_tags` order — is a **breaking** change at
61//!   the same version, because it makes two nodes of different builds disagree. Such a change must
62//!   bump [`LABEL_DECODE_VERSION`] and update that fixture with it.
63//! - The text is canonical: [`LabelDecodeSpec::canonicalize`] fixes the only part whose order
64//!   carries no meaning, so equal labels always write equal bytes.
65//!
66//! Deployment rule: during a rolling upgrade a frame may carry a version the receiving node does not
67//! implement, and a byte-for-byte schema comparison may fail for that reason alone. The intended
68//! behaviour is that such a mismatch disables the native series path at planning time and falls back
69//! to the generic path, instead of failing the query at execution.
70//!
71//! TODO(narthex): implement that planning-time fallback. No planner reads
72//! `raw_series_frame_label_decode` to decide support today, so a version or text mismatch currently
73//! surfaces as an execution-time error from the raw-frame decode or the remote schema comparison.
74
75#[cfg(test)]
76mod tests;
77
78use std::collections::{HashMap, HashSet};
79use std::mem::size_of;
80use std::sync::Arc;
81
82use arrow::array::{
83    Array, ArrayRef, BinaryArray, BooleanArray, Float64Array, Int64Array, ListArray, StringArray,
84    StructArray, UInt32Array, UInt64Array,
85};
86use arrow::buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer, ScalarBuffer};
87use arrow::compute::{concat, take};
88use arrow::datatypes::{DataType, Field, Fields, Schema, SchemaRef};
89use arrow::record_batch::{RecordBatch, RecordBatchOptions};
90use serde::{Deserialize, Serialize};
91
92use crate::data_type::ConcreteDataType;
93use crate::error::{InvalidSeriesSnafu, Result};
94use crate::series::aggregate_state::{
95    AggregateStateSchema, AggregateStateValues, HistogramState, StateComponent, StateFieldsBatch,
96    StatePayload, StateSeries,
97};
98use crate::series::histogram::{
99    BucketSideView, CounterResetHint, HistogramBatch, HistogramBatchBuilder, HistogramView,
100    fields as histogram_fields,
101};
102use crate::series::raw::{RawSeriesChunk, RawTimestamps};
103use crate::series::samples::{
104    DenseSamplesRef, FieldSpec, HistogramSamples, Samples, Series, SeriesFields, SeriesSchema,
105};
106use crate::series::time::{EvalGrid, GridRun, GridSpan, GridSpec, TimeAxis};
107use crate::series::{Label, SeriesLabels, invalid_series};
108
109const LAYOUT: &str = "greptime.series.layout";
110const CONTENT: &str = "greptime.series.content";
111const LABELS: &str = "greptime.series.labels";
112const TIME: &str = "greptime.series.time";
113const GRID: &str = "greptime.series.grid";
114/// Metadata key of the versioned label decode description carried by key-encoded frames.
115const LABEL_DECODE: &str = "greptime.series.label_decode";
116/// Metadata key of the producer ordering carried by a complete frame declaration.
117const ORDERING: &str = "greptime.series.ordering";
118/// Metadata key naming the aggregate whose accumulator a state frame carries.
119const AGGREGATE_KIND: &str = "greptime.series.aggregate.kind";
120/// Metadata key listing the accumulator components a state frame carries, in column order.
121const AGGREGATE_COMPONENTS: &str = "greptime.series.aggregate.components";
122
123/// Every `greptime.series.*` key a frame this revision writes may carry.
124///
125/// Frame schemas carry an explicit `contiguous` default; streaming producers may replace it with
126/// their stronger guarantee.
127const RESERVED_KEYS: [&str; 9] = [
128    LAYOUT,
129    CONTENT,
130    LABELS,
131    TIME,
132    GRID,
133    LABEL_DECODE,
134    ORDERING,
135    AGGREGATE_KIND,
136    AGGREGATE_COMPONENTS,
137];
138
139/// The layout marker every frame this engine writes carries.
140///
141/// It stays at one value because the native path is experimental: this branch may break its own
142/// frame format between revisions, so a revision number has no compatibility promise to describe
143/// and no older layout that a reader must still decode. The marker becomes movable once the path
144/// reaches a release branch, where a producer and a consumer can legitimately be different
145/// revisions. A reader that meets another marker refuses the frame instead of guessing at it - that
146/// check is what turns a stale producer into an error rather than into wrong values.
147pub const FRAME_LAYOUT_VERSION: &str = "v1";
148
149/// Version of the label decode description this revision writes and reads.
150///
151/// This is independent of [`FRAME_LAYOUT_VERSION`]: the description versions its own text, which a
152/// reader refuses to guess at, while the layout versions the column and metadata set around it.
153pub const LABEL_DECODE_VERSION: u32 = 1;
154
155/// What one frame's rows hold.
156///
157/// The content decides the row layout, the time mode and the payload columns together, so a frame
158/// states it once and every other declaration is derived from it rather than chosen separately.
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub enum FrameContent {
161    /// Samples read from storage, each row carrying the timestamps it was read at.
162    Raw,
163    /// Values computed on an evaluation grid, each row carrying the grid positions it holds.
164    Evaluated,
165    /// Partial aggregate accumulator state, addressed on the grid the frame declares.
166    ///
167    /// A state row is not a query value: it names a group and the positions it has contributions
168    /// at, and its payload carries the accumulator components that aggregate declared. It is
169    /// addressed like an evaluated row because a group's state lives at the same grid positions a
170    /// value would, but the two are not interchangeable — a consumer that folds values must refuse
171    /// state, and one that merges state must refuse values.
172    AggregateState,
173}
174
175impl FrameContent {
176    /// The `greptime.series.content` text of this content.
177    pub const fn as_str(self) -> &'static str {
178        match self {
179            Self::Raw => "raw",
180            Self::Evaluated => "evaluated",
181            Self::AggregateState => "aggregate_state",
182        }
183    }
184
185    /// Parses a `greptime.series.content` value this revision implements.
186    const fn parse(text: &str) -> Option<Self> {
187        match text.as_bytes() {
188            b"raw" => Some(Self::Raw),
189            b"evaluated" => Some(Self::Evaluated),
190            b"aggregate_state" => Some(Self::AggregateState),
191            _ => None,
192        }
193    }
194
195    /// The `greptime.series.time` text this content's rows are addressed by.
196    ///
197    /// Time mode is a function of content and never an independent choice: raw samples carry their
198    /// own timestamps and evaluated ones sit on a grid, so a frame has no way to hold one without
199    /// the other. Writing it as a derived text rather than a second enum keeps the two from ever
200    /// disagreeing.
201    const fn time_text(self) -> &'static str {
202        match self {
203            Self::Raw => "timestamps",
204            Self::Evaluated | Self::AggregateState => "grid_spans",
205        }
206    }
207
208    /// The struct member a row's time column carries for this content.
209    const fn time_member(self) -> &'static str {
210        match self {
211            Self::Raw => "timestamps",
212            Self::Evaluated | Self::AggregateState => "spans",
213        }
214    }
215}
216
217/// How a frame names the series of its rows.
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219pub enum FrameLabelMode {
220    /// Identity is only the encoded storage key in `read_key`, decoded through the frame's own
221    /// [`LabelDecodeSpec`].
222    Key,
223    /// The complete metric name and ordinary labels are present in the frame as well.
224    Explicit,
225}
226
227impl FrameLabelMode {
228    /// The `greptime.series.labels` text of this mode.
229    pub const fn as_str(self) -> &'static str {
230        match self {
231            Self::Key => "key",
232            Self::Explicit => "explicit",
233        }
234    }
235
236    /// Parses a `greptime.series.labels` value this revision implements.
237    const fn parse(text: &str) -> Option<Self> {
238        match text.as_bytes() {
239            b"key" => Some(Self::Key),
240            b"explicit" => Some(Self::Explicit),
241            _ => None,
242        }
243    }
244}
245
246/// Primary-key encoding of the labels a key-encoded frame carries.
247///
248/// This mirrors the storage contract's `PrimaryKeyEncoding` without making this crate depend on
249/// it; Dense and Sparse keys use different decode layouts.
250#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "snake_case")]
252pub enum LabelDecodeEncoding {
253    /// Dense key: every primary-key field is encoded in order, with no ids on the wire.
254    Dense,
255    /// Sparse key: `(column id, value)` pairs, so the layout only frames the field stream.
256    Sparse,
257}
258
259/// One ordered key column needed to decode key-encoded labels.
260///
261/// Only tag columns reach this list: region metadata rejects a primary key that holds the time
262/// index or a non-`Tag` column, and it requires the primary key to name every tag column. The
263/// array's position is therefore the encoding position, with nothing to disambiguate.
264#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
265#[serde(deny_unknown_fields)]
266pub struct LabelDecodeColumn {
267    /// Physical column id of this key column.
268    pub column_id: u32,
269    /// Physical column name; a logical tag of the same id must repeat it.
270    pub name: String,
271    /// Physical data type of the encoded value, in [`ConcreteDataType`]'s own serde form. Dense
272    /// keys carry no types on the wire, so the codec is reconstructed from this exact ordered type
273    /// list.
274    pub physical_type: ConcreteDataType,
275}
276
277/// One logical tag name bound to a primary-key column.
278#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(deny_unknown_fields)]
280pub struct LabelDecodeTag {
281    /// Physical column id this logical tag reads.
282    pub column_id: u32,
283    /// Logical tag name exposed to queries.
284    pub name: String,
285}
286
287/// Versioned, self-contained description of how to decode key-encoded labels.
288///
289/// It carries exactly what decoding a primary-key label source reads and nothing else: no region
290/// identity, no field columns, no time index. A consumer that receives the frame schema can
291/// therefore reconstruct an equivalent decoder without a scan-side binding, while a description
292/// that is missing, of an unknown version, or structurally inconsistent is a hard error instead of
293/// a silent fallback.
294///
295/// It is JSON-encoded in one schema metadata entry, always through
296/// [`series_frame_schema`], so both the producing and the expecting side of a
297/// `greptime.series.*` exact metadata comparison see byte-identical text. The text is
298/// self-describing but not a general interchange format: readers reject unknown fields here only
299/// at this structure's own levels, while [`LabelDecodeColumn::physical_type`] is decoded by
300/// [`ConcreteDataType`]'s own representation and is therefore exactly as stable as that type's
301/// serde. The frozen text this revision writes is pinned by
302/// `tests/compatibility/wire/raw_series_label_decode/v1_physical_types.json`; see the module
303/// documentation for what a change to it means.
304#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
305#[serde(deny_unknown_fields)]
306pub struct LabelDecodeSpec {
307    /// Description version; see [`LABEL_DECODE_VERSION`].
308    pub version: u32,
309    /// Metric name attached to every decoded label set; may be empty.
310    pub metric_name: String,
311    /// Primary-key encoding that determines the decode layout.
312    pub encoding: LabelDecodeEncoding,
313    /// Every tag column of the primary key, in primary-key encoding order. This is exactly the
314    /// set of encoded key fields: region metadata forbids a primary key from naming the time
315    /// index or a field column, and requires it to name every tag column, so no time-index or
316    /// field entry can appear here. The order is significant and is compared as written: a dense
317    /// decode reads field *n* at position *n*, so the same columns in another order describe a
318    /// different key, not the same key in another order.
319    pub primary_key: Vec<LabelDecodeColumn>,
320    /// Logical tags, as bound by the producer, in [`LabelDecodeSpec::canonicalize`] order.
321    ///
322    /// The order carries no meaning: the decoder sorts the tags by name when it binds them
323    /// (`src/mito-codec/src/labels.rs:235`), so a decoded label set does not depend on it. It is
324    /// nevertheless fixed rather than left to the caller, because this description is compared as
325    /// exact text across nodes: two producers with the same tags in another order must write
326    /// byte-identical text, or one side rejects the other as a schema mismatch.
327    ///
328    /// The semantic checks on these tags (reserved and internal names, name equality with the bound
329    /// column, membership in `primary_key`) are the decoder's, matching what a typed binding gets.
330    pub logical_tags: Vec<LabelDecodeTag>,
331}
332
333impl LabelDecodeSpec {
334    /// Puts the order-insensitive part of the description in its canonical order.
335    ///
336    /// [`series_frame_schema`] applies this to a copy before serializing, and
337    /// so does the description a binding derives (in `common_query::series_frame`), so both sides of
338    /// a text comparison produce the same bytes and a reader can compare descriptions structurally.
339    /// `primary_key` is deliberately untouched: its order is the encoding order.
340    ///
341    /// The writer canonicalizes a **copy** on purpose. A caller's binding keeps its own
342    /// `logical_tags` order, and that order is meaningful elsewhere: `src/table/src/table/scan.rs`
343    /// compares two bindings' tag lists positionally (`lt.iter().zip(rt.iter())`), so reordering the
344    /// caller's list here would make two bindings for the same labels compare unequal. Only the
345    /// serialized text is canonical; nothing outside it is rewritten.
346    ///
347    /// Sorting by `(column_id, name)` is a total order for a validated description, which names
348    /// each tag column and each tag name at most once, so the canonical form is unique.
349    pub fn canonicalize(&mut self) {
350        self.logical_tags
351            .sort_unstable_by(|a, b| (a.column_id, &a.name).cmp(&(b.column_id, &b.name)));
352    }
353
354    /// Checks the version and structural invariants of the description.
355    ///
356    /// Storage-region binding semantics are deliberately outside this schema-level validation.
357    pub fn validate(&self) -> Result<()> {
358        if self.version != LABEL_DECODE_VERSION {
359            return Err(err(format!(
360                "unsupported label decode description version {}",
361                self.version
362            )));
363        }
364        let mut column_ids = HashSet::with_capacity(self.primary_key.len());
365        for column in &self.primary_key {
366            if !column_ids.insert(column.column_id) {
367                return Err(err(format!(
368                    "duplicate primary-key column id {} in label decode description",
369                    column.column_id
370                )));
371            }
372        }
373        let mut tag_ids = HashSet::with_capacity(self.logical_tags.len());
374        let mut tag_names = HashSet::with_capacity(self.logical_tags.len());
375        for tag in &self.logical_tags {
376            if !tag_ids.insert(tag.column_id) {
377                return Err(err(format!(
378                    "duplicate logical tag column id {} in label decode description",
379                    tag.column_id
380                )));
381            }
382            if !tag_names.insert(tag.name.as_str()) {
383                return Err(err(format!(
384                    "duplicate logical tag {} in label decode description",
385                    tag.name
386                )));
387            }
388            if !column_ids.contains(&tag.column_id) {
389                return Err(err(format!(
390                    "logical tag {} is not a primary-key column of the label decode description",
391                    tag.name
392                )));
393            }
394        }
395        Ok(())
396    }
397}
398
399/// Builds the one frame schema family: raw or evaluated, keyed or explicit.
400///
401/// Everything the wire states is derived from the two things a producer actually holds. The
402/// evaluation grid comes from `schema.eval_grid`, where a schema without one describes raw samples
403/// and a schema with one describes values addressed on that grid, so content and time mode can never
404/// contradict the columns they describe. `labels` decides identity, and with it whether the frame
405/// carries the `name`/`labels` columns: a key frame keeps its labels encoded in `read_key` and must
406/// declare the [`LabelDecodeSpec`] that decodes them, while an explicit frame carries complete
407/// labels and must not declare one.
408///
409/// This is the only place the reserved `greptime.series.*` text is written, so a producer and a
410/// reader cannot spell one frame two ways.
411pub fn series_frame_schema(
412    schema: &SeriesSchema,
413    labels: FrameLabelMode,
414    decode: Option<&LabelDecodeSpec>,
415) -> Result<SchemaRef> {
416    if schema.fields.is_empty() {
417        return invalid_series("series frame schema must have fields");
418    }
419    let content = match &schema.eval_grid {
420        Some(_) => FrameContent::Evaluated,
421        None => FrameContent::Raw,
422    };
423    match (labels, decode) {
424        (FrameLabelMode::Key, None) => {
425            return Err(err(
426                "key-encoded frames must carry a label decode description",
427            ));
428        }
429        (FrameLabelMode::Explicit, Some(_)) => {
430            return Err(err(
431                "explicit-label frames carry no label decode description",
432            ));
433        }
434        (FrameLabelMode::Key, Some(_)) | (FrameLabelMode::Explicit, None) => {}
435    }
436    if content == FrameContent::Evaluated && labels == FrameLabelMode::Key {
437        return Err(err(
438            "an evaluated frame names its series by label, not by a storage key",
439        ));
440    }
441    let list = |ty, nullable| DataType::List(Arc::new(Field::new("item", ty, nullable)));
442    let time = match content {
443        FrameContent::Raw => DataType::Struct(
444            vec![Field::new(
445                "timestamps",
446                list(DataType::Int64, false),
447                false,
448            )]
449            .into(),
450        ),
451        FrameContent::Evaluated | FrameContent::AggregateState => DataType::Struct(
452            vec![Field::new(
453                "spans",
454                list(
455                    DataType::Struct(
456                        vec![
457                            Field::new("start", DataType::UInt64, false),
458                            Field::new("len", DataType::UInt64, false),
459                        ]
460                        .into(),
461                    ),
462                    false,
463                ),
464                false,
465            )]
466            .into(),
467        ),
468    };
469    let hist = DataType::Struct(
470        vec![
471            Field::new("indices", list(DataType::UInt32, true), false),
472            Field::new(
473                "table",
474                list(DataType::Struct(histogram_fields()), false),
475                false,
476            ),
477        ]
478        .into(),
479    );
480    let payload = DataType::Struct(
481        vec![
482            Field::new("float_values", list(DataType::Float64, true), true),
483            Field::new("histogram", hist, true),
484        ]
485        .into(),
486    );
487    let fields: Fields = schema
488        .fields
489        .iter()
490        .map(|field| Field::new(field.name.as_ref(), payload.clone(), false))
491        .collect();
492    let mut columns = vec![
493        // A key frame *is* its key, so the column is required. An explicit frame names its series
494        // by label and keeps the column for the runtime chunk's own contract: a raw chunk still
495        // carries the key it was read under, an evaluated one carries none.
496        Field::new(
497            "read_key",
498            DataType::Binary,
499            labels == FrameLabelMode::Explicit,
500        ),
501        Field::new("is_last", DataType::Boolean, false),
502        Field::new("time", time, false),
503        Field::new("fields", DataType::Struct(fields), false),
504    ];
505    if labels == FrameLabelMode::Explicit {
506        columns.push(Field::new("name", DataType::Utf8, true));
507        columns.push(Field::new(
508            "labels",
509            list(
510                DataType::Struct(
511                    vec![
512                        Field::new("name", DataType::Utf8, false),
513                        Field::new("value", DataType::Utf8, false),
514                    ]
515                    .into(),
516                ),
517                false,
518            ),
519            false,
520        ));
521    }
522    let mut metadata = vec![
523        (LAYOUT.to_string(), FRAME_LAYOUT_VERSION.to_string()),
524        (CONTENT.to_string(), content.as_str().to_string()),
525        (LABELS.to_string(), labels.as_str().to_string()),
526        (TIME.to_string(), content.time_text().to_string()),
527        (ORDERING.to_string(), "contiguous".to_string()),
528    ];
529    if let Some(grid) = &schema.eval_grid {
530        metadata.push((GRID.to_string(), grid_text(grid.spec())?));
531    }
532    if let Some(decode) = decode {
533        // Writing is faithful: the description records what the producer declares, and nothing is
534        // rewritten or dropped. The one exception is the order of `logical_tags`, which carries no
535        // meaning to a decoder and which this text nevertheless has to fix so two producers of the
536        // same labels write the same bytes; a copy is canonicalized and the caller's value is
537        // untouched.
538        //
539        // What is not accepted is a description this revision would refuse to read. A frame is worth
540        // writing only if it can be decoded, so the same check runs here: a duplicate key column, a
541        // logical tag naming no listed column, or a description of an unknown version is refused at
542        // the producer rather than when the frame reaches its consumer, where the producer is no
543        // longer in a position to fix it.
544        let mut canonical = decode.clone();
545        canonical.canonicalize();
546        canonical.validate()?;
547        metadata.push((
548            LABEL_DECODE.to_string(),
549            serde_json::to_string(&canonical)
550                .map_err(|e| err(format!("cannot encode label decode description: {e}")))?,
551        ));
552    }
553    Ok(Arc::new(Schema::new_with_metadata(
554        columns,
555        metadata.into_iter().collect(),
556    )))
557}
558
559/// Builds an aggregate state frame schema with explicit labels and a declared grid.
560pub fn aggregate_state_frame_schema(
561    state: &AggregateStateSchema,
562    schema: &SeriesSchema,
563    labels: FrameLabelMode,
564) -> Result<SchemaRef> {
565    if schema.eval_grid.is_none() {
566        return invalid_series("an aggregate state frame needs an evaluation grid");
567    }
568    if labels != FrameLabelMode::Explicit {
569        return invalid_series("an aggregate state frame requires explicit labels");
570    }
571    let components: Fields = state
572        .components
573        .iter()
574        .map(|component| Field::new(component.as_str(), component.element_type(), true))
575        .collect();
576    let member = DataType::List(Arc::new(Field::new(
577        "item",
578        DataType::Struct(components),
579        true,
580    )));
581    let fields: Fields = schema
582        .fields
583        .iter()
584        .map(|field| Field::new(field.name.as_ref(), member.clone(), false))
585        .collect();
586    let mut ordinary = series_frame_schema(schema, labels, None)?;
587    let mut metadata = ordinary.metadata().clone();
588    metadata.insert(
589        CONTENT.to_string(),
590        FrameContent::AggregateState.as_str().to_string(),
591    );
592    metadata.insert(
593        TIME.to_string(),
594        FrameContent::AggregateState.time_text().to_string(),
595    );
596    metadata.insert(AGGREGATE_KIND.to_string(), state.kind.as_str().to_string());
597    metadata.insert(AGGREGATE_COMPONENTS.to_string(), state.components_text());
598    let mut columns = ordinary.fields().to_vec();
599    columns[3] = Field::new("fields", DataType::Struct(fields), false).into();
600    ordinary = Arc::new(Schema::new_with_metadata(columns, metadata));
601    Ok(ordinary)
602}
603
604/// Builds the typed schema for a raw frame, refusing a series schema with an evaluation grid.
605///
606/// A key frame is unreadable without its description, so this constructor serves explicit-label
607/// frames only; a caller that holds a binding declares through [`series_frame_schema`].
608pub fn raw_series_frame_schema(schema: &SeriesSchema, labels: FrameLabelMode) -> Result<SchemaRef> {
609    if schema.eval_grid.is_some() {
610        return invalid_series("raw series schema cannot have an evaluation grid");
611    }
612    match labels {
613        FrameLabelMode::Key => Err(err(
614            "raw key frames must declare a label decode description",
615        )),
616        FrameLabelMode::Explicit => series_frame_schema(schema, labels, None),
617    }
618}
619
620/// The canonical `greptime.series.grid` text of one grid.
621///
622/// Field order is the struct's declaration order and the text is compact, so two producers of the
623/// same grid write the same bytes; nothing else in the tree spells this text.
624fn grid_text(spec: GridSpec) -> Result<String> {
625    serde_json::to_string(&spec).map_err(|e| err(format!("cannot encode evaluation grid: {e}")))
626}
627
628/// Parses one `greptime.series.grid` text back into a validated, deferrable grid.
629///
630/// Validation is [`GridSpec::try_new`]'s plus the unknown-field refusal serde performs, so a frame
631/// cannot declare a grid this revision would compute differently. The timestamps themselves stay
632/// unmaterialized until a consumer asks for them.
633fn parse_grid(text: &str) -> Result<Arc<EvalGrid>> {
634    let spec: GridSpec = serde_json::from_str(text)
635        .map_err(|e| err(format!("cannot decode evaluation grid: {e}")))?;
636    Ok(Arc::new(EvalGrid::try_deferred(spec)?))
637}
638
639/// A frame schema's reserved declarations, parsed and cross-checked.
640///
641/// The three facts a receiver needs are not independent - the content decides the time mode, the
642/// label mode decides whether a description must be present, and only an evaluated frame may name a
643/// grid - so they are parsed together and every contradictory combination is refused instead of one
644/// side of it being picked.
645#[derive(Clone, Debug)]
646pub struct SeriesFrameDeclaration {
647    series: SeriesSchema,
648    content: FrameContent,
649    labels: FrameLabelMode,
650    label_decode: Option<LabelDecodeSpec>,
651    aggregate_state: Option<crate::series::aggregate_state::AggregateStateSchema>,
652}
653
654fn validate_ordering(schema: &Schema, content: FrameContent) -> Result<()> {
655    match schema.metadata().get(ORDERING).map(String::as_str) {
656        Some("contiguous") => Ok(()),
657        Some("read_key_then_time" | "interleaved") if content == FrameContent::Raw => Ok(()),
658        Some("read_key_then_time") => Err(err(
659            "an evaluated frame cannot claim key-then-time ordering",
660        )),
661        Some("interleaved") => Err(err("an evaluated frame cannot claim interleaved ordering")),
662        None => Err(err(format!("frame declares no {ORDERING} value"))),
663        Some(_) => Err(err("unknown series ordering")),
664    }
665}
666
667impl SeriesFrameDeclaration {
668    /// Parses and cross-checks one frame schema.
669    pub fn parse(schema: &Schema) -> Result<Self> {
670        for key in schema.metadata().keys() {
671            if key.starts_with("greptime.series.") && !RESERVED_KEYS.contains(&key.as_str()) {
672                return Err(err(format!(
673                    "frame declares unknown reserved metadata {key}"
674                )));
675            }
676        }
677        if schema.metadata().get(LAYOUT).map(String::as_str) != Some(FRAME_LAYOUT_VERSION) {
678            return Err(err(format!("frame declares no known {LAYOUT} value")));
679        }
680        let content = schema
681            .metadata()
682            .get(CONTENT)
683            .and_then(|text| FrameContent::parse(text))
684            .ok_or_else(|| err(format!("frame declares no known {CONTENT} value")))?;
685        validate_ordering(schema, content)?;
686        let labels = schema
687            .metadata()
688            .get(LABELS)
689            .and_then(|text| FrameLabelMode::parse(text))
690            .ok_or_else(|| err(format!("frame declares no known {LABELS} value")))?;
691        // Time mode is read as the content's own text: a frame whose time column is addressed the
692        // other way contradicts itself, and there is no third time mode to fall back to.
693        if schema.metadata().get(TIME).map(String::as_str) != Some(content.time_text()) {
694            return Err(err(format!(
695                "frame declares no {TIME} value this content can carry"
696            )));
697        }
698        if content == FrameContent::Evaluated && labels == FrameLabelMode::Key {
699            return Err(err(
700                "an evaluated frame names its series by label, not by a storage key",
701            ));
702        }
703        let grid = match (content, schema.metadata().get(GRID)) {
704            (FrameContent::Raw, None) => None,
705            (FrameContent::Raw, Some(_)) => {
706                return Err(err("a raw frame cannot declare an evaluation grid"));
707            }
708            (FrameContent::Evaluated, None) => {
709                return Err(err("an evaluated frame must declare its evaluation grid"));
710            }
711            (FrameContent::Evaluated, Some(text)) => Some(parse_grid(text)?),
712            (FrameContent::AggregateState, None) => {
713                return Err(err(
714                    "an aggregate state frame must declare its evaluation grid",
715                ));
716            }
717            (FrameContent::AggregateState, Some(text)) => Some(parse_grid(text)?),
718        };
719        let has_kind = schema.metadata().contains_key(AGGREGATE_KIND);
720        let has_components = schema.metadata().contains_key(AGGREGATE_COMPONENTS);
721        let aggregate_state = match content {
722            FrameContent::AggregateState => {
723                if !has_kind || !has_components {
724                    return Err(err(
725                        "an aggregate state frame must declare kind and components",
726                    ));
727                }
728                if schema.metadata().contains_key(LABEL_DECODE) {
729                    return Err(err(
730                        "an aggregate state frame cannot carry a label decode description",
731                    ));
732                }
733                Some(AggregateStateSchema::from_text(
734                    schema.metadata()[AGGREGATE_KIND].as_str(),
735                    schema.metadata()[AGGREGATE_COMPONENTS].as_str(),
736                )?)
737            }
738            FrameContent::Raw | FrameContent::Evaluated => {
739                if has_kind || has_components {
740                    return Err(err(
741                        "raw or evaluated frames cannot carry aggregate state metadata",
742                    ));
743                }
744                None
745            }
746        };
747        let label_decode = match schema.metadata().get(LABEL_DECODE) {
748            None => None,
749            Some(text) => {
750                let decode: LabelDecodeSpec = serde_json::from_str(text)
751                    .map_err(|e| err(format!("cannot decode label decode description: {e}")))?;
752                decode.validate()?;
753                Some(decode)
754            }
755        };
756        match (labels, &label_decode) {
757            (FrameLabelMode::Key, None) => {
758                return Err(err(
759                    "key-encoded frames must carry a label decode description",
760                ));
761            }
762            (FrameLabelMode::Explicit, Some(_)) => {
763                return Err(err(
764                    "explicit-label frames carry no label decode description",
765                ));
766            }
767            (FrameLabelMode::Key, Some(_)) | (FrameLabelMode::Explicit, None) => {}
768        }
769        let fields = schema
770            .fields()
771            .iter()
772            .find(|field| field.name() == "fields")
773            .ok_or_else(|| err("frame declares no fields column"))?;
774        let DataType::Struct(members) = fields.data_type() else {
775            return Err(err("frame fields column is not a struct"));
776        };
777        if members.is_empty() {
778            return Err(err("series frame schema must have fields"));
779        }
780        let declared_time = schema
781            .fields()
782            .iter()
783            .find(|field| field.name() == "time")
784            .ok_or_else(|| err("frame declares no time column"))?;
785        let DataType::Struct(time_members) = declared_time.data_type() else {
786            return Err(err("frame time column is not a struct"));
787        };
788        if time_members.len() != 1 || time_members[0].name() != content.time_member() {
789            return Err(err(
790                "frame time column does not match its declared time mode",
791            ));
792        }
793        Ok(Self {
794            content,
795            aggregate_state,
796            series: SeriesSchema {
797                fields: members
798                    .iter()
799                    .map(|member| FieldSpec {
800                        name: Arc::from(member.name().as_str()),
801                    })
802                    .collect(),
803                eval_grid: grid,
804            },
805            labels,
806            label_decode,
807        })
808    }
809
810    /// The logical fields and evaluation grid the frame declares.
811    pub fn series(&self) -> &SeriesSchema {
812        &self.series
813    }
814
815    /// What the frame's rows hold.
816    pub fn content(&self) -> FrameContent {
817        self.content
818    }
819
820    /// The validated accumulator kind and component layout, present only on state frames.
821    pub fn aggregate_state(&self) -> Option<&AggregateStateSchema> {
822        self.aggregate_state.as_ref()
823    }
824
825    /// How the frame names its series.
826    pub fn labels(&self) -> FrameLabelMode {
827        self.labels
828    }
829
830    /// The label decode description the frame declares, present exactly for key identity.
831    pub fn label_decode(&self) -> Option<&LabelDecodeSpec> {
832        self.label_decode.as_ref()
833    }
834}
835
836/// Recovers the label decode description a frame schema declares.
837///
838/// Returns `None` for an explicit-label frame, which must not declare one. A key-encoded frame must
839/// declare one, so a missing description is an error rather than a reason to reuse a caller-side
840/// binding; [`series_frame_schema`] and [`SeriesFrameDeclaration::parse`] enforce that both ways.
841pub fn series_frame_label_decode(schema: &Schema) -> Result<Option<LabelDecodeSpec>> {
842    Ok(SeriesFrameDeclaration::parse(schema)?.label_decode)
843}
844
845/// The two declarations the encoder and decoder dispatch on.
846///
847/// A frame's time mode follows from its content and its identity is the label mode, so those two
848/// are all that has to travel next to the column layout.
849#[derive(Clone, Copy, Debug, PartialEq, Eq)]
850struct FrameShape {
851    content: FrameContent,
852    labels: FrameLabelMode,
853}
854
855impl FrameShape {
856    fn of(schema: &SeriesSchema, labels: FrameLabelMode) -> Self {
857        let content = match schema.eval_grid {
858            Some(_) => FrameContent::Evaluated,
859            None => FrameContent::Raw,
860        };
861        Self { content, labels }
862    }
863
864    fn aggregate_state(labels: FrameLabelMode) -> Self {
865        Self {
866            content: FrameContent::AggregateState,
867            labels,
868        }
869    }
870}
871
872/// Bounded multi-row builder for finite series frame batches.
873///
874/// Rows accumulate until the row limit or the estimated byte limit is reached; the next cursor call
875/// then emits them as one batch. `max_bytes` is stored as the effective group cap
876/// `min(requested, i32::MAX)`, and each row carries a measure that dominates every cumulative Arrow
877/// offset domain, so any admitted group can be encoded. The measure is an internal work estimate, not
878/// an exact IPC size and not a resident-memory cap: one individually representable row that exceeds
879/// the requested cap is still accepted and emitted alone, because that slice cannot be split into
880/// smaller legal rows.
881pub struct SeriesFrameBuilder {
882    schema: SeriesSchema,
883    frame_schema: SchemaRef,
884    shape: FrameShape,
885    max_rows: usize,
886    max_bytes: usize,
887    rows: Vec<FrameRow>,
888    bytes: usize,
889}
890
891impl SeriesFrameBuilder {
892    /// Default maximum rows in one packed batch when no explicit bound is needed.
893    pub const DEFAULT_MAX_ROWS: usize = 256;
894    /// Default maximum estimated encoded bytes in one packed batch when no explicit bound is
895    /// needed.
896    pub const DEFAULT_MAX_BYTES: usize = 1024 * 1024;
897
898    /// Creates an empty builder for the given schema, identity declaration, and nonzero bounds.
899    ///
900    /// The frame schema is built once here and reused for every emitted batch. It declares
901    /// everything the rows carry except the stream's producer ordering, which only the streaming
902    /// layer knows and adds when it declares the batch.
903    pub fn try_new(
904        schema: &SeriesSchema,
905        labels: FrameLabelMode,
906        decode: Option<&LabelDecodeSpec>,
907        max_rows: usize,
908        max_bytes: usize,
909    ) -> Result<Self> {
910        if max_rows == 0 || max_bytes == 0 {
911            return invalid_series("series frame limits must be nonzero");
912        }
913        Ok(Self {
914            schema: schema.clone(),
915            frame_schema: series_frame_schema(schema, labels, decode)?,
916            shape: FrameShape::of(schema, labels),
917            max_rows,
918            max_bytes: max_bytes.min(i32::MAX as usize),
919            rows: Vec::new(),
920            bytes: 0,
921        })
922    }
923
924    /// Creates a bounded builder for validated aggregate state rows.
925    pub fn try_new_aggregate_state(
926        state: &AggregateStateSchema,
927        schema: &SeriesSchema,
928        labels: FrameLabelMode,
929        max_rows: usize,
930        max_bytes: usize,
931    ) -> Result<Self> {
932        if max_rows == 0 || max_bytes == 0 {
933            return invalid_series("series frame limits must be nonzero");
934        }
935        Ok(Self {
936            schema: schema.clone(),
937            frame_schema: aggregate_state_frame_schema(state, schema, labels)?,
938            shape: FrameShape::aggregate_state(labels),
939            max_rows,
940            max_bytes: max_bytes.min(i32::MAX as usize),
941            rows: Vec::new(),
942            bytes: 0,
943        })
944    }
945
946    /// The frame schema of every batch this builder emits.
947    pub fn schema(&self) -> &SchemaRef {
948        &self.frame_schema
949    }
950
951    /// Emits the accumulated rows as one batch, or `None` when nothing is buffered.
952    pub fn flush(&mut self) -> Result<Option<RecordBatch>> {
953        if self.rows.is_empty() {
954            return Ok(None);
955        }
956        let batch = encode_rows(&self.frame_schema, self.shape, &self.rows)?;
957        self.rows.clear();
958        self.bytes = 0;
959        Ok(Some(batch))
960    }
961
962    /// Whether the buffered rows reached either bound.
963    fn is_full(&self) -> bool {
964        self.rows.len() >= self.max_rows || self.bytes >= self.max_bytes
965    }
966
967    /// Bytes available to an evaluated row that is being assembled before cursor advancement.
968    fn available_bytes(&self) -> Option<usize> {
969        if self.rows.len() >= self.max_rows || self.bytes >= self.max_bytes {
970            None
971        } else {
972            Some(self.max_bytes - self.bytes)
973        }
974    }
975
976    /// Whether `row` may join the buffered rows without crossing either bound.
977    ///
978    /// An empty builder accepts any individually measured row; a group total that would overflow
979    /// or exceed the cap flushes the buffered rows before this row is consumed, never dropping or
980    /// splitting the row.
981    fn accepts(&self, row: &FrameRow) -> bool {
982        self.rows.is_empty()
983            || (self.bytes < self.max_bytes
984                && self.rows.len() < self.max_rows
985                && self
986                    .bytes
987                    .checked_add(row.bytes)
988                    .is_some_and(|total| total <= self.max_bytes))
989    }
990
991    /// Buffers one individually measured row.
992    fn push(&mut self, row: FrameRow) -> Result<()> {
993        self.bytes = add_checked(self.bytes, row.bytes)?;
994        self.rows.push(row);
995        Ok(())
996    }
997
998    /// Checks that a cursor walks the same fields, identity, and time of what this builder encodes.
999    ///
1000    /// The grid is compared by its specification rather than by whether one is present: a cursor
1001    /// holding positions on one grid and a builder encoding them under another would write the same
1002    /// numbers meaning different instants, and nothing downstream could tell. Two grids with equal
1003    /// bounds are the same grid, so they compare equal however they were allocated.
1004    fn matches(&self, schema: &SeriesSchema, shape: FrameShape) -> Result<()> {
1005        let same_fields = schema.fields.len() == self.schema.fields.len()
1006            && schema
1007                .fields
1008                .iter()
1009                .zip(self.schema.fields.iter())
1010                .all(|(left, right)| left.name == right.name);
1011        let same_grid = match (&schema.eval_grid, &self.schema.eval_grid) {
1012            (None, None) => true,
1013            (Some(left), Some(right)) => left.spec() == right.spec(),
1014            _ => false,
1015        };
1016        if shape != self.shape || !same_grid || !same_fields {
1017            return invalid_series("series frame cursor and builder schema mismatch");
1018        }
1019        Ok(())
1020    }
1021}
1022
1023/// One validated chunk walked into a bounded builder, one row at a time.
1024///
1025/// The two sample shapes differ only in how a row's positions are addressed and where its identity
1026/// comes from, so one cursor serves both: a raw chunk is walked segment by segment over the
1027/// timestamps it carries, an evaluated chunk run by run over the grid positions it holds. Each row is
1028/// measured once and retried after a flush, so a flush error never consumes input.
1029pub struct SeriesFrameCursor {
1030    schema: SeriesSchema,
1031    shape: FrameShape,
1032    walk: ChunkWalk,
1033    pending: Option<FrameRow>,
1034}
1035
1036/// Where a cursor is in the chunk it walks.
1037enum ChunkWalk {
1038    /// A raw chunk: one timestamp per row of samples.
1039    Raw(RawWalk),
1040    /// An evaluated chunk: absolute grid positions, carried as runs.
1041    Evaluated(EvaluatedWalk),
1042    State(StateWalk),
1043}
1044
1045/// The walk state of one raw chunk.
1046///
1047/// The chunk's fields are walked segment by segment, so a row never spans two segments of one field
1048/// and no per-row temporary vectors are allocated.
1049struct RawWalk {
1050    chunk: RawSeriesChunk,
1051    /// The dense segment each field is being read from.
1052    segments: Vec<usize>,
1053    /// How much of each field's current segment has been consumed.
1054    offsets: Vec<usize>,
1055    /// How many timestamps have been consumed.
1056    pos: usize,
1057}
1058
1059struct StateWalk {
1060    series: StateSeries,
1061    is_last: bool,
1062    runs: Vec<GridRun>,
1063    done: bool,
1064}
1065
1066/// The walk state of one evaluated chunk.
1067///
1068/// The runs are collected once, so a row is one intersection of a run with a sample segment and the
1069/// walk never re-derives the runs per row. A chunk that carries no position keeps a single `closing`
1070/// flag: it still owes one row, and that row is what tells its consumer the chain ended.
1071struct EvaluatedWalk {
1072    series: Series,
1073    is_last: bool,
1074    /// The runs of carried rows, in absolute grid order and never empty.
1075    runs: Vec<GridRun>,
1076    /// The run being read.
1077    run: usize,
1078    /// How much of the current run has been consumed.
1079    offset: usize,
1080    /// The dense segment each field is being read from.
1081    segments: Vec<usize>,
1082    offsets: Vec<usize>,
1083    /// Whether the one row a chunk without positions still owes is yet to be emitted.
1084    closing: bool,
1085}
1086
1087impl SeriesFrameCursor {
1088    /// Validates one public raw chunk's shape and label mode once, taking ownership of it.
1089    pub fn try_new_raw(
1090        schema: &SeriesSchema,
1091        mode: FrameLabelMode,
1092        chunk: RawSeriesChunk,
1093    ) -> Result<Self> {
1094        let RawSeriesChunk {
1095            primary_key,
1096            metric,
1097            time,
1098            fields,
1099            is_last,
1100        } = chunk;
1101        let chunk = RawSeriesChunk::try_new(schema, primary_key, metric, time, fields, is_last)?;
1102        match (mode, &chunk.metric) {
1103            (FrameLabelMode::Key, None) | (FrameLabelMode::Explicit, Some(_)) => {}
1104            _ => return invalid_series("raw chunk label mode does not match frame mode"),
1105        }
1106        let segments = vec![0usize; chunk.fields.len()];
1107        let offsets = vec![0usize; chunk.fields.len()];
1108        Ok(Self {
1109            schema: schema.clone(),
1110            shape: FrameShape::of(schema, mode),
1111            walk: ChunkWalk::Raw(RawWalk {
1112                chunk,
1113                segments,
1114                offsets,
1115                pos: 0,
1116            }),
1117            pending: None,
1118        })
1119    }
1120
1121    /// Validates one evaluated chunk against the frame's schema, grid, and finality rules.
1122    ///
1123    /// A chunk that carries no position is legal only when it closes its series: it is how a
1124    /// consumer tells "nothing more here" from "no more input", and a chain of empty chunks that
1125    /// close nothing would never make progress. It still occupies one frame row, because dropping it
1126    /// would drop the finality it exists to carry.
1127    pub fn try_new_evaluated(schema: &SeriesSchema, series: Series, is_last: bool) -> Result<Self> {
1128        if schema.eval_grid.is_none() {
1129            return invalid_series("an evaluated chunk needs a schema with an evaluation grid");
1130        }
1131        let series = Series::try_new(
1132            schema,
1133            series.metric.clone(),
1134            series.time.clone(),
1135            series.fields.clone(),
1136        )?;
1137        if series.time.grid().is_none() {
1138            return invalid_series("an evaluated chunk must be addressed on a grid");
1139        }
1140        if series.time.is_empty() && !is_last {
1141            return invalid_series("an evaluated chunk without positions must close its series");
1142        }
1143        // The runs are the only runs this chunk carries, so collecting them once is what keeps the
1144        // walk from re-deriving them per row; a maximal run is merged by the axis itself.
1145        let runs: Vec<GridRun> = series.time.runs().collect();
1146        let segments = vec![0usize; series.fields.len()];
1147        let offsets = vec![0usize; series.fields.len()];
1148        Ok(Self {
1149            schema: schema.clone(),
1150            shape: FrameShape::of(schema, FrameLabelMode::Explicit),
1151            walk: ChunkWalk::Evaluated(EvaluatedWalk {
1152                closing: runs.is_empty(),
1153                series,
1154                is_last,
1155                runs,
1156                run: 0,
1157                offset: 0,
1158                segments,
1159                offsets,
1160            }),
1161            pending: None,
1162        })
1163    }
1164
1165    /// Validates and walks one aggregate state chunk.
1166    pub fn try_new_aggregate_state(
1167        state: &AggregateStateSchema,
1168        schema: &SeriesSchema,
1169        series: StateSeries,
1170        is_last: bool,
1171    ) -> Result<Self> {
1172        if schema.eval_grid.is_none() {
1173            return invalid_series("an aggregate state chunk needs an evaluation grid");
1174        }
1175        if series.states.len() != schema.fields.len()
1176            || series
1177                .states
1178                .iter()
1179                .any(|field| field.len() != series.time.len())
1180        {
1181            return invalid_series("aggregate state field shape mismatch");
1182        }
1183        if series.time.grid().map(|grid| grid.spec())
1184            != schema.eval_grid.as_ref().map(|grid| grid.spec())
1185        {
1186            return invalid_series("aggregate state chunk grid does not match schema");
1187        }
1188        // A position's payload has to be the family its kind declares, and a histogram payload has to
1189        // keep its compensation aligned with its live value: the kernel indexes the compensation by
1190        // the value's bucket positions, so a layout that drifted is an out-of-bounds add rather than
1191        // a loss of precision. Both are refused here, at the producer, rather than written.
1192        let histogram = state.kind.is_histogram();
1193        for payload in series.states.iter().flatten().flatten() {
1194            match payload {
1195                StatePayload::Float(_) if histogram => {
1196                    return invalid_series("a histogram state kind carries numeric state");
1197                }
1198                StatePayload::Histogram(_) if !histogram => {
1199                    return invalid_series("a numeric state kind carries histogram state");
1200                }
1201                StatePayload::Histogram(payload) => payload.validate_layout()?,
1202                StatePayload::Float(_) => {}
1203            }
1204        }
1205        let mut states = series.states;
1206        // A position is carried when some field of it was folded, which is what the axis says. When
1207        // every position is carried - the shape a fold produces whenever each group has a sample at
1208        // each of its points - the axis and the states are already the ones this walk reads, so
1209        // nothing is rebuilt. Deciding that first keeps the common case free of a mask, a position
1210        // list and a second axis.
1211        let every_position_carried = state.kind
1212            == crate::series::aggregate_state::AggregateStateKind::Group
1213            || (0..series.time.len()).all(|row| states.iter().any(|field| field[row].is_some()));
1214        let time = if every_position_carried {
1215            series.time
1216        } else {
1217            let contributing = (0..series.time.len())
1218                .map(|row| states.iter().any(|field| field[row].is_some()))
1219                .collect::<Vec<_>>();
1220            let carried = series
1221                .time
1222                .positions()
1223                .filter_map(|(position, row)| contributing[row].then_some(position))
1224                .collect::<Vec<_>>();
1225            let spans = positions_to_spans(&carried);
1226            for field in &mut states {
1227                let mut row = 0;
1228                field.retain(|_| {
1229                    let keep = contributing[row];
1230                    row += 1;
1231                    keep
1232                });
1233            }
1234            TimeAxis::from_grid_spans(series.time.grid().expect("validated grid").clone(), spans)?
1235        };
1236        let runs: Vec<GridRun> = time.runs().collect();
1237        let series = StateSeries {
1238            metric: series.metric,
1239            time,
1240            states,
1241        };
1242        Ok(Self {
1243            schema: schema.clone(),
1244            shape: FrameShape::aggregate_state(FrameLabelMode::Explicit),
1245            walk: ChunkWalk::State(StateWalk {
1246                series,
1247                is_last,
1248                runs,
1249                done: false,
1250            }),
1251            pending: None,
1252        })
1253    }
1254
1255    /// Appends rows to the builder until one batch is ready or this chunk is exhausted.
1256    ///
1257    /// `None` means the cursor is exhausted; calling again returns `None` without touching the
1258    /// builder. The single pending row is measured once by [`Self::next_row`] and retried after the
1259    /// buffered rows are emitted.
1260    pub fn append_to(&mut self, builder: &mut SeriesFrameBuilder) -> Result<Option<RecordBatch>> {
1261        builder.matches(&self.schema, self.shape)?;
1262        loop {
1263            let row = match self.pending.take() {
1264                Some(row) => row,
1265                None => match self.next_row(builder.available_bytes())? {
1266                    Some(row) => {
1267                        self.pending = Some(row);
1268                        continue;
1269                    }
1270                    None => return Ok(None),
1271                },
1272            };
1273            if !builder.accepts(&row) {
1274                // Reinstate the row before flushing so a flush error cannot consume it.
1275                self.pending = Some(row);
1276                let batch = builder
1277                    .flush()?
1278                    .ok_or_else(|| err("frame builder rejected a row without buffered rows"))?;
1279                return Ok(Some(batch));
1280            }
1281            builder.push(row)?;
1282            if builder.is_full()
1283                && let Some(batch) = builder.flush()?
1284            {
1285                return Ok(Some(batch));
1286            }
1287        }
1288    }
1289
1290    /// Builds and measures the next row, or `None` when the chunk is exhausted.
1291    fn next_row(&mut self, available_bytes: Option<usize>) -> Result<Option<FrameRow>> {
1292        match &mut self.walk {
1293            ChunkWalk::Raw(walk) => walk.next_row(),
1294            ChunkWalk::Evaluated(walk) => walk.next_row(available_bytes),
1295            ChunkWalk::State(walk) => walk.next_row(),
1296        }
1297    }
1298}
1299
1300impl StateWalk {
1301    fn next_row(&mut self) -> Result<Option<FrameRow>> {
1302        if self.done {
1303            return Ok(None);
1304        }
1305        self.done = true;
1306        let states = std::mem::take(&mut self.series.states);
1307        let time = RowTime::Spans(
1308            self.runs
1309                .iter()
1310                .map(|run| GridSpan::new(run.position, run.len))
1311                .collect(),
1312        );
1313        let mut row = FrameRow {
1314            key: None,
1315            metric: Some(self.series.metric.clone()),
1316            is_last: self.is_last,
1317            time,
1318            payload: RowPayload::States(states),
1319            bytes: 0,
1320        };
1321        row.bytes = measure_row(&row)?;
1322        Ok(Some(row))
1323    }
1324}
1325
1326impl RawWalk {
1327    /// Builds the next row, or `None` when the chunk is exhausted.
1328    ///
1329    /// The chunk fields are walked twice: once to find how many positions every field can cover, and
1330    /// once to slice them. A row does collect one slice per field, so the saving here is not
1331    /// allocation-free rows but no row spanning two segments of one field, which is what keeps the
1332    /// slice arithmetic per row a single offset. The offsets advance only after the row measure
1333    /// succeeded.
1334    fn next_row(&mut self) -> Result<Option<FrameRow>> {
1335        let Self {
1336            chunk,
1337            segments,
1338            offsets,
1339            pos,
1340        } = self;
1341        if *pos >= chunk.time.len() {
1342            return Ok(None);
1343        }
1344        let time_axis = chunk.time.as_buffer();
1345        let mut take = time_axis.len() - *pos;
1346        for (index, field) in chunk.fields.iter().enumerate() {
1347            let part = segment(field, segments[index])?;
1348            take = take.min(part.len().saturating_sub(offsets[index]));
1349        }
1350        if take == 0 {
1351            return invalid_series("empty sample segment");
1352        }
1353        let mut samples = Vec::with_capacity(chunk.fields.len());
1354        for (index, field) in chunk.fields.iter().enumerate() {
1355            let part = segment(field, segments[index])?;
1356            samples.push(part.slice(offsets[index], take)?);
1357        }
1358        let mut row = FrameRow {
1359            key: Some(chunk.primary_key.clone()),
1360            metric: chunk.metric.clone(),
1361            is_last: chunk.is_last && *pos + take == chunk.time.len(),
1362            time: RowTime::Timestamps(time_axis.slice(*pos, take)),
1363            payload: RowPayload::Samples(samples),
1364            bytes: 0,
1365        };
1366        row.bytes = measure_row(&row)?;
1367        *pos += take;
1368        for (index, field) in chunk.fields.iter().enumerate() {
1369            let length = segment(field, segments[index])?.len();
1370            offsets[index] += take;
1371            if offsets[index] == length {
1372                segments[index] += 1;
1373                offsets[index] = 0;
1374            }
1375        }
1376        Ok(Some(row))
1377    }
1378}
1379
1380impl EvaluatedWalk {
1381    /// Builds the next row, or `None` when the chunk is exhausted.
1382    ///
1383    /// A row may cover several run/segment intersections, but never crosses a dense segment
1384    /// boundary. Grid holes are represented by separate spans while the sample slice stays
1385    /// contiguous. Cursor state is committed only after the complete row has been measured.
1386    fn next_row(&mut self, available_bytes: Option<usize>) -> Result<Option<FrameRow>> {
1387        let Self {
1388            series,
1389            is_last,
1390            runs,
1391            run,
1392            offset,
1393            segments,
1394            offsets,
1395            closing,
1396        } = self;
1397        if *closing {
1398            // A chunk that carries no position still owes its consumer one row: the row that says the
1399            // chain ends here. It holds no grid position and no sample, and each field is kept as the
1400            // producer built it - an empty float stays float, an empty histogram stays histogram - so a
1401            // decoder sees an empty closing chunk of the same payload kind rather than a missing one or
1402            // one silently converted.
1403            let mut samples = Vec::with_capacity(series.fields.len());
1404            for field in series.fields.iter() {
1405                samples.push(field.clone());
1406            }
1407            let mut row = FrameRow {
1408                key: None,
1409                metric: Some(series.metric.clone()),
1410                is_last: *is_last,
1411                time: RowTime::Spans(Vec::new()),
1412                payload: RowPayload::Samples(samples),
1413                bytes: 0,
1414            };
1415            row.bytes = measure_row(&row)?;
1416            *closing = false;
1417            return Ok(Some(row));
1418        }
1419        let Some(_) = runs.get(*run) else {
1420            return Ok(None);
1421        };
1422        let mut next_run = *run;
1423        let mut next_offset = *offset;
1424        let mut next_segments = segments.clone();
1425        let mut next_offsets = offsets.clone();
1426        let mut total = 0usize;
1427        let mut row: Option<FrameRow> = None;
1428        while let Some(current) = runs.get(next_run) {
1429            let remaining = current.len - next_offset;
1430            let mut take = remaining;
1431            let mut segment_remaining_lengths = Vec::with_capacity(series.fields.len());
1432            for (index, field) in series.fields.iter().enumerate() {
1433                let part = segment(field, next_segments[index])?;
1434                let segment_remaining = part.len().saturating_sub(next_offsets[index]);
1435                segment_remaining_lengths.push(segment_remaining);
1436                take = take.min(segment_remaining);
1437            }
1438            let reaches_segment_boundary = segment_remaining_lengths.contains(&take);
1439            if take == 0 {
1440                return invalid_series("empty sample segment");
1441            }
1442            let proposed_total = add_checked(total, take)?;
1443            let sample_growth = sample_range_growth(&series.fields, segments, total, take)?;
1444            if let Some(row) = &mut row {
1445                let RowTime::Spans(row_spans) = &mut row.time else {
1446                    unreachable!("evaluated row has spans")
1447                };
1448                let proposed_span_count = row_spans
1449                    .len()
1450                    .checked_add(1)
1451                    .ok_or_else(|| err("raw series frame offset overflow"))?;
1452                checked_offset(proposed_span_count)?;
1453                checked_offset(proposed_total)?;
1454                let proposed_bytes = add_checked(
1455                    add_checked(row.bytes, add_checked(SPAN_CHARGE, 2)?)?,
1456                    sample_growth,
1457                )?;
1458                if available_bytes.is_some_and(|available| proposed_bytes > available) {
1459                    break;
1460                }
1461                row_spans.push(GridSpan::new(current.position + next_offset, take));
1462                row.is_last = *is_last && next_run + 1 == runs.len() && take == remaining;
1463                row.bytes = proposed_bytes;
1464            } else {
1465                let mut candidate = FrameRow {
1466                    key: None,
1467                    metric: Some(series.metric.clone()),
1468                    is_last: *is_last && next_run + 1 == runs.len() && take == remaining,
1469                    time: RowTime::Spans(vec![GridSpan::new(current.position + next_offset, take)]),
1470                    payload: RowPayload::Samples(Vec::new()),
1471                    bytes: 0,
1472                };
1473                candidate.bytes = add_checked(measure_row(&candidate)?, sample_growth)?;
1474                row = Some(candidate);
1475            }
1476            total = proposed_total;
1477            next_offset += take;
1478            if next_offset == current.len {
1479                next_run += 1;
1480                next_offset = 0;
1481            }
1482            for (index, field) in series.fields.iter().enumerate() {
1483                let length = segment(field, next_segments[index])?.len();
1484                next_offsets[index] += take;
1485                if next_offsets[index] == length {
1486                    next_segments[index] += 1;
1487                    next_offsets[index] = 0;
1488                }
1489            }
1490            // An individually oversized atomic intersection must be emitted alone.
1491            if available_bytes.is_none()
1492                || available_bytes.is_some_and(|available| row.as_ref().unwrap().bytes > available)
1493                || reaches_segment_boundary
1494            {
1495                break;
1496            }
1497        }
1498        if let Some(row) = &mut row {
1499            row.payload = RowPayload::Samples(
1500                series
1501                    .fields
1502                    .iter()
1503                    .enumerate()
1504                    .map(|(index, field)| {
1505                        segment(field, segments[index])?.slice(offsets[index], total)
1506                    })
1507                    .collect::<Result<Vec<_>>>()?,
1508            );
1509        }
1510        *run = next_run;
1511        *offset = next_offset;
1512        segments.clone_from(&next_segments);
1513        offsets.clone_from(&next_offsets);
1514        Ok(row)
1515    }
1516}
1517
1518/// The next dense segment of one field, or an error when the walk left the segment list.
1519fn segment(field: &Samples, index: usize) -> Result<&Samples> {
1520    field
1521        .segments()
1522        .get(index)
1523        .ok_or_else(|| err("empty sample segment"))
1524}
1525
1526/// Packs one raw chunk, retaining the `Vec<RecordBatch>` compatibility signature.
1527///
1528/// The chunk packs into bounded multi-row batches; callers that need streaming behavior should
1529/// drive [`SeriesFrameCursor`] and [`SeriesFrameBuilder`] directly instead of collecting.
1530pub fn pack_raw_series_chunk(
1531    schema: &SeriesSchema,
1532    mode: FrameLabelMode,
1533    decode: Option<&LabelDecodeSpec>,
1534    chunk: &RawSeriesChunk,
1535) -> Result<Vec<RecordBatch>> {
1536    let mut builder = SeriesFrameBuilder::try_new(
1537        schema,
1538        mode,
1539        decode,
1540        SeriesFrameBuilder::DEFAULT_MAX_ROWS,
1541        SeriesFrameBuilder::DEFAULT_MAX_BYTES,
1542    )?;
1543    let mut cursor = SeriesFrameCursor::try_new_raw(schema, mode, chunk.clone())?;
1544    let mut batches = Vec::new();
1545    while let Some(batch) = cursor.append_to(&mut builder)? {
1546        batches.push(batch);
1547    }
1548    if let Some(batch) = builder.flush()? {
1549        batches.push(batch);
1550    }
1551    Ok(batches)
1552}
1553
1554/// One pending output row: one chunk's identity, finality, time slice, and one dense sample slice per
1555/// field, with its checked encoded-size measure.
1556///
1557/// This is the codec's own row, not a third runtime chunk type: `RawSeriesChunk` and `Series` are
1558/// what a producer and a consumer see, and this is what the encoder writes between them.
1559struct FrameRow {
1560    /// The encoded storage key. A raw row always carries the key it was read under, a key-encoded
1561    /// frame names its series only by it, and an evaluated row has none.
1562    key: Option<Buffer>,
1563    /// Complete labels, present exactly for explicit identity.
1564    metric: Option<SeriesLabels>,
1565    /// Whether this row closes the chunk chain it belongs to.
1566    is_last: bool,
1567    /// The positions this row's samples are addressed at.
1568    time: RowTime,
1569    payload: RowPayload,
1570    bytes: usize,
1571}
1572
1573enum RowPayload {
1574    Samples(Vec<Samples>),
1575    States(Vec<Vec<Option<StatePayload>>>),
1576}
1577
1578/// How one row addresses the time of its samples.
1579enum RowTime {
1580    /// The timestamps of this row's samples, strictly increasing within the row.
1581    Timestamps(ScalarBuffer<i64>),
1582    /// Runs of absolute grid positions, ordered, non-overlapping, and never zero length.
1583    Spans(Vec<GridSpan>),
1584}
1585
1586impl RowTime {
1587    /// How many grid positions or timestamps this row's samples cover.
1588    ///
1589    /// The sum is checked because this is the first place a decoded row's positions are counted, and
1590    /// a frame can name spans whose lengths overflow `usize` long before any span is validated
1591    /// against the grid it claims to sit on. Adding them up unchecked would panic on a hostile frame
1592    /// in a debug build and wrap in a release build, both before the grid check that should have
1593    /// refused it.
1594    fn len(&self) -> Result<usize> {
1595        match self {
1596            Self::Timestamps(timestamps) => Ok(timestamps.len()),
1597            Self::Spans(spans) => spans.iter().try_fold(0usize, |total, span| {
1598                total
1599                    .checked_add(span.len())
1600                    .ok_or_else(|| err("grid span length overflow"))
1601            }),
1602        }
1603    }
1604}
1605
1606/// Measures the added dense positions without slicing Arrow arrays or rescanning histogram tables.
1607fn sample_range_growth(
1608    fields: &SeriesFields,
1609    segments: &[usize],
1610    previous: usize,
1611    added: usize,
1612) -> Result<usize> {
1613    let end = previous
1614        .checked_add(added)
1615        .ok_or_else(|| err("raw series frame offset overflow"))?;
1616    checked_offset(end)?;
1617    let bitmap_growth = bitmap_bytes(end).saturating_sub(bitmap_bytes(previous));
1618    fields
1619        .iter()
1620        .enumerate()
1621        .try_fold(0usize, |bytes, (index, field)| {
1622            let part = segment(field, segments[index])?;
1623            let (value_width, bitmap_count, table_charge) = match part
1624                .dense()
1625                .ok_or_else(|| err("sample segment is not dense"))?
1626            {
1627                DenseSamplesRef::Float(_) => (8, 1, None),
1628                DenseSamplesRef::Histogram(values) => (4, 1, Some(values)),
1629                DenseSamplesRef::Mixed(values) => (12, 2, Some(values.histograms())),
1630            };
1631            let mut charge = mul_checked(added, value_width)?;
1632            charge = add_checked(charge, mul_checked(bitmap_growth, bitmap_count)?)?;
1633            if previous == 0 {
1634                charge = add_checked(charge, FIELD_CHARGE)?;
1635                if let Some(values) = table_charge {
1636                    charge = add_checked(charge, histogram_table_charge(values)?)?;
1637                }
1638            }
1639            add_checked(bytes, charge)
1640        })
1641}
1642
1643fn histogram_table_charge(values: &HistogramSamples) -> Result<usize> {
1644    histogram_array_charge(values.batch().as_arrow())
1645}
1646
1647/// Bytes a histogram table holds: one row's fixed part per histogram plus every bucket, span and
1648/// custom bound its list columns carry, so a layout with more buckets is charged more.
1649fn histogram_array_charge(table: &StructArray) -> Result<usize> {
1650    checked_offset(table.len())?;
1651    let mut bytes = add_checked(
1652        HISTOGRAM_TABLE_CHARGE,
1653        mul_checked(table.len(), HISTOGRAM_ROW_CHARGE)?,
1654    )?;
1655    for (position, width) in HISTOGRAM_LIST_WIDTHS.iter().enumerate() {
1656        let list = table
1657            .column(7 + position)
1658            .as_any()
1659            .downcast_ref::<ListArray>()
1660            .ok_or_else(|| err("histogram table schema mismatch"))?;
1661        // Charge the visible offset range, not the backing child array: the table may be sliced.
1662        let offsets = list.value_offsets();
1663        let first = offsets
1664            .first()
1665            .copied()
1666            .ok_or_else(|| err("histogram table schema mismatch"))?;
1667        let last = offsets
1668            .get(list.len())
1669            .copied()
1670            .ok_or_else(|| err("histogram table schema mismatch"))?;
1671        let span = last
1672            .checked_sub(first)
1673            .and_then(|span| usize::try_from(span).ok())
1674            .ok_or_else(|| err("histogram table offsets are invalid"))?;
1675        bytes = add_checked(bytes, mul_checked(span, *width)?)?;
1676    }
1677    Ok(bytes)
1678}
1679
1680fn state_charges(fields: &[Vec<Option<StatePayload>>]) -> Result<usize> {
1681    fields.iter().try_fold(0usize, |bytes, values| {
1682        let mut charge = FIELD_CHARGE;
1683        for payload in values.iter().flatten() {
1684            charge = add_checked(charge, state_payload_charge(payload)?)?;
1685        }
1686        add_checked(bytes, charge)
1687    })
1688}
1689
1690/// Bytes one position's state holds.
1691///
1692/// A numeric payload's components are inline and have always been charged as such. A histogram
1693/// payload is charged for what it actually carries: the boxed state, then both histograms' rows,
1694/// spans, buckets and custom bounds, so a wide bucket layout pays for itself and an empty
1695/// placeholder costs almost nothing.
1696fn state_payload_charge(payload: &StatePayload) -> Result<usize> {
1697    match payload {
1698        // The numeric components, inline: four `f64` and one flag.
1699        StatePayload::Float(_) => Ok(8 * 4 + 1),
1700        StatePayload::Histogram(payload) => {
1701            let histograms = add_checked(
1702                histogram_array_charge(payload.value.as_arrow())?,
1703                histogram_array_charge(payload.compensation.as_arrow())?,
1704            )?;
1705            add_checked(histograms, size_of::<HistogramState>())
1706        }
1707    }
1708}
1709
1710/// A histogram with no buckets: what an absent state position holds under the shared mask.
1711fn empty_histogram() -> HistogramView<'static> {
1712    let side = BucketSideView {
1713        span_offsets: &[],
1714        span_lengths: &[],
1715        buckets: &[],
1716    };
1717    HistogramView {
1718        schema: 0,
1719        zero_threshold: 0.0,
1720        sum: 0.0,
1721        count: 0.0,
1722        zero_count: 0.0,
1723        reset_hint: CounterResetHint::Unknown,
1724        start_timestamp: None,
1725        custom_values: &[],
1726        positive: side,
1727        negative: side,
1728    }
1729}
1730
1731fn missing_state_component() -> crate::error::Error {
1732    err("present aggregate state has a missing component")
1733}
1734
1735/// The states one field of a state row carries, in the row's own position order.
1736fn state_field(row: &FrameRow, index: usize) -> Result<&[Option<StatePayload>]> {
1737    let RowPayload::States(fields) = &row.payload else {
1738        return invalid_series("state frame row carries sample payload");
1739    };
1740    fields
1741        .get(index)
1742        .map(Vec::as_slice)
1743        .ok_or_else(|| err("state field count mismatch"))
1744}
1745
1746fn sample_charges(samples: &[Samples]) -> Result<usize> {
1747    samples.iter().try_fold(0usize, |bytes, sample| {
1748        add_checked(bytes, sample_charge(sample)?)
1749    })
1750}
1751
1752fn sample_charge(sample: &Samples) -> Result<usize> {
1753    let mut bytes = FIELD_CHARGE;
1754    match sample
1755        .dense()
1756        .ok_or_else(|| err("sample segment is not dense"))?
1757    {
1758        DenseSamplesRef::Float(values) => add_checked(bytes, float_charge(values.len())?),
1759        DenseSamplesRef::Histogram(values) => add_checked(bytes, histogram_charge(values)?),
1760        DenseSamplesRef::Mixed(values) => {
1761            bytes = add_checked(bytes, float_charge(values.floats().len())?)?;
1762            add_checked(bytes, histogram_charge(values.histograms())?)
1763        }
1764    }
1765}
1766
1767fn measure_row(row: &FrameRow) -> Result<usize> {
1768    let time_len = row.time.len()?;
1769    let key_len = row.key.as_ref().map(Buffer::len).unwrap_or(0);
1770    checked_offset(key_len)?;
1771    checked_offset(time_len)?;
1772    let mut bytes = add_checked(ROW_CHARGE, key_len)?;
1773    bytes = match &row.time {
1774        RowTime::Timestamps(timestamps) => add_checked(bytes, mul_checked(timestamps.len(), 8)?)?,
1775        // Two `u64` per span, plus the list's own offsets and validity.
1776        RowTime::Spans(spans) => add_checked(
1777            add_checked(bytes, mul_checked(spans.len(), SPAN_CHARGE)?)?,
1778            mul_checked(spans.len(), 2)?,
1779        )?,
1780    };
1781    bytes = add_checked(
1782        bytes,
1783        match &row.payload {
1784            RowPayload::Samples(samples) => sample_charges(samples)?,
1785            RowPayload::States(fields) => state_charges(fields)?,
1786        },
1787    )?;
1788    if let Some(metric) = &row.metric {
1789        if let Some(name) = metric.name() {
1790            checked_offset(name.len())?;
1791            bytes = add_checked(bytes, name.len())?;
1792        }
1793        checked_offset(metric.tags().len())?;
1794        bytes = add_checked(bytes, mul_checked(metric.tags().len(), 16)?)?;
1795        let mut names = 0usize;
1796        let mut values = 0usize;
1797        for label in metric.tags() {
1798            names = add_checked(names, label.name.len())?;
1799            values = add_checked(values, label.value.len())?;
1800        }
1801        checked_offset(names)?;
1802        checked_offset(values)?;
1803        bytes = add_checked(bytes, names)?;
1804        bytes = add_checked(bytes, values)?;
1805    }
1806    Ok(bytes)
1807}
1808
1809/// Float values plus their validity bitmap.
1810fn float_charge(len: usize) -> Result<usize> {
1811    checked_offset(len)?;
1812    add_checked(mul_checked(len, 8)?, bitmap_bytes(len))
1813}
1814
1815/// Reference indices plus their bitmap and the full referenced histogram table.
1816fn histogram_charge(values: &HistogramSamples) -> Result<usize> {
1817    let indices = values.indices();
1818    checked_offset(indices.len())?;
1819    add_checked(
1820        add_checked(mul_checked(indices.len(), 4)?, bitmap_bytes(indices.len()))?,
1821        histogram_table_charge(values)?,
1822    )
1823}
1824
1825fn compact_histogram(values: &HistogramSamples) -> Result<(ArrayRef, UInt32Array)> {
1826    let indices = values.indices();
1827    // One encoded entry per *distinct* referenced row: a segment that references the same row many
1828    // times would otherwise copy that row once per reference, so a small table plus a long run of
1829    // equal indices would still grow the payload with every position.
1830    let mut carried: HashMap<u32, u32> = HashMap::new();
1831    let mut selected = Vec::new();
1832    let mut remapped = Vec::with_capacity(indices.len());
1833    for index in 0..indices.len() {
1834        if indices.is_valid(index) {
1835            let original = indices.value(index);
1836            let local_index = match carried.get(&original) {
1837                Some(local_index) => *local_index,
1838                None => {
1839                    let local_index = u32::try_from(selected.len())
1840                        .map_err(|_| err("too many referenced histograms in one frame segment"))?;
1841                    selected.push(original);
1842                    carried.insert(original, local_index);
1843                    local_index
1844                }
1845            };
1846            remapped.push(Some(local_index));
1847        } else {
1848            remapped.push(None);
1849        }
1850    }
1851    let selected = UInt32Array::from(selected);
1852    let table = arrow(take(values.batch().as_arrow(), &selected, None))?;
1853    Ok((table, UInt32Array::from(remapped)))
1854}
1855
1856/// The `fields` column of a state frame: one list per row, one item per carried position.
1857///
1858/// A state frame's per-field list carries one item per grid position the row holds, and an item is
1859/// absent exactly where that field has no contribution at that position. The absence lives on the
1860/// item - the child struct's validity - not on the list's own validity, which is per row: a row
1861/// always has a list, with zero or more items in it.
1862///
1863/// One encoder builds this column, so a state frame and a state row handed over in process are the
1864/// same bytes: [`StateFrameRow::from_state_series`] calls it for a single group, and the frame
1865/// encoder calls it for the rows it is about to write.
1866fn encode_state_fields(field_types: &Fields, rows: &[FrameRow]) -> Result<StructArray> {
1867    // A state frame's per-field list carries one item per grid position the row holds, and an
1868    // item is absent exactly where that field has no contribution at that position. The
1869    // absence lives on the item — the child struct's validity — not on the list's own
1870    // validity, which is per row: a row always has a list, with zero or more items in it.
1871    let count = rows.len();
1872    let mut field_arrays: Vec<ArrayRef> = Vec::with_capacity(field_types.len());
1873    for (index, field) in field_types.iter().enumerate() {
1874        let mut lengths = Vec::with_capacity(count);
1875        let mut positions = 0usize;
1876        for row in rows {
1877            let RowPayload::States(fields) = &row.payload else {
1878                return invalid_series("state frame row carries sample payload");
1879            };
1880            let values = fields
1881                .get(index)
1882                .ok_or_else(|| err("state field count mismatch"))?;
1883            if values.len() != row.time.len()? {
1884                return invalid_series("state list length mismatch");
1885            }
1886            lengths.push(values.len());
1887            positions = add_checked(positions, values.len())?;
1888        }
1889
1890        let item = match field.data_type() {
1891            DataType::List(item) => item,
1892            _ => return invalid_series("state field schema mismatch"),
1893        };
1894        let DataType::Struct(components) = item.data_type() else {
1895            return invalid_series("state list item is not a component struct");
1896        };
1897        // Absence lives on the item, so the child struct's validity is one flag per position.
1898        // A row of a state frame always carries states; a caller that hands in the wrong payload
1899        // is refused here rather than panicking inside an iterator.
1900        let mut present = Vec::with_capacity(positions);
1901        for row in rows {
1902            let RowPayload::States(fields) = &row.payload else {
1903                return invalid_series("state frame row carries sample payload");
1904            };
1905            present.extend(fields[index].iter().map(Option::is_some));
1906        }
1907        debug_assert_eq!(present.len(), positions);
1908
1909        // Every component of a field is absent at exactly the same positions - the field's own -
1910        // so they share the one mask, which the child struct already needs.
1911        let nulls = present
1912            .iter()
1913            .any(|present| !present)
1914            .then(|| NullBuffer::from(present.clone()));
1915        // A column's name is the component it declares, so each array is built by reading that
1916        // component off the payload; a payload that does not keep it is refused rather than
1917        // written as a zero.
1918        let arrays: Vec<ArrayRef> = components
1919            .iter()
1920            .map(|component| {
1921                let declared = StateComponent::parse(component.name())?;
1922                let array: ArrayRef = match declared {
1923                    StateComponent::HistogramValue | StateComponent::HistogramCompensation => {
1924                        // One histogram per position, so one batch carries the whole column. An
1925                        // absent position holds an empty placeholder whose value the shared mask
1926                        // makes unreadable, exactly as a null float slot holds a zero.
1927                        let mut histograms = HistogramBatchBuilder::new();
1928                        for row in rows {
1929                            for state in state_field(row, index)? {
1930                                let Some(state) = state else {
1931                                    histograms.push(empty_histogram())?;
1932                                    continue;
1933                                };
1934                                let histogram = state
1935                                    .histogram_component(declared)
1936                                    .ok_or_else(missing_state_component)?;
1937                                if histogram.len() != 1 {
1938                                    return invalid_series(
1939                                        "a histogram state component carries exactly one histogram",
1940                                    );
1941                                }
1942                                let view = histogram.view(0).ok_or_else(missing_state_component)?;
1943                                histograms.push(view)?;
1944                            }
1945                        }
1946                        let batch = histograms.finish()?;
1947                        Arc::new(
1948                            StructArray::try_new(
1949                                histogram_fields(),
1950                                batch.as_arrow().columns().to_vec(),
1951                                nulls.clone(),
1952                            )
1953                            .map_err(|error| err(error.to_string()))?,
1954                        ) as ArrayRef
1955                    }
1956                    StateComponent::Value
1957                    | StateComponent::Mean
1958                    | StateComponent::Compensation
1959                    | StateComponent::Count => {
1960                        let mut floats = Vec::with_capacity(positions);
1961                        for row in rows {
1962                            for state in state_field(row, index)? {
1963                                // A missing position's value is unreadable, so it holds the same
1964                                // zero a null slot has always held here.
1965                                floats.push(match state {
1966                                    None => 0.0,
1967                                    Some(state) => state
1968                                        .float_component(declared)
1969                                        .ok_or_else(missing_state_component)?,
1970                                });
1971                            }
1972                        }
1973                        Arc::new(Float64Array::new(ScalarBuffer::from(floats), nulls.clone()))
1974                    }
1975                    _ => {
1976                        let mut booleans = Vec::with_capacity(positions);
1977                        for row in rows {
1978                            for state in state_field(row, index)? {
1979                                booleans.push(match state {
1980                                    None => false,
1981                                    Some(state) => state
1982                                        .bool_component(declared)
1983                                        .ok_or_else(missing_state_component)?,
1984                                });
1985                            }
1986                        }
1987                        Arc::new(BooleanArray::new(
1988                            BooleanBuffer::from(booleans),
1989                            nulls.clone(),
1990                        ))
1991                    }
1992                };
1993                Ok(array)
1994            })
1995            .collect::<Result<Vec<_>>>()?;
1996
1997        let child = if components.is_empty() {
1998            Arc::new(StructArray::new_empty_fields(
1999                positions,
2000                Some(NullBuffer::from(present)),
2001            )) as ArrayRef
2002        } else {
2003            Arc::new(
2004                StructArray::try_new(components.clone(), arrays, Some(NullBuffer::from(present)))
2005                    .map_err(|error| err(error.to_string()))?,
2006            ) as ArrayRef
2007        };
2008        // The list itself is valid for every row: absence is an absent item, never an absent
2009        // list, so a reader can tell "this field holds nothing here" from "this row has no
2010        // list at all".
2011        let list = list_array(&lengths, child, item.as_ref().clone(), None)?;
2012        field_arrays.push(Arc::new(list) as ArrayRef);
2013    }
2014    struct_array(field_types.clone(), field_arrays)
2015}
2016
2017/// Encodes buffered rows as one batch with direct N-row Arrow array construction.
2018///
2019/// Each histogram segment carries each *distinct* table row it references exactly once, and its
2020/// local indices are remapped into that compact table, so the payload grows with the rows a segment
2021/// actually names rather than with its positions. A single constituent child array is reused by
2022/// clone (sharing its buffers); multiple constituents are concatenated, which copies.
2023fn encode_rows(schema: &SchemaRef, shape: FrameShape, rows: &[FrameRow]) -> Result<RecordBatch> {
2024    let count = rows.len();
2025    let DataType::Struct(time_fields) = schema.field(2).data_type() else {
2026        return invalid_series("time schema mismatch");
2027    };
2028    let DataType::List(time_item) = time_fields[0].data_type() else {
2029        return invalid_series("time schema mismatch");
2030    };
2031    let DataType::Struct(field_types) = schema.field(3).data_type() else {
2032        return invalid_series("fields schema mismatch");
2033    };
2034    let time = match shape.content {
2035        FrameContent::Raw => {
2036            let mut time_lengths = Vec::with_capacity(count);
2037            let mut time_parts: Vec<ArrayRef> = Vec::with_capacity(count);
2038            for row in rows {
2039                let RowTime::Timestamps(timestamps) = &row.time else {
2040                    return invalid_series("a raw frame row carries grid positions");
2041                };
2042                time_lengths.push(timestamps.len());
2043                time_parts.push(Arc::new(Int64Array::new(timestamps.clone(), None)));
2044            }
2045            let time_child = materialize_parts(&time_parts, || {
2046                Ok(Arc::new(Int64Array::new_null(0)) as ArrayRef)
2047            })?;
2048            let times = list_array(&time_lengths, time_child, time_item.as_ref().clone(), None)?;
2049            struct_array(time_fields.clone(), vec![Arc::new(times)])?
2050        }
2051        FrameContent::Evaluated | FrameContent::AggregateState => {
2052            let DataType::Struct(span_fields) = time_item.data_type() else {
2053                return invalid_series("grid span schema mismatch");
2054            };
2055            let mut span_lengths = Vec::with_capacity(count);
2056            let mut starts = Vec::new();
2057            let mut lengths = Vec::new();
2058            for row in rows {
2059                let RowTime::Spans(spans) = &row.time else {
2060                    return invalid_series("an evaluated frame row carries timestamps");
2061                };
2062                span_lengths.push(spans.len());
2063                for span in spans {
2064                    starts.push(u64::try_from(span.start()).map_err(|_| {
2065                        err("a grid position does not fit the frame's unsigned span")
2066                    })?);
2067                    lengths.push(u64::try_from(span.len()).map_err(|_| {
2068                        err("a grid span length does not fit the frame's unsigned span")
2069                    })?);
2070                }
2071            }
2072            // A batch with no span at all still needs a typed child, so the empty case is spelled
2073            // out instead of being left to whatever `concat` does with nothing.
2074            let span_struct = if starts.is_empty() {
2075                struct_array(
2076                    span_fields.clone(),
2077                    vec![
2078                        Arc::new(UInt64Array::new_null(0)),
2079                        Arc::new(UInt64Array::new_null(0)),
2080                    ],
2081                )?
2082            } else {
2083                struct_array(
2084                    span_fields.clone(),
2085                    vec![
2086                        Arc::new(UInt64Array::from(starts)),
2087                        Arc::new(UInt64Array::from(lengths)),
2088                    ],
2089                )?
2090            };
2091            let spans = list_array(
2092                &span_lengths,
2093                Arc::new(span_struct),
2094                time_item.as_ref().clone(),
2095                None,
2096            )?;
2097            struct_array(time_fields.clone(), vec![Arc::new(spans)])?
2098        }
2099    };
2100
2101    if shape.content == FrameContent::AggregateState {
2102        let fields = encode_state_fields(field_types, rows)?;
2103        return assemble_frame_batch(schema, shape, rows, time, fields);
2104    }
2105    let mut empty_table: Option<ArrayRef> = None;
2106    let mut field_arrays = Vec::with_capacity(field_types.len());
2107    for (index, field) in field_types.iter().enumerate() {
2108        let DataType::Struct(payload) = field.data_type() else {
2109            return invalid_series("payload schema mismatch");
2110        };
2111        let DataType::List(float_item) = payload[0].data_type() else {
2112            return invalid_series("float values schema mismatch");
2113        };
2114        let DataType::Struct(histogram_fields) = payload[1].data_type() else {
2115            return invalid_series("histogram schema mismatch");
2116        };
2117        let DataType::List(index_item) = histogram_fields[0].data_type() else {
2118            return invalid_series("histogram index schema mismatch");
2119        };
2120        let DataType::List(table_item) = histogram_fields[1].data_type() else {
2121            return invalid_series("histogram table schema mismatch");
2122        };
2123        let DataType::Struct(table_fields) = table_item.data_type() else {
2124            return invalid_series("histogram table schema mismatch");
2125        };
2126        let mut float_lengths = Vec::with_capacity(count);
2127        let mut float_parts: Vec<ArrayRef> = Vec::new();
2128        let mut float_valid = Vec::with_capacity(count);
2129        let mut index_lengths = Vec::with_capacity(count);
2130        let mut index_parts: Vec<ArrayRef> = Vec::new();
2131        let mut table_lengths = Vec::with_capacity(count);
2132        let mut table_parts: Vec<ArrayRef> = Vec::new();
2133        let mut histogram_valid = Vec::with_capacity(count);
2134        for row in rows {
2135            let dense = match &row.payload {
2136                RowPayload::Samples(samples) => samples.get(index),
2137                _ => return invalid_series("sample frame row carries state payload"),
2138            }
2139            .ok_or_else(|| err("raw frame row field count mismatch"))?
2140            .dense()
2141            .ok_or_else(|| err("sample segment is not dense"))?;
2142            match dense {
2143                DenseSamplesRef::Float(values) => {
2144                    float_lengths.push(values.len());
2145                    float_parts.push(Arc::new(values.clone()));
2146                    float_valid.push(true);
2147                    index_lengths.push(0);
2148                    table_lengths.push(0);
2149                    histogram_valid.push(false);
2150                }
2151                DenseSamplesRef::Histogram(values) => {
2152                    float_lengths.push(0);
2153                    float_valid.push(false);
2154                    let (table, indices) = compact_histogram(values)?;
2155                    index_lengths.push(indices.len());
2156                    index_parts.push(Arc::new(indices));
2157                    table_lengths.push(table.len());
2158                    table_parts.push(table);
2159                    histogram_valid.push(true);
2160                }
2161                DenseSamplesRef::Mixed(values) => {
2162                    float_lengths.push(values.floats().len());
2163                    float_parts.push(Arc::new(values.floats().clone()));
2164                    float_valid.push(true);
2165                    let (table, indices) = compact_histogram(values.histograms())?;
2166                    index_lengths.push(indices.len());
2167                    index_parts.push(Arc::new(indices));
2168                    table_lengths.push(table.len());
2169                    table_parts.push(table);
2170                    histogram_valid.push(true);
2171                }
2172            }
2173        }
2174        let float_child = materialize_parts(&float_parts, || {
2175            Ok(Arc::new(Float64Array::new_null(0)) as ArrayRef)
2176        })?;
2177        let floats = list_array(
2178            &float_lengths,
2179            float_child,
2180            float_item.as_ref().clone(),
2181            validity(&float_valid),
2182        )?;
2183        let index_child = materialize_parts(&index_parts, || {
2184            Ok(Arc::new(UInt32Array::new_null(0)) as ArrayRef)
2185        })?;
2186        let indices = list_array(
2187            &index_lengths,
2188            index_child,
2189            index_item.as_ref().clone(),
2190            None,
2191        )?;
2192        // A batch without histogram tables shares one empty schema-typed table, built once here
2193        // instead of per float-only row.
2194        let table_child = if table_parts.is_empty() {
2195            match &empty_table {
2196                Some(table) => table.clone(),
2197                None => {
2198                    let table = empty_histogram_table(table_fields)?;
2199                    empty_table = Some(table.clone());
2200                    table
2201                }
2202            }
2203        } else {
2204            materialize_parts(&table_parts, || Err(err("missing histogram table values")))?
2205        };
2206        let tables = list_array(
2207            &table_lengths,
2208            table_child,
2209            table_item.as_ref().clone(),
2210            None,
2211        )?;
2212        let histogram = arrow(StructArray::try_new(
2213            histogram_fields.clone(),
2214            vec![Arc::new(indices), Arc::new(tables)],
2215            validity(&histogram_valid),
2216        ))?;
2217        field_arrays.push(Arc::new(struct_array(
2218            payload.clone(),
2219            vec![Arc::new(floats), Arc::new(histogram)],
2220        )?) as ArrayRef);
2221    }
2222    let fields = struct_array(field_types.clone(), field_arrays)?;
2223    assemble_frame_batch(schema, shape, rows, time, fields)
2224}
2225
2226/// Builds the batch from the parts every content shares: the key, finality, time and field
2227/// columns, plus the labels an explicit frame carries.
2228///
2229/// Keeping the assembly in one place is what makes a state row and an evaluated row leave the
2230/// encoder under the same column order and the same options; only how their field columns were
2231/// built differs, and that is decided before this call.
2232fn assemble_frame_batch(
2233    schema: &SchemaRef,
2234    shape: FrameShape,
2235    rows: &[FrameRow],
2236    time: StructArray,
2237    fields: StructArray,
2238) -> Result<RecordBatch> {
2239    let count = rows.len();
2240    let mut columns: Vec<ArrayRef> = vec![
2241        Arc::new(binary_array(rows, shape)?),
2242        Arc::new(BooleanArray::from(
2243            rows.iter().map(|row| row.is_last).collect::<Vec<_>>(),
2244        )),
2245        Arc::new(time),
2246        Arc::new(fields),
2247    ];
2248    if shape.labels == FrameLabelMode::Explicit {
2249        columns.push(Arc::new(
2250            rows.iter()
2251                .map(|row| row.metric.as_ref().and_then(SeriesLabels::name))
2252                .collect::<StringArray>(),
2253        ));
2254        let DataType::List(label_item) = schema.field(5).data_type() else {
2255            return invalid_series("labels schema mismatch");
2256        };
2257        let DataType::Struct(label_fields) = label_item.data_type() else {
2258            return invalid_series("labels schema mismatch");
2259        };
2260        let mut label_lengths = Vec::with_capacity(count);
2261        let mut tag_names: Vec<&str> = Vec::new();
2262        let mut tag_values: Vec<&str> = Vec::new();
2263        for row in rows {
2264            let metric = row
2265                .metric
2266                .as_ref()
2267                .ok_or_else(|| err("explicit labels missing"))?;
2268            label_lengths.push(metric.tags().len());
2269            for label in metric.tags() {
2270                tag_names.push(label.name.as_ref());
2271                tag_values.push(label.value.as_ref());
2272            }
2273        }
2274        let labels = struct_array(
2275            label_fields.clone(),
2276            vec![
2277                Arc::new(StringArray::from_iter_values(tag_names)),
2278                Arc::new(StringArray::from_iter_values(tag_values)),
2279            ],
2280        )?;
2281        columns.push(Arc::new(list_array(
2282            &label_lengths,
2283            Arc::new(labels),
2284            label_item.as_ref().clone(),
2285            None,
2286        )?));
2287    }
2288
2289    arrow(RecordBatch::try_new_with_options(
2290        schema.clone(),
2291        columns,
2292        &RecordBatchOptions::new().with_row_count(Some(count)),
2293    ))
2294}
2295
2296/// Row-level binary keys.
2297///
2298/// A raw row always carries the key its chunk was read under, so the column is complete and
2299/// non-null for a key frame and for a raw explicit frame alike; only an evaluated row has none, and
2300/// it is a null entry rather than an empty key. A null and `b""` stay distinct, because the second is
2301/// a key a producer could hold and the first is the absence of one.
2302fn binary_array(rows: &[FrameRow], shape: FrameShape) -> Result<BinaryArray> {
2303    let mut offsets = Vec::with_capacity(rows.len() + 1);
2304    let mut total = 0usize;
2305    let mut valid = Vec::with_capacity(rows.len());
2306    offsets.push(0);
2307    for row in rows {
2308        match (&row.key, shape) {
2309            (Some(key), _) => {
2310                total = add_checked(total, key.len())?;
2311                valid.push(true);
2312            }
2313            (None, shape) if shape.content == FrameContent::Raw => {
2314                // `RawSeriesChunk` still carries the key it was read under, and an explicit frame
2315                // only adds the decoded labels beside it. Dropping the key would lose the identity
2316                // a consumer of the raw chunk needs.
2317                return invalid_series("a raw frame row carries no key");
2318            }
2319            (None, _) => valid.push(false),
2320        }
2321        offsets.push(checked_offset(total)?);
2322    }
2323    let mut values = Vec::with_capacity(total);
2324    for row in rows {
2325        if let Some(key) = &row.key {
2326            values.extend_from_slice(key.as_slice());
2327        }
2328    }
2329    let nulls = if valid.iter().all(|valid| *valid) {
2330        None
2331    } else {
2332        validity(&valid)
2333    };
2334    arrow(BinaryArray::try_new(
2335        OffsetBuffer::new(ScalarBuffer::from(offsets)),
2336        Buffer::from_vec(values),
2337        nulls,
2338    ))
2339}
2340
2341/// Per-row charge for key/time/nullable overhead shared by every row.
2342const ROW_CHARGE: usize = 64;
2343/// Per-span charge for the two 64-bit coordinates one grid span carries.
2344const SPAN_CHARGE: usize = 16;
2345/// Per-field charge for the payload struct, nested list and validity overhead.
2346const FIELD_CHARGE: usize = 64;
2347/// Conservative per-table-row charge: the fixed fourteen-column histogram schema has seven
2348/// primitive columns plus seven list columns whose item widths are [`HISTOGRAM_LIST_WIDTHS`].
2349const HISTOGRAM_ROW_CHARGE: usize = 128;
2350/// Fixed per-histogram charge for the seven list columns' offset and validity overhead.
2351const HISTOGRAM_TABLE_CHARGE: usize = 28;
2352/// Item widths of histogram table list columns `7..=13`, in that order.
2353const HISTOGRAM_LIST_WIDTHS: [usize; 7] = [8, 4, 4, 8, 4, 4, 8];
2354
2355fn positions_to_spans(positions: &[usize]) -> Vec<GridSpan> {
2356    let mut spans: Vec<GridSpan> = Vec::new();
2357    for position in positions {
2358        if let Some(last) = spans.last_mut()
2359            && last.start() + last.len() == *position
2360        {
2361            *last = GridSpan::new(last.start(), last.len() + 1);
2362            continue;
2363        }
2364        spans.push(GridSpan::new(*position, 1));
2365    }
2366    spans
2367}
2368
2369fn list_array(
2370    lengths: &[usize],
2371    values: ArrayRef,
2372    item: Field,
2373    nulls: Option<NullBuffer>,
2374) -> Result<ListArray> {
2375    arrow(ListArray::try_new(
2376        Arc::new(item),
2377        offset_buffer(lengths)?,
2378        values,
2379        nulls,
2380    ))
2381}
2382
2383fn offset_buffer(lengths: &[usize]) -> Result<OffsetBuffer<i32>> {
2384    let mut offsets = Vec::with_capacity(lengths.len() + 1);
2385    let mut total = 0usize;
2386    offsets.push(0);
2387    for length in lengths {
2388        total = add_checked(total, *length)?;
2389        offsets.push(checked_offset(total)?);
2390    }
2391    Ok(OffsetBuffer::new(ScalarBuffer::from(offsets)))
2392}
2393
2394/// Materializes one list child: a single constituent is cloned to keep its buffers shared.
2395fn materialize_parts(
2396    parts: &[ArrayRef],
2397    empty: impl FnOnce() -> Result<ArrayRef>,
2398) -> Result<ArrayRef> {
2399    match parts {
2400        [] => empty(),
2401        [only] => Ok(only.clone()),
2402        _ => arrow(concat(
2403            &parts.iter().map(|array| &**array).collect::<Vec<_>>(),
2404        )),
2405    }
2406}
2407
2408fn empty_histogram_table(fields: &Fields) -> Result<ArrayRef> {
2409    let columns = fields
2410        .iter()
2411        .map(|field| arrow::array::new_null_array(field.data_type(), 0))
2412        .collect();
2413    arrow(StructArray::try_new(fields.clone(), columns, None))
2414        .map(|table| Arc::new(table) as ArrayRef)
2415}
2416
2417fn validity(valid: &[bool]) -> Option<NullBuffer> {
2418    if valid.iter().all(|valid| *valid) {
2419        None
2420    } else {
2421        Some(NullBuffer::from(valid.to_vec()))
2422    }
2423}
2424
2425fn bitmap_bytes(len: usize) -> usize {
2426    len.div_ceil(8)
2427}
2428
2429fn add_checked(total: usize, amount: usize) -> Result<usize> {
2430    total
2431        .checked_add(amount)
2432        .ok_or_else(|| err("raw series frame offset overflow"))
2433}
2434
2435fn mul_checked(len: usize, width: usize) -> Result<usize> {
2436    len.checked_mul(width)
2437        .ok_or_else(|| err("raw series frame offset overflow"))
2438}
2439
2440/// One decoded state row retaining Arrow handles for its per-field state columns.
2441///
2442/// The arrays remain columnar so consumers can read typed components in place rather than building
2443/// a nested accumulator tree. Null list items remain field-local absence, not numeric zero.
2444pub struct StateFrameRow {
2445    metric: SeriesLabels,
2446    time: TimeAxis,
2447    is_last: bool,
2448    fields: StructArray,
2449    state: AggregateStateSchema,
2450}
2451
2452/// The Arrow layout the state rows of one publication are encoded against.
2453///
2454/// Building a row needs three things that depend on the state layout and the series it is of rather
2455/// than on the group: the `fields` column's item struct, the components each item carries, and the
2456/// grid the positions are on. Resolving them once makes a group cost its own encoding and nothing
2457/// else, which is what a consumer merging the groups of one publication wants.
2458///
2459/// One constructor builds every row of every group ([`StateRowLayout::row`]), so a producer that
2460/// hands a row over in process and a frame a boundary reads cannot disagree about what a row is.
2461pub struct StateRowLayout {
2462    /// The layout every row is validated against, and the one its fields encode.
2463    state: AggregateStateSchema,
2464    /// How many series fields a row carries.
2465    fields: usize,
2466    /// The grid a row's positions are on.
2467    grid: Arc<EvalGrid>,
2468    /// The `fields` column's item struct, resolved from the frame schema once.
2469    field_types: Fields,
2470}
2471
2472impl StateRowLayout {
2473    /// The layout `schema`'s export declares, as the rows of its groups are built against it.
2474    ///
2475    /// `state` is the layout the export declares: it is checked against itself once here, so a
2476    /// layout no row could encode is refused before any group is built against it.
2477    pub fn try_new(state: &AggregateStateSchema, schema: &SeriesSchema) -> Result<Self> {
2478        let grid = schema
2479            .eval_grid
2480            .clone()
2481            .ok_or_else(|| err("an aggregate state chunk needs an evaluation grid"))?;
2482        let state = AggregateStateSchema::try_new(state.kind, state.components.to_vec())?;
2483        let frame_schema = aggregate_state_frame_schema(&state, schema, FrameLabelMode::Explicit)?;
2484        let DataType::Struct(field_types) = frame_schema.field(3).data_type() else {
2485            return invalid_series("fields schema mismatch");
2486        };
2487        Ok(Self {
2488            state,
2489            fields: schema.fields.len(),
2490            grid,
2491            field_types: field_types.clone(),
2492        })
2493    }
2494
2495    /// One producer group as the state row a consumer merges.
2496    ///
2497    /// The group already is the row: field-major state on sparse absolute positions, the labels it
2498    /// was folded under, and whether it closes its chain. What the group must also be is a row of
2499    /// this layout: its positions on this grid, its field count the series', and every position it
2500    /// carries a contribution from at least one field. Those are checked here rather than where the
2501    /// row is consumed, so a row that exists is a row a merge can read - exactly what the frame
2502    /// decoder checks of a decoded frame row.
2503    pub fn row(&self, series: StateSeries, is_last: bool) -> Result<StateFrameRow> {
2504        if series.states.len() != self.fields
2505            || series
2506                .states
2507                .iter()
2508                .any(|field| field.len() != series.time.len())
2509        {
2510            return invalid_series("aggregate state fields do not match the carried positions");
2511        }
2512        // A position is addressed on the grid this layout declares: a group folded on another grid
2513        // would name positions this node's merge does not have.
2514        if !series
2515            .time
2516            .grid()
2517            .is_some_and(|grid| grid.spec() == self.grid.spec())
2518        {
2519            return invalid_series("aggregate state positions are not on the series grid");
2520        }
2521        let spans = series
2522            .time
2523            .runs()
2524            .map(|run| GridSpan::new(run.position, run.len))
2525            .collect::<Vec<_>>();
2526        let axis = TimeAxis::from_grid_spans(Arc::clone(&self.grid), spans)?;
2527        let row = FrameRow {
2528            key: None,
2529            metric: Some(series.metric.clone()),
2530            is_last,
2531            time: RowTime::Spans(
2532                axis.runs()
2533                    .map(|run| GridSpan::new(run.position, run.len))
2534                    .collect(),
2535            ),
2536            payload: RowPayload::States(series.states),
2537            bytes: 0,
2538        };
2539        let fields = encode_state_fields(&self.field_types, std::slice::from_ref(&row))?;
2540        // The row is checked against the layout it declares, so a consumer that merges it reads the
2541        // components this producer wrote and nothing else - the same check the frame decoder makes.
2542        let validated = StateFieldsBatch::try_from_arrow(fields.clone(), &self.state)?;
2543        if validated.len() != self.fields {
2544            return invalid_series("aggregate state field count mismatch");
2545        }
2546        for field in 0..validated.len() {
2547            let items = validated
2548                .field(field)
2549                .ok_or_else(|| err("null state field list"))?;
2550            if items.len() != axis.len() {
2551                return invalid_series("state list length does not match carried positions");
2552            }
2553        }
2554        // A carried position exists because a field has a contribution there; one no field carries
2555        // is a position the merge would have to invent a state for, so it is refused here.
2556        for position in 0..axis.len() {
2557            let mut present = false;
2558            for field in 0..validated.len() {
2559                present |= validated.is_present(field, position)?;
2560            }
2561            if !present {
2562                return invalid_series("aggregate state names a position with no contribution");
2563            }
2564        }
2565        Ok(StateFrameRow {
2566            metric: series.metric,
2567            time: axis,
2568            is_last,
2569            fields,
2570            state: self.state.clone(),
2571        })
2572    }
2573}
2574
2575impl StateFrameRow {
2576    /// One producer group as the state row a consumer merges.
2577    ///
2578    /// The group already is the row: field-major state on sparse absolute positions, the labels it
2579    /// was folded under, and whether it closes its chain. Building it here is what lets a producer
2580    /// hand the row over in process instead of packing a frame and decoding it back, and it is the
2581    /// same construction the frame encoder uses ([`encode_state_fields`]), so the two readings of
2582    /// one export cannot disagree.
2583    ///
2584    /// `state` is the layout the export declares and `schema` the series it is of: both are checked
2585    /// against the group before anything is built, exactly as the frame decoder checks them against
2586    /// the frame it reads. Building many groups of one export is what [`StateRowLayout`] is for; this
2587    /// is that layout resolved for one row.
2588    pub fn from_state_series(
2589        state: &AggregateStateSchema,
2590        schema: &SeriesSchema,
2591        series: StateSeries,
2592        is_last: bool,
2593    ) -> Result<Self> {
2594        StateRowLayout::try_new(state, schema)?.row(series, is_last)
2595    }
2596
2597    /// Complete group identity for this row.
2598    pub fn metric(&self) -> &SeriesLabels {
2599        &self.metric
2600    }
2601    /// Grid positions carried by this row.
2602    pub fn time(&self) -> &TimeAxis {
2603        &self.time
2604    }
2605    /// Whether this row closes its producer-local chunk chain.
2606    pub fn is_last(&self) -> bool {
2607        self.is_last
2608    }
2609    /// Columnar state arrays validated against the declared aggregate layout.
2610    pub fn fields(&self) -> Result<StateFieldsBatch> {
2611        StateFieldsBatch::try_from_arrow(self.fields.clone(), &self.state)
2612    }
2613}
2614
2615/// Reads one present position's state as the payload family its kind keeps.
2616///
2617/// A histogram payload is checked against the compensation invariant as it is built, so a state
2618/// whose compensation disagrees with its live value cannot be handed to a merge that would index the
2619/// compensation by the value's bucket positions.
2620fn state_payload(
2621    fields: &StateFieldsBatch,
2622    histogram: bool,
2623    field: usize,
2624    position: usize,
2625) -> Result<StatePayload> {
2626    if histogram {
2627        let mut value = HistogramState {
2628            value: Arc::new(state_histogram(
2629                fields,
2630                field,
2631                StateComponent::HistogramValue,
2632                position,
2633            )?),
2634            compensation: Arc::new(state_histogram(
2635                fields,
2636                field,
2637                StateComponent::HistogramCompensation,
2638                position,
2639            )?),
2640            count: 0.0,
2641            incremental_mean: false,
2642            poisoned: false,
2643            incompatible_layout: false,
2644            custom_bounds_reconciled: false,
2645            counter_reset_seen: false,
2646            not_counter_reset_seen: false,
2647        };
2648        for &component in fields.components() {
2649            match component {
2650                StateComponent::HistogramValue | StateComponent::HistogramCompensation => {}
2651                StateComponent::Count => {
2652                    value.count = state_float(fields, field, component, position)?
2653                }
2654                StateComponent::IncrementalMean => {
2655                    value.incremental_mean = state_bool(fields, field, component, position)?
2656                }
2657                StateComponent::Poisoned => {
2658                    value.poisoned = state_bool(fields, field, component, position)?
2659                }
2660                StateComponent::IncompatibleLayout => {
2661                    value.incompatible_layout = state_bool(fields, field, component, position)?
2662                }
2663                StateComponent::CustomBoundsReconciled => {
2664                    value.custom_bounds_reconciled = state_bool(fields, field, component, position)?
2665                }
2666                StateComponent::CounterResetSeen => {
2667                    value.counter_reset_seen = state_bool(fields, field, component, position)?
2668                }
2669                StateComponent::NotCounterResetSeen => {
2670                    value.not_counter_reset_seen = state_bool(fields, field, component, position)?
2671                }
2672                StateComponent::Value | StateComponent::Mean | StateComponent::Compensation => {
2673                    return invalid_series("a histogram state kind carries a numeric component");
2674                }
2675            }
2676        }
2677        value.validate_layout()?;
2678        return Ok(StatePayload::Histogram(Box::new(value)));
2679    }
2680    let mut value = AggregateStateValues::default();
2681    for &component in fields.components() {
2682        match component {
2683            StateComponent::Value => value.value = state_float(fields, field, component, position)?,
2684            StateComponent::Mean => value.mean = state_float(fields, field, component, position)?,
2685            StateComponent::Compensation => {
2686                value.compensation = state_float(fields, field, component, position)?
2687            }
2688            StateComponent::Count => value.count = state_float(fields, field, component, position)?,
2689            StateComponent::IncrementalMean => {
2690                value.incremental_mean = state_bool(fields, field, component, position)?
2691            }
2692            _ => return invalid_series("a numeric state kind carries a histogram component"),
2693        }
2694    }
2695    Ok(StatePayload::Float(value))
2696}
2697
2698fn state_float(
2699    fields: &StateFieldsBatch,
2700    field: usize,
2701    component: StateComponent,
2702    position: usize,
2703) -> Result<f64> {
2704    fields
2705        .field_values(field, component)?
2706        .and_then(|array| (!array.is_null(position)).then(|| array.value(position)))
2707        .ok_or_else(missing_state_component)
2708}
2709
2710fn state_bool(
2711    fields: &StateFieldsBatch,
2712    field: usize,
2713    component: StateComponent,
2714    position: usize,
2715) -> Result<bool> {
2716    fields
2717        .field_bool_values(field, component)?
2718        .and_then(|array| (!array.is_null(position)).then(|| array.value(position)))
2719        .ok_or_else(missing_state_component)
2720}
2721
2722fn state_histogram(
2723    fields: &StateFieldsBatch,
2724    field: usize,
2725    component: StateComponent,
2726    position: usize,
2727) -> Result<HistogramBatch> {
2728    fields
2729        .field_histogram(field, component, position)?
2730        .ok_or_else(missing_state_component)
2731}
2732
2733/// Reuses one prepared frame schema while decoding all batches of a stream.
2734///
2735/// The decoder is built from the schema a consumer expects and then checks every batch against it:
2736/// the reserved declarations are compared as text, the column layout as Arrow fields, and every row
2737/// on its own. A batch that disagrees anywhere is an error rather than a partial decode, because a
2738/// receiver has no way to tell which half of a contradictory frame is the true one.
2739pub struct SeriesFrameDecoder {
2740    schema: SeriesSchema,
2741    shape: FrameShape,
2742    expected: SchemaRef,
2743    aggregate_state: Option<AggregateStateSchema>,
2744}
2745
2746impl SeriesFrameDecoder {
2747    /// Builds the expected frame schema once from the series schema and identity declaration.
2748    pub fn try_new(
2749        schema: &SeriesSchema,
2750        labels: FrameLabelMode,
2751        decode: Option<&LabelDecodeSpec>,
2752    ) -> Result<Self> {
2753        let shape = FrameShape::of(schema, labels);
2754        Ok(Self {
2755            schema: schema.clone(),
2756            shape,
2757            expected: series_frame_schema(schema, labels, decode)?,
2758            aggregate_state: None,
2759        })
2760    }
2761
2762    /// Builds a decoder for the declared aggregate state and its grid-addressed series fields.
2763    pub fn try_new_aggregate_state(
2764        state: &AggregateStateSchema,
2765        schema: &SeriesSchema,
2766        labels: FrameLabelMode,
2767    ) -> Result<Self> {
2768        if schema.eval_grid.is_none() {
2769            return invalid_series("an aggregate state decoder requires an evaluation grid");
2770        }
2771        Ok(Self {
2772            schema: schema.clone(),
2773            shape: FrameShape::aggregate_state(labels),
2774            expected: aggregate_state_frame_schema(state, schema, labels)?,
2775            aggregate_state: Some(state.clone()),
2776        })
2777    }
2778
2779    /// Reads only the explicit labels of each aggregate-state row.
2780    ///
2781    /// This validates the declared frame schema and label columns without inspecting time or state.
2782    pub fn decode_aggregate_state_labels(&self, batch: &RecordBatch) -> Result<Vec<SeriesLabels>> {
2783        if self.shape.labels != FrameLabelMode::Explicit {
2784            return invalid_series("aggregate state routing requires explicit labels");
2785        }
2786        let cols = batch.columns();
2787        let names = down::<StringArray>(&cols[4], "name")?;
2788        let labels = down::<ListArray>(&cols[5], "labels")?;
2789        let mut rows = Vec::with_capacity(batch.num_rows());
2790        for row in 0..batch.num_rows() {
2791            if labels.is_null(row) {
2792                return invalid_series("null required aggregate state label");
2793            }
2794            let values = labels.value(row);
2795            let label_struct = down::<StructArray>(&values, "labels")?;
2796            if label_struct.null_count() != 0 {
2797                return invalid_series("null label struct element");
2798            }
2799            let label_names = down::<StringArray>(label_struct.column(0), "label names")?;
2800            let label_values = down::<StringArray>(label_struct.column(1), "label values")?;
2801            if label_names.null_count() != 0 || label_values.null_count() != 0 {
2802                return invalid_series("null label element");
2803            }
2804            let tags = (0..label_names.len())
2805                .map(|i| Label {
2806                    name: Arc::from(label_names.value(i)),
2807                    value: Arc::from(label_values.value(i)),
2808                })
2809                .collect();
2810            // An aggregation drops the metric name, and the frame says so by leaving it null. That
2811            // is an identity with no name, not a malformed row.
2812            let name = (!names.is_null(row)).then(|| Arc::from(names.value(row)));
2813            rows.push(SeriesLabels::try_new(name, tags)?);
2814        }
2815        Ok(rows)
2816    }
2817
2818    /// Decodes one aggregate-state row without materializing its accumulator values.
2819    pub fn decode_aggregate_state(&self, batch: &RecordBatch) -> Result<Vec<StateFrameRow>> {
2820        let state = self
2821            .aggregate_state
2822            .as_ref()
2823            .ok_or_else(|| err("decoder has no aggregate state declaration"))?;
2824        if batch.schema().as_ref() != self.expected.as_ref() {
2825            return invalid_series("aggregate state frame schema mismatch");
2826        }
2827        validate_ordering(batch.schema().as_ref(), FrameContent::AggregateState)?;
2828        let cols = batch.columns();
2829        let lasts = down::<BooleanArray>(&cols[1], "is_last")?;
2830        let time = down::<StructArray>(&cols[2], "time")?;
2831        let fields = down::<StructArray>(&cols[3], "fields")?;
2832        let names = down::<StringArray>(&cols[4], "name")?;
2833        let labels = down::<ListArray>(&cols[5], "labels")?;
2834        let grid = self
2835            .schema
2836            .eval_grid
2837            .clone()
2838            .ok_or_else(|| err("an aggregate state frame needs an evaluation grid"))?;
2839        let mut rows = Vec::with_capacity(batch.num_rows());
2840        for row in 0..batch.num_rows() {
2841            if lasts.is_null(row) || time.is_null(row) || fields.is_null(row) || labels.is_null(row)
2842            {
2843                return invalid_series("null required aggregate state parent");
2844            }
2845            let spans_array = down::<ListArray>(time.column(0), "spans")?;
2846            if spans_array.is_null(row) {
2847                return invalid_series("null aggregate state spans");
2848            }
2849            let spans_values = spans_array.value(row);
2850            let spans_struct = down::<StructArray>(&spans_values, "spans")?;
2851            if spans_struct.null_count() != 0 {
2852                return invalid_series("null aggregate state span");
2853            }
2854            let starts = down::<UInt64Array>(spans_struct.column(0), "span starts")?;
2855            let lengths = down::<UInt64Array>(spans_struct.column(1), "span lengths")?;
2856            let mut spans = Vec::with_capacity(starts.len());
2857            for index in 0..starts.len() {
2858                let start = usize::try_from(starts.value(index))
2859                    .map_err(|_| err("grid span start exceeds the supported range"))?;
2860                let len = usize::try_from(lengths.value(index))
2861                    .map_err(|_| err("grid span length exceeds the supported range"))?;
2862                if len == 0 {
2863                    return invalid_series("grid spans must not be empty");
2864                }
2865                spans.push(GridSpan::new(start, len));
2866            }
2867            let axis = TimeAxis::from_grid_spans(grid.clone(), spans)?;
2868            let label_values = labels.value(row);
2869            let label_struct = down::<StructArray>(&label_values, "labels")?;
2870            if label_struct.null_count() != 0 {
2871                return invalid_series("null label struct element");
2872            }
2873            let label_names = down::<StringArray>(label_struct.column(0), "label names")?;
2874            let label_values = down::<StringArray>(label_struct.column(1), "label values")?;
2875            if label_names.null_count() != 0 || label_values.null_count() != 0 {
2876                return invalid_series("null label element");
2877            }
2878            let tags = (0..label_names.len())
2879                .map(|i| Label {
2880                    name: Arc::from(label_names.value(i)),
2881                    value: Arc::from(label_values.value(i)),
2882                })
2883                .collect();
2884            let metric = SeriesLabels::try_new(
2885                (!names.is_null(row)).then(|| Arc::from(names.value(row))),
2886                tags,
2887            )?;
2888            let row_fields = fields.slice(row, 1);
2889            let validated = StateFieldsBatch::try_from_arrow(row_fields.clone(), state)?;
2890            if validated.len() != self.schema.fields.len() {
2891                return invalid_series("aggregate state field count mismatch");
2892            }
2893            for field in 0..validated.len() {
2894                let items = validated
2895                    .field(field)
2896                    .ok_or_else(|| err("null state field list"))?;
2897                if items.len() != axis.len() {
2898                    return invalid_series("state list length does not match carried positions");
2899                }
2900                if state.kind != crate::series::aggregate_state::AggregateStateKind::Group {
2901                    for component in 0..state.components.len() {
2902                        let values = items.column(component);
2903                        for position in 0..items.len() {
2904                            if !items.is_null(position) && values.is_null(position) {
2905                                return invalid_series(
2906                                    "present state item has a missing component",
2907                                );
2908                            }
2909                        }
2910                    }
2911                    if state.kind.is_histogram() {
2912                        // A histogram state's compensation must carry its value's bucket layout, or
2913                        // the kernel's compensated add indexes it out of bounds. Deciding that means
2914                        // reading both histograms: two span lists may spell the same buckets
2915                        // differently, so comparing the wire bytes would refuse state that is fine.
2916                        for position in 0..items.len() {
2917                            if !items.is_null(position) {
2918                                state_payload(&validated, true, field, position)?;
2919                            }
2920                        }
2921                    }
2922                }
2923            }
2924            rows.push(StateFrameRow {
2925                metric,
2926                time: axis,
2927                is_last: lasts.value(row),
2928                fields: row_fields,
2929                state: state.clone(),
2930            });
2931        }
2932        Ok(rows)
2933    }
2934
2935    /// Decodes all rows of one batch as raw chunks.
2936    pub fn decode_raw(&self, batch: &RecordBatch) -> Result<Vec<RawSeriesChunk>> {
2937        if self.shape.content != FrameContent::Raw {
2938            return invalid_series("a raw frame decoder cannot read an evaluated frame");
2939        }
2940        self.decode_raw_chunks(batch)
2941    }
2942
2943    /// Builds every raw chunk of one batch straight from its columns.
2944    ///
2945    /// A raw row holds exactly what one [`RawSeriesChunk`] holds, so an intermediate row list would
2946    /// only hold the chunk's parts for a few lines and unpack them again. No payload is copied either
2947    /// way - a `ListArray::value` is a handle over the parent's buffer, not a copy - so what this path
2948    /// avoids is the row list itself and the per-row work that builds it: one `FrameRow` allocation
2949    /// per row and one temporary Arrow handle per row per field, from handles downcast once per batch
2950    /// instead.
2951    ///
2952    /// Every check the row path made still happens here, with the same constraints and the same whole-batch rejection, and the chunks are
2953    /// still built through [`RawTimestamps::try_new`], [`SeriesFields::try_from_vec`], and
2954    /// [`RawSeriesChunk::try_new`]. A batch that fails anywhere fails as a whole: the chunks of the
2955    /// rows before the bad one are dropped with the error rather than returned, because a caller
2956    /// has no way to tell which part of a contradictory batch is the true one.
2957    ///
2958    /// The checks run in the order the row path ran them, over the same two passes: every row is
2959    /// decoded first (its structure, then its labels, then its payloads), and only then are the
2960    /// chunks built in row order. A batch carrying more than one defect therefore reports the same
2961    /// error through either path, which the differential tests hold this one to.
2962    fn decode_raw_chunks(&self, batch: &RecordBatch) -> Result<Vec<RawSeriesChunk>> {
2963        self.validate_batch(batch)?;
2964        let cols = batch.columns();
2965        let keys = down::<BinaryArray>(&cols[0], "read_key")?;
2966        let lasts = down::<BooleanArray>(&cols[1], "is_last")?;
2967        let time_struct = down::<StructArray>(&cols[2], "time")?;
2968        let fs = down::<StructArray>(&cols[3], "fields")?;
2969        let (names, labels) = if self.shape.labels == FrameLabelMode::Explicit {
2970            (
2971                Some(down::<StringArray>(&cols[4], "name")?),
2972                Some(down::<ListArray>(&cols[5], "labels")?),
2973            )
2974        } else {
2975            (None, None)
2976        };
2977        let times = down::<ListArray>(time_struct.column(0), "timestamps")?;
2978        let time_values = down::<Int64Array>(times.values(), "timestamp values")?;
2979        let payloads = raw_field_columns(fs)?;
2980        let mut rows = Vec::with_capacity(batch.num_rows());
2981        for row in 0..batch.num_rows() {
2982            if lasts.is_null(row) || time_struct.is_null(row) || fs.is_null(row) {
2983                return invalid_series("null required frame parent");
2984            }
2985            // A raw row carries its key under either label mode: key mode names the series only by
2986            // it, and explicit mode keeps the chunk's own key beside the decoded labels.
2987            if keys.is_null(row) {
2988                return invalid_series(match self.shape.labels {
2989                    FrameLabelMode::Key => "null required frame parent",
2990                    FrameLabelMode::Explicit => "a raw explicit frame row carries no key",
2991                });
2992            }
2993            if times.is_null(row) {
2994                return invalid_series("null required raw frame parent");
2995            }
2996            let (time_start, positions) = list_range(times.value_offsets(), row)?;
2997            reject_nulls(time_values.nulls(), time_start, positions, "null timestamp")?;
2998            let metric = match (names, labels) {
2999                (None, None) => None,
3000                (Some(ns), Some(ls)) => {
3001                    if ls.is_null(row) {
3002                        return invalid_series("null labels list");
3003                    }
3004                    let label_values = ls.value(row);
3005                    let label_struct = down::<StructArray>(&label_values, "labels")?;
3006                    if label_struct.null_count() != 0 {
3007                        return invalid_series("null label struct element");
3008                    }
3009                    let ln = down::<StringArray>(label_struct.column(0), "label names")?;
3010                    let lv = down::<StringArray>(label_struct.column(1), "label values")?;
3011                    if ln.null_count() != 0 || lv.null_count() != 0 {
3012                        return invalid_series("null label element");
3013                    }
3014                    let tags = (0..ln.len())
3015                        .map(|i| Label {
3016                            name: Arc::from(ln.value(i)),
3017                            value: Arc::from(lv.value(i)),
3018                        })
3019                        .collect();
3020                    Some(SeriesLabels::try_new(
3021                        (!ns.is_null(row)).then(|| Arc::from(ns.value(row))),
3022                        tags,
3023                    )?)
3024                }
3025                _ => return invalid_series("incomplete explicit label columns"),
3026            };
3027            let mut samples = Vec::with_capacity(payloads.len());
3028            for payload in &payloads {
3029                if payload.payload.is_null(row) {
3030                    return invalid_series("null field payload");
3031                }
3032                let has_float = !payload.floats.is_null(row);
3033                let has_hist = !payload.histogram.is_null(row);
3034                if !has_float && !has_hist {
3035                    return invalid_series("field has neither float nor histogram payload");
3036                }
3037                let floats = if has_float {
3038                    let (start, len) = list_range(payload.floats.value_offsets(), row)?;
3039                    payload.float_values.slice(start, len)
3040                } else {
3041                    Float64Array::new_null(0)
3042                };
3043                if has_float && floats.len() != positions {
3044                    return invalid_series("float payload length mismatch");
3045                }
3046                let decoded = if !has_hist {
3047                    Samples::from_float(floats)
3048                } else {
3049                    if payload.indices.is_null(row) || payload.tables.is_null(row) {
3050                        return invalid_series("null histogram indices or table");
3051                    }
3052                    let indices =
3053                        down::<UInt32Array>(&payload.indices.value(row), "histogram indices")?
3054                            .clone();
3055                    if indices.len() != positions {
3056                        return invalid_series("histogram index length mismatch");
3057                    }
3058                    let table =
3059                        down::<StructArray>(&payload.tables.value(row), "histogram table")?.clone();
3060                    let batch = Arc::new(HistogramBatch::try_from_arrow(table)?);
3061                    if has_float {
3062                        Samples::try_from_mixed(floats, HistogramSamples::try_new(indices, batch)?)?
3063                    } else {
3064                        Samples::try_from_histogram(indices, batch)?
3065                    }
3066                };
3067                samples.push(decoded);
3068            }
3069            rows.push(RawRow {
3070                key: binary_slice(keys, row)?,
3071                metric,
3072                samples,
3073                is_last: lasts.value(row),
3074                time_start,
3075                positions,
3076            });
3077        }
3078        // Every row is decoded before any chunk is built, and the chunk-level checks then run in
3079        // row order: a row's timestamps must be strictly increasing, its samples must form fields,
3080        // and the chunk must agree with the frame's schema.
3081        let mut out = Vec::with_capacity(rows.len());
3082        for row in rows {
3083            let time =
3084                RawTimestamps::try_new(time_values.values().slice(row.time_start, row.positions))?;
3085            let fields = SeriesFields::try_from_vec(row.samples)?;
3086            out.push(RawSeriesChunk::try_new(
3087                &self.schema,
3088                row.key,
3089                row.metric,
3090                time,
3091                fields,
3092                row.is_last,
3093            )?);
3094        }
3095        Ok(out)
3096    }
3097
3098    /// Decodes a raw batch through the former intermediate row list.
3099    ///
3100    /// This is the reference the direct path is diffed against in tests only: keeping it reachable
3101    /// there is what makes the two paths comparable row for row, and it is compiled out of every
3102    /// non-test build so it cannot become a second production path.
3103    #[cfg(test)]
3104    fn decode_raw_via_rows(&self, batch: &RecordBatch) -> Result<Vec<RawSeriesChunk>> {
3105        if self.shape.content != FrameContent::Raw {
3106            return invalid_series("a raw frame decoder cannot read an evaluated frame");
3107        }
3108        let rows = self.decode_rows(batch)?;
3109        let mut out = Vec::with_capacity(rows.len());
3110        for row in rows {
3111            let RowTime::Timestamps(timestamps) = row.time else {
3112                return invalid_series("a raw frame row carries grid positions");
3113            };
3114            let key = row
3115                .key
3116                .ok_or_else(|| err("a raw frame row carries no key"))?;
3117            let time = RawTimestamps::try_new(timestamps)?;
3118            let RowPayload::Samples(samples) = row.payload else {
3119                return invalid_series("raw frame row carries state payload");
3120            };
3121            let fields = SeriesFields::try_from_vec(samples)?;
3122            out.push(RawSeriesChunk::try_new(
3123                &self.schema,
3124                key,
3125                row.metric,
3126                time,
3127                fields,
3128                row.is_last,
3129            )?);
3130        }
3131        Ok(out)
3132    }
3133
3134    /// Decodes all rows of one batch as evaluated series and their finality.
3135    ///
3136    /// The pair is what a compute consumer needs and nothing more: the values on their absolute grid
3137    /// positions, and whether this chunk closed the chain. A row that carries no position is kept, so
3138    /// a closing chunk with no value still reaches the consumer that has to see it.
3139    pub fn decode_evaluated(&self, batch: &RecordBatch) -> Result<Vec<(Series, bool)>> {
3140        if self.shape.content != FrameContent::Evaluated {
3141            return invalid_series("an evaluated frame decoder cannot read a raw frame");
3142        }
3143        let grid = self
3144            .schema
3145            .eval_grid
3146            .clone()
3147            .ok_or_else(|| err("an evaluated frame needs an evaluation grid"))?;
3148        let rows = self.decode_rows(batch)?;
3149        let mut out = Vec::with_capacity(rows.len());
3150        for row in rows {
3151            let RowTime::Spans(spans) = row.time else {
3152                return invalid_series("an evaluated frame row carries timestamps");
3153            };
3154            let metric = row
3155                .metric
3156                .ok_or_else(|| err("an evaluated frame row carries no labels"))?;
3157            let time = TimeAxis::from_grid_spans(grid.clone(), spans)?;
3158            // A row that covers no position is the closing chunk's shape and nothing else. The
3159            // streaming validator refuses one that closes nothing, but this decoder is public and a
3160            // caller driving it directly must not be handed a chunk it could never have produced
3161            // either: an empty chunk that opens a chain carries no value and no finality, so no
3162            // consumer could act on it.
3163            if time.is_empty() && !row.is_last {
3164                return invalid_series(
3165                    "an evaluated chunk without positions must close its series",
3166                );
3167            }
3168            let RowPayload::Samples(samples) = row.payload else {
3169                return invalid_series("evaluated frame row carries state payload");
3170            };
3171            let fields = SeriesFields::try_from_vec(samples)?;
3172            out.push((
3173                Series::try_new(&self.schema, metric, time, fields)?,
3174                row.is_last,
3175            ));
3176        }
3177        Ok(out)
3178    }
3179
3180    /// Checks the reserved metadata, declaration text, and field layout of one frame batch.
3181    ///
3182    /// Every entry point of this codec goes through it, so a batch is refused for the same reasons
3183    /// whichever way it is decoded.
3184    fn validate_batch(&self, batch: &RecordBatch) -> Result<()> {
3185        let actual = batch.schema();
3186        validate_ordering(actual.as_ref(), self.shape.content)?;
3187        for key in [LAYOUT, CONTENT, LABELS, TIME, GRID, LABEL_DECODE] {
3188            if actual.metadata().get(key) != self.expected.metadata().get(key) {
3189                return invalid_series("frame metadata mismatch");
3190            }
3191        }
3192        // The same reservation rule the declaration parser applies, because a frame's protocol
3193        // legality must not depend on which entry point reads it: a reserved key nobody checks would
3194        // travel as dead metadata here while being refused a layer up.
3195        for key in actual.metadata().keys() {
3196            if key.starts_with("greptime.series.") && !RESERVED_KEYS.contains(&key.as_str()) {
3197                return invalid_series("frame declares unknown reserved metadata");
3198            }
3199        }
3200        if actual.fields() != self.expected.fields() {
3201            return invalid_series("frame schema mismatch");
3202        }
3203        Ok(())
3204    }
3205
3206    /// Decodes all rows of one batch, checking its reserved metadata, declared fields, and rows.
3207    fn decode_rows(&self, batch: &RecordBatch) -> Result<Vec<FrameRow>> {
3208        self.validate_batch(batch)?;
3209        let cols = batch.columns();
3210        let keys = down::<BinaryArray>(&cols[0], "read_key")?;
3211        let lasts = down::<BooleanArray>(&cols[1], "is_last")?;
3212        let time_struct = down::<StructArray>(&cols[2], "time")?;
3213        let fs = down::<StructArray>(&cols[3], "fields")?;
3214        let (names, labels) = if self.shape.labels == FrameLabelMode::Explicit {
3215            (
3216                Some(down::<StringArray>(&cols[4], "name")?),
3217                Some(down::<ListArray>(&cols[5], "labels")?),
3218            )
3219        } else {
3220            (None, None)
3221        };
3222        let mut out = Vec::with_capacity(batch.num_rows());
3223        for row in 0..batch.num_rows() {
3224            if lasts.is_null(row) || time_struct.is_null(row) || fs.is_null(row) {
3225                return invalid_series("null required frame parent");
3226            }
3227            match self.shape.labels {
3228                FrameLabelMode::Key => {
3229                    if keys.is_null(row) {
3230                        return invalid_series("null required frame parent");
3231                    }
3232                }
3233                // An explicit row names its series by label; the key column is the raw chunk's own
3234                // contract, and an evaluated row has none at all.
3235                FrameLabelMode::Explicit => {
3236                    if self.shape.content == FrameContent::Raw && keys.is_null(row) {
3237                        return invalid_series("a raw explicit frame row carries no key");
3238                    }
3239                    if self.shape.content == FrameContent::Evaluated && !keys.is_null(row) {
3240                        return invalid_series("an evaluated frame row carries a storage key");
3241                    }
3242                }
3243            }
3244            let time = match self.shape.content {
3245                FrameContent::Raw => {
3246                    let times = down::<ListArray>(time_struct.column(0), "timestamps")?;
3247                    if times.is_null(row) {
3248                        return invalid_series("null required raw frame parent");
3249                    }
3250                    let values = times.value(row);
3251                    let tv = down::<Int64Array>(&values, "timestamp values")?;
3252                    if tv.null_count() != 0 {
3253                        return invalid_series("null timestamp");
3254                    }
3255                    RowTime::Timestamps(tv.values().clone())
3256                }
3257                FrameContent::Evaluated | FrameContent::AggregateState => {
3258                    let typed = down::<ListArray>(time_struct.column(0), "spans")?;
3259                    if typed.is_null(row) {
3260                        return invalid_series("null required evaluated frame parent");
3261                    }
3262                    let values = typed.value(row);
3263                    let span_struct = down::<StructArray>(&values, "spans")?;
3264                    if span_struct.null_count() != 0 {
3265                        return invalid_series("null grid span");
3266                    }
3267                    let starts = down::<UInt64Array>(span_struct.column(0), "span starts")?;
3268                    let lengths = down::<UInt64Array>(span_struct.column(1), "span lengths")?;
3269                    if starts.null_count() != 0 || lengths.null_count() != 0 {
3270                        return invalid_series("null grid span bound");
3271                    }
3272                    let mut spans = Vec::with_capacity(starts.len());
3273                    for index in 0..starts.len() {
3274                        let start = usize::try_from(starts.value(index))
3275                            .map_err(|_| err("grid span start exceeds the supported range"))?;
3276                        let len = usize::try_from(lengths.value(index))
3277                            .map_err(|_| err("grid span length exceeds the supported range"))?;
3278                        if len == 0 {
3279                            return invalid_series("grid spans must not be empty");
3280                        }
3281                        spans.push(GridSpan::new(start, len));
3282                    }
3283                    RowTime::Spans(spans)
3284                }
3285            };
3286            let positions = time.len()?;
3287            let metric = match (names, labels) {
3288                (None, None) => None,
3289                (Some(ns), Some(ls)) => {
3290                    if ls.is_null(row) {
3291                        return invalid_series("null labels list");
3292                    }
3293                    let label_values = ls.value(row);
3294                    let label_struct = down::<StructArray>(&label_values, "labels")?;
3295                    if label_struct.null_count() != 0 {
3296                        return invalid_series("null label struct element");
3297                    }
3298                    let ln = down::<StringArray>(label_struct.column(0), "label names")?;
3299                    let lv = down::<StringArray>(label_struct.column(1), "label values")?;
3300                    if ln.null_count() != 0 || lv.null_count() != 0 {
3301                        return invalid_series("null label element");
3302                    }
3303                    let tags = (0..ln.len())
3304                        .map(|i| Label {
3305                            name: Arc::from(ln.value(i)),
3306                            value: Arc::from(lv.value(i)),
3307                        })
3308                        .collect();
3309                    Some(SeriesLabels::try_new(
3310                        (!ns.is_null(row)).then(|| Arc::from(ns.value(row))),
3311                        tags,
3312                    )?)
3313                }
3314                _ => return invalid_series("incomplete explicit label columns"),
3315            };
3316            let mut decoded = Vec::with_capacity(fs.num_columns());
3317            for col in fs.columns() {
3318                let payload = down::<StructArray>(col, "field payload")?;
3319                if payload.is_null(row) {
3320                    return invalid_series("null field payload");
3321                }
3322                let floats_list = down::<ListArray>(payload.column(0), "float values")?;
3323                let hist = down::<StructArray>(payload.column(1), "histogram payload")?;
3324                let has_float = !floats_list.is_null(row);
3325                let has_hist = !hist.is_null(row);
3326                if !has_float && !has_hist {
3327                    return invalid_series("field has neither float nor histogram payload");
3328                }
3329                let floats = if has_float {
3330                    down::<Float64Array>(&floats_list.value(row), "float values")?.clone()
3331                } else {
3332                    Float64Array::new_null(0)
3333                };
3334                if has_float && floats.len() != positions {
3335                    return invalid_series("float payload length mismatch");
3336                }
3337                let samples = if !has_hist {
3338                    Samples::from_float(floats)
3339                } else {
3340                    let inds = down::<ListArray>(hist.column(0), "histogram indices")?;
3341                    let tables = down::<ListArray>(hist.column(1), "histogram table")?;
3342                    if inds.is_null(row) || tables.is_null(row) {
3343                        return invalid_series("null histogram indices or table");
3344                    }
3345                    let indices =
3346                        down::<UInt32Array>(&inds.value(row), "histogram indices")?.clone();
3347                    if indices.len() != positions {
3348                        return invalid_series("histogram index length mismatch");
3349                    }
3350                    let table = down::<StructArray>(&tables.value(row), "histogram table")?.clone();
3351                    let batch = Arc::new(HistogramBatch::try_from_arrow(table)?);
3352                    if has_float {
3353                        Samples::try_from_mixed(floats, HistogramSamples::try_new(indices, batch)?)?
3354                    } else {
3355                        Samples::try_from_histogram(indices, batch)?
3356                    }
3357                };
3358                decoded.push(samples);
3359            }
3360            let key = if keys.is_null(row) {
3361                None
3362            } else {
3363                Some(binary_slice(keys, row)?)
3364            };
3365            out.push(FrameRow {
3366                key,
3367                metric,
3368                is_last: lasts.value(row),
3369                time,
3370                payload: RowPayload::Samples(decoded),
3371                bytes: 0,
3372            });
3373        }
3374        Ok(out)
3375    }
3376}
3377
3378/// Decodes all rows of one raw frame; any malformed row makes the entire call fail.
3379pub fn unpack_raw_series_frame(
3380    schema: &SeriesSchema,
3381    mode: FrameLabelMode,
3382    decode: Option<&LabelDecodeSpec>,
3383    batch: &RecordBatch,
3384) -> Result<Vec<RawSeriesChunk>> {
3385    SeriesFrameDecoder::try_new(schema, mode, decode)?.decode_raw(batch)
3386}
3387
3388fn binary_slice(array: &BinaryArray, row: usize) -> Result<Buffer> {
3389    let (start, len) = list_range(array.value_offsets(), row)?;
3390    Ok(array.values().slice_with_length(start, len))
3391}
3392
3393/// The `(start, len)` window of one list slot in its child array.
3394///
3395/// Read straight from the parent's offsets, which is what [`ListArray::value`] does internally: a
3396/// caller that only needs the window in order to slice the child itself avoids the temporary
3397/// `ArrayRef` a per-row `value(row)` would allocate.
3398fn list_range(offsets: &[i32], row: usize) -> Result<(usize, usize)> {
3399    let start = usize::try_from(offsets[row]).map_err(|_| err("negative list offset"))?;
3400    let end = usize::try_from(offsets[row + 1]).map_err(|_| err("negative list offset"))?;
3401    let len = end
3402        .checked_sub(start)
3403        .ok_or_else(|| err("invalid list offsets"))?;
3404    Ok((start, len))
3405}
3406
3407/// Rejects nulls in the `[start, start + len)` window of one child column.
3408///
3409/// A parent column that carries no null at all costs one branch, which is the common case; a column
3410/// that does is checked per row exactly where the row's own slice is checked.
3411fn reject_nulls(nulls: Option<&NullBuffer>, start: usize, len: usize, reason: &str) -> Result<()> {
3412    if let Some(nulls) = nulls
3413        && nulls.slice(start, len).null_count() != 0
3414    {
3415        return invalid_series(reason);
3416    }
3417    Ok(())
3418}
3419
3420/// One decoded raw row, before its chunk is built.
3421///
3422/// A row keeps its timestamps as the window they occupy in the time column, so the chunk is built
3423/// from the same values instead of another handle over them: the row-list path held a
3424/// [`RawTimestamps`] buffer per row (`RowTime::Timestamps`), and the chunk consumed it. Everything
3425/// else here is a slice or a move: the key is a slice of the key column, and a field's samples are
3426/// slices of their own columns.
3427struct RawRow {
3428    /// The row's exact key.
3429    key: Buffer,
3430    /// The row's labels, in explicit label mode.
3431    metric: Option<SeriesLabels>,
3432    /// The row's samples, one entry per field.
3433    samples: Vec<Samples>,
3434    /// Whether the row closes its series.
3435    is_last: bool,
3436    /// Start of the row's timestamps in the time column's values.
3437    time_start: usize,
3438    /// Positions the row carries, i.e. the length of its timestamp window.
3439    positions: usize,
3440}
3441
3442/// One raw field's payload columns, borrowed and downcast once per batch.
3443///
3444/// The raw decode reads one row of every field per row of the batch, so a downcast per row would
3445/// repeat the same work for every row. These are the five columns a row of one field needs, and
3446/// nothing here decides anything: the shape checks stay in the decode loop itself.
3447struct RawFieldColumns<'a> {
3448    /// The per-row payload struct, whose validity says a field has a payload at all.
3449    payload: &'a StructArray,
3450    /// Every row's `float_values` list.
3451    floats: &'a ListArray,
3452    /// The `float_values` child array those lists index into.
3453    float_values: &'a Float64Array,
3454    /// Every row's `histogram` struct.
3455    histogram: &'a StructArray,
3456    /// Every row's histogram `indices` list.
3457    indices: &'a ListArray,
3458    /// Every row's histogram `table` list.
3459    tables: &'a ListArray,
3460}
3461
3462impl<'a> RawFieldColumns<'a> {
3463    /// Downcasts one field column of the frame's `fields` struct.
3464    fn of(column: &'a ArrayRef) -> Result<Self> {
3465        let payload = down::<StructArray>(column, "field payload")?;
3466        let floats = down::<ListArray>(payload.column(0), "float values")?;
3467        let histogram = down::<StructArray>(payload.column(1), "histogram payload")?;
3468        Ok(Self {
3469            payload,
3470            float_values: down::<Float64Array>(floats.values(), "float values")?,
3471            floats,
3472            histogram,
3473            indices: down::<ListArray>(histogram.column(0), "histogram indices")?,
3474            tables: down::<ListArray>(histogram.column(1), "histogram table")?,
3475        })
3476    }
3477}
3478
3479/// Downcasts every field column of a raw frame's `fields` struct once.
3480fn raw_field_columns(fs: &StructArray) -> Result<Vec<RawFieldColumns<'_>>> {
3481    fs.columns().iter().map(RawFieldColumns::of).collect()
3482}
3483
3484fn checked_offset(len: usize) -> Result<i32> {
3485    i32::try_from(len).map_err(|_| err("Arrow offset limit exceeded"))
3486}
3487
3488fn struct_array(fields: Fields, arrays: Vec<ArrayRef>) -> Result<StructArray> {
3489    arrow(StructArray::try_new(fields, arrays, None))
3490}
3491
3492fn down<'a, T: Array + 'static>(array: &'a ArrayRef, label: &str) -> Result<&'a T> {
3493    array
3494        .as_any()
3495        .downcast_ref()
3496        .ok_or_else(|| err(format!("{label} type mismatch")))
3497}
3498
3499fn err(reason: impl Into<String>) -> crate::error::Error {
3500    InvalidSeriesSnafu {
3501        reason: reason.into(),
3502    }
3503    .build()
3504}
3505
3506fn arrow<T>(result: std::result::Result<T, arrow::error::ArrowError>) -> Result<T> {
3507    result.map_err(|e| err(e.to_string()))
3508}
3509
3510#[cfg(test)]
3511mod aggregate_state_contribution_tests {
3512    use std::sync::Arc;
3513
3514    use super::*;
3515    use crate::series::aggregate_state::{
3516        AggregateStateKind as Kind, AggregateStateValues as Values, StateComponent as Component,
3517    };
3518    use crate::series::samples::FieldSpec;
3519
3520    /// The numeric components of a state vector: what a walk hands on unchanged.
3521    fn numeric(states: &[Option<StatePayload>]) -> Vec<Option<Values>> {
3522        states
3523            .iter()
3524            .map(|state| state.as_ref().and_then(StatePayload::float).copied())
3525            .collect()
3526    }
3527
3528    fn schema(len: usize) -> SeriesSchema {
3529        SeriesSchema {
3530            fields: ["a", "b"]
3531                .into_iter()
3532                .map(|name| FieldSpec {
3533                    name: Arc::from(name),
3534                })
3535                .collect::<Vec<_>>()
3536                .into(),
3537            eval_grid: Some(Arc::new(
3538                EvalGrid::try_new(GridSpec::try_new(0, 1, len as u64).unwrap()).unwrap(),
3539            )),
3540        }
3541    }
3542
3543    fn cursor(
3544        kind: Kind,
3545        schema: &SeriesSchema,
3546        spans: Vec<GridSpan>,
3547        states: Vec<Vec<Option<StatePayload>>>,
3548    ) -> SeriesFrameCursor {
3549        let components = match kind {
3550            Kind::Group => vec![],
3551            _ => vec![Component::Value, Component::Compensation],
3552        };
3553        let state = AggregateStateSchema::try_new(kind, components).unwrap();
3554        SeriesFrameCursor::try_new_aggregate_state(
3555            &state,
3556            schema,
3557            StateSeries {
3558                metric: SeriesLabels::try_new(None, vec![]).unwrap(),
3559                time: TimeAxis::from_grid_spans(schema.eval_grid.clone().unwrap(), spans).unwrap(),
3560                states,
3561            },
3562            true,
3563        )
3564        .unwrap()
3565    }
3566
3567    #[test]
3568    fn sparse_rows_are_filtered_and_group_keeps_all_rows() {
3569        let schema = schema(12);
3570        let sparse = cursor(
3571            Kind::Sum,
3572            &schema,
3573            vec![GridSpan::new(0, 5), GridSpan::new(7, 4)],
3574            vec![
3575                vec![
3576                    None,
3577                    Some(StatePayload::Float(Values::default())),
3578                    None,
3579                    None,
3580                    Some(StatePayload::Float(Values::default())),
3581                    None,
3582                    None,
3583                    None,
3584                    None,
3585                ],
3586                vec![
3587                    None,
3588                    None,
3589                    None,
3590                    Some(StatePayload::Float(Values::default())),
3591                    None,
3592                    None,
3593                    Some(StatePayload::Float(Values::default())),
3594                    None,
3595                    None,
3596                ],
3597            ],
3598        );
3599        let ChunkWalk::State(walk) = sparse.walk else {
3600            panic!("expected state walk")
3601        };
3602        assert_eq!(
3603            walk.series.time.positions().collect::<Vec<_>>(),
3604            vec![(1, 0), (3, 1), (4, 2), (8, 3)]
3605        );
3606        assert_eq!(
3607            walk.series
3608                .time
3609                .runs()
3610                .map(|run| (run.position, run.len))
3611                .collect::<Vec<_>>(),
3612            vec![(1, 1), (3, 2), (8, 1)]
3613        );
3614        assert_eq!(
3615            numeric(&walk.series.states[0]),
3616            vec![Some(Values::default()), None, Some(Values::default()), None]
3617        );
3618        assert_eq!(
3619            numeric(&walk.series.states[1]),
3620            vec![None, Some(Values::default()), None, Some(Values::default())]
3621        );
3622
3623        let group = cursor(
3624            Kind::Group,
3625            &schema,
3626            vec![GridSpan::new(2, 3), GridSpan::new(8, 2)],
3627            vec![vec![None; 5], vec![None; 5]],
3628        );
3629        let ChunkWalk::State(walk) = group.walk else {
3630            panic!("expected state walk")
3631        };
3632        assert_eq!(
3633            walk.series.time.positions().collect::<Vec<_>>(),
3634            vec![(2, 0), (3, 1), (4, 2), (8, 3), (9, 4)]
3635        );
3636        assert_eq!(
3637            walk.series
3638                .states
3639                .iter()
3640                .map(|field| numeric(field))
3641                .collect::<Vec<_>>(),
3642            vec![vec![None; 5], vec![None; 5]]
3643        );
3644    }
3645}