Skip to main content

mito2/sst/index/
handler.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//! Planning and creation contracts for built-in and injected indexes.
16
17pub(crate) mod builtin;
18
19use std::fmt::Debug;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use common_error::ext::BoxedError;
24use datatypes::arrow::record_batch::RecordBatch;
25use index::target::IndexTarget;
26use store_api::metadata::RegionMetadataRef;
27use store_api::storage::ColumnId;
28
29use crate::read::Batch;
30use crate::region::options::IndexOptions;
31use crate::sst::file::{ColumnIndexMetadata, FileHandle, FileMeta, RegionIndexId};
32use crate::sst::index::intermediate::IntermediateManager;
33use crate::sst::index::kind::IndexKind;
34use crate::sst::index::puffin_manager::{SstPuffinManager, SstPuffinWriter};
35use crate::sst::index::{CompletedEntry, IndexBuildType};
36
37/// A requested column format; typed implementation parameters stay in its plan.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct PlanEntry {
40    /// Column to index.
41    pub column_id: ColumnId,
42    /// Implementation owning this entry.
43    pub kind: IndexKind,
44    /// Requested format version. The manifest records extension types, not versions.
45    /// A format upgrade requires a forced rebuild; the provider validates Puffin
46    /// properties and payload compatibility before reusing input state.
47    pub format_version: u32,
48}
49
50/// Schema and options used to prepare work without reading input files.
51pub struct PlanContext<'a> {
52    /// Shared region schema.
53    pub metadata: &'a RegionMetadataRef,
54    /// Region index options.
55    pub index_options: &'a IndexOptions,
56    /// Lifecycle event requesting the build.
57    pub build_type: IndexBuildType,
58    /// Existing column descriptors of the target SST during rebuild.
59    /// Empty for new outputs, including compaction; input descriptors are available
60    /// through [`BuildContext::inputs`] when constructing a creator.
61    pub existing_indexes: &'a [ColumnIndexMetadata],
62}
63
64/// Inputs for constructing all of one handler's indexes in a single output file.
65pub struct BuildContext<'a> {
66    /// Shared output schema.
67    pub metadata: &'a RegionMetadataRef,
68    /// Physical output index identity.
69    pub output: RegionIndexId,
70    /// Output manager, possibly backed by a local write cache.
71    pub puffin_manager: &'a SstPuffinManager,
72    /// Existing intermediate-file facility shared by built-in creators.
73    pub intermediate_manager: &'a IntermediateManager,
74    /// Pinned physical input files.
75    pub inputs: &'a [FileHandle],
76    /// Manager for reading persisted input indexes. With no inputs this falls back
77    /// to the output manager; determine input availability from `inputs.is_empty()`.
78    pub input_puffin_manager: &'a SstPuffinManager,
79    /// Permits coarse input-summary reuse only for a complete single output.
80    /// The caller that owns the output plan verifies this scope before construction.
81    pub can_merge_inputs: bool,
82    /// Retained-memory allowance for an injected creator, capped by the remaining
83    /// operation budget and its plan ceiling. `None` applies no limit at this layer.
84    /// Built-in creators use spill budgets.
85    pub memory_limit: Option<usize>,
86    /// Row count of the output's row groups, except the last, when the writer knows it.
87    pub row_group_size: Option<usize>,
88    /// Exact row count when rebuilding an existing SST; unknown for compaction outputs.
89    pub output_rows: Option<u64>,
90}
91
92/// Shared plugin installed by the embedding application.
93pub type IndexKindProviderRef = Arc<dyn IndexKindProvider>;
94
95/// Supplies extension handlers while the engine retains the complete lifecycle.
96pub trait IndexKindProvider: Send + Sync + Debug {
97    /// Related algorithms may share one handler to reuse row traversal.
98    fn handlers(&self) -> Vec<Arc<dyn IndexKindHandler>>;
99}
100
101/// Owns one or more related kinds that can share preparation and row traversal.
102pub trait IndexKindHandler: Send + Sync + Debug {
103    /// Nonempty, unique kinds exclusively owned by this handler. A group must be
104    /// entirely built-in or entirely extension kinds.
105    fn kinds(&self) -> &[IndexKind];
106
107    /// Validates options at region creation independently of whether this lifecycle
108    /// event builds indexes. Implementations must not skip validation based on
109    /// `context.build_type`.
110    fn validate(&self, context: &PlanContext<'_>) -> Result<(), BoxedError>;
111
112    /// Prepares typed parameters. `None` means no work; an empty entry list may
113    /// still request removal of obsolete descriptors during maintenance.
114    fn plan(&self, context: &PlanContext<'_>) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError>;
115}
116
117/// An immutable typed plan shared by output files of an operation.
118#[async_trait]
119pub trait PlannedIndex: Send + Sync + Debug {
120    /// Nonempty, unique subset of the handler's kinds, including removal plans.
121    fn kinds(&self) -> &[IndexKind];
122
123    /// Requested column formats. Every entry kind must belong to this plan.
124    fn entries(&self) -> &[PlanEntry];
125
126    /// Prepares input reuse before any output batch is consumed.
127    async fn build(
128        &self,
129        context: &BuildContext<'_>,
130    ) -> Result<Option<Box<dyn IndexCreator>>, BoxedError>;
131
132    /// Whether persisted entries satisfy this plan.
133    /// The context uses the same file's indexes as the planning input.
134    fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool;
135
136    /// Whether building this plan can reuse persisted input summaries.
137    /// Row-only plans do not require checking input object existence.
138    fn needs_input_reuse(&self) -> bool {
139        false
140    }
141
142    /// Optional hard ceiling; built-in creators use their existing spill budgets.
143    fn memory_limit(&self) -> Option<usize> {
144        None
145    }
146}
147
148/// Accumulates rows and writes blobs into the engine-owned Puffin lifecycle.
149/// Implementations release retained state on drop, including cancellation.
150#[async_trait]
151pub trait IndexCreator: Send {
152    /// Whether rebuilding this index requires scanning SST rows after preparation.
153    /// A creator reusing persisted state must account for output rows without updates.
154    fn requires_row_scan(&self) -> bool {
155        true
156    }
157
158    /// Borrows a batch and its reusable primary-key decode cache.
159    async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError>;
160
161    /// Borrows array data; cloning shared array handles is allowed.
162    async fn update_flat(&mut self, batch: &RecordBatch) -> Result<(), BoxedError>;
163
164    /// Writes completed entries. Publication waits for the engine to close Puffin.
165    /// The creator is dropped afterward, including on error, without calling its
166    /// `abort` method; implementations must finalize their own temporary resources.
167    async fn finish(
168        &mut self,
169        writer: &mut SstPuffinWriter,
170    ) -> Result<Vec<CompletedEntry>, BoxedError>;
171
172    /// Releases temporary resources; the engine owns final-file cleanup.
173    async fn abort(&mut self) -> Result<(), BoxedError>;
174
175    /// Estimated retained memory, not exact allocator or process RSS accounting.
176    fn memory_usage(&self) -> usize;
177
178    /// Targets needed when preparing the shared dense primary-key decoder.
179    fn indexed_targets(&self) -> Vec<IndexTarget> {
180        Vec::new()
181    }
182
183    /// Whether this creator participates in existing dense-key predecoding.
184    fn needs_dense_pk(&self) -> bool {
185        false
186    }
187}