mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
feat(mito2): wire index plugins into compaction and rebuild
Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
@@ -86,6 +86,14 @@ pending. DDL cancellation retains its existing scheduling fence and priority.
|
||||
`tests/compatibility/manifest/table_compaction/` and
|
||||
`tests/compatibility/manifest/pending_tails/`.
|
||||
- **SST/Parquet layout** (`sst/`): readers must stay compatible with existing files.
|
||||
- **Compaction index extensions** (`sst/index/handler.rs`, `sst/index/registry.rs`): enterprise providers use
|
||||
the existing borrowed-batch and Puffin writer lifecycle. Publish column-level sketch descriptors
|
||||
only after successful file finish; index rebuilds maintain existing sketches
|
||||
through the provider before replacing the Puffin version. Rebuild retains the old version on
|
||||
provider failure; operation entry points reject missing providers required by schema options or input descriptors before file I/O.
|
||||
Typed sketch options are enterprise-gated; metadata keys and extension contracts are shared by both builds. Fully reused indexes
|
||||
with known output counts can skip the rebuild row scan. Multi-output or filtered compaction builds from
|
||||
output rows rather than reusing whole-input summaries.
|
||||
- **Series-index disk limit**: tasks estimate usage from entry sizes in open-region snapshots
|
||||
and defer new builds when the shared estimate is full. Cleanup still prunes obsolete
|
||||
range entries and expires series indexes to reclaim published usage. Concurrent builds may
|
||||
|
||||
@@ -400,6 +400,10 @@ impl AccessLayer {
|
||||
metrics: &mut Metrics,
|
||||
context: Option<crate::sst::parquet::writer::SstWriteContext>,
|
||||
) -> Result<SstInfoArray> {
|
||||
let mut request = request;
|
||||
if let Some(provider) = &mut request.index_build_inputs {
|
||||
provider.can_merge_inputs &= write_opts.max_file_size.is_none();
|
||||
}
|
||||
let limits = context.as_ref().map(|context| context.limits);
|
||||
let guard = context.map(|context| context.guard);
|
||||
let op_type = request.op_type;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -26,7 +27,7 @@ use itertools::Itertools;
|
||||
use object_store::manager::ObjectStoreManagerRef;
|
||||
use partition::expr::PartitionExpr;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use snafu::{IntoError, OptionExt, ResultExt, ensure};
|
||||
use store_api::ManifestVersion;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::region_request::PathType;
|
||||
@@ -53,10 +54,14 @@ use crate::region::version::VersionRef;
|
||||
use crate::region::{ManifestContext, RegionLeaderState, RegionRoleState};
|
||||
use crate::schedule::scheduler::LocalScheduler;
|
||||
use crate::sst::FormatType;
|
||||
use crate::sst::file::{self, FileHandle, FileMeta, UncommittedSsts};
|
||||
use crate::sst::file::{self, FileHandle, FileMeta, RegionFileId, UncommittedSsts};
|
||||
use crate::sst::file_purger::LocalFilePurger;
|
||||
use crate::sst::index::IndexBuildType;
|
||||
use crate::sst::index::build::IndexBuildInputs;
|
||||
use crate::sst::index::handler::{IndexKindProviderRef, PlanContext};
|
||||
use crate::sst::index::intermediate::IntermediateManager;
|
||||
use crate::sst::index::puffin_manager::PuffinManagerFactory;
|
||||
use crate::sst::index::registry::{IndexBuildPlan, IndexRegistry};
|
||||
use crate::sst::location::region_dir_from_table_dir;
|
||||
use crate::sst::parquet::metadata::extract_primary_key_range;
|
||||
use crate::sst::parquet::parallel_writer::EncodeRuntime;
|
||||
@@ -143,10 +148,39 @@ pub struct CompactionContext {
|
||||
pub(crate) access_layer: AccessLayerRef,
|
||||
manifest_ctx: Arc<ManifestContext>,
|
||||
plugins: Plugins,
|
||||
index_plan: Arc<IndexBuildPlan>,
|
||||
index_registry: Arc<IndexRegistry>,
|
||||
/// Context assembly is infallible; report registration/planning errors at merge entry.
|
||||
planning_error: Option<Arc<error::Error>>,
|
||||
existing_index_inputs: Option<Arc<HashSet<RegionFileId>>>,
|
||||
}
|
||||
|
||||
impl From<&CompactionRegion> for CompactionContext {
|
||||
fn from(region: &CompactionRegion) -> Self {
|
||||
let registry = IndexRegistry::new(
|
||||
region.engine_config.inverted_index.clone(),
|
||||
region.engine_config.fulltext_index.clone(),
|
||||
region.engine_config.bloom_filter_index.clone(),
|
||||
);
|
||||
let mut planning_error = None;
|
||||
let registry = registry
|
||||
.clone()
|
||||
.with_provider(region.plugins.get::<IndexKindProviderRef>())
|
||||
.unwrap_or_else(|err| {
|
||||
planning_error = Some(Arc::new(
|
||||
error::ExternalSnafu {
|
||||
context: "compaction index registration".to_string(),
|
||||
}
|
||||
.into_error(err),
|
||||
));
|
||||
registry
|
||||
});
|
||||
let index_plan = Arc::new(registry.plan(&PlanContext {
|
||||
metadata: ®ion.region_metadata,
|
||||
index_options: ®ion.current_version.options.index_options,
|
||||
build_type: IndexBuildType::Compact,
|
||||
existing_indexes: &[],
|
||||
}));
|
||||
Self {
|
||||
region_id: region.region_id,
|
||||
region_options: region.region_options.clone(),
|
||||
@@ -157,6 +191,10 @@ impl From<&CompactionRegion> for CompactionContext {
|
||||
access_layer: region.access_layer.clone(),
|
||||
manifest_ctx: region.manifest_ctx.clone(),
|
||||
plugins: region.plugins.clone(),
|
||||
index_plan,
|
||||
index_registry: Arc::new(registry),
|
||||
planning_error,
|
||||
existing_index_inputs: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -391,6 +429,58 @@ impl CompactionRegion {
|
||||
}
|
||||
|
||||
impl CompactionContext {
|
||||
/// Rejects missing configured or persisted index handlers before file I/O.
|
||||
/// This check is independent of plan failures: an absent handler produces no plan.
|
||||
fn validate_index_plan<'a>(&self, inputs: impl Iterator<Item = &'a FileHandle>) -> Result<()> {
|
||||
if let Some(error) = &self.planning_error {
|
||||
return Err(error::CompactRegionSnafu {
|
||||
region_id: self.region_id,
|
||||
}
|
||||
.into_error(error.clone()));
|
||||
}
|
||||
self.index_registry
|
||||
.validate_required_kinds(&self.region_metadata, inputs.map(FileHandle::meta_ref))
|
||||
.with_context(|_| error::ExternalSnafu {
|
||||
context: "compaction index planning".to_string(),
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks each physical input once before output tasks begin. Missing inputs
|
||||
/// disable imported summaries without changing the reader's tolerant behavior.
|
||||
async fn prepare_index_inputs<'a>(&mut self, inputs: impl Iterator<Item = &'a FileHandle>) {
|
||||
if !self.index_plan.needs_input_reuse()
|
||||
|| self
|
||||
.region_metadata
|
||||
.partition_expr
|
||||
.as_deref()
|
||||
.is_some_and(|expr| !expr.is_empty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let mut existing = HashSet::new();
|
||||
for input in inputs {
|
||||
let id = input.file_id();
|
||||
if !seen.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let path = crate::sst::location::sst_file_path(
|
||||
self.access_layer.table_dir(),
|
||||
id,
|
||||
self.access_layer.path_type(),
|
||||
);
|
||||
if matches!(
|
||||
self.access_layer.object_store().exists(&path).await,
|
||||
Ok(true)
|
||||
) {
|
||||
existing.insert(id);
|
||||
}
|
||||
}
|
||||
// FileHandles protect ordinary purge; external object-store deletion can race.
|
||||
self.existing_index_inputs = Some(Arc::new(existing));
|
||||
}
|
||||
|
||||
/// Reports this unit's output metadata before publishing its manifest edit.
|
||||
pub(crate) async fn invoke_sst_hook(&self, merge_output: &MergeOutput) {
|
||||
let Some(hook) = self.plugins.get::<RegionHookRef>() else {
|
||||
@@ -645,6 +735,39 @@ impl SstMerger for DefaultSstMerger {
|
||||
merge_mode,
|
||||
read_parallelism: write_opts.encode_parallelism,
|
||||
};
|
||||
// A region filter, rollover or time slice requires output-scoped accumulation.
|
||||
let no_region_filter = context
|
||||
.region_metadata
|
||||
.partition_expr
|
||||
.as_deref()
|
||||
.is_none_or(str::is_empty);
|
||||
let can_merge_inputs = write_opts.max_file_size.is_none()
|
||||
&& output.output_time_range.is_none()
|
||||
&& no_region_filter
|
||||
&& context
|
||||
.existing_index_inputs
|
||||
.as_ref()
|
||||
.is_some_and(|existing| {
|
||||
output
|
||||
.inputs
|
||||
.iter()
|
||||
.all(|input| existing.contains(&input.file_id()))
|
||||
});
|
||||
let index_build_inputs = Some(IndexBuildInputs {
|
||||
output_rows: None,
|
||||
plan: context.index_plan.clone(),
|
||||
memory_limit: None,
|
||||
inputs: if context.index_plan.needs_input_reuse() {
|
||||
output.inputs.clone().into()
|
||||
} else {
|
||||
Arc::from([])
|
||||
},
|
||||
input_puffin_manager: context
|
||||
.access_layer
|
||||
.build_puffin_manager()
|
||||
.with_puffin_metadata_cache(context.cache_manager.puffin_metadata_cache().cloned()),
|
||||
can_merge_inputs,
|
||||
});
|
||||
let source = spawn_merge(builder.build_flat_sst_reader().await?);
|
||||
|
||||
let mut metrics = Metrics::new(WriteType::Compaction);
|
||||
@@ -653,7 +776,7 @@ impl SstMerger for DefaultSstMerger {
|
||||
.access_layer
|
||||
.write_sst(
|
||||
SstWriteRequest {
|
||||
index_build_inputs: None,
|
||||
index_build_inputs,
|
||||
op_type: OperationType::Compact,
|
||||
metadata: region_metadata.clone(),
|
||||
source,
|
||||
@@ -791,6 +914,16 @@ impl<M: SstMerger> DefaultCompactor<M> {
|
||||
context: &CompactionContext,
|
||||
unit: &CompactionUnit,
|
||||
) -> Result<MergeOutput> {
|
||||
context.validate_index_plan(unit.inputs.iter())?;
|
||||
let mut context = context.clone();
|
||||
if unit.max_file_size.is_none()
|
||||
&& unit
|
||||
.outputs
|
||||
.iter()
|
||||
.any(|output| output.output_time_range.is_none())
|
||||
{
|
||||
context.prepare_index_inputs(unit.inputs.iter()).await;
|
||||
}
|
||||
let mut result = MergeOutput {
|
||||
files_to_remove: unit.inputs.iter().map(|f| f.meta_ref().clone()).collect(),
|
||||
compaction_time_window: Some(unit.time_window_size),
|
||||
@@ -862,7 +995,24 @@ where
|
||||
let internal_parallelism = compaction_region.max_parallelism.max(1);
|
||||
let compaction_time_window = picker_output.time_window_size;
|
||||
let region_id = compaction_region.region_id;
|
||||
let context = CompactionContext::from(compaction_region);
|
||||
let mut context = CompactionContext::from(compaction_region);
|
||||
context.validate_index_plan(
|
||||
picker_output
|
||||
.outputs
|
||||
.iter()
|
||||
.flat_map(|output| output.inputs.iter()),
|
||||
)?;
|
||||
if picker_output.max_file_size.is_none() {
|
||||
context
|
||||
.prepare_index_inputs(
|
||||
picker_output
|
||||
.outputs
|
||||
.iter()
|
||||
.filter(|output| output.output_time_range.is_none())
|
||||
.flat_map(|output| output.inputs.iter()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Build tasks along with their input file metas so we can track which
|
||||
// inputs correspond to each task.
|
||||
@@ -1025,6 +1175,110 @@ mod tests {
|
||||
FileHandle::new(meta, Arc::new(NoopFilePurger))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InputReusePlan;
|
||||
|
||||
impl crate::sst::index::handler::IndexKindHandler for InputReusePlan {
|
||||
fn kinds(&self) -> &[crate::sst::index::kind::IndexKind] {
|
||||
&[crate::sst::index::kind::IndexKind::Extension(
|
||||
crate::sst::index::kind::ExtensionIndexKind::Hll,
|
||||
)]
|
||||
}
|
||||
|
||||
fn plan(
|
||||
&self,
|
||||
_context: &PlanContext<'_>,
|
||||
) -> std::result::Result<
|
||||
Option<Arc<dyn crate::sst::index::handler::PlannedIndex>>,
|
||||
common_error::ext::BoxedError,
|
||||
> {
|
||||
Ok(Some(Arc::new(Self)))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl crate::sst::index::handler::PlannedIndex for InputReusePlan {
|
||||
fn kinds(&self) -> &[crate::sst::index::kind::IndexKind] {
|
||||
crate::sst::index::handler::IndexKindHandler::kinds(self)
|
||||
}
|
||||
|
||||
fn entries(&self) -> &[crate::sst::index::handler::PlanEntry] {
|
||||
&[]
|
||||
}
|
||||
|
||||
fn needs_input_reuse(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
async fn build(
|
||||
&self,
|
||||
_context: &crate::sst::index::handler::BuildContext<'_>,
|
||||
) -> std::result::Result<
|
||||
Option<Box<dyn crate::sst::index::handler::IndexCreator>>,
|
||||
common_error::ext::BoxedError,
|
||||
> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn is_current(
|
||||
&self,
|
||||
_file: &FileMeta,
|
||||
_context: &crate::sst::index::handler::CurrencyContext<'_>,
|
||||
) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_index_input_preparation_tracks_physical_files() {
|
||||
let mut region = new_test_compaction_region().await;
|
||||
Arc::make_mut(&mut region.region_metadata).column_metadatas[0]
|
||||
.column_schema
|
||||
.set_inverted_index(true);
|
||||
let mut context = CompactionContext::from(®ion);
|
||||
assert!(context.existing_index_inputs.is_none());
|
||||
// Builtin plans do not probe physical inputs solely for optional reuse.
|
||||
context.prepare_index_inputs(std::iter::empty()).await;
|
||||
assert!(context.existing_index_inputs.is_none());
|
||||
let mut registry =
|
||||
IndexRegistry::new(Default::default(), Default::default(), Default::default());
|
||||
registry.register(Arc::new(InputReusePlan)).unwrap();
|
||||
context.index_plan = Arc::new(registry.plan(&PlanContext {
|
||||
metadata: &context.region_metadata,
|
||||
index_options: &context.version_options.index_options,
|
||||
build_type: IndexBuildType::Compact,
|
||||
existing_indexes: &[],
|
||||
}));
|
||||
let present = new_file_handle(dummy_file_meta());
|
||||
let missing = new_file_handle(dummy_file_meta());
|
||||
let path = crate::sst::location::sst_file_path(
|
||||
context.access_layer.table_dir(),
|
||||
present.file_id(),
|
||||
context.access_layer.path_type(),
|
||||
);
|
||||
context
|
||||
.access_layer
|
||||
.object_store()
|
||||
.write(&path, vec![1])
|
||||
.await
|
||||
.unwrap();
|
||||
// Duplicate references are checked as one physical input. Only successfully
|
||||
// probed files can contribute imported summaries to an output.
|
||||
context
|
||||
.prepare_index_inputs([&present, &missing, &present].into_iter())
|
||||
.await;
|
||||
assert_eq!(
|
||||
context.existing_index_inputs.as_deref(),
|
||||
Some(&HashSet::from([present.file_id()]))
|
||||
);
|
||||
let prepared = context.clone();
|
||||
assert!(Arc::ptr_eq(
|
||||
context.existing_index_inputs.as_ref().unwrap(),
|
||||
prepared.existing_index_inputs.as_ref().unwrap()
|
||||
));
|
||||
assert!(Arc::ptr_eq(&context.index_plan, &prepared.index_plan));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_effective_target_trust_and_max_sequence() {
|
||||
let target = RegionId::new(1, 1);
|
||||
@@ -1402,6 +1656,14 @@ mod tests {
|
||||
access_layer: region.access_layer.clone(),
|
||||
manifest_ctx: region.manifest_ctx.clone(),
|
||||
plugins: Plugins::new(),
|
||||
index_plan: Arc::default(),
|
||||
index_registry: Arc::new(IndexRegistry::new(
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
)),
|
||||
planning_error: None,
|
||||
existing_index_inputs: None,
|
||||
};
|
||||
region
|
||||
.access_layer
|
||||
@@ -1537,6 +1799,107 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_missing_index_handler_blocks_configured_and_persisted_kinds() {
|
||||
use api::v1::SemanticType;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{
|
||||
ColumnSchema, FulltextOptions, SkippingIndexOptions, SkippingIndexType,
|
||||
};
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
|
||||
|
||||
use crate::sst::file::{ColumnIndexMetadata, IndexType};
|
||||
use crate::sst::index::kind::IndexKind;
|
||||
|
||||
for required_by in ["none", "schema", "file", "column"] {
|
||||
let mut region = new_test_compaction_region().await;
|
||||
Arc::make_mut(&mut region.region_metadata).column_metadatas[0]
|
||||
.column_schema
|
||||
.set_inverted_index(true);
|
||||
let mut metadata =
|
||||
RegionMetadataBuilder::from_existing((*region.region_metadata).clone());
|
||||
metadata.push_column_metadata(ColumnMetadata {
|
||||
column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), true)
|
||||
.with_fulltext_options(FulltextOptions {
|
||||
enable: true,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap()
|
||||
.with_skipping_options(SkippingIndexOptions::new_unchecked(
|
||||
42,
|
||||
0.01,
|
||||
SkippingIndexType::BloomFilter,
|
||||
))
|
||||
.unwrap(),
|
||||
semantic_type: SemanticType::Field,
|
||||
column_id: 5,
|
||||
});
|
||||
region.region_metadata = Arc::new(metadata.build().unwrap());
|
||||
let context = CompactionContext::from(®ion);
|
||||
assert_eq!(
|
||||
context
|
||||
.index_plan
|
||||
.planned()
|
||||
.iter()
|
||||
.flat_map(|plan| plan.kinds().iter().copied())
|
||||
.collect::<Vec<_>>(),
|
||||
[IndexKind::Inverted, IndexKind::Fulltext, IndexKind::Bloom]
|
||||
);
|
||||
let mut input = dummy_file_meta();
|
||||
match required_by {
|
||||
"schema" => {
|
||||
Arc::make_mut(&mut region.region_metadata).column_metadatas[0]
|
||||
.column_schema
|
||||
.mut_metadata()
|
||||
.insert(
|
||||
datatypes::schema::HLL_KEY.into(),
|
||||
r#"{"precision":10}"#.into(),
|
||||
);
|
||||
}
|
||||
"file" => input.available_indexes.push(IndexType::HllIndex),
|
||||
"column" => input.indexes.push(ColumnIndexMetadata {
|
||||
column_id: 0,
|
||||
created_indexes: [IndexType::HllIndex].into_iter().collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
_ => {}
|
||||
}
|
||||
let output = PickerOutput {
|
||||
outputs: vec![CompactionOutput {
|
||||
output_level: 1,
|
||||
inputs: vec![new_file_handle(input)],
|
||||
filter_deleted: false,
|
||||
output_time_range: None,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
for local in [false, true] {
|
||||
let merger = MockMerger::new(vec![Ok(Vec::new())]);
|
||||
let calls = merger.call_idx.clone();
|
||||
let compactor = DefaultCompactor::with_merger(merger);
|
||||
let result = if local {
|
||||
let context = CompactionContext::from(®ion);
|
||||
let unit = CompactionUnit::from_picker(output.clone())
|
||||
.unwrap()
|
||||
.pop()
|
||||
.unwrap();
|
||||
compactor.merge_unit(&context, &unit).await
|
||||
} else {
|
||||
compactor.merge_ssts(®ion, output.clone()).await
|
||||
};
|
||||
assert_eq!(
|
||||
result.is_err(),
|
||||
required_by != "none",
|
||||
"{required_by}, local={local}"
|
||||
);
|
||||
assert_eq!(
|
||||
calls.load(Ordering::SeqCst),
|
||||
usize::from(required_by == "none")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_partial_merge_failure_collects_only_successful_outputs() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
|
||||
@@ -31,7 +31,7 @@ use std::sync::atomic::AtomicU64;
|
||||
use common_base::cancellation::{CancellableFuture, CancellationHandle};
|
||||
use common_time::Timestamp;
|
||||
use partition::PartitionRuleRef;
|
||||
use snafu::{OptionExt, ensure};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
@@ -41,6 +41,7 @@ use crate::config::MitoConfig;
|
||||
use crate::error::{InvalidMultiRegionCompactionSnafu, Result};
|
||||
use crate::region::options::RegionOptions;
|
||||
use crate::sst::file::{FileMeta, RegionFileId};
|
||||
use crate::sst::index::handler::IndexKindProviderRef;
|
||||
use crate::sst::parquet::SstInfo;
|
||||
use crate::sst::parquet::writer::SstWriteGuard;
|
||||
|
||||
@@ -78,6 +79,8 @@ pub struct MultiRegionCompactionPlan {
|
||||
|
||||
/// Shared storage services and attempt-owned output resources.
|
||||
pub struct MultiRegionCompactionContext {
|
||||
/// Optional enterprise index implementation. Each routed output builds its own state.
|
||||
pub index_kind_provider: Option<IndexKindProviderRef>,
|
||||
pub access_layer: AccessLayerRef,
|
||||
pub cache: CacheManagerRef,
|
||||
pub config: Arc<MitoConfig>,
|
||||
@@ -127,6 +130,27 @@ pub async fn compact_regions(
|
||||
context: MultiRegionCompactionContext,
|
||||
) -> Result<MultiRegionCompactionOutput> {
|
||||
let metadata = validate_plan(&plan)?;
|
||||
// Validate before source footer reads or any output creation. The source and
|
||||
// target snapshots may each carry file-level or column-level index metadata.
|
||||
let registry = crate::sst::index::registry::IndexRegistry::new(
|
||||
context.config.inverted_index.clone(),
|
||||
context.config.fulltext_index.clone(),
|
||||
context.config.bloom_filter_index.clone(),
|
||||
)
|
||||
.with_provider(context.index_kind_provider.clone())
|
||||
.with_context(|_| crate::error::ExternalSnafu {
|
||||
context: "compaction index registration".to_string(),
|
||||
})?;
|
||||
for target in plan.targets.values() {
|
||||
registry
|
||||
.validate_required_kinds(
|
||||
&target.metadata,
|
||||
plan.sources.iter().chain(target.inputs.values()),
|
||||
)
|
||||
.with_context(|_| crate::error::ExternalSnafu {
|
||||
context: "compaction index planning".to_string(),
|
||||
})?;
|
||||
}
|
||||
if context.cancellation.is_cancelled() {
|
||||
return crate::error::CompactionCancelledSnafu.fail();
|
||||
}
|
||||
|
||||
@@ -43,6 +43,8 @@ pub(crate) struct MemoryLimits {
|
||||
pub(crate) batch: usize,
|
||||
pub(crate) group: usize,
|
||||
pub(crate) index: usize,
|
||||
/// Reuses index allocation only when the optional working set fits admission.
|
||||
pub(crate) extension_index_memory_limit: Option<usize>,
|
||||
pub(crate) writer: SstWriteLimits,
|
||||
pub(crate) estimated: u64,
|
||||
}
|
||||
@@ -60,6 +62,7 @@ impl MemoryLimits {
|
||||
batch,
|
||||
group: plan.memory_limit / 16,
|
||||
index: plan.memory_limit / (64 * plan.targets.len()),
|
||||
extension_index_memory_limit: None,
|
||||
writer: SstWriteLimits {
|
||||
// Parquet 59 preallocates a 1 MiB bit writer for each of the
|
||||
// timestamp/sequence delta encoders. Dictionary interner tables
|
||||
@@ -78,6 +81,7 @@ impl MemoryLimits {
|
||||
plan: &MultiRegionCompactionPlan,
|
||||
context: &MultiRegionCompactionContext,
|
||||
footers: &[Arc<ParquetMetaData>],
|
||||
extension_targets: usize,
|
||||
) -> Result<()> {
|
||||
self.check_upload_minimum(context)?;
|
||||
let mut extra_delta = 0;
|
||||
@@ -105,7 +109,10 @@ impl MemoryLimits {
|
||||
),
|
||||
}
|
||||
);
|
||||
self.estimated = bytes;
|
||||
// Optional indexes must not turn an admitted data compaction into a
|
||||
// resource failure. Reserve all resident target states together or skip.
|
||||
(self.extension_index_memory_limit, self.estimated) =
|
||||
admit_extension_indexes(bytes, plan.memory_limit, self.index, extension_targets);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -219,3 +226,37 @@ fn reader_bytes(footer: &ParquetMetaData) -> u64 {
|
||||
.unwrap_or(0);
|
||||
pages.saturating_add(footer.memory_size() as u64)
|
||||
}
|
||||
|
||||
/// Twice the retained budget estimates state plus finish scratch, not allocator RSS.
|
||||
fn admit_extension_indexes(
|
||||
base: u64,
|
||||
budget: usize,
|
||||
index: usize,
|
||||
targets: usize,
|
||||
) -> (Option<usize>, u64) {
|
||||
let with_extension_indexes = base.saturating_add(
|
||||
(index as u64)
|
||||
.saturating_mul(2)
|
||||
.saturating_mul(targets as u64),
|
||||
);
|
||||
if targets > 0 && index > 0 && with_extension_indexes <= budget as u64 {
|
||||
(Some(index), with_extension_indexes)
|
||||
} else {
|
||||
(None, base)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::admit_extension_indexes;
|
||||
|
||||
#[test]
|
||||
fn test_extension_indexes_do_not_reject_admitted_data() {
|
||||
// Both target writers are resident. Insufficient extra room leaves the
|
||||
// already-admitted data budget unchanged and explicitly disables optional indexes.
|
||||
assert_eq!(admit_extension_indexes(900, 1000, 30, 2), (None, 900));
|
||||
assert_eq!(admit_extension_indexes(880, 1000, 30, 2), (Some(30), 1000));
|
||||
assert_eq!(admit_extension_indexes(900, 1000, 30, 0), (None, 900));
|
||||
assert_eq!(admit_extension_indexes(900, 1000, 0, 2), (None, 900));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::config::MemoryThreshold;
|
||||
use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY;
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use common_time::Timestamp;
|
||||
use datatypes::arrow::array::{
|
||||
Array, ArrayRef, BinaryArray, GenericByteArray, GenericByteDictionaryBuilder, UInt64Array,
|
||||
@@ -49,6 +51,9 @@ use crate::read::read_columns::ReadColumns;
|
||||
use crate::read::{BoxedRecordBatchStream, timestamp_array_to_i64_slice};
|
||||
use crate::sst::file::{FileHandle, FileMeta};
|
||||
use crate::sst::file_purger::NoopFilePurger;
|
||||
use crate::sst::index::IndexBuildType;
|
||||
use crate::sst::index::handler::PlanContext;
|
||||
use crate::sst::index::registry::{IndexBuildPlan, IndexRegistry};
|
||||
use crate::sst::parquet::flat_format::{
|
||||
primary_key_column_index, sequence_column_index, time_index_column_index,
|
||||
};
|
||||
@@ -108,6 +113,7 @@ pub(crate) struct SharedSource {
|
||||
partition_rule: PartitionRuleRef,
|
||||
window: (Timestamp, Timestamp),
|
||||
pub(crate) limits: MemoryLimits,
|
||||
pub(crate) index_plans: BTreeMap<RegionId, Arc<IndexBuildPlan>>,
|
||||
peak_group_bytes: AtomicU64,
|
||||
cancellation: Arc<common_base::cancellation::CancellationHandle>,
|
||||
stop: CancellationToken,
|
||||
@@ -205,7 +211,49 @@ impl SharedSource {
|
||||
)?;
|
||||
let schema = mapper.input_arrow_schema(false);
|
||||
let mut limits = MemoryLimits::new(plan, &schema)?;
|
||||
limits.admit(plan, context, &footers)?;
|
||||
let threshold = |configured: Option<usize>| {
|
||||
MemoryThreshold::Size(ReadableSize(
|
||||
configured.unwrap_or(limits.index).min(limits.index) as u64,
|
||||
))
|
||||
};
|
||||
let mut inverted = context.config.inverted_index.clone();
|
||||
inverted.mem_threshold_on_create = threshold(inverted.mem_threshold_on_create());
|
||||
let mut fulltext = context.config.fulltext_index.clone();
|
||||
fulltext.mem_threshold_on_create = threshold(Some(fulltext.mem_threshold_on_create()));
|
||||
let mut bloom = context.config.bloom_filter_index.clone();
|
||||
bloom.mem_threshold_on_create = threshold(bloom.mem_threshold_on_create());
|
||||
let registry = IndexRegistry::new(inverted, fulltext, bloom)
|
||||
.with_provider(context.index_kind_provider.clone())
|
||||
.with_context(|_| crate::error::ExternalSnafu {
|
||||
context: "compaction index registration".to_string(),
|
||||
})?;
|
||||
let mut index_plans = plan
|
||||
.targets
|
||||
.iter()
|
||||
.map(|(id, target)| {
|
||||
let work = registry.plan(&PlanContext {
|
||||
metadata: &target.metadata,
|
||||
index_options: &target.options.index_options,
|
||||
build_type: IndexBuildType::Compact,
|
||||
existing_indexes: &[],
|
||||
});
|
||||
(*id, Arc::new(work))
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
limits.admit(
|
||||
plan,
|
||||
context,
|
||||
&footers,
|
||||
index_plans
|
||||
.values()
|
||||
.filter(|work| work.entries().any(|entry| !entry.kind.is_builtin()))
|
||||
.count(),
|
||||
)?;
|
||||
if limits.extension_index_memory_limit.is_none() {
|
||||
for (region_id, work) in &mut index_plans {
|
||||
Arc::make_mut(work).omit_extensions_for_budget(*region_id);
|
||||
}
|
||||
}
|
||||
// Compute routing/version annotations on bounded reader batches, but
|
||||
// keep physical __sequence as the merge key. The annotations are not
|
||||
// persisted and fixed-position time/PK/sequence/op columns stay last.
|
||||
@@ -233,6 +281,7 @@ impl SharedSource {
|
||||
Timestamp::new_second(plan.window_start + plan.window_seconds),
|
||||
),
|
||||
limits,
|
||||
index_plans,
|
||||
peak_group_bytes: AtomicU64::new(0),
|
||||
cancellation: context.cancellation.clone(),
|
||||
stop: CancellationToken::new(),
|
||||
|
||||
@@ -273,6 +273,7 @@ impl Fixture {
|
||||
});
|
||||
(
|
||||
MultiRegionCompactionContext {
|
||||
index_kind_provider: None,
|
||||
access_layer: self.layer.clone(),
|
||||
cache: Arc::new(CacheManager::default()),
|
||||
config: self.config.clone(),
|
||||
@@ -2327,6 +2328,7 @@ async fn test_limited_writer_fails_instead_of_publishing_over_budget(#[case] kin
|
||||
&context,
|
||||
&limits,
|
||||
plan.max_output_file_size,
|
||||
Arc::default(),
|
||||
)
|
||||
.write(source)
|
||||
.await
|
||||
@@ -2455,3 +2457,152 @@ async fn test_invalid_plan_is_rejected_before_creating_outputs(
|
||||
);
|
||||
assert!(protection.files.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InvalidOptionalIndexHandler;
|
||||
|
||||
impl crate::sst::index::handler::IndexKindProvider for InvalidOptionalIndexHandler {
|
||||
fn handlers(&self) -> Vec<Arc<dyn crate::sst::index::handler::IndexKindHandler>> {
|
||||
vec![Arc::new(Self)]
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::sst::index::handler::IndexKindHandler for InvalidOptionalIndexHandler {
|
||||
fn kinds(&self) -> &[crate::sst::index::kind::IndexKind] {
|
||||
&[crate::sst::index::kind::IndexKind::Extension(
|
||||
crate::sst::index::kind::ExtensionIndexKind::Hll,
|
||||
)]
|
||||
}
|
||||
|
||||
fn plan(
|
||||
&self,
|
||||
context: &crate::sst::index::handler::PlanContext<'_>,
|
||||
) -> std::result::Result<
|
||||
Option<Arc<dyn crate::sst::index::handler::PlannedIndex>>,
|
||||
common_error::ext::BoxedError,
|
||||
> {
|
||||
assert!(
|
||||
context.metadata.column_metadatas[0]
|
||||
.column_schema
|
||||
.hll_options()
|
||||
.is_err()
|
||||
);
|
||||
Err(common_error::ext::BoxedError::new(
|
||||
crate::error::InvalidConfigSnafu {
|
||||
reason: "invalid optional index configuration",
|
||||
}
|
||||
.build(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ConflictingRegistrationProvider(std::sync::atomic::AtomicUsize);
|
||||
|
||||
impl crate::sst::index::handler::IndexKindProvider for ConflictingRegistrationProvider {
|
||||
fn handlers(&self) -> Vec<Arc<dyn crate::sst::index::handler::IndexKindHandler>> {
|
||||
// Preflight succeeds; source preparation must propagate its own failure too.
|
||||
let calls = self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let handler: Arc<dyn crate::sst::index::handler::IndexKindHandler> =
|
||||
Arc::new(InvalidOptionalIndexHandler);
|
||||
if calls == 0 {
|
||||
vec![handler]
|
||||
} else {
|
||||
vec![handler.clone(), handler]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_source_index_registration_failure_does_not_fall_back() {
|
||||
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
|
||||
let (mut context, protection) = fixture.context(None);
|
||||
context.index_kind_provider = Some(Arc::new(ConflictingRegistrationProvider::default()));
|
||||
let error = compact_regions(fixture.plan(2), context)
|
||||
.await
|
||||
.err()
|
||||
.expect("conflicting registration must fail");
|
||||
assert!(format!("{error:?}").contains("compaction index registration"));
|
||||
assert!(protection.files.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_invalid_optional_index_options_do_not_block_routed_compaction() {
|
||||
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
|
||||
for invalid_value in ["missing-column", "bad-capacity"] {
|
||||
let mut plan = fixture.plan(2);
|
||||
for target in plan.targets.values_mut() {
|
||||
Arc::make_mut(&mut target.metadata).column_metadatas[0]
|
||||
.column_schema
|
||||
.mut_metadata()
|
||||
.insert(datatypes::schema::HLL_KEY.into(), invalid_value.into());
|
||||
}
|
||||
let (mut context, _) = fixture.context(None);
|
||||
context.index_kind_provider = Some(Arc::new(InvalidOptionalIndexHandler));
|
||||
let output = compact_regions(plan, context).await.unwrap();
|
||||
assert_eq!(output.stats.source_rows, output.stats.output_rows);
|
||||
assert!(output.stats.output_rows > 0);
|
||||
assert!(
|
||||
output
|
||||
.files
|
||||
.values()
|
||||
.flatten()
|
||||
.all(|file| file
|
||||
.indexes
|
||||
.iter()
|
||||
.all(|index| index.created_indexes.iter().all(|kind| !matches!(
|
||||
kind,
|
||||
crate::sst::file::IndexType::HllIndex
|
||||
| crate::sst::file::IndexType::KllIndex
|
||||
| crate::sst::file::IndexType::MgIndex
|
||||
))))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_missing_index_handler_blocks_source_and_target_descriptors() {
|
||||
use crate::sst::file::{ColumnIndexMetadata, IndexType};
|
||||
|
||||
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
|
||||
for required_by in ["schema", "file", "column", "target"] {
|
||||
let mut plan = fixture.plan(2);
|
||||
match required_by {
|
||||
"schema" => {
|
||||
for target in plan.targets.values_mut() {
|
||||
Arc::make_mut(&mut target.metadata).column_metadatas[0]
|
||||
.column_schema
|
||||
.set_hll_options(&datatypes::schema::HllOptions::default())
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
"file" => plan.sources[0].available_indexes.push(IndexType::HllIndex),
|
||||
"column" => plan.sources[0].indexes.push(ColumnIndexMetadata {
|
||||
column_id: 0,
|
||||
created_indexes: [IndexType::HllIndex].into_iter().collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
_ => {
|
||||
plan.targets
|
||||
.values_mut()
|
||||
.next()
|
||||
.unwrap()
|
||||
.inputs
|
||||
.values_mut()
|
||||
.next()
|
||||
.unwrap()
|
||||
.available_indexes
|
||||
.push(IndexType::HllIndex);
|
||||
}
|
||||
}
|
||||
let (context, _) = fixture.context(None);
|
||||
let result = compact_regions(plan, context).await;
|
||||
let error = result
|
||||
.err()
|
||||
.expect("configured or persisted kind requires a handler");
|
||||
assert!(
|
||||
error.to_string().contains("compaction index planning"),
|
||||
"{required_by}: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ pub(crate) async fn execute(
|
||||
senders.insert(id, sender);
|
||||
let schema = source.schema();
|
||||
let limits = source.limits.clone();
|
||||
let index_plans = source.index_plans.get(&id).cloned().unwrap_or_default();
|
||||
let plan = plan.clone();
|
||||
let context = context.clone();
|
||||
workers.push(AbortOnDropHandle::new(common_runtime::spawn_compact(
|
||||
@@ -76,6 +77,7 @@ pub(crate) async fn execute(
|
||||
&context,
|
||||
&limits,
|
||||
plan.max_output_file_size,
|
||||
index_plans,
|
||||
)
|
||||
.write(input)
|
||||
.await?;
|
||||
|
||||
@@ -20,11 +20,12 @@ use store_api::codec::PrimaryKeyEncoding;
|
||||
use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType};
|
||||
use crate::compaction::multi_region::memory::{self, MemoryLimits};
|
||||
use crate::compaction::multi_region::{MultiRegionCompactionContext, MultiRegionTarget};
|
||||
use crate::config::MemoryThreshold;
|
||||
use crate::error::{ComputeArrowSnafu, Result};
|
||||
use crate::read::FlatSource;
|
||||
use crate::sst::FormatType;
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::sst::index::build::IndexBuildInputs;
|
||||
use crate::sst::index::registry::IndexBuildPlan;
|
||||
use crate::sst::parquet::metadata::extract_primary_key_range;
|
||||
use crate::sst::parquet::parallel_writer::EncodeRuntime;
|
||||
use crate::sst::parquet::{SstInfo, WriteOptions};
|
||||
@@ -33,6 +34,7 @@ pub(crate) struct TargetWriter<'a> {
|
||||
target: &'a MultiRegionTarget,
|
||||
context: &'a MultiRegionCompactionContext,
|
||||
limits: &'a MemoryLimits,
|
||||
index_plans: Arc<IndexBuildPlan>,
|
||||
max_file_size: usize,
|
||||
sequence: Option<NonZeroU64>,
|
||||
preserve_row_sequence: bool,
|
||||
@@ -44,6 +46,7 @@ impl<'a> TargetWriter<'a> {
|
||||
context: &'a MultiRegionCompactionContext,
|
||||
limits: &'a MemoryLimits,
|
||||
max_file_size: usize,
|
||||
index_plans: Arc<IndexBuildPlan>,
|
||||
) -> Self {
|
||||
let sequence = crate::sst::file::known_max_input_sequence(target.inputs.values());
|
||||
let preserve_row_sequence = target.options.preserve_row_sequence
|
||||
@@ -55,6 +58,7 @@ impl<'a> TargetWriter<'a> {
|
||||
target,
|
||||
context,
|
||||
limits,
|
||||
index_plans,
|
||||
max_file_size,
|
||||
sequence,
|
||||
preserve_row_sequence,
|
||||
@@ -96,16 +100,19 @@ impl<'a> TargetWriter<'a> {
|
||||
|
||||
fn request(&self, source: FlatSource) -> Result<SstWriteRequest> {
|
||||
let config = &self.context.config;
|
||||
let mut inverted = config.inverted_index.clone();
|
||||
inverted.mem_threshold_on_create = self.index_threshold(inverted.mem_threshold_on_create());
|
||||
let mut fulltext = config.fulltext_index.clone();
|
||||
fulltext.mem_threshold_on_create =
|
||||
self.index_threshold(Some(fulltext.mem_threshold_on_create()));
|
||||
let mut bloom = config.bloom_filter_index.clone();
|
||||
bloom.mem_threshold_on_create = self.index_threshold(bloom.mem_threshold_on_create());
|
||||
// The shared source plan already applies the admitted index thresholds.
|
||||
let source = output_projection(self.target, source, self.context.cancellation.clone())?;
|
||||
let index_build_inputs = Some(IndexBuildInputs {
|
||||
output_rows: None,
|
||||
plan: self.index_plans.clone(),
|
||||
input_puffin_manager: self.context.access_layer.build_puffin_manager(),
|
||||
// Routing and file rollover change coverage. Consume only actual output rows.
|
||||
inputs: Arc::from([]),
|
||||
can_merge_inputs: false,
|
||||
memory_limit: self.limits.extension_index_memory_limit,
|
||||
});
|
||||
Ok(SstWriteRequest {
|
||||
index_build_inputs: None,
|
||||
index_build_inputs,
|
||||
op_type: OperationType::Compact,
|
||||
metadata: self.target.metadata.clone(),
|
||||
source,
|
||||
@@ -121,20 +128,12 @@ impl<'a> TargetWriter<'a> {
|
||||
preserve_row_sequence: self.preserve_row_sequence,
|
||||
index_options: self.target.options.index_options.clone(),
|
||||
index_config: config.index.clone(),
|
||||
inverted_index_config: inverted,
|
||||
fulltext_index_config: fulltext,
|
||||
bloom_filter_index_config: bloom,
|
||||
inverted_index_config: config.inverted_index.clone(),
|
||||
fulltext_index_config: config.fulltext_index.clone(),
|
||||
bloom_filter_index_config: config.bloom_filter_index.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn index_threshold(&self, configured: Option<usize>) -> MemoryThreshold {
|
||||
MemoryThreshold::Size(ReadableSize(
|
||||
configured
|
||||
.unwrap_or(self.limits.index)
|
||||
.min(self.limits.index) as u64,
|
||||
))
|
||||
}
|
||||
|
||||
fn options(&self) -> WriteOptions {
|
||||
WriteOptions {
|
||||
write_buffer_size: ReadableSize(self.limits.batch as u64),
|
||||
|
||||
@@ -49,6 +49,94 @@ use crate::test_util::{
|
||||
CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, reopen_region, rows_schema,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_engine_create_validates_extension_options_before_manifest() {
|
||||
use crate::sst::index::handler::{
|
||||
IndexKindHandler, IndexKindProvider, IndexKindProviderRef, PlanContext, PlannedIndex,
|
||||
};
|
||||
use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
|
||||
use common_base::Plugins;
|
||||
use common_error::ext::BoxedError;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ValidatingHandler;
|
||||
impl IndexKindHandler for ValidatingHandler {
|
||||
fn kinds(&self) -> &[IndexKind] {
|
||||
&[IndexKind::Extension(ExtensionIndexKind::Hll)]
|
||||
}
|
||||
fn validate(&self, context: &PlanContext<'_>) -> Result<(), BoxedError> {
|
||||
for column in &context.metadata.column_metadatas {
|
||||
if column
|
||||
.column_schema
|
||||
.metadata()
|
||||
.get(datatypes::schema::HLL_KEY)
|
||||
.map(String::as_str)
|
||||
== Some(r#"{"precision":0}"#)
|
||||
{
|
||||
return Err(BoxedError::new(common_error::ext::PlainError::new(
|
||||
"injected invalid extension option".into(),
|
||||
StatusCode::InvalidArguments,
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn plan(&self, _: &PlanContext<'_>) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Provider;
|
||||
impl IndexKindProvider for Provider {
|
||||
fn handlers(&self) -> Vec<Arc<dyn IndexKindHandler>> {
|
||||
vec![Arc::new(ValidatingHandler)]
|
||||
}
|
||||
}
|
||||
let mut env = TestEnv::new().await;
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<IndexKindProviderRef>(Arc::new(Provider));
|
||||
let engine = env
|
||||
.create_engine_with_plugins(MitoConfig::default(), plugins)
|
||||
.await;
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let mut request = CreateRequestBuilder::new().build();
|
||||
request.column_metadatas[0]
|
||||
.column_schema
|
||||
.mut_metadata()
|
||||
.insert(
|
||||
datatypes::schema::HLL_KEY.into(),
|
||||
r#"{"precision":0}"#.into(),
|
||||
);
|
||||
let dir = manifest_dir(®ion_dir_from_table_dir(
|
||||
&request.table_dir,
|
||||
region_id,
|
||||
request.path_type,
|
||||
));
|
||||
let error = engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
|
||||
assert!(engine.get_region(region_id).is_none());
|
||||
assert!(
|
||||
env.get_object_store()
|
||||
.unwrap()
|
||||
.list(&dir)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
// A failed plugin validation must leave a clean path for a subsequent create.
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Create(CreateRequestBuilder::new().build()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(engine.get_region(region_id).is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_engine_column_compression_validation() {
|
||||
use datatypes::schema::COMPRESSION_KEY;
|
||||
|
||||
@@ -2577,3 +2577,701 @@ async fn test_truncate_while_indexing_encoded_bulk_part_removes_uploaded_sst() {
|
||||
.collect::<Vec<_>>();
|
||||
assert!(leftovers.is_empty(), "{leftovers:?}");
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
struct RebuildSketchProvider {
|
||||
fail_manual_plan: bool,
|
||||
manual_plans: Arc<AtomicUsize>,
|
||||
creates: Arc<AtomicUsize>,
|
||||
readable_inputs: Arc<std::sync::Mutex<Vec<(crate::sst::file::RegionIndexId, bool)>>>,
|
||||
}
|
||||
|
||||
impl crate::sst::index::handler::IndexKindProvider for RebuildSketchProvider {
|
||||
fn handlers(&self) -> Vec<Arc<dyn crate::sst::index::handler::IndexKindHandler>> {
|
||||
vec![Arc::new(self.clone())]
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::sst::index::handler::IndexKindHandler for RebuildSketchProvider {
|
||||
fn kinds(&self) -> &[crate::sst::index::kind::IndexKind] {
|
||||
&[crate::sst::index::kind::IndexKind::Extension(
|
||||
crate::sst::index::kind::ExtensionIndexKind::Hll,
|
||||
)]
|
||||
}
|
||||
fn plan(
|
||||
&self,
|
||||
context: &crate::sst::index::handler::PlanContext<'_>,
|
||||
) -> std::result::Result<
|
||||
Option<Arc<dyn crate::sst::index::handler::PlannedIndex>>,
|
||||
common_error::ext::BoxedError,
|
||||
> {
|
||||
use crate::sst::index::IndexBuildType;
|
||||
if context.build_type == IndexBuildType::Manual {
|
||||
self.manual_plans.fetch_add(1, Ordering::Relaxed);
|
||||
if self.fail_manual_plan {
|
||||
return Err(common_error::ext::BoxedError::new(
|
||||
common_error::ext::PlainError::new(
|
||||
"injected manual plan failure".into(),
|
||||
StatusCode::Internal,
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
if context.build_type == IndexBuildType::Flush {
|
||||
return Ok(None);
|
||||
}
|
||||
if matches!(
|
||||
context.build_type,
|
||||
IndexBuildType::Manual | IndexBuildType::SchemaChange
|
||||
) && !context.existing_indexes.iter().any(|column| {
|
||||
column
|
||||
.created_indexes
|
||||
.contains(&crate::sst::file::IndexType::HllIndex)
|
||||
}) {
|
||||
return Ok(None);
|
||||
}
|
||||
assert!(
|
||||
context
|
||||
.metadata
|
||||
.column_by_id(0)
|
||||
.unwrap()
|
||||
.column_schema
|
||||
.metadata()
|
||||
.contains_key(datatypes::schema::HLL_KEY)
|
||||
);
|
||||
Ok(Some(Arc::new(self.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::sst::index::handler::PlannedIndex for RebuildSketchProvider {
|
||||
fn kinds(&self) -> &[crate::sst::index::kind::IndexKind] {
|
||||
crate::sst::index::handler::IndexKindHandler::kinds(self)
|
||||
}
|
||||
fn entries(&self) -> &[crate::sst::index::handler::PlanEntry] {
|
||||
&[crate::sst::index::handler::PlanEntry {
|
||||
column_id: 0,
|
||||
kind: crate::sst::index::kind::IndexKind::Extension(
|
||||
crate::sst::index::kind::ExtensionIndexKind::Hll,
|
||||
),
|
||||
format_version: 1,
|
||||
}]
|
||||
}
|
||||
fn is_current(
|
||||
&self,
|
||||
_: &crate::sst::file::FileMeta,
|
||||
_: &crate::sst::index::handler::CurrencyContext<'_>,
|
||||
) -> bool {
|
||||
// This test requests explicit maintenance on each manual rebuild.
|
||||
false
|
||||
}
|
||||
|
||||
async fn build(
|
||||
&self,
|
||||
context: &crate::sst::index::handler::BuildContext<'_>,
|
||||
) -> std::result::Result<
|
||||
Option<Box<dyn crate::sst::index::handler::IndexCreator>>,
|
||||
common_error::ext::BoxedError,
|
||||
> {
|
||||
use puffin::puffin_manager::{PuffinManager, PuffinReader};
|
||||
|
||||
for input in context.inputs.iter() {
|
||||
// Initial compaction may read flush files that have no sketches yet.
|
||||
if !input.meta_ref().indexes.iter().any(|column| {
|
||||
column.created_indexes.iter().any(|kind| {
|
||||
matches!(
|
||||
kind,
|
||||
crate::sst::file::IndexType::HllIndex
|
||||
| crate::sst::file::IndexType::KllIndex
|
||||
| crate::sst::file::IndexType::MgIndex
|
||||
)
|
||||
})
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
let reader = context
|
||||
.input_puffin_manager
|
||||
.reader(&input.index_id())
|
||||
.await
|
||||
.unwrap();
|
||||
let metadata = reader.metadata().await.unwrap();
|
||||
assert!(
|
||||
metadata
|
||||
.blobs
|
||||
.iter()
|
||||
.any(|blob| blob.blob_type == "test.sketch")
|
||||
);
|
||||
self.readable_inputs
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((input.index_id(), context.can_merge_inputs));
|
||||
}
|
||||
self.creates.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(Some(Box::new(RebuildSketchCreator { rows: 0 })))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RebuildSketchCreator {
|
||||
rows: usize,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::sst::index::handler::IndexCreator for RebuildSketchCreator {
|
||||
async fn update(
|
||||
&mut self,
|
||||
batch: &mut crate::read::Batch,
|
||||
) -> std::result::Result<(), common_error::ext::BoxedError> {
|
||||
self.rows += batch.num_rows();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_flat(
|
||||
&mut self,
|
||||
batch: &datatypes::arrow::record_batch::RecordBatch,
|
||||
) -> std::result::Result<(), common_error::ext::BoxedError> {
|
||||
self.rows += batch.num_rows();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn finish(
|
||||
&mut self,
|
||||
writer: &mut crate::sst::index::puffin_manager::SstPuffinWriter,
|
||||
) -> std::result::Result<Vec<crate::sst::index::CompletedEntry>, common_error::ext::BoxedError>
|
||||
{
|
||||
use crate::sst::index::CompletedEntry;
|
||||
use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
|
||||
use puffin::puffin_manager::PuffinWriter;
|
||||
writer
|
||||
.put_blob(
|
||||
"test.sketch",
|
||||
futures::io::Cursor::new(self.rows.to_le_bytes().to_vec()),
|
||||
Default::default(),
|
||||
HashMap::new(),
|
||||
)
|
||||
.await
|
||||
.map_err(common_error::ext::BoxedError::new)?;
|
||||
Ok(vec![CompletedEntry {
|
||||
column_id: Some(0),
|
||||
kind: IndexKind::Extension(ExtensionIndexKind::Hll),
|
||||
format_version: 1,
|
||||
}])
|
||||
}
|
||||
|
||||
async fn abort(&mut self) -> std::result::Result<(), common_error::ext::BoxedError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn memory_usage(&self) -> usize {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the rebuilt inverted blob rather than trusting its manifest descriptor.
|
||||
async fn assert_tag_inverted_index(
|
||||
layer: &crate::access_layer::AccessLayer,
|
||||
index_id: RegionIndexId,
|
||||
) {
|
||||
use index::inverted_index::format::reader::{InvertedIndexBlobReader, InvertedIndexReader};
|
||||
use puffin::puffin_manager::{PuffinManager, PuffinReader};
|
||||
|
||||
let manager = layer.build_puffin_manager();
|
||||
let reader = manager.reader(&index_id).await.unwrap();
|
||||
let blob = reader
|
||||
.blob(crate::sst::index::inverted_index::INDEX_BLOB_TYPE)
|
||||
.await
|
||||
.unwrap()
|
||||
.reader()
|
||||
.await
|
||||
.unwrap();
|
||||
let reader = InvertedIndexBlobReader::new(blob);
|
||||
let metadata = reader.metadata(None).await.unwrap();
|
||||
let target = index::target::IndexTarget::ColumnId(0);
|
||||
let meta = &metadata.metas[&target.encode()];
|
||||
assert_eq!(metadata.total_row_count, 4);
|
||||
let fst = reader
|
||||
.fst(
|
||||
meta.base_offset + u64::from(meta.relative_fst_offset),
|
||||
meta.fst_size,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fst.len(), 4);
|
||||
for value in ["0", "1", "2", "3"] {
|
||||
let mut encoded = Vec::new();
|
||||
mito_codec::index::IndexValueCodec::encode_nonnull_value(
|
||||
datatypes::value::ValueRef::String(value),
|
||||
&mito_codec::row_converter::SortField::new(ConcreteDataType::string_datatype()),
|
||||
&mut encoded,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(fst.get(&encoded).is_some(), "missing tag {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_async_compaction_builds_and_manual_rebuild_maintains_sketch() {
|
||||
use crate::sst::index::handler::IndexKindProviderRef;
|
||||
use common_base::Plugins;
|
||||
let mut env = TestEnv::new().await;
|
||||
let plugins = Plugins::new();
|
||||
let provider = Arc::new(RebuildSketchProvider::default());
|
||||
plugins.insert::<IndexKindProviderRef>(provider.clone());
|
||||
let engine = env
|
||||
.create_engine_with_plugins(async_build_mode_config(false), plugins)
|
||||
.await;
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let mut request = CreateRequestBuilder::new()
|
||||
.insert_option("sst_format", "flat")
|
||||
.build();
|
||||
request.column_metadatas[0]
|
||||
.column_schema
|
||||
.set_inverted_index(true);
|
||||
request
|
||||
.column_metadatas
|
||||
.iter_mut()
|
||||
.find(|column| column.column_id == 0)
|
||||
.unwrap()
|
||||
.column_schema
|
||||
.mut_metadata()
|
||||
.insert(
|
||||
datatypes::schema::HLL_KEY.into(),
|
||||
r#"{"precision":10}"#.into(),
|
||||
);
|
||||
let schema = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
for start in [0, 2] {
|
||||
let rows = build_rows(start, start + 2);
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: schema.clone(),
|
||||
rows,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
flush_region(&engine, region_id, None).await;
|
||||
}
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::BuildIndex(RegionBuildIndexRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
0,
|
||||
provider.creates.load(Ordering::Relaxed),
|
||||
"manual rebuild must not introduce sketches on flush files"
|
||||
);
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Compact(RegionCompactRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let files = region.all_manifest_files().await.0;
|
||||
if files.len() == 1
|
||||
&& files[0].index_version > 0
|
||||
&& files[0].indexes.iter().any(|column| {
|
||||
column.created_indexes.iter().any(|kind| {
|
||||
matches!(
|
||||
kind,
|
||||
crate::sst::file::IndexType::HllIndex
|
||||
| crate::sst::file::IndexType::KllIndex
|
||||
| crate::sst::file::IndexType::MgIndex
|
||||
)
|
||||
})
|
||||
})
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let before = region.all_manifest_files().await.0[0].clone();
|
||||
assert_tag_inverted_index(®ion.access_layer, before.index_id()).await;
|
||||
let before_inputs = provider.readable_inputs.lock().unwrap().len();
|
||||
let before_creates = provider.creates.load(Ordering::Relaxed);
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::BuildIndex(RegionBuildIndexRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let files = region.all_manifest_files().await.0;
|
||||
assert_eq!(before_creates + 1, provider.creates.load(Ordering::Relaxed));
|
||||
assert!(files[0].index_version > before.index_version);
|
||||
assert_eq!(
|
||||
&provider.readable_inputs.lock().unwrap()[before_inputs..],
|
||||
&[(before.index_id(), true)],
|
||||
"manual rebuild must read the current manifest's committed Puffin version"
|
||||
);
|
||||
assert!(files[0].indexes.iter().any(|column| {
|
||||
column
|
||||
.created_indexes
|
||||
.contains(&crate::sst::file::IndexType::HllIndex)
|
||||
}));
|
||||
assert_tag_inverted_index(®ion.access_layer, files[0].index_id()).await;
|
||||
engine.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rebuild_column_only_index_advances_zero_generation() {
|
||||
use crate::sst::file::{ColumnIndexMetadata, IndexType};
|
||||
use crate::sst::index::handler::IndexKindProviderRef;
|
||||
use common_base::Plugins;
|
||||
|
||||
let mut env = TestEnv::new().await;
|
||||
let plugins = Plugins::new();
|
||||
let provider = Arc::new(RebuildSketchProvider::default());
|
||||
plugins.insert::<IndexKindProviderRef>(provider.clone());
|
||||
let engine = env
|
||||
.create_engine_with_plugins(MitoConfig::default(), plugins)
|
||||
.await;
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let mut request = CreateRequestBuilder::new().build();
|
||||
request.column_metadatas[0]
|
||||
.column_schema
|
||||
.mut_metadata()
|
||||
.insert(
|
||||
datatypes::schema::HLL_KEY.into(),
|
||||
r#"{"precision":10}"#.into(),
|
||||
);
|
||||
let table_dir = request.table_dir.clone();
|
||||
let schema = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
for start in [0, 2] {
|
||||
put_and_flush(&engine, region_id, &schema, start..start + 2).await;
|
||||
}
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Compact(RegionCompactRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let mut files = region.all_manifest_files().await.0;
|
||||
assert_eq!(files.len(), 1);
|
||||
let mut before = files.pop().unwrap();
|
||||
assert_eq!(before.index_version, 0);
|
||||
assert!(before.index_file_size > 0);
|
||||
before.available_indexes.clear();
|
||||
before.indexes = vec![ColumnIndexMetadata {
|
||||
column_id: 0,
|
||||
created_indexes: [IndexType::HllIndex].into_iter().collect(),
|
||||
..Default::default()
|
||||
}];
|
||||
let old_path = location::index_file_path(
|
||||
region.access_layer.table_dir(),
|
||||
before.index_id(),
|
||||
region.access_layer.path_type(),
|
||||
);
|
||||
let store = region.access_layer.object_store().clone();
|
||||
let old_bytes = store.read(&old_path).await.unwrap().to_vec();
|
||||
engine
|
||||
.edit_region(
|
||||
region_id,
|
||||
RegionEdit {
|
||||
files_to_add: vec![before.clone()],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await;
|
||||
let inputs_before = provider.readable_inputs.lock().unwrap().len();
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::BuildIndex(RegionBuildIndexRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let files = region.all_manifest_files().await.0;
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].file_id, before.file_id);
|
||||
assert_eq!(files[0].index_version, 1);
|
||||
assert!(
|
||||
files[0]
|
||||
.indexes
|
||||
.iter()
|
||||
.any(|column| column.created_indexes.contains(&IndexType::HllIndex))
|
||||
);
|
||||
assert_eq!(
|
||||
&provider.readable_inputs.lock().unwrap()[inputs_before..],
|
||||
&[(before.index_id(), true)]
|
||||
);
|
||||
let new_path = location::index_file_path(
|
||||
region.access_layer.table_dir(),
|
||||
files[0].index_id(),
|
||||
region.access_layer.path_type(),
|
||||
);
|
||||
assert_ne!(old_path, new_path);
|
||||
assert!(store.exists(&new_path).await.unwrap());
|
||||
assert_eq!(store.read(&old_path).await.unwrap().to_vec(), old_bytes);
|
||||
engine.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_compaction_without_required_provider_preserves_indexes() {
|
||||
use crate::sst::file::{ColumnIndexMetadata, IndexType};
|
||||
|
||||
let mut env = TestEnv::new().await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let request = CreateRequestBuilder::new().build_with_index();
|
||||
let schema = rows_schema(&request);
|
||||
let table_dir = request.table_dir.clone();
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
for start in [0, 2] {
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: schema.clone(),
|
||||
rows: build_rows(start, start + 2),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
flush_region(&engine, region_id, None).await;
|
||||
}
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let mut inputs = region.all_manifest_files().await.0;
|
||||
for file in &mut inputs {
|
||||
file.available_indexes.push(IndexType::HllIndex);
|
||||
file.indexes.push(ColumnIndexMetadata {
|
||||
column_id: 0,
|
||||
created_indexes: [IndexType::HllIndex].into_iter().collect(),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
engine
|
||||
.edit_region(
|
||||
region_id,
|
||||
RegionEdit {
|
||||
files_to_add: inputs,
|
||||
files_to_remove: vec![],
|
||||
timestamp_ms: None,
|
||||
compaction_time_window: None,
|
||||
flushed_entry_id: None,
|
||||
flushed_sequence: None,
|
||||
committed_sequence: None,
|
||||
wal_recovery: Default::default(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// Reload handles so compaction sees the persisted descriptors as well as the manifest.
|
||||
reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await;
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let version = region.version();
|
||||
let files: Vec<_> = version
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files())
|
||||
.collect();
|
||||
assert_eq!(files.len(), 2);
|
||||
assert!(files.iter().all(|file| {
|
||||
file.meta_ref()
|
||||
.available_indexes
|
||||
.contains(&IndexType::HllIndex)
|
||||
}));
|
||||
drop(version);
|
||||
let before = region.all_manifest_files().await.0;
|
||||
let error = engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Compact(RegionCompactRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(format!("{error:?}").contains("required index HllIndex has no registered handler"));
|
||||
let after = region.all_manifest_files().await.0;
|
||||
assert_eq!(after.len(), before.len());
|
||||
for before in &before {
|
||||
let after = after
|
||||
.iter()
|
||||
.find(|file| file.file_id == before.file_id)
|
||||
.unwrap();
|
||||
assert_eq!(after.index_version, before.index_version);
|
||||
assert_eq!(after.available_indexes, before.available_indexes);
|
||||
assert_eq!(after.indexes, before.indexes);
|
||||
}
|
||||
engine.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_manual_rebuild_without_required_provider_preserves_sketch_metadata() {
|
||||
use crate::sst::file::ColumnIndexMetadata;
|
||||
let mut env = TestEnv::new().await;
|
||||
let engine = env.create_engine(async_build_mode_config(false)).await;
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let request = CreateRequestBuilder::new().build();
|
||||
let schema = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema,
|
||||
rows: build_rows(0, 2),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
flush_region(&engine, region_id, None).await;
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::BuildIndex(RegionBuildIndexRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let mut file = region.all_manifest_files().await.0.pop().unwrap();
|
||||
if !file.indexes.iter().any(|column| column.column_id == 0) {
|
||||
file.indexes.push(ColumnIndexMetadata {
|
||||
column_id: 0,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
file.indexes
|
||||
.iter_mut()
|
||||
.find(|column| column.column_id == 0)
|
||||
.unwrap()
|
||||
.created_indexes
|
||||
.push(crate::sst::file::IndexType::HllIndex);
|
||||
// Persisted extension metadata requires its implementation even when
|
||||
// ordinary indexes already satisfy the current schema.
|
||||
engine
|
||||
.edit_region(
|
||||
region_id,
|
||||
RegionEdit {
|
||||
files_to_add: vec![file.clone()],
|
||||
files_to_remove: vec![],
|
||||
timestamp_ms: None,
|
||||
compaction_time_window: None,
|
||||
flushed_entry_id: None,
|
||||
flushed_sequence: None,
|
||||
committed_sequence: None,
|
||||
wal_recovery: Default::default(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// Region edits may assign a new sequence; compare against the committed metadata.
|
||||
let file = region.all_manifest_files().await.0.pop().unwrap();
|
||||
for _ in 0..2 {
|
||||
let error = engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::BuildIndex(RegionBuildIndexRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(format!("{error:?}").contains("no registered handler"));
|
||||
let current = region.all_manifest_files().await.0;
|
||||
assert_eq!(file.index_version, current[0].index_version);
|
||||
assert_eq!(file.indexes, current[0].indexes);
|
||||
}
|
||||
// Explicit internal requests must reject unavailable implementations as well.
|
||||
let (result_tx, mut result_rx) = tokio::sync::mpsc::channel(1);
|
||||
engine
|
||||
.inner
|
||||
.workers
|
||||
.submit_to_worker(
|
||||
region_id,
|
||||
crate::request::WorkerRequest::Background {
|
||||
region_id,
|
||||
notify: crate::request::BackgroundNotify::IndexBuildRetry(
|
||||
crate::request::BuildIndexRequest {
|
||||
region_id,
|
||||
build_type: crate::sst::index::IndexBuildType::Manual,
|
||||
file_metas: vec![file.clone()],
|
||||
result_senders: vec![result_tx],
|
||||
},
|
||||
),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let outcome = tokio::time::timeout(Duration::from_secs(10), result_rx.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(outcome.is_err());
|
||||
let current = region.all_manifest_files().await.0;
|
||||
assert_eq!(current, vec![file]);
|
||||
engine.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_manual_rebuild_plan_failure_returns_before_scheduling() {
|
||||
let mut env = TestEnv::new().await;
|
||||
let plugins = common_base::Plugins::new();
|
||||
let provider = Arc::new(RebuildSketchProvider {
|
||||
fail_manual_plan: true,
|
||||
..Default::default()
|
||||
});
|
||||
plugins.insert::<crate::sst::index::handler::IndexKindProviderRef>(provider.clone());
|
||||
let engine = env
|
||||
.create_engine_with_plugins(async_build_mode_config(false), plugins)
|
||||
.await;
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let request = CreateRequestBuilder::new().build();
|
||||
let schema = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema,
|
||||
rows: build_rows(0, 2),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
flush_region(&engine, region_id, None).await;
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let before = region.all_manifest_files().await.0;
|
||||
assert_eq!(before.len(), 1);
|
||||
let error = engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::BuildIndex(RegionBuildIndexRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(format!("{error:?}").contains("injected manual plan failure"));
|
||||
// Selection and task preparation would each plan again; only entry preflight ran.
|
||||
assert_eq!(provider.manual_plans.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(provider.creates.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(region.all_manifest_files().await.0, before);
|
||||
engine.stop().await.unwrap();
|
||||
}
|
||||
|
||||
@@ -77,8 +77,11 @@ use crate::sst::FormatType;
|
||||
use crate::sst::file::{FileHandle, RegionFileId, RegionIndexId};
|
||||
use crate::sst::file_purger::{FilePurgerRef, create_file_purger};
|
||||
use crate::sst::file_ref::FileReferenceManagerRef;
|
||||
use crate::sst::index::IndexBuildType;
|
||||
use crate::sst::index::handler::PlanContext;
|
||||
use crate::sst::index::intermediate::IntermediateManager;
|
||||
use crate::sst::index::puffin_manager::PuffinManagerFactory;
|
||||
use crate::sst::index::registry::IndexRegistryRef;
|
||||
use crate::sst::location::{self, region_dir_from_table_dir};
|
||||
use crate::sst::parquet::metadata::{MetadataLoader, extract_primary_key_range};
|
||||
use crate::sst::parquet::reader::MetadataCacheMetrics;
|
||||
@@ -148,6 +151,7 @@ pub type PartitionExprFetcherRef = Arc<dyn PartitionExprFetcher + Send + Sync>;
|
||||
|
||||
/// Builder to create a new [MitoRegion] or open an existing one.
|
||||
pub(crate) struct RegionOpener {
|
||||
index_registry: Option<IndexRegistryRef>,
|
||||
region_id: RegionId,
|
||||
metadata_builder: Option<RegionMetadataBuilder>,
|
||||
memtable_builder_provider: MemtableBuilderProvider,
|
||||
@@ -191,6 +195,7 @@ impl RegionOpener {
|
||||
partition_expr_fetcher: PartitionExprFetcherRef,
|
||||
) -> RegionOpener {
|
||||
RegionOpener {
|
||||
index_registry: None,
|
||||
region_id,
|
||||
metadata_builder: None,
|
||||
memtable_builder_provider,
|
||||
@@ -216,6 +221,12 @@ impl RegionOpener {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the registry used to validate new-region index options.
|
||||
pub(crate) fn with_index_registry(mut self, registry: IndexRegistryRef) -> Self {
|
||||
self.index_registry = Some(registry);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the store for companion range indexes.
|
||||
pub(crate) fn series_index_store(mut self, store: Option<ObjectStore>) -> Self {
|
||||
self.series_index_store = store;
|
||||
@@ -383,6 +394,23 @@ impl RegionOpener {
|
||||
};
|
||||
ensure_json2_uses_flat_format(&metadata, &options)?;
|
||||
options.validate_column_compression(&metadata)?;
|
||||
// Validate explicit new-region configuration before creating its manifest.
|
||||
// Recovery and later compactions tolerate stale optional sketch settings.
|
||||
if let Some(registry) = &self.index_registry {
|
||||
registry
|
||||
.validate(&PlanContext {
|
||||
metadata: &metadata,
|
||||
index_options: &options.index_options,
|
||||
build_type: IndexBuildType::Flush,
|
||||
existing_indexes: &[],
|
||||
})
|
||||
.map_err(|err| {
|
||||
crate::error::InvalidRegionOptionsSnafu {
|
||||
reason: err.to_string(),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
}
|
||||
// The region's WAL history starts in this log store, so reopening
|
||||
// the region on it passes the history check without any entry. It is
|
||||
// recorded before the manifest exists: a log store that gave up its
|
||||
|
||||
@@ -422,6 +422,21 @@ pub enum IndexType {
|
||||
MgIndex,
|
||||
}
|
||||
|
||||
impl IndexType {
|
||||
/// Stable label used by index diagnostics and metrics.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::InvertedIndex => "inverted_index",
|
||||
Self::FulltextIndex => "fulltext_index",
|
||||
Self::BloomFilterIndex => "bloom_filter_index",
|
||||
Self::VectorIndex => "vector_index",
|
||||
Self::HllIndex => "hll_index",
|
||||
Self::KllIndex => "kll_index",
|
||||
Self::MgIndex => "mg_index",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata of indexes created for a specific column in an SST file.
|
||||
///
|
||||
/// This structure tracks which index types have been successfully created for a column.
|
||||
|
||||
+647
-55
@@ -63,8 +63,8 @@ use crate::cache::{CacheManagerRef, CacheStrategy};
|
||||
#[cfg(test)]
|
||||
use crate::config::{BloomFilterConfig, InvertedIndexConfig};
|
||||
use crate::error::{
|
||||
BuildIndexAsyncSnafu, Error, ExternalSnafu, InvalidConfigSnafu, JoinSnafu, RegionClosedSnafu,
|
||||
RegionDroppedSnafu, RegionTruncatedSnafu, Result,
|
||||
BuildIndexAsyncSnafu, Error, ExternalSnafu, InvalidConfigSnafu, JoinSnafu,
|
||||
OperateAbortedIndexSnafu, RegionClosedSnafu, RegionDroppedSnafu, RegionTruncatedSnafu, Result,
|
||||
};
|
||||
use crate::metrics::{
|
||||
INDEX_ARTIFACT_CLEANUP_FAILURE_TOTAL, INDEX_CREATE_DISCARDED_TOTAL, INDEX_CREATE_MEMORY_USAGE,
|
||||
@@ -512,6 +512,20 @@ pub(crate) struct IndexerBuilderImpl {
|
||||
pub(crate) index_options: IndexOptions,
|
||||
}
|
||||
|
||||
impl IndexerBuilderImpl {
|
||||
fn plan(&self) -> Arc<registry::IndexBuildPlan> {
|
||||
if let Some(inputs) = &self.index_build_inputs {
|
||||
return inputs.plan.clone();
|
||||
}
|
||||
Arc::new(self.registry.plan(&handler::PlanContext {
|
||||
metadata: &self.metadata,
|
||||
index_options: &self.index_options,
|
||||
build_type: self.build_type.clone(),
|
||||
existing_indexes: &[],
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl IndexerBuilder for IndexerBuilderImpl {
|
||||
/// Sanity check for arguments and create a new [Indexer] if arguments are valid.
|
||||
@@ -530,17 +544,7 @@ impl IndexerBuilder for IndexerBuilderImpl {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let plan = if let Some(inputs) = &self.index_build_inputs {
|
||||
inputs.plan.clone()
|
||||
} else {
|
||||
let context = handler::PlanContext {
|
||||
metadata: &self.metadata,
|
||||
index_options: &self.index_options,
|
||||
build_type: self.build_type.clone(),
|
||||
existing_indexes: &[],
|
||||
};
|
||||
Arc::new(self.registry.plan(&context))
|
||||
};
|
||||
let plan = self.plan();
|
||||
indexer.failure = plan.check_success().err();
|
||||
let mut context = handler::BuildContext {
|
||||
metadata: &self.metadata,
|
||||
@@ -796,7 +800,7 @@ pub struct IndexBuildTask {
|
||||
pub file_purger: FilePurgerRef,
|
||||
/// When write cache is enabled, the indexer builder should be built from the write cache.
|
||||
/// Otherwise, it should be built from the access layer.
|
||||
pub indexer_builder: Arc<dyn IndexerBuilder + Send + Sync>,
|
||||
pub(crate) indexer_builder: Arc<IndexerBuilderImpl>,
|
||||
/// Request sender to notify the region worker.
|
||||
pub(crate) request_sender: Sender<WorkerRequestWithTime>,
|
||||
/// Senders of callers waiting for this build. Coalesced tasks and
|
||||
@@ -957,16 +961,20 @@ impl IndexBuildTask {
|
||||
// Taken before `prepare_source` replaces the source, and used for the
|
||||
// index files and listener events of this build.
|
||||
let region_file_id = self.region_file_id();
|
||||
if let ControlFlow::Break(report) =
|
||||
self.prepare_source(region_file_id, &version_control).await
|
||||
if let ControlFlow::Break(report) = self
|
||||
.prepare_source(region_file_id, &version_control)
|
||||
.await?
|
||||
{
|
||||
return Ok(report);
|
||||
}
|
||||
let new_index_version = self
|
||||
.source
|
||||
.file_meta
|
||||
.index_version()
|
||||
.map_or(0, |version| version + 1);
|
||||
// Metadata-only removal leaves no current index, but its version still reserves
|
||||
// every older path until GC finishes. Never reuse those paths on a later build.
|
||||
let file_meta = &self.source.file_meta;
|
||||
let new_index_version = if file_meta.index_version > 0 || file_meta.exists_index() {
|
||||
file_meta.index_version + 1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let (mut indexer, index_output) =
|
||||
match self.create_index(region_file_id, new_index_version).await? {
|
||||
ControlFlow::Continue(created) => created,
|
||||
@@ -992,13 +1000,13 @@ impl IndexBuildTask {
|
||||
&mut self,
|
||||
region_file_id: RegionFileId,
|
||||
version_control: &VersionControlRef,
|
||||
) -> ControlFlow<IndexBuildReport> {
|
||||
) -> Result<ControlFlow<IndexBuildReport>> {
|
||||
// Check SST file existence before building index to avoid failure of parquet reader.
|
||||
if !self.check_sst_file_exists(version_control).await {
|
||||
return ControlFlow::Break(
|
||||
return Ok(ControlFlow::Break(
|
||||
self.abort_and_notify(region_file_id, "SST file not found during index build")
|
||||
.await,
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
// A task may have waited behind another build of the same SST. Build on
|
||||
@@ -1011,41 +1019,80 @@ impl IndexBuildTask {
|
||||
.get(&self.source.file_meta.file_id)
|
||||
.cloned();
|
||||
let Some(current_file_meta) = current_file_meta else {
|
||||
return ControlFlow::Break(
|
||||
return Ok(ControlFlow::Break(
|
||||
self.abort_and_notify(
|
||||
region_file_id,
|
||||
"SST file not found in manifest during index build",
|
||||
)
|
||||
.await,
|
||||
);
|
||||
));
|
||||
};
|
||||
self.indexer_builder
|
||||
.registry
|
||||
.validate_required_kinds(&self.target_region_metadata, [¤t_file_meta])
|
||||
.with_context(|_| ExternalSnafu {
|
||||
context: "validating index handlers for rebuild".to_string(),
|
||||
})?;
|
||||
let context = handler::PlanContext {
|
||||
metadata: &self.target_region_metadata,
|
||||
index_options: &self.index_options,
|
||||
build_type: self.reason.clone(),
|
||||
existing_indexes: ¤t_file_meta.indexes,
|
||||
};
|
||||
let plan = Arc::new(self.indexer_builder.registry.plan(&context));
|
||||
plan.check_success().context(BuildIndexAsyncSnafu {
|
||||
region_id: self.region_id,
|
||||
})?;
|
||||
let currency = handler::CurrencyContext {
|
||||
metadata: &self.target_region_metadata,
|
||||
index_options: &self.index_options,
|
||||
build_type: self.reason.clone(),
|
||||
};
|
||||
if self.reason == IndexBuildType::Manual
|
||||
&& current_file_meta.is_index_consistent_with_region(
|
||||
&self.target_region_metadata.column_metadatas,
|
||||
&self.index_options,
|
||||
)
|
||||
&& plan.is_current(¤t_file_meta, ¤cy)
|
||||
{
|
||||
return ControlFlow::Break(
|
||||
return Ok(ControlFlow::Break(
|
||||
self.abort_and_notify(region_file_id, "Index is already up to date")
|
||||
.await,
|
||||
);
|
||||
));
|
||||
}
|
||||
let current_file = FileHandle::new(current_file_meta.clone(), self.file_purger.clone());
|
||||
let builder = Arc::make_mut(&mut self.indexer_builder);
|
||||
if let Some(inputs) = &mut builder.index_build_inputs {
|
||||
inputs.plan = plan;
|
||||
inputs.inputs = vec![current_file.clone()].into();
|
||||
inputs.output_rows = Some(current_file_meta.num_rows);
|
||||
}
|
||||
self.file = current_file;
|
||||
self.source.file_meta = current_file_meta;
|
||||
ControlFlow::Continue(())
|
||||
Ok(ControlFlow::Continue(()))
|
||||
}
|
||||
|
||||
/// Reads the SST and creates the index files.
|
||||
/// Builds a replacement index file, scanning data only when a creator needs rows.
|
||||
async fn create_index(
|
||||
&self,
|
||||
region_file_id: RegionFileId,
|
||||
new_index_version: u64,
|
||||
) -> Result<ControlFlow<IndexBuildReport, (Indexer, IndexOutput)>> {
|
||||
let mut parquet_reader = self
|
||||
let reader_builder = self
|
||||
.access_layer
|
||||
.read_sst(self.file.clone()) // use the latest file handle instead of creating a new one
|
||||
.expected_metadata(Some(self.target_region_metadata.clone()))
|
||||
.build()
|
||||
.await?;
|
||||
.read_sst(self.file.clone())
|
||||
.expected_metadata(Some(self.target_region_metadata.clone()));
|
||||
let plan = self.indexer_builder.plan();
|
||||
// Inverted segments must align with the actual SST row groups. Other
|
||||
// creators can decide input reuse without opening the Parquet file.
|
||||
let needs_row_group_size = plan
|
||||
.entries()
|
||||
.any(|entry| entry.kind.index_type() == IndexType::InvertedIndex);
|
||||
let mut parquet_reader = if needs_row_group_size {
|
||||
reader_builder.build().await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let row_group_size = parquet_reader.as_ref().and_then(|reader| {
|
||||
reader
|
||||
@@ -1055,39 +1102,101 @@ impl IndexBuildTask {
|
||||
.map(|row_group| row_group.num_rows() as usize)
|
||||
.filter(|size| *size > 0)
|
||||
});
|
||||
|
||||
let mut indexer = self
|
||||
.indexer_builder
|
||||
.build(region_file_id, new_index_version, row_group_size)
|
||||
.await;
|
||||
// The build type or index options may leave nothing to build. Return before reading
|
||||
// any row; an empty indexer finishes with no output, which publishes nothing.
|
||||
if let Err(err) = self.check_rebuild_indexer(&indexer) {
|
||||
indexer.abort().await;
|
||||
return Err(err).context(BuildIndexAsyncSnafu {
|
||||
region_id: self.region_id,
|
||||
});
|
||||
}
|
||||
if indexer.is_empty() {
|
||||
if self.can_remove_all_indexes() {
|
||||
return Ok(ControlFlow::Continue((indexer, IndexOutput::default())));
|
||||
}
|
||||
return Ok(ControlFlow::Break(self.aborted("No index to build")));
|
||||
}
|
||||
|
||||
if let Some(mut parquet_reader) = parquet_reader.take() {
|
||||
// TODO(SNC123): optimize index batch
|
||||
loop {
|
||||
match parquet_reader.next_record_batch().await {
|
||||
if indexer.requires_row_scan() && !needs_row_group_size {
|
||||
parquet_reader = match reader_builder.build().await {
|
||||
Ok(reader) => reader,
|
||||
Err(err) => {
|
||||
indexer.abort().await;
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
}
|
||||
if indexer.requires_row_scan()
|
||||
&& let Some(mut reader) = parquet_reader.take()
|
||||
{
|
||||
while indexer.requires_row_scan() {
|
||||
match reader.next_record_batch().await {
|
||||
Ok(Some(batch)) => {
|
||||
indexer.update_flat(&batch).await;
|
||||
if let Err(err) = self.check_rebuild_indexer(&indexer) {
|
||||
indexer.abort().await;
|
||||
return Err(err).context(BuildIndexAsyncSnafu {
|
||||
region_id: self.region_id,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(e) => {
|
||||
Err(err) => {
|
||||
indexer.abort().await;
|
||||
return Err(e);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let index_output = indexer.finish().await;
|
||||
|
||||
if index_output.file_size == 0 {
|
||||
// The indexer logs and drops index creation failures.
|
||||
let output = indexer.finish().await;
|
||||
if let Err(err) = self.check_rebuild_indexer(&indexer) {
|
||||
indexer.abort().await;
|
||||
return Err(err).context(BuildIndexAsyncSnafu {
|
||||
region_id: self.region_id,
|
||||
});
|
||||
}
|
||||
if output.file_size == 0 {
|
||||
return Ok(ControlFlow::Break(self.aborted("No index was created")));
|
||||
}
|
||||
Ok(ControlFlow::Continue((indexer, index_output)))
|
||||
Ok(ControlFlow::Continue((indexer, output)))
|
||||
}
|
||||
|
||||
/// A budget skip may omit a new kind, but must not erase an existing one.
|
||||
fn check_rebuild_indexer(&self, indexer: &Indexer) -> Result<(), Arc<Error>> {
|
||||
indexer.check_success()?;
|
||||
let source = &self.source.file_meta;
|
||||
if indexer.discarded().iter().any(|kind| {
|
||||
let index_type = kind.index_type();
|
||||
source.available_indexes.contains(&index_type)
|
||||
|| source
|
||||
.indexes
|
||||
.iter()
|
||||
.any(|column| column.created_indexes.contains(&index_type))
|
||||
}) {
|
||||
warn!(
|
||||
"Preserving previous index generation after budget discard, region_id: {}, file_id: {}, discarded: {:?}",
|
||||
self.region_id,
|
||||
source.file_id,
|
||||
indexer.discarded()
|
||||
);
|
||||
return Err(Arc::new(OperateAbortedIndexSnafu.build()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Disabled options may remove old indexes after handler validation.
|
||||
/// A failed plan is not an empty removal plan and must retain the old file.
|
||||
fn can_remove_all_indexes(&self) -> bool {
|
||||
self.source.file_meta.exists_index()
|
||||
&& self
|
||||
.indexer_builder
|
||||
.index_build_inputs
|
||||
.as_ref()
|
||||
.is_some_and(|inputs| {
|
||||
inputs.plan.check_success().is_ok() && inputs.plan.entries().next().is_none()
|
||||
})
|
||||
}
|
||||
|
||||
/// Uploads the index files and commits them to the manifest.
|
||||
@@ -1185,6 +1294,9 @@ impl IndexBuildTask {
|
||||
index_file_id: FileId,
|
||||
index_version: u64,
|
||||
) -> Result<()> {
|
||||
if output.file_size == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(write_cache) = &self.write_cache {
|
||||
let file_id = self.source.file_meta.file_id;
|
||||
let region_id = self.source.file_meta.region_id;
|
||||
@@ -2118,6 +2230,13 @@ mod tests {
|
||||
}],
|
||||
}
|
||||
}
|
||||
fn is_current(
|
||||
&self,
|
||||
_: &crate::sst::file::FileMeta,
|
||||
_: &handler::CurrencyContext<'_>,
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn memory_limit(&self) -> Option<usize> {
|
||||
self.hard_limit
|
||||
@@ -2241,6 +2360,13 @@ mod tests {
|
||||
format_version: 2,
|
||||
}]
|
||||
}
|
||||
fn is_current(
|
||||
&self,
|
||||
_: &crate::sst::file::FileMeta,
|
||||
_: &handler::CurrencyContext<'_>,
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn memory_limit(&self) -> Option<usize> {
|
||||
(self.0 == ProviderFailure::Budget).then_some(16)
|
||||
@@ -2475,6 +2601,41 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_extension_finish_failure_discards_completed_builtin_output() {
|
||||
for failure in [ProviderFailure::None, ProviderFailure::Finish] {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let mut builder = mock_indexer_builder(Arc::new(sst_region_metadata()), &env).await;
|
||||
let builder = Arc::make_mut(&mut builder);
|
||||
builder.build_type = IndexBuildType::Compact;
|
||||
Arc::make_mut(&mut builder.registry)
|
||||
.register(Arc::new(FailingProvider(failure)))
|
||||
.unwrap();
|
||||
let mut indexer = builder.build(random_region_file_id(), 0, Some(1024)).await;
|
||||
// Registry order puts real built-in creators before the failing extension.
|
||||
assert!(indexer.creators.first().unwrap().is_builtin());
|
||||
assert!(!indexer.creators.last().unwrap().is_builtin());
|
||||
indexer
|
||||
.update_flat(&new_record_batch_by_range(&["a", "b"], 0, 10))
|
||||
.await;
|
||||
assert!(indexer.check_success().is_ok());
|
||||
let output = indexer.finish().await;
|
||||
if failure == ProviderFailure::None {
|
||||
assert!(output.entries.iter().any(|entry| entry.kind.is_builtin()));
|
||||
assert!(output.entries.iter().any(|entry| !entry.kind.is_builtin()));
|
||||
assert!(output.file_size > 0);
|
||||
assert!(indexer.check_success().is_ok());
|
||||
} else {
|
||||
// A shared writer cannot publish the preceding successful index alone.
|
||||
assert!(output.entries.is_empty());
|
||||
assert!(output.build_indexes().unwrap().is_empty());
|
||||
assert_eq!(output.file_size, 0);
|
||||
assert!(indexer.check_success().is_err());
|
||||
}
|
||||
assert!(indexer.creators.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_provider_compaction_only_and_per_output() {
|
||||
let (dir, factory) = PuffinManagerFactory::new_for_test_async("provider_scope").await;
|
||||
@@ -2524,6 +2685,9 @@ mod tests {
|
||||
);
|
||||
assert!(!first.is_empty());
|
||||
assert!(!second.is_empty());
|
||||
// Deferring the built-in indexes must retain the sketch creator.
|
||||
first.disable_builtin_indexes().await;
|
||||
assert!(!first.creators.is_empty());
|
||||
assert_eq!(first.creators[0].creator.memory_usage(), 17);
|
||||
first.abort().await;
|
||||
assert!(first.creators.is_empty());
|
||||
@@ -3154,6 +3318,11 @@ mod tests {
|
||||
file_size: sst_info.file_size,
|
||||
max_row_group_uncompressed_size: sst_info.max_row_group_uncompressed_size,
|
||||
available_indexes: smallvec![IndexType::InvertedIndex],
|
||||
indexes: vec![ColumnIndexMetadata {
|
||||
column_id: 2,
|
||||
created_indexes: smallvec::smallvec![IndexType::InvertedIndex],
|
||||
..Default::default()
|
||||
}],
|
||||
// Old manifests may publish an index without recording its size.
|
||||
index_file_size: 0,
|
||||
index_version: 0,
|
||||
@@ -3210,6 +3379,18 @@ mod tests {
|
||||
assert!(updated_meta.index_file_size > 0);
|
||||
assert_eq!(updated_meta.file_id, file_meta.file_id);
|
||||
assert_eq!(updated_meta.index_version, 1);
|
||||
// This built-in-only rebuild must not advertise extension indexes.
|
||||
assert!(
|
||||
updated_meta
|
||||
.indexes
|
||||
.iter()
|
||||
.all(|index| index.created_indexes.iter().all(|kind| !matches!(
|
||||
kind,
|
||||
crate::sst::file::IndexType::HllIndex
|
||||
| crate::sst::file::IndexType::KllIndex
|
||||
| crate::sst::file::IndexType::MgIndex
|
||||
)))
|
||||
);
|
||||
let field_0_index = updated_meta
|
||||
.indexes
|
||||
.iter()
|
||||
@@ -3343,8 +3524,308 @@ mod tests {
|
||||
schedule_index_build_task_with_mode(IndexBuildMode::Sync).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rebuild_scans_only_when_a_creator_requires_rows() {
|
||||
for with_builtin in [false, true] {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let mut metadata = sst_region_metadata();
|
||||
if !with_builtin {
|
||||
for column in &mut metadata.column_metadatas {
|
||||
column.column_schema.set_inverted_index(false);
|
||||
column.column_schema.unset_skipping_options().unwrap();
|
||||
}
|
||||
}
|
||||
let metadata = Arc::new(metadata);
|
||||
let manifest_ctx = env.mock_manifest_context(metadata.clone()).await;
|
||||
let file_purger = Arc::new(NoopFilePurger {});
|
||||
let info = mock_sst_file(metadata.clone(), &env, IndexBuildMode::Async).await;
|
||||
let file_meta = FileMeta {
|
||||
region_id: metadata.region_id,
|
||||
file_id: info.file_id,
|
||||
file_size: info.file_size,
|
||||
max_row_group_uncompressed_size: info.max_row_group_uncompressed_size,
|
||||
num_rows: info.num_rows as u64,
|
||||
num_row_groups: info.num_row_groups,
|
||||
..Default::default()
|
||||
};
|
||||
seed_manifest_file(&manifest_ctx, &file_meta).await;
|
||||
let version = mock_version_control(
|
||||
metadata.clone(),
|
||||
file_purger.clone(),
|
||||
HashMap::from([(file_meta.file_id, file_meta.clone())]),
|
||||
)
|
||||
.await;
|
||||
let mut builder = mock_indexer_builder(metadata.clone(), &env).await;
|
||||
let mutable = Arc::make_mut(&mut builder);
|
||||
mutable.build_type = IndexBuildType::Manual;
|
||||
Arc::make_mut(&mut mutable.registry)
|
||||
.register(Arc::new(FailingProvider(ProviderFailure::Reused)))
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
let mut task = IndexBuildTask {
|
||||
region_id: metadata.region_id,
|
||||
file: FileHandle::new(file_meta.clone(), file_purger.clone()),
|
||||
target_region_metadata: metadata.clone(),
|
||||
source: IndexBuildSource::new(file_meta.clone(), metadata.schema_version),
|
||||
reason: IndexBuildType::Manual,
|
||||
access_layer: env.access_layer.clone(),
|
||||
listener: WorkerListener::default(),
|
||||
manifest_ctx: manifest_ctx.clone(),
|
||||
write_cache: None,
|
||||
cache_manager: None,
|
||||
file_purger,
|
||||
indexer_builder: builder,
|
||||
request_sender: tx,
|
||||
index_options: IndexOptions::default(),
|
||||
result_senders: Vec::new(),
|
||||
};
|
||||
if !with_builtin {
|
||||
// A reuse-only build must not open even the Parquet footer.
|
||||
// Keep the file identity published, but make footer reads fail.
|
||||
let path = task
|
||||
.file
|
||||
.file_path(env.access_layer.table_dir(), env.access_layer.path_type());
|
||||
env.access_layer
|
||||
.object_store()
|
||||
.write(&path, Bytes::from_static(b"not a parquet file"))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
// The reused test creator fails if it receives rows. Adding a builtin
|
||||
// changes only the scan requirement, so it must exercise that failure.
|
||||
let result = task.index_build(version).await;
|
||||
assert_eq!(result.is_err(), with_builtin);
|
||||
let published = manifest_ctx.manifest().await.files[&file_meta.file_id].clone();
|
||||
if with_builtin {
|
||||
assert_eq!(published, file_meta);
|
||||
} else {
|
||||
assert_eq!(
|
||||
published.available_indexes.as_slice(),
|
||||
&[IndexType::HllIndex]
|
||||
);
|
||||
assert!(published.index_file_size > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rebuild_failure_preserves_published_indexes() {
|
||||
for (failure, old_hll) in [
|
||||
(Some(ProviderFailure::Plan), true),
|
||||
(Some(ProviderFailure::Create), true),
|
||||
(Some(ProviderFailure::UpdateFlat), true),
|
||||
(Some(ProviderFailure::Finish), true),
|
||||
(Some(ProviderFailure::Budget), true),
|
||||
(Some(ProviderFailure::Budget), false),
|
||||
(None, true),
|
||||
(None, false),
|
||||
] {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let metadata = Arc::new(sst_region_metadata());
|
||||
let region_id = metadata.region_id;
|
||||
let manifest_ctx = env.mock_manifest_context(metadata.clone()).await;
|
||||
let file_purger = Arc::new(NoopFilePurger {});
|
||||
let info = mock_sst_file(metadata.clone(), &env, IndexBuildMode::Async).await;
|
||||
let initial = FileMeta {
|
||||
region_id,
|
||||
file_id: info.file_id,
|
||||
file_size: info.file_size,
|
||||
max_row_group_uncompressed_size: info.max_row_group_uncompressed_size,
|
||||
num_rows: info.num_rows as u64,
|
||||
num_row_groups: info.num_row_groups,
|
||||
..Default::default()
|
||||
};
|
||||
seed_manifest_file(&manifest_ctx, &initial).await;
|
||||
let version = mock_version_control(
|
||||
metadata.clone(),
|
||||
file_purger.clone(),
|
||||
HashMap::from([(initial.file_id, initial.clone())]),
|
||||
)
|
||||
.await;
|
||||
let mut builder = mock_indexer_builder(metadata.clone(), &env).await;
|
||||
Arc::make_mut(&mut builder).build_type = IndexBuildType::Manual;
|
||||
if old_hll {
|
||||
Arc::make_mut(&mut Arc::make_mut(&mut builder).registry)
|
||||
.register(Arc::new(FailingProvider(ProviderFailure::None)))
|
||||
.unwrap();
|
||||
}
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
let mut task = IndexBuildTask {
|
||||
region_id,
|
||||
file: FileHandle::new(initial.clone(), file_purger.clone()),
|
||||
target_region_metadata: metadata.clone(),
|
||||
source: IndexBuildSource::new(initial.clone(), metadata.schema_version),
|
||||
reason: IndexBuildType::Manual,
|
||||
access_layer: env.access_layer.clone(),
|
||||
listener: WorkerListener::default(),
|
||||
manifest_ctx: manifest_ctx.clone(),
|
||||
write_cache: None,
|
||||
cache_manager: None,
|
||||
file_purger: file_purger.clone(),
|
||||
indexer_builder: builder,
|
||||
request_sender: tx,
|
||||
index_options: IndexOptions::default(),
|
||||
result_senders: Vec::new(),
|
||||
};
|
||||
// First publish real built-in blobs and the test provider's HLL blob.
|
||||
task.index_build(version).await.unwrap();
|
||||
let old = manifest_ctx.manifest().await.files[&initial.file_id].clone();
|
||||
assert_eq!(
|
||||
old.available_indexes.contains(&IndexType::HllIndex),
|
||||
old_hll
|
||||
);
|
||||
assert!(
|
||||
old.available_indexes
|
||||
.iter()
|
||||
.any(|kind| *kind != IndexType::HllIndex)
|
||||
);
|
||||
let old_path = location::index_file_path(
|
||||
env.access_layer.table_dir(),
|
||||
RegionIndexId::new(RegionFileId::new(region_id, old.file_id), old.index_version),
|
||||
env.access_layer.path_type(),
|
||||
);
|
||||
let old_bytes = env
|
||||
.access_layer
|
||||
.object_store()
|
||||
.read(&old_path)
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes();
|
||||
assert!(!old_bytes.is_empty());
|
||||
let version = mock_version_control(
|
||||
metadata.clone(),
|
||||
file_purger.clone(),
|
||||
HashMap::from([(old.file_id, old.clone())]),
|
||||
)
|
||||
.await;
|
||||
let mut builder = mock_indexer_builder(metadata.clone(), &env).await;
|
||||
Arc::make_mut(&mut builder).build_type = IndexBuildType::Manual;
|
||||
if let Some(failure) = failure {
|
||||
Arc::make_mut(&mut Arc::make_mut(&mut builder).registry)
|
||||
.register(Arc::new(FailingProvider(failure)))
|
||||
.unwrap();
|
||||
}
|
||||
if failure.is_none() && !old_hll {
|
||||
// Newly configured sketches must also fail before replacing the
|
||||
// built-in indexes when their provider is unavailable.
|
||||
Arc::make_mut(&mut task.target_region_metadata).column_metadatas[0]
|
||||
.column_schema
|
||||
.mut_metadata()
|
||||
.insert(
|
||||
datatypes::schema::HLL_KEY.into(),
|
||||
r#"{"precision":10}"#.into(),
|
||||
);
|
||||
}
|
||||
task.file = FileHandle::new(old.clone(), file_purger);
|
||||
task.source = IndexBuildSource::new(old.clone(), metadata.schema_version);
|
||||
task.indexer_builder = builder;
|
||||
let result = task.index_build(version).await;
|
||||
let published = manifest_ctx.manifest().await.files[&old.file_id].clone();
|
||||
if old_hll || failure.is_none() {
|
||||
assert!(result.is_err(), "maintenance must fail for {failure:?}");
|
||||
assert_eq!(
|
||||
old, published,
|
||||
"failed {failure:?} must not change manifest"
|
||||
);
|
||||
} else {
|
||||
result.unwrap();
|
||||
assert_eq!(published.index_version, old.index_version + 1);
|
||||
assert!(!published.available_indexes.contains(&IndexType::HllIndex));
|
||||
assert!(
|
||||
published
|
||||
.indexes
|
||||
.iter()
|
||||
.all(|column| !column.created_indexes.contains(&IndexType::HllIndex))
|
||||
);
|
||||
let expected: Vec<_> = old
|
||||
.available_indexes
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|kind| *kind != IndexType::HllIndex)
|
||||
.collect();
|
||||
assert_eq!(published.available_indexes.as_slice(), expected.as_slice());
|
||||
assert!(published.index_file_size > 0);
|
||||
}
|
||||
// NoopFilePurger keeps the historical generation available for byte comparison.
|
||||
assert_eq!(
|
||||
old_bytes,
|
||||
env.access_layer
|
||||
.object_store()
|
||||
.read(&old_path)
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_index_build_task_no_index() {
|
||||
for remove_sketches in [false, true] {
|
||||
check_empty_index_build(remove_sketches, true).await;
|
||||
if remove_sketches {
|
||||
check_empty_index_build(true, false).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RemoveTestIndex;
|
||||
|
||||
impl handler::IndexKindHandler for RemoveTestIndex {
|
||||
fn kinds(&self) -> &[kind::IndexKind] {
|
||||
&[kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll)]
|
||||
}
|
||||
|
||||
fn plan(
|
||||
&self,
|
||||
context: &handler::PlanContext<'_>,
|
||||
) -> std::result::Result<
|
||||
Option<Arc<dyn handler::PlannedIndex>>,
|
||||
common_error::ext::BoxedError,
|
||||
> {
|
||||
Ok(context
|
||||
.existing_indexes
|
||||
.iter()
|
||||
.any(|column| {
|
||||
column
|
||||
.created_indexes
|
||||
.contains(&crate::sst::file::IndexType::HllIndex)
|
||||
})
|
||||
.then(|| Arc::new(Self) as Arc<dyn handler::PlannedIndex>))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl handler::PlannedIndex for RemoveTestIndex {
|
||||
fn kinds(&self) -> &[kind::IndexKind] {
|
||||
handler::IndexKindHandler::kinds(self)
|
||||
}
|
||||
|
||||
fn entries(&self) -> &[handler::PlanEntry] {
|
||||
&[]
|
||||
}
|
||||
|
||||
async fn build(
|
||||
&self,
|
||||
_: &handler::BuildContext<'_>,
|
||||
) -> std::result::Result<
|
||||
Option<Box<dyn handler::IndexCreator>>,
|
||||
common_error::ext::BoxedError,
|
||||
> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn is_current(&self, file: &FileMeta, _: &handler::CurrencyContext<'_>) -> bool {
|
||||
!file.indexes.iter().any(|column| {
|
||||
column
|
||||
.created_indexes
|
||||
.contains(&crate::sst::file::IndexType::HllIndex)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_empty_index_build(remove_sketches: bool, registered: bool) {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let mut scheduler = env.mock_index_build_scheduler(4);
|
||||
let mut metadata = sst_region_metadata();
|
||||
@@ -3358,7 +3839,7 @@ mod tests {
|
||||
let manifest_ctx = env.mock_manifest_context(metadata.clone()).await;
|
||||
let file_purger = Arc::new(NoopFilePurger {});
|
||||
let sst_info = mock_sst_file(metadata.clone(), &env, IndexBuildMode::Async).await;
|
||||
let file_meta = FileMeta {
|
||||
let mut file_meta = FileMeta {
|
||||
region_id,
|
||||
file_id: sst_info.file_id,
|
||||
file_size: sst_info.file_size,
|
||||
@@ -3368,13 +3849,47 @@ mod tests {
|
||||
num_row_groups: sst_info.num_row_groups,
|
||||
..Default::default()
|
||||
};
|
||||
if remove_sketches {
|
||||
file_meta
|
||||
.indexes
|
||||
.push(crate::sst::file::ColumnIndexMetadata {
|
||||
column_id: metadata.column_metadatas[0].column_id,
|
||||
created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex],
|
||||
fulltext_bloom_version: 0,
|
||||
});
|
||||
file_meta.index_file_size = 123;
|
||||
}
|
||||
seed_manifest_file(&manifest_ctx, &file_meta).await;
|
||||
let files = HashMap::from([(file_meta.file_id, file_meta.clone())]);
|
||||
let version_control =
|
||||
mock_version_control(metadata.clone(), file_purger.clone(), files).await;
|
||||
let indexer_builder = mock_indexer_builder(metadata.clone(), &env).await;
|
||||
|
||||
let mut indexer_builder = mock_indexer_builder(metadata.clone(), &env).await;
|
||||
let file = FileHandle::new(file_meta.clone(), file_purger.clone());
|
||||
if remove_sketches {
|
||||
// A registered owner can remove its index after options are disabled.
|
||||
let builder = Arc::make_mut(&mut indexer_builder);
|
||||
if registered {
|
||||
Arc::make_mut(&mut builder.registry)
|
||||
.register(Arc::new(RemoveTestIndex))
|
||||
.unwrap();
|
||||
}
|
||||
let plan = builder.registry.plan(&handler::PlanContext {
|
||||
metadata: &metadata,
|
||||
index_options: &builder.index_options,
|
||||
build_type: IndexBuildType::SchemaChange,
|
||||
existing_indexes: &file_meta.indexes,
|
||||
});
|
||||
assert_eq!(!plan.is_empty(), registered);
|
||||
assert!(plan.entries().next().is_none());
|
||||
builder.index_build_inputs = Some(build::IndexBuildInputs {
|
||||
output_rows: None,
|
||||
plan: Arc::new(plan),
|
||||
inputs: vec![file.clone()].into(),
|
||||
input_puffin_manager: builder.puffin_manager.clone(),
|
||||
can_merge_inputs: false,
|
||||
memory_limit: None,
|
||||
});
|
||||
}
|
||||
|
||||
// Create mock task.
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
@@ -3387,10 +3902,10 @@ mod tests {
|
||||
file_meta.clone(),
|
||||
version_control.current().version.metadata.schema_version,
|
||||
),
|
||||
reason: IndexBuildType::Flush,
|
||||
reason: IndexBuildType::SchemaChange,
|
||||
access_layer: env.access_layer.clone(),
|
||||
listener: WorkerListener::default(),
|
||||
manifest_ctx,
|
||||
manifest_ctx: manifest_ctx.clone(),
|
||||
write_cache: None,
|
||||
cache_manager: None,
|
||||
file_purger,
|
||||
@@ -3400,7 +3915,84 @@ mod tests {
|
||||
result_senders: vec![result_tx],
|
||||
};
|
||||
|
||||
scheduler.schedule_build(&version_control, task).await;
|
||||
if remove_sketches && !registered {
|
||||
let mut task = task;
|
||||
assert!(task.index_build(version_control.clone()).await.is_err());
|
||||
assert_eq!(
|
||||
manifest_ctx.manifest().await.files[&file_meta.file_id],
|
||||
file_meta
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if remove_sketches {
|
||||
assert!(task.can_remove_all_indexes());
|
||||
for column_level in [false, true] {
|
||||
let mut mixed = task.clone();
|
||||
if column_level {
|
||||
mixed.source.file_meta.indexes[0]
|
||||
.created_indexes
|
||||
.push(IndexType::InvertedIndex);
|
||||
} else {
|
||||
mixed
|
||||
.source
|
||||
.file_meta
|
||||
.available_indexes
|
||||
.push(IndexType::InvertedIndex);
|
||||
}
|
||||
assert!(mixed.can_remove_all_indexes());
|
||||
}
|
||||
}
|
||||
|
||||
scheduler
|
||||
.schedule_build(&version_control, task.clone())
|
||||
.await;
|
||||
|
||||
if remove_sketches {
|
||||
let finished = recv_index_build_finished(&mut rx).await;
|
||||
assert!(finished.file_meta.indexes.is_empty());
|
||||
assert!(finished.file_meta.available_indexes.is_empty());
|
||||
assert_eq!(finished.file_meta.index_file_size, 0);
|
||||
assert_eq!(finished.file_meta.index_version, 1);
|
||||
assert!(
|
||||
manifest_ctx.manifest().await.files[&file_meta.file_id]
|
||||
.indexes
|
||||
.is_empty()
|
||||
);
|
||||
// Reconstruct the file from persisted metadata as reopening does, then enable
|
||||
// an ordinary index. Its new Puffin must not reuse the historical version 0.
|
||||
let persisted = serde_json::to_vec(&finished.file_meta).unwrap();
|
||||
let reopened: FileMeta = serde_json::from_slice(&persisted).unwrap();
|
||||
assert!(!reopened.exists_index());
|
||||
let target_metadata = Arc::new(sst_region_metadata());
|
||||
let reopened_version = mock_version_control(
|
||||
target_metadata.clone(),
|
||||
task.file_purger.clone(),
|
||||
HashMap::from([(reopened.file_id, reopened.clone())]),
|
||||
)
|
||||
.await;
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
let mut rebuild = task;
|
||||
rebuild.file = FileHandle::new(reopened.clone(), rebuild.file_purger.clone());
|
||||
rebuild.source.file_meta = reopened;
|
||||
rebuild.target_region_metadata = target_metadata.clone();
|
||||
rebuild.indexer_builder = mock_indexer_builder(target_metadata, &env).await;
|
||||
rebuild.request_sender = tx;
|
||||
let mut reopened_scheduler = env.mock_index_build_scheduler(4);
|
||||
reopened_scheduler
|
||||
.schedule_build(&reopened_version, rebuild)
|
||||
.await;
|
||||
let rebuilt = recv_index_build_finished(&mut rx).await;
|
||||
assert!(rebuilt.file_meta.exists_index());
|
||||
assert_eq!(rebuilt.file_meta.index_version, 2);
|
||||
let path = location::index_file_path(
|
||||
env.access_layer.table_dir(),
|
||||
RegionIndexId::new(RegionFileId::new(region_id, file_meta.file_id), 2),
|
||||
env.access_layer.path_type(),
|
||||
);
|
||||
assert!(env.access_layer.object_store().exists(&path).await.unwrap());
|
||||
return;
|
||||
}
|
||||
|
||||
// No index needs to be built, so the SST is not read.
|
||||
assert!(matches!(
|
||||
|
||||
@@ -28,7 +28,7 @@ use store_api::storage::ColumnId;
|
||||
|
||||
use crate::read::Batch;
|
||||
use crate::region::options::IndexOptions;
|
||||
use crate::sst::file::{ColumnIndexMetadata, FileHandle, RegionIndexId};
|
||||
use crate::sst::file::{ColumnIndexMetadata, FileHandle, FileMeta, RegionIndexId};
|
||||
use crate::sst::index::intermediate::IntermediateManager;
|
||||
use crate::sst::index::kind::IndexKind;
|
||||
use crate::sst::index::puffin_manager::{SstPuffinManager, SstPuffinWriter};
|
||||
@@ -89,6 +89,16 @@ pub struct BuildContext<'a> {
|
||||
pub output_rows: Option<u64>,
|
||||
}
|
||||
|
||||
/// Current schema and options against which published entries are checked.
|
||||
pub struct CurrencyContext<'a> {
|
||||
/// Shared region schema.
|
||||
pub metadata: &'a RegionMetadataRef,
|
||||
/// Region index options.
|
||||
pub index_options: &'a IndexOptions,
|
||||
/// Lifecycle event requesting the check.
|
||||
pub build_type: IndexBuildType,
|
||||
}
|
||||
|
||||
/// Shared plugin installed by the embedding application.
|
||||
pub type IndexKindProviderRef = Arc<dyn IndexKindProvider>;
|
||||
|
||||
@@ -104,6 +114,12 @@ pub trait IndexKindHandler: Send + Sync + Debug {
|
||||
/// entirely built-in or entirely extension kinds.
|
||||
fn kinds(&self) -> &[IndexKind];
|
||||
|
||||
/// Validates options at region creation, even when this lifecycle event does
|
||||
/// not build indexes. Implementations can override operation-specific planning.
|
||||
fn validate(&self, context: &PlanContext<'_>) -> Result<(), BoxedError> {
|
||||
self.plan(context).map(|_| ())
|
||||
}
|
||||
|
||||
/// Prepares typed parameters. `None` means no work; an empty entry list may
|
||||
/// still request removal of obsolete descriptors during maintenance.
|
||||
fn plan(&self, context: &PlanContext<'_>) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError>;
|
||||
@@ -124,6 +140,9 @@ pub trait PlannedIndex: Send + Sync + Debug {
|
||||
context: &BuildContext<'_>,
|
||||
) -> Result<Option<Box<dyn IndexCreator>>, BoxedError>;
|
||||
|
||||
/// Whether persisted entries satisfy this plan.
|
||||
fn is_current(&self, file: &FileMeta, context: &CurrencyContext<'_>) -> bool;
|
||||
|
||||
/// Whether building this plan can reuse persisted input summaries.
|
||||
/// Row-only plans do not require checking input object existence.
|
||||
fn needs_input_reuse(&self) -> bool {
|
||||
|
||||
@@ -24,10 +24,13 @@ use common_error::ext::BoxedError;
|
||||
use index::target::IndexTarget;
|
||||
|
||||
use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig};
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::sst::index::handler::builtin::bloom::BloomPlan;
|
||||
use crate::sst::index::handler::builtin::fulltext::FulltextPlan;
|
||||
use crate::sst::index::handler::builtin::inverted::InvertedPlan;
|
||||
use crate::sst::index::handler::{IndexKindHandler, PlanContext, PlanEntry, PlannedIndex};
|
||||
use crate::sst::index::handler::{
|
||||
CurrencyContext, IndexKindHandler, PlanContext, PlanEntry, PlannedIndex,
|
||||
};
|
||||
use crate::sst::index::kind::IndexKind;
|
||||
|
||||
/// Configuration for one of the existing file-level built-in creators.
|
||||
@@ -47,6 +50,12 @@ impl IndexKindHandler for BuiltinIndexHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(&self, _context: &PlanContext<'_>) -> Result<(), BoxedError> {
|
||||
// Built-in options retain their existing schema/build-time validation.
|
||||
// Planning here would make region creation reject inputs it previously accepted.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn plan(&self, context: &PlanContext<'_>) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
|
||||
match self {
|
||||
Self::Inverted(config) => InvertedPlan::plan(config, context)
|
||||
@@ -83,6 +92,11 @@ fn normalize_entries(entries: &mut Vec<PlanEntry>) {
|
||||
});
|
||||
}
|
||||
|
||||
fn is_current(file: &FileMeta, context: &CurrencyContext<'_>) -> bool {
|
||||
// Preserve the established schema/version policy, including its JSON rebuild scope.
|
||||
file.is_index_consistent_with_region(&context.metadata.column_metadatas, context.index_options)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -90,6 +104,45 @@ mod tests {
|
||||
use crate::sst::index::IndexBuildType;
|
||||
use crate::test_util::sst_util;
|
||||
|
||||
#[test]
|
||||
fn test_builtin_validation_preserves_build_time_option_errors() {
|
||||
for (handler, key) in [
|
||||
(
|
||||
BuiltinIndexHandler::Fulltext(FulltextIndexConfig::default()),
|
||||
datatypes::schema::FULLTEXT_KEY,
|
||||
),
|
||||
(
|
||||
BuiltinIndexHandler::Bloom(BloomFilterConfig::default()),
|
||||
datatypes::schema::SKIPPING_INDEX_KEY,
|
||||
),
|
||||
] {
|
||||
let mut metadata = sst_util::sst_region_metadata();
|
||||
let column = metadata
|
||||
.column_metadatas
|
||||
.iter_mut()
|
||||
.find(|column| column.semantic_type == api::v1::SemanticType::Field)
|
||||
.unwrap();
|
||||
column.column_schema =
|
||||
column
|
||||
.column_schema
|
||||
.clone()
|
||||
.with_metadata(std::collections::HashMap::from([(
|
||||
key.to_string(),
|
||||
"invalid json".to_string(),
|
||||
)]));
|
||||
let metadata = Arc::new(metadata);
|
||||
let options = IndexOptions::default();
|
||||
let context = PlanContext {
|
||||
metadata: &metadata,
|
||||
index_options: &options,
|
||||
build_type: IndexBuildType::Flush,
|
||||
existing_indexes: &[],
|
||||
};
|
||||
assert!(handler.validate(&context).is_ok());
|
||||
assert!(handler.plan(&context).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builtin_planning_reports_invalid_options() {
|
||||
for (handler, key) in [
|
||||
|
||||
@@ -24,10 +24,13 @@ use index::target::IndexTarget;
|
||||
|
||||
use crate::config::BloomFilterConfig;
|
||||
use crate::read::Batch;
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::sst::index::bloom_filter::creator::BloomFilterIndexer;
|
||||
use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id};
|
||||
use crate::sst::index::handler::builtin::{
|
||||
column_target_id, is_current, normalize_entries, target_column_id,
|
||||
};
|
||||
use crate::sst::index::handler::{
|
||||
BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex,
|
||||
BuildContext, CurrencyContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex,
|
||||
};
|
||||
use crate::sst::index::kind::IndexKind;
|
||||
use crate::sst::index::puffin_manager::SstPuffinWriter;
|
||||
@@ -105,6 +108,10 @@ impl PlannedIndex for BloomPlan {
|
||||
.map(|creator| creator.map(|c| Box::new(c) as Box<dyn IndexCreator>))
|
||||
.map_err(BoxedError::new)
|
||||
}
|
||||
|
||||
fn is_current(&self, file: &FileMeta, context: &CurrencyContext<'_>) -> bool {
|
||||
is_current(file, context)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
|
||||
@@ -24,11 +24,14 @@ use index::target::IndexTarget;
|
||||
|
||||
use crate::config::FulltextIndexConfig;
|
||||
use crate::read::Batch;
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::sst::index::fulltext_index;
|
||||
use crate::sst::index::fulltext_index::creator::{FulltextIndexer, FulltextTarget};
|
||||
use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id};
|
||||
use crate::sst::index::handler::builtin::{
|
||||
column_target_id, is_current, normalize_entries, target_column_id,
|
||||
};
|
||||
use crate::sst::index::handler::{
|
||||
BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex,
|
||||
BuildContext, CurrencyContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex,
|
||||
};
|
||||
use crate::sst::index::kind::IndexKind;
|
||||
use crate::sst::index::puffin_manager::SstPuffinWriter;
|
||||
@@ -118,6 +121,10 @@ impl PlannedIndex for FulltextPlan {
|
||||
.map(|creator| creator.map(|c| Box::new(c) as Box<dyn IndexCreator>))
|
||||
.map_err(BoxedError::new)
|
||||
}
|
||||
|
||||
fn is_current(&self, file: &FileMeta, context: &CurrencyContext<'_>) -> bool {
|
||||
is_current(file, context)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
|
||||
@@ -27,9 +27,12 @@ use index::target::IndexTarget;
|
||||
|
||||
use crate::config::InvertedIndexConfig;
|
||||
use crate::read::Batch;
|
||||
use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id};
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::sst::index::handler::builtin::{
|
||||
column_target_id, is_current, normalize_entries, target_column_id,
|
||||
};
|
||||
use crate::sst::index::handler::{
|
||||
BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex,
|
||||
BuildContext, CurrencyContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex,
|
||||
};
|
||||
use crate::sst::index::inverted_index::creator::InvertedIndexer;
|
||||
use crate::sst::index::kind::IndexKind;
|
||||
@@ -131,6 +134,10 @@ impl PlannedIndex for InvertedPlan {
|
||||
self.targets.clone(),
|
||||
))))
|
||||
}
|
||||
|
||||
fn is_current(&self, file: &FileMeta, context: &CurrencyContext<'_>) -> bool {
|
||||
is_current(file, context)
|
||||
}
|
||||
}
|
||||
|
||||
fn json_inverted_targets(context: &PlanContext<'_>) -> Vec<IndexTarget> {
|
||||
|
||||
@@ -19,6 +19,20 @@ use crate::sst::file::{RegionFileId, RegionIndexId};
|
||||
use crate::sst::index::Indexer;
|
||||
|
||||
impl Indexer {
|
||||
/// Defers builtin indexes without discarding synchronous extension state.
|
||||
pub(crate) async fn disable_builtin_indexes(&mut self) {
|
||||
self.dense_pk_decoder = None;
|
||||
let mut position = 0;
|
||||
while position < self.creators.len() {
|
||||
if self.creators[position].is_builtin() {
|
||||
self.abort_creator(position).await;
|
||||
} else {
|
||||
position += 1;
|
||||
}
|
||||
}
|
||||
self.flush_mem_metrics();
|
||||
}
|
||||
|
||||
pub(crate) async fn abort_creator(&mut self, position: usize) {
|
||||
let mut active = self.creators.remove(position);
|
||||
if let Err(err) = active.creator.abort().await {
|
||||
|
||||
@@ -30,7 +30,7 @@ use crate::sst::file::{FileMeta, IndexType};
|
||||
use crate::sst::index::IndexBuildType;
|
||||
use crate::sst::index::handler::builtin::BuiltinIndexHandler;
|
||||
use crate::sst::index::handler::{
|
||||
IndexKindHandler, IndexKindProviderRef, PlanContext, PlanEntry, PlannedIndex,
|
||||
CurrencyContext, IndexKindHandler, IndexKindProviderRef, PlanContext, PlanEntry, PlannedIndex,
|
||||
};
|
||||
use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
|
||||
|
||||
@@ -72,6 +72,14 @@ impl IndexRegistry {
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Strictly validates configured options before a region is opened.
|
||||
pub fn validate(&self, context: &PlanContext<'_>) -> Result<(), BoxedError> {
|
||||
for handler in &self.handlers {
|
||||
handler.validate(context)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Installs a handler, rejecting empty or overlapping kind ownership.
|
||||
pub fn register(&mut self, handler: Arc<dyn IndexKindHandler>) -> Result<(), BoxedError> {
|
||||
self.validate_registration(handler.kinds())?;
|
||||
@@ -270,6 +278,11 @@ impl IndexBuildPlan {
|
||||
&self.planned
|
||||
}
|
||||
|
||||
/// Whether no handler requested work, including metadata-only maintenance.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.planned.is_empty()
|
||||
}
|
||||
|
||||
/// All requested column formats.
|
||||
pub fn entries(&self) -> impl Iterator<Item = &PlanEntry> {
|
||||
self.planned.iter().flat_map(|plan| plan.entries())
|
||||
@@ -301,6 +314,15 @@ impl IndexBuildPlan {
|
||||
self.planned
|
||||
.retain(|plan| plan.kinds().iter().all(|kind| kind.is_builtin()));
|
||||
}
|
||||
|
||||
/// Whether every handler considers the published file current.
|
||||
pub fn is_current(&self, file: &FileMeta, context: &CurrencyContext<'_>) -> bool {
|
||||
self.failure.is_none()
|
||||
&& self
|
||||
.planned
|
||||
.iter()
|
||||
.all(|plan| plan.is_current(file, context))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -340,6 +362,10 @@ mod tests {
|
||||
) -> Result<Option<Box<dyn crate::sst::index::handler::IndexCreator>>, BoxedError> {
|
||||
unreachable!("admission must not construct creators")
|
||||
}
|
||||
|
||||
fn is_current(&self, _: &FileMeta, _: &CurrencyContext<'_>) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -55,7 +55,7 @@ use crate::error::{
|
||||
};
|
||||
use crate::read::FlatSource;
|
||||
use crate::sst::file::RegionFileId;
|
||||
use crate::sst::index::{IndexOutput, Indexer, IndexerBuilder};
|
||||
use crate::sst::index::{Indexer, IndexerBuilder};
|
||||
use crate::sst::parquet::flat_format::{
|
||||
FlatWriteFormat, primary_key_column_index, time_index_column_index,
|
||||
};
|
||||
@@ -424,18 +424,7 @@ where
|
||||
|
||||
// Finish indexer and writer.
|
||||
// safety: writer and index can only be both present or not.
|
||||
let mut index_output = IndexOutput::default();
|
||||
match self.index_config.build_mode {
|
||||
IndexBuildMode::Sync => {
|
||||
index_output = self.current_indexer.as_mut().unwrap().finish().await;
|
||||
}
|
||||
IndexBuildMode::Async => {
|
||||
debug!(
|
||||
"Index for file {} will be built asynchronously later",
|
||||
self.current_file
|
||||
);
|
||||
}
|
||||
}
|
||||
let index_output = self.current_indexer.as_mut().unwrap().finish().await;
|
||||
current_writer.flush().await.context(WriteParquetSnafu)?;
|
||||
|
||||
let parquet_metadata = current_writer.close().await.context(WriteParquetSnafu)?;
|
||||
@@ -632,16 +621,15 @@ where
|
||||
self.metrics.write_batch += start.elapsed();
|
||||
|
||||
stats.update_flat(batch)?;
|
||||
if matches!(self.index_config.build_mode, IndexBuildMode::Sync) {
|
||||
let start = Instant::now();
|
||||
// safety: self.current_indexer must be set when first batch has been written.
|
||||
self.current_indexer
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.update_flat(batch)
|
||||
.await;
|
||||
self.metrics.update_index += start.elapsed();
|
||||
}
|
||||
let start = Instant::now();
|
||||
// The indexer exists once the first batch has been written. In async
|
||||
// mode it contains only the compaction extension, if one is enabled.
|
||||
self.current_indexer
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.update_flat(batch)
|
||||
.await;
|
||||
self.metrics.update_index += start.elapsed();
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
@@ -746,7 +734,7 @@ where
|
||||
};
|
||||
self.writer = Some(arrow_writer);
|
||||
|
||||
let indexer = self
|
||||
let mut indexer = self
|
||||
.indexer_builder
|
||||
.build(
|
||||
RegionFileId::new(self.metadata.region_id, self.current_file),
|
||||
@@ -754,6 +742,9 @@ where
|
||||
Some(opts.row_group_size),
|
||||
)
|
||||
.await;
|
||||
if matches!(self.index_config.build_mode, IndexBuildMode::Async) {
|
||||
indexer.disable_builtin_indexes().await;
|
||||
}
|
||||
self.current_indexer = Some(indexer);
|
||||
|
||||
// safety: self.writer is assigned above
|
||||
|
||||
@@ -399,6 +399,7 @@ pub struct TestEnv {
|
||||
kv_backend: KvBackendRef,
|
||||
partition_expr_fetcher: PartitionExprFetcherRef,
|
||||
object_store_mock_layer: Option<MockLayer>,
|
||||
object_store_override: Option<ObjectStore>,
|
||||
}
|
||||
|
||||
impl TestEnv {
|
||||
@@ -436,6 +437,7 @@ impl TestEnv {
|
||||
kv_backend,
|
||||
partition_expr_fetcher: noop_partition_expr_fetcher(),
|
||||
object_store_mock_layer: None,
|
||||
object_store_override: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,6 +453,13 @@ impl TestEnv {
|
||||
self
|
||||
}
|
||||
|
||||
/// Uses a supplied default store, for example Memory to exercise object-store GC
|
||||
/// in release integration tests. The configured mock layer is still applied.
|
||||
pub fn with_object_store(mut self, object_store: ObjectStore) -> Self {
|
||||
self.object_store_override = Some(object_store);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the original `object_store_mock_layer`.
|
||||
pub fn with_mock_layer(mut self, mock_layer: MockLayer) -> TestEnv {
|
||||
self.object_store_mock_layer = Some(mock_layer);
|
||||
@@ -861,11 +870,15 @@ impl TestEnv {
|
||||
let data_path = data_home.join("data").as_path().display().to_string();
|
||||
let builder = Fs::default().root(&data_path);
|
||||
|
||||
let object_store = self
|
||||
.object_store_override
|
||||
.clone()
|
||||
.unwrap_or_else(|| ObjectStore::new(builder).unwrap());
|
||||
let object_store = if let Some(mock_layer) = self.object_store_mock_layer.as_ref() {
|
||||
debug!("create object store with mock layer");
|
||||
ObjectStore::new(builder).unwrap().layer(mock_layer.clone())
|
||||
object_store.layer(mock_layer.clone())
|
||||
} else {
|
||||
ObjectStore::new(builder).unwrap()
|
||||
object_store
|
||||
};
|
||||
ObjectStoreManager::new("default", object_store)
|
||||
}
|
||||
|
||||
@@ -14,14 +14,18 @@
|
||||
|
||||
//! Handling create request.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_telemetry::info;
|
||||
use store_api::logstore::LogStore;
|
||||
use store_api::metadata::RegionMetadataBuilder;
|
||||
use store_api::region_request::{AffectedRows, RegionCreateRequest};
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::error::{InvalidConfigSnafu, Result};
|
||||
use crate::region::opener::{RegionOpener, check_recovered_region};
|
||||
use crate::sst::index::handler::IndexKindProviderRef;
|
||||
use crate::sst::index::registry::IndexRegistry;
|
||||
#[cfg(feature = "hdfs-object-store")]
|
||||
use crate::temp_file_sweeper;
|
||||
use crate::worker::RegionWorkerLoop;
|
||||
@@ -57,6 +61,18 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
|
||||
// Create a MitoRegion from the RegionMetadata.
|
||||
let requirements = request.requirements;
|
||||
let registry = IndexRegistry::new(
|
||||
self.config.inverted_index.clone(),
|
||||
self.config.fulltext_index.clone(),
|
||||
self.config.bloom_filter_index.clone(),
|
||||
)
|
||||
.with_provider(self.plugins.get::<IndexKindProviderRef>())
|
||||
.map_err(|err| {
|
||||
InvalidConfigSnafu {
|
||||
reason: err.to_string(),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let opener = RegionOpener::new(
|
||||
region_id,
|
||||
&request.table_dir,
|
||||
@@ -76,7 +92,8 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
.cache(Some(self.cache_manager.clone()))
|
||||
.series_index_store(self.series_index_store.clone())
|
||||
.series_index_purger(self.series_index_purger.clone())
|
||||
.hook(self.plugins.get());
|
||||
.hook(self.plugins.get())
|
||||
.with_index_registry(Arc::new(registry));
|
||||
|
||||
opener.ensure_region_requirements(requirements)?;
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ use std::sync::Arc;
|
||||
|
||||
use api::v1::region::build_index_request;
|
||||
use common_telemetry::{debug, warn};
|
||||
use snafu::{IntoError, ResultExt};
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::region_request::RegionBuildIndexRequest;
|
||||
use store_api::storage::{FileId, RegionId};
|
||||
@@ -26,7 +27,8 @@ use tokio::sync::mpsc;
|
||||
|
||||
use crate::cache::CacheStrategy;
|
||||
use crate::error::{
|
||||
IndexBuildIncompleteSnafu, InvalidRequestSnafu, RegionStateSnafu, Result, WorkerStoppedSnafu,
|
||||
BuildIndexAsyncSnafu, ExternalSnafu, IndexBuildIncompleteSnafu, InvalidRequestSnafu,
|
||||
RegionStateSnafu, Result, WorkerStoppedSnafu,
|
||||
};
|
||||
use crate::manifest::action::RegionEdit;
|
||||
use crate::metrics::INDEX_PUBLICATION_STALE_TOTAL;
|
||||
@@ -34,6 +36,9 @@ use crate::region::options::IndexOptions;
|
||||
use crate::region::{IndexBuildSource, MitoRegionRef, RegionLeaderState, RegionRoleState};
|
||||
use crate::request::{BuildIndexRequest, IndexBuildFinished, IndexBuildStopped, OptionOutputTx};
|
||||
use crate::sst::file::{self, FileHandle, FileMeta, RegionFileId, RegionIndexId};
|
||||
use crate::sst::index::build::IndexBuildInputs;
|
||||
use crate::sst::index::handler::{CurrencyContext, IndexKindProviderRef, PlanContext};
|
||||
use crate::sst::index::registry::{IndexRegistry, IndexRegistryRef};
|
||||
use crate::sst::index::{
|
||||
IndexBuildOutcome, IndexBuildTask, IndexBuildType, IndexerBuilderImpl, ResultMpscSender,
|
||||
cleanup_stale_index_caches,
|
||||
@@ -54,11 +59,12 @@ impl<S> RegionWorkerLoop<S> {
|
||||
&self,
|
||||
region: &MitoRegionRef,
|
||||
snapshot: &IndexBuildSnapshot,
|
||||
file: FileHandle,
|
||||
file_meta: FileMeta,
|
||||
registry: IndexRegistryRef,
|
||||
source: (FileHandle, FileMeta),
|
||||
build_type: IndexBuildType,
|
||||
result_senders: Vec<ResultMpscSender>,
|
||||
) -> IndexBuildTask {
|
||||
let (file, file_meta) = source;
|
||||
let access_layer = region.access_layer.clone();
|
||||
|
||||
let puffin_manager = if let Some(write_cache) = self.cache_manager.write_cache() {
|
||||
@@ -73,15 +79,30 @@ impl<S> RegionWorkerLoop<S> {
|
||||
access_layer.intermediate_manager().clone()
|
||||
};
|
||||
|
||||
let plan = Arc::new(registry.plan(&PlanContext {
|
||||
metadata: &snapshot.metadata,
|
||||
index_options: &snapshot.index_options,
|
||||
build_type: build_type.clone(),
|
||||
existing_indexes: &file_meta.indexes,
|
||||
}));
|
||||
let index_build_inputs = Some(IndexBuildInputs {
|
||||
output_rows: Some(file_meta.num_rows),
|
||||
plan,
|
||||
inputs: vec![FileHandle::new(file_meta.clone(), file.file_purger())].into(),
|
||||
input_puffin_manager: access_layer.build_puffin_manager(),
|
||||
can_merge_inputs: snapshot
|
||||
.metadata
|
||||
.partition_expr
|
||||
.as_deref()
|
||||
.is_none_or(str::is_empty)
|
||||
&& file_meta.region_id == region.region_id,
|
||||
memory_limit: None,
|
||||
});
|
||||
let indexer_builder_ref = Arc::new(IndexerBuilderImpl {
|
||||
index_build_inputs,
|
||||
build_type: build_type.clone(),
|
||||
metadata: snapshot.metadata.clone(),
|
||||
index_build_inputs: None,
|
||||
registry: Arc::new(crate::sst::index::registry::IndexRegistry::new(
|
||||
self.config.inverted_index.clone(),
|
||||
self.config.fulltext_index.clone(),
|
||||
self.config.bloom_filter_index.clone(),
|
||||
)),
|
||||
registry: registry.clone(),
|
||||
index_options: snapshot.index_options.clone(),
|
||||
intermediate_manager,
|
||||
puffin_manager,
|
||||
@@ -223,6 +244,33 @@ impl<S> RegionWorkerLoop<S> {
|
||||
file_meta.cloned()
|
||||
};
|
||||
|
||||
let registry = match index_registry(
|
||||
&self.config,
|
||||
self.plugins.get::<IndexKindProviderRef>(),
|
||||
)
|
||||
.and_then(|registry| {
|
||||
registry
|
||||
.validate_required_kinds(&snapshot.metadata, manifest.files.values())
|
||||
.with_context(|_| ExternalSnafu {
|
||||
context: "checking required index handlers for rebuild".to_string(),
|
||||
})?;
|
||||
validate_rebuild_plan(®istry, &snapshot, request.build_type.clone())?;
|
||||
Ok(registry)
|
||||
}) {
|
||||
Ok(registry) => registry,
|
||||
Err(err) => {
|
||||
let err = Arc::new(err);
|
||||
for result_sender in &request.result_senders {
|
||||
let _ = result_sender
|
||||
.send(Err(
|
||||
BuildIndexAsyncSnafu { region_id }.into_error(err.clone())
|
||||
))
|
||||
.await;
|
||||
}
|
||||
sender.send(Err(BuildIndexAsyncSnafu { region_id }.into_error(err)));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let build_tasks = if request.file_metas.is_empty() {
|
||||
// If no specific files are provided, find files whose index is inconsistent with the region metadata.
|
||||
// Check the version rather than the manifest: a publication committed
|
||||
@@ -231,9 +279,11 @@ impl<S> RegionWorkerLoop<S> {
|
||||
all_files
|
||||
.values()
|
||||
.filter(|file| {
|
||||
!file.meta_ref().is_index_consistent_with_region(
|
||||
&snapshot.metadata.column_metadatas,
|
||||
&snapshot.index_options,
|
||||
index_needs_rebuild(
|
||||
®istry,
|
||||
&snapshot,
|
||||
file.meta_ref(),
|
||||
request.build_type.clone(),
|
||||
)
|
||||
})
|
||||
.filter_map(|file| {
|
||||
@@ -292,8 +342,8 @@ impl<S> RegionWorkerLoop<S> {
|
||||
let task = self.new_index_build_task(
|
||||
®ion,
|
||||
&snapshot,
|
||||
file_handle,
|
||||
file_meta,
|
||||
registry.clone(),
|
||||
(file_handle, file_meta),
|
||||
request.build_type.clone(),
|
||||
result_senders,
|
||||
);
|
||||
@@ -450,3 +500,336 @@ impl<S> RegionWorkerLoop<S> {
|
||||
.on_task_stopped(region_id, request.file_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn index_registry(
|
||||
config: &crate::config::MitoConfig,
|
||||
provider: Option<IndexKindProviderRef>,
|
||||
) -> Result<IndexRegistryRef> {
|
||||
IndexRegistry::new(
|
||||
config.inverted_index.clone(),
|
||||
config.fulltext_index.clone(),
|
||||
config.bloom_filter_index.clone(),
|
||||
)
|
||||
.with_provider(provider)
|
||||
.map(Arc::new)
|
||||
.with_context(|_| ExternalSnafu {
|
||||
context: "registering index handlers for rebuild".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rejects invalid current options before selecting files or scheduling any task.
|
||||
fn validate_rebuild_plan(
|
||||
registry: &IndexRegistry,
|
||||
snapshot: &IndexBuildSnapshot,
|
||||
build_type: IndexBuildType,
|
||||
) -> Result<()> {
|
||||
registry
|
||||
.validate_required_kinds(&snapshot.metadata, [])
|
||||
.with_context(|_| ExternalSnafu {
|
||||
context: "validating index handlers for rebuild".to_string(),
|
||||
})?;
|
||||
let plan = registry.plan(&PlanContext {
|
||||
metadata: &snapshot.metadata,
|
||||
index_options: &snapshot.index_options,
|
||||
build_type,
|
||||
existing_indexes: &[],
|
||||
});
|
||||
plan.check_success().context(BuildIndexAsyncSnafu {
|
||||
region_id: snapshot.metadata.region_id,
|
||||
})
|
||||
}
|
||||
|
||||
fn index_needs_rebuild(
|
||||
registry: &IndexRegistry,
|
||||
snapshot: &IndexBuildSnapshot,
|
||||
file: &FileMeta,
|
||||
build_type: IndexBuildType,
|
||||
) -> bool {
|
||||
let plan = registry.plan(&PlanContext {
|
||||
metadata: &snapshot.metadata,
|
||||
index_options: &snapshot.index_options,
|
||||
build_type: build_type.clone(),
|
||||
existing_indexes: &file.indexes,
|
||||
});
|
||||
if plan.check_success().is_err() {
|
||||
return true;
|
||||
}
|
||||
!plan.is_current(
|
||||
file,
|
||||
&CurrencyContext {
|
||||
metadata: &snapshot.metadata,
|
||||
index_options: &snapshot.index_options,
|
||||
build_type,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use store_api::metadata::RegionMetadataBuilder;
|
||||
|
||||
use super::*;
|
||||
use crate::sst::file::ColumnIndexMetadata;
|
||||
use crate::sst::index::handler::{
|
||||
BuildContext, IndexCreator, IndexKindHandler, PlanEntry, PlannedIndex,
|
||||
};
|
||||
use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
|
||||
use crate::test_util::CreateRequestBuilder;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MaintenanceHandler;
|
||||
|
||||
impl IndexKindHandler for MaintenanceHandler {
|
||||
fn kinds(&self) -> &[IndexKind] {
|
||||
&[IndexKind::Extension(ExtensionIndexKind::Hll)]
|
||||
}
|
||||
|
||||
fn plan(
|
||||
&self,
|
||||
context: &PlanContext<'_>,
|
||||
) -> std::result::Result<Option<Arc<dyn PlannedIndex>>, common_error::ext::BoxedError>
|
||||
{
|
||||
let existing = context.existing_indexes.iter().any(|column| {
|
||||
column
|
||||
.created_indexes
|
||||
.contains(&crate::sst::file::IndexType::HllIndex)
|
||||
});
|
||||
Ok((existing
|
||||
&& matches!(
|
||||
context.build_type,
|
||||
IndexBuildType::Manual | IndexBuildType::SchemaChange
|
||||
))
|
||||
.then(|| Arc::new(Self) as Arc<dyn PlannedIndex>))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl PlannedIndex for MaintenanceHandler {
|
||||
fn kinds(&self) -> &[IndexKind] {
|
||||
IndexKindHandler::kinds(self)
|
||||
}
|
||||
|
||||
fn entries(&self) -> &[PlanEntry] {
|
||||
&[]
|
||||
}
|
||||
|
||||
async fn build(
|
||||
&self,
|
||||
_context: &BuildContext<'_>,
|
||||
) -> std::result::Result<Option<Box<dyn IndexCreator>>, common_error::ext::BoxedError>
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn is_current(&self, _file: &FileMeta, _context: &CurrencyContext<'_>) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot_without_builtin_indexes() -> IndexBuildSnapshot {
|
||||
let request = CreateRequestBuilder::new().build();
|
||||
let mut metadata = RegionMetadataBuilder::new(RegionId::new(1, 1));
|
||||
metadata.primary_key(request.primary_key);
|
||||
for mut column in request.column_metadatas {
|
||||
column.column_schema.set_inverted_index(false);
|
||||
column.column_schema.unset_skipping_options().unwrap();
|
||||
metadata.push_column_metadata(column);
|
||||
}
|
||||
IndexBuildSnapshot {
|
||||
metadata: Arc::new(metadata.build().unwrap()),
|
||||
index_options: IndexOptions::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rebuild_selection_uses_registered_currency_and_empty_maintenance_plans() {
|
||||
let snapshot = snapshot_without_builtin_indexes();
|
||||
let builtin =
|
||||
IndexRegistry::new(Default::default(), Default::default(), Default::default());
|
||||
let mut registered = builtin.clone();
|
||||
registered.register(Arc::new(MaintenanceHandler)).unwrap();
|
||||
let empty = FileMeta::default();
|
||||
let mut existing = empty.clone();
|
||||
existing.indexes.push(ColumnIndexMetadata {
|
||||
column_id: 0,
|
||||
created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex],
|
||||
..Default::default()
|
||||
});
|
||||
// Missing owners are rejected before selection; currency only compares
|
||||
// the plans of registered handlers with the persisted indexes.
|
||||
assert!(
|
||||
builtin
|
||||
.validate_required_kinds(&snapshot.metadata, [&existing])
|
||||
.is_err()
|
||||
);
|
||||
for reason in [IndexBuildType::Manual, IndexBuildType::SchemaChange] {
|
||||
assert!(!index_needs_rebuild(
|
||||
®istered,
|
||||
&snapshot,
|
||||
&empty,
|
||||
reason.clone()
|
||||
));
|
||||
assert!(
|
||||
index_needs_rebuild(®istered, &snapshot, &existing, reason),
|
||||
"an explicit empty maintenance plan still requests publication"
|
||||
);
|
||||
}
|
||||
for reason in [IndexBuildType::Flush, IndexBuildType::Compact] {
|
||||
assert!(!index_needs_rebuild(
|
||||
®istered,
|
||||
&snapshot,
|
||||
&existing,
|
||||
reason
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FailingPlanHandler;
|
||||
|
||||
impl IndexKindHandler for FailingPlanHandler {
|
||||
fn kinds(&self) -> &[IndexKind] {
|
||||
&[IndexKind::Extension(ExtensionIndexKind::Hll)]
|
||||
}
|
||||
|
||||
fn plan(
|
||||
&self,
|
||||
_context: &PlanContext<'_>,
|
||||
) -> std::result::Result<Option<Arc<dyn PlannedIndex>>, common_error::ext::BoxedError>
|
||||
{
|
||||
Err(common_error::ext::BoxedError::new(
|
||||
common_error::ext::PlainError::new(
|
||||
"injected plan failure".into(),
|
||||
common_error::status_code::StatusCode::Internal,
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_failed_plan_requires_rebuild_even_without_planned_entries() {
|
||||
let snapshot = snapshot_without_builtin_indexes();
|
||||
let mut registry =
|
||||
IndexRegistry::new(Default::default(), Default::default(), Default::default());
|
||||
registry.register(Arc::new(FailingPlanHandler)).unwrap();
|
||||
let file = FileMeta {
|
||||
indexes: vec![ColumnIndexMetadata {
|
||||
column_id: 0,
|
||||
created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(
|
||||
registry
|
||||
.validate_required_kinds(&snapshot.metadata, [&file])
|
||||
.is_ok()
|
||||
);
|
||||
for reason in [IndexBuildType::Manual, IndexBuildType::SchemaChange] {
|
||||
let plan = registry.plan(&PlanContext {
|
||||
metadata: &snapshot.metadata,
|
||||
index_options: &snapshot.index_options,
|
||||
build_type: reason.clone(),
|
||||
existing_indexes: &file.indexes,
|
||||
});
|
||||
assert!(plan.entries().next().is_none());
|
||||
assert!(plan.check_success().is_err());
|
||||
assert!(index_needs_rebuild(®istry, &snapshot, &file, reason));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DuplicateKindProvider;
|
||||
|
||||
impl crate::sst::index::handler::IndexKindProvider for DuplicateKindProvider {
|
||||
fn handlers(&self) -> Vec<Arc<dyn IndexKindHandler>> {
|
||||
vec![Arc::new(MaintenanceHandler), Arc::new(MaintenanceHandler)]
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rebuild_registry_registration_failure_is_not_provider_absence() {
|
||||
let config = crate::config::MitoConfig::default();
|
||||
assert!(index_registry(&config, None).is_ok());
|
||||
let error = index_registry(&config, Some(Arc::new(DuplicateKindProvider))).unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("registering index handlers for rebuild")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rebuild_preflight_rejects_plan_failure_before_file_selection() {
|
||||
let snapshot = snapshot_without_builtin_indexes();
|
||||
let mut registry =
|
||||
IndexRegistry::new(Default::default(), Default::default(), Default::default());
|
||||
assert!(validate_rebuild_plan(®istry, &snapshot, IndexBuildType::Manual).is_ok());
|
||||
registry.register(Arc::new(FailingPlanHandler)).unwrap();
|
||||
assert!(validate_rebuild_plan(®istry, &snapshot, IndexBuildType::Manual).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_required_handlers_cover_schema_and_both_persisted_locations() {
|
||||
use crate::sst::file::IndexType;
|
||||
let registry =
|
||||
IndexRegistry::new(Default::default(), Default::default(), Default::default());
|
||||
for kind in [IndexType::HllIndex, IndexType::KllIndex, IndexType::MgIndex] {
|
||||
let mut snapshot = snapshot_without_builtin_indexes();
|
||||
let schema =
|
||||
&mut Arc::make_mut(&mut snapshot.metadata).column_metadatas[0].column_schema;
|
||||
let (key, value) = match kind {
|
||||
IndexType::HllIndex => (datatypes::schema::HLL_KEY, r#"{"precision":10}"#),
|
||||
IndexType::KllIndex => (datatypes::schema::KLL_KEY, r#"{"capacity":64}"#),
|
||||
IndexType::MgIndex => (datatypes::schema::MG_KEY, r#"{"max-counters":64}"#),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
schema.mut_metadata().insert(key.into(), value.into());
|
||||
assert!(
|
||||
registry
|
||||
.validate_required_kinds(&snapshot.metadata, [])
|
||||
.is_err()
|
||||
);
|
||||
assert!(validate_rebuild_plan(®istry, &snapshot, IndexBuildType::Manual).is_err());
|
||||
assert!(
|
||||
registry
|
||||
.plan(&PlanContext {
|
||||
metadata: &snapshot.metadata,
|
||||
index_options: &snapshot.index_options,
|
||||
build_type: IndexBuildType::Flush,
|
||||
existing_indexes: &[],
|
||||
})
|
||||
.check_success()
|
||||
.is_ok()
|
||||
);
|
||||
let snapshot = snapshot_without_builtin_indexes();
|
||||
for column_level in [false, true] {
|
||||
let mut file = FileMeta::default();
|
||||
if column_level {
|
||||
file.indexes.push(ColumnIndexMetadata {
|
||||
column_id: 0,
|
||||
created_indexes: smallvec::smallvec![kind],
|
||||
..Default::default()
|
||||
});
|
||||
} else {
|
||||
file.available_indexes.push(kind);
|
||||
}
|
||||
assert!(
|
||||
registry
|
||||
.validate_required_kinds(&snapshot.metadata, [&file])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
let snapshot = snapshot_without_builtin_indexes();
|
||||
let legacy = FileMeta {
|
||||
available_indexes: smallvec::smallvec![IndexType::VectorIndex],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(
|
||||
registry
|
||||
.validate_required_kinds(&snapshot.metadata, [&legacy])
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user