fix(mito2): decouple table compaction upload and Arrow budgets (#10607)

* fix(mito2): decouple table compaction upload and Arrow budgets

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* test(mito2): prune redundant table compaction checks

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* fix(mito2): cap GCS compaction objects at 5 TiB

Apply the GCS service limit even when the operator omits its object limit. Keep stricter advertised limits and the multipart part-count limit, and cover all three with geometry tests that perform no uploads.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* test(mito2): require an SST part before its final input batch

Gate the payload of the last source row group on the first Parquet part from its target. A writer that buffers until close can no longer pass the lossless multipart regression.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* refactor(mito2): isolate enterprise buffered uploads

Move the bounded SST and Puffin upload adapter and its regression test behind one gated module declaration. Leave the shared chunk transfer in the Apache-licensed parent and register the new enterprise source in both license lists.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* docs(mito2): describe ObjectStoreWriter bytes as accepted for upload

Bounded uploads stage bytes in a local part buffer before they reach the object store, so output_bytes counts accepted bytes rather than bytes already submitted. The only reader takes the value after a successful close, when both counts agree.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* refactor(mito2): rename the compaction compute estimate

MemoryLimits::compute_bytes returned the estimated working set that admit()
compares against the compute budget, while UploadBudget::compute_bytes holds
that budget. Rename the method to estimate_compute_bytes and name the
admission local accordingly so the estimate and the budget are not read as
the same quantity. The budget field keeps its visibility because source
admission still bounds footer memory by it.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* test(mito2): rename the source-less table compaction fixture

Rename `Fixture::empty` to `Fixture::without_source`. The constructor still creates the scheduler environment, access layer and config and only skips writing the input SST, so the old name suggested a state-less fixture. The new name mirrors `with_source`; both call sites are updated.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* fix(mito2): check the upload object limit inside the bounded writer

Move the object-limit check from the Parquet SST writer into UploadBuffer::write so every caller of the bounded buffer is covered and the remaining-allowance subtraction cannot underflow. Make check_size private; the Puffin adapter keeps its own check and the limit error still surfaces as MultiRegionCompactionResource. Cover writes accepted up to the limit and the rejected next write.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

* docs(mito2): document index writer upload policies

IndexWriteBuffer variants select different object-store writers: the default writer, exact-size parts, or a serial upload buffered through the enterprise adapter. Document each policy and explain that IndexObjectWriter boxes the bounded side because that adapter is returned as an opaque type.

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>

---------

Signed-off-by: Lei, HUANG <ratuthomm@gmail.com>
This commit is contained in:
Lei, HUANG
2026-11-24 15:33:23 +00:00
committed by GitHub
parent 81e60511b5
commit 9ecd84f622
13 changed files with 1359 additions and 204 deletions
+1
View File
@@ -36,6 +36,7 @@ includes = [
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
"src/mito2/src/sst/upload/buffered.rs",
"src/common/function/src/admin/purge_table.rs",
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
"src/common/meta/src/ddl/purge_dropped_table.rs",
+1
View File
@@ -52,6 +52,7 @@ excludes = [
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
"src/mito2/src/sst/upload/buffered.rs",
"src/common/function/src/admin/purge_table.rs",
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
"src/common/meta/src/ddl/purge_dropped_table.rs",
+13 -6
View File
@@ -454,12 +454,12 @@ impl AccessLayer {
// bypass it.
let store = self.object_store.clone();
let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
let puffin_factory = if limits.is_some() {
self.puffin_manager_factory
.clone()
.with_write_buffer_size(write_opts.write_buffer_size.as_bytes() as usize)
let puffin_factory = self.puffin_manager_factory.clone();
#[cfg(feature = "enterprise")]
let puffin_factory = if let Some(limits) = limits {
puffin_factory.with_upload_limits(limits.upload_limits)
} else {
self.puffin_manager_factory.clone()
puffin_factory
};
let indexer_builder = IndexerBuilderImpl {
index_build_inputs: request.index_build_inputs,
@@ -479,7 +479,7 @@ impl AccessLayer {
// TODO(yingwen): If we support other non-fs stores without the write cache, then
// we may have find a way to check whether we need the cleaner.
let cleaner = TempFileCleaner::new(region_id, self.object_store.clone());
let mut writer = ParquetWriter::new_with_object_store(
let writer = ParquetWriter::new_with_object_store(
self.object_store.clone(),
request.metadata,
request.index_config,
@@ -497,6 +497,13 @@ impl AccessLayer {
.with_write_guard(guard)
.with_cancellation(cancellation)
.with_memory_limits(limits);
#[cfg(feature = "enterprise")]
let writer = if let Some(limits) = limits {
writer.with_upload_limits(limits.upload_limits)
} else {
writer
};
let mut writer = writer;
match request.sst_write_format {
FormatType::PrimaryKey => {
writer
+5 -5
View File
@@ -64,10 +64,10 @@ pub struct MultiRegionCompactionPlan {
pub sources: Vec<FileMeta>,
/// Metadata and routing must belong to the same physical-table snapshot.
pub targets: BTreeMap<RegionId, MultiRegionTarget>,
/// Working-set admission budget, including all resident writers and their finish workspace.
/// This bounds managed buffers and estimates codec/index allocations, not process RSS.
/// It must be large enough that the per-buffer share still covers the storage
/// multipart minimum, otherwise the plan is rejected before any output.
/// Total working-set admission budget for computation and all resident uploads.
/// Upload chunks follow the destination backend's limits independently of the Arrow
/// batch limit. The executor reserves uploads before sizing the compute buffers and
/// checks the estimated working set before creating outputs. This is not a process RSS limit.
pub memory_limit: usize,
/// Soft size limit, in bytes, of one output SST. A file rolls over at the next
/// series boundary after it is exceeded, so a single series may stay in one file.
@@ -99,7 +99,7 @@ pub struct MultiRegionCompactionStats {
pub source_store_page_bytes: u64,
pub output_rows: u64,
pub output_bytes: u64,
/// Conservative admission estimate, including reader pages, writers, indexes and finish.
/// Admission estimate for reader pages, encoders, indexes, uploads, and finish workspace.
pub estimated_memory_bytes: u64,
/// Peak retained equal-key group storage (including shared buffer capacities).
pub peak_group_bytes: u64,
+245 -56
View File
@@ -15,17 +15,18 @@ use api::v1::SemanticType;
use datatypes::arrow::datatypes::SchemaRef;
use datatypes::schema::{ColumnEncoding, FulltextBackend};
use index::fulltext_index::create::TantivyFulltextIndexCreator;
use object_store::ObjectStore;
use parquet::arrow::ArrowSchemaConverter;
use parquet::file::metadata::ParquetMetaData;
use snafu::{ResultExt, ensure};
use snafu::{OptionExt, ResultExt, ensure};
use crate::compaction::multi_region::{
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget,
};
use crate::compaction::multi_region::{MultiRegionCompactionPlan, MultiRegionTarget};
use crate::config::{FulltextIndexConfig, MitoConfig};
use crate::error::{IndexOptionsSnafu, MultiRegionCompactionResourceSnafu, Result};
use crate::sst::DEFAULT_WRITE_BUFFER_SIZE;
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;
/// Cap on the rows of one output row group.
@@ -41,9 +42,11 @@ pub(crate) const MAX_ROW_GROUP_SIZE: usize = 1024;
/// separate runtime checks. Neither estimate nor buffer accounting measures RSS.
#[derive(Clone)]
pub(crate) struct MemoryLimits {
pub(crate) batch: usize,
pub(crate) arrow_batch_bytes: usize,
pub(crate) group: usize,
pub(crate) index: usize,
upload_reserved_bytes: usize,
compute_budget: usize,
/// Reuses index allocation only when the optional working set fits admission.
pub(crate) extension_index_memory_limit: Option<usize>,
pub(crate) writer: SstWriteLimits,
@@ -51,27 +54,46 @@ pub(crate) struct MemoryLimits {
}
impl MemoryLimits {
pub(crate) fn new(plan: &MultiRegionCompactionPlan, schema: &SchemaRef) -> Result<Self> {
pub(crate) fn new(
plan: &MultiRegionCompactionPlan,
schema: &SchemaRef,
upload: UploadBudget,
) -> Result<Self> {
let schema = crate::sst::maybe_wrap_schema(schema)?;
let columns = ArrowSchemaConverter::new()
.convert(&schema)
.context(crate::error::WriteParquetSnafu)?
.num_columns();
let batch =
plan.memory_limit / (64 * (plan.sources.len() + plan.targets.len() + BATCH_SIZE + 4));
let targets = plan.targets.len();
let batch_share = 64usize.saturating_mul(
plan.sources
.len()
.saturating_add(targets)
.saturating_add(BATCH_SIZE + 4),
);
let arrow_batch_bytes = upload.compute_bytes / batch_share;
ensure!(
arrow_batch_bytes > 0,
MultiRegionCompactionResourceSnafu {
reason: "No Arrow batch budget after reserving upload memory",
}
);
Ok(Self {
batch,
group: plan.memory_limit / 16,
index: plan.memory_limit / (64 * plan.targets.len()),
arrow_batch_bytes,
group: upload.compute_bytes / 16,
index: upload.compute_bytes / targets / 64,
upload_reserved_bytes: upload.reserved_bytes,
compute_budget: upload.compute_bytes,
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
// also have a nonzero minimum, independent of batch row count.
working_bytes: 2 * 1024 * 1024
+ columns * 128 * 1024
+ batch * (MAX_ROW_GROUP_SIZE / BATCH_SIZE),
metadata_bytes: plan.memory_limit / (8 * plan.targets.len()),
working_bytes: (2usize << 20)
.saturating_add(columns.saturating_mul(128 << 10))
.saturating_add(arrow_batch_bytes * (MAX_ROW_GROUP_SIZE / BATCH_SIZE)),
metadata_bytes: upload.compute_bytes / targets / 8,
upload_limits: upload.limits,
},
estimated: 0,
})
@@ -80,60 +102,67 @@ impl MemoryLimits {
pub(crate) fn admit(
&mut self,
plan: &MultiRegionCompactionPlan,
context: &MultiRegionCompactionContext,
config: &MitoConfig,
footers: &[Arc<ParquetMetaData>],
extension_targets: usize,
) -> Result<()> {
self.check_upload_minimum(context)?;
let mut extra_delta = 0;
for target in plan.targets.values() {
extra_delta = extra_delta.max(extra_delta_encoder_bytes(target)?);
}
self.writer.working_bytes = self.writer.working_bytes.saturating_add(extra_delta);
// Merge assembly can retain exhausted batches until an output batch is full.
let mut bytes = 4_u64
.saturating_mul((plan.sources.len() + BATCH_SIZE + 2) as u64)
.saturating_mul(self.batch as u64)
.saturating_add(6 * self.group as u64);
for footer in footers {
bytes = bytes.saturating_add(reader_bytes(footer));
}
for target in plan.targets.values() {
bytes = bytes.saturating_add(self.target_bytes(target, &context.config)?);
}
let estimate = self.estimate_compute_bytes(plan, config, footers)?;
let upload = self.writer.upload_limits;
ensure!(
bytes <= plan.memory_limit as u64,
estimate <= self.compute_budget as u64,
MultiRegionCompactionResourceSnafu {
reason: format!(
"Reader/writer/index minimum working set needs {bytes} bytes, budget is {}",
plan.memory_limit
"Reader/writer/index minimum working set needs {estimate} bytes, compute budget is {} ({} bytes reserved for {}-byte upload chunks out of {} total)",
self.compute_budget,
self.upload_reserved_bytes,
upload.chunk_bytes,
plan.memory_limit,
),
}
);
// Optional indexes must not turn an admitted data compaction into a
// resource failure. Reserve all resident target states together or skip.
let admission =
admit_extension_indexes(bytes, plan.memory_limit, self.index, extension_targets);
admit_extension_indexes(estimate, self.compute_budget, self.index, extension_targets);
self.extension_index_memory_limit = admission.limit;
self.estimated = admission.estimated;
self.estimated = admission.estimated + self.upload_reserved_bytes as u64;
common_telemetry::debug!(
memory_limit = plan.memory_limit,
compute_budget = self.compute_budget,
arrow_batch_bytes = self.arrow_batch_bytes,
upload_chunk_bytes = upload.chunk_bytes,
upload_max_object_bytes = upload.max_object_bytes,
upload_reserved_bytes = self.upload_reserved_bytes,
estimated_memory_bytes = self.estimated,
"Admitted multi-region compaction working set",
);
Ok(())
}
fn check_upload_minimum(&self, context: &MultiRegionCompactionContext) -> Result<()> {
let minimum = context
.access_layer
.object_store()
.info()
.capability()
.write_multi_min_size
.unwrap_or(0);
ensure!(
self.batch >= minimum && self.batch > 0,
MultiRegionCompactionResourceSnafu {
reason: "Storage multipart minimum exceeds the task buffer budget",
}
);
Ok(())
/// Estimates the compute working set to compare against the compute budget.
fn estimate_compute_bytes(
&self,
plan: &MultiRegionCompactionPlan,
config: &MitoConfig,
footers: &[Arc<ParquetMetaData>],
) -> 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(self.arrow_batch_bytes as u64)
.saturating_add(6 * self.group as u64);
for footer in footers {
bytes = bytes.saturating_add(reader_bytes(footer));
}
for target in plan.targets.values() {
bytes = bytes.saturating_add(self.target_bytes(target, config)?);
}
Ok(bytes)
}
fn target_bytes(&self, target: &MultiRegionTarget, config: &MitoConfig) -> Result<u64> {
@@ -143,15 +172,22 @@ impl MemoryLimits {
.context(crate::error::InvalidMetadataSnafu)?
.len();
// Task/channel allocation plus captured schema and input-map copies.
let control = 8 * 1024
+ 3 * schema_bytes
+ 3 * target.inputs.len() * std::mem::size_of::<crate::sst::file::FileMeta>();
// Encoding/finish workspace, SST and index multipart buffers, result metadata.
let writer = self.writer.working_bytes * 2 + self.batch * 4 + self.writer.metadata_bytes;
let control = (8_u64 << 10)
.saturating_add((schema_bytes as u64).saturating_mul(3))
.saturating_add(
(target.inputs.len() as u64)
.saturating_mul((3 * std::mem::size_of::<crate::sst::file::FileMeta>()) as u64),
);
// A routed batch can be queued while the writer encodes another batch.
// Finish workspace includes the encoded Parquet block handed to the uploader.
let writer = (self.writer.working_bytes as u64)
.saturating_mul(RETAINED_AND_FINISH_SCRATCH_FACTOR)
.saturating_add(2 * self.arrow_batch_bytes as u64)
.saturating_add(self.writer.metadata_bytes as u64);
// Creators are instantiated even in async-index mode. Inverted/skipping
// thresholds are shared within their indexers, fulltext is per column.
Ok((control as u64)
.saturating_add(writer as u64)
Ok(control
.saturating_add(writer)
.saturating_add(4 * self.index as u64)
.saturating_add(self.fulltext_bytes(target, &config.fulltext_index)?))
}
@@ -194,6 +230,136 @@ impl MemoryLimits {
}
}
/// Each serial upload can retain three parts: local assembly, the OpenDAL chunker,
/// and the backend's pending or in-flight part. Both writers can hold parts while
/// Puffin finishes, before Parquet closes.
const UPLOAD_CHUNKS_PER_TARGET: usize = 6;
const LOCAL_CHUNK_BYTES: usize = 256 << 10;
const PUFFIN_COPY_BUFFER_BYTES: usize = 8 << 10;
/// Estimate for two writers' part receipts and completion requests, per part number.
const COMPLETION_BYTES_PER_PART: usize = 512;
#[derive(Clone, Copy)]
pub(crate) struct UploadBudget {
limits: UploadLimits,
reserved_bytes: usize,
pub(crate) compute_bytes: usize,
}
struct UploadGeometry {
min_part_bytes: usize,
max_part_bytes: usize,
max_parts: Option<usize>,
max_object_bytes: u64,
}
impl UploadBudget {
pub(crate) fn new(plan: &MultiRegionCompactionPlan, store: &ObjectStore) -> Result<Self> {
let geometry = UploadGeometry::from_store(store)?;
let targets = plan.targets.len();
let chunk_bytes = geometry.choose_chunk_bytes(plan);
let fixed_bytes =
PUFFIN_COPY_BUFFER_BYTES + COMPLETION_BYTES_PER_PART * geometry.max_parts.unwrap_or(0);
let reserved_bytes = chunk_bytes
.checked_mul(UPLOAD_CHUNKS_PER_TARGET)
.and_then(|bytes| bytes.checked_add(fixed_bytes))
.and_then(|bytes| bytes.checked_mul(targets))
.context(MultiRegionCompactionResourceSnafu {
reason: "Table compaction upload reservation overflow",
})?;
let compute_bytes = plan.memory_limit.checked_sub(reserved_bytes).filter(|bytes| *bytes > 0)
.with_context(|| MultiRegionCompactionResourceSnafu {
reason: format!(
"Upload reservation of {reserved_bytes} bytes for {targets} resident targets with {chunk_bytes}-byte chunks leaves no compute budget (task budget is {})",
plan.memory_limit,
),
})?;
Ok(Self {
limits: geometry.limits(chunk_bytes),
reserved_bytes,
compute_bytes,
})
}
}
impl UploadGeometry {
fn from_store(store: &ObjectStore) -> Result<Self> {
let store_info = store.info();
let scheme = store_info.scheme();
let caps = store_info.capability();
let (max_parts, protocol_part_max, protocol_object_max) = match scheme {
"s3" | "oss" => (Some(10_000), usize::MAX, u64::MAX),
// GCS caps even multipart objects at 5 TiB: https://cloud.google.com/storage/quotas#objects
"gcs" => (Some(10_000), usize::MAX, 5_u64 << 40),
// OpenDAL 0.59 does not advertise Azure's Put Block limit.
"azblob" => (Some(50_000), 4000 << 20, u64::MAX),
"fs" => (None, usize::MAX, u64::MAX),
// Writers that spool a whole object or have their own transfer queues
// need different admission rules (e.g. MySQL and HDFS).
_ => {
return MultiRegionCompactionResourceSnafu {
reason: format!(
"Cannot bound table compaction uploads for storage backend {scheme}"
),
}
.fail();
}
};
let min_part_bytes = caps.write_multi_min_size.unwrap_or(1).max(1);
let max_part_bytes = caps
.write_multi_max_size
.unwrap_or(protocol_part_max)
.min(protocol_part_max);
let max_object_bytes = caps
.write_total_max_size
.map_or(protocol_object_max, |size| {
protocol_object_max.min(size as u64)
});
ensure!(
caps.write
&& caps.write_can_multi
&& min_part_bytes <= max_part_bytes
&& max_object_bytes > 0,
MultiRegionCompactionResourceSnafu {
reason: format!(
"No supported upload chunk size for {scheme}: minimum {min_part_bytes}, maximum {max_part_bytes}, object limit {max_object_bytes}"
),
}
);
Ok(Self {
min_part_bytes,
max_part_bytes,
max_parts,
max_object_bytes,
})
}
fn limits(&self, chunk_bytes: usize) -> UploadLimits {
let max_object_bytes = self.max_parts.map_or(self.max_object_bytes, |parts| {
self.max_object_bytes
.min((chunk_bytes as u64).saturating_mul(parts as u64))
});
UploadLimits {
chunk_bytes,
max_object_bytes,
}
}
fn choose_chunk_bytes(&self, plan: &MultiRegionCompactionPlan) -> usize {
let preferred = self.max_parts.map_or(LOCAL_CHUNK_BYTES, |parts| {
// Leave room for a final part near the soft rollover target. The
// hard upload limit still applies to a long series or large index.
(DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize)
.max(plan.max_output_file_size.div_ceil(parts - 1))
});
// Prefer to spend at most one eighth of the task on part buffers
// unless the backend minimum requires more.
preferred
.min(plan.memory_limit / plan.targets.len() / 8 / UPLOAD_CHUNKS_PER_TARGET)
.clamp(self.min_part_bytes, self.max_part_bytes)
}
}
fn extra_delta_encoder_bytes(target: &MultiRegionTarget) -> Result<usize> {
let mut bytes = 0;
for column in target
@@ -270,7 +436,30 @@ fn admit_extension_indexes(
#[cfg(test)]
mod tests {
use super::{ExtensionIndexAdmission, admit_extension_indexes};
use object_store::ObjectStore;
use object_store::layers::CapabilityOverrideLayer;
use object_store::services::Gcs;
use super::{ExtensionIndexAdmission, UploadGeometry, admit_extension_indexes};
#[rstest::rstest]
#[case::service_limit(1 << 30, None, 5_u64 << 40)]
#[case::advertised_limit(1 << 30, Some(2 << 30), 2 << 30)]
#[case::part_count_limit(5 << 20, None, 10_000 * (5_u64 << 20))]
fn test_gcs_multipart_object_limit(
#[case] chunk_bytes: usize,
#[case] advertised: Option<usize>,
#[case] expected: u64,
) {
let store = ObjectStore::new(Gcs::default().bucket("test"))
.unwrap()
.layer(CapabilityOverrideLayer::new(move |mut caps| {
caps.write_total_max_size = advertised;
caps
}));
let geometry = UploadGeometry::from_store(&store).unwrap();
assert_eq!(expected, geometry.limits(chunk_bytes).max_object_bytes);
}
#[test]
fn test_extension_indexes_do_not_reject_admitted_data() {
@@ -33,7 +33,7 @@ use tokio_util::sync::CancellationToken;
use crate::cache::CacheStrategy;
use crate::compaction::json2::collect_json2_rewrite_plans_from_parquet;
use crate::compaction::multi_region::memory::{BATCH_SIZE, MemoryLimits};
use crate::compaction::multi_region::memory::{BATCH_SIZE, MemoryLimits, UploadBudget};
use crate::compaction::multi_region::{
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, SourceCounters,
};
@@ -88,7 +88,7 @@ impl RoutedBatch {
let batch = take_record_batch(&self.batch, &indices).context(ComputeArrowSnafu)?;
let batch = compact_dictionaries(batch)?;
ensure!(
batch.get_array_memory_size() <= source.limits.batch,
batch.get_array_memory_size() <= source.limits.arrow_batch_bytes,
MultiRegionCompactionResourceSnafu {
reason: "Routed batch exceeds the task buffer budget"
}
@@ -127,6 +127,7 @@ impl SharedSource {
metadata: RegionMetadataRef,
counters: Arc<SourceCounters>,
) -> Result<Arc<Self>> {
let upload = UploadBudget::new(plan, context.access_layer.object_store())?;
let mut common = (*metadata).clone();
common.set_partition_expr(None);
let metadata = Arc::new(common);
@@ -157,9 +158,12 @@ impl SharedSource {
let footer = sst.parquet_metadata();
footer_bytes = footer_bytes.saturating_add(footer.memory_size());
ensure!(
footer_bytes <= plan.memory_limit / 8,
footer_bytes <= upload.compute_bytes / 8,
MultiRegionCompactionResourceSnafu {
reason: "Source footer metadata exceeds the task budget",
reason: format!(
"Source footer metadata needs {footer_bytes} bytes, budget after reserving uploads is {}",
upload.compute_bytes / 8,
),
}
);
footers.push(footer);
@@ -194,7 +198,7 @@ impl SharedSource {
.with_cache(cache.clone())
.with_json2_rewrite_targets(json2_targets.clone())
.build();
let mut limits = MemoryLimits::new(plan, &schema)?;
let mut limits = MemoryLimits::new(plan, &schema, upload)?;
let mut inverted = context.config.inverted_index.clone();
inverted.mem_threshold_on_create =
admitted_index_threshold(inverted.mem_threshold_on_create(), limits.index);
@@ -224,7 +228,7 @@ impl SharedSource {
.collect::<BTreeMap<_, _>>();
limits.admit(
plan,
context,
&context.config,
&footers,
index_plans
.values()
@@ -363,12 +367,12 @@ impl SharedSource {
let batch = compact_dictionaries(batch)?;
let batch_bytes = batch.get_array_memory_size();
ensure!(
batch_bytes <= preparing.limits.batch,
batch_bytes <= preparing.limits.arrow_batch_bytes,
MultiRegionCompactionResourceSnafu {
reason: format!(
"Decoded source batch uses {} bytes, budget is {}",
batch_bytes,
preparing.limits.batch,
preparing.limits.arrow_batch_bytes,
),
}
);
@@ -583,7 +587,7 @@ impl SharedSource {
batch
.get_array_memory_size()
.saturating_add(materialized_bytes)
<= self.limits.batch,
<= self.limits.arrow_batch_bytes,
MultiRegionCompactionResourceSnafu {
reason: "Routing projection exceeds the task buffer budget"
}
+624 -67
View File
@@ -11,6 +11,7 @@
use std::collections::{BTreeMap, HashSet};
use std::num::NonZeroU64;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -33,14 +34,20 @@ use datatypes::value::Value;
use datatypes::vectors::json::array::JsonArray;
use datatypes::vectors::json::json2_physical_data_type;
use futures::TryStreamExt;
use futures::io::{self, AsyncReadExt};
use object_store::layers::CapabilityOverrideLayer;
use object_store::layers::mock::oio::Write as _;
use object_store::layers::mock::{self, MockLayerBuilder, oio};
use partition::expr::col;
use partition::multi_dim::MultiDimPartitionRule;
use puffin::puffin_manager::{PuffinManager, PuffinReader, PuffinWriter};
use rand::{RngCore, SeedableRng, rngs::SmallRng};
use serde_json::json;
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataBuilder};
use store_api::region_request::PathType;
use store_api::storage::RegionId;
use tokio::sync::watch;
use super::*;
use crate::access_layer::{AccessLayer, Metrics, OperationType, SstWriteRequest, WriteType};
@@ -49,10 +56,15 @@ use crate::error::InvalidMultiRegionCompactionSnafu;
use crate::read::FlatSource;
use crate::sst::file::{FileHandle, RegionFileId};
use crate::sst::file_purger::NoopFilePurger;
use crate::sst::index::handler::{IndexKindHandler, IndexKindProvider, PlanContext, PlannedIndex};
use crate::sst::index::CompletedEntry;
use crate::sst::index::handler::{
BuildContext, IndexCreator, IndexKindHandler, IndexKindProvider, PlanContext, PlanEntry,
PlannedIndex,
};
use crate::sst::index::intermediate::IntermediateManager;
use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
use crate::sst::index::puffin_manager::PuffinManagerFactory;
use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinWriter};
use crate::sst::location;
use crate::sst::parquet::WriteOptions;
use crate::sst::parquet::flat_format::{
primary_key_column_index, sequence_column_index, time_index_column_index,
@@ -124,30 +136,8 @@ impl Fixture {
format: FormatType,
batches: impl FnOnce(&RegionMetadataRef) -> Vec<RecordBatch>,
) -> Self {
let env = SchedulerEnv::new().await;
let aux = env.path.path().join("table-index");
let layer = Arc::new(AccessLayer::new(
"table/",
if encoding == PrimaryKeyEncoding::Sparse {
PathType::Data
} else {
PathType::Bare
},
env.access_layer.object_store().clone(),
PuffinManagerFactory::new(&aux, 1024 * 1024, None, None)
.await
.unwrap(),
IntermediateManager::init_fs(aux.to_str().unwrap())
.await
.unwrap(),
));
let mut metadata = sst_region_metadata_with_encoding(encoding);
metadata.region_id = RegionId::new(1, 0);
let metadata = Arc::new(metadata);
let mut config = MitoConfig::default();
config.index.aux_path = aux.display().to_string();
let config = Arc::new(config);
let mut batches = batches(&metadata);
let mut fixture = Self::without_source(sst_region_metadata_with_encoding(encoding)).await;
let mut batches = batches(&fixture.metadata);
batches.sort_by_cached_key(|batch| {
let keys = cast(
batch.column(primary_key_column_index(batch.num_columns())),
@@ -160,18 +150,41 @@ impl Fixture {
.value(0)
.to_vec()
});
let mut fixture = Self {
let info = fixture
.write_source(fixture.metadata.clone(), batches, format)
.await;
fixture.source = file_meta(info, fixture.metadata.region_id);
fixture
}
async fn without_source(mut metadata: RegionMetadata) -> Self {
let env = SchedulerEnv::new().await;
let aux = env.path.path().join("table-index");
let layer = Arc::new(AccessLayer::new(
"table/",
if metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse {
PathType::Data
} else {
PathType::Bare
},
env.access_layer.object_store().clone(),
PuffinManagerFactory::new(&aux, 1024 * 1024, None, None)
.await
.unwrap(),
IntermediateManager::init_fs(aux.to_str().unwrap())
.await
.unwrap(),
));
metadata.region_id = RegionId::new(1, 0);
let mut config = MitoConfig::default();
config.index.aux_path = aux.display().to_string();
Self {
env,
layer,
metadata: metadata.clone(),
metadata: Arc::new(metadata),
source: FileMeta::default(),
config,
};
let info = fixture
.write_source(metadata.clone(), batches, format)
.await;
fixture.source = file_meta(info, metadata.region_id);
fixture
config: Arc::new(config),
}
}
async fn write_source(
@@ -179,6 +192,17 @@ impl Fixture {
metadata: RegionMetadataRef,
batches: Vec<RecordBatch>,
format: FormatType,
) -> SstInfo {
self.write_source_with_options(metadata, batches, format, &WriteOptions::default())
.await
}
async fn write_source_with_options(
&self,
metadata: RegionMetadataRef,
batches: Vec<RecordBatch>,
format: FormatType,
options: &WriteOptions,
) -> SstInfo {
self.layer
.write_sst(
@@ -188,7 +212,7 @@ impl Fixture {
&self.config,
format,
),
&WriteOptions::default(),
options,
&mut Metrics::new(WriteType::Flush),
)
.await
@@ -204,6 +228,10 @@ impl Fixture {
}
fn plan(&self, regions: u32) -> MultiRegionCompactionPlan {
self.plan_with_sources(regions, vec![self.source.clone()])
}
fn plan_with_sources(&self, regions: u32, sources: Vec<FileMeta>) -> MultiRegionCompactionPlan {
let mut targets = BTreeMap::new();
for region in 0..regions {
let id = RegionId::new(1, region);
@@ -218,8 +246,14 @@ impl Fixture {
.as_json_str()
.unwrap(),
));
let mut input = self.source.clone();
input.sequence = NonZeroU64::new(100 + region as u64);
let inputs = sources
.iter()
.cloned()
.map(|mut input| {
input.sequence = NonZeroU64::new(100 + region as u64);
(input.file_id(), input)
})
.collect();
let options = RegionOptions {
append_mode: true,
preserve_row_sequence: true,
@@ -231,7 +265,7 @@ impl Fixture {
MultiRegionTarget {
metadata: Arc::new(metadata),
options,
inputs: [(input.file_id(), input)].into_iter().collect(),
inputs,
},
);
}
@@ -254,7 +288,7 @@ impl Fixture {
);
MultiRegionCompactionPlan {
partition_rule,
sources: vec![self.source.clone()],
sources,
targets,
// Includes the fixed Parquet encoder allocations of every resident
// target, unlike the old run-cache-only budget.
@@ -617,7 +651,6 @@ async fn test_failed_target_never_returns_a_partial_table_result() {
fixture.layer.path_type(),
);
assert!(fixture.layer.object_store().exists(&path).await.unwrap());
assert_spill_cleaned(&fixture.env.path.path().join("spill")).await;
}
#[rstest::rstest]
@@ -681,8 +714,6 @@ async fn test_long_tag_stream_is_lossless_and_insufficient_admission_creates_no_
let output = fixture.compact(plan).await;
assert_eq!(102400, output.stats.output_rows);
assert!(output.stats.estimated_memory_bytes <= 128 * 1024 * 1024);
// The long-tag regression still checks every physical row. There is no
// intermediate IPC path or repeated materialization of all destinations.
let mut ordinal = 0;
for file in output.files.into_values().flatten() {
for batch in fixture.read_output(file, fixture.metadata.clone()).await {
@@ -720,7 +751,6 @@ async fn test_long_tag_stream_is_lossless_and_insufficient_admission_creates_no_
"{error:?}"
);
assert!(protected.files.lock().unwrap().is_empty());
assert_spill_cleaned(&fixture.env.path.path().join("spill")).await;
}
#[tokio::test]
@@ -1767,15 +1797,6 @@ async fn test_streaming_merge_preserves_overlapping_versions_and_field_routing(
for path in source_paths {
assert!(fixture.layer.object_store().exists(&path).await.unwrap());
}
assert_spill_cleaned(&fixture.env.path.path().join("spill")).await;
}
async fn assert_spill_cleaned(path: &std::path::Path) {
// Stronger than cleanup: the streaming merge must never create this directory.
assert!(
!tokio::fs::try_exists(path).await.unwrap(),
"merge spill directory was created"
);
}
struct BlockIndexedSstWrite {
@@ -2000,7 +2021,6 @@ async fn test_interrupted_indexed_worker_cleans_tantivy_files(#[case] fail_sibli
})
.await
.expect("cancelled worker leaked Tantivy intermediate files");
assert_spill_cleaned(&fixture.env.path.path().join("spill")).await;
// Attempt cleanup must not delete sources or protected SSTs owned by the caller.
for id in [fixture.source.file_id(), file] {
let path = crate::sst::location::sst_file_path(
@@ -2025,7 +2045,7 @@ impl SstWriteGuard for CancelBeforeCreate {
}
#[tokio::test]
async fn test_cancelling_a_blocked_writer_preserves_sources_without_merge_spill() {
async fn test_cancelling_a_blocked_writer_preserves_sources() {
let (fixture, plan) = overlapping_fixture().await;
let sources = plan.sources.clone();
let (mut context, _) = fixture.context(None);
@@ -2039,7 +2059,6 @@ async fn test_cancelling_a_blocked_writer_preserves_sources_without_merge_spill(
error,
crate::error::Error::CompactionCancelled { .. }
));
assert_spill_cleaned(&fixture.env.path.path().join("spill")).await;
for file in sources {
let path = crate::sst::location::sst_file_path(
fixture.layer.table_dir(),
@@ -2271,6 +2290,538 @@ async fn test_all_resident_writers_are_admitted_before_creating_outputs() {
assert!(protection.files.lock().unwrap().is_empty());
}
const MIB: usize = 1024 * 1024;
const MULTIPART_CHUNK: usize = 5 * MIB;
const MULTIPART_INPUTS: usize = 8;
const ROWS_PER_INPUT_PER_TARGET: usize = 4096;
const PAYLOAD_BYTES: usize = 640;
const MULTIPART_TAGS: [&str; 2] = ["000", "020"];
#[tokio::test]
async fn test_table_budget_below_legacy_floor_writes_multipart_outputs_losslessly() {
let metadata = build_test_binary_test_region_metadata();
let mut fixture = Fixture::without_source((*metadata).clone()).await;
let row_group_size = 256;
let options = WriteOptions {
row_group_size,
..Default::default()
};
// Each SST has both tags and a disjoint timestamp range: 40 MiB of
// incompressible payload overall, but only 40 KiB of payload per 64 rows.
let mut sources = Vec::new();
for input in 0..MULTIPART_INPUTS {
let info = fixture
.write_source_with_options(
fixture.metadata.clone(),
multipart_input_batches(input),
FormatType::Flat,
&options,
)
.await;
sources.push(info);
}
// The final source row group contains the last batches for the second target.
let tail = Arc::new(InputTailGate::new(
&fixture,
sources.last().unwrap(),
RegionId::new(1, 1),
));
let sources = sources
.into_iter()
.map(|info| file_meta(info, fixture.metadata.region_id))
.collect();
let mut plan = fixture.plan_with_sources(2, sources);
// The old per-Arrow-buffer minimum rejected this even at 1 GiB. Each
// target now gets a separate upload chunk and writes one ~20 MiB SST.
let budget = 512 * MIB;
plan.memory_limit = budget;
plan.max_output_file_size = 32 * MIB;
for target in plan.targets.values_mut() {
target.options.max_row_group_row_count = Some(row_group_size);
}
let targets = plan.targets.clone();
let uploads = install_multipart_backend(&mut fixture, MULTIPART_CHUNK, Some(tail.clone()));
let (mut context, _) = fixture.context(None);
context.index_kind_provider = Some(Arc::new(UploadProbeIndex));
let output = tokio::time::timeout(Duration::from_secs(60), compact_regions(plan, context))
.await
.expect("the target must upload a part before reading its final input group")
.unwrap();
assert!(
tail.requested.load(Ordering::Relaxed),
"input never reached the gated row group"
);
assert!(output.stats.estimated_memory_bytes <= budget as u64);
assert_eq!(targets.len(), output.files.len());
let layer = &fixture.layer;
for (id, target) in targets {
let files = &output.files[&id];
assert_eq!(1, files.len());
let file = &files[0];
let path = location::sst_file_path(layer.table_dir(), file.file_id(), layer.path_type());
uploads.assert_completed(&path, file.file_size);
let path = location::index_file_path(layer.table_dir(), file.index_id(), layer.path_type());
uploads.assert_completed(&path, file.index_file_size);
let puffin = layer
.build_puffin_manager()
.reader(&file.index_id())
.await
.unwrap();
assert!(puffin.metadata().await.unwrap().blobs.iter().any(|blob| {
blob.blob_type == UPLOAD_PROBE_BLOB && blob.length as u64 == UPLOAD_PROBE_BYTES
}));
check_multipart_rows(
fixture
.read_published_output(file.clone(), target.metadata)
.await,
id.region_sequence() as usize,
MULTIPART_INPUTS * ROWS_PER_INPUT_PER_TARGET,
);
}
}
#[rstest::rstest]
#[case::budget_cannot_cover_both_targets(8 * MIB, 92 * MIB)]
#[case::backend_disallows_all_part_sizes(0, 512 * MIB)]
#[tokio::test]
async fn test_multipart_admission_rejects_before_protection_or_write(
#[case] chunk: usize,
#[case] budget: usize,
) {
let mut fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
let mut plan = fixture.plan(2);
plan.memory_limit = budget;
let uploads = install_multipart_backend(&mut fixture, chunk, None);
let (context, protection) = fixture.context(None);
let error = compact_regions(plan, context)
.await
.err()
.expect("must reject before writing");
assert!(
matches!(
error,
crate::error::Error::MultiRegionCompactionResource { .. }
),
"{error:?}"
);
assert!(protection.files.lock().unwrap().is_empty());
assert!(uploads.files.lock().unwrap().is_empty());
}
fn multipart_input_batches(input: usize) -> Vec<RecordBatch> {
let start = input * ROWS_PER_INPUT_PER_TARGET;
let end = start + ROWS_PER_INPUT_PER_TARGET;
MULTIPART_TAGS
.iter()
.enumerate()
.map(|(target, tag)| {
let values = (start..end)
.map(|timestamp| multipart_payload(target, timestamp).to_vec())
.collect::<Vec<_>>();
let batch = new_record_batch_with_binary_values(tag, &values);
let mut columns = batch.columns().to_vec();
let time_index = time_index_column_index(columns.len());
columns[time_index] = Arc::new(TimestampMillisecondArray::from_iter_values(
start as i64..end as i64,
));
RecordBatch::try_new(batch.schema(), columns).unwrap()
})
.collect()
}
fn multipart_payload(target: usize, timestamp: usize) -> [u8; PAYLOAD_BYTES] {
let mut bytes = [0; PAYLOAD_BYTES];
SmallRng::seed_from_u64((timestamp * MULTIPART_TAGS.len() + target) as u64)
.fill_bytes(&mut bytes);
bytes
}
fn check_multipart_rows(batches: Vec<RecordBatch>, target: usize, rows: usize) {
let mut seen = vec![false; rows];
// The input owner keeps physical versions; the other region uses its
// admitted file version (see plan_with_sources).
let expected_sequence = if target == 0 { 1000 } else { 101 };
for batch in batches {
let tags = cast(batch.column_by_name("tag_0").unwrap(), &DataType::Utf8).unwrap();
let tags = tags.as_any().downcast_ref::<StringArray>().unwrap();
let values = cast(batch.column_by_name("field_0").unwrap(), &DataType::Binary).unwrap();
let values = values.as_any().downcast_ref::<BinaryArray>().unwrap();
let timestamps =
crate::read::timestamp_array_to_i64_slice(batch.column_by_name("ts").unwrap());
let sequences = batch
.column(sequence_column_index(batch.num_columns()))
.as_any()
.downcast_ref::<UInt64Array>()
.unwrap();
for (row, &timestamp) in timestamps.iter().enumerate() {
assert_eq!(expected_sequence, sequences.value(row));
assert!(tags.is_valid(row) && tags.value(row) == MULTIPART_TAGS[target]);
let timestamp = timestamp as usize;
assert!(!seen[timestamp], "duplicate timestamp {timestamp}");
seen[timestamp] = true;
assert!(
values.is_valid(row)
&& values.value(row) == &multipart_payload(target, timestamp)[..],
"wrong payload for target {target}, timestamp {timestamp}"
);
}
}
assert!(
seen.into_iter().all(|row| row),
"missing rows in target {target}"
);
}
/// Withholds the payload of the last input row group until its target's SST starts uploading.
struct InputTailGate {
source_path: String,
source_size: usize,
payload_offset: usize,
target_dir: String,
first_part: watch::Sender<bool>,
requested: AtomicBool,
}
impl InputTailGate {
fn new(fixture: &Fixture, source: &SstInfo, target: RegionId) -> Self {
let footer = source.file_metadata.as_ref().unwrap();
let payload = footer
.row_groups()
.last()
.unwrap()
.columns()
.iter()
.find(|column| column.column_path().string() == "field_0")
.unwrap();
let layer = &fixture.layer;
Self {
source_path: location::sst_file_path(
layer.table_dir(),
RegionFileId::new(fixture.metadata.region_id, source.file_id),
layer.path_type(),
),
source_size: source.file_size as usize,
payload_offset: payload.byte_range().0 as usize,
target_dir: location::region_dir_from_table_dir(
layer.table_dir(),
target,
layer.path_type(),
),
first_part: watch::channel(false).0,
requested: AtomicBool::new(false),
}
}
async fn wait_for_part(&self, range: mock::BytesRange) -> mock::Result<()> {
if range
.to_content_range(self.source_size)?
.contains(&self.payload_offset)
{
self.requested.store(true, Ordering::Relaxed);
self.first_part
.subscribe()
.wait_for(|&started| started)
.await
.unwrap();
}
Ok(())
}
}
struct TailReader {
inner: oio::Reader,
gate: Arc<InputTailGate>,
}
impl oio::Read for TailReader {
async fn open(
&self,
range: mock::BytesRange,
) -> mock::Result<(mock::RpRead, Box<dyn oio::ReadStreamDyn>)> {
self.gate.wait_for_part(range).await?;
self.inner.open(range).await
}
async fn read(&self, range: mock::BytesRange) -> mock::Result<(mock::RpRead, mock::Buffer)> {
self.gate.wait_for_part(range).await?;
self.inner.read(range).await
}
}
struct MultipartUploads {
files: Mutex<BTreeMap<String, MultipartUpload>>,
tail: Option<Arc<InputTailGate>>,
}
#[derive(Default)]
struct MultipartUpload {
parts: Vec<u64>,
completed: bool,
}
impl MultipartUploads {
fn assert_completed(&self, path: &str, size: u64) {
let uploads = self.files.lock().unwrap();
let upload = uploads
.get(path)
.unwrap_or_else(|| panic!("no upload for {path}"));
assert!(
upload.completed,
"multipart upload did not complete for {path}"
);
let (last, full) = upload.parts.split_last().unwrap();
assert!(
full.len() >= 2
&& full.iter().all(|&part| part == MULTIPART_CHUNK as u64)
&& (1..=MULTIPART_CHUNK as u64).contains(last),
"wrong multipart sizes for {path}: {:?}",
upload.parts
);
assert_eq!(size, upload.parts.iter().sum::<u64>(), "{path}");
}
}
/// Uses the same OpenDAL chunker and multipart state machine as S3. Only the
/// service's part requests are replaced, appending to an FS writer with no
/// whole-file buffer in the fake backend.
fn install_multipart_backend(
fixture: &mut Fixture,
chunk: usize,
tail: Option<Arc<InputTailGate>>,
) -> Arc<MultipartUploads> {
let mut mock = MockLayerBuilder::default();
if let Some(gate) = tail.clone() {
mock.reader_factory(Arc::new(move |path, _, inner| {
if path == gate.source_path {
Box::new(TailReader {
inner,
gate: gate.clone(),
})
} else {
inner
}
}));
}
let uploads = Arc::new(MultipartUploads {
files: Mutex::default(),
tail,
});
let layer = &fixture.layer;
let store = layer.object_store().clone();
let executor = store.context().executor().clone();
let observed = uploads.clone();
let mock = mock
.writer_factory(Arc::new(move |path, args, inner| {
assert_eq!(1, args.concurrent(), "multipart concurrency for {path}");
let previous = observed
.files
.lock()
.unwrap()
.insert(path.to_string(), MultipartUpload::default());
assert!(previous.is_none(), "opened multiple writers for {path}");
Box::new(oio::MultipartWriter::new(
executor.clone(),
FsMultipartSink {
inner: tokio::sync::Mutex::new(inner),
path: path.to_string(),
uploads: observed.clone(),
},
args.concurrent(),
)) as oio::Writer
}))
.build()
.unwrap();
let store = store
.layer(mock)
.layer(CapabilityOverrideLayer::new(move |mut caps| {
caps.write_multi_min_size = Some(chunk);
caps.write_multi_max_size = Some(chunk);
caps
}));
fixture.layer = Arc::new(AccessLayer::new(
layer.table_dir(),
layer.path_type(),
store,
layer.puffin_manager_factory().clone(),
layer.intermediate_manager().clone(),
));
uploads
}
struct FsMultipartSink {
inner: tokio::sync::Mutex<oio::Writer>,
path: String,
uploads: Arc<MultipartUploads>,
}
impl oio::MultipartWrite for FsMultipartSink {
async fn write_once(&self, _size: u64, body: mock::Buffer) -> mock::Result<mock::Metadata> {
let mut writer = self.inner.lock().await;
writer.write(body).await?;
writer.close().await
}
async fn initiate_part(&self) -> mock::Result<String> {
Ok(self.path.clone())
}
async fn write_part(
&self,
_: &str,
part_number: usize,
size: u64,
body: mock::Buffer,
) -> mock::Result<oio::MultipartPart> {
{
let mut files = self.uploads.files.lock().unwrap();
let parts = &mut files.get_mut(&self.path).unwrap().parts;
assert_eq!(
parts.len(),
part_number,
"out-of-order part for {}",
self.path
);
parts.push(size);
}
if part_number == 0
&& let Some(tail) = &self.uploads.tail
&& self.path.starts_with(&tail.target_dir)
&& self.path.ends_with(".parquet")
{
assert!(
!tail.first_part.send_replace(true),
"multiple SSTs released the same input tail"
);
}
self.inner.lock().await.write(body).await?;
Ok(oio::MultipartPart {
part_number,
size: Some(size),
etag: part_number.to_string(),
checksum: None,
})
}
async fn complete_part(
&self,
_: &str,
_: &[oio::MultipartPart],
) -> mock::Result<mock::Metadata> {
let metadata = self.inner.lock().await.close().await?;
self.uploads
.files
.lock()
.unwrap()
.get_mut(&self.path)
.unwrap()
.completed = true;
Ok(metadata)
}
async fn abort_part(&self, _: &str) -> mock::Result<()> {
self.inner.lock().await.abort().await
}
}
const UPLOAD_PROBE_BLOB: &str = "test.upload-budget";
const UPLOAD_PROBE_BYTES: u64 = (2 * MULTIPART_CHUNK + 123) as u64;
const UPLOAD_PROBE_ENTRY: PlanEntry = PlanEntry {
column_id: 0,
kind: IndexKind::Extension(ExtensionIndexKind::Hll),
format_version: 1,
};
/// An uncompressed streaming blob drives the real Puffin writer across two
/// parts without inflating a built-in index or retaining a large creator state.
#[derive(Debug)]
struct UploadProbeIndex;
impl IndexKindProvider for UploadProbeIndex {
fn handlers(&self) -> Vec<Arc<dyn IndexKindHandler>> {
vec![Arc::new(Self)]
}
}
impl IndexKindHandler for UploadProbeIndex {
fn kinds(&self) -> &[IndexKind] {
&[UPLOAD_PROBE_ENTRY.kind]
}
fn validate(&self, _: &PlanContext<'_>) -> std::result::Result<(), BoxedError> {
Ok(())
}
fn plan(
&self,
_: &PlanContext<'_>,
) -> std::result::Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
Ok(Some(Arc::new(Self)))
}
}
#[async_trait::async_trait]
impl PlannedIndex for UploadProbeIndex {
fn kinds(&self) -> &[IndexKind] {
IndexKindHandler::kinds(self)
}
fn entries(&self) -> &[PlanEntry] {
&[UPLOAD_PROBE_ENTRY]
}
async fn build(
&self,
_: &BuildContext<'_>,
) -> std::result::Result<Option<Box<dyn IndexCreator>>, BoxedError> {
Ok(Some(Box::new(Self)))
}
fn is_current(&self, _: &FileMeta, _: &PlanContext<'_>) -> bool {
false
}
}
#[async_trait::async_trait]
impl IndexCreator for UploadProbeIndex {
async fn update(&mut self, _: &mut crate::read::Batch) -> std::result::Result<(), BoxedError> {
Ok(())
}
async fn update_flat(&mut self, _: &RecordBatch) -> std::result::Result<(), BoxedError> {
Ok(())
}
async fn finish(
&mut self,
writer: &mut SstPuffinWriter,
) -> std::result::Result<Vec<CompletedEntry>, BoxedError> {
writer
.put_blob(
UPLOAD_PROBE_BLOB,
io::repeat(0x5a).take(UPLOAD_PROBE_BYTES),
Default::default(),
Default::default(),
)
.await
.map_err(BoxedError::new)?;
Ok(vec![CompletedEntry {
column_id: Some(UPLOAD_PROBE_ENTRY.column_id),
kind: UPLOAD_PROBE_ENTRY.kind,
format_version: UPLOAD_PROBE_ENTRY.format_version,
}])
}
async fn abort(&mut self) -> std::result::Result<(), BoxedError> {
Ok(())
}
fn memory_usage(&self) -> usize {
0
}
}
#[rstest::rstest]
#[case::sync(crate::config::IndexBuildMode::Sync)]
#[case::async_mode(crate::config::IndexBuildMode::Async)]
@@ -2296,7 +2847,7 @@ async fn test_admission_includes_each_tantivy_creator_even_in_async_mode(
}
#[tokio::test]
async fn test_oversized_equal_key_group_fails_without_partial_outputs_or_spill() {
async fn test_oversized_equal_key_group_fails_without_partial_outputs() {
let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| {
let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 262_144, 0);
let mut columns = batch.columns().to_vec();
@@ -2314,7 +2865,6 @@ async fn test_oversized_equal_key_group_fails_without_partial_outputs_or_spill()
"{error:?}"
);
assert!(protection.files.lock().unwrap().is_empty());
assert_spill_cleaned(&fixture.env.path.path().join("spill")).await;
}
#[tokio::test]
@@ -2323,7 +2873,8 @@ async fn test_target_writer_sizes_row_groups_from_source_size() {
let plan = fixture.plan(1);
let (context, _protection) = fixture.context(None);
let source = new_flat_source_from_record_batches(vec![source_batch(&fixture.metadata, 0, 100)]);
let limits = memory::MemoryLimits::new(&plan, source.schema()).unwrap();
let upload = memory::UploadBudget::new(&plan, context.access_layer.object_store()).unwrap();
let limits = memory::MemoryLimits::new(&plan, source.schema(), upload).unwrap();
// 64 decoded rows of 4 MiB: 32 rows fill the 128 MiB target. The target's `FileMeta` inputs
// describe the narrow fixture rows, which would allow the full cap.
let writer = writer::TargetWriter::new(
@@ -2362,16 +2913,21 @@ async fn test_reader_admission_counts_decoded_values() {
#[rstest::rstest]
#[case::encoder("encoder")]
#[case::metadata("metadata")]
#[case::upload("upload")]
#[tokio::test]
async fn test_limited_writer_fails_instead_of_publishing_over_budget(#[case] kind: &'static str) {
async fn test_limited_writer_fails_instead_of_returning_over_budget_output(
#[case] kind: &'static str,
) {
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
let plan = fixture.plan(1);
let (context, protection) = fixture.context(None);
let source = new_flat_source_from_record_batches(vec![source_batch(&fixture.metadata, 0, 100)]);
let mut limits = memory::MemoryLimits::new(&plan, source.schema()).unwrap();
let upload = memory::UploadBudget::new(&plan, context.access_layer.object_store()).unwrap();
let mut limits = memory::MemoryLimits::new(&plan, source.schema(), upload).unwrap();
match kind {
"encoder" => limits.writer.working_bytes = 1,
"metadata" => limits.writer.metadata_bytes = 1,
"upload" => limits.writer.upload_limits.max_object_bytes = 1,
_ => unreachable!(),
}
let error = writer::TargetWriter::new(
@@ -2386,10 +2942,11 @@ async fn test_limited_writer_fails_instead_of_publishing_over_budget(#[case] kin
.await
.err()
.unwrap();
assert!(
matches!(&error, crate::error::Error::SstWriteMemoryExceeded { kind: actual, .. } if *actual == kind),
"{error:?}"
);
match error {
crate::error::Error::MultiRegionCompactionResource { .. } if kind == "upload" => {}
crate::error::Error::SstWriteMemoryExceeded { kind: actual, .. } if actual == kind => {}
_ => panic!("unexpected {kind} limit error: {error:?}"),
}
assert_eq!(1, protection.files.lock().unwrap().len());
}
@@ -2691,7 +3248,7 @@ async fn test_routing_at_source_batch_budget(#[case] encoding: PrimaryKeyEncodin
.unwrap();
let source = Arc::get_mut(&mut source).unwrap();
let batch = source_batch(&fixture.metadata, 0, 7);
source.limits.batch = batch.get_array_memory_size();
source.limits.arrow_batch_bytes = batch.get_array_memory_size();
let owners = source.row_owners(&batch);
if encoding == PrimaryKeyEncoding::Dense {
assert_eq!(
@@ -142,7 +142,7 @@ impl<'a> TargetWriter<'a> {
pub(super) fn options(&self) -> WriteOptions {
WriteOptions {
write_buffer_size: ReadableSize(self.limits.batch as u64),
write_buffer_size: ReadableSize(self.limits.writer.upload_limits.chunk_bytes as u64),
max_file_size: Some(self.max_file_size),
// Capped so each admitted encoder stays within the task budget; see
// [memory::MAX_ROW_GROUP_SIZE].
+13 -11
View File
@@ -18,7 +18,7 @@ use std::time::Duration;
use async_trait::async_trait;
use common_error::ext::BoxedError;
use object_store::{FuturesAsyncWriter, ObjectStore, Service, ServiceInfo, Servicer};
use object_store::{ObjectStore, Service, ServiceInfo, Servicer};
use puffin::error::{self as puffin_error, Result as PuffinResult};
use puffin::puffin_manager::file_accessor::PuffinFileAccessor;
use puffin::puffin_manager::file_key::{PuffinFileKey, PuffinStorageScope};
@@ -34,10 +34,10 @@ use crate::metrics::{
INDEX_PUFFIN_WRITE_BYTES_TOTAL, INDEX_PUFFIN_WRITE_OP_TOTAL, StagerMetrics,
};
use crate::sst::file::RegionIndexId;
use crate::sst::index::store::{self, InstrumentedStore};
use crate::sst::index::store::{self, IndexObjectWriter, IndexWriteBuffer, InstrumentedStore};
type InstrumentedRangeReader = store::InstrumentedRangeReader<'static>;
type InstrumentedAsyncWrite = store::InstrumentedAsyncWrite<'static, FuturesAsyncWriter>;
type InstrumentedAsyncWrite = store::InstrumentedAsyncWrite<'static, IndexObjectWriter>;
pub type SstPuffinManager =
FsPuffinManager<Arc<BoundedStager<RegionIndexId>>, ObjectStorePuffinFileAccessor>;
@@ -97,8 +97,7 @@ pub struct PuffinManagerFactory {
/// The stager used by the puffin manager.
stager: Arc<BoundedStager<RegionIndexId>>,
/// The size of the write buffer used to create object store.
write_buffer_size: Option<usize>,
write_buffer: IndexWriteBuffer,
backend_scopes: Arc<BackendScopes>,
}
@@ -121,14 +120,18 @@ impl PuffinManagerFactory {
.context(PuffinInitStagerSnafu)?;
Ok(Self {
stager: Arc::new(stager),
write_buffer_size,
write_buffer: write_buffer_size.into(),
backend_scopes: Arc::default(),
})
}
/// Overrides only this task's upload buffers, sharing the existing stager.
pub(crate) fn with_write_buffer_size(mut self, bytes: usize) -> Self {
self.write_buffer_size = Some(bytes);
#[cfg(feature = "enterprise")]
pub(crate) fn with_upload_limits(
mut self,
limits: crate::sst::upload::buffered::UploadLimits,
) -> Self {
self.write_buffer = IndexWriteBuffer::Bounded(limits);
self
}
@@ -138,7 +141,7 @@ impl PuffinManagerFactory {
path_provider: impl FilePathProvider + 'static,
) -> SstPuffinManager {
let scope = self.backend_scopes.get(&store);
let store = InstrumentedStore::new(store).with_write_buffer_size(self.write_buffer_size);
let store = InstrumentedStore::new(store).with_write_buffer(self.write_buffer);
let puffin_file_accessor =
ObjectStorePuffinFileAccessor::new(store, Arc::new(path_provider), scope);
SstPuffinManager::new(self.stager.clone(), puffin_file_accessor)
@@ -157,8 +160,7 @@ impl PuffinManagerFactory {
) -> SstPuffinManager {
let origin = origin.file_accessor();
let accessor = ObjectStorePuffinFileAccessor {
object_store: InstrumentedStore::new(store)
.with_write_buffer_size(self.write_buffer_size),
object_store: InstrumentedStore::new(store).with_write_buffer(self.write_buffer),
path_provider: Arc::new(path_provider),
cache_path_provider: origin.cache_path_provider.clone(),
cache_scope: origin.cache_scope.clone(),
+73 -21
View File
@@ -20,8 +20,10 @@ use std::task::{Context, Poll};
use async_trait::async_trait;
use bytes::{BufMut, Bytes};
use common_base::range_read::{Metadata, RangeReader, SizeAwareRangeReader};
#[cfg(feature = "enterprise")]
use futures::future::Either;
use futures::{AsyncRead, AsyncSeek, AsyncWrite};
use object_store::ObjectStore;
use object_store::{FuturesAsyncWriter, ObjectStore};
use pin_project::pin_project;
use prometheus::IntCounter;
use snafu::ResultExt;
@@ -36,8 +38,34 @@ use crate::error::{OpenDalSnafu, Result};
pub(crate) struct InstrumentedStore {
/// The underlying object store.
object_store: ObjectStore,
/// The size of the write buffer.
write_buffer_size: Option<usize>,
write_buffer: IndexWriteBuffer,
}
/// Upload policy of the Puffin index writer opened by [`InstrumentedStore::writer`].
///
/// Each variant selects a different object-store writer, not only a buffer size.
#[derive(Clone, Copy, Default)]
pub(crate) enum IndexWriteBuffer {
/// Opens the store's default writer: no explicit chunk size or concurrency,
/// so the backend's own limits apply.
#[default]
Default,
/// Requests exact parts of the given size, clamped to the backend's limits,
/// with the store's default concurrency.
Chunk(usize),
/// Requests parts sized by the given limits with one upload at a time, and
/// buffers writes through [`crate::sst::upload::buffered::writer`], which
/// assembles whole parts and rejects writes beyond the object size limit.
#[cfg(feature = "enterprise")]
Bounded(crate::sst::upload::buffered::UploadLimits),
}
impl From<Option<usize>> for IndexWriteBuffer {
fn from(bytes: Option<usize>) -> Self {
bytes
.filter(|&size| size > 0)
.map_or(Self::Default, Self::Chunk)
}
}
impl InstrumentedStore {
@@ -45,7 +73,7 @@ impl InstrumentedStore {
pub fn new(object_store: ObjectStore) -> Self {
Self {
object_store,
write_buffer_size: None,
write_buffer: IndexWriteBuffer::Default,
}
}
@@ -54,8 +82,12 @@ impl InstrumentedStore {
}
/// Set the size of the write buffer.
pub fn with_write_buffer_size(mut self, write_buffer_size: Option<usize>) -> Self {
self.write_buffer_size = write_buffer_size.filter(|&size| size > 0);
pub fn with_write_buffer_size(self, write_buffer_size: Option<usize>) -> Self {
self.with_write_buffer(write_buffer_size.into())
}
pub(crate) fn with_write_buffer(mut self, write_buffer: IndexWriteBuffer) -> Self {
self.write_buffer = write_buffer;
self
}
@@ -112,22 +144,31 @@ impl InstrumentedStore {
write_byte_count: &'a IntCounter,
write_count: &'a IntCounter,
flush_count: &'a IntCounter,
) -> Result<InstrumentedAsyncWrite<'a, object_store::FuturesAsyncWriter>> {
let writer = match self.write_buffer_size {
Some(size) => self
.object_store
.writer_with(path)
.chunk(size)
.await
.context(OpenDalSnafu)?
.into_futures_async_write(),
None => self
.object_store
.writer(path)
.await
.context(OpenDalSnafu)?
.into_futures_async_write(),
) -> Result<InstrumentedAsyncWrite<'a, IndexObjectWriter>> {
let writer = match self.write_buffer {
IndexWriteBuffer::Default => self.object_store.writer(path).await,
IndexWriteBuffer::Chunk(bytes) => {
self.object_store.writer_with(path).chunk(bytes).await
}
#[cfg(feature = "enterprise")]
IndexWriteBuffer::Bounded(limits) => {
self.object_store
.writer_with(path)
.chunk(limits.chunk_bytes)
.concurrent(1)
.await
}
}
.context(OpenDalSnafu)?;
#[cfg(feature = "enterprise")]
let writer: IndexObjectWriter = match self.write_buffer {
IndexWriteBuffer::Bounded(limits) => Either::Right(Box::new(
crate::sst::upload::buffered::writer(writer, limits),
)),
_ => Either::Left(writer.into_futures_async_write()),
};
#[cfg(not(feature = "enterprise"))]
let writer = writer.into_futures_async_write();
Ok(InstrumentedAsyncWrite::new(
writer,
write_byte_count,
@@ -208,6 +249,17 @@ impl<R: AsyncSeek + Unpin + Send> AsyncSeek for InstrumentedAsyncRead<'_, R> {
}
}
/// The [`AsyncWrite`] sink of a Puffin index file.
///
/// The bounded side is boxed because [`crate::sst::upload::buffered::writer`]
/// returns an opaque `impl AsyncWrite`, which keeps that private adapter out of
/// this alias; the plain side stays concrete.
#[cfg(feature = "enterprise")]
pub type IndexObjectWriter = Either<FuturesAsyncWriter, Box<dyn AsyncWrite + Send + Sync + Unpin>>;
/// The [`AsyncWrite`] sink of a Puffin index file.
#[cfg(not(feature = "enterprise"))]
pub type IndexObjectWriter = FuturesAsyncWriter;
/// A wrapper around [`AsyncWrite`] that adds instrumentation for monitoring
#[pin_project]
pub struct InstrumentedAsyncWrite<'a, W> {
+92 -22
View File
@@ -211,6 +211,8 @@ impl<W: AsyncFileWriter> SstArrowWriter<W> {
pub(crate) struct SstWriteLimits {
pub(crate) working_bytes: usize,
pub(crate) metadata_bytes: usize,
#[cfg(feature = "enterprise")]
pub(crate) upload_limits: upload::buffered::UploadLimits,
}
/// Tracks retained footer memory across rolled files as well as the current file.
@@ -307,12 +309,15 @@ pub trait WriterFactory {
}
/// Bridges an OpenDAL [`Writer`] with Parquet's [`AsyncFileWriter`] and tracks
/// the number of bytes successfully submitted to the object store.
/// the number of bytes accepted for upload. Bounded uploads stage bytes in a
/// local part buffer before submitting them to the object store.
pub struct ObjectStoreWriter {
inner: Writer,
output_bytes: u64,
write_buffer_size: usize,
cancellation: Option<CancellationToken>,
#[cfg(feature = "enterprise")]
buffered_upload: Option<upload::buffered::UploadBuffer>,
}
impl ObjectStoreWriter {
@@ -326,6 +331,8 @@ impl ObjectStoreWriter {
output_bytes: 0,
write_buffer_size,
cancellation,
#[cfg(feature = "enterprise")]
buffered_upload: None,
}
}
@@ -336,24 +343,30 @@ impl ObjectStoreWriter {
pub(crate) fn into_inner(self) -> Writer {
self.inner
}
async fn write_bytes(&mut self, bytes: Bytes) -> parquet::errors::Result<u64> {
#[cfg(feature = "enterprise")]
if let Some(buffer) = &mut self.buffered_upload {
return buffer
.write(&mut self.inner, bytes, self.cancellation.as_ref())
.await
.map_err(map_buffered_upload_error);
}
upload::write(
&mut self.inner,
bytes.into(),
self.write_buffer_size,
self.cancellation.as_ref(),
)
.await
.map_err(map_upload_error)
}
}
impl AsyncFileWriter for ObjectStoreWriter {
fn write(&mut self, bytes: Bytes) -> BoxFuture<'_, parquet::errors::Result<()>> {
Box::pin(async move {
let written = upload::write(
&mut self.inner,
bytes.into(),
self.write_buffer_size,
self.cancellation.as_ref(),
)
.await
.map_err(|error| match error {
UploadError::Cancelled => ParquetError::External(Box::new(Cancelled)),
UploadError::Read { source } | UploadError::Write { source } => {
ParquetError::External(Box::new(source))
}
})?;
let written = self.write_bytes(bytes).await?;
self.output_bytes += written;
Ok(())
})
@@ -361,6 +374,13 @@ impl AsyncFileWriter for ObjectStoreWriter {
fn complete(&mut self) -> BoxFuture<'_, parquet::errors::Result<()>> {
Box::pin(async move {
#[cfg(feature = "enterprise")]
if let Some(buffer) = &mut self.buffered_upload {
buffer
.write_tail(&mut self.inner)
.await
.map_err(|error| ParquetError::External(Box::new(error)))?;
}
self.inner
.close()
.await
@@ -370,9 +390,30 @@ impl AsyncFileWriter for ObjectStoreWriter {
}
}
fn map_upload_error(error: UploadError) -> ParquetError {
match error {
UploadError::Cancelled => ParquetError::External(Box::new(Cancelled)),
UploadError::Read { source } | UploadError::Write { source } => {
ParquetError::External(Box::new(source))
}
}
}
#[cfg(feature = "enterprise")]
fn map_buffered_upload_error(error: upload::buffered::BufferedWriteError) -> ParquetError {
match error {
upload::buffered::BufferedWriteError::ObjectLimit(error) => {
ParquetError::External(Box::new(error))
}
upload::buffered::BufferedWriteError::Upload(error) => map_upload_error(error),
}
}
pub struct ObjectStoreWriterFactory {
object_store: ObjectStore,
concurrency: usize,
#[cfg(feature = "enterprise")]
upload_limits: Option<upload::buffered::UploadLimits>,
}
impl WriterFactory for ObjectStoreWriterFactory {
@@ -384,12 +425,25 @@ impl WriterFactory for ObjectStoreWriterFactory {
write_buffer_size: usize,
cancellation: Option<&CancellationToken>,
) -> Result<Self::Writer> {
#[cfg(feature = "enterprise")]
let write_buffer_size = self
.upload_limits
.map_or(write_buffer_size, |limits| limits.chunk_bytes);
self.object_store
.writer_with(file_path)
.chunk(write_buffer_size)
.concurrent(self.concurrency)
.await
.map(|writer| ObjectStoreWriter::new(writer, write_buffer_size, cancellation.cloned()))
.map(|writer| {
let writer =
ObjectStoreWriter::new(writer, write_buffer_size, cancellation.cloned());
#[cfg(feature = "enterprise")]
let writer = ObjectStoreWriter {
buffered_upload: self.upload_limits.map(upload::buffered::UploadBuffer::new),
..writer
};
writer
})
.context(OpenDalSnafu)
}
@@ -408,6 +462,14 @@ where
self
}
#[cfg(feature = "enterprise")]
pub(crate) fn with_upload_limits(mut self, limits: upload::buffered::UploadLimits) -> Self {
self.writer_factory.upload_limits = Some(limits);
// Upload admission accounts for the serial OpenDAL writer.
self.writer_factory.concurrency = 1;
self
}
pub async fn new_with_object_store(
object_store: ObjectStore,
metadata: RegionMetadataRef,
@@ -420,6 +482,8 @@ where
ObjectStoreWriterFactory {
object_store,
concurrency: DEFAULT_WRITE_CONCURRENCY,
#[cfg(feature = "enterprise")]
upload_limits: None,
},
metadata,
index_config,
@@ -940,15 +1004,21 @@ where
/// Keeps cancellation inside the SST write error contract, including nested encoder errors.
fn map_write_error(error: ParquetError) -> Error {
let cancelled = std::iter::successors(Some(&error as &(dyn StdError + 'static)), |source| {
for source in std::iter::successors(Some(&error as &(dyn StdError + 'static)), |source| {
(*source).source()
})
.any(|source| source.is::<Cancelled>());
if cancelled {
crate::error::SstWriteCancelledSnafu.build()
} else {
WriteParquetSnafu.into_error(error)
}) {
if source.is::<Cancelled>() {
return crate::error::SstWriteCancelledSnafu.build();
}
#[cfg(feature = "enterprise")]
if let Some(error) = source.downcast_ref::<upload::buffered::UploadObjectLimit>() {
return crate::error::MultiRegionCompactionResourceSnafu {
reason: error.to_string(),
}
.build();
}
}
WriteParquetSnafu.into_error(error)
}
#[derive(Default)]
+19 -6
View File
@@ -14,6 +14,9 @@
//! Cooperative byte transfer for SST uploads. Callers own close, abort, and file cleanup.
#[cfg(feature = "enterprise")]
pub(crate) mod buffered;
use futures::{Stream, StreamExt};
use object_store::{Buffer, Error as ObjectStoreError, Result as ObjectStoreResult, Writer};
use snafu::Snafu;
@@ -63,23 +66,33 @@ pub(crate) async fn write(
write_buffer_size: usize,
cancellation: Option<&CancellationToken>,
) -> Result<u64, UploadError> {
let len = bytes.len() as u64;
// Keep each slice nonempty even when the configured size is zero.
let write_buffer_size = write_buffer_size.max(1);
while !bytes.is_empty() {
let chunks = std::iter::from_fn(|| {
(!bytes.is_empty()).then(|| bytes.split_to(bytes.len().min(write_buffer_size.max(1))))
});
write_chunks(writer, chunks, cancellation).await
}
async fn write_chunks(
writer: &mut Writer,
chunks: impl Iterator<Item = Buffer>,
cancellation: Option<&CancellationToken>,
) -> Result<u64, UploadError> {
let mut written = 0;
for chunk in chunks {
if cancellation.is_some_and(CancellationToken::is_cancelled) {
return Err(UploadError::Cancelled);
}
let chunk = bytes.split_to(bytes.len().min(write_buffer_size));
let len = chunk.len() as u64;
writer
.write(chunk)
.await
.map_err(|source| UploadError::Write { source })?;
written += len;
}
if cancellation.is_some_and(CancellationToken::is_cancelled) {
return Err(UploadError::Cancelled);
}
Ok(len)
Ok(written)
}
#[cfg(test)]
+259
View File
@@ -0,0 +1,259 @@
// 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 multipart uploads for table compaction SSTs and their Puffin indexes.
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll, ready};
use bytes::{Buf, Bytes, BytesMut};
use futures::{AsyncWrite, Sink, SinkExt};
use object_store::{Buffer, Result as ObjectStoreResult, Writer};
use snafu::Snafu;
use tokio_util::sync::CancellationToken;
use crate::sst::upload::{self, UploadError};
#[derive(Debug, Snafu)]
#[snafu(display("Upload exceeds the backend object limit of {limit} bytes"))]
pub(crate) struct UploadObjectLimit {
pub(crate) limit: u64,
}
/// Part and object limits for the bounded, serial upload path.
#[derive(Clone, Copy)]
pub(crate) struct UploadLimits {
pub(crate) chunk_bytes: usize,
pub(crate) max_object_bytes: u64,
}
/// Owns at most one part while assembling bytes from encoder blocks or index blobs.
/// Sending whole owned parts avoids retaining a large producer allocation or a
/// queue of small fragments in OpenDAL. Only the final part may be short.
/// Both write paths check the remaining object allowance before buffering bytes.
pub(crate) struct UploadBuffer {
limits: UploadLimits,
pending: BytesMut,
object_bytes: u64,
}
/// A bounded write stopped at the object limit or failed in the store writer.
#[derive(Debug)]
pub(crate) enum BufferedWriteError {
ObjectLimit(UploadObjectLimit),
Upload(UploadError),
}
impl UploadBuffer {
pub(crate) fn new(limits: UploadLimits) -> Self {
Self {
limits,
pending: BytesMut::new(),
object_bytes: 0,
}
}
fn check_size(&self, bytes: usize) -> Result<(), UploadObjectLimit> {
if bytes as u64 > self.limits.max_object_bytes - self.object_bytes {
return Err(UploadObjectLimit {
limit: self.limits.max_object_bytes,
});
}
Ok(())
}
fn append(&mut self, bytes: &[u8]) -> usize {
let len = bytes
.len()
.min(self.limits.chunk_bytes - self.pending.len());
if len > 0 {
if self.pending.capacity() == 0 {
self.pending = BytesMut::with_capacity(self.limits.chunk_bytes);
}
self.pending.extend_from_slice(&bytes[..len]);
self.object_bytes += len as u64;
}
len
}
fn is_full(&self) -> bool {
self.pending.len() == self.limits.chunk_bytes
}
fn take_part(&mut self) -> Buffer {
std::mem::take(&mut self.pending).freeze().into()
}
pub(crate) async fn write(
&mut self,
writer: &mut Writer,
mut bytes: Bytes,
cancellation: Option<&CancellationToken>,
) -> Result<u64, BufferedWriteError> {
self.check_size(bytes.len())
.map_err(BufferedWriteError::ObjectLimit)?;
let len = bytes.len() as u64;
let parts = std::iter::from_fn(|| {
let appended = self.append(&bytes);
bytes.advance(appended);
self.is_full().then(|| self.take_part())
});
upload::write_chunks(writer, parts, cancellation)
.await
.map_err(BufferedWriteError::Upload)?;
Ok(len)
}
pub(crate) async fn write_tail(&mut self, writer: &mut Writer) -> ObjectStoreResult<()> {
if !self.pending.is_empty() {
writer.write(self.take_part()).await?;
}
Ok(())
}
}
/// Coalesces writes across blob flushes until a full part or the end of the object.
pub(crate) fn writer(
writer: Writer,
limits: UploadLimits,
) -> impl AsyncWrite + Send + Sync + Unpin {
BufferedUploadWriter {
sink: writer.into_sink().sink_map_err(io::Error::other),
buffer: UploadBuffer::new(limits),
}
}
struct BufferedUploadWriter<S> {
sink: S,
buffer: UploadBuffer,
}
impl<S: Sink<Buffer, Error = io::Error> + Unpin> BufferedUploadWriter<S> {
fn poll_send_part(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(Pin::new(&mut self.sink).poll_ready(cx))?;
Poll::Ready(Pin::new(&mut self.sink).start_send(self.buffer.take_part()))
}
}
impl<S: Sink<Buffer, Error = io::Error> + Unpin> AsyncWrite for BufferedUploadWriter<S> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bytes: &[u8],
) -> Poll<io::Result<usize>> {
let writer = self.get_mut();
writer
.buffer
.check_size(bytes.len())
.map_err(io::Error::other)?;
if writer.buffer.is_full() {
ready!(writer.poll_send_part(cx))?;
}
// The sink can retain the submitted part. Drain it into OpenDAL before
// allocating the next assembly buffer so admission covers both states.
ready!(Pin::new(&mut writer.sink).poll_ready(cx))?;
Poll::Ready(Ok(writer.buffer.append(bytes)))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let writer = self.get_mut();
// A blob flush must not fragment the upload queue. Flush complete parts;
// close is the file boundary and submits the remaining short part.
if writer.buffer.is_full() {
ready!(writer.poll_send_part(cx))?;
}
Pin::new(&mut writer.sink).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let writer = self.get_mut();
if !writer.buffer.pending.is_empty() {
ready!(writer.poll_send_part(cx))?;
}
Pin::new(&mut writer.sink).poll_close(cx)
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use bytes::Bytes;
use futures::io::AsyncWriteExt;
use object_store::ObjectStore;
use object_store::layers::mock::{MockLayerBuilder, ObservedWriter, WriterObservations};
use object_store::services::Memory;
use super::*;
#[tokio::test]
async fn test_buffered_upload_coalesces_blob_flushes_and_limits_object_size() {
let observations = Arc::new(Mutex::new(WriterObservations::default()));
let observer = observations.clone();
let layer = MockLayerBuilder::default()
.writer_factory(Arc::new(move |_, _, inner| {
Box::new(ObservedWriter::new(inner, observer.clone()))
}))
.build()
.unwrap();
let store = ObjectStore::new(Memory::default()).unwrap().layer(layer);
// Observe adapter boundaries without OpenDAL coalescing them for the test.
let mut writer = writer(
store.writer("index").await.unwrap(),
UploadLimits {
chunk_bytes: 4,
max_object_bytes: 9,
},
);
for byte in b"abcdefghi" {
writer.write_all(std::slice::from_ref(byte)).await.unwrap();
writer.flush().await.unwrap();
}
let error = writer.write_all(b"j").await.unwrap_err();
assert!(error.get_ref().unwrap().is::<UploadObjectLimit>());
writer.close().await.unwrap();
assert_eq!(vec![4, 4, 1], observations.lock().unwrap().write_sizes);
assert_eq!(
b"abcdefghi",
store.read("index").await.unwrap().to_bytes().as_ref()
);
}
#[tokio::test]
async fn test_upload_buffer_accepts_the_object_limit_and_rejects_more() {
let store = ObjectStore::new(Memory::default()).unwrap();
let mut buffer = UploadBuffer::new(UploadLimits {
chunk_bytes: 4,
max_object_bytes: 5,
});
let mut writer = store.writer("sst").await.unwrap();
buffer
.write(&mut writer, Bytes::from_static(b"abcd"), None)
.await
.unwrap();
buffer
.write(&mut writer, Bytes::from_static(b"e"), None)
.await
.unwrap();
let error = buffer
.write(&mut writer, Bytes::from_static(b"f"), None)
.await
.unwrap_err();
assert!(matches!(error, BufferedWriteError::ObjectLimit(_)));
buffer.write_tail(&mut writer).await.unwrap();
writer.close().await.unwrap();
assert_eq!(
b"abcde",
store.read("sst").await.unwrap().to_bytes().as_ref()
);
}
}