Skip to main content

metric_engine/
data_region.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;
16
17use api::v1::SemanticType;
18use common_query::native_histogram::is_native_histogram_value_type;
19use common_telemetry::{debug, info};
20use datatypes::schema::{SkippingIndexOptions, SkippingIndexType};
21use mito2::engine::MitoEngine;
22use snafu::ResultExt;
23use store_api::metadata::{ColumnMetadata, RegionMetadataRef};
24use store_api::region_engine::RegionEngine;
25use store_api::region_request::{
26    AddColumn, AffectedRows, AlterKind, RegionAlterRequest, RegionRequest,
27};
28use store_api::storage::consts::ReservedColumnId;
29use store_api::storage::{ConcreteDataType, RegionId};
30
31use crate::engine::{IndexOptions, validate_shared_column};
32use crate::error::{
33    AddingFieldColumnSnafu, ColumnTypeMismatchSnafu, ForbiddenPhysicalAlterSnafu,
34    MitoReadOperationSnafu, MitoWriteOperationSnafu, Result, SetSkippingIndexOptionSnafu,
35};
36use crate::metrics::{FORBIDDEN_OPERATION_COUNT, MITO_DDL_DURATION, PHYSICAL_COLUMN_COUNT};
37use crate::utils;
38
39/// This is a generic handler like [MetricEngine](crate::engine::MetricEngine). It
40/// will handle all the data related operations across physical tables. Thus
41/// every operation should be associated to a [RegionId], which is the physical
42/// table id + region sequence. This handler will transform the region group by
43/// itself.
44pub struct DataRegion {
45    mito: MitoEngine,
46}
47
48impl DataRegion {
49    pub(crate) fn new(mito: MitoEngine) -> Self {
50        Self { mito }
51    }
52
53    /// Submit an alter request to underlying physical region.
54    ///
55    /// This method will change the nullability of those given columns.
56    /// [SemanticType::Tag] will become nullable column as it's shared between
57    /// logical regions.
58    ///
59    /// Invoker don't need to set up or verify the column id. This method will adjust
60    /// it using underlying schema, and reuse the persisted id of a column that the
61    /// physical region already has.
62    ///
63    /// This method will also set the nullable marker to true. All of those change are applies
64    /// to `columns` in-place.
65    ///
66    /// Callers must hold the column-add lock of the physical region, otherwise two
67    /// concurrent requests could read the same metadata and assign one column id to
68    /// different columns. Use
69    /// [MetricEngineInner::add_physical_columns](crate::engine::MetricEngineInner::add_physical_columns).
70    pub async fn add_columns(
71        &self,
72        physical_region_id: RegionId,
73        columns: Vec<ColumnMetadata>,
74        index_options: IndexOptions,
75    ) -> Result<()> {
76        // Return early if no new columns are added.
77        if columns.is_empty() {
78            return Ok(());
79        }
80
81        let Some((new_column_count, request)) = self
82            .assemble_alter_request(physical_region_id, columns, index_options)
83            .await?
84        else {
85            // Every requested column already exists.
86            return Ok(());
87        };
88
89        let _timer = MITO_DDL_DURATION.start_timer();
90
91        let _ = self
92            .mito
93            .handle_request(utils::to_data_region_id(physical_region_id), request)
94            .await
95            .context(MitoWriteOperationSnafu)?;
96
97        PHYSICAL_COLUMN_COUNT.add(new_column_count as _);
98
99        Ok(())
100    }
101
102    /// Generate wrapped [RegionAlterRequest] with given [ColumnMetadata].
103    ///
104    /// Columns that the physical region already has are not added again: their
105    /// definitions are validated and their persisted column ids are reused.
106    /// Returns `None` if every given column already exists.
107    async fn assemble_alter_request(
108        &self,
109        physical_region_id: RegionId,
110        columns: Vec<ColumnMetadata>,
111        index_options: IndexOptions,
112    ) -> Result<Option<(usize, RegionRequest)>> {
113        let region_metadata = self.physical_metadata(physical_region_id).await?;
114        let region_id = region_metadata.region_id;
115
116        // The caller derives the columns to add from a cached schema that a cancelled or
117        // concurrent alter may have left behind, so the names are checked against the
118        // real metadata instead of being trusted.
119        let mut seen: HashMap<String, usize> = HashMap::with_capacity(columns.len());
120        let mut columns_to_add = Vec::with_capacity(columns.len());
121        for column in columns {
122            let name = column.column_schema.name.clone();
123            if let Some(existing) = region_metadata.column_by_name(&name) {
124                validate_shared_column(region_id, existing, &column)?;
125                continue;
126            }
127            // The batch itself may repeat a column that is not installed yet: the duplicate
128            // must agree with the first occurrence, and only one of them is added.
129            if let Some(&index) = seen.get(&name) {
130                validate_shared_column(region_id, &columns_to_add[index], &column)?;
131                continue;
132            }
133            seen.insert(name, columns_to_add.len());
134            columns_to_add.push(column);
135        }
136
137        if columns_to_add.is_empty() {
138            debug!("No new columns to add to physical region {region_id:?}");
139            return Ok(None);
140        }
141        let new_column_count = columns_to_add.len();
142
143        // find the max column id
144        let new_column_id_start = 1 + region_metadata
145            .column_metadatas
146            .iter()
147            .filter_map(|c| {
148                if ReservedColumnId::is_reserved(c.column_id) {
149                    None
150                } else {
151                    Some(c.column_id)
152                }
153            })
154            .max()
155            .unwrap_or(0);
156
157        // overwrite semantic type
158        let new_columns = columns_to_add
159            .into_iter()
160            .enumerate()
161            .map(|(delta, mut c)| {
162                match c.semantic_type {
163                    SemanticType::Tag => {
164                        if !c.column_schema.data_type.is_string() {
165                            return ColumnTypeMismatchSnafu {
166                                expect: ConcreteDataType::string_datatype(),
167                                actual: c.column_schema.data_type.clone(),
168                            }
169                            .fail();
170                        }
171                    }
172                    // Field columns can only be added to the shared physical
173                    // table for native histograms; ordinary metric fields are
174                    // created with the logical table.
175                    SemanticType::Field
176                        if is_native_histogram_value_type(&c.column_schema.data_type) => {}
177                    _ => {
178                        return AddingFieldColumnSnafu {
179                            name: &c.column_schema.name,
180                        }
181                        .fail();
182                    }
183                }
184
185                c.column_id = new_column_id_start + delta as u32;
186                c.column_schema.set_nullable();
187                if c.semantic_type == SemanticType::Tag {
188                    match index_options {
189                        IndexOptions::None => {}
190                        IndexOptions::Inverted => {
191                            c.column_schema.set_inverted_index(true);
192                        }
193                        IndexOptions::Skipping {
194                            granularity,
195                            false_positive_rate,
196                        } => {
197                            c.column_schema
198                                .set_skipping_options(
199                                    &SkippingIndexOptions::new(
200                                        granularity,
201                                        false_positive_rate,
202                                        SkippingIndexType::BloomFilter,
203                                    )
204                                    .context(SetSkippingIndexOptionSnafu)?,
205                                )
206                                .context(SetSkippingIndexOptionSnafu)?;
207                        }
208                    }
209                }
210
211                Ok(AddColumn {
212                    column_metadata: c.clone(),
213                    location: None,
214                })
215            })
216            .collect::<Result<_>>()?;
217
218        debug!("Adding (Column id assigned) columns {new_columns:?} to region {region_id:?}");
219        // assemble alter request
220        let alter_request = RegionRequest::Alter(RegionAlterRequest {
221            kind: AlterKind::AddColumns {
222                columns: new_columns,
223            },
224        });
225
226        Ok(Some((new_column_count, alter_request)))
227    }
228
229    pub async fn write_data(
230        &self,
231        region_id: RegionId,
232        request: RegionRequest,
233    ) -> Result<AffectedRows> {
234        let region_id = utils::to_data_region_id(region_id);
235        self.mito
236            .handle_request(region_id, request)
237            .await
238            .context(MitoWriteOperationSnafu)
239            .map(|result| result.affected_rows)
240    }
241
242    /// Returns the current physical schema, including columns installed by an ALTER.
243    pub async fn physical_metadata(
244        &self,
245        physical_region_id: RegionId,
246    ) -> Result<RegionMetadataRef> {
247        self.mito
248            .get_metadata(utils::to_data_region_id(physical_region_id))
249            .await
250            .context(MitoReadOperationSnafu)
251    }
252
253    pub async fn alter_region_options(
254        &self,
255        region_id: RegionId,
256        request: RegionAlterRequest,
257    ) -> Result<AffectedRows> {
258        match request.kind {
259            AlterKind::SetRegionOptions { options: _ }
260            | AlterKind::UnsetRegionOptions { keys: _ }
261            | AlterKind::SetIndexes { options: _ }
262            | AlterKind::UnsetIndexes { options: _ }
263            | AlterKind::SetJsonSettings { .. }
264            | AlterKind::SyncColumns {
265                column_metadatas: _,
266            } => {
267                let region_id = utils::to_data_region_id(region_id);
268                self.mito
269                    .handle_request(region_id, RegionRequest::Alter(request))
270                    .await
271                    .context(MitoWriteOperationSnafu)
272                    .map(|result| result.affected_rows)
273            }
274            _ => {
275                info!(
276                    "Metric region received alter request {request:?} on physical region {region_id:?}"
277                );
278                FORBIDDEN_OPERATION_COUNT.inc();
279
280                ForbiddenPhysicalAlterSnafu.fail()
281            }
282        }
283    }
284}
285
286#[cfg(test)]
287mod test {
288    use common_query::prelude::{greptime_timestamp, greptime_value};
289    use datatypes::prelude::ConcreteDataType;
290    use datatypes::schema::ColumnSchema;
291
292    use super::*;
293    use crate::test_util::TestEnv;
294
295    fn tag_column(name: &str) -> ColumnMetadata {
296        ColumnMetadata {
297            column_id: 0,
298            semantic_type: SemanticType::Tag,
299            column_schema: ColumnSchema::new(name, ConcreteDataType::string_datatype(), false),
300        }
301    }
302
303    #[tokio::test]
304    async fn test_add_columns() {
305        let env = TestEnv::new().await;
306        env.init_metric_region().await;
307
308        let current_version = env
309            .mito()
310            .get_metadata(utils::to_data_region_id(env.default_physical_region_id()))
311            .await
312            .unwrap()
313            .schema_version;
314        // TestEnv will create a logical region which changes the version to 1.
315        assert_eq!(current_version, 1);
316
317        let new_columns = vec![
318            ColumnMetadata {
319                column_id: 0,
320                semantic_type: SemanticType::Tag,
321                column_schema: ColumnSchema::new(
322                    "tag2",
323                    ConcreteDataType::string_datatype(),
324                    false,
325                ),
326            },
327            ColumnMetadata {
328                column_id: 0,
329                semantic_type: SemanticType::Tag,
330                column_schema: ColumnSchema::new(
331                    "tag3",
332                    ConcreteDataType::string_datatype(),
333                    false,
334                ),
335            },
336        ];
337        env.data_region()
338            .add_columns(
339                env.default_physical_region_id(),
340                new_columns,
341                IndexOptions::Inverted,
342            )
343            .await
344            .unwrap();
345
346        let new_metadata = env
347            .mito()
348            .get_metadata(utils::to_data_region_id(env.default_physical_region_id()))
349            .await
350            .unwrap();
351        let column_names = new_metadata
352            .column_metadatas
353            .iter()
354            .map(|c| &c.column_schema.name)
355            .collect::<Vec<_>>();
356        let expected = vec![
357            greptime_timestamp(),
358            greptime_value(),
359            "__table_id",
360            "__tsid",
361            "job",
362            "tag2",
363            "tag3",
364        ];
365        assert_eq!(column_names, expected);
366    }
367
368    // Only string is allowed for tag column
369    #[tokio::test]
370    async fn test_add_invalid_column() {
371        let env = TestEnv::new().await;
372        env.init_metric_region().await;
373
374        let new_columns = vec![ColumnMetadata {
375            column_id: 0,
376            semantic_type: SemanticType::Tag,
377            column_schema: ColumnSchema::new("tag2", ConcreteDataType::int64_datatype(), false),
378        }];
379        let result = env
380            .data_region()
381            .add_columns(
382                env.default_physical_region_id(),
383                new_columns,
384                IndexOptions::Inverted,
385            )
386            .await;
387        assert!(result.is_err());
388    }
389
390    // A duplicate column inside one batch must agree with the first occurrence instead of
391    // being dropped silently.
392    #[tokio::test]
393    async fn test_add_columns_rejects_conflicting_duplicates() {
394        let env = TestEnv::new().await;
395        env.init_metric_region().await;
396        let physical_region_id = env.default_physical_region_id();
397        let data_region_id = utils::to_data_region_id(physical_region_id);
398
399        let conflicting = ColumnMetadata {
400            column_id: 0,
401            semantic_type: SemanticType::Field,
402            column_schema: ColumnSchema::new("dup", ConcreteDataType::float64_datatype(), false),
403        };
404        let result = env
405            .data_region()
406            .add_columns(
407                physical_region_id,
408                vec![tag_column("dup"), conflicting],
409                IndexOptions::Inverted,
410            )
411            .await;
412
413        assert!(result.is_err());
414        assert!(
415            env.mito()
416                .get_metadata(data_region_id)
417                .await
418                .unwrap()
419                .column_by_name("dup")
420                .is_none()
421        );
422    }
423
424    // A retry passes the column it added before, because the caller derives the columns to
425    // add from a cache that a cancelled request may not have refreshed. The column keeps the
426    // id it was installed with.
427    #[tokio::test]
428    async fn test_add_columns_reuses_the_existing_column_id() {
429        let env = TestEnv::new().await;
430        env.init_metric_region().await;
431        let physical_region_id = env.default_physical_region_id();
432        let data_region_id = utils::to_data_region_id(physical_region_id);
433
434        env.data_region()
435            .add_columns(
436                physical_region_id,
437                vec![tag_column("tag2")],
438                IndexOptions::Inverted,
439            )
440            .await
441            .unwrap();
442        let tag2_id = env
443            .mito()
444            .get_metadata(data_region_id)
445            .await
446            .unwrap()
447            .column_by_name("tag2")
448            .unwrap()
449            .column_id;
450
451        env.data_region()
452            .add_columns(
453                physical_region_id,
454                vec![tag_column("tag2"), tag_column("tag3")],
455                IndexOptions::Inverted,
456            )
457            .await
458            .unwrap();
459
460        let metadata = env.mito().get_metadata(data_region_id).await.unwrap();
461        assert_eq!(metadata.column_by_name("tag2").unwrap().column_id, tag2_id);
462        assert_eq!(
463            metadata.column_by_name("tag3").unwrap().column_id,
464            tag2_id + 1
465        );
466    }
467
468    // Adding only columns that already exist must not submit an ALTER at all.
469    #[tokio::test]
470    async fn test_add_columns_skips_the_alter_when_all_columns_exist() {
471        let env = TestEnv::new().await;
472        env.init_metric_region().await;
473        let physical_region_id = env.default_physical_region_id();
474        let data_region_id = utils::to_data_region_id(physical_region_id);
475
476        env.data_region()
477            .add_columns(
478                physical_region_id,
479                vec![tag_column("tag2")],
480                IndexOptions::Inverted,
481            )
482            .await
483            .unwrap();
484        let metadata = env.mito().get_metadata(data_region_id).await.unwrap();
485        let version = metadata.schema_version;
486
487        env.data_region()
488            .add_columns(
489                physical_region_id,
490                vec![tag_column("tag2")],
491                IndexOptions::Inverted,
492            )
493            .await
494            .unwrap();
495
496        let metadata = env.mito().get_metadata(data_region_id).await.unwrap();
497        assert_eq!(metadata.schema_version, version);
498        assert_eq!(
499            metadata
500                .column_metadatas
501                .iter()
502                .filter(|column| column.column_schema.name == "tag2")
503                .count(),
504            1
505        );
506    }
507}