perf(mito2): improve shared SST table compaction execution

Preserve sparse primary keys and materialize only routing dependencies. Bound parallel encoding resources and expose stage and progress metrics. Allow compatible additive sparse schema changes during conditional publication.

Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
WenyXu
2026-11-27 12:47:40 +00:00
parent b82ede4762
commit 7eb6d4c4bf
13 changed files with 1645 additions and 137 deletions
+1
View File
@@ -33,6 +33,7 @@ includes = [
"src/mito2/src/compaction/multi_region.rs",
"src/mito2/src/compaction/multi_region/source.rs",
"src/mito2/src/compaction/multi_region/memory.rs",
"src/mito2/src/compaction/multi_region/metrics.rs",
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
+1
View File
@@ -49,6 +49,7 @@ excludes = [
"src/mito2/src/compaction/multi_region.rs",
"src/mito2/src/compaction/multi_region/source.rs",
"src/mito2/src/compaction/multi_region/memory.rs",
"src/mito2/src/compaction/multi_region/metrics.rs",
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
+76 -1
View File
@@ -18,6 +18,7 @@
//! caller; see [MultiRegionCompactionOutput::files] for the output level convention.
mod memory;
mod metrics;
mod source;
#[cfg(test)]
mod tests;
@@ -25,8 +26,8 @@ mod worker;
mod writer;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::{Arc, LazyLock};
use common_time::Timestamp;
use partition::PartitionRuleRef;
@@ -47,6 +48,77 @@ use crate::sst::index::registry::IndexRegistry;
use crate::sst::parquet::SstInfo;
use crate::sst::parquet::writer::SstWriteGuard;
/// Process-local execution tuning shared with the table-compaction picker.
/// Owners and executors must use the same settings; these are not serialized
/// into the plan, and execution always rechecks the local memory budget.
#[derive(Debug, Clone, Copy)]
pub struct MultiRegionCompactionTuning {
/// Rows per source, merge and routed output batch; byte limits still apply.
pub batch_rows: usize,
/// Maximum concurrently prepared source batches; each source buffers at most one.
pub source_parallelism: usize,
/// Parallel column encoders per target writer, under its admitted byte budget.
pub encode_parallelism: usize,
}
/// Returns execution tuning captured once per process.
pub fn tuning() -> &'static MultiRegionCompactionTuning {
static TUNING: LazyLock<MultiRegionCompactionTuning> = LazyLock::new(|| {
let batch_rows = read_tuning(
"GREPTIMEDB_EXPERIMENTAL_TABLE_COMPACTION_BATCH_ROWS",
64,
64,
1024,
);
let source_parallelism = read_tuning(
"GREPTIMEDB_EXPERIMENTAL_TABLE_COMPACTION_SOURCE_PARALLELISM",
4,
1,
32,
);
let encode_parallelism = read_tuning(
"GREPTIMEDB_EXPERIMENTAL_TABLE_COMPACTION_ENCODE_PARALLELISM",
2,
1,
32,
);
let tuning = MultiRegionCompactionTuning {
batch_rows,
source_parallelism,
encode_parallelism,
};
common_telemetry::info!("Table compaction execution tuning: {:?}", tuning);
tuning
});
&TUNING
}
fn read_tuning(name: &str, default: usize, min: usize, max: usize) -> usize {
match std::env::var(name) {
Ok(value) => match parse_tuning(&value, min, max) {
Some(value) => value,
None => {
common_telemetry::warn!(
"Invalid {name}={value:?}; expected {min}..={max}, using {default}"
);
default
}
},
Err(std::env::VarError::NotPresent) => default,
Err(error) => {
common_telemetry::warn!("Cannot read {name}: {error}; using {default}");
default
}
}
}
fn parse_tuning(value: &str, min: usize, max: usize) -> Option<usize> {
value
.parse()
.ok()
.filter(|value| (min..=max).contains(value))
}
/// A target partition and the source versions currently visible in its sequence domain.
#[derive(Debug, Clone)]
pub struct MultiRegionTarget {
@@ -87,6 +159,9 @@ pub struct MultiRegionCompactionContext {
pub cache: CacheManagerRef,
pub config: Arc<MitoConfig>,
pub protection: Arc<dyn SstWriteGuard>,
/// Retained by blocking preparation until it finishes, even if the caller
/// cancels and drops the execution future.
pub memory_admission: Option<Arc<tokio::sync::OwnedSemaphorePermit>>,
pub cancellation: CancellationToken,
}
@@ -28,7 +28,8 @@ use crate::sst::parquet::max_row_group_value_bytes;
use crate::sst::parquet::writer::SstWriteLimits;
use crate::sst::upload::buffered::UploadLimits;
pub(crate) const BATCH_SIZE: usize = 64;
/// Conservative byte-buffer scaling, independent of the configured batch row count.
const BUFFER_BUDGET_FACTOR: usize = 64;
/// Cap on the rows of one output row group.
///
/// Every resident target admits an encoder sized by this count, while readers
@@ -43,6 +44,8 @@ pub(crate) const MAX_ROW_GROUP_SIZE: usize = 1024;
#[derive(Clone)]
pub(crate) struct MemoryLimits {
pub(crate) arrow_batch_bytes: usize,
pub(crate) batch_rows: usize,
pub(crate) source_parallelism: usize,
pub(crate) group: usize,
pub(crate) index: usize,
upload_reserved_bytes: usize,
@@ -64,12 +67,14 @@ impl MemoryLimits {
.convert(&schema)
.context(crate::error::WriteParquetSnafu)?
.num_columns();
let tuning = crate::compaction::multi_region::tuning();
let batch_rows = tuning.batch_rows;
let targets = plan.targets.len();
let batch_share = 64usize.saturating_mul(
let batch_share = BUFFER_BUDGET_FACTOR.saturating_mul(
plan.sources
.len()
.saturating_add(targets)
.saturating_add(BATCH_SIZE + 4),
.saturating_add(batch_rows + 4),
);
let arrow_batch_bytes = upload.compute_bytes / batch_share;
ensure!(
@@ -80,6 +85,8 @@ impl MemoryLimits {
);
Ok(Self {
arrow_batch_bytes,
batch_rows,
source_parallelism: tuning.source_parallelism,
group: upload.compute_bytes / 16,
index: upload.compute_bytes / targets / 64,
upload_reserved_bytes: upload.reserved_bytes,
@@ -91,7 +98,9 @@ impl MemoryLimits {
// also have a nonzero minimum, independent of batch row count.
working_bytes: (2usize << 20)
.saturating_add(columns.saturating_mul(128 << 10))
.saturating_add(arrow_batch_bytes * (MAX_ROW_GROUP_SIZE / BATCH_SIZE)),
.saturating_add(
arrow_batch_bytes.saturating_mul(MAX_ROW_GROUP_SIZE.div_ceil(batch_rows)),
),
metadata_bytes: upload.compute_bytes / targets / 8,
upload_limits: upload.limits,
},
@@ -153,9 +162,19 @@ impl MemoryLimits {
) -> Result<u64> {
// Merge assembly can retain exhausted batches until an output batch is full.
let mut bytes = 4_u64
.saturating_mul((plan.sources.len() as u64).saturating_add((BATCH_SIZE + 2) as u64))
.saturating_mul(
(plan.sources.len() as u64).saturating_add((self.batch_rows + 2) as u64),
)
.saturating_mul(self.arrow_batch_bytes as u64)
.saturating_add(6 * self.group as u64);
// A prefetched source retains a queued batch and one being prepared.
if self.source_parallelism > 1 {
bytes = bytes.saturating_add(
2_u64
.saturating_mul(plan.sources.len() as u64)
.saturating_mul(self.arrow_batch_bytes as u64),
);
}
for footer in footers {
bytes = bytes.saturating_add(reader_bytes(footer));
}
@@ -0,0 +1,100 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
//! Bounded-label progress metrics. Stage durations are wall time, not CPU time.
//! Read stages include decode/cache work; store_page_bytes counts fetched Parquet
//! pages, not all object-store traffic (for example, footer requests).
use std::time::Instant;
use prometheus::{
Histogram, HistogramVec, IntCounterVec, IntGauge, IntGaugeVec, register_histogram_vec,
register_int_counter_vec, register_int_gauge_vec,
};
lazy_static::lazy_static! {
static ref STAGE_SECONDS: HistogramVec = register_histogram_vec!(
"greptime_mito_table_compaction_stage_seconds",
"Table compaction stage wall seconds; overlapping stages are not additive",
&["stage"],
vec![0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 60.0, 300.0]
).unwrap();
static ref STAGE_ACTIVE: IntGaugeVec = register_int_gauge_vec!(
"greptime_mito_table_compaction_stage_active",
"Active table compaction stage operations",
&["stage"]
).unwrap();
static ref PROGRESS: IntCounterVec = register_int_counter_vec!(
"greptime_mito_table_compaction_progress_total",
"Table compaction work by unit; counters include work from failed attempts",
&["unit"]
).unwrap();
}
/// Balances active-stage accounting on success, error and future cancellation.
pub(crate) struct StageGuard {
started: Instant,
elapsed: Histogram,
active: IntGauge,
}
impl StageGuard {
pub(crate) fn start(stage: &'static str) -> Self {
let active = STAGE_ACTIVE.with_label_values(&[stage]);
active.inc();
Self {
started: Instant::now(),
elapsed: STAGE_SECONDS.with_label_values(&[stage]),
active,
}
}
}
impl Drop for StageGuard {
fn drop(&mut self) {
self.elapsed.observe(self.started.elapsed().as_secs_f64());
self.active.dec();
}
}
pub(crate) fn observe_stage(stage: &'static str, duration: std::time::Duration) {
STAGE_SECONDS
.with_label_values(&[stage])
.observe(duration.as_secs_f64());
}
pub(crate) fn progress(unit: &'static str, count: u64) {
PROGRESS.with_label_values(&[unit]).inc_by(count);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stage_guard_balances_on_early_return() {
fn work() -> Result<(), ()> {
let _stage = StageGuard::start("test_early_return");
Err(())
}
assert!(work().is_err());
assert_eq!(
STAGE_ACTIVE.with_label_values(&["test_early_return"]).get(),
0
);
assert_eq!(
STAGE_SECONDS
.with_label_values(&["test_early_return"])
.get_sample_count(),
1
);
}
}
+757 -88
View File
@@ -17,23 +17,28 @@ use std::sync::atomic::{AtomicU64, Ordering};
use common_base::readable_size::ReadableSize;
use common_time::Timestamp;
use datatypes::arrow::array::{
Array, ArrayRef, BinaryArray, GenericByteArray, GenericByteDictionaryBuilder, UInt64Array,
Array, ArrayRef, BinaryArray, DictionaryArray, GenericByteArray, GenericByteDictionaryBuilder,
UInt32Array, UInt64Array,
};
use datatypes::arrow::compute::{cast, concat_batches, take_record_batch};
use datatypes::arrow::compute::{concat_batches, take_record_batch};
use datatypes::arrow::datatypes::{
BinaryType, ByteArrayType, DataType, Field, Schema, SchemaRef, UInt32Type, Utf8Type,
};
use datatypes::arrow::record_batch::RecordBatch;
use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec};
use parquet::file::metadata::PageIndexPolicy;
use partition::PartitionRuleRef;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metadata::RegionMetadataRef;
use store_api::metadata::{RegionMetadata, RegionMetadataRef};
use store_api::storage::RegionId;
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc};
use tokio_util::sync::CancellationToken;
use tokio_util::task::AbortOnDropHandle;
use crate::cache::CacheStrategy;
use crate::compaction::json2::collect_json2_rewrite_plans_from_parquet;
use crate::compaction::multi_region::memory::{BATCH_SIZE, MemoryLimits, UploadBudget};
use crate::compaction::multi_region::memory::{MemoryLimits, UploadBudget};
use crate::compaction::multi_region::metrics::{self, StageGuard};
use crate::compaction::multi_region::{
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, SourceCounters,
};
@@ -55,7 +60,7 @@ use crate::sst::index::registry::{IndexBuildPlan, IndexRegistry};
use crate::sst::parquet::decoded_input_size;
use crate::sst::parquet::file_range::PreFilterMode;
use crate::sst::parquet::flat_format::{
primary_key_column_index, sequence_column_index, time_index_column_index,
decode_primary_keys, primary_key_column_index, sequence_column_index, time_index_column_index,
};
use crate::sst::parquet::format::{PrimaryKeyArray, need_override_sequence};
use crate::sst::parquet::reader::{MetadataCacheMetrics, ReaderMetrics};
@@ -83,7 +88,7 @@ impl RoutedBatch {
let rows = &self.rows[self.offset..];
let len = rows
.partition_point(|row| row.0 == region_id)
.min(BATCH_SIZE);
.min(source.limits.batch_rows);
let indices = UInt64Array::from_iter_values(rows[..len].iter().map(|row| row.3 as u64));
let batch = take_record_batch(&self.batch, &indices).context(ComputeArrowSnafu)?;
let batch = compact_dictionaries(batch)?;
@@ -105,7 +110,7 @@ pub(crate) struct SharedSource {
targets: BTreeMap<RegionId, MultiRegionTarget>,
metadata: RegionMetadataRef,
scan_input: ScanInput,
routing_codec: Arc<dyn mito_codec::row_converter::PrimaryKeyCodec>,
primary_key_codec: Arc<dyn PrimaryKeyCodec>,
schema: SchemaRef,
merge_schema: SchemaRef,
partition_rule: PartitionRuleRef,
@@ -118,6 +123,7 @@ pub(crate) struct SharedSource {
cancellation: CancellationToken,
stop: CancellationToken,
counters: Arc<SourceCounters>,
memory_admission: Option<Arc<OwnedSemaphorePermit>>,
}
impl SharedSource {
@@ -194,7 +200,7 @@ impl SharedSource {
let scan_input = ScanInput::builder(context.access_layer.clone(), mapper)
.with_compaction(true)
.with_page_index_policy(PageIndexPolicy::Skip)
.with_batch_size(BATCH_SIZE)
.with_batch_size(super::tuning().batch_rows)
.with_cache(cache.clone())
.with_json2_rewrite_targets(json2_targets.clone())
.build();
@@ -250,11 +256,12 @@ impl SharedSource {
.collect::<Vec<_>>();
let merge_schema = Arc::new(Schema::new(fields));
Ok(Arc::new(Self {
memory_admission: context.memory_admission.clone(),
sources: plan.sources.clone(),
legacy_overrides,
expected_rows,
targets: plan.targets.clone(),
routing_codec: mito_codec::row_converter::build_primary_key_codec(&metadata),
primary_key_codec: build_primary_key_codec(&metadata),
metadata,
scan_input,
schema,
@@ -293,11 +300,20 @@ impl SharedSource {
) -> std::pin::Pin<Box<dyn futures::Stream<Item = Result<SourceEvent>> + Send>> {
use futures::TryStreamExt;
Box::pin(async_stream::try_stream! {
let parallelism = self.limits.source_parallelism;
let permits = Arc::new(Semaphore::new(parallelism));
let streams = (0..self.sources.len())
.map(|index| self.clone().source_batches(index))
.map(|index| {
let stream = self.clone().source_batches(index);
if parallelism > 1 {
prefetch_source(stream, permits.clone())
} else {
stream
}
})
.collect();
let mut merged =
FlatMergeReader::new(self.merge_schema.clone(), streams, BATCH_SIZE, None).await?;
FlatMergeReader::new(self.merge_schema.clone(), streams, self.limits.batch_rows, None).await?;
let mut groups = KeyGroups::new(self.limits.group);
while let Some(batch) = merged.next_batch().await? {
self.check_cancelled()?;
@@ -321,12 +337,12 @@ impl SharedSource {
) -> std::pin::Pin<Box<dyn futures::Stream<Item = Result<SourceEvent>> + Send>> {
Box::pin(async_stream::try_stream! {
let router = self.clone();
let mut routed = common_runtime::spawn_blocking_compact(move || router.route(batches))
let mut routed = spawn_preparation(self.memory_admission.clone(), move || router.route(batches))
.await
.context(crate::error::JoinSnafu)??;
loop {
let router = self.clone();
let (event, next) = common_runtime::spawn_blocking_compact(move || {
let (event, next) = spawn_preparation(self.memory_admission.clone(), move || {
let event = routed.next_fragment(&router)?;
Ok::<_, crate::error::Error>((event, routed))
}).await.context(crate::error::JoinSnafu)??;
@@ -353,16 +369,26 @@ impl SharedSource {
let fetch_metrics = ParquetFetchMetrics::default();
let mut rows = 0u64;
let mut last_key = None;
let mut read_batches = 0usize;
let mut reported_bytes = 0;
for range in ranges {
let Some(mut reader) = range.flat_reader(None, Some(&fetch_metrics)).await? else {
continue;
};
while let Some(batch) = crate::read::scan_util::next_aligned_file_batch(
&range, &mut reader, None, false,
).await? {
while let Some(batch) = {
let _stage = StageGuard::start("read_batch");
crate::read::scan_util::next_aligned_file_batch(
&range, &mut reader, None, false,
).await?
} {
self.check_cancelled()?;
read_batches += 1;
if read_batches.is_multiple_of(64) {
self.report_store_bytes(&fetch_metrics, &mut reported_bytes)?;
}
let preparing = self.clone();
let (batch, previous) = common_runtime::spawn_blocking_compact(move || {
let (batch, previous) = spawn_preparation(self.memory_admission.clone(), move || {
let _stage = StageGuard::start("prepare_batch");
preparing.check_cancelled()?;
let batch = compact_dictionaries(batch)?;
let batch_bytes = batch.get_array_memory_size();
@@ -383,15 +409,11 @@ impl SharedSource {
last_key = previous;
rows += batch.num_rows() as u64;
self.counters.rows.fetch_add(batch.num_rows() as u64, Ordering::Relaxed);
metrics::progress("input_rows", batch.num_rows() as u64);
yield batch;
}
}
let store_bytes = fetch_metrics.data.lock()
.map(|metrics| metrics.page_size_to_fetch_store)
.map_err(|_| crate::error::UnexpectedSnafu {
reason: "Source fetch metrics lock poisoned",
}.build())?;
self.counters.store_page_bytes.fetch_add(store_bytes, Ordering::Relaxed);
self.report_store_bytes(&fetch_metrics, &mut reported_bytes)?;
let expected = self.expected_rows[index];
if expected < 0 || rows != expected as u64 {
Err(InvalidMultiRegionCompactionSnafu {
@@ -400,9 +422,34 @@ impl SharedSource {
.build())?;
}
self.counters.files.fetch_add(1, Ordering::Relaxed);
metrics::progress("input_files", 1);
})
}
fn report_store_bytes(
&self,
fetch_metrics: &ParquetFetchMetrics,
reported: &mut u64,
) -> Result<()> {
let total = fetch_metrics
.data
.lock()
.map_err(|_| {
crate::error::UnexpectedSnafu {
reason: "Source fetch metrics lock poisoned",
}
.build()
})?
.page_size_to_fetch_store;
let delta = total.saturating_sub(*reported);
self.counters
.store_page_bytes
.fetch_add(delta, Ordering::Relaxed);
metrics::progress("store_page_bytes", delta);
*reported = total;
Ok(())
}
fn validate_batch(
&self,
batch: &RecordBatch,
@@ -538,60 +585,14 @@ impl SharedSource {
})
}
/// Materialize only routing dependencies; merge and output retain encoded keys.
fn routing_batch(&self, batch: &RecordBatch) -> Result<(RecordBatch, usize)> {
let mut materialized_bytes = 0usize;
let mut decoded = None;
let mut fields = Vec::new();
let mut arrays = Vec::new();
for name in self.partition_rule.partition_columns() {
let column =
self.metadata
.column_by_name(name)
.context(InvalidMultiRegionCompactionSnafu {
reason: "Unknown partition column",
})?;
let array = if let Some(array) = batch.column_by_name(name) {
array.clone()
} else {
if decoded.is_none() {
decoded = Some(crate::sst::parquet::flat_format::decode_primary_keys(
self.routing_codec.as_ref(),
batch,
)?);
}
let array = decoded
.as_mut()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Missing decoded routing key",
})?
.get_tag_column(column.column_id, None, &column.column_schema.data_type)?;
materialized_bytes =
materialized_bytes.saturating_add(array.get_array_memory_size());
array
};
fields.push(Field::new(name, array.data_type().clone(), true));
arrays.push(array);
}
let options = datatypes::arrow::record_batch::RecordBatchOptions::new()
.with_row_count(Some(batch.num_rows()));
let routing =
RecordBatch::try_new_with_options(Arc::new(Schema::new(fields)), arrays, &options)
.context(NewRecordBatchSnafu)?;
Ok((routing, materialized_bytes))
}
pub(super) fn row_owners(&self, batch: &RecordBatch) -> Result<Vec<RegionId>> {
let (routing, materialized_bytes) = self.routing_batch(batch)?;
ensure!(
batch
.get_array_memory_size()
.saturating_add(materialized_bytes)
<= self.limits.arrow_batch_bytes,
MultiRegionCompactionResourceSnafu {
reason: "Routing projection exceeds the task buffer budget"
}
);
let routing = routing_batch(
&self.metadata,
self.primary_key_codec.as_ref(),
self.partition_rule.partition_columns(),
batch,
self.limits.arrow_batch_bytes,
)?;
let batch = &routing;
let rows = batch.num_rows();
let masks = self
@@ -681,6 +682,73 @@ impl SharedSource {
}
}
/// Decodes only partition dependencies into a temporary batch. The merge
/// stream and writers retain the compact SST layout.
fn routing_batch(
metadata: &RegionMetadata,
codec: &dyn PrimaryKeyCodec,
names: &[String],
batch: &RecordBatch,
memory_limit: usize,
) -> Result<RecordBatch> {
let mut retained_bytes = batch.get_array_memory_size();
ensure!(
retained_bytes <= memory_limit,
MultiRegionCompactionResourceSnafu {
reason: "Partition routing batch exceeds the task buffer budget",
}
);
if names.is_empty() {
return Ok(batch.clone());
}
let mut decoded = None;
let mut columns = Vec::with_capacity(names.len());
let mut fields = Vec::with_capacity(names.len());
for name in names {
let array = if let Some(array) = batch.column_by_name(name) {
array.clone()
} else {
let column =
metadata
.column_by_name(name)
.context(InvalidMultiRegionCompactionSnafu {
reason: "Partition column missing from the source metadata",
})?;
ensure!(
metadata.primary_key_index(column.column_id).is_some(),
InvalidMultiRegionCompactionSnafu {
reason: "Partition column missing from the source batch",
}
);
let decoded = match &mut decoded {
Some(decoded) => decoded,
None => decoded.insert(decode_primary_keys(codec, batch)?),
};
let array = decoded.get_tag_column(
column.column_id,
metadata.primary_key_index(column.column_id),
&column.column_schema.data_type,
)?;
// The compact source and decoded routing dependencies coexist. Stop
// before decoding the next dependency if their buffers exceed the
// same per-source allowance used by the expanded representation.
retained_bytes = retained_bytes.saturating_add(array.get_array_memory_size());
ensure!(
retained_bytes <= memory_limit,
MultiRegionCompactionResourceSnafu {
reason: "Partition routing batch exceeds the task buffer budget",
}
);
array
};
fields.push(Field::new(name, array.data_type().clone(), true));
columns.push(array);
}
let routing = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)
.context(NewRecordBatchSnafu)?;
Ok(routing)
}
/// Carries only the trailing equal (PK,time) group. Complete groups can be
/// routed immediately; EOF closes the remaining group without another scan.
struct KeyGroups {
@@ -744,6 +812,62 @@ impl KeyGroups {
}
}
/// Tokio cannot abort an already-running blocking closure. Retain its admission
/// independently of the awaiting future so cancellation cannot admit another job
/// against memory that this closure is still using.
fn spawn_preparation<F, T>(
admission: Option<Arc<OwnedSemaphorePermit>>,
prepare: F,
) -> tokio::task::JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
common_runtime::spawn_blocking_compact(move || {
let _admission = admission;
prepare()
})
}
/// Keep one prepared batch per source ahead of the merge. The shared permit
/// bounds active I/O/preparation, and is released before waiting on the channel
/// so a source that is not the current merge winner cannot block other sources.
fn prefetch_source(
mut source: BoxedRecordBatchStream,
permits: Arc<Semaphore>,
) -> BoxedRecordBatchStream {
use futures::TryStreamExt;
let (sender, mut receiver) = mpsc::channel(1);
let task = AbortOnDropHandle::new(common_runtime::spawn_compact(async move {
loop {
let next = {
let _permit = permits.acquire().await.map_err(|_| {
InvalidMultiRegionCompactionSnafu {
reason: "Source preparation semaphore closed",
}
.build()
})?;
source.try_next().await?
};
let Some(batch) = next else { break };
let _stage = StageGuard::start("source_channel_wait");
if sender.send(batch).await.is_err() {
break;
}
}
Ok::<_, crate::error::Error>(())
}));
Box::pin(async_stream::try_stream! {
while let Some(batch) = receiver.recv().await {
yield batch;
}
// A closed channel alone cannot distinguish EOF from a failed/panicked
// producer. Keep the task owned by this stream, including on cancellation.
task.await.context(crate::error::JoinSnafu)??;
})
}
fn trailing_group_start(batch: &RecordBatch) -> Result<usize> {
let last = batch.num_rows() - 1;
let mut start = last;
@@ -769,8 +893,9 @@ fn same_key(
}
/// A selected batch must not pin dictionaries for a whole row group or version
/// group. Casting through the value type compacts both tag and PK dictionaries.
/// group. Copy only referenced dictionary values without expanding them per row.
fn compact_dictionaries(batch: RecordBatch) -> Result<RecordBatch> {
let _stage = StageGuard::start("dictionary_remap");
let columns = batch
.columns()
.iter()
@@ -787,26 +912,55 @@ fn compact_dictionaries(batch: RecordBatch) -> Result<RecordBatch> {
}
fn compact_dictionary<T: ByteArrayType>(array: &ArrayRef) -> Result<ArrayRef> {
let decoded = cast(array, &T::DATA_TYPE).context(ComputeArrowSnafu)?;
let values = decoded
let dictionary = array
.as_any()
.downcast_ref::<DictionaryArray<UInt32Type>>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Invalid UInt32 dictionary",
})?;
let values = dictionary
.values()
.as_any()
.downcast_ref::<GenericByteArray<T>>()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Invalid decoded dictionary",
reason: "Invalid byte dictionary values",
})?;
// Bound remapping work by the selected batch, not the original row group's
// dictionary. Arrow's dictionary garbage collector sizes its map by that
// entire dictionary, which can be much larger than a routed fragment.
let mut selected: Vec<_> = dictionary.keys().iter().flatten().collect();
selected.sort_unstable();
selected.dedup();
// Different dictionary keys can contain equal bytes. Intern each referenced
// key once, preserving the old memory compactness without hashing every row
// or first expanding all rows into a temporary byte array.
let mut builder = GenericByteDictionaryBuilder::<UInt32Type, T>::with_capacity(
values.len(),
values.len(),
values.value_data().len(),
selected.len(),
selected.len(),
0,
);
for value in values.iter() {
if let Some(value) = value {
builder.append(value).context(ComputeArrowSnafu)?;
} else {
for &key in &selected {
if values.is_null(key as usize) {
builder.append_null();
} else {
builder
.append(values.value(key as usize))
.context(ComputeArrowSnafu)?;
}
}
Ok(Arc::new(builder.finish()))
let referenced = builder.finish();
let keys = UInt32Array::from_iter(dictionary.keys().iter().map(|key| {
key.and_then(|key| {
// Every non-null input key is in selected. The referenced dictionary
// key is null when the old key addressed a null dictionary value.
let index = selected.partition_point(|old| *old < key);
(!referenced.keys().is_null(index)).then(|| referenced.keys().value(index))
})
}));
Ok(Arc::new(
DictionaryArray::<UInt32Type>::try_new(keys, referenced.values().clone())
.context(ComputeArrowSnafu)?,
))
}
fn key_at(batch: &RecordBatch, row: usize) -> Result<&[u8]> {
@@ -839,3 +993,518 @@ fn key_at(batch: &RecordBatch, row: usize) -> Result<&[u8]> {
fn admitted_index_threshold(configured: Option<usize>, limit: usize) -> MemoryThreshold {
MemoryThreshold::Size(ReadableSize(configured.unwrap_or(limit).min(limit) as u64))
}
#[cfg(test)]
mod tests {
use std::hint::black_box;
use std::time::Instant;
use datatypes::arrow::array::StringArray;
use datatypes::arrow::compute::cast;
use super::*;
// Keep the previous implementation as an independent semantic oracle and
// benchmark baseline: decode rows, then intern their values again.
fn rebuild_dictionary<T: ByteArrayType>(array: &ArrayRef) -> ArrayRef {
let decoded = cast(array.as_ref(), &T::DATA_TYPE).unwrap();
let values = decoded
.as_any()
.downcast_ref::<GenericByteArray<T>>()
.unwrap();
let mut builder = GenericByteDictionaryBuilder::<UInt32Type, T>::with_capacity(
values.len(),
values.len(),
values.value_data().len(),
);
for value in values.iter() {
if let Some(value) = value {
builder.append(value).unwrap();
} else {
builder.append_null();
}
}
Arc::new(builder.finish())
}
fn assert_dictionary_values(array: ArrayRef) -> ArrayRef {
let DataType::Dictionary(_, value_type) = array.data_type() else {
unreachable!();
};
let output = match value_type.as_ref() {
DataType::Utf8 => compact_dictionary::<Utf8Type>(&array).unwrap(),
DataType::Binary => compact_dictionary::<BinaryType>(&array).unwrap(),
_ => unreachable!(),
};
assert_eq!(output.data_type(), array.data_type());
assert_eq!(output.len(), array.len());
assert_eq!(
cast(array.as_ref(), value_type).unwrap().to_data(),
cast(output.as_ref(), value_type).unwrap().to_data(),
);
output
}
#[test]
fn test_compact_dictionary_preserves_values_and_nulls() {
let strings = StringArray::from(vec![
Some("unused"),
Some("same"),
None,
Some("same"),
Some(""),
]);
let binary = BinaryArray::from(vec![
Some(b"unused".as_slice()),
Some(b"same".as_slice()),
None,
Some(b"same".as_slice()),
Some(b"".as_slice()),
]);
for values in [Arc::new(strings) as ArrayRef, Arc::new(binary) as ArrayRef] {
for keys in [
vec![Some(0), Some(3), None, Some(2), Some(1), Some(4), Some(3)],
vec![None, None],
vec![],
] {
let array: ArrayRef = Arc::new(
DictionaryArray::<UInt32Type>::try_new(UInt32Array::from(keys), values.clone())
.unwrap(),
);
let output = assert_dictionary_values(array.clone());
let baseline = if matches!(values.data_type(), DataType::Utf8) {
rebuild_dictionary::<Utf8Type>(&array)
} else {
rebuild_dictionary::<BinaryType>(&array)
};
let actual = output
.as_any()
.downcast_ref::<DictionaryArray<UInt32Type>>()
.unwrap();
let expected = baseline
.as_any()
.downcast_ref::<DictionaryArray<UInt32Type>>()
.unwrap();
assert_eq!(actual.values().len(), expected.values().len());
if array.len() > 2 {
assert_dictionary_values(array.slice(1, array.len() - 2));
}
}
}
}
#[test]
fn test_compact_dictionary_releases_unused_and_sliced_value_buffers() {
let values = Arc::new(StringArray::from_iter_values(
(0..4096).map(|i| format!("{i}:{}", "x".repeat(1024))),
)) as ArrayRef;
// Sparse selections must not allocate proportional to the old dictionary,
// or retain its multi-megabyte string buffer.
let dictionary: ArrayRef = Arc::new(
DictionaryArray::<UInt32Type>::try_new(
UInt32Array::from(vec![Some(4095), None, Some(4095)]),
values.clone(),
)
.unwrap(),
);
let output = assert_dictionary_values(dictionary);
assert!(output.get_array_memory_size() < 8192);
let compacted = output
.as_any()
.downcast_ref::<DictionaryArray<UInt32Type>>()
.unwrap();
assert_eq!(compacted.values().len(), 1);
// Even when all values are referenced, a slice can retain a large buffer.
let dictionary: ArrayRef = Arc::new(
DictionaryArray::<UInt32Type>::try_new(
UInt32Array::from(vec![0, 1, 0]),
values.slice(4094, 2),
)
.unwrap(),
);
let output = assert_dictionary_values(dictionary);
assert!(output.get_array_memory_size() < 8192);
}
#[tokio::test]
async fn test_cancelled_preparation_retains_memory_admission() {
let permits = Arc::new(Semaphore::new(1));
let admission = Arc::new(permits.clone().acquire_owned().await.unwrap());
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let task = spawn_preparation(Some(admission.clone()), move || {
let _ = started_tx.send(());
release_rx.recv().unwrap();
});
started_rx.await.unwrap();
task.abort();
drop(task);
drop(admission);
// The detached blocking closure still owns its memory, even after both
// the awaiting task and the original executor's permit have been dropped.
assert!(permits.try_acquire().is_err());
release_tx.send(()).unwrap();
let permit = tokio::time::timeout(std::time::Duration::from_secs(10), permits.acquire())
.await
.unwrap()
.unwrap();
drop(permit);
assert_eq!(permits.available_permits(), 1);
}
#[tokio::test]
async fn test_prefetch_sources_parallel_bounded_and_ordered() {
use futures::TryStreamExt;
use std::sync::atomic::AtomicUsize;
use tokio::sync::Barrier;
let permits = Arc::new(Semaphore::new(2));
let active = Arc::new(AtomicUsize::new(0));
let peak = Arc::new(AtomicUsize::new(0));
let barrier = Arc::new(Barrier::new(2));
let mut streams = Vec::new();
for source_id in 0..4 {
let active = active.clone();
let peak = peak.clone();
let barrier = barrier.clone();
let source: BoxedRecordBatchStream = Box::pin(async_stream::try_stream! {
let count = active.fetch_add(1, Ordering::Relaxed) + 1;
peak.fetch_max(count, Ordering::Relaxed);
// Both admitted sources must reach this point before either
// proceeds. This proves actual overlap without timing sleeps.
barrier.wait().await;
active.fetch_sub(1, Ordering::Relaxed);
for row in 0..3 {
yield RecordBatch::try_from_iter([
("value", Arc::new(UInt64Array::from(vec![source_id * 10 + row])) as ArrayRef),
]).unwrap();
}
});
streams.push(prefetch_source(source, permits.clone()));
}
let reads = streams
.into_iter()
.map(|stream| stream.try_collect::<Vec<_>>());
let outputs = tokio::time::timeout(
std::time::Duration::from_secs(10),
futures::future::try_join_all(reads),
)
.await
.unwrap()
.unwrap();
assert_eq!(peak.load(Ordering::Relaxed), 2);
for (source_id, output) in outputs.into_iter().enumerate() {
let values: Vec<_> = output
.iter()
.map(|batch| {
batch
.column(0)
.as_any()
.downcast_ref::<UInt64Array>()
.unwrap()
.value(0)
})
.collect();
assert_eq!(
values,
vec![
source_id as u64 * 10,
source_id as u64 * 10 + 1,
source_id as u64 * 10 + 2
]
);
}
}
#[tokio::test]
async fn test_prefetch_source_preserves_error_and_releases_on_drop() {
use futures::TryStreamExt;
use tokio::sync::oneshot;
let source: BoxedRecordBatchStream = Box::pin(futures::stream::once(async {
Err(InvalidMultiRegionCompactionSnafu {
reason: "source test failure",
}
.build())
}));
let mut stream = prefetch_source(source, Arc::new(Semaphore::new(1)));
assert!(
stream
.try_next()
.await
.unwrap_err()
.to_string()
.contains("source test failure")
);
let (started_tx, started_rx) = oneshot::channel();
let (dropped_tx, dropped_rx) = oneshot::channel();
struct NotifyOnDrop(Option<oneshot::Sender<()>>);
impl Drop for NotifyOnDrop {
fn drop(&mut self) {
if let Some(sender) = self.0.take() {
let _ = sender.send(());
}
}
}
let source: BoxedRecordBatchStream = Box::pin(async_stream::try_stream! {
let _guard = NotifyOnDrop(Some(dropped_tx));
let _ = started_tx.send(());
futures::future::pending::<()>().await;
yield RecordBatch::new_empty(Arc::new(Schema::empty()));
});
let permits = Arc::new(Semaphore::new(1));
let stream = prefetch_source(source, permits.clone());
started_rx.await.unwrap();
drop(stream);
tokio::time::timeout(std::time::Duration::from_secs(10), dropped_rx)
.await
.unwrap()
.unwrap();
assert_eq!(permits.available_permits(), 1);
}
#[test]
#[ignore = "manual dictionary compaction performance comparison"]
fn bench_compact_dictionary_remap() {
common_telemetry::init_default_ut_logging();
let values: ArrayRef = Arc::new(StringArray::from_iter_values(
(0..4096).map(|i| format!("{i}:{}", "x".repeat(1024))),
));
for rows in [64, 256, 1024] {
for distinct in [1, 8, rows] {
let input: ArrayRef = Arc::new(
DictionaryArray::<UInt32Type>::try_new(
UInt32Array::from_iter_values(
(0..rows).map(|row| (4095 - row % distinct) as u32),
),
values.clone(),
)
.unwrap(),
);
let baseline = rebuild_dictionary::<Utf8Type>(&input);
let actual = assert_dictionary_values(input.clone());
assert_eq!(
cast(baseline.as_ref(), &DataType::Utf8).unwrap().to_data(),
cast(actual.as_ref(), &DataType::Utf8).unwrap().to_data()
);
for repetition in 0..5 {
// Alternate execution order to reduce warmup/order bias.
for remap in if repetition % 2 == 0 {
[false, true]
} else {
[true, false]
} {
let start = Instant::now();
for _ in 0..1000 {
let output = if remap {
compact_dictionary::<Utf8Type>(black_box(&input)).unwrap()
} else {
rebuild_dictionary::<Utf8Type>(black_box(&input))
};
black_box(output);
}
common_telemetry::info!(
rows,
distinct,
repetition,
remap,
elapsed_ns = start.elapsed().as_nanos() as u64,
retained_bytes = actual.get_array_memory_size(),
"Dictionary compaction benchmark"
);
}
}
}
}
}
#[test]
fn test_sparse_routing_accounts_decoded_dependencies() {
use crate::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema};
use crate::test_util::sst_util::{
new_sparse_primary_key, sst_region_metadata_with_encoding,
};
use datatypes::arrow::array::{
BinaryDictionaryBuilder, TimestampMillisecondArray, UInt8Array,
};
use store_api::codec::PrimaryKeyEncoding;
let metadata = Arc::new(sst_region_metadata_with_encoding(
PrimaryKeyEncoding::Sparse,
));
let codec = build_primary_key_codec(&metadata);
let label = "x".repeat(4096);
let mut keys = BinaryDictionaryBuilder::<UInt32Type>::new();
keys.append(new_sparse_primary_key(&[&label, "series"], &metadata, 1, 1))
.unwrap();
let batch = RecordBatch::try_new(
to_flat_sst_arrow_schema(
&metadata,
&FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Sparse),
),
vec![
Arc::new(UInt64Array::from(vec![1])),
Arc::new(TimestampMillisecondArray::from(vec![0])),
Arc::new(keys.finish()),
Arc::new(UInt64Array::from(vec![1])),
Arc::new(UInt8Array::from(vec![0])),
],
)
.unwrap();
let names = ["tag_0".into(), "field_0".into()];
let routing = routing_batch(&metadata, codec.as_ref(), &names, &batch, usize::MAX).unwrap();
assert_eq!(2, routing.num_columns());
let retained = batch.get_array_memory_size() + routing.column(0).get_array_memory_size();
routing_batch(&metadata, codec.as_ref(), &names, &batch, retained).unwrap();
let error =
routing_batch(&metadata, codec.as_ref(), &names, &batch, retained - 1).unwrap_err();
assert!(matches!(
error,
crate::error::Error::MultiRegionCompactionResource { .. }
));
assert!(Arc::ptr_eq(
batch.column_by_name("field_0").unwrap(),
routing.column(1)
));
}
/// Isolates tag materialization and dictionary work from object-store I/O.
#[test]
#[ignore = "manual wide sparse routing ablation benchmark"]
fn bench_sparse_routing_materialization() {
use crate::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema};
use crate::test_util::sst_util::{
new_sparse_primary_key, sst_region_metadata_with_encoding,
};
use api::v1::SemanticType;
use datatypes::arrow::array::{
BinaryDictionaryBuilder, TimestampMillisecondArray, UInt8Array,
};
use datatypes::data_type::ConcreteDataType;
use datatypes::schema::ColumnSchema;
use datatypes::value::Value;
use partition::expr::col;
use partition::multi_dim::MultiDimPartitionRule;
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
common_telemetry::init_default_ut_logging();
let metadata = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse);
let mut builder = RegionMetadataBuilder::from_existing(metadata.clone());
let mut primary_key = metadata.primary_key.clone();
for id in 10..3610 {
builder.push_column_metadata(ColumnMetadata {
column_id: id,
semantic_type: SemanticType::Tag,
column_schema: ColumnSchema::new(
format!("unused_tag_{id}"),
ConcreteDataType::string_datatype(),
true,
),
});
primary_key.push(id);
}
builder.primary_key(primary_key);
let metadata = Arc::new(builder.build().unwrap());
let codec = build_primary_key_codec(&metadata);
let all_tags: Vec<_> = metadata
.primary_key_columns()
.map(|column| (column.column_id, column.column_schema.data_type.clone()))
.collect();
let rule = MultiDimPartitionRule::try_new(
vec!["tag_0".into()],
vec![0, 1],
vec![
col("tag_0").lt(Value::from("032")),
col("tag_0").gt_eq(Value::from("032")),
],
false,
)
.unwrap();
for distinct in [1, 8, 64] {
let mut keys = BinaryDictionaryBuilder::<UInt32Type>::new();
for row in 0..64 {
keys.append(new_sparse_primary_key(
&[&format!("{:03}", row % distinct), "series"],
&metadata,
1,
(row % distinct) as u64,
))
.unwrap();
}
let batch = RecordBatch::try_new(
to_flat_sst_arrow_schema(
&metadata,
&FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Sparse),
),
vec![
Arc::new(UInt64Array::from(vec![1; 64])),
Arc::new(TimestampMillisecondArray::from(vec![0; 64])),
Arc::new(keys.finish()),
Arc::new(UInt64Array::from(vec![1; 64])),
Arc::new(UInt8Array::from(vec![0; 64])),
],
)
.unwrap();
let materialize = |full: bool| {
if !full {
let routing = routing_batch(
&metadata,
codec.as_ref(),
&["tag_0".into()],
&batch,
usize::MAX,
)
.unwrap();
return (
rule.split_record_batch(&routing).unwrap(),
routing.get_array_memory_size(),
);
}
let mut decoded = decode_primary_keys(codec.as_ref(), &batch).unwrap();
let arrays = decoded.get_sparse_tag_columns(&all_tags).unwrap();
let fields: Vec<_> = arrays
.iter()
.enumerate()
.map(|(i, array)| {
let column = metadata.column_by_id(all_tags[i].0).unwrap();
Field::new(&column.column_schema.name, array.data_type().clone(), true)
})
.collect();
let routing = compact_dictionaries(
RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).unwrap(),
)
.unwrap();
let masks = rule.split_record_batch(&routing).unwrap();
(masks, routing.get_array_memory_size())
};
let (baseline, full_bytes) = materialize(true);
let (projected, projected_bytes) = materialize(false);
assert_eq!(baseline.len(), projected.len());
for (region, mask) in baseline {
assert_eq!(mask.array(), projected[&region].array());
}
for repetition in 0..5 {
for full in if repetition % 2 == 0 {
[true, false]
} else {
[false, true]
} {
let start = Instant::now();
for _ in 0..20 {
black_box(materialize(black_box(full)));
}
common_telemetry::info!(
distinct,
repetition,
full,
elapsed_ns = start.elapsed().as_nanos() as u64,
full_bytes,
projected_bytes,
"Sparse routing materialization benchmark"
);
}
}
}
}
}
+207 -2
View File
@@ -316,6 +316,7 @@ impl Fixture {
cache: Arc::new(CacheManager::default()),
config: self.config.clone(),
protection: protection.clone(),
memory_admission: None,
cancellation: CancellationToken::new(),
},
protection,
@@ -1215,9 +1216,14 @@ async fn test_unmatched_partition_values_use_the_table_default_region() {
}
}
#[rstest::rstest]
#[case::dense(PrimaryKeyEncoding::Dense)]
#[case::sparse(PrimaryKeyEncoding::Sparse)]
#[tokio::test]
async fn test_nullable_field_partitioning_preserves_delete_records() {
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
async fn test_nullable_field_partitioning_preserves_delete_records(
#[case] encoding: PrimaryKeyEncoding,
) {
let fixture = Fixture::new(encoding, FormatType::Flat, 0).await;
let mut plan = fixture.plan(2);
let exprs = vec![
col("field_0").lt(Value::UInt64(20)),
@@ -1254,6 +1260,176 @@ async fn test_nullable_field_partitioning_preserves_delete_records() {
}
}
#[tokio::test]
async fn test_shared_compaction_preserves_dense_to_sparse_compatibility() {
let mut fixture = Fixture::new(PrimaryKeyEncoding::Sparse, FormatType::Flat, 7).await;
let mut builder = RegionMetadataBuilder::from_existing((*fixture.metadata).clone());
builder.primary_key_encoding(PrimaryKeyEncoding::Dense);
let dense = Arc::new(builder.build().unwrap());
// Construct a real dense input: query projection alone need not rewrite
// internal key bytes, even when its exposed metadata uses another encoding.
let sparse_codec = mito_codec::row_converter::build_primary_key_codec(&fixture.metadata);
let dense_codec = mito_codec::row_converter::build_primary_key_codec(&dense);
let batches = fixture
.read_output(fixture.source.clone(), fixture.metadata.clone())
.await
.into_iter()
.map(|batch| {
let key_index = primary_key_column_index(batch.num_columns());
let keys = cast(batch.column(key_index), &DataType::Binary).unwrap();
let keys = keys.as_any().downcast_ref::<BinaryArray>().unwrap();
let mut encoded = BinaryDictionaryBuilder::<UInt32Type>::new();
for key in keys.iter() {
let mito_codec::row_converter::CompositeValues::Sparse(values) =
sparse_codec.decode(key.unwrap()).unwrap()
else {
unreachable!()
};
let values: Vec<_> = dense
.primary_key
.iter()
.map(|id| (*id, values.get_or_null(*id).clone()))
.collect();
let mut key = Vec::new();
dense_codec.encode_values(&values, &mut key).unwrap();
let mito_codec::row_converter::CompositeValues::Dense(decoded) =
dense_codec.decode(&key).unwrap()
else {
unreachable!()
};
assert_eq!(values, decoded);
encoded.append(key).unwrap();
}
let mut columns = batch.columns().to_vec();
columns[key_index] = Arc::new(encoded.finish());
RecordBatch::try_new(
to_flat_sst_arrow_schema(
&dense,
&FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Dense),
),
columns,
)
.unwrap()
})
.collect();
let info = fixture
.write_source(dense.clone(), batches, FormatType::Flat)
.await;
fixture.source = file_meta(info, dense.region_id);
let plan = fixture.plan(2);
let targets = plan.targets.clone();
let output = fixture.compact(plan).await;
assert_eq!(124, output.stats.output_rows);
for (id, files) in output.files {
let mut rows = Vec::new();
for file in files {
rows.extend(
fixture
.read_output_rows(file, targets[&id].metadata.clone())
.await,
);
}
rows.sort();
let sequence = if id == fixture.metadata.region_id {
7
} else {
100 + u64::from(id.region_sequence())
};
let mut expected = expected_source_rows(2, id, sequence);
expected.sort();
assert_eq!(expected, rows);
}
}
/// Wide sparse schemas must not become wide Arrow batches during routing or merge.
#[tokio::test]
async fn test_sparse_shared_compaction_keeps_unrelated_tags_encoded() {
let fixture = Fixture::new(PrimaryKeyEncoding::Sparse, FormatType::Flat, 7).await;
let mut plan = fixture.plan(2);
let expressions: Vec<_> = plan
.targets
.values_mut()
.map(|target| {
let expr =
crate::region::parse_partition_expr(target.metadata.partition_expr.as_deref())
.unwrap()
.unwrap()
.and(col("tag_1").eq(Value::from("series")));
Arc::make_mut(&mut target.metadata)
.set_partition_expr(Some(expr.as_json_str().unwrap()));
expr
})
.collect();
plan.partition_rule = Arc::new(
MultiDimPartitionRule::try_new(
vec!["tag_0".into(), "tag_1".into()],
vec![0, 1],
expressions,
false,
)
.unwrap(),
);
for target in plan.targets.values_mut() {
let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone());
let mut primary_key = target.metadata.primary_key.clone();
for id in 10..3610 {
builder.push_column_metadata(ColumnMetadata {
column_id: id,
semantic_type: SemanticType::Tag,
column_schema: ColumnSchema::new(
format!("unused_tag_{id}"),
ConcreteDataType::string_datatype(),
true,
),
});
primary_key.push(id);
}
builder.primary_key(primary_key);
target.metadata = Arc::new(builder.build().unwrap());
}
let targets = plan.targets.clone();
let (context, _) = fixture.context(None);
let source = source::SharedSource::build(
&plan,
&context,
validate_plan(&plan).unwrap(),
Arc::new(SourceCounters::default()),
)
.await
.unwrap();
assert_eq!(5, source.schema().fields().len());
let mut batches = source.batches();
let mut rows = 0;
while let Some(event) = batches.try_next().await.unwrap() {
assert_eq!(5, event.batch.num_columns());
assert!(event.batch.column_by_name("tag_0").is_none());
rows += event.batch.num_rows();
}
assert_eq!(124, rows);
let output = fixture.compact(plan).await;
assert_eq!(124, output.stats.output_rows);
for (id, files) in output.files {
let mut rows = Vec::new();
for file in files {
rows.extend(
fixture
.read_output_rows(file, targets[&id].metadata.clone())
.await,
);
}
rows.sort();
let sequence = if id == fixture.metadata.region_id {
7
} else {
100 + u64::from(id.region_sequence())
};
let mut expected = expected_source_rows(2, id, sequence);
expected.sort();
assert_eq!(expected, rows);
}
}
#[tokio::test]
async fn test_unknown_partition_target_fails_before_creating_output() {
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
@@ -3337,3 +3513,32 @@ async fn test_sparse_routing_with_wide_target_schema(#[case] target_tag_count: u
assert_eq!(expected, rows);
}
}
#[test]
fn test_batch_rows_configuration_bounds() {
for (value, expected) in [
("64", Some(64)),
("256", Some(256)),
("1024", Some(1024)),
("0", None),
("63", None),
("1025", None),
("-1", None),
("x", None),
] {
assert_eq!(super::parse_tuning(value, 64, 1024), expected);
}
}
#[test]
fn test_parallelism_configuration_bounds() {
for (value, expected) in [
("0", None),
("1", Some(1)),
("4", Some(4)),
("32", Some(32)),
("33", None),
] {
assert_eq!(super::parse_tuning(value, 1, 32), expected);
}
}
@@ -16,6 +16,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use datatypes::arrow::record_batch::RecordBatch;
use futures::stream::FuturesUnordered;
@@ -25,6 +26,7 @@ use store_api::storage::RegionId;
use tokio::sync::mpsc;
use tokio_util::task::AbortOnDropHandle;
use crate::compaction::multi_region::metrics::{self, StageGuard};
use crate::compaction::multi_region::source::SharedSource;
use crate::compaction::multi_region::{
MultiRegionCompactionContext, MultiRegionCompactionOutput, MultiRegionCompactionPlan,
@@ -46,6 +48,21 @@ pub(crate) async fn execute(
counters: Arc<SourceCounters>,
) -> Result<MultiRegionCompactionOutput> {
let _cancel_on_drop = source.cancel_on_drop();
let table_id = plan
.targets
.keys()
.next()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Compaction requires at least one target",
})?
.table_id();
let started = Instant::now();
let progress_interval = Duration::from_secs(30);
let mut progress = tokio::time::interval_at(
tokio::time::Instant::now() + progress_interval,
progress_interval,
);
progress.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let plan = Arc::new(plan);
let context = Arc::new(context);
let mut senders = BTreeMap::new();
@@ -69,14 +86,17 @@ pub(crate) async fn execute(
workers.push(AbortOnDropHandle::new(common_runtime::spawn_compact(
async move {
let stream = async_stream::try_stream! {
while let Message::Batch(batch) = receiver
.recv()
.await
.context(InvalidMultiRegionCompactionSnafu {
reason: "Source channel closed without Finish",
})?
{
yield batch;
loop {
let message = {
let _stage = StageGuard::start("target_input_wait");
receiver.recv().await.context(InvalidMultiRegionCompactionSnafu {
reason: "Source channel closed without Finish",
})?
};
match message {
Message::Batch(batch) => yield batch,
Message::Finish => break,
}
}
};
let input = FlatSource::new_stream(schema, Box::pin(stream));
@@ -105,6 +125,21 @@ pub(crate) async fn execute(
while !scan_finished || !workers.is_empty() {
tokio::select! {
biased;
_ = progress.tick() => {
common_telemetry::info!(
"Table compaction progress: table_id={}, elapsed_secs={}, completed_input_files={}/{}, input_rows={}, store_page_bytes={}, completed_targets={}/{}, completed_target_output_rows={}, completed_target_output_bytes={}",
table_id,
started.elapsed().as_secs(),
counters.files.load(Ordering::Relaxed),
plan.sources.len(),
counters.rows.load(Ordering::Relaxed),
counters.store_page_bytes.load(Ordering::Relaxed),
output.files.len(),
plan.targets.len(),
output.stats.output_rows,
output.stats.output_bytes,
);
}
Some(result) = workers.next(), if !workers.is_empty() => {
let (id, files, infos) = result.context(crate::error::JoinSnafu)??;
output.stats.output_rows += files
@@ -115,6 +150,9 @@ pub(crate) async fn execute(
.iter()
.map(|file| file.file_size + file.index_file_size)
.sum::<u64>();
metrics::progress("output_files", files.len() as u64);
metrics::progress("output_rows", files.iter().map(|file| file.num_rows).sum());
metrics::progress("output_bytes", files.iter().map(|file| file.file_size + file.index_file_size).sum());
output.files.insert(id, files);
output.sst_infos.insert(id, infos);
}
@@ -144,7 +182,14 @@ async fn dispatch(
senders: BTreeMap<RegionId, mpsc::Sender<Message>>,
) -> Result<()> {
let mut batches = source.batches();
while let Some(event) = batches.try_next().await? {
loop {
let event = {
let _stage = StageGuard::start("merge_route_next");
batches.try_next().await?
};
let Some(event) = event else {
break;
};
let sender = senders
.get(&event.region_id)
.context(InvalidMultiRegionCompactionSnafu {
@@ -159,6 +204,7 @@ async fn dispatch(
}
async fn send(sender: &mpsc::Sender<Message>, message: Message) {
let _stage = StageGuard::start("dispatch_wait");
if sender.send(message).await.is_err() {
// The supervisor reports the writer's original error, not a racing
// channel-closed error. It also aborts siblings on failure or drop.
@@ -75,6 +75,7 @@ impl<'a> TargetWriter<'a> {
!self.context.cancellation.is_cancelled(),
crate::error::CompactionCancelledSnafu
);
let _stage = crate::compaction::multi_region::metrics::StageGuard::start("write_total");
let request = self.request(source)?;
let mut metrics = Metrics::new(WriteType::Compaction);
let infos = self
@@ -91,6 +92,14 @@ impl<'a> TargetWriter<'a> {
},
)
.await?;
for (stage, elapsed) in [
("encode_write_batch", metrics.write_batch),
("update_index", metrics.update_index),
("upload_parquet", metrics.upload_parquet),
("upload_puffin", metrics.upload_puffin),
] {
crate::compaction::multi_region::metrics::observe_stage(stage, elapsed);
}
metrics.observe();
let expression =
crate::region::parse_partition_expr(self.target.metadata.partition_expr.as_deref())?;
@@ -156,7 +165,7 @@ impl<'a> TargetWriter<'a> {
),
float_field_encoding: self.target.options.float_field_encoding,
// Every resident encoder and its finish workspace are admitted together.
encode_parallelism: 1,
encode_parallelism: crate::compaction::multi_region::tuning().encode_parallelism,
encode_runtime: EncodeRuntime::Compact,
}
}
+47 -9
View File
@@ -18,7 +18,7 @@ mod tests;
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metadata::{RegionMetadata, RegionMetadataRef};
use store_api::storage::RegionId;
use store_api::storage::{FileId, RegionId};
use tokio::sync::oneshot;
use crate::engine::MitoEngine;
@@ -28,7 +28,7 @@ use crate::error::{
};
use crate::manifest::action::RegionEdit;
use crate::region::options::RegionOptions;
use crate::region::{RegionLeaderState, RegionRoleState};
use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState};
use crate::request::{RegionEditKind, RegionEditRequest, WorkerRequest};
use crate::sst::file::{FileMeta, SHARED_LEVEL_SLOT};
@@ -70,17 +70,12 @@ pub fn is_table_compaction_metadata_compatible(
}
impl MitoEngine {
/// Reads committed inputs while an ordinary edit or ALTER is in progress.
pub fn table_compaction_snapshot(
&self,
region_id: RegionId,
) -> Result<TableCompactionSnapshot> {
let region = self
.find_region(region_id)
.context(RegionNotFoundSnafu { region_id })?;
ensure!(
region.state() == RegionRoleState::Leader(RegionLeaderState::Writable),
RegionBusySnafu { region_id }
);
let region = self.committed_compaction_region(region_id)?;
let current = region.version_control.current();
Ok(TableCompactionSnapshot {
metadata: current.version.metadata.clone(),
@@ -92,6 +87,49 @@ impl MitoEngine {
})
}
/// Reads committed shared inputs for admission checks, without requiring an idle worker.
///
/// An empty selection reads only metadata and options. Lookups are bounded by the requested
/// file ids, not the region's file count. Editing/Altering leave the committed version readable;
/// actual admission still goes through the worker queue and its lifecycle checks.
/// This is not a compaction planning snapshot or a reservation of the selected inputs.
pub fn shared_ingest_snapshot(
&self,
region_id: RegionId,
file_ids: &[FileId],
) -> Result<TableCompactionSnapshot> {
let region = self.committed_compaction_region(region_id)?;
let current = region.version_control.current();
let shared = &current.version.ssts.levels()[SHARED_LEVEL_SLOT];
Ok(TableCompactionSnapshot {
metadata: current.version.metadata.clone(),
options: serde_json::to_value(&current.version.options).context(SerdeJsonSnafu)?,
inputs: file_ids
.iter()
.filter_map(|id| shared.files.get(id))
.map(|file| file.meta_ref().clone())
.collect(),
})
}
fn committed_compaction_region(&self, region_id: RegionId) -> Result<MitoRegionRef> {
let region = self
.find_region(region_id)
.context(RegionNotFoundSnafu { region_id })?;
ensure!(
match region.state() {
RegionRoleState::Leader(
RegionLeaderState::Writable | RegionLeaderState::Altering,
) => true,
RegionRoleState::Leader(RegionLeaderState::Editing) =>
region.manifest_ctx.staging_partition_info().is_none(),
_ => false,
},
RegionBusySnafu { region_id }
);
Ok(region)
}
/// Publishes one region independently, using compaction rather than import sequences.
///
/// Duplicate submissions are allowed. A stale outcome does NOT prove these
+95 -1
View File
@@ -37,7 +37,7 @@ use crate::engine::lease_test::promote_to_await_leader_lease;
use crate::engine::region_hook::{RegionHook, RegionHookRef, VerifiedSstFileInfo};
use crate::error::Error;
use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
use crate::region::MitoRegionRef;
use crate::region::{MitoRegionRef, RegionLeaderState};
use crate::sst::file::{ColumnIndexMetadata, FileMeta, IndexType, LEVEL_SHARED, SHARED_LEVEL_SLOT};
use crate::sst::location;
use crate::test_util::sst_util::new_sparse_primary_key;
@@ -924,6 +924,94 @@ async fn test_empty_target_replacement_preserves_other_shared_reference() {
assert_eq!(3, row_count(&engine, source).await);
}
#[tokio::test]
async fn test_shared_ingest_snapshot_during_manifest_work() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(config()).await;
let region_id = RegionId::new(1, 1);
let (snapshot, _) = seed_shared_inputs(&engine, region_id, &[(0, 3), (3, 6)]).await;
let region = engine.get_region(region_id).unwrap();
let selected = &snapshot.inputs[0];
for state in [RegionLeaderState::Editing, RegionLeaderState::Altering] {
match state {
RegionLeaderState::Editing => region.set_editing(RegionLeaderState::Writable).unwrap(),
RegionLeaderState::Altering => region.set_altering().unwrap(),
_ => unreachable!(),
}
let planning = engine.table_compaction_snapshot(region_id).unwrap();
assert_eq!(snapshot.metadata, planning.metadata);
assert_eq!(snapshot.options, planning.options);
assert_eq!(snapshot.inputs, planning.inputs);
let options = engine.shared_ingest_snapshot(region_id, &[]).unwrap();
assert_eq!(snapshot.options, options.options);
assert!(options.inputs.is_empty());
let admission = engine
.shared_ingest_snapshot(region_id, &[selected.file_id, FileId::random()])
.unwrap();
assert_eq!(vec![selected.clone()], admission.inputs);
region.switch_state_to_writable(state);
}
region.set_role(RegionRole::Follower);
assert!(engine.table_compaction_snapshot(region_id).is_err());
assert!(engine.shared_ingest_snapshot(region_id, &[]).is_err());
region.set_role(RegionRole::Leader);
region.set_entering_staging().unwrap();
assert!(engine.table_compaction_snapshot(region_id).is_err());
assert!(engine.shared_ingest_snapshot(region_id, &[]).is_err());
}
#[tokio::test]
async fn test_shared_ingest_queues_behind_table_publication() {
let hook = Arc::new(PublicationBarrier {
after_commit: false,
armed: AtomicBool::new(false),
entered: Default::default(),
resume: Default::default(),
});
let plugins = Plugins::new();
plugins.insert(hook.clone() as RegionHookRef);
let mut env = TestEnv::new().await;
let engine = env.create_engine_with_plugins(config(), plugins).await;
let region_id = RegionId::new(1, 1);
let (snapshot, output) = seed(&engine, region_id).await;
let region = engine.get_region(region_id).unwrap();
let mut incoming = copy_sst(&region, &output, LEVEL_SHARED).await;
incoming.sequence = None;
hook.armed.store(true, Ordering::SeqCst);
let (publication, admission) =
tokio::time::timeout(std::time::Duration::from_secs(10), async {
tokio::join!(
engine.publish_table_compaction(region_id, snapshot, vec![output]),
async {
hook.entered.notified().await;
// Admission checks can read committed options while the worker is Editing.
engine.shared_ingest_snapshot(region_id, &[]).unwrap();
let edit = engine.edit_region(
region_id,
RegionEdit {
files_to_add: vec![incoming.clone()],
..Default::default()
},
);
tokio::pin!(edit);
assert!(futures::poll!(&mut edit).is_pending());
hook.resume.notify_one();
edit.await
}
)
})
.await
.unwrap();
assert_eq!(PublicationOutcome::Applied, publication.unwrap());
admission.unwrap();
let installed = engine
.shared_ingest_snapshot(region_id, &[incoming.file_id])
.unwrap();
assert_eq!(1, installed.inputs.len());
assert!(installed.inputs[0].sequence.is_some());
assert_eq!(3, row_count(&engine, region_id).await);
}
#[tokio::test]
async fn test_staging_rejects_publication_without_changing_files() {
use store_api::region_request::{EnterStagingRequest, StagingPartitionDirective};
@@ -949,6 +1037,12 @@ async fn test_staging_rejects_publication_without_changing_files() {
.is_err()
);
assert!(region.is_staging());
region.set_editing(RegionLeaderState::Staging).unwrap();
assert!(matches!(
engine.table_compaction_snapshot(region_id),
Err(Error::RegionBusy { .. })
));
region.switch_state_to_staging(RegionLeaderState::Editing);
assert_eq!(version, region.manifest_ctx.manifest_version().await);
assert_eq!(
1,
+243 -12
View File
@@ -16,6 +16,7 @@
use std::mem;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use bytes::Bytes;
@@ -29,11 +30,13 @@ use parquet::arrow::arrow_writer::{
};
use parquet::arrow::async_writer::AsyncFileWriter;
use parquet::errors::{ParquetError, Result};
use parquet::file::metadata::{KeyValue, ParquetMetaData};
use parquet::file::metadata::{KeyValue, ParquetMetaData, RowGroupMetaData};
use parquet::file::properties::WriterProperties;
use parquet::file::writer::SerializedFileWriter;
use tokio_util::sync::CancellationToken;
use crate::sst::parquet::writer::SstWriteGuard;
/// Runtime whose blocking pool encodes the columns of a writer.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum EncodeRuntime {
@@ -62,7 +65,14 @@ type FieldWriters = (usize, Vec<(usize, ArrowColumnWriter)>);
/// Output of one encode task: column chunks by leaf index, and the time spent
/// on each field.
type EncodedFields = (Vec<(usize, ArrowColumnChunk)>, Vec<(usize, Duration)>);
#[derive(Default)]
pub(crate) struct EncodedFields {
chunks: Vec<(usize, ArrowColumnChunk)>,
costs: Vec<(usize, Duration)>,
// Kept after chunks so dropping an unobserved JoinHandle result releases
// its encoded buffers before the execution admission.
write_guard: Option<Arc<dyn SstWriteGuard>>,
}
/// Writes Parquet like [`parquet::arrow::AsyncArrowWriter`], but encodes the
/// columns of each row group on up to `parallelism` blocking tasks.
@@ -93,6 +103,12 @@ pub struct ParallelArrowWriter<W> {
encoding: Vec<JoinHandle<Result<EncodedFields>>>,
num_row_groups: usize,
cancellation: Option<CancellationToken>,
/// Bounded writers encode columns concurrently but do not overlap row groups.
working_limit: Option<usize>,
buffered_bytes: usize,
/// Output ownership may also retain execution admission until detached
/// blocking encoders finish after their async writer is cancelled.
write_guard: Option<Arc<dyn SstWriteGuard>>,
}
impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
@@ -141,6 +157,9 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
encoding: Vec::new(),
num_row_groups: 0,
cancellation: None,
working_limit: None,
buffered_bytes: 0,
write_guard: None,
})
}
@@ -149,17 +168,49 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
self
}
pub(crate) fn with_write_guard(mut self, guard: Option<Arc<dyn SstWriteGuard>>) -> Self {
self.write_guard = guard;
self
}
pub(crate) fn with_working_limit(mut self, limit: Option<usize>) -> Self {
self.working_limit = limit;
self
}
pub(crate) fn memory_size(&self) -> usize {
self.buffered_bytes
}
pub(crate) fn flushed_row_groups(&self) -> &[RowGroupMetaData] {
self.file_writer.flushed_row_groups()
}
/// Buffers `batch`, starting to encode each row group once it is full.
pub async fn write(&mut self, batch: &RecordBatch) -> Result<()> {
let mut offset = 0;
while offset < batch.num_rows() {
check_cancelled(self.cancellation.as_ref())?;
let len = (self.max_row_group_rows - self.buffered_rows).min(batch.num_rows() - offset);
self.buffered.push(batch.slice(offset, len));
let slice = batch.slice(offset, len);
if let Some(limit) = self.working_limit {
// Count retained buffers, including dictionary values. Shared buffers may
// be counted more than once; the bounded path is conservative.
self.buffered_bytes = self
.buffered_bytes
.saturating_add(slice.get_array_memory_size());
check_working_memory(self.buffered_bytes, limit)?;
}
self.buffered.push(slice);
self.buffered_rows += len;
offset += len;
if self.buffered_rows == self.max_row_group_rows {
self.encode_buffered().await?;
if self.working_limit.is_some() {
// The second workspace reserved by the caller covers finalization,
// not another raw row group alongside the column encoders.
self.finish_encoding().await?;
}
}
}
Ok(())
@@ -215,7 +266,19 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
let batches: Arc<[RecordBatch]> = mem::take(&mut self.buffered).into();
self.buffered_rows = 0;
let budget = self.working_limit.map(|limit| {
Arc::new(EncodingBudget {
bytes: AtomicUsize::new(self.buffered_bytes),
limit,
})
});
self.buffered_bytes = 0;
let writers = self.factory.create_column_writers(self.num_row_groups)?;
if let Some(budget) = budget.as_ref() {
for writer in &writers {
budget.observe(&mut 0, writer.memory_size())?;
}
}
self.num_row_groups += 1;
// One array produces all leaves of a field, so a field is never split.
@@ -231,8 +294,24 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
let batches = batches.clone();
let schema = self.arrow_schema.clone();
let cancellation = self.cancellation.clone();
self.runtime
.spawn(move || encode_fields(&schema, &batches, fields, cancellation.as_ref()))
let budget = budget.clone();
let write_guard = self.write_guard.clone();
self.runtime.spawn(move || {
let mut result = encode_fields(
&schema,
&batches,
fields,
cancellation.as_ref(),
budget.as_deref(),
);
// A dropped async receiver does not stop a running blocking task.
// Retain admission with returned chunks as well as the input arrays.
drop(batches);
if let Ok(encoded) = &mut result {
encoded.write_guard = write_guard;
}
result
})
})
.collect();
Ok(())
@@ -243,6 +322,7 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
if self.encoding.is_empty() {
return Ok(());
}
let mut guards = Vec::new();
let mut chunks = Vec::with_capacity(self.leaf_fields.len());
let mut tasks = mem::take(&mut self.encoding).into_iter();
while let Some(task) = tasks.next() {
@@ -250,13 +330,18 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
.await
.map_err(|e| ParquetError::External(Box::new(e)))
.and_then(|encoded| encoded);
let (task_chunks, costs) = match encoded {
let EncodedFields {
chunks: task_chunks,
costs,
write_guard,
} = match encoded {
Ok(encoded) => encoded,
Err(error) => {
abort_encoding_tasks(tasks.as_mut_slice()).await;
return Err(error);
}
};
guards.push(write_guard);
chunks.extend(task_chunks);
for (field, cost) in costs {
self.field_costs[field] = cost;
@@ -268,7 +353,12 @@ impl<W: AsyncFileWriter> ParallelArrowWriter<W> {
chunk.append_to_row_group(&mut row_group)?;
}
row_group.close()?;
self.write_buffered_bytes().await
if let Some(limit) = self.working_limit {
check_working_memory(self.file_writer.inner_mut().capacity(), limit)?;
}
let result = self.write_buffered_bytes().await;
drop(guards);
result
}
/// Moves the bytes assembled so far to the async writer.
@@ -330,17 +420,61 @@ fn check_cancelled(cancellation: Option<&CancellationToken>) -> Result<()> {
Ok(())
}
/// Tracks the sum of per-column high-water marks until the entire row group is
/// written. Completed column chunks remain charged while sibling tasks run.
struct EncodingBudget {
bytes: AtomicUsize,
limit: usize,
}
impl EncodingBudget {
fn observe(&self, peak: &mut usize, bytes: usize) -> Result<()> {
if bytes > *peak {
let growth = bytes - *peak;
*peak = bytes;
let previous = self
.bytes
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |old| {
Some(old.saturating_add(growth))
})
.unwrap();
check_working_memory(previous.saturating_add(growth), self.limit)?;
}
Ok(())
}
}
fn check_working_memory(bytes: usize, limit: usize) -> Result<()> {
if bytes > limit {
return Err(ParquetError::External(Box::new(
crate::error::SstWriteMemoryExceededSnafu {
kind: "encoder",
bytes,
limit,
}
.build(),
)));
}
Ok(())
}
/// Encodes `fields` of all `batches` and closes their column writers.
fn encode_fields(
schema: &SchemaRef,
batches: &[RecordBatch],
fields: Vec<FieldWriters>,
cancellation: Option<&CancellationToken>,
budget: Option<&EncodingBudget>,
) -> Result<EncodedFields> {
let mut chunks = Vec::new();
let mut costs = Vec::with_capacity(fields.len());
for (field, mut writers) in fields {
let start = Instant::now();
// Initial writer allocations were charged before any encode task started.
let mut peaks = writers
.iter()
.map(|(_, writer)| writer.memory_size())
.collect::<Vec<_>>();
for batch in batches {
check_cancelled(cancellation)?;
let leaves = compute_leaves(schema.field(field), batch.column(field))?;
@@ -352,18 +486,33 @@ fn encode_fields(
writers.len()
)));
}
for (leaf, (_, writer)) in leaves.iter().zip(writers.iter_mut()) {
for ((leaf, (_, writer)), peak) in leaves.iter().zip(writers.iter_mut()).zip(&mut peaks)
{
check_cancelled(cancellation)?;
writer.write(leaf)?;
if let Some(budget) = budget {
budget.observe(peak, writer.memory_size())?;
}
}
}
for (leaf, writer) in writers {
for ((leaf, writer), mut peak) in writers.into_iter().zip(peaks) {
check_cancelled(cancellation)?;
chunks.push((leaf, writer.close()?));
let chunk = writer.close()?;
if let Some(budget) = budget {
budget.observe(
&mut peak,
usize::try_from(chunk.close().bytes_written).unwrap_or(usize::MAX),
)?;
}
chunks.push((leaf, chunk));
}
costs.push((field, start.elapsed()));
}
Ok((chunks, costs))
Ok(EncodedFields {
chunks,
costs,
write_guard: None,
})
}
#[cfg(test)]
@@ -500,6 +649,87 @@ mod tests {
buf
}
#[tokio::test]
async fn test_bounded_parallel_writer_matches_arrow_writer() {
let steps = [
Step::Write(13),
Step::Write(120),
Step::Flush,
Step::Write(9),
];
let expected = write_serial(&steps, props(64));
for parallelism in [1, 2, 4] {
let mut output = Vec::new();
let mut writer = ParallelArrowWriter::try_new(
&mut output,
schema(),
props(64),
parallelism,
EncodeRuntime::Global,
)
.unwrap()
.with_working_limit(Some(64 * 1024 * 1024));
let mut start = 0;
for step in steps {
match step {
Step::Write(len) => {
writer.write(&batch(start, len)).await.unwrap();
start += len;
assert!(
writer.encoding.is_empty(),
"bounded writes must join row-group encoders"
);
}
Step::Flush => writer.flush().await.unwrap(),
}
}
writer.close().await.unwrap();
assert_eq!(expected, output);
}
}
#[tokio::test]
async fn test_bounded_parallel_writer_checks_buffered_and_encoder_memory() {
for limit in [1, batch(0, 64).get_array_memory_size()] {
let mut output = Vec::new();
let mut writer = ParallelArrowWriter::try_new(
&mut output,
schema(),
props(64),
4,
EncodeRuntime::Global,
)
.unwrap()
.with_working_limit(Some(limit));
let error = writer.write(&batch(0, 64)).await.unwrap_err();
let ParquetError::External(source) = error else {
panic!("Expected a typed memory budget error, got {error:?}");
};
assert!(
matches!(
source.downcast_ref::<crate::error::Error>(),
Some(crate::error::Error::SstWriteMemoryExceeded { .. })
),
"Unexpected budget error: {source:?}"
);
writer.abort().await;
}
}
#[test]
fn test_encoding_budget_retains_finished_column_peaks() {
let budget = EncodingBudget {
bytes: AtomicUsize::new(10),
limit: 30,
};
let mut first = 0;
budget.observe(&mut first, 12).unwrap();
budget.observe(&mut first, 4).unwrap();
assert_eq!(22, budget.bytes.load(Ordering::Relaxed));
let mut second = 0;
assert!(budget.observe(&mut second, 9).is_err());
}
#[tokio::test]
async fn test_parallel_writer_matches_arrow_writer() {
use Step::*;
@@ -572,6 +802,7 @@ mod tests {
&running_batches,
vec![(0, vec![(0, column)])],
None,
None,
)?;
Err(ParquetError::General("later encoding failure".to_string()))
});
@@ -585,7 +816,7 @@ mod tests {
let queued = runtime.spawn_blocking(move || {
queued_started_task.store(true, Ordering::SeqCst);
drop(batches);
Ok((Vec::new(), Vec::new()))
Ok(EncodedFields::default())
});
writer.encoding = vec![failed, running, queued];
+29 -9
View File
@@ -571,23 +571,31 @@ where
let Some(limits) = self.memory.limits else {
return Ok(());
};
if let Some(SstArrowWriter::Serial(writer)) = &mut self.writer {
if let Some(writer) = &mut self.writer {
let (memory_size, row_groups) = match writer {
SstArrowWriter::Serial(writer) => {
(writer.memory_size(), writer.flushed_row_groups())
}
SstArrowWriter::Parallel(writer) => {
(writer.memory_size(), writer.flushed_row_groups())
}
};
ensure!(
writer.memory_size() <= limits.working_bytes,
memory_size <= limits.working_bytes,
crate::error::SstWriteMemoryExceededSnafu {
kind: "encoder",
bytes: writer.memory_size(),
bytes: memory_size,
limit: limits.working_bytes,
}
);
for group in &writer.flushed_row_groups()[self.memory.row_groups..] {
for group in &row_groups[self.memory.row_groups..] {
let file = FileMetaData::new(1, 0, None, None, group.schema_descr_ptr(), None);
// Reuse Parquet's heap estimator; counting the schema per group
// is conservative, including variable-length min/max statistics.
let metadata = ParquetMetaData::new(file, vec![group.clone()]);
self.memory.current = self.memory.current.saturating_add(metadata.memory_size());
}
self.memory.row_groups = writer.flushed_row_groups().len();
self.memory.row_groups = row_groups.len();
}
self.memory
.check(self.memory.completed.saturating_add(self.memory.current))
@@ -955,8 +963,7 @@ where
self.bytes_written.clone(),
);
let schema = maybe_wrap_schema(schema)?;
let arrow_writer = if self.memory.limits.is_none()
&& opts.encode_parallelism > 1
let arrow_writer = if opts.encode_parallelism > 1
&& ParallelArrowWriter::<SizeAwareWriter<F::Writer>>::supports(&writer_props)
{
SstArrowWriter::Parallel(
@@ -968,7 +975,9 @@ where
opts.encode_runtime,
)
.map_err(map_write_error)?
.with_cancellation(self.cancellation.clone()),
.with_cancellation(self.cancellation.clone())
.with_write_guard(self.write_guard.clone())
.with_working_limit(self.memory.limits.map(|limits| limits.working_bytes)),
)
} else {
SstArrowWriter::Serial(
@@ -1007,6 +1016,17 @@ fn map_write_error(error: ParquetError) -> Error {
for source in std::iter::successors(Some(&error as &(dyn StdError + 'static)), |source| {
(*source).source()
}) {
if let Some(Error::SstWriteMemoryExceeded {
kind, bytes, limit, ..
}) = source.downcast_ref::<Error>()
{
return crate::error::SstWriteMemoryExceededSnafu {
kind: *kind,
bytes: *bytes,
limit: *limit,
}
.build();
}
if source.is::<Cancelled>() {
return crate::error::SstWriteCancelledSnafu.build();
}
@@ -1674,7 +1694,7 @@ mod tests {
let queued = runtime.spawn_blocking(move || {
queued_started_task.store(true, Ordering::SeqCst);
drop(queued_batch);
Ok((Vec::new(), Vec::new()))
Ok(crate::sst::parquet::parallel_writer::EncodedFields::default())
});
let SstArrowWriter::Parallel(parallel) = writer
.maybe_init_writer(&encoding_schema, &opts)