Skip to main content

operator/req_convert/insert/row_to_batch/
memory.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::collections::{HashMap, HashSet};
16
17use api::v1::value::ValueData;
18use api::v1::{JsonValue, Rows, json_value};
19use arrow::datatypes::DataType;
20use arrow_schema::extension::ExtensionType;
21use common_query::prelude::{greptime_exemplar_labels, greptime_value};
22use datatypes::extension::json::Json2ExtensionType;
23use datatypes::json::value::JsonVariant;
24use datatypes::json::{JSON2_DEFAULT_MAX_AUTO_EXPANDED_PATHS, JsonSettings};
25use datatypes::schema::ColumnDefaultConstraint;
26use datatypes::value::Value;
27use datatypes::vectors::json;
28use store_api::metric_engine_consts::{
29    DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME,
30};
31use store_api::storage::ColumnId;
32use store_api::storage::consts::ReservedColumnId;
33use table::metadata::TableInfo;
34
35use crate::insert::ExemplarBatch;
36
37const ARRAY_OVERHEAD: usize = 512;
38const VIEW_BLOCK_BYTES: usize = 8192;
39const VALUE_SCRATCH_BYTES: usize = 256;
40pub(super) const SPARSE_PK_MIN_ROW_BYTES: usize = 64;
41const SPARSE_PK_PREFIX_BYTES: usize = 22;
42const SPARSE_PK_TAG_OVERHEAD_BYTES: usize = 16;
43
44/// Estimates additional memory for conversion, including destination columns absent
45/// from the request. Overflow fails closed. Source rows remain separately reserved.
46///
47/// This budgets buffers, capacity growth and JSON2 conversion scratch, not allocator
48/// RSS. shortcut: account for flush concatenation, partitioning and IPC separately
49/// when extending admission to the entire flush pipeline.
50pub(crate) fn estimated_record_batch_bytes(rows: &Rows, table: &TableInfo) -> Option<usize> {
51    estimate_rows_record_batch_bytes(rows, table, false)
52}
53
54/// Estimates Arrow conversion bytes for an ordinary sparse table written as `__primary_key`
55/// and non-tag columns.
56pub(crate) fn estimated_sparse_record_batch_bytes(rows: &Rows, table: &TableInfo) -> Option<usize> {
57    estimate_rows_record_batch_bytes(rows, table, true)
58}
59
60fn estimate_sparse_pk_array_bytes(
61    row_count: usize,
62    pk_encoded_bytes: usize,
63    pk_scratch: usize,
64    pk_meta_scratch: usize,
65) -> Option<usize> {
66    let min_builder_data = row_count.checked_mul(SPARSE_PK_MIN_ROW_BYTES)?;
67    let pk_data_bytes = pk_encoded_bytes.max(min_builder_data).checked_mul(2)?;
68    array_bytes(&DataType::Binary, row_count)?
69        .checked_mul(2)?
70        .checked_add(pk_data_bytes)?
71        .checked_add(pk_scratch)?
72        .checked_add(pk_meta_scratch)
73}
74
75fn is_reserved_sparse_column(
76    column: &datatypes::schema::ColumnSchema,
77    column_id: Option<ColumnId>,
78) -> bool {
79    column.name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME
80        || column.name == DATA_SCHEMA_TSID_COLUMN_NAME
81        || column_id == Some(ReservedColumnId::table_id())
82        || column_id == Some(ReservedColumnId::tsid())
83}
84
85fn estimate_rows_record_batch_bytes(rows: &Rows, table: &TableInfo, sparse: bool) -> Option<usize> {
86    let source = rows
87        .schema
88        .iter()
89        .enumerate()
90        .map(|(i, column)| (column.column_name.as_str(), i))
91        .collect::<HashMap<_, _>>();
92    let row_count = rows.rows.len();
93    let pk_set: HashSet<usize> = if sparse {
94        table.meta.primary_key_indices.iter().copied().collect()
95    } else {
96        HashSet::new()
97    };
98
99    let mut total = 0usize;
100    let mut pk_encoded_bytes = if sparse {
101        row_count.checked_mul(SPARSE_PK_PREFIX_BYTES)?
102    } else {
103        0
104    };
105    let mut pk_scratch = 0usize;
106    let pk_meta_scratch = if sparse {
107        pk_set.len().checked_mul(128)?.checked_add(256)?
108    } else {
109        0
110    };
111
112    for (index, (column, field)) in table
113        .meta
114        .schema
115        .column_schemas()
116        .iter()
117        .zip(table.meta.schema.arrow_schema().fields())
118        .enumerate()
119    {
120        let mut values = ValueSize::default();
121        let mut non_null_rows = 0usize;
122        let source_index = source.get(column.name.as_str()).copied();
123        if let Some(src_idx) = source_index {
124            for row in &rows.rows {
125                if let Some(vd) = row.values.get(src_idx)?.value_data.as_ref() {
126                    non_null_rows += 1;
127                    values.proto(Some(vd))?;
128                }
129            }
130        } else if let Some(default) = column.default_constraint() {
131            match default {
132                ColumnDefaultConstraint::Value(value) => {
133                    if !value.is_null() {
134                        non_null_rows = row_count;
135                    }
136                    values.default_value(value)?;
137                    values.payload = values.payload.checked_mul(row_count)?;
138                    values.items = values.items.checked_mul(row_count)?;
139                    values.scratch = values.scratch.checked_mul(row_count)?;
140                }
141                ColumnDefaultConstraint::Function(_) => {
142                    non_null_rows = row_count;
143                }
144            }
145        }
146
147        if sparse && pk_set.contains(&index) {
148            let reserved_col_id = table.meta.column_ids.get(index).copied();
149            if !is_reserved_sparse_column(column, reserved_col_id) {
150                pk_encoded_bytes = pk_encoded_bytes
151                    .checked_add(non_null_rows.checked_mul(SPARSE_PK_TAG_OVERHEAD_BYTES)?)?
152                    .checked_add(values.payload.checked_mul(2)?)?;
153                pk_scratch = pk_scratch.checked_add(values.scratch)?;
154            }
155            continue;
156        }
157
158        let extension = column.extension_type::<Json2ExtensionType>().ok()?;
159        // Only supplied v2 JSON2 values use the settings-aware builder; defaults use the datatype.
160        let settings = extension
161            .as_ref()
162            .filter(|extension| {
163                source_index.is_some()
164                    && column.data_type.is_json2()
165                    && extension.metadata().is_version_2()
166            })
167            .map(|extension| extension.metadata().json_settings());
168        total = total.checked_add(estimate_column_arrow_bytes(
169            field.data_type(),
170            row_count,
171            field.size(),
172            settings,
173            &values,
174        )?)?;
175    }
176
177    if sparse {
178        total = total.checked_add(estimate_sparse_pk_array_bytes(
179            row_count,
180            pk_encoded_bytes,
181            pk_scratch,
182            pk_meta_scratch,
183        )?)?;
184    }
185    Some(total)
186}
187
188/// Estimates Arrow conversion bytes for an exemplar batch against the resolved destination schema.
189///
190/// Accounts for destination-dependent JSON2 `type_hints` and `expanded_paths` while keeping
191/// absent inherited catalog tags compact inside `__primary_key`.
192pub(crate) fn estimated_exemplar_record_batch_bytes(
193    exemplars: &ExemplarBatch,
194    table: &TableInfo,
195) -> Option<usize> {
196    let row_count = exemplars.len();
197    let meta = &table.meta;
198    let schema = &meta.schema;
199    let arrow_schema = schema.arrow_schema();
200
201    let ts_idx = schema.timestamp_index();
202    let val_idx = schema.column_index_by_name(greptime_value());
203    let labels_idx = schema.column_index_by_name(greptime_exemplar_labels());
204
205    let mut pk_encoded_bytes = 0usize;
206    let mut label_values = ValueSize::default();
207    for exemplar in exemplars.exemplars() {
208        // 22B for (__table_id, __tsid) + encoded metric name + present inherited tags.
209        pk_encoded_bytes = pk_encoded_bytes
210            .checked_add(SPARSE_PK_PREFIX_BYTES)?
211            .checked_add(SPARSE_PK_TAG_OVERHEAD_BYTES)?
212            .checked_add(exemplar.metric.len().checked_mul(2)?)?;
213        for value in exemplar.series_labels.values() {
214            pk_encoded_bytes = pk_encoded_bytes
215                .checked_add(SPARSE_PK_TAG_OVERHEAD_BYTES)?
216                .checked_add(value.len().checked_mul(2)?)?;
217        }
218        label_values.scratch = label_values.scratch.checked_add(VALUE_SCRATCH_BYTES)?;
219        for (k, v) in &exemplar.labels {
220            label_values.payload(k.len().checked_add(v.len())?)?;
221            label_values.scratch = label_values.scratch.checked_add(VALUE_SCRATCH_BYTES)?;
222            let key_path = [PathComponent::Key(k.as_str())];
223            if !label_values.paths.contains(key_path.as_slice()) {
224                label_values.paths.insert(key_path.to_vec());
225            }
226        }
227    }
228
229    let pk_meta_scratch = exemplars
230        .distinct_tags()
231        .len()
232        .checked_add(1)?
233        .checked_mul(128)?
234        .checked_add(256)?;
235    let mut total =
236        estimate_sparse_pk_array_bytes(row_count, pk_encoded_bytes, 0, pk_meta_scratch)?;
237
238    if let Some(ts_idx) = ts_idx {
239        let field = &arrow_schema.fields()[ts_idx];
240        total = total.checked_add(estimate_column_arrow_bytes(
241            field.data_type(),
242            row_count,
243            field.size(),
244            None,
245            &ValueSize::default(),
246        )?)?;
247    }
248    if let Some(val_idx) = val_idx {
249        let field = &arrow_schema.fields()[val_idx];
250        total = total.checked_add(estimate_column_arrow_bytes(
251            field.data_type(),
252            row_count,
253            field.size(),
254            None,
255            &ValueSize::default(),
256        )?)?;
257    }
258    if let Some(labels_idx) = labels_idx {
259        let column = &schema.column_schemas()[labels_idx];
260        let field = &arrow_schema.fields()[labels_idx];
261        let extension = column.extension_type::<Json2ExtensionType>().ok()?;
262        let settings = extension
263            .as_ref()
264            .filter(|ext| column.data_type.is_json2() && ext.metadata().is_version_2())
265            .map(|ext| ext.metadata().json_settings());
266        total = total.checked_add(estimate_column_arrow_bytes(
267            field.data_type(),
268            row_count,
269            field.size(),
270            settings,
271            &label_values,
272        )?)?;
273    }
274    Some(total)
275}
276
277fn estimate_column_arrow_bytes(
278    data_type: &DataType,
279    row_count: usize,
280    field_size: usize,
281    settings: Option<&JsonSettings>,
282    values: &ValueSize<'_>,
283) -> Option<usize> {
284    let count = row_count.checked_add(values.items)?;
285    let (mut bytes, paths) = if let Some(settings) = settings {
286        let limit = settings
287            .max_auto_expanded_paths()
288            .unwrap_or(JSON2_DEFAULT_MAX_AUTO_EXPANDED_PATHS);
289        (
290            array_bytes(&json::json2_physical_data_type(settings), count)?,
291            values.expanded_paths(usize::try_from(limit).ok()?)?,
292        )
293    } else {
294        (array_bytes(data_type, count)?, values.paths.len())
295    };
296    // Each selected path can need buffers for every row or nested element.
297    let path_bytes = count
298        .checked_add(1)?
299        .checked_mul(48)?
300        .checked_add(3 * ARRAY_OVERHEAD + VIEW_BLOCK_BYTES)?;
301    bytes = bytes.checked_add(paths.checked_mul(path_bytes)?)?;
302    // Builders can double capacity; payload and JSON scratch can coexist with
303    // the final arrays. Fixed per-array slack covers alignment and empty buffers.
304    bytes
305        .checked_mul(2)?
306        .checked_add(field_size.checked_mul(2)?)?
307        .checked_add(values.payload.checked_mul(4)?)?
308        .checked_add(values.scratch)
309}
310
311fn array_bytes(data_type: &DataType, count: usize) -> Option<usize> {
312    let width = match data_type {
313        DataType::Null => 0,
314        DataType::Boolean => 1,
315        DataType::Utf8 | DataType::Binary | DataType::List(_) => 4,
316        DataType::LargeUtf8 | DataType::LargeBinary | DataType::LargeList(_) => 8,
317        DataType::Utf8View | DataType::BinaryView => 16,
318        DataType::Struct(_) | DataType::FixedSizeList(_, _) | DataType::Dictionary(_, _) => 0,
319        DataType::FixedSizeBinary(width) => usize::try_from(*width).ok()?,
320        other => other.primitive_width()?,
321    };
322    // A byte per validity bit is deliberately conservative, including null padding.
323    let mut bytes = count
324        .checked_add(1)?
325        .checked_mul(width.checked_add(1)?)?
326        .checked_add(ARRAY_OVERHEAD)?;
327    if matches!(data_type, DataType::Utf8View | DataType::BinaryView) {
328        // Arrow starts out-of-line view data with an 8 KiB block.
329        bytes = bytes.checked_add(VIEW_BLOCK_BYTES)?;
330    }
331    match data_type {
332        DataType::Struct(fields) => {
333            for field in fields {
334                bytes = bytes.checked_add(array_bytes(field.data_type(), count)?)?;
335            }
336        }
337        DataType::List(field) | DataType::LargeList(field) => {
338            bytes = bytes.checked_add(array_bytes(field.data_type(), count)?)?;
339        }
340        DataType::FixedSizeList(field, len) => {
341            bytes = bytes.checked_add(array_bytes(
342                field.data_type(),
343                count.checked_mul(usize::try_from(*len).ok()?)?,
344            )?)?;
345        }
346        DataType::Dictionary(key, value) => {
347            bytes = bytes
348                .checked_add(array_bytes(key, count)?)?
349                .checked_add(array_bytes(value, count)?)?;
350        }
351        _ => {}
352    }
353    Some(bytes)
354}
355
356#[derive(Default)]
357struct ValueSize<'a> {
358    payload: usize,
359    items: usize,
360    scratch: usize,
361    paths: HashSet<Vec<PathComponent<'a>>>,
362    path: Vec<PathComponent<'a>>,
363}
364
365#[derive(Clone, PartialEq, Eq, Hash)]
366enum PathComponent<'a> {
367    Key(&'a str),
368    Field(usize),
369    Element,
370}
371
372impl<'a> ValueSize<'a> {
373    fn expanded_paths(&self, limit: usize) -> Option<usize> {
374        if limit == 0 {
375            return Some(0);
376        }
377        if self.paths.len() <= limit {
378            return Some(self.paths.len());
379        }
380
381        // Arrays count as one selectable leaf, but all their element fields can expand.
382        let mut path_sizes = HashMap::new();
383        for path in &self.paths {
384            let element = path
385                .iter()
386                .position(|part| matches!(part, PathComponent::Element));
387            let leaf = &path[..element.unwrap_or(path.len())];
388            let size = path_sizes.entry(leaf).or_insert(leaf.len());
389            if element.is_some() {
390                *size = size.checked_add(1)?;
391            }
392        }
393        // The largest candidates bound any frequency-based selection, including parent structs.
394        let mut sizes = path_sizes.into_values().collect::<Vec<_>>();
395        sizes.sort_unstable_by(|a, b| b.cmp(a));
396        let count = sizes
397            .into_iter()
398            .take(limit)
399            .try_fold(0usize, usize::checked_add)?;
400        Some(count.min(self.paths.len()))
401    }
402
403    fn payload(&mut self, bytes: usize) -> Option<()> {
404        self.payload = self.payload.checked_add(bytes)?;
405        Some(())
406    }
407
408    fn children(&mut self, len: usize, array: bool) -> Option<()> {
409        if array {
410            self.items = self.items.checked_add(len)?;
411        }
412        self.scratch = self
413            .scratch
414            .checked_add(len.checked_mul(VALUE_SCRATCH_BYTES)?)?;
415        Some(())
416    }
417
418    fn variant(&mut self, bytes: usize) -> Option<()> {
419        self.payload(bytes)?;
420        // Opaque JSONB is decoded into a tree when written to a Variant remainder.
421        self.scratch = self.scratch.checked_add(bytes.checked_mul(64)?)?;
422        Some(())
423    }
424
425    fn proto(&mut self, value: Option<&'a ValueData>) -> Option<()> {
426        match value {
427            Some(ValueData::StringValue(value)) => self.payload(value.len())?,
428            Some(ValueData::BinaryValue(value)) => self.payload(value.len())?,
429            Some(ValueData::ListValue(value)) => {
430                self.children(value.items.len(), true)?;
431                self.path.push(PathComponent::Element);
432                for value in &value.items {
433                    self.proto(value.value_data.as_ref())?;
434                }
435                self.path.pop();
436            }
437            Some(ValueData::StructValue(value)) => {
438                self.children(value.items.len(), false)?;
439                for (index, value) in value.items.iter().enumerate() {
440                    self.path.push(PathComponent::Field(index));
441                    self.proto(value.value_data.as_ref())?;
442                    self.path.pop();
443                }
444            }
445            Some(ValueData::JsonValue(value)) => self.json(value)?,
446            _ => {}
447        }
448        Some(())
449    }
450
451    fn json(&mut self, value: &'a JsonValue) -> Option<()> {
452        if !self.paths.contains(&self.path) {
453            self.paths.insert(self.path.clone());
454        }
455        self.scratch = self.scratch.checked_add(VALUE_SCRATCH_BYTES)?;
456        match value.value.as_ref() {
457            Some(json_value::Value::Str(value)) => self.payload(value.len())?,
458            Some(json_value::Value::Variant(value)) => self.variant(value.len())?,
459            Some(json_value::Value::Array(value)) => {
460                self.items = self.items.checked_add(value.items.len())?;
461                self.path.push(PathComponent::Element);
462                for value in &value.items {
463                    self.json(value)?;
464                }
465                self.path.pop();
466            }
467            Some(json_value::Value::Object(value)) => {
468                for entry in &value.entries {
469                    self.payload(entry.key.len())?;
470                    self.path.push(PathComponent::Key(&entry.key));
471                    if let Some(value) = &entry.value {
472                        self.json(value)?;
473                    }
474                    self.path.pop();
475                }
476            }
477            _ => {}
478        }
479        Some(())
480    }
481
482    fn default_value(&mut self, value: &'a Value) -> Option<()> {
483        match value {
484            Value::String(value) => self.payload(value.len())?,
485            Value::Binary(value) => self.payload(value.len())?,
486            Value::List(value) => {
487                self.children(value.items().len(), true)?;
488                self.path.push(PathComponent::Element);
489                for value in value.items() {
490                    self.default_value(value)?;
491                }
492                self.path.pop();
493            }
494            Value::Struct(value) => {
495                self.children(value.items().len(), false)?;
496                for (index, value) in value.items().iter().enumerate() {
497                    self.path.push(PathComponent::Field(index));
498                    self.default_value(value)?;
499                    self.path.pop();
500                }
501            }
502            Value::Json(value) => self.default_json(value.variant())?,
503            _ => {}
504        }
505        Some(())
506    }
507
508    fn default_json(&mut self, value: &'a JsonVariant) -> Option<()> {
509        if !self.paths.contains(&self.path) {
510            self.paths.insert(self.path.clone());
511        }
512        self.scratch = self.scratch.checked_add(VALUE_SCRATCH_BYTES)?;
513        match value {
514            JsonVariant::String(value) => self.payload(value.len())?,
515            JsonVariant::Variant(value) => self.variant(value.len())?,
516            JsonVariant::Array(values) => {
517                self.items = self.items.checked_add(values.len())?;
518                self.path.push(PathComponent::Element);
519                for value in values {
520                    self.default_json(value)?;
521                }
522                self.path.pop();
523            }
524            JsonVariant::Object(values) => {
525                for (key, value) in values {
526                    self.payload(key.len())?;
527                    self.path.push(PathComponent::Key(key));
528                    self.default_json(value)?;
529                    self.path.pop();
530                }
531            }
532            _ => {}
533        }
534        Some(())
535    }
536}
537
538#[cfg(test)]
539mod tests {
540    use super::*;
541
542    #[test]
543    fn test_estimate_overflow_fails_closed() {
544        assert!(array_bytes(&DataType::Utf8, usize::MAX).is_none());
545        let mut values = ValueSize::default();
546        assert!(values.payload(usize::MAX).is_some());
547        assert!(values.payload(1).is_none());
548        assert!(values.children(usize::MAX, true).is_none());
549    }
550}