Skip to main content

promql/native/
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
15//! The aggregate-state chunk a native `Partial`/`Final` aggregate passes between executions.
16//!
17//! A state chunk is not a query value. It names the group a partition folded and the grid
18//! positions that group has contributions at, and it carries the accumulator components its
19//! aggregate declared -- nothing else. The conversions here are the only place kernel state
20//! ([`PartialAggregate`]) and frame state ([`StateSeries`]) meet, so a hole in one is a hole in the
21//! other: a field with no contribution at a carried position stays absent through both directions
22//! rather than being filled in with a zero that a later merge would count.
23
24use std::mem::{size_of, size_of_val};
25use std::sync::Arc;
26
27use datafusion::arrow::array::Array;
28use datafusion::error::{DataFusionError, Result};
29use datafusion::execution::memory_pool::MemoryReservation;
30use datatypes::series::aggregate_state::{
31    AggregateStateKind, StateComponent, StatePayload, StateSeries,
32};
33use datatypes::series::frame::StateFrameRow;
34use datatypes::series::time::{GridSpan, TimeAxis};
35
36use crate::aggregate::{AggregateOp, PartialAggregate};
37use crate::native::plan::{AggregateStateSchema, BoundAggregate, aggregate_state_binding};
38
39/// One partition's aggregate state, either in producer series form or as a decoded consumer row.
40#[derive(Debug)]
41pub enum StateChunk {
42    Series {
43        series: Vec<StateSeries>,
44        state_schema: Arc<AggregateStateSchema>,
45        /// The producer charge this chunk carries once it has left its node's queue.
46        ///
47        /// A state chunk is charged to the node that folded it until the chunk is handed over. The
48        /// consumer keeps the batch across polls while it packs rows from it, so the charge travels
49        /// with those series rather than being returned the moment the producer lets go.
50        reservation: Option<MemoryReservation>,
51    },
52    Row(crate::aggregate::state::StateRow),
53}
54
55/// Rejects a bound state whose kind or component layout is not what this node binds.
56///
57/// Both halves matter. A frame carries its kind so a `sum` state is never merged as an `avg` one, and
58/// it carries the component list so a merge reads exactly the columns the producer wrote. The
59/// expected pair comes from the same binding the node was built from, so a histogram aggregate
60/// exports and accepts histogram state and a numeric one numeric state, with no second table to
61/// drift from the first.
62fn ensure_bound_state(op: &BoundAggregate, state_schema: &AggregateStateSchema) -> Result<()> {
63    let Some((expected_kind, expected_components)) =
64        aggregate_state_binding(op.kind, op.field_kind)
65    else {
66        return Err(DataFusionError::NotImplemented(format!(
67            "aggregate state is not defined for {:?}",
68            op.kind
69        )));
70    };
71    if state_schema.kind != expected_kind {
72        return Err(DataFusionError::Execution(format!(
73            "aggregate state of kind {:?} is not {expected_kind:?} state",
74            state_schema.kind
75        )));
76    }
77    if state_schema.components.as_ref() != expected_components.as_slice() {
78        return Err(DataFusionError::Execution(format!(
79            "aggregate state components {:?} are not what {:?} produces: {:?}",
80            state_schema.components, op.kind, expected_components
81        )));
82    }
83    Ok(())
84}
85
86/// Hands one partition's kernel state over as the frame state a consumer reads.
87///
88/// The fold already builds the frame's own representation - field-major states on sparse absolute
89/// grid positions - so this moves the groups. It copies nothing: the charge the fold reported for
90/// those groups is the charge the chunk keeps.
91pub(crate) fn state_chunk_from_partial(
92    partial: PartialAggregate,
93    state_schema: Arc<AggregateStateSchema>,
94    op: &BoundAggregate,
95) -> Result<StateChunk> {
96    ensure_bound_state(op, state_schema.as_ref())?;
97    Ok(StateChunk::Series {
98        series: partial.groups,
99        state_schema,
100        reservation: None,
101    })
102}
103
104/// Builds the executor's state row for one exported row, as its producer declared it.
105///
106/// A producer hands a row over without knowing which binding will fold it: the kind and the columns
107/// it was written with travel in the row, and the consumer checks them against its own binding. So
108/// this converts the row's columns and keeps the layout they were validated against.
109pub(crate) fn state_row_of(row: StateFrameRow) -> Result<crate::aggregate::state::StateRow> {
110    let fields = row
111        .fields()
112        .map_err(|error| DataFusionError::Execution(error.to_string()))?;
113    let kind = fields.kind();
114    Ok(crate::aggregate::state::StateRow {
115        metric: row.metric().clone(),
116        time: row.time().clone(),
117        fields,
118        kind,
119    })
120}
121
122/// Builds the executor's Arrow-backed state row from one decoded frame row.
123pub(crate) fn state_row_from_frame_row(
124    row: StateFrameRow,
125    binding: &AggregateStateSchema,
126) -> Result<crate::aggregate::state::StateRow> {
127    let fields = row
128        .fields()
129        .map_err(|error| DataFusionError::Execution(error.to_string()))?;
130    if fields.kind() != binding.kind {
131        return Err(DataFusionError::Execution(format!(
132            "aggregate state row kind {:?} does not match Final binding {:?}",
133            fields.kind(),
134            binding.kind
135        )));
136    }
137    if fields.components() != binding.components.as_ref() {
138        return Err(DataFusionError::Execution(format!(
139            "aggregate state row components {:?} do not match Final binding {:?}",
140            fields.components(),
141            binding.components
142        )));
143    }
144    Ok(crate::aggregate::state::StateRow {
145        metric: row.metric().clone(),
146        time: row.time().clone(),
147        fields,
148        kind: binding.kind,
149    })
150}
151
152/// The aggregate a state kind is the state of.
153///
154/// A histogram kind is the state of the same aggregate over a histogram input, so it merges with the
155/// same rules; what differs is the payload, which the merge reads from the kind itself.
156pub(crate) fn op_of_state(kind: AggregateStateKind) -> AggregateOp {
157    match kind {
158        AggregateStateKind::Sum | AggregateStateKind::HistogramSum => AggregateOp::Sum,
159        AggregateStateKind::Count => AggregateOp::Count,
160        AggregateStateKind::Avg | AggregateStateKind::HistogramAvg => AggregateOp::Avg,
161        AggregateStateKind::Min => AggregateOp::Min,
162        AggregateStateKind::Max => AggregateOp::Max,
163        AggregateStateKind::Group => AggregateOp::Group,
164        AggregateStateKind::Stddev => AggregateOp::Stddev,
165        AggregateStateKind::Stdvar => AggregateOp::Stdvar,
166    }
167}
168
169/// Transient bytes for the selected state array consumed by a decoded row.
170///
171/// This estimates the selected extent, not a reservation for the batch's shared parent buffers;
172/// a router retains and charges those buffers separately while handing the batch downstream.
173pub(crate) fn slice_bytes(array: &dyn Array) -> usize {
174    array
175        .to_data()
176        .get_slice_memory_size()
177        .unwrap_or_else(|_| array.get_array_memory_size())
178}
179
180/// Bytes held by one decoded state row's owned wrappers and retained payloads.
181pub(crate) fn state_row_bytes(row: &crate::aggregate::state::StateRow) -> usize {
182    let fields = row.fields.len();
183    size_of::<StateChunk>()
184        .saturating_add(size_of::<crate::aggregate::state::StateRow>())
185        .saturating_add(fields.saturating_mul(size_of::<datafusion::arrow::array::StructArray>()))
186        .saturating_add(
187            (0..fields)
188                .filter_map(|index| row.fields.field(index))
189                .map(|field| slice_bytes(field))
190                .fold(0usize, usize::saturating_add),
191        )
192        .saturating_add(
193            row.metric
194                .name()
195                .map_or(0, str::len)
196                .saturating_add(size_of_val(row.metric.tags()))
197                .saturating_add(
198                    row.metric
199                        .tags()
200                        .iter()
201                        .map(|tag| tag.name.len().saturating_add(tag.value.len()))
202                        .sum::<usize>(),
203                ),
204        )
205        .saturating_add(
206            row.time
207                .runs()
208                .count()
209                .saturating_mul(size_of::<GridSpan>().saturating_add(size_of::<usize>()))
210                .saturating_add(if row.time.is_empty() {
211                    0
212                } else {
213                    size_of::<TimeAxis>()
214                }),
215        )
216}
217
218/// Bytes a state chunk holds: labels, axis runs, and one sparse state vector per field.
219///
220/// Like [`crate::grid_series::series_bytes`] this is a work estimate rather than a heap
221/// measurement -- it counts vector capacities, not allocator overhead -- which is what the
222/// reservation it feeds needs: a figure that never under-counts what the executor holds.
223pub(crate) fn state_bytes(chunk: &StateChunk) -> usize {
224    let StateChunk::Series {
225        series,
226        state_schema,
227        ..
228    } = chunk
229    else {
230        let StateChunk::Row(row) = chunk else {
231            unreachable!("a state chunk is either producer series or a decoded row")
232        };
233        return state_row_bytes(row);
234    };
235    let series_bytes = series.iter().fold(0usize, |total, series| {
236        let runs = series.time.runs().count();
237        let labels = series
238            .metric
239            .name()
240            .map_or(0, str::len)
241            .saturating_add(size_of_val(series.metric.tags()))
242            .saturating_add(
243                series
244                    .metric
245                    .tags()
246                    .iter()
247                    .map(|tag| tag.name.len().saturating_add(tag.value.len()))
248                    .sum::<usize>(),
249            );
250        let fields = series
251            .states
252            .capacity()
253            .saturating_mul(size_of::<Vec<Option<StatePayload>>>());
254        let states = series.states.iter().fold(fields, |bytes, field| {
255            // The slot is sized for the payload family it holds; a histogram payload also owns its
256            // boxed state and both histograms' Arrow buffers, so its buckets are charged by width
257            // rather than estimated at a fixed size.
258            bytes
259                .saturating_add(
260                    field
261                        .capacity()
262                        .saturating_mul(size_of::<Option<StatePayload>>()),
263                )
264                .saturating_add(field.iter().flatten().fold(0usize, |heap, state| {
265                    heap.saturating_add(state.heap_bytes())
266                }))
267        });
268        total
269            .saturating_add(size_of::<StateSeries>())
270            .saturating_add(runs.saturating_mul(size_of::<(usize, usize)>()))
271            .saturating_add(labels)
272            .saturating_add(states)
273    });
274    size_of::<StateChunk>()
275        .saturating_add(series.capacity().saturating_mul(size_of::<StateSeries>()))
276        .saturating_add(series_bytes)
277        .saturating_add(
278            state_schema
279                .components
280                .len()
281                .saturating_mul(size_of::<StateComponent>()),
282        )
283}