Skip to main content

mito2/worker/
handle_rebuild_index.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//! Handles index build requests.
16
17use std::collections::HashMap;
18use std::sync::Arc;
19
20use api::v1::region::build_index_request;
21use common_telemetry::{debug, info, warn};
22use snafu::{IntoError, ResultExt};
23use store_api::metadata::RegionMetadataRef;
24use store_api::region_request::RegionBuildIndexRequest;
25use store_api::storage::{FileId, RegionId};
26use tokio::sync::mpsc;
27
28use crate::cache::CacheStrategy;
29use crate::error::{
30    BuildIndexAsyncSnafu, ExternalSnafu, IndexBuildIncompleteSnafu, InvalidRequestSnafu,
31    RegionStateSnafu, Result, WorkerStoppedSnafu,
32};
33use crate::manifest::action::RegionEdit;
34use crate::metrics::INDEX_PUBLICATION_STALE_TOTAL;
35use crate::region::options::IndexOptions;
36use crate::region::{IndexBuildSource, MitoRegionRef, RegionLeaderState, RegionRoleState};
37use crate::request::{BuildIndexRequest, IndexBuildFinished, IndexBuildStopped, OptionOutputTx};
38use crate::sst::file::{self, FileHandle, FileMeta, FileMetaRef, RegionFileId, RegionIndexId};
39use crate::sst::index::handler::{IndexKindProviderRef, PlanContext};
40use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
41use crate::sst::index::registry::{IndexRegistry, IndexRegistryRef};
42use crate::sst::index::{
43    IndexBuildOutcome, IndexBuildTask, IndexBuildType, IndexerBuilderImpl, ResultMpscSender,
44    cleanup_stale_index_caches,
45};
46use crate::worker::{RegionWorkerLoop, index_registry};
47
48/// Parts of a region version that index build tasks need.
49///
50/// Holding this instead of the whole version avoids pinning memtables and the
51/// SST version while the worker awaits.
52pub(crate) struct IndexBuildSnapshot {
53    metadata: RegionMetadataRef,
54    index_options: IndexOptions,
55}
56
57/// Returns whether a background build may replace the index of `file`: a file that already has
58/// an extension index was indexed whole by its writer, and a replacement would erase those blobs.
59pub(crate) fn needs_background_indexes(file: &FileMeta) -> bool {
60    !ExtensionIndexKind::ALL.iter().any(|kind| {
61        let index_type = IndexKind::Extension(*kind).index_type();
62        file.available_indexes.contains(&index_type)
63            || file
64                .indexes
65                .iter()
66                .any(|column| column.created_indexes.contains(&index_type))
67    })
68}
69
70/// Selects the files that a build of `build_type` for every file of a region builds, from the
71/// region's files that its manifest records (`candidates`, each with the manifest's file meta).
72/// A flush build, which the end of a wait for the Leader lease asks for, builds no extension
73/// index, so it leaves the files that have one. Of the others it builds those whose index in the
74/// version is not current for the plan of `build_type`: a publication committed to the manifest
75/// but not yet applied is still invisible to queries, and its build still holds the file, so a
76/// manual build waits for it.
77fn select_whole_region_builds(
78    candidates: Vec<(FileHandle, FileMetaRef)>,
79    registry: &IndexRegistry,
80    snapshot: &IndexBuildSnapshot,
81    build_type: &IndexBuildType,
82) -> Vec<(FileHandle, FileMetaRef)> {
83    candidates
84        .into_iter()
85        .filter(|(_, file_meta)| {
86            *build_type != IndexBuildType::Flush || needs_background_indexes(file_meta)
87        })
88        .filter(|(file, _)| {
89            index_needs_rebuild(registry, snapshot, file.meta_ref(), build_type.clone())
90        })
91        .collect()
92}
93
94impl<S> RegionWorkerLoop<S> {
95    pub(crate) fn new_index_build_task(
96        &self,
97        region: &MitoRegionRef,
98        snapshot: &IndexBuildSnapshot,
99        registry: IndexRegistryRef,
100        source: (FileHandle, FileMeta),
101        build_type: IndexBuildType,
102        result_senders: Vec<ResultMpscSender>,
103    ) -> IndexBuildTask {
104        let (file, file_meta) = source;
105        let access_layer = region.access_layer.clone();
106
107        let puffin_manager = if let Some(write_cache) = self.cache_manager.write_cache() {
108            write_cache.build_puffin_manager()
109        } else {
110            access_layer.build_puffin_manager()
111        };
112
113        let intermediate_manager = if let Some(write_cache) = self.cache_manager.write_cache() {
114            write_cache.intermediate_manager().clone()
115        } else {
116            access_layer.intermediate_manager().clone()
117        };
118
119        let indexer_builder_ref = Arc::new(IndexerBuilderImpl {
120            index_build_inputs: None,
121            build_type: build_type.clone(),
122            metadata: snapshot.metadata.clone(),
123            registry: registry.clone(),
124            index_options: snapshot.index_options.clone(),
125            intermediate_manager,
126            puffin_manager,
127            write_cache_enabled: self.cache_manager.write_cache().is_some(),
128        });
129
130        IndexBuildTask {
131            region_id: region.region_id,
132            file: file.clone(),
133            target_region_metadata: snapshot.metadata.clone(),
134            source: IndexBuildSource::new(file_meta, snapshot.metadata.schema_version),
135            index_options: snapshot.index_options.clone(),
136            reason: build_type,
137            access_layer: access_layer.clone(),
138            listener: self.listener.clone(),
139            manifest_ctx: region.manifest_ctx.clone(),
140            write_cache: self.cache_manager.write_cache().cloned(),
141            cache_manager: Some(self.cache_manager.clone()),
142            file_purger: file.file_purger(),
143            request_sender: self.sender.clone(),
144            indexer_builder: indexer_builder_ref.clone(),
145            result_senders,
146        }
147    }
148
149    /// Validates providers and the current plan before selecting or scheduling files.
150    fn prepare_rebuild_registry(
151        &self,
152        snapshot: &IndexBuildSnapshot,
153        build_type: IndexBuildType,
154    ) -> Result<IndexRegistryRef> {
155        // Post-flush/compaction tasks build the built-in indexes of a new SST.
156        // Compaction extension construction belongs to the compaction writer.
157        let provider = match build_type {
158            IndexBuildType::Flush | IndexBuildType::Compact => None,
159            IndexBuildType::Manual | IndexBuildType::SchemaChange => {
160                self.plugins.get::<IndexKindProviderRef>()
161            }
162        };
163        let registry = index_registry(&self.config, provider)?;
164        validate_rebuild_plan(&registry, snapshot, build_type)?;
165        Ok(registry)
166    }
167
168    /// Handles manual build index requests.
169    pub(crate) async fn handle_build_index_request(
170        &mut self,
171        region_id: RegionId,
172        req: RegionBuildIndexRequest,
173        sender: OptionOutputTx,
174    ) {
175        match req.options {
176            Some(build_index_request::Options::SeriesIndex(_)) => {
177                self.handle_build_series_index_request(region_id, sender);
178            }
179            None | Some(build_index_request::Options::SstIndex(_)) => {
180                self.handle_rebuild_index(
181                    BuildIndexRequest {
182                        region_id,
183                        build_type: IndexBuildType::Manual,
184                        file_metas: Vec::new(),
185                        result_senders: Vec::new(),
186                    },
187                    sender,
188                )
189                .await;
190            }
191        }
192    }
193
194    /// Submits manual reconciliation without blocking the region worker on index I/O.
195    fn handle_build_series_index_request(&self, region_id: RegionId, mut sender: OptionOutputTx) {
196        let Some(region) = self.regions.writable_region_or(region_id, &mut sender) else {
197            return;
198        };
199        if region.version().options.sst_format != Some(crate::sst::FormatType::Narthex) {
200            sender.send(
201                InvalidRequestSnafu {
202                    region_id,
203                    reason: "series indexes require Narthex storage",
204                }
205                .fail(),
206            );
207            return;
208        }
209        let Some(state) = &self.series_index_task_state else {
210            sender.send(
211                InvalidRequestSnafu {
212                    region_id,
213                    reason: "series index is disabled; enable experimental_enable_series_index",
214                }
215                .fail(),
216            );
217            return;
218        };
219        let receiver = match state.try_reconcile(region) {
220            Ok(receiver) => receiver,
221            Err(error) => {
222                sender.send(Err(error));
223                return;
224            }
225        };
226        let worker_id = self.id;
227        common_runtime::spawn_global(async move {
228            let result = receiver
229                .await
230                .unwrap_or_else(|_| WorkerStoppedSnafu { id: worker_id }.fail());
231            sender.send(result.map(|_| 0));
232        });
233    }
234
235    /// Handles an index build request that is not a retry. Returns true if the state of the
236    /// registered region stopped it before it scheduled every build.
237    pub(crate) async fn handle_rebuild_index(
238        &mut self,
239        request: BuildIndexRequest,
240        sender: OptionOutputTx,
241    ) -> bool {
242        self.handle_rebuild_index_inner(request, sender, false)
243            .await
244    }
245
246    /// Handles an index build request, a retry if `is_retry`. Returns true if the state of the
247    /// registered region stopped it before it scheduled every build.
248    pub(crate) async fn handle_rebuild_index_inner(
249        &mut self,
250        request: BuildIndexRequest,
251        mut sender: OptionOutputTx,
252        is_retry: bool,
253    ) -> bool {
254        let region_id = request.region_id;
255        // A retry has no caller to try again, so each check of the region's state below that
256        // refuses one keeps it until the region is a writable leader with its Leader lease.
257        let Some(region) = self.regions.writable_region_or(region_id, &mut sender) else {
258            if is_retry {
259                self.keep_index_build_retry(request);
260            }
261            return self.regions.get_region(region_id).is_some();
262        };
263        // Staging regions are writable but must not publish indexes.
264        if region.should_abort_index() {
265            if is_retry {
266                self.keep_index_build_retry(request);
267                return true;
268            }
269            sender.send(
270                RegionStateSnafu {
271                    region_id,
272                    state: region.state(),
273                    expect: RegionRoleState::Leader(RegionLeaderState::Writable),
274                }
275                .fail(),
276            );
277            return true;
278        }
279        // A region that awaits its Leader lease could not publish the index. In async build
280        // mode it builds the missing indexes once it is a writable leader with its lease (see
281        // `DeferredLeaseWork`).
282        if let Err(e) = region
283            .manifest_ctx
284            .ensure_leader_lease_or_downgrading(region_id)
285        {
286            if is_retry {
287                self.keep_index_build_retry(request);
288                return true;
289            }
290            info!("Region {region_id} awaits its Leader lease, building no index");
291            sender.send(Err(e));
292            return true;
293        }
294
295        // Only keep the parts of the version that index builds need, so the
296        // memtables and SST version are not pinned across the awaits below.
297        let (snapshot, all_files) = {
298            let version = region.version_control.current().version;
299            let all_files: HashMap<FileId, FileHandle> = version
300                .ssts
301                .levels()
302                .iter()
303                .flat_map(|level| level.files.iter())
304                .filter(|(_, handle)| {
305                    !handle.is_deleted()
306                        && !handle.compacting()
307                        && handle.level() < file::LEVEL_SHARED
308                })
309                .map(|(id, handle)| (*id, handle.clone()))
310                .collect();
311            let snapshot = IndexBuildSnapshot {
312                metadata: version.metadata.clone(),
313                index_options: version.options.index_options.clone(),
314            };
315            (snapshot, all_files)
316        };
317        // A committed index publication may not have reached version control
318        // yet. Use the manifest's FileMeta as the conditional publication
319        // source while keeping the builder's schema generation from the version.
320        self.listener.on_rebuild_index_admitted(region_id).await;
321        let manifest = region.manifest_ctx.manifest().await;
322        let current_file_meta = |file_id| {
323            let file_meta = manifest.files.get(&file_id);
324            if file_meta.is_none() {
325                debug!(
326                    "Skipping index build because file is absent from manifest, region: {}, file_id: {}",
327                    region_id, file_id
328                );
329            }
330            file_meta.cloned()
331        };
332
333        // Collect eligible inputs before currency selection.
334        let candidates = if request.file_metas.is_empty() {
335            all_files
336                .values()
337                .filter_map(|file| {
338                    let file_meta = current_file_meta(file.meta_ref().file_id)?;
339                    Some((file.clone(), file_meta))
340                })
341                .collect::<Vec<_>>()
342        } else {
343            request
344                .file_metas
345                .iter()
346                .filter_map(|meta| {
347                    let file = all_files.get(&meta.file_id)?;
348                    let file_meta = current_file_meta(meta.file_id)?;
349                    Some((file.clone(), file_meta))
350                })
351                .collect::<Vec<_>>()
352        };
353
354        let registry = match self.prepare_rebuild_registry(&snapshot, request.build_type.clone()) {
355            Ok(registry) => registry,
356            Err(err) => {
357                warn!(err;
358                    "Failed to prepare index build, region_id: {}, build_type: {:?}, candidate_files: {}",
359                    region_id, request.build_type, candidates.len()
360                );
361                let err = Arc::new(err);
362                for result_sender in &request.result_senders {
363                    let _ = result_sender
364                        .send(Err(
365                            BuildIndexAsyncSnafu { region_id }.into_error(err.clone())
366                        ))
367                        .await;
368                }
369                sender.send(Err(BuildIndexAsyncSnafu { region_id }.into_error(err)));
370                return false;
371            }
372        };
373        let build_tasks = if request.file_metas.is_empty() {
374            select_whole_region_builds(candidates, &registry, &snapshot, &request.build_type)
375        } else {
376            candidates
377        };
378
379        if build_tasks.is_empty() {
380            debug!(
381                "No files need to build index for region {}, request: {:?}",
382                region_id, request
383            );
384            sender.send(Ok(0));
385            return false;
386        }
387
388        let file_ids = build_tasks
389            .iter()
390            .map(|(file, _)| file.meta_ref().file_id)
391            .collect::<Vec<_>>();
392        let build_type = request.build_type.clone();
393        // Each task holds a sender and reports at most once, so sends never block.
394        let (tx, mut rx) = mpsc::channel::<Result<IndexBuildOutcome>>(build_tasks.len());
395        let mut stopped = false;
396        for (file_handle, file_meta) in build_tasks {
397            debug!(
398                "Scheduling index build for region {}, file_id {}",
399                region_id,
400                file_handle.meta_ref().file_id
401            );
402
403            // `set_region_role` can change the state while tasks are scheduled.
404            if region.should_abort_index() {
405                warn!(
406                    "Region {} is in state {:?}, abort index rebuild process for file_id {}",
407                    region_id,
408                    region.state(),
409                    file_handle.meta_ref().file_id
410                );
411                // A role change outside the worker during the awaits above stops a retry,
412                // which the region keeps until it is a writable leader again.
413                if is_retry {
414                    self.keep_index_build_retry(request);
415                }
416                stopped = true;
417                break;
418            }
419
420            let mut result_senders = request.result_senders.clone();
421            result_senders.push(tx.clone());
422            let task = self.new_index_build_task(
423                &region,
424                &snapshot,
425                registry.clone(),
426                (file_handle, file_meta.as_ref().clone()),
427                request.build_type.clone(),
428                result_senders,
429            );
430            if is_retry {
431                self.index_build_scheduler
432                    .schedule_retry(&region.version_control, task)
433                    .await;
434            } else {
435                self.index_build_scheduler
436                    .schedule_build(&region.version_control, task)
437                    .await;
438            }
439        }
440        drop(tx);
441
442        // Wait for all index build tasks to finish and notify the caller.
443        common_runtime::spawn_global(async move {
444            let mut abort_reasons = Vec::new();
445            // The channel closes once every task has reported or been dropped.
446            while let Some(result) = rx.recv().await {
447                match result {
448                    Ok(IndexBuildOutcome::Finished) => {}
449                    Ok(IndexBuildOutcome::Aborted(reason)) => abort_reasons.push(reason),
450                    Err(e) => {
451                        warn!(e; "Index build task failed for region: {}", region_id);
452                        sender.send(Err(e));
453                        return;
454                    }
455                }
456            }
457
458            // The build covers the SSTs that existed when it was requested. A file
459            // removed meanwhile, e.g. replaced by compaction, counts as done: its
460            // replacement is indexed according to the compaction index options,
461            // as any later compaction would be.
462            let manifest = region.manifest_ctx.manifest().await;
463            let (present, removed): (Vec<_>, Vec<_>) = file_ids
464                .into_iter()
465                .partition(|file_id| manifest.files.contains_key(file_id));
466            if !removed.is_empty() && build_type == IndexBuildType::Manual {
467                warn!(
468                    "Files were removed during the manual index build, their replacements follow the compaction index options, region: {}, files: {:?}",
469                    region_id, removed
470                );
471            }
472            let incomplete = present
473                .into_iter()
474                .filter(|file_id| {
475                    let file = &manifest.files[file_id];
476                    !file.is_index_consistent_with_region(
477                        &snapshot.metadata.column_metadatas,
478                        &snapshot.index_options,
479                    ) || index_needs_rebuild(&registry, &snapshot, file, build_type.clone())
480                })
481                .collect::<Vec<_>>();
482            let result = if incomplete.is_empty() {
483                Ok(0)
484            } else {
485                // Background builds have no caller, and files they leave
486                // unindexed by configuration are expected.
487                if build_type == IndexBuildType::Manual {
488                    warn!(
489                        "Manual index build did not complete, region: {}, files: {:?}, aborted: {:?}",
490                        region_id, incomplete, abort_reasons
491                    );
492                }
493                IndexBuildIncompleteSnafu {
494                    region_id,
495                    file_ids: incomplete,
496                }
497                .fail()
498            };
499            sender.send(result);
500        });
501        stopped
502    }
503
504    /// Keeps an index build retry that the state of its region refused until the region is a
505    /// writable leader with its Leader lease. Its callers learn now that the build stopped,
506    /// rather than wait for the region.
507    fn keep_index_build_retry(&mut self, mut request: BuildIndexRequest) {
508        for sender in std::mem::take(&mut request.result_senders) {
509            let reason = "the region's state refused the retry".to_string();
510            let _ = sender.try_send(Ok(IndexBuildOutcome::Aborted(reason)));
511        }
512        let region_id = request.region_id;
513        let Some(region) = self.regions.get_region(region_id) else {
514            return;
515        };
516        info!(
517            "Region {region_id} is {:?} or awaits its Leader lease, keeping an index build retry",
518            region.state()
519        );
520        self.defer_lease_work(&region).retries.push(request);
521    }
522
523    pub(crate) async fn handle_index_build_finished(
524        &mut self,
525        region_id: RegionId,
526        request: IndexBuildFinished,
527    ) {
528        let region = match self.regions.get_region(region_id) {
529            Some(region) => region,
530            None => {
531                warn!(
532                    "Region not found for index build finished, region_id: {}",
533                    region_id
534                );
535                return;
536            }
537        };
538
539        let file_meta = request.file_meta;
540        let region_file_id = RegionFileId::new(file_meta.region_id, file_meta.file_id);
541        let index_id = RegionIndexId::new(region_file_id, file_meta.index_version);
542
543        // Clean old puffin-related cache before making the new metadata visible.
544        let cache_strategy = CacheStrategy::EnableAll(self.cache_manager.clone());
545        cache_strategy.evict_puffin_cache(index_id).await;
546
547        let manager = region.manifest_ctx.manifest_manager.read().await;
548        let manifest = manager.manifest();
549        let is_current =
550            manifest.files.get(&file_meta.file_id).map(AsRef::as_ref) == Some(&file_meta);
551        if is_current {
552            region.version_control.apply_edit(
553                Some(RegionEdit {
554                    files_to_add: vec![file_meta.clone()],
555                    files_to_remove: Vec::new(),
556                    timestamp_ms: None,
557                    flushed_sequence: None,
558                    flushed_entry_id: None,
559                    committed_sequence: None,
560                    compaction_time_window: None,
561                    ..Default::default()
562                }),
563                &[],
564                region.file_purger.clone(),
565            );
566        }
567        drop(manager);
568
569        let outcome = if is_current {
570            self.listener.on_index_build_finish(region_file_id).await;
571            IndexBuildOutcome::Finished
572        } else {
573            INDEX_PUBLICATION_STALE_TOTAL
574                .with_label_values(&["worker_apply"])
575                .inc();
576            warn!(
577                "Ignores stale index build result, region: {}, file_id: {}, index_version: {}, committed manifest version: {}",
578                region_id, file_meta.file_id, file_meta.index_version, request.manifest_version
579            );
580            cleanup_stale_index_caches(
581                index_id,
582                &region.access_layer,
583                Some(&self.cache_manager),
584                self.cache_manager.write_cache(),
585            )
586            .await;
587            self.listener.on_index_build_abort(region_file_id).await;
588            IndexBuildOutcome::Aborted(format!(
589                "Index publication was superseded before worker apply, region: {}, file_id: {}",
590                region_id, file_meta.file_id
591            ))
592        };
593        // Notify waiters after the version is updated, so queries issued after a
594        // manual build returns can use the new index. `try_send` keeps the worker
595        // loop from waiting on a caller; a missing result is caught by the
596        // waiter's manifest check.
597        for sender in &request.result_senders {
598            let _ = sender.try_send(Ok(outcome.clone()));
599        }
600    }
601
602    pub(crate) async fn handle_index_build_stopped(
603        &mut self,
604        region_id: RegionId,
605        request: IndexBuildStopped,
606    ) {
607        self.index_build_scheduler
608            .on_task_stopped(region_id, request.file_id);
609        self.listener
610            .on_index_build_stopped(RegionFileId::new(region_id, request.file_id))
611            .await;
612    }
613}
614
615/// Rejects invalid current options before selecting files or scheduling any task.
616fn validate_rebuild_plan(
617    registry: &IndexRegistry,
618    snapshot: &IndexBuildSnapshot,
619    build_type: IndexBuildType,
620) -> Result<()> {
621    // New SSTs need built-in indexes even when optional providers are unavailable.
622    // Explicit maintenance follows current options, allowing removed sketch options
623    // to discard their historical descriptors without requiring a provider.
624    if matches!(
625        build_type,
626        IndexBuildType::Manual | IndexBuildType::SchemaChange
627    ) {
628        registry
629            .validate_schema_kinds(&snapshot.metadata)
630            .with_context(|_| ExternalSnafu {
631                context: "validating index handlers for rebuild".to_string(),
632            })?;
633    }
634    let plan = registry.plan(&PlanContext {
635        metadata: &snapshot.metadata,
636        index_options: &snapshot.index_options,
637        build_type,
638        existing_indexes: &[],
639    });
640    plan.check_success().context(BuildIndexAsyncSnafu {
641        region_id: snapshot.metadata.region_id,
642    })
643}
644
645fn index_needs_rebuild(
646    registry: &IndexRegistry,
647    snapshot: &IndexBuildSnapshot,
648    file: &FileMeta,
649    build_type: IndexBuildType,
650) -> bool {
651    let context = PlanContext {
652        metadata: &snapshot.metadata,
653        index_options: &snapshot.index_options,
654        build_type,
655        existing_indexes: &file.indexes,
656    };
657    let plan = registry.plan(&context);
658    !plan.is_current(file, &context)
659}
660
661#[cfg(test)]
662mod tests {
663    use common_error::ext::ErrorExt;
664    use common_error::status_code::StatusCode;
665    use store_api::metadata::RegionMetadataBuilder;
666
667    use super::*;
668    use crate::sst::file::ColumnIndexMetadata;
669    use crate::sst::file_purger::NoopFilePurger;
670    use crate::sst::index::handler::{
671        BuildContext, IndexCreator, IndexKindHandler, PlanEntry, PlannedIndex,
672    };
673    use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
674    use crate::test_util::CreateRequestBuilder;
675
676    #[test]
677    fn test_whole_region_flush_build_leaves_files_with_extension_indexes() {
678        let request = CreateRequestBuilder::new().build_with_index();
679        let mut metadata = RegionMetadataBuilder::new(RegionId::new(1, 1));
680        metadata.primary_key(request.primary_key);
681        for column in request.column_metadatas {
682            metadata.push_column_metadata(column);
683        }
684        let snapshot = IndexBuildSnapshot {
685            metadata: Arc::new(metadata.build().unwrap()),
686            index_options: IndexOptions::default(),
687        };
688        let registry =
689            IndexRegistry::new(Default::default(), Default::default(), Default::default());
690        let sketched = FileMeta {
691            file_id: FileId::random(),
692            indexes: vec![ColumnIndexMetadata {
693                column_id: 0,
694                created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex],
695                ..Default::default()
696            }],
697            ..Default::default()
698        };
699        let plain = FileMeta {
700            file_id: FileId::random(),
701            ..Default::default()
702        };
703        let select = |build_type| {
704            let candidates = [&sketched, &plain]
705                .map(|file| {
706                    let handle = FileHandle::new(file.clone(), Arc::new(NoopFilePurger));
707                    (handle, FileMetaRef::from(file.clone()))
708                })
709                .to_vec();
710            select_whole_region_builds(candidates, &registry, &snapshot, &build_type)
711                .into_iter()
712                .map(|(_, file)| file.file_id)
713                .collect::<Vec<_>>()
714        };
715
716        assert_eq!(vec![plain.file_id], select(IndexBuildType::Flush));
717        assert_eq!(
718            vec![sketched.file_id, plain.file_id],
719            select(IndexBuildType::Manual)
720        );
721    }
722
723    #[derive(Debug)]
724    struct MaintenanceHandler;
725
726    impl IndexKindHandler for MaintenanceHandler {
727        fn kinds(&self) -> &[IndexKind] {
728            &[IndexKind::Extension(ExtensionIndexKind::Hll)]
729        }
730
731        fn validate(
732            &self,
733            _context: &PlanContext<'_>,
734        ) -> std::result::Result<(), common_error::ext::BoxedError> {
735            Ok(())
736        }
737
738        fn plan(
739            &self,
740            context: &PlanContext<'_>,
741        ) -> std::result::Result<Option<Arc<dyn PlannedIndex>>, common_error::ext::BoxedError>
742        {
743            let existing = context.existing_indexes.iter().any(|column| {
744                column
745                    .created_indexes
746                    .contains(&crate::sst::file::IndexType::HllIndex)
747            });
748            Ok((existing
749                && matches!(
750                    context.build_type,
751                    IndexBuildType::Manual | IndexBuildType::SchemaChange
752                ))
753            .then(|| Arc::new(Self) as Arc<dyn PlannedIndex>))
754        }
755    }
756
757    #[async_trait::async_trait]
758    impl PlannedIndex for MaintenanceHandler {
759        fn kinds(&self) -> &[IndexKind] {
760            IndexKindHandler::kinds(self)
761        }
762
763        fn entries(&self) -> &[PlanEntry] {
764            &[]
765        }
766
767        async fn build(
768            &self,
769            _context: &BuildContext<'_>,
770        ) -> std::result::Result<Option<Box<dyn IndexCreator>>, common_error::ext::BoxedError>
771        {
772            Ok(None)
773        }
774
775        fn is_current(&self, _file: &FileMeta, _context: &PlanContext<'_>) -> bool {
776            false
777        }
778    }
779
780    fn snapshot_without_builtin_indexes() -> IndexBuildSnapshot {
781        let request = CreateRequestBuilder::new().build();
782        let mut metadata = RegionMetadataBuilder::new(RegionId::new(1, 1));
783        metadata.primary_key(request.primary_key);
784        for mut column in request.column_metadatas {
785            column.column_schema.set_inverted_index(false);
786            column.column_schema.unset_skipping_options().unwrap();
787            metadata.push_column_metadata(column);
788        }
789        IndexBuildSnapshot {
790            metadata: Arc::new(metadata.build().unwrap()),
791            index_options: IndexOptions::default(),
792        }
793    }
794
795    #[test]
796    fn test_rebuild_selection_uses_registered_currency_and_empty_maintenance_plans() {
797        let snapshot = snapshot_without_builtin_indexes();
798        let builtin =
799            IndexRegistry::new(Default::default(), Default::default(), Default::default());
800        let mut registered = builtin.clone();
801        registered.register(Arc::new(MaintenanceHandler)).unwrap();
802        let empty = FileMeta::default();
803        let mut existing = empty.clone();
804        existing.indexes.push(ColumnIndexMetadata {
805            column_id: 0,
806            created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex],
807            ..Default::default()
808        });
809        // Missing owners are rejected before selection; currency only compares
810        // the plans of registered handlers with the persisted indexes.
811        assert!(
812            builtin
813                .validate_required_kinds(&snapshot.metadata, [&existing])
814                .is_err()
815        );
816        for reason in [IndexBuildType::Manual, IndexBuildType::SchemaChange] {
817            assert!(!index_needs_rebuild(
818                &registered,
819                &snapshot,
820                &empty,
821                reason.clone()
822            ));
823            assert!(
824                index_needs_rebuild(&registered, &snapshot, &existing, reason),
825                "an explicit empty maintenance plan still requests publication"
826            );
827        }
828        for reason in [IndexBuildType::Flush, IndexBuildType::Compact] {
829            assert!(!index_needs_rebuild(
830                &registered,
831                &snapshot,
832                &existing,
833                reason
834            ));
835        }
836    }
837
838    #[derive(Debug)]
839    struct FailingPlanHandler;
840
841    impl IndexKindHandler for FailingPlanHandler {
842        fn kinds(&self) -> &[IndexKind] {
843            &[IndexKind::Extension(ExtensionIndexKind::Hll)]
844        }
845
846        fn validate(
847            &self,
848            _context: &PlanContext<'_>,
849        ) -> std::result::Result<(), common_error::ext::BoxedError> {
850            Ok(())
851        }
852
853        fn plan(
854            &self,
855            _context: &PlanContext<'_>,
856        ) -> std::result::Result<Option<Arc<dyn PlannedIndex>>, common_error::ext::BoxedError>
857        {
858            Err(common_error::ext::BoxedError::new(
859                common_error::ext::PlainError::new(
860                    "injected plan failure".into(),
861                    common_error::status_code::StatusCode::Internal,
862                ),
863            ))
864        }
865    }
866
867    #[test]
868    fn test_failed_plan_requires_rebuild_even_without_planned_entries() {
869        let snapshot = snapshot_without_builtin_indexes();
870        let mut registry =
871            IndexRegistry::new(Default::default(), Default::default(), Default::default());
872        registry.register(Arc::new(FailingPlanHandler)).unwrap();
873        let file = FileMeta {
874            indexes: vec![ColumnIndexMetadata {
875                column_id: 0,
876                created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex],
877                ..Default::default()
878            }],
879            ..Default::default()
880        };
881        assert!(
882            registry
883                .validate_required_kinds(&snapshot.metadata, [&file])
884                .is_ok()
885        );
886        for reason in [IndexBuildType::Manual, IndexBuildType::SchemaChange] {
887            let plan = registry.plan(&PlanContext {
888                metadata: &snapshot.metadata,
889                index_options: &snapshot.index_options,
890                build_type: reason.clone(),
891                existing_indexes: &file.indexes,
892            });
893            assert!(plan.entries().next().is_none());
894            assert!(plan.check_success().is_err());
895            assert!(index_needs_rebuild(&registry, &snapshot, &file, reason));
896        }
897    }
898
899    #[derive(Debug)]
900    struct DuplicateKindProvider;
901
902    impl crate::sst::index::handler::IndexKindProvider for DuplicateKindProvider {
903        fn handlers(&self) -> Vec<Arc<dyn IndexKindHandler>> {
904            vec![Arc::new(MaintenanceHandler), Arc::new(MaintenanceHandler)]
905        }
906    }
907
908    #[test]
909    fn test_rebuild_registry_registration_failure_is_not_provider_absence() {
910        let config = crate::config::MitoConfig::default();
911        assert!(index_registry(&config, None).is_ok());
912        let error = index_registry(&config, Some(Arc::new(DuplicateKindProvider))).unwrap_err();
913        assert_eq!(error.status_code(), StatusCode::InvalidArguments);
914        assert!(error.to_string().contains("registering index handlers"));
915    }
916
917    #[test]
918    fn test_rebuild_preflight_rejects_plan_failure_before_file_selection() {
919        let snapshot = snapshot_without_builtin_indexes();
920        let mut registry =
921            IndexRegistry::new(Default::default(), Default::default(), Default::default());
922        assert!(validate_rebuild_plan(&registry, &snapshot, IndexBuildType::Manual).is_ok());
923        registry.register(Arc::new(FailingPlanHandler)).unwrap();
924        assert!(validate_rebuild_plan(&registry, &snapshot, IndexBuildType::Manual).is_err());
925    }
926
927    #[test]
928    fn test_required_handlers_cover_schema_and_both_persisted_locations() {
929        use crate::sst::file::IndexType;
930        let registry =
931            IndexRegistry::new(Default::default(), Default::default(), Default::default());
932        for kind in [IndexType::HllIndex, IndexType::KllIndex, IndexType::MgIndex] {
933            let mut snapshot = snapshot_without_builtin_indexes();
934            let schema =
935                &mut Arc::make_mut(&mut snapshot.metadata).column_metadatas[0].column_schema;
936            let (key, value) = match kind {
937                IndexType::HllIndex => (datatypes::schema::HLL_KEY, r#"{"precision":10}"#),
938                IndexType::KllIndex => (datatypes::schema::KLL_KEY, r#"{"capacity":64}"#),
939                IndexType::MgIndex => (datatypes::schema::MG_KEY, r#"{"capacity":64}"#),
940                _ => unreachable!(),
941            };
942            schema.mut_metadata().insert(key.into(), value.into());
943            assert!(
944                registry
945                    .validate_required_kinds(&snapshot.metadata, [])
946                    .is_err()
947            );
948            assert!(validate_rebuild_plan(&registry, &snapshot, IndexBuildType::Manual).is_err());
949            assert!(
950                registry
951                    .plan(&PlanContext {
952                        metadata: &snapshot.metadata,
953                        index_options: &snapshot.index_options,
954                        build_type: IndexBuildType::Flush,
955                        existing_indexes: &[],
956                    })
957                    .check_success()
958                    .is_ok()
959            );
960            let snapshot = snapshot_without_builtin_indexes();
961            for column_level in [false, true] {
962                let mut file = FileMeta::default();
963                if column_level {
964                    file.indexes.push(ColumnIndexMetadata {
965                        column_id: 0,
966                        created_indexes: smallvec::smallvec![kind],
967                        ..Default::default()
968                    });
969                } else {
970                    file.available_indexes.push(kind);
971                }
972                // Historical descriptors alone do not require the provider.
973                assert!(
974                    validate_rebuild_plan(&registry, &snapshot, IndexBuildType::Manual).is_ok()
975                );
976                assert!(index_needs_rebuild(
977                    &registry,
978                    &snapshot,
979                    &file,
980                    IndexBuildType::Manual
981                ));
982                // Compaction's strict input validation remains available to its writer.
983                assert!(
984                    registry
985                        .validate_required_kinds(&snapshot.metadata, [&file])
986                        .is_err()
987                );
988            }
989        }
990        let snapshot = snapshot_without_builtin_indexes();
991        let legacy = FileMeta {
992            available_indexes: smallvec::smallvec![IndexType::VectorIndex],
993            ..Default::default()
994        };
995        assert!(validate_rebuild_plan(&registry, &snapshot, IndexBuildType::Manual).is_ok());
996        assert!(
997            registry
998                .validate_required_kinds(&snapshot.metadata, [&legacy])
999                .is_ok()
1000        );
1001    }
1002}