Skip to main content

mito2/sst/index/
registry.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//! Ordered registration and planning of index implementations.
16
17use std::collections::HashSet;
18use std::sync::Arc;
19
20use common_error::ext::BoxedError;
21use common_telemetry::warn;
22use snafu::{IntoError, ResultExt};
23use store_api::metadata::RegionMetadataRef;
24use store_api::storage::RegionId;
25
26use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig, MitoConfig};
27use crate::error::{Error, ExternalSnafu, InvalidConfigSnafu};
28use crate::metrics::{INDEX_CREATE_DISCARDED_TOTAL, INDEX_DISCARD_ADMISSION_REJECTED};
29use crate::sst::file::{FileMeta, IndexType};
30use crate::sst::index::IndexBuildType;
31use crate::sst::index::handler::builtin::BuiltinIndexHandler;
32use crate::sst::index::handler::{
33    IndexKindHandler, IndexKindProviderRef, PlanContext, PlanEntry, PlannedIndex,
34};
35use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
36
37/// Shared registry installed by the engine and its embedding application.
38pub type IndexRegistryRef = Arc<IndexRegistry>;
39
40/// One handler per owner; related algorithms may share one creator and row traversal.
41#[derive(Debug, Clone)]
42pub struct IndexRegistry {
43    handlers: Vec<Arc<dyn IndexKindHandler>>,
44}
45
46impl IndexRegistry {
47    /// Registers the existing built-in creators in their established order.
48    pub fn new(
49        inverted: InvertedIndexConfig,
50        fulltext: FulltextIndexConfig,
51        bloom: BloomFilterConfig,
52    ) -> Self {
53        Self {
54            handlers: vec![
55                Arc::new(BuiltinIndexHandler::Inverted(inverted)),
56                Arc::new(BuiltinIndexHandler::Fulltext(fulltext)),
57                Arc::new(BuiltinIndexHandler::Bloom(bloom)),
58            ],
59        }
60    }
61
62    /// Assembles the configured built-ins and the injected provider.
63    pub(crate) fn from_config(
64        config: &MitoConfig,
65        provider: Option<IndexKindProviderRef>,
66    ) -> crate::error::Result<Self> {
67        Self::new(
68            config.inverted_index.clone(),
69            config.fulltext_index.clone(),
70            config.bloom_filter_index.clone(),
71        )
72        .with_provider(provider)
73        .with_context(|_| ExternalSnafu {
74            context: "registering index handlers".to_string(),
75        })
76    }
77
78    /// Adds the embedding application's handlers after the built-in configuration.
79    pub fn with_provider(
80        mut self,
81        provider: Option<IndexKindProviderRef>,
82    ) -> Result<Self, BoxedError> {
83        if let Some(provider) = provider {
84            for handler in provider.handlers() {
85                self.register(handler)?;
86            }
87        }
88        Ok(self)
89    }
90
91    /// Validates required providers and their options before creating a new region.
92    /// Built-in handlers preserve their existing schema/build-time validation.
93    pub fn validate(&self, context: &PlanContext<'_>) -> Result<(), BoxedError> {
94        self.validate_schema_kinds(context.metadata)?;
95        for handler in &self.handlers {
96            handler.validate(context)?;
97        }
98        Ok(())
99    }
100
101    /// Installs a handler, rejecting empty or overlapping kind ownership.
102    pub fn register(&mut self, handler: Arc<dyn IndexKindHandler>) -> Result<(), BoxedError> {
103        self.validate_registration(handler.kinds())?;
104        self.handlers.push(handler);
105        self.handlers
106            .sort_by_key(|handler| handler.kinds().iter().min().copied());
107        Ok(())
108    }
109
110    /// Rejects required extension indexes whose implementation is unavailable.
111    /// Checks current schema options and both file-level and column-level metadata.
112    pub fn validate_required_kinds<'a>(
113        &self,
114        metadata: &RegionMetadataRef,
115        files: impl IntoIterator<Item = &'a FileMeta>,
116    ) -> Result<(), BoxedError> {
117        self.validate_schema_kinds(metadata)?;
118        self.validate_file_kinds(files)
119    }
120
121    /// Reports unavailable sketches without blocking compaction after a downgrade.
122    /// Logs each missing kind at most once for this input group.
123    pub(crate) fn warn_missing_compaction_handlers<'a>(
124        &self,
125        metadata: &RegionMetadataRef,
126        files: impl IntoIterator<Item = &'a FileMeta>,
127    ) {
128        let missing = ExtensionIndexKind::ALL
129            .map(|kind| !self.has_handler(IndexKind::Extension(kind).index_type()));
130        if !missing.iter().any(|missing| *missing) {
131            return;
132        }
133        let mut requested = ExtensionIndexKind::ALL.map(|kind| {
134            metadata.column_metadatas.iter().any(|column| {
135                column
136                    .column_schema
137                    .metadata()
138                    .contains_key(kind.required_metadata_key())
139            })
140        });
141        for file in files {
142            for (position, kind) in ExtensionIndexKind::ALL.iter().enumerate() {
143                if missing[position] && !requested[position] {
144                    let index_type = IndexKind::Extension(*kind).index_type();
145                    requested[position] = file.available_indexes.contains(&index_type)
146                        || file
147                            .indexes
148                            .iter()
149                            .any(|column| column.created_indexes.contains(&index_type));
150                }
151            }
152        }
153        for (position, kind) in ExtensionIndexKind::ALL.iter().enumerate() {
154            if missing[position] && requested[position] {
155                warn!(
156                    "Compacting without unavailable sketch provider, region_id: {}, kind: {}; output will omit this sketch",
157                    metadata.region_id,
158                    kind.as_str()
159                );
160            }
161        }
162    }
163
164    /// Rejects unavailable implementations for indexes being replaced.
165    fn validate_file_kinds<'a>(
166        &self,
167        files: impl IntoIterator<Item = &'a FileMeta>,
168    ) -> Result<(), BoxedError> {
169        for file in files {
170            for kind in file.available_indexes.iter().chain(
171                file.indexes
172                    .iter()
173                    .flat_map(|column| &column.created_indexes),
174            ) {
175                self.validate_required_kind(*kind)?;
176            }
177        }
178        Ok(())
179    }
180
181    /// Prepares each handler once. Construction failures retain the existing
182    /// built-in test panic and production skip policy. Other failures are retained
183    /// for the caller to check before publishing rebuilt indexes. Required-provider
184    /// validation belongs to the operation entry point, before calling this method.
185    pub fn plan(&self, context: &PlanContext<'_>) -> IndexBuildPlan {
186        let mut planned = Vec::new();
187        let mut failure = None;
188        for handler in &self.handlers {
189            if context.build_type == IndexBuildType::Flush
190                && !handler.kinds().iter().all(|kind| kind.is_builtin())
191            {
192                continue;
193            }
194            let result = handler.plan(context).and_then(|plan| {
195                if let Some(plan) = &plan {
196                    Self::validate_plan(handler.as_ref(), plan.as_ref())?;
197                }
198                Ok(plan)
199            });
200            match result {
201                Ok(Some(plan)) => planned.push(plan),
202                Ok(None) => {}
203                Err(err) => {
204                    Self::record_planning_error(handler.as_ref(), context, err, &mut failure);
205                }
206            }
207        }
208        IndexBuildPlan { planned, failure }
209    }
210
211    fn validate_registration(&self, kinds: &[IndexKind]) -> Result<(), BoxedError> {
212        if kinds.is_empty()
213            || kinds
214                .iter()
215                .enumerate()
216                .any(|(i, kind)| kinds[..i].contains(kind))
217        {
218            return Err(BoxedError::new(
219                InvalidConfigSnafu {
220                    reason: "index handler kinds must be nonempty and unique",
221                }
222                .build(),
223            ));
224        }
225        if kinds.iter().any(|kind| kind.is_builtin()) && kinds.iter().any(|kind| !kind.is_builtin())
226        {
227            return Err(BoxedError::new(
228                InvalidConfigSnafu {
229                    reason: "index handler cannot mix built-in and extension kinds",
230                }
231                .build(),
232            ));
233        }
234        if kinds.iter().any(|kind| self.has_handler(kind.index_type())) {
235            return Err(BoxedError::new(
236                InvalidConfigSnafu {
237                    reason: "index handler kind is already registered",
238                }
239                .build(),
240            ));
241        }
242        Ok(())
243    }
244
245    fn has_handler(&self, kind: IndexType) -> bool {
246        self.handlers.iter().any(|handler| {
247            handler
248                .kinds()
249                .iter()
250                .any(|owned| owned.index_type() == kind)
251        })
252    }
253
254    fn validate_plan(
255        handler: &dyn IndexKindHandler,
256        plan: &dyn PlannedIndex,
257    ) -> Result<(), BoxedError> {
258        let kinds = plan.kinds();
259        if kinds.is_empty()
260            || kinds
261                .iter()
262                .enumerate()
263                .any(|(i, kind)| kinds[..i].contains(kind) || !handler.kinds().contains(kind))
264            || plan
265                .entries()
266                .iter()
267                .any(|entry| !kinds.contains(&entry.kind))
268        {
269            return Err(BoxedError::new(
270                InvalidConfigSnafu {
271                    reason: "index plan kinds must be nonempty, unique, owned by the handler, and include every entry kind",
272                }
273                .build(),
274            ));
275        }
276        Ok(())
277    }
278
279    fn record_planning_error(
280        handler: &dyn IndexKindHandler,
281        context: &PlanContext<'_>,
282        err: BoxedError,
283        failure: &mut Option<Arc<Error>>,
284    ) {
285        if handler.kinds().iter().all(|kind| kind.is_builtin()) && cfg!(any(test, feature = "test"))
286        {
287            panic!(
288                "Failed to prepare built-in index, region_id: {}, err: {err}",
289                context.metadata.region_id
290            );
291        }
292        warn!(err; "Failed to prepare index, region_id: {}, kinds: {:?}", context.metadata.region_id, handler.kinds());
293        failure.get_or_insert_with(|| {
294            Arc::new(
295                ExternalSnafu {
296                    context: "index planning".to_string(),
297                }
298                .into_error(err),
299            )
300        });
301    }
302
303    pub(crate) fn validate_schema_kinds(
304        &self,
305        metadata: &RegionMetadataRef,
306    ) -> Result<(), BoxedError> {
307        for column in &metadata.column_metadatas {
308            let schema = &column.column_schema;
309            for kind in ExtensionIndexKind::ALL {
310                if schema.metadata().contains_key(kind.required_metadata_key()) {
311                    self.validate_required_kind(IndexKind::Extension(kind).index_type())?;
312                }
313            }
314        }
315        Ok(())
316    }
317
318    fn validate_required_kind(&self, kind: IndexType) -> Result<(), BoxedError> {
319        if ExtensionIndexKind::ALL
320            .iter()
321            .any(|extension| IndexKind::Extension(*extension).index_type() == kind)
322            && !self.has_handler(kind)
323        {
324            return Err(BoxedError::new(
325                InvalidConfigSnafu {
326                    reason: format!("required index {kind:?} has no registered handler"),
327                }
328                .build(),
329            ));
330        }
331        Ok(())
332    }
333}
334
335/// Typed plans retained across output files of one operation.
336#[derive(Debug, Clone, Default)]
337pub struct IndexBuildPlan {
338    planned: Vec<Arc<dyn PlannedIndex>>,
339    failure: Option<Arc<Error>>,
340}
341
342impl IndexBuildPlan {
343    /// Reports preparation failure separately from a successful empty plan.
344    pub fn check_success(&self) -> Result<(), Arc<Error>> {
345        self.failure.clone().map_or(Ok(()), Err)
346    }
347
348    /// Plans in execution order, grouped by owner rather than by column.
349    pub fn planned(&self) -> &[Arc<dyn PlannedIndex>] {
350        &self.planned
351    }
352
353    /// Whether no handler requested work, including metadata-only maintenance.
354    pub fn is_empty(&self) -> bool {
355        self.planned.is_empty()
356    }
357
358    /// All requested column formats.
359    pub fn entries(&self) -> impl Iterator<Item = &PlanEntry> {
360        self.planned.iter().flat_map(|plan| plan.entries())
361    }
362
363    /// Whether any planned implementation can reuse persisted input indexes.
364    pub fn needs_input_reuse(&self) -> bool {
365        self.planned.iter().any(|plan| plan.needs_input_reuse())
366    }
367
368    /// Omits optional extension work when the caller cannot admit its memory budget.
369    /// Records each requested kind once per target plan, rather than once per column.
370    pub fn omit_extensions_for_budget(&mut self, region_id: RegionId) {
371        let omitted: HashSet<_> = self
372            .entries()
373            .filter(|entry| !entry.kind.is_builtin())
374            .map(|entry| entry.kind)
375            .collect();
376        for kind in omitted {
377            warn!(
378                "Omitting index before construction, region_id: {}, kind: {}, reason: admission_rejected",
379                region_id,
380                kind.as_str()
381            );
382            INDEX_CREATE_DISCARDED_TOTAL
383                .with_label_values(&[kind.as_str(), INDEX_DISCARD_ADMISSION_REJECTED])
384                .inc();
385        }
386        self.planned
387            .retain(|plan| plan.kinds().iter().all(|kind| kind.is_builtin()));
388    }
389
390    /// Whether every handler considers the published file current.
391    pub fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool {
392        let has_removed_extensions = matches!(
393            context.build_type,
394            IndexBuildType::Manual | IndexBuildType::SchemaChange
395        ) && ExtensionIndexKind::ALL.iter().any(|kind| {
396            let index_type = IndexKind::Extension(*kind).index_type();
397            let configured = |column_id| {
398                context
399                    .metadata
400                    .column_by_id(column_id)
401                    .is_some_and(|column| {
402                        column
403                            .column_schema
404                            .metadata()
405                            .contains_key(kind.required_metadata_key())
406                    })
407            };
408            let mut has_column_descriptor = false;
409            for column in &file.indexes {
410                if column.created_indexes.contains(&index_type) {
411                    has_column_descriptor = true;
412                    if !configured(column.column_id) {
413                        return true;
414                    }
415                }
416            }
417            // Legacy file-level descriptors cannot identify individual columns.
418            !has_column_descriptor
419                && file.available_indexes.contains(&index_type)
420                && !context.metadata.column_metadatas.iter().any(|column| {
421                    column
422                        .column_schema
423                        .metadata()
424                        .contains_key(kind.required_metadata_key())
425                })
426        });
427        self.failure.is_none()
428            && !has_removed_extensions
429            && self
430                .planned
431                .iter()
432                .all(|plan| plan.is_current(file, context))
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439    use crate::sst::index::kind::ExtensionIndexKind;
440
441    #[derive(Debug)]
442    struct TestHandler(Vec<IndexKind>);
443
444    impl IndexKindHandler for TestHandler {
445        fn kinds(&self) -> &[IndexKind] {
446            &self.0
447        }
448
449        fn validate(&self, _: &PlanContext<'_>) -> Result<(), BoxedError> {
450            Ok(())
451        }
452
453        fn plan(&self, _: &PlanContext<'_>) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
454            Ok(None)
455        }
456    }
457
458    #[derive(Debug)]
459    struct TestPlan {
460        kinds: Vec<IndexKind>,
461        entries: Vec<PlanEntry>,
462    }
463
464    #[async_trait::async_trait]
465    impl PlannedIndex for TestPlan {
466        fn kinds(&self) -> &[IndexKind] {
467            &self.kinds
468        }
469        fn entries(&self) -> &[PlanEntry] {
470            &self.entries
471        }
472        async fn build(
473            &self,
474            _: &crate::sst::index::handler::BuildContext<'_>,
475        ) -> Result<Option<Box<dyn crate::sst::index::handler::IndexCreator>>, BoxedError> {
476            unreachable!("admission must not construct creators")
477        }
478
479        fn is_current(&self, _: &FileMeta, _: &PlanContext<'_>) -> bool {
480            false
481        }
482    }
483
484    #[test]
485    fn test_admission_omission_records_each_requested_kind_once() {
486        let builtin = IndexKind::Bloom;
487        let enabled = IndexKind::Extension(ExtensionIndexKind::Mg);
488        let disabled = IndexKind::Extension(ExtensionIndexKind::Kll);
489        let entry = |kind, column_id| PlanEntry {
490            kind,
491            column_id,
492            format_version: 1,
493        };
494        let mut plan = IndexBuildPlan {
495            planned: vec![
496                Arc::new(TestPlan {
497                    kinds: vec![builtin],
498                    entries: vec![entry(builtin, 0)],
499                }),
500                Arc::new(TestPlan {
501                    kinds: vec![enabled, disabled],
502                    entries: vec![entry(enabled, 0), entry(enabled, 1)],
503                }),
504            ],
505            failure: None,
506        };
507        let counter = INDEX_CREATE_DISCARDED_TOTAL
508            .with_label_values(&[enabled.as_str(), "admission_rejected"]);
509        let disabled_counter = INDEX_CREATE_DISCARDED_TOTAL
510            .with_label_values(&[disabled.as_str(), "admission_rejected"]);
511        let before = counter.get();
512        let disabled_before = disabled_counter.get();
513        plan.omit_extensions_for_budget(RegionId::new(1, 1));
514        assert_eq!(
515            plan.entries().cloned().collect::<Vec<_>>(),
516            vec![entry(builtin, 0)]
517        );
518        assert_eq!(counter.get(), before + 1);
519        assert_eq!(disabled_counter.get(), disabled_before);
520        assert!(plan.check_success().is_ok());
521        plan.omit_extensions_for_budget(RegionId::new(1, 1));
522        assert_eq!(counter.get(), before + 1);
523    }
524
525    #[test]
526    fn test_registration_preserves_grouped_owner_and_rejects_overlap() {
527        let mut registry =
528            IndexRegistry::new(Default::default(), Default::default(), Default::default());
529        let kinds = vec![
530            IndexKind::Extension(ExtensionIndexKind::Hll),
531            IndexKind::Extension(ExtensionIndexKind::Kll),
532            IndexKind::Extension(ExtensionIndexKind::Mg),
533        ];
534        registry
535            .register(Arc::new(TestHandler(kinds.clone())))
536            .unwrap();
537        assert_eq!(registry.handlers.len(), 4);
538        assert_eq!(registry.handlers[3].kinds(), kinds);
539        for invalid in [vec![], vec![kinds[0]], vec![IndexKind::Fulltext]] {
540            assert!(registry.register(Arc::new(TestHandler(invalid))).is_err());
541            assert_eq!(registry.handlers.len(), 4);
542        }
543    }
544
545    #[test]
546    fn test_registration_rejects_duplicates_within_one_owner() {
547        let mut registry =
548            IndexRegistry::new(Default::default(), Default::default(), Default::default());
549        let kind = IndexKind::Extension(ExtensionIndexKind::Hll);
550        assert!(
551            registry
552                .register(Arc::new(TestHandler(vec![kind, kind])))
553                .is_err()
554        );
555        assert_eq!(registry.handlers.len(), 3);
556    }
557
558    #[derive(Debug)]
559    struct PlannedHandler {
560        owned: Vec<IndexKind>,
561        plan: Arc<TestPlan>,
562    }
563
564    impl IndexKindHandler for PlannedHandler {
565        fn kinds(&self) -> &[IndexKind] {
566            &self.owned
567        }
568
569        fn validate(&self, _: &PlanContext<'_>) -> Result<(), BoxedError> {
570            Ok(())
571        }
572
573        fn plan(&self, _: &PlanContext<'_>) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
574            Ok(Some(self.plan.clone()))
575        }
576    }
577
578    #[test]
579    fn test_plans_validate_ownership_without_removing_valid_plans() {
580        let hll = IndexKind::Extension(ExtensionIndexKind::Hll);
581        let kll = IndexKind::Extension(ExtensionIndexKind::Kll);
582        let metadata = Arc::new(crate::test_util::sst_util::sst_region_metadata());
583        let options = Default::default();
584        let context = PlanContext {
585            metadata: &metadata,
586            index_options: &options,
587            build_type: crate::sst::index::IndexBuildType::Compact,
588            existing_indexes: &[],
589        };
590        for (kinds, entry_kind, invalid) in [
591            (vec![], hll, true),
592            (vec![hll, hll], hll, true),
593            (vec![kll], kll, true),
594            (vec![hll], kll, true),
595            (vec![hll], hll, false),
596        ] {
597            let mut registry =
598                IndexRegistry::new(Default::default(), Default::default(), Default::default());
599            registry
600                .register(Arc::new(PlannedHandler {
601                    owned: vec![hll, IndexKind::Extension(ExtensionIndexKind::Mg)],
602                    plan: Arc::new(TestPlan {
603                        kinds,
604                        entries: vec![PlanEntry {
605                            column_id: 0,
606                            kind: entry_kind,
607                            format_version: 1,
608                        }],
609                    }),
610                }))
611                .unwrap();
612            registry
613                .register(Arc::new(PlannedHandler {
614                    owned: vec![kll],
615                    plan: Arc::new(TestPlan {
616                        kinds: vec![kll],
617                        entries: vec![PlanEntry {
618                            column_id: 0,
619                            kind: kll,
620                            format_version: 1,
621                        }],
622                    }),
623                }))
624                .unwrap();
625            let plan = registry.plan(&context);
626            assert_eq!(plan.check_success().is_err(), invalid);
627            assert_eq!(
628                plan.entries()
629                    .filter(|entry| !entry.kind.is_builtin())
630                    .map(|entry| entry.kind)
631                    .collect::<Vec<_>>(),
632                if invalid { vec![kll] } else { vec![hll, kll] }
633            );
634            assert_eq!(registry.handlers.len(), 5);
635        }
636    }
637
638    #[test]
639    fn test_registration_rejects_mixed_builtin_and_extension_owner() {
640        let mut registry = IndexRegistry {
641            handlers: Vec::new(),
642        };
643        assert!(
644            registry
645                .register(Arc::new(TestHandler(vec![
646                    IndexKind::Inverted,
647                    IndexKind::Extension(ExtensionIndexKind::Hll),
648                ])))
649                .is_err()
650        );
651        assert!(registry.handlers.is_empty());
652    }
653}