Skip to main content

datatypes/series/
aggregate_state.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
15use std::mem::size_of;
16use std::sync::Arc;
17
18use arrow::array::{Array, BooleanArray, Float64Array, ListArray, StructArray};
19use arrow::datatypes::DataType;
20
21use crate::error::{InvalidSeriesSnafu, Result};
22use crate::series::SeriesLabels;
23use crate::series::histogram::{
24    BucketSideView, HistogramBatch, HistogramView, fields as histogram_fields,
25};
26use crate::series::time::TimeAxis;
27
28/// Aggregate whose accumulator is represented by a state frame.
29///
30/// Two families share one state vector: the numeric kinds below, whose components are scalar, and
31/// the two histogram kinds, whose payload is a native histogram ([`HistogramState`]). A kind's
32/// components are fixed by [`AggregateStateKind::components`], so a histogram kind can never declare
33/// a numeric component and a sum state can never claim mean mode.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
35pub enum AggregateStateKind {
36    Sum,
37    Count,
38    Avg,
39    Min,
40    Max,
41    Group,
42    Stddev,
43    Stdvar,
44    /// `sum` over native histograms.
45    HistogramSum,
46    /// `avg` over native histograms.
47    HistogramAvg,
48}
49
50impl AggregateStateKind {
51    /// Canonical metadata spelling.
52    pub const fn as_str(self) -> &'static str {
53        match self {
54            Self::Sum => "sum",
55            Self::Count => "count",
56            Self::Avg => "avg",
57            Self::Min => "min",
58            Self::Max => "max",
59            Self::Group => "group",
60            Self::Stddev => "stddev",
61            Self::Stdvar => "stdvar",
62            Self::HistogramSum => "histogram_sum",
63            Self::HistogramAvg => "histogram_avg",
64        }
65    }
66    /// Parses a canonical aggregate name without treating unknown kinds as another state.
67    pub fn parse(text: &str) -> Result<Self> {
68        match text {
69            "sum" => Ok(Self::Sum),
70            "count" => Ok(Self::Count),
71            "avg" => Ok(Self::Avg),
72            "min" => Ok(Self::Min),
73            "max" => Ok(Self::Max),
74            "group" => Ok(Self::Group),
75            "stddev" => Ok(Self::Stddev),
76            "stdvar" => Ok(Self::Stdvar),
77            "histogram_sum" => Ok(Self::HistogramSum),
78            "histogram_avg" => Ok(Self::HistogramAvg),
79            _ => invalid("unknown aggregate state kind"),
80        }
81    }
82    /// Whether this kind's positions carry a native-histogram payload rather than numeric ones.
83    pub const fn is_histogram(self) -> bool {
84        matches!(self, Self::HistogramSum | Self::HistogramAvg)
85    }
86    /// The components this kind's state carries, in canonical order.
87    ///
88    /// [`AggregateStateSchema::try_new`] accepts exactly this list for this kind, so a producer that
89    /// binds a state from this table cannot declare a layout the frame would refuse.
90    pub fn components(self) -> &'static [StateComponent] {
91        use StateComponent as C;
92        match self {
93            Self::Sum => &[C::Value, C::Compensation],
94            Self::Count => &[C::Count],
95            Self::Avg => &[
96                C::Value,
97                C::Mean,
98                C::Compensation,
99                C::Count,
100                C::IncrementalMean,
101            ],
102            Self::Min | Self::Max => &[C::Value],
103            Self::Group => &[],
104            Self::Stddev | Self::Stdvar => &[C::Value, C::Mean, C::Count],
105            // The live histogram, its layout-carrying compensation, then the evidence a merge
106            // records. A sum has no observation count and no mean mode.
107            Self::HistogramSum => &[
108                C::HistogramValue,
109                C::HistogramCompensation,
110                C::Poisoned,
111                C::IncompatibleLayout,
112                C::CustomBoundsReconciled,
113                C::CounterResetSeen,
114                C::NotCounterResetSeen,
115            ],
116            // An average has no separate mean column: `incremental_mean` says whether the live
117            // histogram is a cumulative sum or a running mean.
118            Self::HistogramAvg => &[
119                C::HistogramValue,
120                C::HistogramCompensation,
121                C::Count,
122                C::IncrementalMean,
123                C::Poisoned,
124                C::IncompatibleLayout,
125                C::CustomBoundsReconciled,
126                C::CounterResetSeen,
127                C::NotCounterResetSeen,
128            ],
129        }
130    }
131}
132
133/// One named accumulator column.
134#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
135pub enum StateComponent {
136    Value,
137    Mean,
138    Compensation,
139    Count,
140    IncrementalMean,
141    /// The live native histogram of a histogram accumulator.
142    HistogramValue,
143    /// The compensation that carries [`StateComponent::HistogramValue`]'s bucket layout.
144    HistogramCompensation,
145    /// The point cannot be answered because its inputs disagreed on their bucket layout.
146    Poisoned,
147    /// Two inputs carried an exponential layout and a custom-buckets layout at once.
148    IncompatibleLayout,
149    /// A merge reconciled the custom bucket bounds of two inputs.
150    CustomBoundsReconciled,
151    /// Some input reported a counter reset.
152    CounterResetSeen,
153    /// Some input reported that no counter reset happened.
154    NotCounterResetSeen,
155}
156
157impl StateComponent {
158    /// Canonical metadata spelling.
159    pub const fn as_str(self) -> &'static str {
160        match self {
161            Self::Value => "value",
162            Self::Mean => "mean",
163            Self::Compensation => "compensation",
164            Self::Count => "count",
165            Self::IncrementalMean => "incremental_mean",
166            Self::HistogramValue => "histogram_value",
167            Self::HistogramCompensation => "histogram_compensation",
168            Self::Poisoned => "poisoned",
169            Self::IncompatibleLayout => "incompatible_layout",
170            Self::CustomBoundsReconciled => "custom_bounds_reconciled",
171            Self::CounterResetSeen => "counter_reset_seen",
172            Self::NotCounterResetSeen => "not_counter_reset_seen",
173        }
174    }
175    /// Parses a canonical component name, refusing unknown wire values.
176    pub fn parse(text: &str) -> Result<Self> {
177        match text {
178            "value" => Ok(Self::Value),
179            "mean" => Ok(Self::Mean),
180            "compensation" => Ok(Self::Compensation),
181            "count" => Ok(Self::Count),
182            "incremental_mean" => Ok(Self::IncrementalMean),
183            "histogram_value" => Ok(Self::HistogramValue),
184            "histogram_compensation" => Ok(Self::HistogramCompensation),
185            "poisoned" => Ok(Self::Poisoned),
186            "incompatible_layout" => Ok(Self::IncompatibleLayout),
187            "custom_bounds_reconciled" => Ok(Self::CustomBoundsReconciled),
188            "counter_reset_seen" => Ok(Self::CounterResetSeen),
189            "not_counter_reset_seen" => Ok(Self::NotCounterResetSeen),
190            _ => invalid("unknown aggregate state component"),
191        }
192    }
193    /// The Arrow item type of this component.
194    ///
195    /// A histogram component is one native histogram per position, in the representation
196    /// [`crate::series::histogram`] already defines for sample frames; the two histogram components
197    /// of a state therefore nest the same struct a histogram sample does.
198    pub(crate) fn element_type(self) -> DataType {
199        match self {
200            Self::HistogramValue | Self::HistogramCompensation => {
201                DataType::Struct(histogram_fields())
202            }
203            Self::IncrementalMean
204            | Self::Poisoned
205            | Self::IncompatibleLayout
206            | Self::CustomBoundsReconciled
207            | Self::CounterResetSeen
208            | Self::NotCounterResetSeen => DataType::Boolean,
209            Self::Value | Self::Mean | Self::Compensation | Self::Count => DataType::Float64,
210        }
211    }
212}
213
214/// Values for all accumulator components at one field and grid position.
215#[derive(Clone, Copy, Debug, Default, PartialEq)]
216pub struct AggregateStateValues {
217    /// Accumulator value.
218    pub value: f64,
219    /// Running mean.
220    pub mean: f64,
221    /// Compensation retained for stable summation.
222    pub compensation: f64,
223    /// Observation count represented as a floating-point accumulator.
224    pub count: f64,
225    /// Whether the mean is incremental.
226    pub incremental_mean: bool,
227}
228
229/// One position's native-histogram accumulator: its live histogram, the compensation that carries
230/// the same bucket layout, and the evidence bits a merge records.
231///
232/// The fields mirror [`AggregateStateValues`]: every component a histogram kind can declare has a
233/// slot, and the ones the kind does not declare stay at their default. `HistogramSum` declares no
234/// `count` and no `incremental_mean`, which is what makes a sum state unable to claim mean mode.
235#[derive(Clone, Debug)]
236pub struct HistogramState {
237    /// The live histogram, held as one row of the frame's own histogram representation.
238    pub value: Arc<HistogramBatch>,
239    /// Compensation retained for a stable sum of the value's buckets.
240    ///
241    /// It always carries the live value's bucket layout and is never an `empty_like` placeholder: the
242    /// kernel's compensated add indexes this histogram by the value's bucket positions.
243    pub compensation: Arc<HistogramBatch>,
244    /// Number of observations folded in. A `HistogramSum` state leaves it at zero.
245    pub count: f64,
246    /// Whether an average switched from a running sum to a running mean.
247    pub incremental_mean: bool,
248    /// Whether the point cannot be answered because its inputs disagreed on their bucket layout.
249    pub poisoned: bool,
250    /// Whether two inputs carried an exponential layout and a custom-buckets layout at once.
251    pub incompatible_layout: bool,
252    /// Whether a merge reconciled the custom bucket bounds of two inputs.
253    pub custom_bounds_reconciled: bool,
254    /// Whether some input reported a counter reset.
255    pub counter_reset_seen: bool,
256    /// Whether some input reported that no counter reset happened.
257    pub not_counter_reset_seen: bool,
258}
259
260impl HistogramState {
261    /// Checks the compensation invariant: a live value's compensation carries its bucket layout.
262    ///
263    /// A poisoned position holds an empty placeholder on both sides -- it has no bucket indices to
264    /// align and is removed rather than merged -- so it only has to be one histogram per component.
265    pub fn validate_layout(&self) -> Result<()> {
266        let value = single_histogram(&self.value)?;
267        let compensation = single_histogram(&self.compensation)?;
268        if self.poisoned {
269            return Ok(());
270        }
271        check_layout(value, compensation)
272    }
273
274    /// Reads the evidence bit a Boolean component declares, if this payload records it.
275    pub fn bool_component(&self, component: StateComponent) -> Option<bool> {
276        match component {
277            StateComponent::IncrementalMean => Some(self.incremental_mean),
278            StateComponent::Poisoned => Some(self.poisoned),
279            StateComponent::IncompatibleLayout => Some(self.incompatible_layout),
280            StateComponent::CustomBoundsReconciled => Some(self.custom_bounds_reconciled),
281            StateComponent::CounterResetSeen => Some(self.counter_reset_seen),
282            StateComponent::NotCounterResetSeen => Some(self.not_counter_reset_seen),
283            _ => None,
284        }
285    }
286
287    /// Heap bytes both histograms retain, counted from the Arrow arrays themselves so a wide bucket
288    /// layout is paid for and a narrow one is not.
289    pub fn heap_bytes(&self) -> usize {
290        self.value
291            .as_arrow()
292            .get_array_memory_size()
293            .saturating_add(self.compensation.as_arrow().get_array_memory_size())
294    }
295}
296
297/// One grid position's aggregate state: numeric components, or a native-histogram payload.
298///
299/// A field holds either family at a position, never both, and a kind's component list says which one
300/// its positions carry. Keeping both in one vector is what leaves absence a single `None` rather
301/// than a second representation of it.
302#[derive(Clone, Debug)]
303pub enum StatePayload {
304    /// Numeric accumulator components, byte-identical to what a float state always carried.
305    Float(AggregateStateValues),
306    /// A native-histogram accumulator.
307    Histogram(Box<HistogramState>),
308}
309
310impl StatePayload {
311    /// The numeric components, when this position holds numeric state.
312    pub fn float(&self) -> Option<&AggregateStateValues> {
313        match self {
314            Self::Float(values) => Some(values),
315            Self::Histogram(_) => None,
316        }
317    }
318    /// The histogram payload, when this position holds histogram state.
319    pub fn histogram(&self) -> Option<&HistogramState> {
320        match self {
321            Self::Float(_) => None,
322            Self::Histogram(state) => Some(state),
323        }
324    }
325    /// Reads the numeric component a state item declares. A component this payload's family does not
326    /// keep as a scalar is `None`, which is how a writer refuses a payload its kind cannot describe.
327    pub fn float_component(&self, component: StateComponent) -> Option<f64> {
328        match self {
329            Self::Float(values) => match component {
330                StateComponent::Value => Some(values.value),
331                StateComponent::Mean => Some(values.mean),
332                StateComponent::Compensation => Some(values.compensation),
333                StateComponent::Count => Some(values.count),
334                _ => None,
335            },
336            Self::Histogram(state) => match component {
337                StateComponent::Count => Some(state.count),
338                _ => None,
339            },
340        }
341    }
342    /// Reads the Boolean component a state item declares, or `None` if this payload does not keep it.
343    pub fn bool_component(&self, component: StateComponent) -> Option<bool> {
344        match self {
345            Self::Float(values) => match component {
346                StateComponent::IncrementalMean => Some(values.incremental_mean),
347                _ => None,
348            },
349            Self::Histogram(state) => state.bool_component(component),
350        }
351    }
352    /// Reads the histogram component a state item declares, or `None` if this payload keeps none.
353    pub fn histogram_component(&self, component: StateComponent) -> Option<&Arc<HistogramBatch>> {
354        let Self::Histogram(state) = self else {
355            return None;
356        };
357        match component {
358            StateComponent::HistogramValue => Some(&state.value),
359            StateComponent::HistogramCompensation => Some(&state.compensation),
360            _ => None,
361        }
362    }
363    /// Heap bytes this payload holds beyond the slot that stores it.
364    ///
365    /// Numeric components are inline and are paid for by the slot; a histogram payload boxes its
366    /// state and both batches own Arrow buffers whose width follows the bucket layout.
367    pub fn heap_bytes(&self) -> usize {
368        match self {
369            Self::Float(_) => 0,
370            Self::Histogram(state) => {
371                size_of::<HistogramState>().saturating_add(state.heap_bytes())
372            }
373        }
374    }
375}
376
377/// The single histogram a state component carries, or an error naming the violation.
378fn single_histogram(batch: &HistogramBatch) -> Result<HistogramView<'_>> {
379    if batch.len() != 1 {
380        return invalid("a histogram state component carries exactly one histogram");
381    }
382    batch
383        .view(0)
384        .ok_or_else(|| invalid_series("empty histogram state component"))
385}
386
387/// Compares the layout a merge reads, not the wire encoding: span lists that spell the same buckets
388/// differently agree, because what the kernel indexes is the expanded bucket index.
389fn check_layout(value: HistogramView<'_>, compensation: HistogramView<'_>) -> Result<()> {
390    if value.schema != compensation.schema {
391        return invalid("histogram compensation schema does not match its value");
392    }
393    if value.zero_threshold.to_bits() != compensation.zero_threshold.to_bits() {
394        return invalid("histogram compensation zero threshold does not match its value");
395    }
396    if !same_bounds(value.custom_values, compensation.custom_values) {
397        return invalid("histogram compensation custom bounds do not match its value");
398    }
399    if bucket_indices(value.positive) != bucket_indices(compensation.positive)
400        || bucket_indices(value.negative) != bucket_indices(compensation.negative)
401    {
402        return invalid("histogram compensation bucket indices do not match its value");
403    }
404    Ok(())
405}
406
407fn same_bounds(lhs: &[f64], rhs: &[f64]) -> bool {
408    lhs.len() == rhs.len()
409        && lhs
410            .iter()
411            .zip(rhs)
412            .all(|(lhs, rhs)| lhs.to_bits() == rhs.to_bits())
413}
414
415/// The logical bucket indices one side's spans expand to, in ascending order.
416fn bucket_indices(side: BucketSideView<'_>) -> Vec<i32> {
417    let mut indices = Vec::with_capacity(side.buckets.len());
418    let mut cursor = 0i32;
419    for (span, (&offset, &length)) in side.span_offsets.iter().zip(side.span_lengths).enumerate() {
420        cursor = if span == 0 {
421            offset
422        } else {
423            cursor.saturating_add(offset)
424        };
425        for index in cursor..cursor.saturating_add(length) {
426            indices.push(index);
427        }
428        cursor = cursor.saturating_add(length);
429    }
430    indices
431}
432
433/// Validated aggregate kind and ordered component layout.
434#[derive(Clone, Debug, PartialEq, Eq)]
435pub struct AggregateStateSchema {
436    pub kind: AggregateStateKind,
437    pub components: Arc<[StateComponent]>,
438}
439
440impl AggregateStateSchema {
441    /// Creates a schema only when its ordered components exactly describe its kind.
442    ///
443    /// The comparison is over the whole list, which is what forbids mixing the two payload families
444    /// (a histogram kind declaring a numeric component, or the other way round) and what keeps
445    /// `HistogramSum` from declaring `incremental_mean`.
446    pub fn try_new(kind: AggregateStateKind, components: Vec<StateComponent>) -> Result<Self> {
447        if kind != AggregateStateKind::Group && components.is_empty() {
448            return invalid("aggregate state components must not be empty");
449        }
450        if components.as_slice() != kind.components() {
451            return invalid("aggregate state components do not match kind");
452        }
453        Ok(Self {
454            kind,
455            components: components.into(),
456        })
457    }
458    /// Parses the aggregate kind and ordered comma-separated component metadata.
459    pub fn from_text(kind: &str, components: &str) -> Result<Self> {
460        let kind = AggregateStateKind::parse(kind)?;
461        let parsed = if components.is_empty() {
462            Vec::new()
463        } else {
464            components
465                .split(',')
466                .map(StateComponent::parse)
467                .collect::<Result<Vec<_>>>()?
468        };
469        Self::try_new(kind, parsed)
470    }
471    /// Returns the canonical ordered component metadata text.
472    pub fn components_text(&self) -> String {
473        self.components
474            .iter()
475            .map(|component| component.as_str())
476            .collect::<Vec<_>>()
477            .join(",")
478    }
479}
480
481/// A group-labelled sparse aggregate-state chunk on a shared time axis.
482#[derive(Clone, Debug)]
483pub struct StateSeries {
484    /// Complete group identity.
485    pub metric: SeriesLabels,
486    /// Grid positions carried by this chunk.
487    pub time: TimeAxis,
488    /// Field-major states; `None` denotes a field position without a contribution.
489    pub states: Vec<Vec<Option<StatePayload>>>,
490}
491
492fn invalid<T>(reason: &str) -> Result<T> {
493    InvalidSeriesSnafu {
494        reason: reason.to_string(),
495    }
496    .fail()
497}
498
499/// Columnar state fields retained in Arrow form so consumers can read component values in place.
500/// Null items are field-local holes, not zero-valued states.
501#[derive(Clone, Debug)]
502pub struct StateFieldsBatch {
503    kind: AggregateStateKind,
504    components: Arc<[StateComponent]>,
505    fields: Vec<StructArray>,
506}
507
508impl StateFieldsBatch {
509    /// Validates the ordered component layout once and keeps the row's typed Arrow arrays.
510    pub fn try_from_arrow(fields: StructArray, schema: &AggregateStateSchema) -> Result<Self> {
511        if fields.num_columns() == 0 {
512            return invalid("state fields array has no fields");
513        }
514        let mut items = Vec::with_capacity(fields.num_columns());
515        for (column, field) in fields.columns().iter().zip(fields.fields()) {
516            let DataType::List(item) = field.data_type() else {
517                return invalid("state field is not a list");
518            };
519            let DataType::Struct(members) = item.data_type() else {
520                return invalid("state list item is not a struct");
521            };
522            if members.len() != schema.components.len() {
523                return invalid("state component count mismatch");
524            }
525            for (member, expected) in members.iter().zip(schema.components.iter()) {
526                if member.name() != expected.as_str() {
527                    return invalid("state component order mismatch");
528                }
529                if member.data_type() != &expected.element_type() {
530                    return invalid("state component type mismatch");
531                }
532            }
533            let list = column
534                .as_any()
535                .downcast_ref::<ListArray>()
536                .ok_or_else(|| invalid_series("state field list type mismatch"))?;
537            if list.is_null(0) {
538                return invalid("null state field list");
539            }
540            let item_array = list.value(0);
541            let item_struct = item_array
542                .as_any()
543                .downcast_ref::<StructArray>()
544                .ok_or_else(|| invalid_series("state item struct type mismatch"))?;
545            items.push(item_struct.clone());
546        }
547        Ok(Self {
548            kind: schema.kind,
549            components: schema.components.clone(),
550            fields: items,
551        })
552    }
553    /// Number of logical series fields in this row.
554    pub fn len(&self) -> usize {
555        self.fields.len()
556    }
557    /// Whether this wrapper contains no series fields.
558    pub fn is_empty(&self) -> bool {
559        self.fields.is_empty()
560    }
561    /// The item struct for one field's list, sliced to the decoded row.
562    pub fn field(&self, index: usize) -> Option<&StructArray> {
563        self.fields.get(index)
564    }
565    /// Aggregate kind represented by these columns.
566    pub fn kind(&self) -> AggregateStateKind {
567        self.kind
568    }
569    /// Declared accumulator components in wire order.
570    pub fn components(&self) -> &[StateComponent] {
571        &self.components
572    }
573    /// Returns a numeric component array, or `None` if the component is not declared.
574    pub fn field_values(
575        &self,
576        field: usize,
577        component: StateComponent,
578    ) -> Result<Option<&Float64Array>> {
579        let Some(index) = self.components.iter().position(|value| *value == component) else {
580            return Ok(None);
581        };
582        self.fields
583            .get(field)
584            .ok_or_else(|| invalid_series("state field index out of range"))?
585            .column(index)
586            .as_any()
587            .downcast_ref::<Float64Array>()
588            .map(Some)
589            .ok_or_else(|| invalid_series("state float component type mismatch"))
590    }
591    /// Returns a Boolean component array, or `None` if the component is not declared.
592    pub fn field_bool_values(
593        &self,
594        field: usize,
595        component: StateComponent,
596    ) -> Result<Option<&BooleanArray>> {
597        let Some(index) = self.components.iter().position(|value| *value == component) else {
598            return Ok(None);
599        };
600        self.fields
601            .get(field)
602            .ok_or_else(|| invalid_series("state field index out of range"))?
603            .column(index)
604            .as_any()
605            .downcast_ref::<BooleanArray>()
606            .map(Some)
607            .ok_or_else(|| invalid_series("state boolean component type mismatch"))
608    }
609    /// Returns the histogram component's per-position column, or `None` if it is not declared.
610    ///
611    /// One row of this column is one histogram, so a state position's payload is that row as its own
612    /// one-row batch.
613    pub fn field_histograms(
614        &self,
615        field: usize,
616        component: StateComponent,
617    ) -> Result<Option<&StructArray>> {
618        let Some(index) = self.components.iter().position(|value| *value == component) else {
619            return Ok(None);
620        };
621        self.fields
622            .get(field)
623            .ok_or_else(|| invalid_series("state field index out of range"))?
624            .column(index)
625            .as_any()
626            .downcast_ref::<StructArray>()
627            .map(Some)
628            .ok_or_else(|| invalid_series("state histogram component type mismatch"))
629    }
630    /// Reads one position's histogram component, or `None` when that position is absent.
631    pub fn field_histogram(
632        &self,
633        field: usize,
634        component: StateComponent,
635        position: usize,
636    ) -> Result<Option<HistogramBatch>> {
637        let Some(column) = self.field_histograms(field, component)? else {
638            return Ok(None);
639        };
640        if position >= column.len() {
641            return invalid("state position out of range");
642        }
643        if column.is_null(position) {
644            return Ok(None);
645        }
646        HistogramBatch::try_from_arrow(column.slice(position, 1)).map(Some)
647    }
648    /// Reads this field's item validity at one carried position; sibling fields never fill holes.
649    pub fn is_present(&self, field: usize, position: usize) -> Result<bool> {
650        let items = self
651            .fields
652            .get(field)
653            .ok_or_else(|| invalid_series("state field index out of range"))?;
654        if position >= items.len() {
655            return invalid("state position out of range");
656        }
657        Ok(!items.is_null(position))
658    }
659}
660
661fn invalid_series(reason: &str) -> crate::error::Error {
662    InvalidSeriesSnafu {
663        reason: reason.to_string(),
664    }
665    .build()
666}