Skip to main content

mito2/series_index/
format.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Reader and writer interfaces for native series and samples files.
16
17use std::collections::{BTreeSet, HashSet};
18use std::sync::Arc;
19
20use api::v1::SemanticType;
21use async_trait::async_trait;
22use common_recordbatch::filter::SimpleFilterEvaluator;
23use datatypes::arrow::datatypes::{Field, SchemaRef};
24use datatypes::arrow::record_batch::RecordBatch;
25use futures::stream::BoxStream;
26use store_api::metadata::RegionMetadata;
27use store_api::storage::consts::ReservedColumnId;
28
29use crate::error::{InvalidRecordBatchSnafu, Result};
30use crate::series_index::MetricSeriesId;
31use crate::series_index::artifact::ArtifactMetadata;
32use crate::series_index::identity::ExactSeriesKey;
33use crate::sst::PARQUET_FIELD_ID_KEY;
34
35/// Writers own partial outputs until finish succeeds; abort removes every partial object.
36/// A failed finish must clean up its output before returning; implementations also own
37/// cleanup on cancellation while a writer is live.
38#[async_trait]
39pub(crate) trait FormatWriter: Send {
40    async fn write(&mut self, batch: &RecordBatch) -> Result<()>;
41    async fn finish(self: Box<Self>) -> Result<ArtifactMetadata>;
42    async fn abort(self: Box<Self>) -> Result<()>;
43}
44
45/// A read has independent traversal state and pins its immutable artifact.
46#[derive(Debug, Clone, Default)]
47pub(crate) struct SeriesReadRequest {
48    pub(crate) projection: Vec<String>,
49    pub(crate) table_id: Option<u32>,
50    pub(crate) ids: Option<BTreeSet<MetricSeriesId>>,
51    /// Predicates the reader applies to select rows, including when mask caching is disabled.
52    pub(crate) filters: Vec<SimpleFilterEvaluator>,
53    /// Original expressions in filter order, used for structural mask-cache identity.
54    pub(crate) filter_exprs: std::sync::Arc<[datafusion::logical_expr::Expr]>,
55}
56
57pub(crate) trait FormatReader: Send + Sync {
58    fn schema(&self) -> SchemaRef;
59    fn read(&self, request: SeriesReadRequest) -> Result<BoxStream<'static, Result<RecordBatch>>>;
60}
61
62/// Selection in the stored timestamp unit. No visibility filtering is implicit.
63#[derive(Debug, Clone, Default)]
64pub(crate) struct SamplesReadRequest {
65    /// Native scans account transient read buffers against their query pool.
66    pub(crate) memory_pool: Option<Arc<dyn datafusion::execution::memory_pool::MemoryPool>>,
67    pub(crate) projection: Vec<String>,
68    pub(crate) table_id: Option<u32>,
69    /// Exact selection. A block whose key is absent here is never read, even when its
70    /// coarse `(table_id, tsid)` is present. The reader derives its coarse pruning set
71    /// from these keys, so the selection cannot disagree with itself.
72    pub(crate) keys: Option<BTreeSet<ExactSeriesKey>>,
73    pub(crate) start: Option<i64>,
74    pub(crate) end: Option<i64>,
75}
76
77/// One samples output batch and the exact series that owns every row in it.
78///
79/// A sample block belongs to exactly one series, so the exact key travels with the batch
80/// instead of being repeated once per row: consumers attribute the whole batch at once.
81#[derive(Debug, Clone, PartialEq)]
82pub(crate) struct SamplesBatch {
83    pub(crate) batch: RecordBatch,
84    pub(crate) key: ExactSeriesKey,
85}
86
87/// Batches read as batches: the key is the only column the wrapped batch does not carry.
88impl std::ops::Deref for SamplesBatch {
89    type Target = RecordBatch;
90
91    fn deref(&self) -> &RecordBatch {
92        &self.batch
93    }
94}
95
96pub(crate) trait SamplesFormatReader: Send + Sync {
97    fn schema(&self) -> SchemaRef;
98    fn read(&self, request: SamplesReadRequest)
99    -> Result<BoxStream<'static, Result<SamplesBatch>>>;
100}
101
102/// Reads a column ID from an artifact schema field.
103pub(crate) fn field_id(field: &Field) -> Result<u32> {
104    field
105        .metadata()
106        .get(PARQUET_FIELD_ID_KEY)
107        .and_then(|id| id.parse().ok())
108        .ok_or_else(|| invalid(format!("missing column ID for {}", field.name())))
109}
110
111/// Checks whether a series index contains exactly the current non-reserved tags.
112pub(crate) fn validate_series_schema(schema: &SchemaRef, metadata: &RegionMetadata) -> Result<()> {
113    let mut ids = HashSet::new();
114    for field in schema.fields().iter().skip(3) {
115        let id = field_id(field)?;
116        let column = metadata
117            .column_by_id(id)
118            .ok_or_else(|| invalid("series tag absent from scan schema"))?;
119        if column.semantic_type != SemanticType::Tag || column.column_schema.name != *field.name() {
120            return Err(invalid("series tag schema changed; rebuild series indexes"));
121        }
122        ids.insert(id);
123    }
124    if metadata
125        .primary_key_columns()
126        .any(|c| !ReservedColumnId::is_reserved(c.column_id) && !ids.contains(&c.column_id))
127    {
128        return Err(invalid(
129            "series index is missing scan tags; rebuild series indexes",
130        ));
131    }
132    Ok(())
133}
134
135fn invalid(reason: impl Into<String>) -> crate::error::Error {
136    InvalidRecordBatchSnafu {
137        reason: reason.into(),
138    }
139    .build()
140}
141
142#[cfg(test)]
143mod tests {
144    use datatypes::arrow::datatypes::{DataType, Schema};
145    use datatypes::prelude::DataType as _;
146    use store_api::codec::PrimaryKeyEncoding;
147
148    use super::*;
149    use crate::test_util::sst_util::sst_region_metadata_with_encoding;
150
151    #[test]
152    fn series_schema_requires_current_tags() {
153        let metadata = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse);
154        let mut fields = vec![
155            Field::new("__table_id", DataType::UInt32, false),
156            Field::new("__tsid", DataType::UInt64, false),
157            Field::new("__row_count", DataType::UInt64, false),
158        ];
159        fields.extend(
160            metadata
161                .column_metadatas
162                .iter()
163                .filter(|c| {
164                    c.semantic_type == SemanticType::Tag
165                        && !ReservedColumnId::is_reserved(c.column_id)
166                })
167                .map(|c| {
168                    crate::sst::with_field_id(
169                        Field::new(
170                            &c.column_schema.name,
171                            c.column_schema.data_type.as_arrow_type(),
172                            true,
173                        ),
174                        c.column_id,
175                    )
176                }),
177        );
178        let validate =
179            |fields: Vec<Field>| validate_series_schema(&Arc::new(Schema::new(fields)), &metadata);
180        validate(fields.clone()).unwrap();
181        let index = 3;
182        let mut missing = fields.clone();
183        missing.remove(index);
184        assert!(validate(missing).is_err());
185        let mut renamed = fields.clone();
186        renamed[index] = renamed[index].clone().with_name("renamed");
187        assert!(validate(renamed).is_err());
188        let mut replaced = fields.clone();
189        replaced[index] = crate::sst::with_field_id(replaced[index].clone(), 100);
190        assert!(validate(replaced).is_err());
191        let mut reordered = fields.clone();
192        reordered[index..].reverse();
193        validate(reordered).unwrap();
194    }
195}