Skip to main content

mito2/sst/index/inverted_index/
applier.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
15pub mod builder;
16
17use std::collections::BTreeMap;
18use std::sync::Arc;
19use std::time::Instant;
20
21use arrow_schema::extension::ExtensionType;
22use common_base::range_read::RangeReader;
23use common_telemetry::warn;
24use datatypes::data_type::ConcreteDataType;
25use datatypes::extension::json::Json2ExtensionType;
26use index::inverted_index::format::reader::{InvertedIndexBlobReader, InvertedIndexReadMetrics};
27use index::inverted_index::search::index_apply::{
28    ApplyOutput, IndexApplier, IndexNotFoundStrategy, PredicatesIndexApplier, SearchContext,
29};
30use index::inverted_index::search::predicate::Predicate;
31use index::target::IndexTarget;
32use object_store::ObjectStore;
33use puffin::puffin_manager::cache::PuffinMetadataCacheRef;
34use puffin::puffin_manager::file_key::PuffinFileKey;
35use puffin::puffin_manager::{PuffinManager, PuffinReader};
36use snafu::ResultExt;
37use store_api::metadata::{RegionMetadata, RegionMetadataRef};
38use store_api::region_request::PathType;
39
40use crate::access_layer::{RegionFilePathFactory, WriteCachePathProvider};
41use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey};
42use crate::cache::index::inverted_index::{CachedInvertedIndexBlobReader, InvertedIndexCacheRef};
43use crate::cache::index::result_cache::PredicateKey;
44use crate::error::{
45    ApplyInvertedIndexSnafu, BuildIndexApplierSnafu, MetadataSnafu, PuffinBuildReaderSnafu,
46    PuffinReadBlobSnafu, Result,
47};
48use crate::metrics::{INDEX_APPLY_ELAPSED, INDEX_APPLY_MEMORY_USAGE};
49use crate::sst::file::RegionIndexId;
50use crate::sst::index::inverted_index::INDEX_BLOB_TYPE;
51use crate::sst::index::puffin_manager::{BlobReader, PuffinManagerFactory, SstPuffinManager};
52use crate::sst::index::{TYPE_INVERTED_INDEX, trigger_index_background_download};
53
54/// Metrics for tracking inverted index apply operations.
55#[derive(Default, Clone)]
56pub struct InvertedIndexApplyMetrics {
57    /// Total time spent applying the index.
58    pub apply_elapsed: std::time::Duration,
59    /// Number of blob cache misses (0 or 1).
60    pub blob_cache_miss: usize,
61    /// Total size of blobs read (in bytes).
62    pub blob_read_bytes: u64,
63    /// Metrics for inverted index reads.
64    pub inverted_index_read_metrics: InvertedIndexReadMetrics,
65}
66
67impl std::fmt::Debug for InvertedIndexApplyMetrics {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        let Self {
70            apply_elapsed,
71            blob_cache_miss,
72            blob_read_bytes,
73            inverted_index_read_metrics,
74        } = self;
75
76        if self.is_empty() {
77            return write!(f, "{{}}");
78        }
79        write!(f, "{{")?;
80
81        write!(f, "\"apply_elapsed\":\"{:?}\"", apply_elapsed)?;
82
83        if *blob_cache_miss > 0 {
84            write!(f, ", \"blob_cache_miss\":{}", blob_cache_miss)?;
85        }
86        if *blob_read_bytes > 0 {
87            write!(f, ", \"blob_read_bytes\":{}", blob_read_bytes)?;
88        }
89        write!(
90            f,
91            ", \"inverted_index_read_metrics\":{:?}",
92            inverted_index_read_metrics
93        )?;
94
95        write!(f, "}}")
96    }
97}
98
99impl InvertedIndexApplyMetrics {
100    /// Returns true if the metrics are empty (contain no meaningful data).
101    pub fn is_empty(&self) -> bool {
102        self.apply_elapsed.is_zero()
103    }
104
105    /// Merges another metrics into this one.
106    pub fn merge_from(&mut self, other: &Self) {
107        self.apply_elapsed += other.apply_elapsed;
108        self.blob_cache_miss += other.blob_cache_miss;
109        self.blob_read_bytes += other.blob_read_bytes;
110        self.inverted_index_read_metrics
111            .merge_from(&other.inverted_index_read_metrics);
112    }
113}
114
115/// `InvertedIndexApplier` is responsible for applying predicates to the provided SST files
116/// and returning the relevant row group ids for further scan.
117pub(crate) struct InvertedIndexApplier {
118    /// The root directory of the table.
119    table_dir: String,
120
121    /// Path type for generating file paths.
122    path_type: PathType,
123
124    /// Store responsible for accessing remote index files.
125    store: ObjectStore,
126
127    /// The cache of index files.
128    file_cache: Option<FileCacheRef>,
129
130    /// The puffin manager factory.
131    puffin_manager_factory: PuffinManagerFactory,
132
133    /// Managers keep backend identity resolution out of per-blob reads.
134    remote_puffin_manager: SstPuffinManager,
135    cached_puffin_manager: Option<SstPuffinManager>,
136
137    /// In-memory cache for inverted index.
138    inverted_index_cache: Option<InvertedIndexCacheRef>,
139
140    /// Puffin metadata cache.
141    puffin_metadata_cache: Option<PuffinMetadataCacheRef>,
142
143    /// All collected predicates.
144    predicates: BTreeMap<IndexTarget, Vec<Predicate>>,
145
146    /// Default apply plan built from all collected predicates.
147    default_plan: SstApplyPlan,
148
149    /// Expected predicate target types from the latest region metadata.
150    expected_predicate_target_types: BTreeMap<IndexTarget, ConcreteDataType>,
151}
152
153pub(crate) type InvertedIndexApplierRef = Arc<InvertedIndexApplier>;
154
155#[derive(Clone)]
156pub(crate) struct SstApplyPlan {
157    pub predicate_key: PredicateKey,
158    pub index_applier: Arc<PredicatesIndexApplier>,
159}
160
161impl InvertedIndexApplier {
162    /// Creates a new `InvertedIndexApplier`.
163    pub fn new(
164        table_dir: String,
165        path_type: PathType,
166        store: ObjectStore,
167        puffin_manager_factory: PuffinManagerFactory,
168        predicates: BTreeMap<IndexTarget, Vec<Predicate>>,
169        expected_predicate_target_types: BTreeMap<IndexTarget, ConcreteDataType>,
170    ) -> Result<Self> {
171        let remote_puffin_manager = puffin_manager_factory.build(
172            store.clone(),
173            RegionFilePathFactory::new(table_dir.clone(), path_type),
174        );
175        let default_plan = Self::build_apply_plan(&predicates)?;
176        INDEX_APPLY_MEMORY_USAGE.add(default_plan.index_applier.memory_usage() as i64);
177
178        Ok(Self {
179            table_dir,
180            path_type,
181            store,
182            file_cache: None,
183            puffin_manager_factory,
184            remote_puffin_manager,
185            cached_puffin_manager: None,
186            inverted_index_cache: None,
187            puffin_metadata_cache: None,
188            predicates,
189            default_plan,
190            expected_predicate_target_types,
191        })
192    }
193
194    /// Sets the file cache.
195    pub fn with_file_cache(mut self, file_cache: Option<FileCacheRef>) -> Self {
196        self.cached_puffin_manager = file_cache.as_ref().map(|cache| {
197            self.puffin_manager_factory.build_cached(
198                &self.remote_puffin_manager,
199                cache.local_store(),
200                WriteCachePathProvider::new(cache.clone()),
201            )
202        });
203        self.file_cache = file_cache;
204        self
205    }
206
207    /// Sets the index cache.
208    pub fn with_index_cache(mut self, index_cache: Option<InvertedIndexCacheRef>) -> Self {
209        self.inverted_index_cache = index_cache;
210        self
211    }
212
213    /// Sets the puffin metadata cache.
214    pub fn with_puffin_metadata_cache(
215        mut self,
216        puffin_metadata_cache: Option<PuffinMetadataCacheRef>,
217    ) -> Self {
218        self.puffin_metadata_cache = puffin_metadata_cache;
219        self
220    }
221
222    /// Applies predicates to one SST file with the provided index applier.
223    ///
224    /// # Arguments
225    /// * `file_id` - The region file ID to apply predicates to
226    /// * `file_size_hint` - Optional hint for file size to avoid extra metadata reads
227    /// * `index_applier` - Inverted index applier produced by `plan_for_sst`.
228    /// * `metrics` - Optional mutable reference to collect metrics on demand
229    #[tracing::instrument(
230        skip_all,
231        fields(file_id = %file_id)
232    )]
233    pub async fn apply(
234        &self,
235        file_id: RegionIndexId,
236        file_size_hint: Option<u64>,
237        index_applier: &PredicatesIndexApplier,
238        mut metrics: Option<&mut InvertedIndexApplyMetrics>,
239    ) -> Result<ApplyOutput> {
240        let start = Instant::now();
241
242        let context = SearchContext {
243            // Older SSTs may lack an index enabled by ALTER, or a column with a default value.
244            // Missing indexes cannot rule out matching rows.
245            index_not_found_strategy: IndexNotFoundStrategy::Ignore,
246        };
247
248        let mut cache_miss = 0;
249        let (file_key, blob) = match self.cached_blob_reader(file_id, file_size_hint).await {
250            Ok(Some(puffin_reader)) => puffin_reader,
251            other => {
252                cache_miss += 1;
253                if let Err(err) = other {
254                    warn!(err; "An unexpected error occurred while reading the cached index file. Fallback to remote index file.")
255                }
256                self.remote_blob_reader(file_id, file_size_hint).await?
257            }
258        };
259
260        let blob_size = blob.metadata().await.context(MetadataSnafu)?.content_length;
261
262        let result = if let Some(index_cache) = &self.inverted_index_cache {
263            let mut index_reader = CachedInvertedIndexBlobReader::new(
264                file_key,
265                blob_size,
266                InvertedIndexBlobReader::new(blob),
267                index_cache.clone(),
268            );
269            index_applier
270                .apply(
271                    context,
272                    &mut index_reader,
273                    metrics
274                        .as_deref_mut()
275                        .map(|m| &mut m.inverted_index_read_metrics),
276                )
277                .await
278                .context(ApplyInvertedIndexSnafu)
279        } else {
280            let mut index_reader = InvertedIndexBlobReader::new(blob);
281            index_applier
282                .apply(
283                    context,
284                    &mut index_reader,
285                    metrics
286                        .as_deref_mut()
287                        .map(|m| &mut m.inverted_index_read_metrics),
288                )
289                .await
290                .context(ApplyInvertedIndexSnafu)
291        };
292
293        // Record elapsed time to histogram and collect metrics if requested
294        let elapsed = start.elapsed();
295        INDEX_APPLY_ELAPSED
296            .with_label_values(&[TYPE_INVERTED_INDEX])
297            .observe(elapsed.as_secs_f64());
298
299        if let Some(metrics) = metrics {
300            metrics.apply_elapsed = elapsed;
301            metrics.blob_cache_miss = cache_miss;
302            metrics.blob_read_bytes = blob_size;
303        }
304
305        result
306    }
307
308    /// Creates a blob reader from the cached index file.
309    async fn cached_blob_reader(
310        &self,
311        file_id: RegionIndexId,
312        file_size_hint: Option<u64>,
313    ) -> Result<Option<(PuffinFileKey<RegionIndexId>, BlobReader)>> {
314        let (Some(file_cache), Some(puffin_manager)) =
315            (&self.file_cache, &self.cached_puffin_manager)
316        else {
317            return Ok(None);
318        };
319
320        let index_key = IndexKey::new(
321            file_id.region_id(),
322            file_id.file_id(),
323            FileType::Puffin(file_id.version),
324        );
325        if file_cache.get(index_key).await.is_none() {
326            return Ok(None);
327        };
328
329        // Adds file size hint to the puffin reader to avoid extra metadata read.
330        let reader = puffin_manager
331            .reader(&file_id)
332            .await
333            .context(PuffinBuildReaderSnafu)?
334            .with_file_size_hint(file_size_hint)
335            .blob(INDEX_BLOB_TYPE)
336            .await
337            .context(PuffinReadBlobSnafu)?
338            .reader()
339            .await
340            .context(PuffinBuildReaderSnafu)?;
341        Ok(Some((puffin_manager.file_key(&file_id), reader)))
342    }
343
344    /// Creates a blob reader from the remote index file.
345    async fn remote_blob_reader(
346        &self,
347        file_id: RegionIndexId,
348        file_size_hint: Option<u64>,
349    ) -> Result<(PuffinFileKey<RegionIndexId>, BlobReader)> {
350        let path_factory = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
351
352        // Trigger background download if file cache and file size are available
353        trigger_index_background_download(
354            self.file_cache.as_ref(),
355            &file_id,
356            file_size_hint,
357            &path_factory,
358            &self.store,
359        );
360
361        let puffin_manager = self
362            .remote_puffin_manager
363            .clone()
364            .with_puffin_metadata_cache(self.puffin_metadata_cache.clone());
365
366        let reader = puffin_manager
367            .reader(&file_id)
368            .await
369            .context(PuffinBuildReaderSnafu)?
370            .with_file_size_hint(file_size_hint)
371            .blob(INDEX_BLOB_TYPE)
372            .await
373            .context(PuffinReadBlobSnafu)?
374            .reader()
375            .await
376            .context(PuffinBuildReaderSnafu)?;
377        Ok((puffin_manager.file_key(&file_id), reader))
378    }
379
380    /// Builds a per-SST apply plan.
381    ///
382    /// Returns `None` when no compatible predicate remains for this SST.
383    pub fn plan_for_sst(&self, sst_metadata: &RegionMetadataRef) -> Result<Option<SstApplyPlan>> {
384        let mut compatible_predicates = BTreeMap::new();
385        let mut has_type_mismatch = false;
386
387        for (target, predicates) in &self.predicates {
388            let Some(expected) = self.expected_predicate_target_types.get(target) else {
389                has_type_mismatch = true;
390                continue;
391            };
392            let actual = index_target_data_type(sst_metadata, target);
393            // JSON paths require a matching type hint in this SST. Ordinary missing
394            // columns retain the missing-index fallback for added columns with defaults.
395            let compatible = match target {
396                IndexTarget::ColumnId(_) => actual.as_ref().is_none_or(|ty| ty == expected),
397                IndexTarget::JsonPath(_) => actual.as_ref() == Some(expected),
398            };
399            if !compatible {
400                has_type_mismatch = true;
401                continue;
402            }
403
404            compatible_predicates.insert(target.clone(), predicates.clone());
405        }
406
407        if compatible_predicates.is_empty() {
408            return Ok(None);
409        }
410
411        if !has_type_mismatch {
412            return Ok(Some(self.default_plan.clone()));
413        }
414
415        let plan = Self::build_apply_plan(&compatible_predicates)?;
416        Ok(Some(plan))
417    }
418
419    fn build_apply_plan(
420        predicates_by_target: &BTreeMap<IndexTarget, Vec<Predicate>>,
421    ) -> Result<SstApplyPlan> {
422        let mut predicates = Vec::with_capacity(predicates_by_target.len());
423        for (target, preds) in predicates_by_target {
424            let name = target.encode();
425            predicates.push((name, preds.clone()));
426        }
427        let index_applier =
428            PredicatesIndexApplier::try_from(predicates).context(BuildIndexApplierSnafu)?;
429
430        let predicate_key = PredicateKey::new_inverted(Arc::new(predicates_by_target.clone()));
431        Ok(SstApplyPlan {
432            predicate_key,
433            index_applier: Arc::new(index_applier),
434        })
435    }
436}
437
438impl Drop for InvertedIndexApplier {
439    fn drop(&mut self) {
440        INDEX_APPLY_MEMORY_USAGE.sub(self.default_plan.index_applier.memory_usage() as i64);
441    }
442}
443
444/// Resolves the value type used to encode an index predicate.
445/// JSON paths must have an enabled inverted-index type hint.
446fn index_target_data_type(
447    metadata: &RegionMetadata,
448    target: &IndexTarget,
449) -> Option<ConcreteDataType> {
450    let target = match target {
451        IndexTarget::ColumnId(id) => {
452            return metadata
453                .column_by_id(*id)
454                .map(|col| col.column_schema.data_type.clone());
455        }
456        IndexTarget::JsonPath(target) => target,
457    };
458    let col = metadata.column_by_id(target.column_id())?;
459    let extension = col
460        .column_schema
461        .extension_type::<Json2ExtensionType>()
462        .ok()??;
463    extension
464        .metadata()
465        .json_settings()
466        .type_hints()
467        .iter()
468        .find(|hint| hint.path == target.path() && hint.inverted_index)
469        .map(|hint| hint.data_type.clone())
470}
471
472#[cfg(test)]
473mod tests {
474    use api::v1::SemanticType;
475    use datatypes::data_type::ConcreteDataType;
476    use datatypes::schema::ColumnSchema;
477    use futures::io::Cursor;
478    use index::inverted_index::search::predicate::RegexMatchPredicate;
479    use object_store::services::Memory;
480    use puffin::puffin_manager::PuffinWriter;
481    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
482    use store_api::storage::{FileId, RegionId};
483
484    use super::*;
485    use crate::sst::index::RegionFileId;
486
487    #[tokio::test]
488    async fn test_plan_for_sst() {
489        let (_d, puffin_manager_factory) =
490            PuffinManagerFactory::new_for_test_async("test_plan_for_sst_basic_").await;
491        let object_store = ObjectStore::new(Memory::default()).unwrap();
492        let table_dir = "table_dir".to_string();
493
494        let mut predicates = BTreeMap::new();
495        predicates.insert(
496            IndexTarget::ColumnId(1),
497            vec![Predicate::RegexMatch(RegexMatchPredicate {
498                pattern: "foo".to_string(),
499            })],
500        );
501        let expected_predicate_target_types = BTreeMap::from_iter([(
502            IndexTarget::ColumnId(1),
503            ConcreteDataType::string_datatype(),
504        )]);
505
506        let sst_index_applier = InvertedIndexApplier::new(
507            table_dir,
508            PathType::Bare,
509            object_store,
510            puffin_manager_factory,
511            predicates,
512            expected_predicate_target_types,
513        )
514        .unwrap();
515        let plan = sst_index_applier
516            .plan_for_sst(&mock_region_metadata())
517            .unwrap();
518        assert!(plan.is_some());
519    }
520
521    #[tokio::test]
522    async fn test_plan_for_sst_type_mismatch() {
523        let (_d, puffin_manager_factory) =
524            PuffinManagerFactory::new_for_test_async("test_plan_for_sst_type_mismatch_").await;
525        let object_store = ObjectStore::new(Memory::default()).unwrap();
526        let table_dir = "table_dir".to_string();
527
528        let mut predicates = BTreeMap::new();
529        predicates.insert(
530            IndexTarget::ColumnId(1),
531            vec![Predicate::RegexMatch(RegexMatchPredicate {
532                pattern: "foo".to_string(),
533            })],
534        );
535        // Column id 1 is String in `mock_region_metadata`, set expected type to Int64.
536        let expected_predicate_target_types =
537            BTreeMap::from_iter([(IndexTarget::ColumnId(1), ConcreteDataType::int64_datatype())]);
538
539        let sst_index_applier = InvertedIndexApplier::new(
540            table_dir,
541            PathType::Bare,
542            object_store,
543            puffin_manager_factory,
544            predicates,
545            expected_predicate_target_types,
546        )
547        .unwrap();
548        let plan = sst_index_applier
549            .plan_for_sst(&mock_region_metadata())
550            .unwrap();
551        assert!(plan.is_none());
552    }
553
554    #[tokio::test]
555    async fn test_index_applier_apply_invalid_blob_type() {
556        let (_d, puffin_manager_factory) =
557            PuffinManagerFactory::new_for_test_async("test_index_applier_apply_invalid_blob_type_")
558                .await;
559        let object_store = ObjectStore::new(Memory::default()).unwrap();
560        let file_id = RegionFileId::new(0.into(), FileId::random());
561        let index_id = RegionIndexId::new(file_id, 0);
562        let table_dir = "table_dir".to_string();
563
564        let puffin_manager = puffin_manager_factory.build(
565            object_store.clone(),
566            RegionFilePathFactory::new(table_dir.clone(), PathType::Bare),
567        );
568        let mut writer = puffin_manager.writer(&index_id).await.unwrap();
569        writer
570            .put_blob(
571                "invalid_blob_type",
572                Cursor::new(vec![]),
573                Default::default(),
574                Default::default(),
575            )
576            .await
577            .unwrap();
578        writer.finish().await.unwrap();
579
580        let mut predicates = BTreeMap::new();
581        predicates.insert(
582            IndexTarget::ColumnId(1),
583            vec![Predicate::RegexMatch(RegexMatchPredicate {
584                pattern: "foo".to_string(),
585            })],
586        );
587        let expected_predicate_target_types = BTreeMap::from_iter([(
588            IndexTarget::ColumnId(1),
589            ConcreteDataType::string_datatype(),
590        )]);
591        let sst_index_applier = InvertedIndexApplier::new(
592            table_dir.clone(),
593            PathType::Bare,
594            object_store,
595            puffin_manager_factory,
596            predicates,
597            expected_predicate_target_types,
598        )
599        .unwrap();
600        let plan = sst_index_applier
601            .plan_for_sst(&mock_region_metadata())
602            .unwrap()
603            .unwrap();
604        let res = sst_index_applier
605            .apply(index_id, None, &plan.index_applier, None)
606            .await;
607        assert!(format!("{:?}", res.unwrap_err()).contains("Blob not found"));
608    }
609
610    fn mock_region_metadata() -> RegionMetadataRef {
611        let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
612        builder
613            .push_column_metadata(ColumnMetadata {
614                column_schema: ColumnSchema::new("tag", ConcreteDataType::string_datatype(), false),
615                semantic_type: SemanticType::Tag,
616                column_id: 1,
617            })
618            .push_column_metadata(ColumnMetadata {
619                column_schema: ColumnSchema::new(
620                    "ts",
621                    ConcreteDataType::timestamp_millisecond_datatype(),
622                    false,
623                ),
624                semantic_type: SemanticType::Timestamp,
625                column_id: 2,
626            })
627            .primary_key(vec![1]);
628        Arc::new(builder.build().unwrap())
629    }
630}