Skip to main content

metric_engine/
row_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::collections::{BTreeMap, HashMap};
16
17use api::v1::value::ValueData;
18use api::v1::{ColumnDataType, ColumnSchema, Row, Rows, SemanticType, Value};
19use datatypes::value::ValueRef;
20use mito_codec::row_converter::SparsePrimaryKeyCodec;
21use smallvec::SmallVec;
22use snafu::ResultExt;
23use store_api::codec::PrimaryKeyEncoding;
24use store_api::metadata::ColumnMetadata;
25use store_api::metric_engine_consts::{
26    DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME,
27};
28use store_api::storage::consts::{PRIMARY_KEY_COLUMN_NAME, ReservedColumnId};
29use store_api::storage::{ColumnId, TableId};
30
31use crate::error::{EncodePrimaryKeySnafu, Result, TableIdCountMismatchSnafu};
32
33/// A row modifier modifies [`Rows`].
34///
35/// - For [`PrimaryKeyEncoding::Sparse`] encoding,
36///   it replaces the primary key columns with the encoded primary key column(`__primary_key`).
37///
38/// - For [`PrimaryKeyEncoding::Dense`] encoding,
39///   it adds two columns(`__table_id`, `__tsid`) to the row.
40pub struct RowModifier {
41    codec: SparsePrimaryKeyCodec,
42}
43
44/// Table id input for row modification.
45#[derive(Clone, Copy)]
46pub(crate) enum TableIdInput<'a> {
47    Single(TableId),
48    Batch(&'a [TableId]),
49}
50
51impl<'a> TableIdInput<'a> {
52    fn table_id_for_row(&self, row_idx: usize) -> TableId {
53        match self {
54            TableIdInput::Single(table_id) => *table_id,
55            TableIdInput::Batch(table_ids) => table_ids[row_idx],
56        }
57    }
58}
59
60impl Default for RowModifier {
61    fn default() -> Self {
62        Self {
63            codec: SparsePrimaryKeyCodec::schemaless(),
64        }
65    }
66}
67
68impl RowModifier {
69    /// Modify rows with the given primary key encoding and table ids.
70    pub(crate) fn modify_rows(
71        &self,
72        iter: RowsIter,
73        table_ids: TableIdInput<'_>,
74        encoding: PrimaryKeyEncoding,
75    ) -> Result<Rows> {
76        let row_count = iter.rows.rows.len();
77        Self::validate_table_id_count(table_ids, row_count)?;
78        match encoding {
79            PrimaryKeyEncoding::Sparse => self.modify_rows_sparse(iter, table_ids),
80            PrimaryKeyEncoding::Dense => self.modify_rows_dense(iter, table_ids),
81        }
82    }
83
84    /// Modifies rows with sparse primary key encoding.
85    /// It replaces the primary key columns with the encoded primary key column(`__primary_key`).
86    fn modify_rows_sparse(&self, mut iter: RowsIter, table_ids: TableIdInput<'_>) -> Result<Rows> {
87        let num_column = iter.rows.schema.len();
88        let num_primary_key_column = iter.index.num_primary_key_column;
89        // num_output_column = remaining columns(fields columns + timestamp column) + 1 (encoded primary key column)
90        let num_output_column = num_column - num_primary_key_column + 1;
91
92        let mut buffer = vec![];
93
94        for (row_index, mut row_iter) in iter.iter_mut().enumerate() {
95            let table_id = table_ids.table_id_for_row(row_index);
96            let (table_id_value, tsid) = Self::fill_internal_columns(table_id, &row_iter);
97            let mut values = Vec::with_capacity(num_output_column);
98            buffer.clear();
99            let internal_columns = [
100                (
101                    ReservedColumnId::table_id(),
102                    api::helper::pb_value_to_value_ref(&table_id_value, None),
103                ),
104                (
105                    ReservedColumnId::tsid(),
106                    api::helper::pb_value_to_value_ref(&tsid, None),
107                ),
108            ];
109            self.codec
110                .encode_to_vec(internal_columns.into_iter(), &mut buffer)
111                .context(EncodePrimaryKeySnafu)?;
112            self.codec
113                .encode_to_vec(row_iter.primary_keys(), &mut buffer)
114                .context(EncodePrimaryKeySnafu)?;
115
116            values.push(ValueData::BinaryValue(buffer.clone()).into());
117            values.extend(row_iter.remaining());
118            // Replace the row with the encoded row
119            *row_iter.row = Row { values };
120        }
121
122        // Update the schema
123        let mut schema = Vec::with_capacity(num_output_column);
124        schema.push(ColumnSchema {
125            column_name: PRIMARY_KEY_COLUMN_NAME.to_string(),
126            datatype: ColumnDataType::Binary as i32,
127            semantic_type: SemanticType::Tag as _,
128            datatype_extension: None,
129            options: None,
130        });
131        schema.extend(iter.remaining_columns());
132        iter.rows.schema = schema;
133
134        Ok(iter.rows)
135    }
136
137    /// Modifies rows with dense primary key encoding.
138    /// It adds two columns(`__table_id`, `__tsid`) to the row.
139    fn modify_rows_dense(&self, mut iter: RowsIter, table_ids: TableIdInput<'_>) -> Result<Rows> {
140        // add table_name column
141        iter.rows.schema.push(ColumnSchema {
142            column_name: DATA_SCHEMA_TABLE_ID_COLUMN_NAME.to_string(),
143            datatype: ColumnDataType::Uint32 as i32,
144            semantic_type: SemanticType::Tag as _,
145            datatype_extension: None,
146            options: None,
147        });
148        // add tsid column
149        iter.rows.schema.push(ColumnSchema {
150            column_name: DATA_SCHEMA_TSID_COLUMN_NAME.to_string(),
151            datatype: ColumnDataType::Uint64 as i32,
152            semantic_type: SemanticType::Tag as _,
153            datatype_extension: None,
154            options: None,
155        });
156        for (row_index, row_iter) in iter.iter_mut().enumerate() {
157            let table_id = table_ids.table_id_for_row(row_index);
158            let (table_id_value, tsid) = Self::fill_internal_columns(table_id, &row_iter);
159            row_iter.row.values.push(table_id_value);
160            row_iter.row.values.push(tsid);
161        }
162
163        Ok(iter.rows)
164    }
165
166    fn validate_table_id_count(table_ids: TableIdInput<'_>, row_count: usize) -> Result<()> {
167        if let TableIdInput::Batch(table_ids) = table_ids
168            && table_ids.len() != row_count
169        {
170            return TableIdCountMismatchSnafu {
171                expected: row_count,
172                actual: table_ids.len(),
173            }
174            .fail();
175        }
176        Ok(())
177    }
178
179    /// Fills internal columns of a row with table name and a hash of tag values.
180    pub fn fill_internal_columns(table_id: TableId, iter: &RowIter<'_>) -> (Value, Value) {
181        let ts_id = if !iter.has_null_labels() {
182            // No null labels in row, we can safely reuse the precomputed label name hash.
183            let mut ts_id_gen = TsidGenerator::new(iter.index.label_name_hash);
184            for (_, value) in iter.primary_keys_with_name() {
185                // The type is checked before. So only null is ignored.
186                if let Some(ValueData::StringValue(string)) = &value.value_data {
187                    ts_id_gen.write_str(string);
188                } else {
189                    unreachable!(
190                        "Should not contain null or non-string value: {:?}, table id: {}",
191                        value, table_id
192                    );
193                }
194            }
195            ts_id_gen.finish()
196        } else {
197            TsidGenerator::from_sorted_tags(iter.primary_keys_with_name().filter_map(
198                |(name, value)| match &value.value_data {
199                    Some(ValueData::StringValue(value)) => Some((name.as_str(), value.as_str())),
200                    _ => None,
201                },
202            ))
203        };
204
205        (
206            ValueData::U32Value(table_id).into(),
207            ValueData::U64Value(ts_id).into(),
208        )
209    }
210}
211
212/// Tsid generator.
213pub use mito_codec::row_converter::TsidGenerator;
214
215/// Index of a value.
216#[derive(Debug, Clone, Copy)]
217struct ValueIndex {
218    column_id: ColumnId,
219    index: usize,
220}
221
222/// Index of a row.
223struct IterIndex {
224    indices: Vec<ValueIndex>,
225    num_primary_key_column: usize,
226    /// Precomputed hash for label names.
227    label_name_hash: u64,
228}
229
230impl IterIndex {
231    fn new(
232        row_schema: &[ColumnSchema],
233        physical_columns: &HashMap<String, ColumnMetadata>,
234    ) -> Self {
235        let mut reserved_indices = SmallVec::<[ValueIndex; 2]>::new();
236        // Uses BTreeMap to keep the primary key column name order (lexicographical)
237        let mut primary_key_indices = BTreeMap::new();
238        let mut field_indices = SmallVec::<[ValueIndex; 1]>::new();
239        let mut ts_index = None;
240        for (idx, col) in row_schema.iter().enumerate() {
241            match col.semantic_type() {
242                SemanticType::Tag => match col.column_name.as_str() {
243                    DATA_SCHEMA_TABLE_ID_COLUMN_NAME => {
244                        reserved_indices.push(ValueIndex {
245                            column_id: ReservedColumnId::table_id(),
246                            index: idx,
247                        });
248                    }
249                    DATA_SCHEMA_TSID_COLUMN_NAME => {
250                        reserved_indices.push(ValueIndex {
251                            column_id: ReservedColumnId::tsid(),
252                            index: idx,
253                        });
254                    }
255                    _ => {
256                        // Inserts primary key column name follower the column name order (lexicographical)
257                        primary_key_indices.insert(
258                            col.column_name.as_str(),
259                            ValueIndex {
260                                column_id: physical_columns
261                                    .get(&col.column_name)
262                                    .unwrap()
263                                    .column_id,
264                                index: idx,
265                            },
266                        );
267                    }
268                },
269                SemanticType::Field => {
270                    field_indices.push(ValueIndex {
271                        column_id: physical_columns.get(&col.column_name).unwrap().column_id,
272                        index: idx,
273                    });
274                }
275                SemanticType::Timestamp => {
276                    ts_index = Some(ValueIndex {
277                        column_id: physical_columns.get(&col.column_name).unwrap().column_id,
278                        index: idx,
279                    });
280                }
281            }
282        }
283        let num_primary_key_column = primary_key_indices.len() + reserved_indices.len();
284        let mut indices = Vec::with_capacity(num_primary_key_column + 2);
285        indices.extend(reserved_indices);
286        let mut label_name_hasher = TsidGenerator::default();
287        for (pk_name, pk_index) in primary_key_indices {
288            // primary_key_indices already sorted.
289            label_name_hasher.write_str(pk_name);
290            indices.push(pk_index);
291        }
292        let label_name_hash = label_name_hasher.finish();
293
294        indices.extend(ts_index);
295        indices.extend(field_indices);
296        IterIndex {
297            indices,
298            num_primary_key_column,
299            label_name_hash,
300        }
301    }
302}
303
304/// Iterator of rows.
305pub struct RowsIter {
306    rows: Rows,
307    index: IterIndex,
308}
309
310impl RowsIter {
311    pub fn new(rows: Rows, physical_columns: &HashMap<String, ColumnMetadata>) -> Self {
312        let index: IterIndex = IterIndex::new(&rows.schema, physical_columns);
313        Self { rows, index }
314    }
315
316    /// Returns the iterator of rows.
317    pub fn iter_mut(&mut self) -> impl Iterator<Item = RowIter<'_>> {
318        self.rows.rows.iter_mut().map(|row| RowIter {
319            row,
320            index: &self.index,
321            schema: &self.rows.schema,
322        })
323    }
324
325    /// Returns the remaining columns.
326    fn remaining_columns(&mut self) -> impl Iterator<Item = ColumnSchema> + '_ {
327        self.index.indices[self.index.num_primary_key_column..]
328            .iter()
329            .map(|idx| std::mem::take(&mut self.rows.schema[idx.index]))
330    }
331}
332
333/// Iterator of a row.
334pub struct RowIter<'a> {
335    row: &'a mut Row,
336    index: &'a IterIndex,
337    schema: &'a Vec<ColumnSchema>,
338}
339
340impl RowIter<'_> {
341    /// Returns the primary keys with their names.
342    fn primary_keys_with_name(&self) -> impl Iterator<Item = (&String, &Value)> + Clone {
343        self.index.indices[..self.index.num_primary_key_column]
344            .iter()
345            .map(|idx| {
346                (
347                    &self.schema[idx.index].column_name,
348                    &self.row.values[idx.index],
349                )
350            })
351    }
352
353    /// Returns true if any label in current row is null.
354    fn has_null_labels(&self) -> bool {
355        self.index.indices[..self.index.num_primary_key_column]
356            .iter()
357            .any(|idx| self.row.values[idx.index].value_data.is_none())
358    }
359
360    /// Returns the primary keys.
361    pub fn primary_keys(&self) -> impl Iterator<Item = (ColumnId, ValueRef<'_>)> {
362        self.index.indices[..self.index.num_primary_key_column]
363            .iter()
364            .map(|idx| {
365                (
366                    idx.column_id,
367                    api::helper::pb_value_to_value_ref(
368                        &self.row.values[idx.index],
369                        self.schema[idx.index].datatype_extension.as_ref(),
370                    ),
371                )
372            })
373    }
374
375    /// Returns the remaining columns.
376    fn remaining(&mut self) -> impl Iterator<Item = Value> + '_ {
377        self.index.indices[self.index.num_primary_key_column..]
378            .iter()
379            .map(|idx| std::mem::take(&mut self.row.values[idx.index]))
380    }
381
382    /// Returns value at given offset.
383    /// # Panics
384    /// Panics if offset out-of-bound
385    pub fn value_at(&self, idx: usize) -> &Value {
386        &self.row.values[idx]
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use std::collections::HashMap;
393
394    use api::v1::{Row, Rows};
395    use store_api::codec::PrimaryKeyEncoding;
396
397    use super::*;
398    use crate::error::Error;
399
400    fn test_schema() -> Vec<ColumnSchema> {
401        vec![
402            ColumnSchema {
403                column_name: "namespace".to_string(),
404                datatype: ColumnDataType::String as i32,
405                semantic_type: SemanticType::Tag as _,
406                datatype_extension: None,
407                options: None,
408            },
409            ColumnSchema {
410                column_name: "host".to_string(),
411                datatype: ColumnDataType::String as i32,
412                semantic_type: SemanticType::Tag as _,
413                datatype_extension: None,
414                options: None,
415            },
416        ]
417    }
418
419    fn test_row(v1: &str, v2: &str) -> Row {
420        Row {
421            values: vec![
422                ValueData::StringValue(v1.to_string()).into(),
423                ValueData::StringValue(v2.to_string()).into(),
424            ],
425        }
426    }
427
428    fn make_info(name: &str, column_id: ColumnId) -> ColumnMetadata {
429        ColumnMetadata {
430            column_schema: datatypes::schema::ColumnSchema::new(
431                name.to_string(),
432                datatypes::prelude::ConcreteDataType::string_datatype(),
433                false,
434            ),
435            semantic_type: SemanticType::Tag,
436            column_id,
437        }
438    }
439
440    fn test_name_to_column_id() -> HashMap<String, ColumnMetadata> {
441        HashMap::from([
442            ("namespace".to_string(), make_info("namespace", 1)),
443            ("host".to_string(), make_info("host", 2)),
444        ])
445    }
446
447    #[test]
448    fn test_encode_sparse() {
449        let name_to_column_id = test_name_to_column_id();
450        let encoder = RowModifier::default();
451        let table_id = 1025;
452        let schema = test_schema();
453        let row = test_row("greptimedb", "127.0.0.1");
454        let rows = Rows {
455            schema,
456            rows: vec![row],
457        };
458        let rows_iter = RowsIter::new(rows, &name_to_column_id);
459        let result = encoder
460            .modify_rows(
461                rows_iter,
462                TableIdInput::Single(table_id),
463                PrimaryKeyEncoding::Sparse,
464            )
465            .unwrap();
466        assert_eq!(result.rows[0].values.len(), 1);
467        let encoded_primary_key = vec![
468            128, 0, 0, 4, 1, 0, 0, 4, 1, 128, 0, 0, 3, 1, 37, 196, 242, 181, 117, 224, 7, 137, 0,
469            0, 0, 2, 1, 1, 49, 50, 55, 46, 48, 46, 48, 46, 9, 49, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
470            1, 1, 1, 103, 114, 101, 112, 116, 105, 109, 101, 9, 100, 98, 0, 0, 0, 0, 0, 0, 2,
471        ];
472        assert_eq!(
473            result.rows[0].values[0],
474            ValueData::BinaryValue(encoded_primary_key).into()
475        );
476        assert_eq!(result.schema, expected_sparse_schema());
477    }
478
479    fn expected_sparse_schema() -> Vec<ColumnSchema> {
480        vec![ColumnSchema {
481            column_name: PRIMARY_KEY_COLUMN_NAME.to_string(),
482            datatype: ColumnDataType::Binary as i32,
483            semantic_type: SemanticType::Tag as _,
484            datatype_extension: None,
485            options: None,
486        }]
487    }
488
489    fn expected_dense_schema() -> Vec<ColumnSchema> {
490        vec![
491            ColumnSchema {
492                column_name: "namespace".to_string(),
493                datatype: ColumnDataType::String as i32,
494                semantic_type: SemanticType::Tag as _,
495                datatype_extension: None,
496                options: None,
497            },
498            ColumnSchema {
499                column_name: "host".to_string(),
500                datatype: ColumnDataType::String as i32,
501                semantic_type: SemanticType::Tag as _,
502                datatype_extension: None,
503                options: None,
504            },
505            ColumnSchema {
506                column_name: DATA_SCHEMA_TABLE_ID_COLUMN_NAME.to_string(),
507                datatype: ColumnDataType::Uint32 as i32,
508                semantic_type: SemanticType::Tag as _,
509                datatype_extension: None,
510                options: None,
511            },
512            ColumnSchema {
513                column_name: DATA_SCHEMA_TSID_COLUMN_NAME.to_string(),
514                datatype: ColumnDataType::Uint64 as i32,
515                semantic_type: SemanticType::Tag as _,
516                datatype_extension: None,
517                options: None,
518            },
519        ]
520    }
521
522    #[test]
523    fn test_encode_dense() {
524        let name_to_column_id = test_name_to_column_id();
525        let encoder = RowModifier::default();
526        let table_id = 1025;
527        let schema = test_schema();
528        let row = test_row("greptimedb", "127.0.0.1");
529        let rows = Rows {
530            schema,
531            rows: vec![row],
532        };
533        let rows_iter = RowsIter::new(rows, &name_to_column_id);
534        let result = encoder
535            .modify_rows(
536                rows_iter,
537                TableIdInput::Single(table_id),
538                PrimaryKeyEncoding::Dense,
539            )
540            .unwrap();
541        assert_eq!(
542            result.rows[0].values[0],
543            ValueData::StringValue("greptimedb".to_string()).into()
544        );
545        assert_eq!(
546            result.rows[0].values[1],
547            ValueData::StringValue("127.0.0.1".to_string()).into()
548        );
549        assert_eq!(result.rows[0].values[2], ValueData::U32Value(1025).into());
550        assert_eq!(
551            result.rows[0].values[3],
552            ValueData::U64Value(2721566936019240841).into()
553        );
554        assert_eq!(result.schema, expected_dense_schema());
555    }
556
557    #[test]
558    fn test_table_id_count_mismatch() {
559        let name_to_column_id = test_name_to_column_id();
560        let encoder = RowModifier::default();
561        let schema = test_schema();
562        let rows = Rows {
563            schema,
564            rows: vec![test_row("a", "b"), test_row("c", "d")],
565        };
566        let rows_iter = RowsIter::new(rows, &name_to_column_id);
567        let table_ids = [1025];
568        let err = encoder
569            .modify_rows(
570                rows_iter,
571                TableIdInput::Batch(&table_ids),
572                PrimaryKeyEncoding::Dense,
573            )
574            .unwrap_err();
575        assert!(matches!(
576            err,
577            Error::TableIdCountMismatch {
578                expected: 2,
579                actual: 1,
580                ..
581            }
582        ));
583    }
584
585    #[test]
586    fn test_fill_internal_columns() {
587        let name_to_column_id = test_name_to_column_id();
588        let table_id = 1025;
589        let schema = test_schema();
590        let row = test_row("greptimedb", "127.0.0.1");
591        let rows = Rows {
592            schema,
593            rows: vec![row],
594        };
595        let mut rows_iter = RowsIter::new(rows, &name_to_column_id);
596        let row_iter = rows_iter.iter_mut().next().unwrap();
597        let (encoded_table_id, tsid) = RowModifier::fill_internal_columns(table_id, &row_iter);
598        assert_eq!(encoded_table_id, ValueData::U32Value(1025).into());
599        assert_eq!(tsid, ValueData::U64Value(2721566936019240841).into());
600
601        // Change the column order
602        let schema = vec![
603            ColumnSchema {
604                column_name: "host".to_string(),
605                datatype: ColumnDataType::String as i32,
606                semantic_type: SemanticType::Tag as _,
607                datatype_extension: None,
608                options: None,
609            },
610            ColumnSchema {
611                column_name: "namespace".to_string(),
612                datatype: ColumnDataType::String as i32,
613                semantic_type: SemanticType::Tag as _,
614                datatype_extension: None,
615                options: None,
616            },
617        ];
618        let row = test_row("127.0.0.1", "greptimedb");
619        let rows = Rows {
620            schema,
621            rows: vec![row],
622        };
623        let mut rows_iter = RowsIter::new(rows, &name_to_column_id);
624        let row_iter = rows_iter.iter_mut().next().unwrap();
625        let (encoded_table_id, tsid) = RowModifier::fill_internal_columns(table_id, &row_iter);
626        assert_eq!(encoded_table_id, ValueData::U32Value(1025).into());
627        assert_eq!(tsid, ValueData::U64Value(2721566936019240841).into());
628    }
629
630    /// Helper function to create a schema with multiple label columns
631    fn create_multi_label_schema(labels: &[&str]) -> Vec<ColumnSchema> {
632        labels
633            .iter()
634            .map(|name| ColumnSchema {
635                column_name: name.to_string(),
636                datatype: ColumnDataType::String as i32,
637                semantic_type: SemanticType::Tag as _,
638                datatype_extension: None,
639                options: None,
640            })
641            .collect()
642    }
643
644    /// Helper function to create a name_to_column_id map
645    fn create_name_to_column_id(labels: &[&str]) -> HashMap<String, ColumnMetadata> {
646        labels
647            .iter()
648            .enumerate()
649            .map(|(idx, name)| (name.to_string(), make_info(name, idx as ColumnId + 1)))
650            .collect()
651    }
652
653    /// Helper function to create a row with string values
654    fn create_row_with_values(values: &[&str]) -> Row {
655        Row {
656            values: values
657                .iter()
658                .map(|v| ValueData::StringValue(v.to_string()).into())
659                .collect(),
660        }
661    }
662
663    /// Helper function to create a row with some null values
664    fn create_row_with_nulls(values: &[Option<&str>]) -> Row {
665        Row {
666            values: values
667                .iter()
668                .map(|v| {
669                    v.map(|s| ValueData::StringValue(s.to_string()).into())
670                        .unwrap_or(Value { value_data: None })
671                })
672                .collect(),
673        }
674    }
675
676    /// Helper function to extract TSID from a row
677    fn extract_tsid(
678        schema: Vec<ColumnSchema>,
679        row: Row,
680        name_to_column_id: &HashMap<String, ColumnMetadata>,
681        table_id: TableId,
682    ) -> u64 {
683        let rows = Rows {
684            schema,
685            rows: vec![row],
686        };
687        let mut rows_iter = RowsIter::new(rows, name_to_column_id);
688        let row_iter = rows_iter.iter_mut().next().unwrap();
689        let (_, tsid_value) = RowModifier::fill_internal_columns(table_id, &row_iter);
690        match tsid_value.value_data {
691            Some(ValueData::U64Value(tsid)) => tsid,
692            _ => panic!("Expected U64Value for TSID"),
693        }
694    }
695
696    #[test]
697    fn test_tsid_same_for_different_label_orders() {
698        // Test that rows with the same label name-value pairs but in different orders
699        // produce the same TSID
700        let table_id = 1025;
701
702        // Schema 1: a, b, c
703        let schema1 = create_multi_label_schema(&["a", "b", "c"]);
704        let name_to_column_id1 = create_name_to_column_id(&["a", "b", "c"]);
705        let row1 = create_row_with_values(&["A", "B", "C"]);
706        let tsid1 = extract_tsid(schema1, row1, &name_to_column_id1, table_id);
707
708        // Schema 2: b, a, c (different order)
709        let schema2 = create_multi_label_schema(&["b", "a", "c"]);
710        let name_to_column_id2 = create_name_to_column_id(&["a", "b", "c"]);
711        let row2 = create_row_with_values(&["B", "A", "C"]);
712        let tsid2 = extract_tsid(schema2, row2, &name_to_column_id2, table_id);
713
714        // Schema 3: c, b, a (another different order)
715        let schema3 = create_multi_label_schema(&["c", "b", "a"]);
716        let name_to_column_id3 = create_name_to_column_id(&["a", "b", "c"]);
717        let row3 = create_row_with_values(&["C", "B", "A"]);
718        let tsid3 = extract_tsid(schema3, row3, &name_to_column_id3, table_id);
719
720        // All should have the same TSID since label names are sorted lexicographically
721        // and we're using the same label name-value pairs
722        assert_eq!(
723            tsid1, tsid2,
724            "TSID should be same for different column orders"
725        );
726        assert_eq!(
727            tsid2, tsid3,
728            "TSID should be same for different column orders"
729        );
730    }
731
732    #[test]
733    fn test_tsid_same_with_null_labels() {
734        // Test that rows that differ only by null label values produce the same TSID
735        let table_id = 1025;
736
737        // Row 1: a=A, b=B (no nulls, fast path)
738        let schema1 = create_multi_label_schema(&["a", "b"]);
739        let name_to_column_id1 = create_name_to_column_id(&["a", "b"]);
740        let row1 = create_row_with_values(&["A", "B"]);
741        let tsid1 = extract_tsid(schema1, row1, &name_to_column_id1, table_id);
742
743        // Row 2: a=A, b=B, c=null (has null, slow path)
744        let schema2 = create_multi_label_schema(&["a", "b", "c"]);
745        let name_to_column_id2 = create_name_to_column_id(&["a", "b", "c"]);
746        let row2 = create_row_with_nulls(&[Some("A"), Some("B"), None]);
747        let tsid2 = extract_tsid(schema2, row2, &name_to_column_id2, table_id);
748
749        // Both should have the same TSID since null labels are ignored
750        assert_eq!(
751            tsid1, tsid2,
752            "TSID should be same when only difference is null label values"
753        );
754    }
755
756    #[test]
757    fn test_sorted_tags_match_metric_rows() {
758        let names = ["b", "a", "absent"];
759        for values in [
760            [Some("B"), Some(""), Some("C")],
761            [Some("B"), Some(""), None],
762            [None, Some("A"), None],
763            [None, None, None],
764        ] {
765            let tags = names
766                .into_iter()
767                .zip(values)
768                .filter_map(|(name, value)| value.map(|value| (name, value)))
769                .collect::<BTreeMap<_, _>>();
770            let tsid =
771                TsidGenerator::from_sorted_tags(tags.iter().map(|(name, value)| (*name, *value)));
772            assert_eq!(
773                tsid,
774                extract_tsid(
775                    create_multi_label_schema(&names),
776                    create_row_with_nulls(&values),
777                    &create_name_to_column_id(&names),
778                    42
779                )
780            );
781        }
782    }
783
784    #[test]
785    fn test_tsid_same_with_multiple_null_labels() {
786        // Test with multiple null labels
787        let table_id = 1025;
788
789        // Row 1: a=A, b=B (no nulls)
790        let schema1 = create_multi_label_schema(&["a", "b"]);
791        let name_to_column_id1 = create_name_to_column_id(&["a", "b"]);
792        let row1 = create_row_with_values(&["A", "B"]);
793        let tsid1 = extract_tsid(schema1, row1, &name_to_column_id1, table_id);
794
795        // Row 2: a=A, b=B, c=null, d=null (multiple nulls)
796        let schema2 = create_multi_label_schema(&["a", "b", "c", "d"]);
797        let name_to_column_id2 = create_name_to_column_id(&["a", "b", "c", "d"]);
798        let row2 = create_row_with_nulls(&[Some("A"), Some("B"), None, None]);
799        let tsid2 = extract_tsid(schema2, row2, &name_to_column_id2, table_id);
800
801        assert_eq!(
802            tsid1, tsid2,
803            "TSID should be same when only difference is multiple null label values"
804        );
805    }
806
807    #[test]
808    fn test_tsid_different_with_different_non_null_values() {
809        // Test that rows with different non-null values produce different TSIDs
810        let table_id = 1025;
811
812        // Row 1: a=A, b=B
813        let schema1 = create_multi_label_schema(&["a", "b"]);
814        let name_to_column_id1 = create_name_to_column_id(&["a", "b"]);
815        let row1 = create_row_with_values(&["A", "B"]);
816        let tsid1 = extract_tsid(schema1, row1, &name_to_column_id1, table_id);
817
818        // Row 2: a=A, b=C (different value for b)
819        let schema2 = create_multi_label_schema(&["a", "b"]);
820        let name_to_column_id2 = create_name_to_column_id(&["a", "b"]);
821        let row2 = create_row_with_values(&["A", "C"]);
822        let tsid2 = extract_tsid(schema2, row2, &name_to_column_id2, table_id);
823
824        assert_ne!(
825            tsid1, tsid2,
826            "TSID should be different when label values differ"
827        );
828    }
829
830    #[test]
831    fn test_tsid_fast_path_vs_slow_path_consistency() {
832        // Test that fast path (no nulls) and slow path (with nulls) produce
833        // the same TSID for the same non-null label values
834        let table_id = 1025;
835
836        // Fast path: a=A, b=B (no nulls)
837        let schema_fast = create_multi_label_schema(&["a", "b"]);
838        let name_to_column_id_fast = create_name_to_column_id(&["a", "b"]);
839        let row_fast = create_row_with_values(&["A", "B"]);
840        let tsid_fast = extract_tsid(schema_fast, row_fast, &name_to_column_id_fast, table_id);
841
842        // Slow path: a=A, b=B, c=null (has null, triggers slow path)
843        let schema_slow = create_multi_label_schema(&["a", "b", "c"]);
844        let name_to_column_id_slow = create_name_to_column_id(&["a", "b", "c"]);
845        let row_slow = create_row_with_nulls(&[Some("A"), Some("B"), None]);
846        let tsid_slow = extract_tsid(schema_slow, row_slow, &name_to_column_id_slow, table_id);
847
848        assert_eq!(
849            tsid_fast, tsid_slow,
850            "Fast path and slow path should produce same TSID for same non-null values"
851        );
852    }
853
854    #[test]
855    fn test_tsid_with_null_in_middle() {
856        // Test with null in the middle of labels
857        let table_id = 1025;
858
859        // Row 1: a=A, b=B, c=C
860        let schema1 = create_multi_label_schema(&["a", "b", "c"]);
861        let name_to_column_id1 = create_name_to_column_id(&["a", "b", "c"]);
862        let row1 = create_row_with_values(&["A", "B", "C"]);
863        let tsid1 = extract_tsid(schema1, row1, &name_to_column_id1, table_id);
864
865        // Row 2: a=A, b=null, c=C (null in middle)
866        let schema2 = create_multi_label_schema(&["a", "b", "c"]);
867        let name_to_column_id2 = create_name_to_column_id(&["a", "b", "c"]);
868        let row2 = create_row_with_nulls(&[Some("A"), None, Some("C")]);
869        let tsid2 = extract_tsid(schema2, row2, &name_to_column_id2, table_id);
870
871        // Should be different because b is null in row2 but B in row1
872        // Actually wait, let me reconsider - if b is null, it should be ignored
873        // So row2 should be equivalent to a=A, c=C
874        // But row1 is a=A, b=B, c=C, so they should be different
875        assert_ne!(
876            tsid1, tsid2,
877            "TSID should be different when a non-null value becomes null"
878        );
879
880        // Row 3: a=A, c=C (no b at all, equivalent to row2)
881        let schema3 = create_multi_label_schema(&["a", "c"]);
882        let name_to_column_id3 = create_name_to_column_id(&["a", "c"]);
883        let row3 = create_row_with_values(&["A", "C"]);
884        let tsid3 = extract_tsid(schema3, row3, &name_to_column_id3, table_id);
885
886        // Row2 (a=A, b=null, c=C) should be same as row3 (a=A, c=C)
887        assert_eq!(
888            tsid2, tsid3,
889            "TSID should be same when null label is ignored"
890        );
891    }
892
893    #[test]
894    fn test_tsid_all_null_labels() {
895        // Test with all labels being null
896        let table_id = 1025;
897
898        // Row with all nulls
899        let schema = create_multi_label_schema(&["a", "b", "c"]);
900        let name_to_column_id = create_name_to_column_id(&["a", "b", "c"]);
901        let row = create_row_with_nulls(&[None, None, None]);
902        let tsid = extract_tsid(schema.clone(), row, &name_to_column_id, table_id);
903
904        // Should still produce a TSID (based on label names only when all values are null)
905        // This tests that the slow path handles the case where all values are null
906        // The TSID will be based on the label name hash only
907        // Test that it's consistent - same schema with all nulls should produce same TSID
908        let row2 = create_row_with_nulls(&[None, None, None]);
909        let tsid2 = extract_tsid(schema, row2, &name_to_column_id, table_id);
910        assert_eq!(
911            tsid, tsid2,
912            "TSID should be consistent when all label values are null"
913        );
914    }
915}