Skip to main content

metric_engine/
batch_modifier.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::hash::Hasher;
16use std::sync::Arc;
17
18use datatypes::arrow::array::{Array, ArrayRef, BinaryBuilder, UInt64Array};
19use datatypes::arrow::datatypes::{DataType, Field, Schema as ArrowSchema};
20use datatypes::arrow::record_batch::RecordBatch;
21use datatypes::arrow_array::{is_string_null_at, string_array_value_at_index};
22use fxhash::FxHasher;
23use mito_codec::row_converter::SparsePrimaryKeyCodec;
24use snafu::ResultExt;
25use store_api::storage::ColumnId;
26use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
27
28use crate::error::{EncodePrimaryKeySnafu, Result, UnexpectedRequestSnafu};
29
30/// Info about a tag column for TSID computation and sparse primary key encoding.
31#[allow(dead_code)]
32pub struct TagColumnInfo {
33    /// Column name (used for label-name hash).
34    pub name: String,
35    /// Column index in the RecordBatch.
36    pub index: usize,
37    /// Column ID in the physical region.
38    pub column_id: ColumnId,
39}
40
41/// Computes the TSID for each row in a [RecordBatch].
42///
43/// The TSID is a stable hash of the set of labels (tags) present in each row.
44/// It accounts for both the names and values of all non-null tag columns.
45///
46/// # Logic
47/// - If a row has no nulls across all `sorted_tag_columns`, it uses a precomputed hash of all label names.
48/// - If a row has nulls, it dynamically computes a hash of the names of labels that are present (non-null).
49/// - In both cases, it then hashes the values of those present labels in the order specified by `sorted_tag_columns`.
50pub fn compute_tsid_array(
51    batch: &RecordBatch,
52    sorted_tag_columns: &[TagColumnInfo],
53    tag_arrays: &[&ArrayRef],
54) -> UInt64Array {
55    let num_rows = batch.num_rows();
56
57    let label_name_hash = {
58        let mut hasher = FxHasher::default();
59        for tag_col in sorted_tag_columns {
60            hasher.write(tag_col.name.as_bytes());
61            hasher.write_u8(0xff);
62        }
63        hasher.finish()
64    };
65
66    let mut tsid_values = Vec::with_capacity(num_rows);
67    for row in 0..num_rows {
68        let has_null = tag_arrays.iter().any(|arr| is_string_null_at(arr, row));
69
70        let tsid = if !has_null {
71            let mut hasher = FxHasher::default();
72            hasher.write_u64(label_name_hash);
73            for arr in tag_arrays {
74                if let Some(value) = string_array_value_at_index(arr, row) {
75                    hasher.write(value.as_bytes());
76                    hasher.write_u8(0xff);
77                }
78            }
79            hasher.finish()
80        } else {
81            let mut name_hasher = FxHasher::default();
82            for (tc, arr) in sorted_tag_columns.iter().zip(tag_arrays.iter()) {
83                if !is_string_null_at(arr, row) {
84                    name_hasher.write(tc.name.as_bytes());
85                    name_hasher.write_u8(0xff);
86                }
87            }
88            let row_label_hash = name_hasher.finish();
89
90            let mut val_hasher = FxHasher::default();
91            val_hasher.write_u64(row_label_hash);
92            for arr in tag_arrays {
93                if let Some(value) = string_array_value_at_index(arr, row) {
94                    val_hasher.write(value.as_bytes());
95                    val_hasher.write_u8(0xff);
96                }
97            }
98            val_hasher.finish()
99        };
100
101        tsid_values.push(tsid);
102    }
103
104    UInt64Array::from(tsid_values)
105}
106
107fn build_tag_arrays<'a>(
108    batch: &'a RecordBatch,
109    sorted_tag_columns: &[TagColumnInfo],
110) -> Result<Vec<&'a ArrayRef>> {
111    sorted_tag_columns
112        .iter()
113        .map(|tc| {
114            let array = batch.column(tc.index);
115            match array.data_type() {
116                DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Ok(array),
117                DataType::Dictionary(key_type, value_type)
118                    if key_type.is_integer() && value_type.is_string() =>
119                {
120                    Ok(array)
121                }
122                data_type => UnexpectedRequestSnafu {
123                    reason: format!(
124                        "Tag column '{}' must be a string, given: {data_type}",
125                        tc.name
126                    ),
127                }
128                .fail(),
129            }
130        })
131        .collect()
132}
133
134/// Modifies a [RecordBatch] to include a sparse primary key column.
135///
136/// This function transforms the input `batch` into a new `RecordBatch` where the first column
137/// is the generated primary key (named [PRIMARY_KEY_COLUMN_NAME]), followed by columns
138/// indicated by `extra_column_indices`.
139///
140/// The primary key uses a "sparse" encoding, which compactly represents the row's identity
141/// by only including non-null tag values. The encoding, handled by [SparsePrimaryKeyCodec],
142/// consists of:
143/// 1. The `table_id`.
144/// 2. A `tsid` (Time Series ID), which is a hash of the present tags.
145/// 3. The actual non-null tag values paired with their `column_id`.
146///
147/// # Parameters
148/// - `batch`: The source [RecordBatch].
149/// - `table_id`: The ID of the table.
150/// - `sorted_tag_columns`: Metadata for tag columns, used for both TSID computation and PK encoding.
151/// - `extra_column_indices`: Indices of columns from the original batch to keep in the output
152///   (typically the timestamp and value fields).
153pub fn modify_batch_sparse(
154    batch: RecordBatch,
155    table_id: u32,
156    sorted_tag_columns: &[TagColumnInfo],
157    extra_column_indices: &[usize],
158) -> Result<RecordBatch> {
159    let num_rows = batch.num_rows();
160    let codec = SparsePrimaryKeyCodec::schemaless();
161    let tag_arrays = build_tag_arrays(&batch, sorted_tag_columns)?;
162    let tsid_array = compute_tsid_array(&batch, sorted_tag_columns, &tag_arrays);
163
164    let mut pk_builder = BinaryBuilder::with_capacity(num_rows, 0);
165    let mut buffer = Vec::new();
166    for row in 0..num_rows {
167        buffer.clear();
168        let tags = sorted_tag_columns
169            .iter()
170            .zip(tag_arrays.iter())
171            .filter_map(|(tc, arr)| {
172                string_array_value_at_index(arr, row).map(|value| (tc.column_id, value.as_bytes()))
173            });
174        codec
175            .encode_raw(table_id, tsid_array.value(row), tags, &mut buffer)
176            .context(EncodePrimaryKeySnafu)?;
177
178        pk_builder.append_value(&buffer);
179    }
180
181    let pk_array = pk_builder.finish();
182
183    let mut fields = vec![Arc::new(Field::new(
184        PRIMARY_KEY_COLUMN_NAME,
185        DataType::Binary,
186        false,
187    ))];
188    let mut columns: Vec<Arc<dyn Array>> = vec![Arc::new(pk_array)];
189
190    for &idx in extra_column_indices {
191        fields.push(batch.schema().fields()[idx].clone());
192        columns.push(batch.column(idx).clone());
193    }
194
195    let new_schema = Arc::new(ArrowSchema::new(fields));
196    RecordBatch::try_new(new_schema, columns).map_err(|e| {
197        UnexpectedRequestSnafu {
198            reason: format!("Failed to build modified sparse RecordBatch: {e}"),
199        }
200        .build()
201    })
202}
203
204#[cfg(test)]
205mod tests {
206    use std::collections::HashMap;
207    use std::sync::Arc;
208
209    use api::v1::value::ValueData;
210    use api::v1::{ColumnDataType, ColumnSchema, Row, Rows, SemanticType, Value};
211    use datatypes::arrow::array::{BinaryArray, Int64Array, StringArray};
212    use datatypes::arrow::datatypes::{DataType, Field, Schema as ArrowSchema};
213    use datatypes::arrow::record_batch::RecordBatch;
214    use store_api::codec::PrimaryKeyEncoding;
215    use store_api::metadata::ColumnMetadata;
216    use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
217
218    use super::*;
219    use crate::row_modifier::{RowModifier, RowsIter, TableIdInput};
220
221    fn build_sparse_test_batch() -> RecordBatch {
222        let schema = Arc::new(ArrowSchema::new(vec![
223            Field::new("greptime_timestamp", DataType::Int64, false),
224            Field::new("greptime_value", DataType::Float64, true),
225            Field::new("namespace", DataType::Utf8, true),
226            Field::new("host", DataType::Utf8, true),
227        ]));
228        RecordBatch::try_new(
229            schema,
230            vec![
231                Arc::new(Int64Array::from(vec![1000])),
232                Arc::new(datatypes::arrow::array::Float64Array::from(vec![42.0])),
233                Arc::new(StringArray::from(vec!["greptimedb"])),
234                Arc::new(StringArray::from(vec!["127.0.0.1"])),
235            ],
236        )
237        .unwrap()
238    }
239
240    fn sparse_tag_columns() -> Vec<TagColumnInfo> {
241        vec![
242            TagColumnInfo {
243                name: "host".to_string(),
244                index: 3,
245                column_id: 3,
246            },
247            TagColumnInfo {
248                name: "namespace".to_string(),
249                index: 2,
250                column_id: 2,
251            },
252        ]
253    }
254
255    #[test]
256    fn test_compute_tsid_basic() {
257        let schema = Arc::new(ArrowSchema::new(vec![
258            Field::new("namespace", DataType::Utf8, true),
259            Field::new("host", DataType::Utf8, true),
260        ]));
261        let batch = RecordBatch::try_new(
262            schema,
263            vec![
264                Arc::new(StringArray::from(vec!["greptimedb"])),
265                Arc::new(StringArray::from(vec!["127.0.0.1"])),
266            ],
267        )
268        .unwrap();
269
270        let tag_columns: Vec<TagColumnInfo> = vec![
271            TagColumnInfo {
272                name: "host".to_string(),
273                index: 1,
274                column_id: 2,
275            },
276            TagColumnInfo {
277                name: "namespace".to_string(),
278                index: 0,
279                column_id: 1,
280            },
281        ];
282        let tag_arrays = build_tag_arrays(&batch, &tag_columns).unwrap();
283        let tsid_array = compute_tsid_array(&batch, &tag_columns, &tag_arrays);
284
285        assert_eq!(tsid_array.value(0), 2721566936019240841);
286    }
287
288    #[test]
289    fn test_compute_tsid_with_nulls() {
290        let schema = Arc::new(ArrowSchema::new(vec![
291            Field::new("a", DataType::Utf8, true),
292            Field::new("b", DataType::Utf8, true),
293        ]));
294        let batch_no_null = RecordBatch::try_new(
295            schema.clone(),
296            vec![
297                Arc::new(StringArray::from(vec!["A"])),
298                Arc::new(StringArray::from(vec!["B"])),
299            ],
300        )
301        .unwrap();
302        let tag_cols_2: Vec<TagColumnInfo> = vec![
303            TagColumnInfo {
304                name: "a".to_string(),
305                index: 0,
306                column_id: 1,
307            },
308            TagColumnInfo {
309                name: "b".to_string(),
310                index: 1,
311                column_id: 2,
312            },
313        ];
314        let tag_arrays_2 = build_tag_arrays(&batch_no_null, &tag_cols_2).unwrap();
315        let tsid_no_null = compute_tsid_array(&batch_no_null, &tag_cols_2, &tag_arrays_2);
316
317        let schema3 = Arc::new(ArrowSchema::new(vec![
318            Field::new("a", DataType::Utf8, true),
319            Field::new("b", DataType::Utf8, true),
320            Field::new("c", DataType::Utf8, true),
321        ]));
322        let batch_with_null = RecordBatch::try_new(
323            schema3,
324            vec![
325                Arc::new(StringArray::from(vec!["A"])),
326                Arc::new(StringArray::from(vec!["B"])),
327                Arc::new(StringArray::from(vec![None as Option<&str>])),
328            ],
329        )
330        .unwrap();
331        let tag_cols_3: Vec<TagColumnInfo> = vec![
332            TagColumnInfo {
333                name: "a".to_string(),
334                index: 0,
335                column_id: 1,
336            },
337            TagColumnInfo {
338                name: "b".to_string(),
339                index: 1,
340                column_id: 2,
341            },
342            TagColumnInfo {
343                name: "c".to_string(),
344                index: 2,
345                column_id: 3,
346            },
347        ];
348        let tag_arrays_3 = build_tag_arrays(&batch_with_null, &tag_cols_3).unwrap();
349        let tsid_with_null = compute_tsid_array(&batch_with_null, &tag_cols_3, &tag_arrays_3);
350
351        assert_eq!(tsid_no_null.value(0), tsid_with_null.value(0));
352    }
353
354    #[test]
355    fn test_modify_batch_sparse() {
356        let batch = build_sparse_test_batch();
357        let tag_columns = sparse_tag_columns();
358        let non_tag_indices = vec![0, 1];
359        let table_id: u32 = 1025;
360
361        let modified =
362            modify_batch_sparse(batch, table_id, &tag_columns, &non_tag_indices).unwrap();
363
364        assert_eq!(modified.num_columns(), 3);
365        assert_eq!(modified.schema().field(0).name(), PRIMARY_KEY_COLUMN_NAME);
366        assert_eq!(modified.schema().field(1).name(), "greptime_timestamp");
367        assert_eq!(modified.schema().field(2).name(), "greptime_value");
368    }
369
370    #[test]
371    fn test_modify_batch_sparse_matches_row_modifier() {
372        let batch = build_sparse_test_batch();
373        let tag_columns = sparse_tag_columns();
374        let non_tag_indices = vec![0, 1];
375        let table_id: u32 = 1025;
376        let modified =
377            modify_batch_sparse(batch, table_id, &tag_columns, &non_tag_indices).unwrap();
378
379        let make_info = |name: &str, column_id: ColumnId| ColumnMetadata {
380            column_schema: datatypes::schema::ColumnSchema::new(
381                name.to_string(),
382                datatypes::prelude::ConcreteDataType::string_datatype(),
383                false,
384            ),
385            semantic_type: SemanticType::Tag,
386            column_id,
387        };
388        let name_to_column_id: HashMap<String, ColumnMetadata> = [
389            (
390                "greptime_timestamp".to_string(),
391                make_info("greptime_timestamp", 0),
392            ),
393            ("greptime_value".to_string(), make_info("greptime_value", 1)),
394            ("namespace".to_string(), make_info("namespace", 2)),
395            ("host".to_string(), make_info("host", 3)),
396        ]
397        .into_iter()
398        .collect();
399
400        let rows = Rows {
401            schema: vec![
402                ColumnSchema {
403                    column_name: "greptime_timestamp".to_string(),
404                    datatype: ColumnDataType::TimestampMillisecond as i32,
405                    semantic_type: SemanticType::Timestamp as i32,
406                    ..Default::default()
407                },
408                ColumnSchema {
409                    column_name: "greptime_value".to_string(),
410                    datatype: ColumnDataType::Float64 as i32,
411                    semantic_type: SemanticType::Field as i32,
412                    ..Default::default()
413                },
414                ColumnSchema {
415                    column_name: "namespace".to_string(),
416                    datatype: ColumnDataType::String as i32,
417                    semantic_type: SemanticType::Tag as i32,
418                    ..Default::default()
419                },
420                ColumnSchema {
421                    column_name: "host".to_string(),
422                    datatype: ColumnDataType::String as i32,
423                    semantic_type: SemanticType::Tag as i32,
424                    ..Default::default()
425                },
426            ],
427            rows: vec![Row {
428                values: vec![
429                    Value {
430                        value_data: Some(ValueData::TimestampMillisecondValue(1000)),
431                    },
432                    Value {
433                        value_data: Some(ValueData::F64Value(42.0)),
434                    },
435                    Value {
436                        value_data: Some(ValueData::StringValue("greptimedb".to_string())),
437                    },
438                    Value {
439                        value_data: Some(ValueData::StringValue("127.0.0.1".to_string())),
440                    },
441                ],
442            }],
443        };
444
445        let row_iter = RowsIter::new(rows, &name_to_column_id);
446        let rows = RowModifier::default()
447            .modify_rows(
448                row_iter,
449                TableIdInput::Single(table_id),
450                PrimaryKeyEncoding::Sparse,
451            )
452            .unwrap();
453        let ValueData::BinaryValue(expected_pk) =
454            rows.rows[0].values[0].value_data.clone().unwrap()
455        else {
456            panic!("expected binary primary key");
457        };
458
459        let actual_array = modified
460            .column(0)
461            .as_any()
462            .downcast_ref::<BinaryArray>()
463            .unwrap();
464        assert_eq!(actual_array.value(0), expected_pk.as_slice());
465    }
466
467    #[test]
468    fn label_replace_with_utf8view_labels_does_not_panic() {
469        // Tag (label) columns may arrive as any string representation (`Utf8`,
470        // `LargeUtf8`, `Utf8View`, or dictionary-encoded). `modify_batch_sparse`
471        // must not assume the tag columns are plain `StringArray`s.
472        let tag_arrays: Vec<ArrayRef> = vec![
473            Arc::new(StringArray::from(vec!["greptimedb"])),
474            Arc::new(datatypes::arrow::array::LargeStringArray::from(vec![
475                "greptimedb",
476            ])),
477            Arc::new(datatypes::arrow::array::StringViewArray::from(vec![
478                "greptimedb",
479            ])),
480            Arc::new(datatypes::arrow::array::DictionaryArray::<
481                datatypes::arrow::datatypes::UInt32Type,
482            >::new(
483                datatypes::arrow::array::UInt32Array::from(vec![0]),
484                Arc::new(StringArray::from(vec!["greptimedb"])),
485            )),
486        ];
487        let tag_columns = vec![TagColumnInfo {
488            name: "namespace".to_string(),
489            index: 2,
490            column_id: 2,
491        }];
492        let non_tag_indices = vec![0, 1];
493
494        let primary_keys = tag_arrays
495            .into_iter()
496            .map(|tag_array| {
497                let schema = Arc::new(ArrowSchema::new(vec![
498                    Field::new("greptime_timestamp", DataType::Int64, false),
499                    Field::new("greptime_value", DataType::Float64, true),
500                    Field::new("namespace", tag_array.data_type().clone(), true),
501                ]));
502                let batch = RecordBatch::try_new(
503                    schema,
504                    vec![
505                        Arc::new(Int64Array::from(vec![1000])),
506                        Arc::new(datatypes::arrow::array::Float64Array::from(vec![42.0])),
507                        tag_array,
508                    ],
509                )
510                .unwrap();
511                let modified =
512                    modify_batch_sparse(batch, 1025, &tag_columns, &non_tag_indices).unwrap();
513                modified
514                    .column(0)
515                    .as_any()
516                    .downcast_ref::<BinaryArray>()
517                    .unwrap()
518                    .value(0)
519                    .to_vec()
520            })
521            .collect::<Vec<_>>();
522
523        assert!(primary_keys.windows(2).all(|keys| keys[0] == keys[1]));
524    }
525
526    #[test]
527    fn test_compute_tsid_utf8view_with_nulls_matches_utf8() {
528        // Regression test for Utf8View tag/label columns: the whole
529        // `build_tag_arrays` -> `compute_tsid_array` -> sparse primary key path must handle
530        // `Utf8View` columns exactly like `Utf8`, including rows with null tags, instead of
531        // panicking or producing different TSIDs.
532        let namespace_values: Vec<Option<&str>> =
533            vec![Some("ns-a"), Some("ns-b"), None, Some("ns-c")];
534        let host_values: Vec<Option<&str>> = vec![Some("host-1"), None, Some("host-2"), None];
535
536        let build_batch = |data_type: DataType| {
537            let (namespace, host): (ArrayRef, ArrayRef) = match &data_type {
538                DataType::Utf8 => (
539                    Arc::new(StringArray::from(namespace_values.clone())),
540                    Arc::new(StringArray::from(host_values.clone())),
541                ),
542                DataType::Utf8View => (
543                    Arc::new(datatypes::arrow::array::StringViewArray::from(
544                        namespace_values.clone(),
545                    )),
546                    Arc::new(datatypes::arrow::array::StringViewArray::from(
547                        host_values.clone(),
548                    )),
549                ),
550                _ => unreachable!(),
551            };
552            let schema = Arc::new(ArrowSchema::new(vec![
553                Field::new("greptime_timestamp", DataType::Int64, false),
554                Field::new("greptime_value", DataType::Float64, true),
555                Field::new("namespace", data_type.clone(), true),
556                Field::new("host", data_type, true),
557            ]));
558            RecordBatch::try_new(
559                schema,
560                vec![
561                    Arc::new(Int64Array::from(vec![1000, 1001, 1002, 1003])),
562                    Arc::new(datatypes::arrow::array::Float64Array::from(vec![
563                        1.0, 2.0, 3.0, 4.0,
564                    ])),
565                    namespace,
566                    host,
567                ],
568            )
569            .unwrap()
570        };
571
572        let tag_columns = vec![
573            TagColumnInfo {
574                name: "host".to_string(),
575                index: 3,
576                column_id: 3,
577            },
578            TagColumnInfo {
579                name: "namespace".to_string(),
580                index: 2,
581                column_id: 2,
582            },
583        ];
584
585        let utf8_batch = build_batch(DataType::Utf8);
586        let utf8view_batch = build_batch(DataType::Utf8View);
587
588        // Both representations must be accepted by `build_tag_arrays`.
589        let utf8_tag_arrays = build_tag_arrays(&utf8_batch, &tag_columns).unwrap();
590        let utf8view_tag_arrays = build_tag_arrays(&utf8view_batch, &tag_columns).unwrap();
591
592        // TSIDs must be identical across representations, including rows with null tags.
593        let utf8_tsids = compute_tsid_array(&utf8_batch, &tag_columns, &utf8_tag_arrays);
594        let utf8view_tsids =
595            compute_tsid_array(&utf8view_batch, &tag_columns, &utf8view_tag_arrays);
596        assert_eq!(utf8_tsids, utf8view_tsids);
597
598        // The full sparse primary key (TSID + tag values) must also be identical.
599        let non_tag_indices = vec![0, 1];
600        let modified_utf8 =
601            modify_batch_sparse(utf8_batch, 1025, &tag_columns, &non_tag_indices).unwrap();
602        let modified_utf8view =
603            modify_batch_sparse(utf8view_batch, 1025, &tag_columns, &non_tag_indices).unwrap();
604        let utf8_pks = modified_utf8
605            .column(0)
606            .as_any()
607            .downcast_ref::<BinaryArray>()
608            .unwrap();
609        let utf8view_pks = modified_utf8view
610            .column(0)
611            .as_any()
612            .downcast_ref::<BinaryArray>()
613            .unwrap();
614        for row in 0..utf8_pks.len() {
615            assert_eq!(utf8_pks.value(row), utf8view_pks.value(row));
616        }
617    }
618}