mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
feat(mito2): read per-row sequences and carry partition expressions in cursors
The engine can now serve an exact (C, H] read of a creator's rows: files are selected by the cursor slices whose partition expression may hold their rows, each row is compared against the slice its own expression selects, and a file's substituted cut hides the rows a substitution produced while reporting their time ranges. The sequence-domain edit boundary is gone; substituted rows are the single statement about rewritten numbering. Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -688,6 +688,29 @@ fn known_max_input_sequence(inputs: &[FileHandle]) -> Option<NonZeroU64> {
|
||||
crate::sst::file::known_max_input_sequence(inputs.iter().map(FileHandle::meta_ref))
|
||||
}
|
||||
|
||||
/// Computes the output's `substituted_up_to` bound from the inputs and their footer facts.
|
||||
///
|
||||
/// `legacy_overrides` reports, per input, whether the footer proves the `__sequence` column is
|
||||
/// all zero (`need_override_sequence`, from the compaction reader), or `None` when the input is
|
||||
/// gone (`compaction/reader.rs`). A gone input has no row in the output, so it contributes
|
||||
/// neither rows nor a substituted constant: taking its handle bound anyway would state a cut
|
||||
/// that hides live rows of the inputs that were merged.
|
||||
fn known_substituted_up_to(
|
||||
region_id: RegionId,
|
||||
inputs: &[FileHandle],
|
||||
legacy_overrides: &[Option<bool>],
|
||||
) -> Option<SequenceNumber> {
|
||||
crate::sst::file::substituted_up_to_after_merge(
|
||||
region_id,
|
||||
inputs
|
||||
.iter()
|
||||
.zip(legacy_overrides)
|
||||
.filter_map(|(file, footer_all_zero)| {
|
||||
footer_all_zero.map(|all_zero| (file.meta_ref(), all_zero))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whole-input summaries require a complete output without file rollover.
|
||||
fn can_reuse_output_inputs(output: &CompactionOutput, has_rollover: bool) -> bool {
|
||||
!has_rollover && output.output_time_range.is_none()
|
||||
@@ -838,16 +861,24 @@ impl DefaultSstMerger {
|
||||
.with_puffin_metadata_cache(context.cache_manager.puffin_metadata_cache().cloned()),
|
||||
can_merge_inputs,
|
||||
});
|
||||
let (source, row_group_size) = tokio::select! {
|
||||
let (reader, row_group_size, legacy_overrides) = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return error::CompactionCancelledSnafu.fail(),
|
||||
source = builder.build_flat_sst_reader_and_row_group_size(write_opts.row_group_size) => source?,
|
||||
built = builder.build_flat_sst_reader_and_row_group_size(write_opts.row_group_size) => built?,
|
||||
};
|
||||
let write_opts = WriteOptions {
|
||||
row_group_size,
|
||||
..write_opts
|
||||
};
|
||||
let source = spawn_merge(source);
|
||||
let source = spawn_merge(reader);
|
||||
// The reader substitutes a file-level constant for the rows of a foreign input and of a
|
||||
// local untrusted input whose footer proves an all-zero column
|
||||
// (`sst/parquet/reader.rs`), so the merged column may carry numbers this region never
|
||||
// allocated up to that constant. `legacy_overrides` is that footer fact per input
|
||||
// (`None` for an input that is gone, which contributes neither rows nor a constant);
|
||||
// `substituted_up_to` also inherits the bound every input already carried.
|
||||
let substituted_up_to =
|
||||
known_substituted_up_to(region_id, &output.inputs, &legacy_overrides);
|
||||
|
||||
let mut metrics = Metrics::new(WriteType::Compaction);
|
||||
let region_metadata = context.region_metadata.clone();
|
||||
@@ -917,6 +948,7 @@ impl DefaultSstMerger {
|
||||
primary_key_min,
|
||||
primary_key_max,
|
||||
preserve_row_sequence: sequence_metadata.exact_sequence_trusted,
|
||||
substituted_up_to,
|
||||
format: sst_info.format.clone(),
|
||||
})
|
||||
})
|
||||
@@ -1678,6 +1710,55 @@ mod tests {
|
||||
assert_eq!(None, known_max_input_sequence(&[]));
|
||||
}
|
||||
|
||||
/// A gone input has no row in the output, so it states no substituted constant of its own:
|
||||
/// its handle bound belongs to bytes the merge never read. Inheriting it would raise the
|
||||
/// output's cut above live rows of the inputs that *were* merged, and a physical-sequence
|
||||
/// read would then hide them for good.
|
||||
#[test]
|
||||
fn test_known_substituted_up_to_skips_gone_inputs() {
|
||||
let target = RegionId::new(1, 1);
|
||||
let foreign = new_file_handle(FileMeta {
|
||||
region_id: RegionId::new(1, 2),
|
||||
sequence: NonZeroU64::new(9),
|
||||
preserve_row_sequence: true,
|
||||
..dummy_file_meta()
|
||||
});
|
||||
// The local input keeps its own numbers, so it states no constant itself.
|
||||
let local = new_file_handle(FileMeta {
|
||||
region_id: target,
|
||||
sequence: NonZeroU64::new(3),
|
||||
preserve_row_sequence: true,
|
||||
..dummy_file_meta()
|
||||
});
|
||||
let inputs = [foreign, local];
|
||||
|
||||
// Both inputs present: the foreign one is substituted at its handle bound, which the
|
||||
// handle does not write into the output, so the output has to state it.
|
||||
assert_eq!(
|
||||
Some(9),
|
||||
known_substituted_up_to(target, &inputs, &[Some(false), Some(false)])
|
||||
);
|
||||
// The foreign input is gone: its rows never reach the output, so nothing is substituted
|
||||
// and the output states no bound instead of the `9` that would hide the local row at 3.
|
||||
assert_eq!(
|
||||
None,
|
||||
known_substituted_up_to(target, &inputs, &[None, Some(false)])
|
||||
);
|
||||
// An input that is present and carries an inherited bound still contributes it, so the
|
||||
// skip above is about gone inputs and not about the legacy footer fact.
|
||||
let inherited = new_file_handle(FileMeta {
|
||||
region_id: target,
|
||||
sequence: NonZeroU64::new(3),
|
||||
preserve_row_sequence: true,
|
||||
substituted_up_to: Some(12),
|
||||
..dummy_file_meta()
|
||||
});
|
||||
assert_eq!(
|
||||
Some(12),
|
||||
known_substituted_up_to(target, &[inherited], &[Some(false)])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_output_sequence_metadata_preserves_trust_and_unknown_bounds() {
|
||||
let mut region = new_test_compaction_region().await;
|
||||
@@ -1911,7 +1992,7 @@ mod tests {
|
||||
} else {
|
||||
deletes.clone()
|
||||
});
|
||||
let mut reader = CompactionSstReaderBuilder {
|
||||
let (mut reader, _) = CompactionSstReaderBuilder {
|
||||
metadata: compaction_region.region_metadata.clone(),
|
||||
sst_layer: region.access_layer.clone(),
|
||||
cache: engine.cache_manager(),
|
||||
@@ -2032,7 +2113,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(1, files.len());
|
||||
let outputs: Vec<_> = files.into_iter().map(new_file_handle).collect();
|
||||
let mut reader = CompactionSstReaderBuilder {
|
||||
let (mut reader, _) = CompactionSstReaderBuilder {
|
||||
metadata: version.metadata.clone(),
|
||||
sst_layer: region.access_layer.clone(),
|
||||
cache: Arc::new(CacheManager::default()),
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
// either express or implied.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
@@ -49,7 +49,7 @@ use crate::read::flat_merge::FlatMergeReader;
|
||||
use crate::read::flat_projection::FlatProjectionMapper;
|
||||
use crate::read::read_columns::ReadColumns;
|
||||
use crate::read::{BoxedRecordBatchStream, timestamp_array_to_i64_slice};
|
||||
use crate::sst::file::{FileHandle, FileMeta};
|
||||
use crate::sst::file::{FileHandle, FileMeta, RegionFileId, substituted_row_constant};
|
||||
use crate::sst::file_purger::NoopFilePurger;
|
||||
use crate::sst::index::IndexBuildType;
|
||||
use crate::sst::index::handler::PlanContext;
|
||||
@@ -102,7 +102,10 @@ pub(crate) struct SharedSource {
|
||||
layer: AccessLayerRef,
|
||||
cache: CacheStrategy,
|
||||
sources: Vec<FileMeta>,
|
||||
legacy_overrides: Vec<bool>,
|
||||
/// Per source file, whether its footer proves that every `__sequence` statistic is 0
|
||||
/// (`need_override_sequence`). Keyed by the cross-region file id so the per-target writers
|
||||
/// can state the same fact the merge reader applies row by row.
|
||||
legacy_overrides: HashMap<RegionFileId, bool>,
|
||||
expected_rows: Vec<i64>,
|
||||
targets: BTreeMap<RegionId, MultiRegionTarget>,
|
||||
metadata: RegionMetadataRef,
|
||||
@@ -166,9 +169,11 @@ impl SharedSource {
|
||||
);
|
||||
footers.push(footer);
|
||||
}
|
||||
let legacy_overrides = footers
|
||||
let legacy_overrides: HashMap<RegionFileId, bool> = plan
|
||||
.sources
|
||||
.iter()
|
||||
.map(|footer| need_override_sequence(footer))
|
||||
.map(|file| file.file_id())
|
||||
.zip(footers.iter().map(|footer| need_override_sequence(footer)))
|
||||
.collect();
|
||||
let expected_rows = footers
|
||||
.iter()
|
||||
@@ -298,6 +303,17 @@ impl SharedSource {
|
||||
pub(crate) fn schema(&self) -> SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
|
||||
/// Returns whether the footer of `file_id` proves that every `__sequence` statistic is 0
|
||||
/// (`need_override_sequence`). An unknown file answers `false`: a footer without the
|
||||
/// statistic is never "all zero".
|
||||
pub(crate) fn footer_all_zero(&self, file_id: RegionFileId) -> bool {
|
||||
self.legacy_overrides
|
||||
.get(&file_id)
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn peak_group_bytes(&self) -> u64 {
|
||||
self.peak_group_bytes.load(Ordering::Relaxed)
|
||||
}
|
||||
@@ -492,18 +508,14 @@ impl SharedSource {
|
||||
reason: "Invalid sequence column",
|
||||
})?;
|
||||
let source = &self.sources[index];
|
||||
let footer_all_zero = self.footer_all_zero(source.file_id());
|
||||
let sequences = owners.iter().enumerate().map(|(row, region)| {
|
||||
let input = &self.targets[region].inputs[&source.file_id()];
|
||||
if input.region_id != *region
|
||||
|| (!input.preserve_row_sequence && self.legacy_overrides[index])
|
||||
{
|
||||
input
|
||||
.sequence
|
||||
.map(|value| value.get())
|
||||
.unwrap_or_else(|| physical.value(row))
|
||||
} else {
|
||||
physical.value(row)
|
||||
}
|
||||
// The two substituting branches of the shared reader, applied to the routed rows:
|
||||
// a foreign input and a local untrusted input whose footer is all-zero become the
|
||||
// input's file-level constant.
|
||||
substituted_row_constant(input, *region, footer_all_zero)
|
||||
.unwrap_or_else(|| physical.value(row))
|
||||
});
|
||||
let columns = [
|
||||
Arc::new(UInt64Array::from_iter_values(
|
||||
|
||||
@@ -2380,6 +2380,7 @@ async fn test_limited_writer_fails_instead_of_publishing_over_budget(#[case] kin
|
||||
&limits,
|
||||
plan.max_output_file_size,
|
||||
(0, 0),
|
||||
|_| false,
|
||||
Arc::default(),
|
||||
)
|
||||
.write(source)
|
||||
|
||||
@@ -56,6 +56,7 @@ pub(crate) async fn execute(
|
||||
let schema = source.schema();
|
||||
let limits = source.limits.clone();
|
||||
let input_size = source.input_size;
|
||||
let source = source.clone();
|
||||
let index_plan =
|
||||
source
|
||||
.index_plans
|
||||
@@ -86,6 +87,7 @@ pub(crate) async fn execute(
|
||||
&limits,
|
||||
plan.max_output_file_size,
|
||||
input_size,
|
||||
|file_id| source.footer_all_zero(file_id),
|
||||
index_plan,
|
||||
)
|
||||
.write(input)
|
||||
|
||||
@@ -16,6 +16,7 @@ use common_base::readable_size::ReadableSize;
|
||||
use partition::expr::PartitionExpr;
|
||||
use snafu::{ResultExt, ensure};
|
||||
use store_api::codec::PrimaryKeyEncoding;
|
||||
use store_api::storage::SequenceNumber;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType};
|
||||
@@ -24,7 +25,7 @@ use crate::compaction::multi_region::{MultiRegionCompactionContext, MultiRegionT
|
||||
use crate::error::{ComputeArrowSnafu, Result};
|
||||
use crate::read::FlatSource;
|
||||
use crate::sst::FormatType;
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::sst::file::{FileMeta, RegionFileId, substituted_up_to_after_merge};
|
||||
use crate::sst::index::build::IndexBuildInputs;
|
||||
use crate::sst::index::registry::IndexBuildPlan;
|
||||
use crate::sst::parquet::metadata::extract_primary_key_range;
|
||||
@@ -42,6 +43,7 @@ pub(crate) struct TargetWriter<'a> {
|
||||
input_size: (u64, u64),
|
||||
sequence: Option<NonZeroU64>,
|
||||
preserve_row_sequence: bool,
|
||||
substituted_up_to: Option<SequenceNumber>,
|
||||
}
|
||||
|
||||
impl<'a> TargetWriter<'a> {
|
||||
@@ -51,14 +53,26 @@ impl<'a> TargetWriter<'a> {
|
||||
limits: &'a MemoryLimits,
|
||||
max_file_size: usize,
|
||||
input_size: (u64, u64),
|
||||
footer_all_zero: impl Fn(RegionFileId) -> bool,
|
||||
index_plan: Arc<IndexBuildPlan>,
|
||||
) -> Self {
|
||||
let region_id = target.metadata.region_id;
|
||||
let sequence = crate::sst::file::known_max_input_sequence(target.inputs.values());
|
||||
let preserve_row_sequence = target.options.preserve_row_sequence
|
||||
&& target
|
||||
.inputs
|
||||
.values()
|
||||
.all(|file| file.is_effective_target_sequence_trusted(target.metadata.region_id));
|
||||
.all(|file| file.is_effective_target_sequence_trusted(region_id));
|
||||
// The merge substitutes a file-level constant for the rows of a foreign input and of a
|
||||
// local untrusted input whose footer proves an all-zero column, so the routed rows may
|
||||
// carry numbers this region never allocated up to that constant.
|
||||
let substituted_up_to = substituted_up_to_after_merge(
|
||||
region_id,
|
||||
target
|
||||
.inputs
|
||||
.values()
|
||||
.map(|file| (file, footer_all_zero(file.file_id()))),
|
||||
);
|
||||
Self {
|
||||
target,
|
||||
context,
|
||||
@@ -68,6 +82,7 @@ impl<'a> TargetWriter<'a> {
|
||||
input_size,
|
||||
sequence,
|
||||
preserve_row_sequence,
|
||||
substituted_up_to,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,6 +225,7 @@ impl<'a> TargetWriter<'a> {
|
||||
primary_key_min: range.as_ref().map(|(min, _)| min.clone()),
|
||||
primary_key_max: range.map(|(_, max)| max),
|
||||
preserve_row_sequence: self.preserve_row_sequence,
|
||||
substituted_up_to: self.substituted_up_to,
|
||||
format: info.format.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ use crate::read::seq_scan::SeqScan;
|
||||
use crate::read::stream::spawn_compact_stream;
|
||||
use crate::region::options::MergeMode;
|
||||
use crate::sst::file::FileHandle;
|
||||
use crate::sst::parquet::format::need_override_sequence;
|
||||
use crate::sst::parquet::reader::MetadataCacheMetrics;
|
||||
use crate::sst::parquet::{Json2RewriteTargets, Json2TargetLayout};
|
||||
use crate::sst::parquet::{decoded_input_size, row_group_size_for};
|
||||
@@ -62,8 +63,16 @@ pub(crate) struct CompactionSstReaderBuilder<'a> {
|
||||
impl CompactionSstReaderBuilder<'_> {
|
||||
/// Build a [FlatSource] that yields Arrow `RecordBatch`s from reading all the input SST files,
|
||||
/// for compaction. The schema of the [FlatSource] is unified.
|
||||
///
|
||||
/// Returns the footer fact `need_override_sequence` of every input, in input order (`None`
|
||||
/// for a file that is gone), so the caller can state the merged column's
|
||||
/// [`FileMeta::substituted_up_to`](crate::sst::file::FileMeta::substituted_up_to) without
|
||||
/// reading the footers a second time.
|
||||
///
|
||||
/// A gone input contributes neither rows nor a substituted constant, so `None` is a fact
|
||||
/// the caller has to skip rather than a footer that merely is not an override.
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn build_flat_sst_reader(self) -> Result<FlatSource> {
|
||||
pub(crate) async fn build_flat_sst_reader(self) -> Result<(FlatSource, Vec<Option<bool>>)> {
|
||||
let parquet_metadata = self.collect_parquet_metadata().await?;
|
||||
self.build_flat_sst_reader_from(parquet_metadata).await
|
||||
}
|
||||
@@ -73,17 +82,31 @@ impl CompactionSstReaderBuilder<'_> {
|
||||
pub(crate) async fn build_flat_sst_reader_and_row_group_size(
|
||||
self,
|
||||
configured: usize,
|
||||
) -> Result<(FlatSource, usize)> {
|
||||
) -> Result<(FlatSource, usize, Vec<Option<bool>>)> {
|
||||
let parquet_metadata = self.collect_parquet_metadata().await?;
|
||||
let (rows, bytes) = decoded_input_size(parquet_metadata.iter().map(Arc::as_ref));
|
||||
let source = self.build_flat_sst_reader_from(parquet_metadata).await?;
|
||||
Ok((source, row_group_size_for(rows, bytes, configured)))
|
||||
let (rows, bytes) = decoded_input_size(
|
||||
parquet_metadata
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|footer| footer.as_ref()),
|
||||
);
|
||||
let (source, legacy_overrides) = self.build_flat_sst_reader_from(parquet_metadata).await?;
|
||||
Ok((
|
||||
source,
|
||||
row_group_size_for(rows, bytes, configured),
|
||||
legacy_overrides,
|
||||
))
|
||||
}
|
||||
|
||||
async fn build_flat_sst_reader_from(
|
||||
self,
|
||||
parquet_metadata: Vec<Arc<ParquetMetaData>>,
|
||||
) -> Result<FlatSource> {
|
||||
parquet_metadata: Vec<Option<Arc<ParquetMetaData>>>,
|
||||
) -> Result<(FlatSource, Vec<Option<bool>>)> {
|
||||
let legacy_overrides = parquet_metadata
|
||||
.iter()
|
||||
.map(|footer| footer.as_ref().map(|footer| need_override_sequence(footer)))
|
||||
.collect::<Vec<_>>();
|
||||
let parquet_metadata = parquet_metadata.into_iter().flatten().collect::<Vec<_>>();
|
||||
let plans = collect_json2_rewrite_plans_from_parquet(&self.metadata, &parquet_metadata)?;
|
||||
let scan_input = self.build_scan_input(&parquet_metadata, &plans)?;
|
||||
|
||||
@@ -95,7 +118,7 @@ impl CompactionSstReaderBuilder<'_> {
|
||||
.build_flat_reader_for_compaction()
|
||||
.boxed()
|
||||
.await?;
|
||||
Ok(FlatSource::new_stream(schema, stream))
|
||||
Ok((FlatSource::new_stream(schema, stream), legacy_overrides))
|
||||
}
|
||||
|
||||
fn build_scan_input(
|
||||
@@ -171,8 +194,9 @@ impl CompactionSstReaderBuilder<'_> {
|
||||
Ok(scan_input.build())
|
||||
}
|
||||
|
||||
/// Reads the footers of all inputs concurrently, keeping the input order.
|
||||
async fn collect_parquet_metadata(&self) -> Result<Vec<Arc<ParquetMetaData>>> {
|
||||
/// Reads the footers of all inputs concurrently, keeping the input order. A file that
|
||||
/// is gone yields `None`, which contributes neither rows nor a substituted constant.
|
||||
async fn collect_parquet_metadata(&self) -> Result<Vec<Option<Arc<ParquetMetaData>>>> {
|
||||
let reads: Vec<_> = self
|
||||
.inputs
|
||||
.iter()
|
||||
@@ -182,7 +206,7 @@ impl CompactionSstReaderBuilder<'_> {
|
||||
.buffered(MAX_CONCURRENT_METADATA_READS)
|
||||
.try_collect()
|
||||
.await?;
|
||||
Ok(metadata.into_iter().flatten().collect())
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Reads the parquet metadata of `file_handle`, or `None` if the file is gone.
|
||||
@@ -341,7 +365,7 @@ mod tests {
|
||||
let inputs: Vec<_> = version.ssts.levels()[0].files().cloned().collect();
|
||||
assert_eq!(2, inputs.len());
|
||||
|
||||
let mut source = CompactionSstReaderBuilder {
|
||||
let (mut source, legacy_overrides) = CompactionSstReaderBuilder {
|
||||
metadata: version.metadata.clone(),
|
||||
sst_layer: region.access_layer.clone(),
|
||||
cache: engine.cache_manager(),
|
||||
@@ -355,6 +379,8 @@ mod tests {
|
||||
.build_flat_sst_reader()
|
||||
.await
|
||||
.unwrap();
|
||||
// A flush writes the allocated sequences, so no input is an all-zero legacy file.
|
||||
assert_eq!(vec![Some(false), Some(false)], legacy_overrides);
|
||||
let mut num_batches = 0;
|
||||
let mut num_rows = 0;
|
||||
while let Some(batch) = source.next_batch().await.unwrap() {
|
||||
@@ -431,7 +457,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(encoded < 1024 * 1024, "{encoded}");
|
||||
|
||||
let (_, row_group_size) = CompactionSstReaderBuilder {
|
||||
let (_, row_group_size, _) = CompactionSstReaderBuilder {
|
||||
metadata: version.metadata.clone(),
|
||||
sst_layer: region.access_layer.clone(),
|
||||
cache: engine.cache_manager(),
|
||||
|
||||
+44
-4
@@ -1528,6 +1528,35 @@ fn validate_sequence_fences(
|
||||
exact_sequence_range_available: bool,
|
||||
extension_provider_blocks_exact: bool,
|
||||
) -> Result<()> {
|
||||
// A read that may cross an invalid boundary prunes at file granularity and reads
|
||||
// no row-level sequence range, so no sequence fence applies: the caller only needs
|
||||
// the timestamps of the surviving rows, and rejecting the request would deadlock
|
||||
// recovery.
|
||||
if request.read_across_invalid_boundary || request.require_flushed_frontier {
|
||||
// Such a read may read rows a stale cursor no longer explains; its result may
|
||||
// only be committed when the layout it read is still the one `H` was taken from.
|
||||
if let Some(high) = request.memtable_max_sequence {
|
||||
// A read that requires the flushed frontier has no incremental lower bound
|
||||
// and no exact sequence-range mode, so `H` bounds memtables only. When `H`
|
||||
// is behind the flushed frontier an SST cannot be filtered by `H`, and a
|
||||
// plain flush that landed after `H` was frozen would be aggregated into the
|
||||
// recomputed window and then counted again by the next round. Keep the SST
|
||||
// upper-bound fence so the caller rediscovers instead.
|
||||
if request.require_flushed_frontier && !request.skip_sst_files {
|
||||
let min_enforceable_seq = version.flushed_sequence;
|
||||
ensure!(
|
||||
high >= min_enforceable_seq,
|
||||
SnapshotFenceStaleSnafu {
|
||||
region_id,
|
||||
given_seq: high,
|
||||
min_enforceable_seq,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if request.exact_sequence_range {
|
||||
// Exact `sequence_range` mode: when the capability is available the
|
||||
// requested (C, H] delta is enforced row-level on memtables and every
|
||||
@@ -1568,7 +1597,11 @@ fn validate_sequence_fences(
|
||||
region_id,
|
||||
min_seq: request.memtable_min_sequence.unwrap_or_default(),
|
||||
max_seq: request.memtable_max_sequence.unwrap_or_default(),
|
||||
reason: sequence_range_unsupported_reason(version, extension_provider_blocks_exact),
|
||||
reason: sequence_range_unsupported_reason(
|
||||
request,
|
||||
version,
|
||||
extension_provider_blocks_exact,
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
@@ -1613,15 +1646,22 @@ fn validate_sequence_fences(
|
||||
}
|
||||
|
||||
fn sequence_range_unsupported_reason(
|
||||
request: &ScanRequest,
|
||||
version: &crate::region::version::Version,
|
||||
extension_provider_blocks_exact: bool,
|
||||
) -> String {
|
||||
if extension_provider_blocks_exact {
|
||||
"region is a follower with an extension range provider, whose streams cannot be filtered by sequence".to_string()
|
||||
} else if version.options.preserve_row_sequence {
|
||||
"region has files without preserved per-row sequences".to_string()
|
||||
} else {
|
||||
} else if !version.options.preserve_row_sequence {
|
||||
"region does not preserve per-row sequences (preserve_row_sequence is off)".to_string()
|
||||
} else if request.read_row_sequence {
|
||||
// A file that states a substituted cut is attributable (its substituted rows are
|
||||
// hidden and reported, the rest keep this region's numbering), so the remaining
|
||||
// case is a local file with neither the preserved-sequence marker nor a cut.
|
||||
"region has files without preserved per-row sequences and without a substituted cut, so a physical-sequence read cannot attribute their rows"
|
||||
.to_string()
|
||||
} else {
|
||||
"region has files without preserved per-row sequences".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,154 @@ fn range_expr(col_name: &str, start: i64, end: i64) -> PartitionExpr {
|
||||
.and(col(col_name).lt(Value::Int64(end)))
|
||||
}
|
||||
|
||||
/// A repartition can keep a region's own files in place: the region id survives, so the
|
||||
/// bytes, the numbers and the `preserve_row_sequence` marker all stay as they are.
|
||||
///
|
||||
/// The staging exit re-marks the barrier of every file it makes visible, and it must not
|
||||
/// clear that marker for a file this region already owned. A local file without trusted
|
||||
/// per-row numbering denies the whole region its exact `(C, H]` range
|
||||
/// (`read/scan_region.rs::exact_sequence_range` fails closed on it), so the rows written
|
||||
/// after the repartition could never be read again — the file never left, only its
|
||||
/// publisher changed.
|
||||
#[tokio::test]
|
||||
async fn test_apply_staging_manifest_keeps_the_marker_of_a_kept_file() {
|
||||
let mut env = TestEnv::with_prefix("apply-staging-keeps-kept-file-marker").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let region = RegionId::new(1, 1);
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.build();
|
||||
let schema = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
put_rows(
|
||||
&engine,
|
||||
region,
|
||||
Rows {
|
||||
schema: schema.clone(),
|
||||
rows: build_rows_for_key("0", 0, 3, 0),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
engine
|
||||
.handle_request(region, RegionRequest::Flush(RegionFlushRequest::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let kept_file_id = {
|
||||
let version = engine.get_region(region).unwrap().version();
|
||||
let files = version
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.values())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(1, files.len());
|
||||
let kept = files[0].meta_ref();
|
||||
assert_eq!(region, kept.region_id);
|
||||
assert!(
|
||||
kept.preserve_row_sequence,
|
||||
"a flushed file of a preserving region states its numbering"
|
||||
);
|
||||
kept.file_id
|
||||
};
|
||||
|
||||
// Repartition the region into itself under a new partition expression: the files stay
|
||||
// where they are, and only the expression the region applies changes.
|
||||
let partition_expr = float_range_expr("field_0", -100.0, 100.0)
|
||||
.as_json_str()
|
||||
.unwrap();
|
||||
// The region owns the staging session as well as the layout that stays in it, which is
|
||||
// what a repartition that keeps a region in place does. The session clears the region's
|
||||
// staging directory, so the layout is remapped only after it starts.
|
||||
engine
|
||||
.handle_request(
|
||||
region,
|
||||
RegionRequest::EnterStaging(EnterStagingRequest {
|
||||
partition_directive: StagingPartitionDirective::UpdatePartitionExpr(
|
||||
partition_expr.clone(),
|
||||
),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let remapped = engine
|
||||
.remap_manifests(RemapManifestsRequest {
|
||||
region_id: region,
|
||||
input_regions: vec![region],
|
||||
region_mapping: [(region, vec![region])].into_iter().collect(),
|
||||
new_partition_exprs: [(region, partition_expr.clone())].into_iter().collect(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
engine
|
||||
.handle_request(
|
||||
region,
|
||||
RegionRequest::ApplyStagingManifest(ApplyStagingManifestRequest {
|
||||
partition_expr,
|
||||
central_region_id: region,
|
||||
manifest_path: remapped.manifest_paths[®ion].clone(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// The file never changed hands, so the exit re-stamped its barrier and kept the marker.
|
||||
let version = engine.get_region(region).unwrap().version();
|
||||
let files = version
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.values())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(1, files.len());
|
||||
let kept = files[0].meta_ref();
|
||||
assert_eq!(kept_file_id, kept.file_id);
|
||||
assert_eq!(region, kept.region_id, "the file is still this region's");
|
||||
assert!(
|
||||
kept.preserve_row_sequence,
|
||||
"a file that stayed in the region keeps the numbering this region allocated for it"
|
||||
);
|
||||
|
||||
// The exact delta is still served after the repartition: the kept rows plus the row
|
||||
// written afterwards, which the region numbers above the exit's admission.
|
||||
put_rows(
|
||||
&engine,
|
||||
region,
|
||||
Rows {
|
||||
schema: schema.clone(),
|
||||
rows: build_rows_for_key("1", 3, 4, 99),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
engine
|
||||
.handle_request(region, RegionRequest::Flush(RegionFlushRequest::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
let stream = engine
|
||||
.scan_to_stream(
|
||||
region,
|
||||
ScanRequest {
|
||||
exact_sequence_range: true,
|
||||
read_row_sequence: true,
|
||||
memtable_min_sequence: Some(0),
|
||||
memtable_max_sequence: Some(100),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
assert_eq!(
|
||||
4,
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
|
||||
"the repartition must not deny the region its exact (C, H] range"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_apply_staging_manifest_sequence_domain() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
@@ -178,13 +326,21 @@ async fn test_apply_staging_manifest_sequence_domain_with_format(
|
||||
.manifest()
|
||||
.await;
|
||||
assert_eq!(manifest.files.len(), 1);
|
||||
assert_eq!(manifest.committed_sequence, Some(1));
|
||||
// The staging exit allocates the holder's admission `B` (the staging apply's
|
||||
// allocation, 1, plus one) and raises the committed watermark to at least `B`
|
||||
// in the same action list, so the persisted manifest proves `H >= B`.
|
||||
assert_eq!(manifest.committed_sequence, Some(2));
|
||||
let imported_file = manifest.files.values().next().unwrap();
|
||||
assert_eq!(imported_file.region_id, source);
|
||||
// The staging exit re-marks every merged file at the published boundary (2), so
|
||||
// file-level pruning can never skip data that only the exit made visible.
|
||||
assert_eq!(
|
||||
imported_file.sequence,
|
||||
Some(std::num::NonZeroU64::new(1).unwrap())
|
||||
Some(std::num::NonZeroU64::new(2).unwrap())
|
||||
);
|
||||
// The re-mark is a holder-side statement: the source file carried no substituted
|
||||
// cut, and copying the bytes verbatim must not invent one.
|
||||
assert_eq!(None, imported_file.substituted_up_to);
|
||||
|
||||
put_rows(
|
||||
&engine,
|
||||
@@ -259,12 +415,18 @@ async fn test_apply_staging_manifest_sequence_domain_with_format(
|
||||
.find(|file| output_ids.contains(&file.meta_ref().file_id))
|
||||
.expect("target-owned compaction output");
|
||||
assert!(output.meta_ref().preserve_row_sequence);
|
||||
// The imported rows are virtualized at target barrier 1 and the local
|
||||
// row has physical sequence 2, so the output frontier is 2.
|
||||
// The staging exit publishes its own boundary (2) and raises the committed
|
||||
// watermark to it in the same publish, while ordinary writes are queued by its
|
||||
// publish window. The local row written afterwards therefore has sequence 3 and
|
||||
// the output frontier is 3.
|
||||
assert_eq!(
|
||||
Some(std::num::NonZeroU64::new(2).unwrap()),
|
||||
Some(std::num::NonZeroU64::new(3).unwrap()),
|
||||
output.meta_ref().sequence
|
||||
);
|
||||
// The imported input is `source`'s file, so this region's reader substituted its
|
||||
// handle bound (2) for every one of its rows. The output's own frontier is 3, but
|
||||
// the cut reaches the constant those rows now carry.
|
||||
assert_eq!(Some(2), output.meta_ref().substituted_up_to);
|
||||
|
||||
let mut reader = engine
|
||||
.get_region(target)
|
||||
@@ -285,36 +447,97 @@ async fn test_apply_staging_manifest_sequence_domain_with_format(
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.expect("sequence column");
|
||||
// The target partition excludes source field_0 = 0, leaving two
|
||||
// imported rows at barrier 1 and the local row at sequence 2.
|
||||
// The staging exit re-marked the imported file at the published boundary (2),
|
||||
// and the target partition excludes source field_0 = 0: two imported rows at
|
||||
// barrier 2 plus the local row at sequence 3.
|
||||
assert_eq!(
|
||||
2,
|
||||
sequences.values().iter().filter(|&&seq| seq == 1).count()
|
||||
sequences.values().iter().filter(|&&seq| seq == 2).count()
|
||||
);
|
||||
assert_eq!(
|
||||
1,
|
||||
sequences.values().iter().filter(|&&seq| seq == 2).count()
|
||||
sequences.values().iter().filter(|&&seq| seq == 3).count()
|
||||
);
|
||||
|
||||
for (min, max, expected_rows) in [(0, 1, 2), (1, 2, 1)] {
|
||||
let stream = engine
|
||||
.scan_to_stream(
|
||||
target,
|
||||
ScanRequest {
|
||||
exact_sequence_range: true,
|
||||
memtable_min_sequence: Some(min),
|
||||
memtable_max_sequence: Some(max),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
assert_eq!(
|
||||
expected_rows,
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>()
|
||||
);
|
||||
}
|
||||
// Neither end of a repartition records an invalidation boundary, so a cursor at
|
||||
// the very bottom (0) is still served: the rows it has not consumed were copied,
|
||||
// not renumbered, and what the holder substituted per file is stated by the
|
||||
// output's `substituted_up_to` (asserted below). The two imported rows it reads
|
||||
// physically carry the exit's admission constant (2) because the reader
|
||||
// substitutes a foreign file at the handle's bound in the default mode.
|
||||
let stream = engine
|
||||
.scan_to_stream(
|
||||
target,
|
||||
ScanRequest {
|
||||
exact_sequence_range: true,
|
||||
memtable_min_sequence: Some(0),
|
||||
memtable_max_sequence: Some(2),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
assert_eq!(
|
||||
2,
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
|
||||
"staging apply and exit record no boundary, so no cursor is rejected"
|
||||
);
|
||||
|
||||
// A cursor at the staged apply's former allocation (1) resumes as well: the
|
||||
// only reason it could be rejected is a boundary this chain does not record.
|
||||
let stream = engine
|
||||
.scan_to_stream(
|
||||
target,
|
||||
ScanRequest {
|
||||
exact_sequence_range: true,
|
||||
memtable_min_sequence: Some(1),
|
||||
memtable_max_sequence: Some(2),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
assert_eq!(
|
||||
2,
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
|
||||
"a repartition leaves the cursor readable instead of invalidating it"
|
||||
);
|
||||
|
||||
// A cursor at the exit's admission (2) is served: only rows published after it
|
||||
// are in the delta.
|
||||
put_rows(
|
||||
&engine,
|
||||
target,
|
||||
Rows {
|
||||
schema: schema.clone(),
|
||||
rows: build_rows_for_key("2", 5, 6, 99),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
engine
|
||||
.handle_request(target, RegionRequest::Flush(RegionFlushRequest::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
let stream = engine
|
||||
.scan_to_stream(
|
||||
target,
|
||||
ScanRequest {
|
||||
exact_sequence_range: true,
|
||||
memtable_min_sequence: Some(2),
|
||||
memtable_max_sequence: Some(5),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
assert_eq!(
|
||||
2,
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
|
||||
"the (2, 5] delta holds the local row (seq 3) and the new row (seq 4)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,8 +26,14 @@ use store_api::storage::{RegionId, ScanRequest};
|
||||
|
||||
use crate::config::MitoConfig;
|
||||
use crate::error::Error;
|
||||
use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState};
|
||||
use crate::test_util::{CreateRequestBuilder, TestEnv, build_rows, put_rows, rows_schema};
|
||||
|
||||
/// A copy must publish the shared references it installs inside the publish window it
|
||||
/// holds, exactly like physically copied files. Handing them to the region edit lane
|
||||
/// instead queues them behind that window (the region is `Editing` for the whole copy) and
|
||||
/// waits for a completion the worker only produces after the window is released, which
|
||||
/// deadlocked both copy cases below.
|
||||
#[cfg(feature = "enterprise")]
|
||||
#[rstest::rstest]
|
||||
#[case::shared_only(false, false)]
|
||||
@@ -626,19 +632,29 @@ async fn test_copy_region_from_clears_preserve_row_sequence_marker() {
|
||||
.all(|meta| !meta.preserve_row_sequence),
|
||||
"copied files must have the preserve_row_sequence marker cleared"
|
||||
);
|
||||
// The source-domain hint is replaced — not kept — by the target's own barrier, so
|
||||
// the copied rows are virtualized at that barrier and the file is never skipped as
|
||||
// "proven disjoint" under a source-domain bound.
|
||||
let target_boundary = target_manifest
|
||||
.files
|
||||
.values()
|
||||
.next()
|
||||
.expect("published file")
|
||||
.sequence
|
||||
.expect("the edit assigns a barrier")
|
||||
.get();
|
||||
assert!(
|
||||
target_manifest
|
||||
.files
|
||||
.values()
|
||||
.all(|meta| meta.sequence.is_none()),
|
||||
"copied files must have their source-domain sequence hint cleared"
|
||||
.all(|meta| meta.sequence.map(|sequence| sequence.get()) == Some(target_boundary)),
|
||||
"copied files must carry the target's backfilled barrier"
|
||||
);
|
||||
|
||||
// An exact sequence-range request intersecting the copied rows' sequences
|
||||
// (rows 3..=7 in the source domain) must fail closed with
|
||||
// `SequenceRangeUnsupported` instead of replaying source-domain rows.
|
||||
let err = engine
|
||||
.scanner(
|
||||
// An exact sequence-range request above the target barrier therefore excludes the
|
||||
// copied rows instead of replaying them as target-domain sequences.
|
||||
let stream = engine
|
||||
.scan_to_stream(
|
||||
target_region_id,
|
||||
ScanRequest {
|
||||
memtable_min_sequence: Some(2),
|
||||
@@ -648,13 +664,13 @@ async fn test_copy_region_from_clears_preserve_row_sequence_marker() {
|
||||
},
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("expected sequence-range unsupported error");
|
||||
assert!(
|
||||
matches!(err, Error::SequenceRangeUnsupported { .. }),
|
||||
"unexpected err: {err}"
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
assert_eq!(
|
||||
0,
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
|
||||
"copied rows are virtualized at the target barrier and stay out of (2, 7]"
|
||||
);
|
||||
assert_eq!(err.status_code(), StatusCode::Unsupported);
|
||||
|
||||
// Sanity: the source region keeps the marker and still serves the same
|
||||
// exact range with its own row-level sequences (3..=7, 5 rows).
|
||||
@@ -677,3 +693,131 @@ async fn test_copy_region_from_clears_preserve_row_sequence_marker() {
|
||||
"source exact range should return rows with sequence 3..=7"
|
||||
);
|
||||
}
|
||||
|
||||
/// Waits until `region` reaches `state`.
|
||||
async fn wait_until_region_state(region: &MitoRegionRef, state: RegionLeaderState) {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while region.state() != RegionRoleState::Leader(state) {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("region did not reach the expected state in time");
|
||||
}
|
||||
|
||||
/// The copy holds the worker-coordinated publish window from the moment it is admitted in
|
||||
/// the worker loop until the copied files are visible, so the boundary it allocates is above
|
||||
/// every sequence already attributed to a row and ordinary writes arriving meanwhile are
|
||||
/// queued instead of being admitted at or below that boundary.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_copy_region_from_publish_window_queues_writes() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
|
||||
let mut env = TestEnv::with_prefix("copy-region-from-publish-window").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
|
||||
let source_region_id = RegionId::new(1, 1);
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.build();
|
||||
let column_schemas = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(source_region_id, RegionRequest::Create(request.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
put_rows(
|
||||
&engine,
|
||||
source_region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(0, 5),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
engine
|
||||
.handle_request(
|
||||
source_region_id,
|
||||
RegionRequest::Flush(RegionFlushRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let target_region_id = RegionId::new(1, 2);
|
||||
engine
|
||||
.handle_request(target_region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let target = engine.get_region(target_region_id).unwrap();
|
||||
let last_sequence_before_copy = target.version_control.current().last_sequence;
|
||||
|
||||
// Holding the target's manifest write lock keeps the copy inside its publish window: the
|
||||
// worker loop opens the window when it admits the copy, and the background task then
|
||||
// blocks on the lock while persisting the copied files.
|
||||
let manifest_guard = target.manifest_ctx.manifest_manager.write().await;
|
||||
let copy_engine = engine.clone();
|
||||
let copy_task = tokio::spawn(async move {
|
||||
copy_engine
|
||||
.copy_region_from(
|
||||
target_region_id,
|
||||
MitoCopyRegionFromRequest {
|
||||
source_region_id,
|
||||
parallelism: 1,
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
wait_until_region_state(&target, RegionLeaderState::Editing).await;
|
||||
|
||||
// A write that arrives during the copy is queued, not attributed a sequence.
|
||||
let write_engine = engine.clone();
|
||||
let write_rows = Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(5, 7),
|
||||
};
|
||||
let write_task =
|
||||
tokio::spawn(async move { put_rows(&write_engine, target_region_id, write_rows).await });
|
||||
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||
assert!(
|
||||
!write_task.is_finished(),
|
||||
"a write must be queued while the copy publish window is open"
|
||||
);
|
||||
assert_eq!(
|
||||
last_sequence_before_copy,
|
||||
target.version_control.current().last_sequence,
|
||||
"a queued write must not allocate a sequence during the copy"
|
||||
);
|
||||
|
||||
// Releasing the lock lets the copied files become visible; the window then closes and the
|
||||
// queued write is admitted.
|
||||
drop(manifest_guard);
|
||||
copy_task.await.unwrap().unwrap();
|
||||
write_task.await.unwrap();
|
||||
|
||||
let boundary = last_sequence_before_copy + 1;
|
||||
assert_eq!(
|
||||
Some(boundary),
|
||||
target
|
||||
.manifest_ctx
|
||||
.manifest()
|
||||
.await
|
||||
.files
|
||||
.values()
|
||||
.next()
|
||||
.and_then(|meta| meta.sequence.map(|sequence| sequence.get())),
|
||||
"the copy must publish the files at last_sequence + 1"
|
||||
);
|
||||
assert_eq!(
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable),
|
||||
target.state(),
|
||||
"the copy publish window must be released after the publish"
|
||||
);
|
||||
assert!(
|
||||
target.version_control.current().last_sequence > boundary,
|
||||
"the queued write must be attributed a sequence above the published boundary, \
|
||||
last_sequence: {}, boundary: {}",
|
||||
target.version_control.current().last_sequence,
|
||||
boundary
|
||||
);
|
||||
}
|
||||
|
||||
@@ -730,8 +730,17 @@ async fn test_failed_region_edit_preserves_sequence() {
|
||||
assert_eq!((current.last_sequence, current.committed_sequence), (4, 4));
|
||||
}
|
||||
|
||||
/// The marker an edit applies to an added file is judged by **ownership**.
|
||||
///
|
||||
/// A file that stays in this region (`region_id ==` this region) kept its bytes and the
|
||||
/// numbers this region allocated for it: a repartition's staging apply lands here as an
|
||||
/// edit too, and clearing the marker of such a file would deny every later exact `(C, H]`
|
||||
/// read of the region although the file never left (`read/scan_region.rs::exact_sequence_range`
|
||||
/// fails closed on a local file with no trusted per-row numbering). A file adopted from
|
||||
/// another region is attributed by the creator's cursor and by its own substituted cut, so
|
||||
/// its marker is cleared. Both keep the destination sequence the edit assigns.
|
||||
#[tokio::test]
|
||||
async fn test_region_edit_clears_preserve_row_sequence() {
|
||||
async fn test_region_edit_keeps_local_and_clears_adopted_preserve_row_sequence() {
|
||||
let mut env = TestEnv::new().await;
|
||||
let (engine, _) = create_engine_with_request_listener(&mut env).await;
|
||||
|
||||
@@ -745,25 +754,40 @@ async fn test_region_edit_clears_preserve_row_sequence() {
|
||||
.unwrap();
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
|
||||
let file_id = FileId::random();
|
||||
let mut edit = test_region_edit(region.region_id, file_id);
|
||||
// The caller claims the file preserves per-row sequences...
|
||||
let local_file_id = FileId::random();
|
||||
let foreign_file_id = FileId::random();
|
||||
let mut edit = test_region_edit(region.region_id, local_file_id);
|
||||
// The caller states that both files preserve per-row sequences...
|
||||
edit.files_to_add[0].preserve_row_sequence = true;
|
||||
edit.files_to_add.push(FileMeta {
|
||||
region_id: RegionId::new(1, 2),
|
||||
file_id: foreign_file_id,
|
||||
level: 0,
|
||||
preserve_row_sequence: true,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
engine.edit_region(region.region_id, edit).await.unwrap();
|
||||
|
||||
// ...but a generic region edit assigns a new destination sequence domain
|
||||
// without proving or rewriting the physical per-row sequence column, so the
|
||||
// marker must be cleared while the assigned sequence stays committed + 1.
|
||||
// ...but only the local one keeps that statement: it is this region's own file, so its
|
||||
// numbers were allocated here. The adopted file's numbers belong to its creator, so the
|
||||
// statement cannot be kept.
|
||||
let version = region.version();
|
||||
let file = version.ssts.levels()[0]
|
||||
.files
|
||||
let files = &version.ssts.levels()[0].files;
|
||||
let local = files
|
||||
.iter()
|
||||
.find(|(id, _)| **id == file_id)
|
||||
.find(|(id, _)| **id == local_file_id)
|
||||
.unwrap()
|
||||
.1;
|
||||
assert!(!file.meta_ref().preserve_row_sequence);
|
||||
assert_eq!(Some(1), file.meta_ref().sequence.map(|s| s.get()));
|
||||
assert!(local.meta_ref().preserve_row_sequence);
|
||||
assert_eq!(Some(1), local.meta_ref().sequence.map(|s| s.get()));
|
||||
let foreign = files
|
||||
.iter()
|
||||
.find(|(id, _)| **id == foreign_file_id)
|
||||
.unwrap()
|
||||
.1;
|
||||
assert!(!foreign.meta_ref().preserve_row_sequence);
|
||||
assert_eq!(Some(1), foreign.meta_ref().sequence.map(|s| s.get()));
|
||||
}
|
||||
|
||||
async fn wait_until_region_is_in_editing(region: &MitoRegionRef) {
|
||||
|
||||
+1839
-37
File diff suppressed because it is too large
Load Diff
@@ -66,7 +66,7 @@ use crate::request::{BackgroundNotify, RegionEditRequest, WorkerRequest};
|
||||
use crate::sst::FormatType;
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::test_util::{
|
||||
CheckpointTaskBlocker, CreateRequestBuilder, MockWriteBufferManager, TestEnv,
|
||||
CheckpointTaskBlocker, CreateRequestBuilder, DeltaFaults, MockWriteBufferManager, TestEnv,
|
||||
build_delete_rows, build_rows, delete_rows, delete_rows_schema, flush_region, put_rows,
|
||||
reopen_region, rows_schema,
|
||||
};
|
||||
@@ -938,9 +938,34 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool)
|
||||
let workers = &engine.inner.workers;
|
||||
let region = workers.get_region(region_id).unwrap();
|
||||
let current = region.version_control.current();
|
||||
// The exit holds the publish window (the `Editing` state) while it allocates the
|
||||
// holder's admission `B = 13` (last_sequence 12 + 1), persists and publishes, and it
|
||||
// raises the commit watermark to `B` in the same publish. No write can therefore be
|
||||
// attributed a sequence at or below `B`: every write admitted afterwards obtains
|
||||
// `B + 1` (14) or later, and `last_sequence` never runs ahead of a failed publish.
|
||||
//
|
||||
// It publishes no sequence boundary of its own: a repartition rewrites no bytes and
|
||||
// substitutes no row number.
|
||||
assert_eq!(
|
||||
(current.last_sequence, current.committed_sequence),
|
||||
(12, 12)
|
||||
(13, 13)
|
||||
);
|
||||
// Every staged file must carry the published boundary: the persisted action list
|
||||
// applies the final merged edit exactly once, so no original edit can overwrite
|
||||
// the barrier on replay.
|
||||
let manifest = region.manifest_ctx.manifest().await;
|
||||
assert!(!manifest.files.is_empty());
|
||||
assert!(
|
||||
manifest
|
||||
.files
|
||||
.values()
|
||||
.all(|meta| meta.sequence.map(|sequence| sequence.get()) == Some(13)),
|
||||
"all staged files must carry the published boundary, got: {:?}",
|
||||
manifest
|
||||
.files
|
||||
.values()
|
||||
.map(|meta| meta.sequence.map(|sequence| sequence.get()))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert!(
|
||||
!region.is_staging(),
|
||||
@@ -2614,6 +2639,545 @@ async fn test_migration_flush_retries_while_staging_ends() {
|
||||
assert_eq!(0, migration_flush().await.unwrap().affected_rows);
|
||||
}
|
||||
|
||||
/// Waits until the region reaches `state`.
|
||||
async fn wait_until_region_state(region: &MitoRegionRef, state: RegionLeaderState) {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while region.state() != RegionRoleState::Leader(state) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("region did not reach the expected state in time");
|
||||
}
|
||||
|
||||
/// Returns the admission barrier of `file_id` in the region's current SST version.
|
||||
fn file_sequence(region: &MitoRegionRef, file_id: FileId) -> Option<u64> {
|
||||
region
|
||||
.version()
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.iter())
|
||||
.find(|(id, _)| **id == file_id)
|
||||
.and_then(|(_, file)| file.meta_ref().sequence)
|
||||
.map(|sequence| sequence.get())
|
||||
}
|
||||
|
||||
/// The staging exit holds the worker-coordinated publish window while it allocates the
|
||||
/// boundary, persists the merged layout and makes it visible. Ordinary writes that arrive
|
||||
/// during the window are queued by the worker, so none of them can be attributed a sequence
|
||||
/// at or below the published boundary: a row at the boundary (or above it) written before
|
||||
/// the publish was visible would let a Flow cursor reach that sequence and then prune the
|
||||
/// published files as already consumed.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_staging_exit_publish_window_queues_writes() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let partition_expr = float_range_expr("field_0", 0., 100.).as_json_str().unwrap();
|
||||
let mut env = TestEnv::new().await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
|
||||
let region_id = RegionId::new(1024, 0);
|
||||
let request = CreateRequestBuilder::new().build();
|
||||
let column_schemas = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// One visible flush; rows written during staging stay in the staging memtable because a
|
||||
// staging region keeps its WAL and flushes nothing, so the exit is what publishes them.
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(0, 3),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Flush(RegionFlushRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::EnterStaging(EnterStagingRequest {
|
||||
partition_directive: StagingPartitionDirective::UpdatePartitionExpr(
|
||||
partition_expr.clone(),
|
||||
),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(3, 5),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
// A staging region publishes nothing on its own, so the exit needs an edit to merge and
|
||||
// re-mark; import one file from a source region to give it that edit.
|
||||
let source_region_id = RegionId::new(1024, 1);
|
||||
engine
|
||||
.handle_request(
|
||||
source_region_id,
|
||||
RegionRequest::Create(CreateRequestBuilder::new().build()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
put_rows(
|
||||
&engine,
|
||||
source_region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(0, 2),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
flush_region(&engine, source_region_id, None).await;
|
||||
let source_file = first_file(&engine.get_region(source_region_id).unwrap()).await;
|
||||
engine
|
||||
.handle_request(
|
||||
source_region_id,
|
||||
RegionRequest::Close(RegionCloseRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// The import needs the staging binding: a staging region rejects imports that carry
|
||||
// none, because the layout that would receive them can still be discarded.
|
||||
submit_staging_edit(&engine, region_id, source_file, partition_expr.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let last_sequence_before_exit = region.version_control.current().last_sequence;
|
||||
|
||||
// Holding the manifest write lock keeps the exit inside its publish window: the worker
|
||||
// loop opens the window before the background publish runs, so the region stays in the
|
||||
// `Editing` state and the worker keeps queuing writes.
|
||||
let manifest_guard = region.manifest_ctx.manifest_manager.write().await;
|
||||
let exit_engine = engine.clone();
|
||||
let exit_task = tokio::spawn(async move {
|
||||
exit_engine
|
||||
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader)
|
||||
.await
|
||||
});
|
||||
wait_until_region_state(®ion, RegionLeaderState::Editing).await;
|
||||
|
||||
// A write that arrives while the window is open must be queued, not admitted.
|
||||
let write_engine = engine.clone();
|
||||
let write_rows = Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(5, 7),
|
||||
};
|
||||
let write_task =
|
||||
tokio::spawn(async move { put_rows(&write_engine, region_id, write_rows).await });
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
assert!(
|
||||
!write_task.is_finished(),
|
||||
"a write must be queued while the publish window of the staging exit is open"
|
||||
);
|
||||
assert_eq!(
|
||||
last_sequence_before_exit,
|
||||
region.version_control.current().last_sequence,
|
||||
"a queued write must not allocate a sequence during the publish"
|
||||
);
|
||||
|
||||
// Releasing the lock lets the publish become visible, which closes the window: only then
|
||||
// is the queued write admitted.
|
||||
drop(manifest_guard);
|
||||
exit_task.await.unwrap().unwrap();
|
||||
write_task.await.unwrap();
|
||||
|
||||
let boundary = last_sequence_before_exit;
|
||||
assert_eq!(
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable),
|
||||
region.state(),
|
||||
"the publish window must be released after the publish"
|
||||
);
|
||||
assert!(
|
||||
region.version_control.current().last_sequence > boundary,
|
||||
"the queued write must be attributed a sequence above the published boundary, \
|
||||
last_sequence: {}, boundary: {}",
|
||||
region.version_control.current().last_sequence,
|
||||
boundary
|
||||
);
|
||||
|
||||
// The invariant the window exists for: a Flow cursor that reaches the staged import's
|
||||
// allocation cannot be handed a file it never consumed, because file-level pruning skips
|
||||
// files at or below the cursor. Every file this region produces after the publish
|
||||
// therefore carries a sequence strictly above that allocation.
|
||||
let files_before_flush = region
|
||||
.version()
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.keys().copied())
|
||||
.collect::<std::collections::HashSet<_>>();
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Flush(RegionFlushRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let post_publish_version = region.version();
|
||||
let post_publish_files = post_publish_version
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.values())
|
||||
.filter(|file| !files_before_flush.contains(&file.meta_ref().file_id))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
!post_publish_files.is_empty(),
|
||||
"the queued write must have been flushed"
|
||||
);
|
||||
for file in post_publish_files {
|
||||
let sequence = file
|
||||
.meta_ref()
|
||||
.sequence
|
||||
.map(|sequence| sequence.get())
|
||||
.expect("a flushed file carries an admission barrier");
|
||||
assert!(
|
||||
sequence > boundary,
|
||||
"a post-publish file must stay above the published boundary (cursor), \
|
||||
file sequence: {sequence}, boundary: {boundary}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An end of staging whose commit may have landed freezes its payload — and with it the
|
||||
/// boundary `B` it publishes — and returns the region to `Staging`. Ordinary and bulk writes
|
||||
/// must be refused until the retry completes: an admitted write could be attributed a sequence
|
||||
/// at or below `B`, read back as a commit watermark `C >= B` before the published files are
|
||||
/// visible, and a later reader would prune the files the retry publishes as already consumed.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_staging_exit_rejects_writes_while_end_commit_pending() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let faults = DeltaFaults::default();
|
||||
let mut env = TestEnv::with_prefix("staging-exit-end-commit-pending")
|
||||
.await
|
||||
.with_mock_layer(faults.layer());
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
|
||||
let region_id = RegionId::new(1024, 0);
|
||||
let request = CreateRequestBuilder::new().build();
|
||||
let schema = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// One visible flush, then rows written during staging that stay in the memtable: the exit
|
||||
// publishes at `last_sequence + 1` and keeps them.
|
||||
put_range(&engine, region_id, &schema, (0, 3)).await;
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Flush(RegionFlushRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
enter_staging(&engine, region_id).await;
|
||||
put_range(&engine, region_id, &schema, (3, 5)).await;
|
||||
|
||||
// A file imported from a source region gives the exit an edit to publish. Its rows use
|
||||
// their own key range so the row count of the scan below is unambiguous.
|
||||
let source_region_id = RegionId::new(1024, 1);
|
||||
engine
|
||||
.handle_request(
|
||||
source_region_id,
|
||||
RegionRequest::Create(CreateRequestBuilder::new().build()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
put_range(&engine, source_region_id, &schema, (20, 22)).await;
|
||||
flush_region(&engine, source_region_id, None).await;
|
||||
let imported = first_file(&engine.get_region(source_region_id).unwrap()).await;
|
||||
engine
|
||||
.handle_request(
|
||||
source_region_id,
|
||||
RegionRequest::Close(RegionCloseRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
submit_staging_edit(
|
||||
&engine,
|
||||
region_id,
|
||||
imported.clone(),
|
||||
float_range_expr("field_0", 0., 100.).as_json_str().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let last_sequence_before_exit = region.version_control.current().last_sequence;
|
||||
|
||||
// The commit lands but its response is lost, so the region keeps the payload to retry with
|
||||
// and goes back to `Staging`.
|
||||
faults.lose_next_response();
|
||||
let response = engine
|
||||
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.is_invalid_transition(), "{response:?}");
|
||||
assert!(
|
||||
region.is_staging(),
|
||||
"a failed exit must keep the region staging"
|
||||
);
|
||||
assert!(
|
||||
region.staging_end_pending(),
|
||||
"a commit that may have landed must leave the retry pending"
|
||||
);
|
||||
assert_eq!(
|
||||
last_sequence_before_exit,
|
||||
region.version_control.current().last_sequence,
|
||||
"a failed exit must not publish its boundary in memory"
|
||||
);
|
||||
|
||||
// The write is refused with the error of the pending commit. It is not queued: the region
|
||||
// is `Staging` again, so nothing would release such a queue.
|
||||
let err = engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Put(RegionPutRequest {
|
||||
rows: Rows {
|
||||
schema: schema.clone(),
|
||||
rows: build_rows(5, 6),
|
||||
},
|
||||
hint: None,
|
||||
partition_expr_version: None,
|
||||
skip_wal: false,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(StatusCode::RegionBusy, err.status_code());
|
||||
assert_eq!(RetryHint::Retryable, err.retry_hint());
|
||||
assert!(
|
||||
err.to_string().contains("waits for a retry"),
|
||||
"the write must be refused by the pending end commit, got: {err}"
|
||||
);
|
||||
assert_eq!(
|
||||
last_sequence_before_exit,
|
||||
region.version_control.current().last_sequence,
|
||||
"the refused write must not be attributed a sequence at or below the frozen boundary"
|
||||
);
|
||||
|
||||
// The retry re-sends the frozen payload, which publishes the imported file at `B`.
|
||||
engine
|
||||
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!region.staging_end_pending(),
|
||||
"a committed retry must drop the pending end commit"
|
||||
);
|
||||
assert_eq!(
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable),
|
||||
region.state(),
|
||||
"the retry must release the region to its writable state"
|
||||
);
|
||||
let boundary = last_sequence_before_exit;
|
||||
// The exit's admission `B` is above the boundary and is what the retry proves idempotent:
|
||||
// replaying the frozen payload cannot publish a second admission.
|
||||
assert_eq!(
|
||||
last_sequence_before_exit + 1,
|
||||
region.version_control.current().committed_sequence
|
||||
);
|
||||
assert!(
|
||||
region
|
||||
.version()
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.keys())
|
||||
.any(|file_id| *file_id == imported.file_id),
|
||||
"the file the retry published must be visible"
|
||||
);
|
||||
// 3 flushed rows + 2 staged rows + 2 imported rows.
|
||||
assert_eq!(
|
||||
7,
|
||||
count_rows(&engine, region_id).await,
|
||||
"the staged file and rows of the retried publish must be counted"
|
||||
);
|
||||
|
||||
// Writes are admitted again, strictly above the published boundary.
|
||||
put_range(&engine, region_id, &schema, (5, 7)).await;
|
||||
assert!(
|
||||
region.version_control.current().last_sequence > boundary,
|
||||
"a write after the publish must be attributed a sequence above the boundary, \
|
||||
last_sequence: {}, boundary: {}",
|
||||
region.version_control.current().last_sequence,
|
||||
boundary
|
||||
);
|
||||
}
|
||||
|
||||
/// Every staged edit must be published at the exit boundary, even when several staged edits
|
||||
/// added files at different barriers. The persisted action list keeps the metadata /
|
||||
/// partition actions in order and applies the final merged edit exactly once, so a reopen
|
||||
/// replays the exit boundary for all staged files instead of restoring a stale sequence from
|
||||
/// an original edit (which would leave a file at or below a cursor that never consumed it).
|
||||
#[tokio::test]
|
||||
async fn test_staging_exit_reopen_applies_boundary_to_every_staged_edit() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let partition_expr = float_range_expr("field_0", 0., 100.).as_json_str().unwrap();
|
||||
let mut env = TestEnv::new().await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
|
||||
let region_id = RegionId::new(1024, 0);
|
||||
let request = CreateRequestBuilder::new().build();
|
||||
let column_schemas = rows_schema(&request);
|
||||
let table_dir = request.table_dir.clone();
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(0, 3),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Flush(RegionFlushRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::EnterStaging(EnterStagingRequest {
|
||||
partition_directive: StagingPartitionDirective::UpdatePartitionExpr(
|
||||
partition_expr.clone(),
|
||||
),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// Rows written during staging stay in the staging memtable; staged files are imported
|
||||
// one edit at a time, so the staging layout holds several distinct files.
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(3, 5),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
// A source region provides the files that staging imports.
|
||||
let source_region_id = RegionId::new(1024, 1);
|
||||
engine
|
||||
.handle_request(
|
||||
source_region_id,
|
||||
RegionRequest::Create(CreateRequestBuilder::new().build()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for (start, end) in [(10, 13), (13, 15)] {
|
||||
put_rows(
|
||||
&engine,
|
||||
source_region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(start, end),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
flush_region(&engine, source_region_id, None).await;
|
||||
}
|
||||
let source_files = engine
|
||||
.get_region(source_region_id)
|
||||
.unwrap()
|
||||
.manifest_ctx
|
||||
.manifest()
|
||||
.await
|
||||
.files
|
||||
.values()
|
||||
.map(|file| file.as_ref().clone())
|
||||
.collect::<Vec<_>>();
|
||||
engine
|
||||
.handle_request(
|
||||
source_region_id,
|
||||
RegionRequest::Close(RegionCloseRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
// Each imported file is added by its own staged edit, so the staging layout holds files
|
||||
// that were admitted at different barriers.
|
||||
for file in source_files {
|
||||
submit_staging_edit(&engine, region_id, file, partition_expr.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
// Two distinct staged files, each added by its own staged edit at its own barrier.
|
||||
let staged_files = {
|
||||
let manager = region.manifest_ctx.manifest_manager.read().await;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
manager
|
||||
.staging_manifest()
|
||||
.unwrap()
|
||||
.files
|
||||
.values()
|
||||
.filter(|file| seen.insert(file.file_id))
|
||||
.take(2)
|
||||
.map(|file| file.as_ref().clone())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(2, staged_files.len(), "need two distinct staged files");
|
||||
for file in &staged_files {
|
||||
submit_staging_edit(&engine, region_id, file.clone(), partition_expr.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let last_sequence_before_exit = region.version_control.current().last_sequence;
|
||||
// The exit re-marks every staged file at the holder's admission `B`, which is one above the
|
||||
// allocator, but it records no boundary of its own.
|
||||
let exit_admission = last_sequence_before_exit + 1;
|
||||
|
||||
engine
|
||||
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader)
|
||||
.await
|
||||
.unwrap();
|
||||
for file in &staged_files {
|
||||
assert_eq!(
|
||||
Some(exit_admission),
|
||||
file_sequence(®ion, file.file_id),
|
||||
"the in-memory publish must re-mark every staged file at the admission"
|
||||
);
|
||||
}
|
||||
|
||||
// Replaying the persisted action list must agree with the in-memory publish: the merged
|
||||
// edit is applied exactly once and after every metadata action, so no original edit can
|
||||
// overwrite the per-file substitution with its own stale value.
|
||||
reopen_region(&engine, region_id, table_dir, true, Default::default()).await;
|
||||
let reopened = engine.get_region(region_id).unwrap();
|
||||
for file in &staged_files {
|
||||
assert_eq!(
|
||||
Some(exit_admission),
|
||||
file_sequence(&reopened, file.file_id),
|
||||
"every staged edit must carry the exit admission after a reopen"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_apply_staging_manifest_revalidates_after_close_during_read() {
|
||||
use object_store::layers::mock;
|
||||
|
||||
@@ -142,6 +142,8 @@ async fn test_engine_truncate_region_basic_with_format(flat_format: bool) {
|
||||
assert_eq!(expected, batches.pretty_print().unwrap());
|
||||
}
|
||||
|
||||
/// A truncation removes rows owned by the region; the rows it keeps keep their own
|
||||
/// numbers, so the region records no sequence boundary.
|
||||
#[tokio::test]
|
||||
async fn test_engine_put_data_after_truncate() {
|
||||
test_engine_put_data_after_truncate_with_format(false).await;
|
||||
@@ -306,6 +308,9 @@ async fn test_engine_truncate_after_flush_with_format(flat_format: bool) {
|
||||
assert_eq!(expected, batches.pretty_print().unwrap());
|
||||
}
|
||||
|
||||
/// `Truncate::Unflushed` discards unflushed rows through a flush-shaped edit
|
||||
/// (`handle_manifest_discard_unflushed_action`); the rows it keeps keep their own
|
||||
/// numbers, so no sequence boundary is recorded.
|
||||
#[tokio::test]
|
||||
async fn test_engine_truncate_reopen() {
|
||||
test_engine_truncate_reopen_with_format(false).await;
|
||||
@@ -561,6 +566,122 @@ async fn test_engine_discard_unflushed_with_format(flat_format: bool) {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_discard_unflushed_reopen_keeps_committed_watermark() {
|
||||
let mut env = TestEnv::with_prefix("discard-unflushed-reopen-watermark").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let request = CreateRequestBuilder::new().build();
|
||||
let table_dir = request.table_dir.clone();
|
||||
let column_schemas = rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Persist the first batch and leave the second one in the memtable and the WAL.
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(0, 3),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Flush(RegionFlushRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: column_schemas.clone(),
|
||||
rows: build_rows(3, 6),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let before = region.version_control.current();
|
||||
// The discard drops the rows above the flushed frontier and moves the frontier to the
|
||||
// discarded sequence. The rows that stay keep their own numbers, so no sequence
|
||||
// boundary is published.
|
||||
let boundary = before.committed_sequence + 1;
|
||||
let discarded_sequence = before.committed_sequence;
|
||||
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Truncate(RegionTruncateRequest::Unflushed),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let version = region.version();
|
||||
assert_eq!(discarded_sequence, version.flushed_sequence);
|
||||
|
||||
// A Flow checkpoint at `B` may already be durable, so the boundary must survive the
|
||||
// reopen together with a commit watermark of at least `B`.
|
||||
let engine = env.reopen_engine(engine, MitoConfig::default()).await;
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Open(RegionOpenRequest {
|
||||
engine: String::new(),
|
||||
table_dir,
|
||||
path_type: PathType::Bare,
|
||||
options: HashMap::default(),
|
||||
skip_wal_replay: false,
|
||||
checkpoint: None,
|
||||
requirements: Default::default(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
engine
|
||||
.set_region_role(region_id, RegionRole::Leader)
|
||||
.unwrap();
|
||||
|
||||
let region = engine.get_region(region_id).unwrap();
|
||||
let recovered = region.version_control.current();
|
||||
assert!(
|
||||
recovered.committed_sequence >= discarded_sequence,
|
||||
"the recovered commit watermark must stay at or above the discarded sequence: {} < {}",
|
||||
recovered.committed_sequence,
|
||||
discarded_sequence
|
||||
);
|
||||
// The flushed frontier keeps the value the WAL and the manifest name: the boundary is
|
||||
// published above it, not by forging it.
|
||||
assert_eq!(
|
||||
discarded_sequence, recovered.version.flushed_sequence,
|
||||
"the recover must not forge the flushed frontier"
|
||||
);
|
||||
|
||||
// The first write after the reopen must not reuse the sequence a checkpoint consumed.
|
||||
put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: column_schemas,
|
||||
rows: build_rows(6, 8),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
region.version_control.current().last_sequence > boundary,
|
||||
"a write after the reopen must be attributed a sequence above the boundary, \
|
||||
last_sequence: {}, boundary: {}",
|
||||
region.version_control.current().last_sequence,
|
||||
boundary
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_engine_discard_unflushed_skip_wal() {
|
||||
let mut env = TestEnv::with_prefix("discard-unflushed-skip-wal").await;
|
||||
|
||||
+21
-3
@@ -347,8 +347,13 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
/// The caller's incremental cursor cannot be trusted any more.
|
||||
///
|
||||
/// The message keeps the stable `sequence range cursor invalid:` prefix the
|
||||
/// enterprise incremental flow matches on to fall back to a full rebuild,
|
||||
/// and the historical `STALE_CURSOR` token for existing log matchers.
|
||||
#[snafu(display(
|
||||
"STALE_CURSOR: incremental query stale, region: {}, given_seq: {}, min_readable_seq: {}, retry_hint: FALLBACK_FULL_RECOMPUTE",
|
||||
"sequence range cursor invalid: STALE_CURSOR: incremental query stale, region: {}, given_seq: {}, min_readable_seq: {}, retry_hint: FALLBACK_FULL_RECOMPUTE",
|
||||
region_id,
|
||||
given_seq,
|
||||
min_readable_seq
|
||||
@@ -375,8 +380,15 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
/// The region cannot prove that an exact `(min, max]` sequence read is
|
||||
/// possible over its current files.
|
||||
///
|
||||
/// Shares the stable `exact sequence range unavailable:` prefix with
|
||||
/// [Self::RegionSequenceDomainBroken]; both mean "exactness is not
|
||||
/// provable" to callers that must fall back, even though they keep
|
||||
/// different status codes.
|
||||
#[snafu(display(
|
||||
"SEQUENCE_RANGE_UNSUPPORTED: exact sequence-range read unsupported, region: {}, min_seq: {}, max_seq: {}, reason: {}, retry_hint: FALLBACK_MEMTABLE_ONLY_OR_FULL_RECOMPUTE",
|
||||
"exact sequence range unavailable: SEQUENCE_RANGE_UNSUPPORTED: exact sequence-range read unsupported, region: {}, min_seq: {}, max_seq: {}, reason: {}, retry_hint: FALLBACK_MEMTABLE_ONLY_OR_FULL_RECOMPUTE",
|
||||
region_id,
|
||||
min_seq,
|
||||
max_seq,
|
||||
@@ -391,8 +403,14 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
/// A selected file carries rows from a foreign sequence domain and has no
|
||||
/// admission barrier, so exactness cannot be proven at all.
|
||||
///
|
||||
/// Shares the stable `exact sequence range unavailable:` prefix with
|
||||
/// [Self::SequenceRangeUnsupported] so a caller can classify it without
|
||||
/// depending on the (unchanged) status code.
|
||||
#[snafu(display(
|
||||
"region {} is unusable for sequence reads: file {} declares region {}",
|
||||
"exact sequence range unavailable: region {} cannot prove exact sequence-range reads: file {} declares region {} and carries no admission barrier, retry_hint: FALLBACK_FULL_RECOMPUTE",
|
||||
region_id,
|
||||
file_id,
|
||||
file_region_id
|
||||
|
||||
@@ -1013,6 +1013,10 @@ impl MemtableSstWriter {
|
||||
primary_key_min,
|
||||
primary_key_max,
|
||||
preserve_row_sequence,
|
||||
// A flush encodes this region's own rows, so it substitutes no file-level
|
||||
// constant over the column. (The `preserve_row_sequence = false` writer override is
|
||||
// a row-level rewrite inside the region's own domain and states no bound.)
|
||||
substituted_up_to: None,
|
||||
format: sst_info.format.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -922,7 +922,9 @@ mod tests {
|
||||
{"region_id":4402341478400,"file_id":"34b6ebb9-b8a5-4a4b-b744-56f67defad02","time_range":[{"value":1451609210000,"unit":"Millisecond"},{"value":1451609520000,"unit":"Millisecond"}],"level":0,"file_size":100}
|
||||
]
|
||||
}"#;
|
||||
let _ = serde_json::from_str::<RegionEdit>(region_edit).unwrap();
|
||||
// An edit written before this build must still deserialize.
|
||||
let legacy_edit: RegionEdit = serde_json::from_str(region_edit).unwrap();
|
||||
assert_eq!(None, legacy_edit.flushed_entry_id);
|
||||
|
||||
let region_edit = r#"{
|
||||
"flushed_entry_id":10,
|
||||
|
||||
@@ -780,6 +780,25 @@ impl RegionManifestManager {
|
||||
(!self.staged.actions.actions.is_empty()).then_some(&self.staged.actions)
|
||||
}
|
||||
|
||||
/// Returns whether an end commit of the staged actions may have been written, so a retry
|
||||
/// has to commit the same payload (see [Self::commit_staged]).
|
||||
pub(crate) fn staged_attempt_pending(&self) -> bool {
|
||||
self.staged.attempted.is_some()
|
||||
}
|
||||
|
||||
/// Replaces the staged actions with `merged`, the single payload the end commit persists.
|
||||
///
|
||||
/// An exit that changes the sequence domain merges the staged edits, allocates a boundary
|
||||
/// and re-marks the files it publishes. A retry must neither merge again nor allocate a
|
||||
/// second boundary, so the merged payload becomes the staged one: [Self::commit_staged]
|
||||
/// persists it once and, when the write may have landed, keeps its bytes for the retry.
|
||||
///
|
||||
/// The staged view stays: the merged payload adds the same files, so the manifest with the
|
||||
/// staged actions applied does not change.
|
||||
pub(crate) fn replace_staged_actions(&mut self, merged: RegionMetaActionList) {
|
||||
self.staged.actions = merged;
|
||||
}
|
||||
|
||||
/// Stages `action_list` in memory.
|
||||
fn stage(&mut self, action_list: RegionMetaActionList) -> Result<()> {
|
||||
if self.staged.attempted.is_some() {
|
||||
|
||||
@@ -12,10 +12,13 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::json;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::manifest::action::{
|
||||
RegionCheckpoint, RegionManifest, RegionMetaAction, RegionMetaActionList,
|
||||
RegionCheckpoint, RegionManifest, RegionMetaAction, RegionMetaActionList, TruncateKind,
|
||||
};
|
||||
use crate::sst::file::FileMeta;
|
||||
|
||||
@@ -48,6 +51,26 @@ fn test_file_only_manifest_compatibility() {
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(Some(8), edit.committed_sequence);
|
||||
// The fixture predates `substituted_up_to`. An absent cut means no row of the file was
|
||||
// substituted, which is what an older writer's output means.
|
||||
assert_eq!(
|
||||
vec![None, None],
|
||||
edit.files_to_add
|
||||
.iter()
|
||||
.map(|f| f.substituted_up_to)
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
// A cut is optional on the wire: encoding a file without one stays readable by an
|
||||
// older writer, and a zero cut (a column that never carried a per-row number) survives
|
||||
// the round trip.
|
||||
let encoded = serde_json::to_value(&edit.files_to_add[0]).unwrap();
|
||||
assert!(encoded.get("substituted_up_to").is_none());
|
||||
for cut in [0, 7] {
|
||||
let mut file = encoded.clone();
|
||||
file["substituted_up_to"] = json!(cut);
|
||||
let decoded: FileMeta = serde_json::from_value(file).unwrap();
|
||||
assert_eq!(Some(cut), decoded.substituted_up_to);
|
||||
}
|
||||
let encoded = String::from_utf8(actions.encode().unwrap()).unwrap();
|
||||
assert!(!encoded.contains("table_compaction") && !encoded.contains("extensions"));
|
||||
let mut manifest: serde_json::Value = serde_json::from_str(MANIFEST).unwrap();
|
||||
@@ -92,6 +115,102 @@ fn test_decoded_row_group_size_is_optional_in_manifests() {
|
||||
assert_eq!(file, serde_json::from_value::<FileMeta>(encoded).unwrap());
|
||||
}
|
||||
|
||||
/// The fixture test above only asserted `FileMeta`. The actions that carry it aged with the
|
||||
/// same format, so decode the legacy bytes into the current action types, assert the fields
|
||||
/// those types still keep, and round-trip them: an older writer's manifest must stay readable
|
||||
/// here, and what this build writes must stay readable to it.
|
||||
#[test]
|
||||
fn test_legacy_edit_truncate_and_manifest_round_trip() {
|
||||
let actions = RegionMetaActionList::decode(EDIT.as_bytes()).unwrap();
|
||||
let RegionMetaAction::Edit(edit) = &actions.actions[0] else {
|
||||
panic!("expected edit")
|
||||
};
|
||||
assert_eq!(Some(5), edit.flushed_entry_id);
|
||||
assert_eq!(Some(8), edit.flushed_sequence);
|
||||
assert_eq!(Some(8), edit.committed_sequence);
|
||||
assert_eq!(Some(Duration::from_secs(3600)), edit.compaction_time_window);
|
||||
assert_eq!(None, edit.timestamp_ms);
|
||||
assert!(edit.files_to_remove.is_empty());
|
||||
// WAL recovery postdates the fixture: an absent flatten decodes to "nothing to change"
|
||||
// rather than to evidence this build silently drops.
|
||||
assert_eq!(None, edit.wal_recovery.pending_tails);
|
||||
assert_eq!(None, edit.wal_recovery.handoff_floor);
|
||||
assert_eq!(
|
||||
actions,
|
||||
RegionMetaActionList::decode(&actions.encode().unwrap()).unwrap()
|
||||
);
|
||||
|
||||
// A truncate of the same era: the untagged kind is told apart by its fields, and the
|
||||
// entry id / sequence pair is the only thing a truncate-all records.
|
||||
let legacy_truncate = json!({"actions": [{"Truncate": {
|
||||
"region_id": 4294967297u64,
|
||||
"truncated_entry_id": 5,
|
||||
"truncated_sequence": 8
|
||||
}}]});
|
||||
let decoded =
|
||||
RegionMetaActionList::decode(&serde_json::to_vec(&legacy_truncate).unwrap()).unwrap();
|
||||
let RegionMetaAction::Truncate(truncate) = &decoded.actions[0] else {
|
||||
panic!("expected truncate")
|
||||
};
|
||||
assert_eq!(RegionId::new(1, 1), truncate.region_id);
|
||||
assert_eq!(None, truncate.timestamp_ms);
|
||||
assert_eq!(
|
||||
TruncateKind::All {
|
||||
truncated_entry_id: 5,
|
||||
truncated_sequence: 8,
|
||||
},
|
||||
truncate.kind
|
||||
);
|
||||
assert_eq!(
|
||||
decoded,
|
||||
RegionMetaActionList::decode(&decoded.encode().unwrap()).unwrap()
|
||||
);
|
||||
|
||||
// A partial truncate lists the files it removes, and the substituted cut a file states
|
||||
// survives the round trip like every other `FileMeta` field.
|
||||
let mut legacy_file = serde_json::from_str::<serde_json::Value>(EDIT).unwrap()["actions"][0]
|
||||
["Edit"]["files_to_add"][1]
|
||||
.clone();
|
||||
legacy_file["substituted_up_to"] = json!(6);
|
||||
let partial_truncate = json!({"actions": [{"Truncate": {
|
||||
"region_id": 4294967297u64,
|
||||
"files_to_remove": [legacy_file]
|
||||
}}]});
|
||||
let decoded =
|
||||
RegionMetaActionList::decode(&serde_json::to_vec(&partial_truncate).unwrap()).unwrap();
|
||||
let RegionMetaAction::Truncate(truncate) = &decoded.actions[0] else {
|
||||
panic!("expected truncate")
|
||||
};
|
||||
let TruncateKind::Partial { files_to_remove } = &truncate.kind else {
|
||||
panic!("expected partial truncate")
|
||||
};
|
||||
assert_eq!(1, files_to_remove.len());
|
||||
assert_eq!(Some(6), files_to_remove[0].substituted_up_to);
|
||||
assert_eq!(Some(8), files_to_remove[0].sequence.map(|seq| seq.get()));
|
||||
assert_eq!(
|
||||
decoded,
|
||||
RegionMetaActionList::decode(&decoded.encode().unwrap()).unwrap()
|
||||
);
|
||||
|
||||
// The manifest is decoded on its own, not only as a checkpoint payload: the entry id and
|
||||
// the sequence it states are what recovery starts from.
|
||||
let manifest = RegionManifest::decode(MANIFEST.as_bytes()).unwrap();
|
||||
assert_eq!(12, manifest.manifest_version);
|
||||
assert_eq!(5, manifest.flushed_entry_id);
|
||||
assert_eq!(8, manifest.flushed_sequence);
|
||||
assert_eq!(Some(8), manifest.committed_sequence);
|
||||
assert_eq!(None, manifest.truncated_entry_id);
|
||||
assert_eq!(
|
||||
Some(Duration::from_secs(3600)),
|
||||
manifest.compaction_time_window
|
||||
);
|
||||
assert!(manifest.files.is_empty());
|
||||
assert_eq!(
|
||||
manifest,
|
||||
RegionManifest::decode(&serde_json::to_vec(&manifest).unwrap()).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case("table_compaction")]
|
||||
#[case("extensions")]
|
||||
|
||||
@@ -37,6 +37,7 @@ pub(crate) mod series_candidate;
|
||||
pub(crate) mod series_reader;
|
||||
pub mod series_scan;
|
||||
pub mod stream;
|
||||
pub(crate) mod substituted_rows;
|
||||
pub(crate) mod unordered_scan;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -43,13 +43,14 @@ use datatypes::value::timestamp_to_scalar_value;
|
||||
use futures::StreamExt;
|
||||
use mito_codec::row_converter::{SortField, build_primary_key_codec_with_fields};
|
||||
use partition::expr::PartitionExpr;
|
||||
use partition::overlap::associate_from_to;
|
||||
use smallvec::SmallVec;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef};
|
||||
use store_api::region_engine::{PartitionRange, RegionScannerRef};
|
||||
use store_api::storage::{
|
||||
ColumnId, RegionId, ScanRequest, SequenceNumber, SequenceRange, TimeSeriesDistribution,
|
||||
TimeSeriesRowSelector,
|
||||
ColumnId, CursorShard, RegionId, ScanRequest, SequenceNumber, SequenceRange,
|
||||
TimeSeriesDistribution, TimeSeriesRowSelector,
|
||||
};
|
||||
use table::predicate::{Predicate, build_time_range_predicate, extract_time_range_from_expr};
|
||||
use tokio::sync::{Semaphore, mpsc};
|
||||
@@ -74,6 +75,10 @@ use crate::read::read_columns::ReadColumns;
|
||||
use crate::read::seq_scan::SeqScan;
|
||||
use crate::read::series_scan::SeriesScan;
|
||||
use crate::read::stream::ScanBatchStream;
|
||||
use crate::read::substituted_rows::{
|
||||
ObservedPartitionExprs, ObservedPartitionExprsRef, SubstitutedRowsAccumulator,
|
||||
SubstitutedRowsAccumulatorRef, SubstitutedSequenceCut,
|
||||
};
|
||||
use crate::read::unordered_scan::UnorderedScan;
|
||||
use crate::read::{BoxedRecordBatchStream, RecordBatch};
|
||||
use crate::region::options::MergeMode;
|
||||
@@ -88,7 +93,7 @@ use crate::sst::index::fulltext_index::applier::builder::FulltextIndexApplierBui
|
||||
use crate::sst::index::inverted_index::applier::InvertedIndexApplierRef;
|
||||
use crate::sst::index::inverted_index::applier::builder::InvertedIndexApplierBuilder;
|
||||
use crate::sst::parquet::Json2RewriteTargets;
|
||||
use crate::sst::parquet::file_range::PreFilterMode;
|
||||
use crate::sst::parquet::file_range::{CreatorSliceCursors, PreFilterMode};
|
||||
use crate::sst::parquet::reader::ReaderMetrics;
|
||||
use crate::sst::primary_key::PrimaryKeyRangeMapper;
|
||||
|
||||
@@ -472,8 +477,40 @@ impl ScanRegion {
|
||||
}
|
||||
|
||||
/// Scans by series.
|
||||
///
|
||||
/// # A physical row-sequence read is refused here
|
||||
///
|
||||
/// `ScanRequest::read_row_sequence` asks a reader to keep a foreign file's own
|
||||
/// `__sequence` column and to hide the rows a substitution produced, which takes both
|
||||
/// the creator's cursor slice ([`ScanInput::foreign_row_sequence_filter`]) and the
|
||||
/// file's substituted cut ([`ScanInput::substituted_sequence_cut`]). Neither is applied
|
||||
/// on this path: the per-series readers filter a file by this region's own `(C, H]` and
|
||||
/// its trust decision alone, and the legacy distributor reads the same files through
|
||||
/// the plain flat reader (`SeqScan::build_flat_partition_range_read`) without any of
|
||||
/// it. Both would hand Flow rows it has already consumed, or compare a foreign file's
|
||||
/// numbers with a bound of another domain, so the combination is refused instead of
|
||||
/// silently approximated.
|
||||
///
|
||||
/// This costs nothing: Flow's incremental delta — the only reader that asks for the
|
||||
/// physical column — is planned as an ordered flat read and never selects this
|
||||
/// distribution. The refusal reuses the shared "exactness is not provable" contract, so
|
||||
/// the caller falls back exactly as it does for every other unprovable range.
|
||||
#[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
|
||||
pub(crate) async fn series_scan(self) -> Result<SeriesScan> {
|
||||
if self.request.read_row_sequence {
|
||||
return SequenceRangeUnsupportedSnafu {
|
||||
region_id: self.region_id(),
|
||||
min_seq: self.request.memtable_min_sequence.unwrap_or_default(),
|
||||
max_seq: self.request.memtable_max_sequence.unwrap_or_default(),
|
||||
reason: "the PerSeries distribution cannot carry a physical row-sequence read: \
|
||||
its series readers apply neither the creator's cursor slice nor the \
|
||||
substituted cut of an adopted file, so rows the caller already consumed \
|
||||
would be delivered again and a foreign sequence domain would be compared \
|
||||
with this region's bounds; plan the incremental delta as a flat ordered read"
|
||||
.to_string(),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
let experimental_series_scan_v2 = self.experimental_series_scan_v2;
|
||||
let input = self.scan_input().await?;
|
||||
Ok(SeriesScan::new(input, experimental_series_scan_v2))
|
||||
@@ -566,6 +603,20 @@ impl ScanRegion {
|
||||
self.version.options.merge_mode(),
|
||||
);
|
||||
|
||||
// A read that may cross an invalid boundary must see the memtable rows whose
|
||||
// sequence already sits at or below its cursor: those are exactly the rows whose
|
||||
// windows the cursor can no longer explain, and this read is what rediscovers
|
||||
// them. A lower bound here would hide them, so the windows would never be
|
||||
// reported and a repair would advance the cursor past them. This matches the
|
||||
// file-level exemption of the same mode ([`exact_sequence_range`]), which prunes
|
||||
// by admission barrier instead of filtering rows by sequence. The upper bound
|
||||
// stays: it is the frozen `H` the caller's result must stay below.
|
||||
let memtable_min_sequence = if self.request.read_across_invalid_boundary {
|
||||
None
|
||||
} else {
|
||||
self.request.memtable_min_sequence
|
||||
};
|
||||
|
||||
for m in memtables {
|
||||
// check if memtable is empty by reading stats.
|
||||
let Some((start, end)) = m.stats().time_range() else {
|
||||
@@ -581,7 +632,7 @@ impl ScanRegion {
|
||||
RangesOptions::default()
|
||||
.with_predicate(predicate.clone())
|
||||
.with_sequence(SequenceRange::new(
|
||||
self.request.memtable_min_sequence,
|
||||
memtable_min_sequence,
|
||||
self.request.memtable_max_sequence,
|
||||
))
|
||||
.with_pre_filter_mode(filter_mode),
|
||||
@@ -648,6 +699,9 @@ impl ScanRegion {
|
||||
.flatten(),
|
||||
)
|
||||
.with_sequence_range(sequence_range)
|
||||
.with_read_across_invalid_boundary(self.request.read_across_invalid_boundary)
|
||||
.with_read_row_sequence(self.request.read_row_sequence)
|
||||
.with_creator_cursor_shards(self.request.creator_cursor_shards.clone())
|
||||
.with_query_stat_counters(self.query_stat_counters);
|
||||
#[cfg(feature = "enterprise")]
|
||||
let input = if !self.request.skip_sst_files
|
||||
@@ -743,6 +797,26 @@ impl ScanRegion {
|
||||
expr.collect_column_names(&mut extra_col_names);
|
||||
}
|
||||
|
||||
// A physical-sequence read evaluates the creator cursor slices of an adopted file
|
||||
// row by row, so the columns those expressions reference must be read too. They are
|
||||
// internal: the output projection happens after the flat batch
|
||||
// (`ConvertBatchStream::convert`), so adding them does not change the result schema.
|
||||
if self.request.read_row_sequence
|
||||
&& let Some(shards) = &self.request.creator_cursor_shards
|
||||
{
|
||||
for shard in shards.values().flatten() {
|
||||
let Some(identity) = shard.partition_expr.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(Some(expr)) = PartitionExpr::from_json_str(identity) else {
|
||||
// An unreadable identity keeps the conservative file-level bound; the
|
||||
// reader reports the same conclusion when it compiles the slices.
|
||||
continue;
|
||||
};
|
||||
expr.collect_column_names(&mut extra_col_names);
|
||||
}
|
||||
}
|
||||
|
||||
if !extra_col_names.is_empty() {
|
||||
for col in &metadata.column_metadatas {
|
||||
if extra_col_names.remove(&col.column_schema.name) && !seen.contains(&col.column_id)
|
||||
@@ -1023,6 +1097,25 @@ pub struct ScanInput {
|
||||
/// carries an explicit exact range. When set, SST readers apply the same
|
||||
/// `(checkpoint, upper_bound]` row-level filter as memtables.
|
||||
pub(crate) sequence_range: Option<SequenceRange>,
|
||||
/// Whether this read may cross an invalid boundary: every selected SST's rows
|
||||
/// are virtualized at the file's admission barrier.
|
||||
pub(crate) read_across_invalid_boundary: bool,
|
||||
/// Whether this scan reads the physical `__sequence` of a foreign file and hides
|
||||
/// the rows a substitution produced ([`ScanRequest::read_row_sequence`]).
|
||||
pub(crate) read_row_sequence: bool,
|
||||
/// Cursor slices of every creator region ([`ScanRequest::creator_cursor_shards`]).
|
||||
/// A file this region adopted from another one is bounded by the least advanced cursor
|
||||
/// slice of its creator that may hold its rows, because its numbers belong to the
|
||||
/// creator's domain.
|
||||
creator_cursor_shards: Option<Arc<BTreeMap<u64, Vec<CursorShard>>>>,
|
||||
/// Collects the timestamp ranges of the rows this scan substituted. `None` turns the
|
||||
/// whole mechanism off, which is what every reader but Flow's incremental delta
|
||||
/// uses.
|
||||
pub(crate) substituted_row_ranges: Option<SubstitutedRowsAccumulatorRef>,
|
||||
/// Collects the `(region, partition expression)` pairs the files this scan read state.
|
||||
/// `None` turns the mechanism off, like [`Self::substituted_row_ranges`]: only the read
|
||||
/// that consumes a `(region, expression)` cursor can say which of them it consumed.
|
||||
pub(crate) observed_slices: Option<ObservedPartitionExprsRef>,
|
||||
/// Whether this scan is for compaction.
|
||||
pub(crate) compaction: bool,
|
||||
/// Max number of compaction inputs decoded concurrently ahead of the merge.
|
||||
@@ -1093,6 +1186,11 @@ impl ScanInput {
|
||||
explain_flat_format: false,
|
||||
snapshot_sequence: None,
|
||||
sequence_range: None,
|
||||
read_across_invalid_boundary: false,
|
||||
read_row_sequence: false,
|
||||
creator_cursor_shards: None,
|
||||
substituted_row_ranges: None,
|
||||
observed_slices: None,
|
||||
compaction: false,
|
||||
compaction_read_parallelism: 1,
|
||||
json2_rewrite_targets: Arc::default(),
|
||||
@@ -1455,6 +1553,47 @@ impl ScanInputBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether this read may cross an invalid boundary.
|
||||
#[must_use]
|
||||
pub(crate) fn with_read_across_invalid_boundary(
|
||||
mut self,
|
||||
read_across_invalid_boundary: bool,
|
||||
) -> Self {
|
||||
self.input.read_across_invalid_boundary = read_across_invalid_boundary;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether this scan reads physical row sequences and hides substituted rows.
|
||||
///
|
||||
/// Turns the substituted-row collector on with it: the ranges it substitutes are the
|
||||
/// only thing that tells the caller which windows to recompute. It turns the
|
||||
/// observed-partition-expression collector on too, because this read is the one that
|
||||
/// consumes a `(region, expression)` cursor and the only one that can report which of
|
||||
/// them it read.
|
||||
#[must_use]
|
||||
pub(crate) fn with_read_row_sequence(mut self, read_row_sequence: bool) -> Self {
|
||||
self.input.read_row_sequence = read_row_sequence;
|
||||
self.input.substituted_row_ranges =
|
||||
read_row_sequence.then(|| Arc::new(SubstitutedRowsAccumulator::new()));
|
||||
self.input.observed_slices =
|
||||
read_row_sequence.then(|| Arc::new(ObservedPartitionExprs::new()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the cursor slices of the regions that created this region's files.
|
||||
///
|
||||
/// Only a physical-sequence read uses them: it bounds an adopted file by the least
|
||||
/// advanced cursor of the creator expression slices that may hold its rows, instead of
|
||||
/// comparing the creator's numbers against this region's own cursor.
|
||||
#[must_use]
|
||||
pub(crate) fn with_creator_cursor_shards(
|
||||
mut self,
|
||||
creator_cursor_shards: Option<Arc<BTreeMap<u64, Vec<CursorShard>>>>,
|
||||
) -> Self {
|
||||
self.input.creator_cursor_shards = creator_cursor_shards;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether this scan is for compaction.
|
||||
#[must_use]
|
||||
pub(crate) fn with_compaction(mut self, compaction: bool) -> Self {
|
||||
@@ -1694,6 +1833,17 @@ impl ScanInput {
|
||||
};
|
||||
let res = reader
|
||||
.expected_metadata(Some(self.mapper.metadata().clone()))
|
||||
// A read that may cross an invalid boundary virtualizes every row at the
|
||||
// file's barrier instead of trusting the file's own sequence column.
|
||||
.force_sequence_override(self.read_across_invalid_boundary)
|
||||
// Flow's incremental delta keeps the physical column of an adopted file and
|
||||
// hides the rows a substitution produced; every other read keeps the
|
||||
// barrier substitution.
|
||||
.read_row_sequence(self.read_row_sequence)
|
||||
// The reader splits the adopted file's rows by the creator slice each row
|
||||
// belongs to, so it needs the slices whose expression may hold rows of *this*
|
||||
// file. A file no slice covers keeps the fail-closed path instead.
|
||||
.creator_slice_cursors(self.creator_slice_cursors(file)?)
|
||||
.compaction(self.compaction)
|
||||
.pre_filter_mode(pre_filter_mode)
|
||||
.enable_predicate_prefilter(enable_predicate_prefilter)
|
||||
@@ -1892,6 +2042,230 @@ impl ScanInput {
|
||||
self.mapper.metadata()
|
||||
}
|
||||
|
||||
/// Returns the collector of the timestamp ranges this scan substituted, if it
|
||||
/// substitutes any.
|
||||
pub(crate) fn substituted_row_ranges(&self) -> Option<&SubstitutedRowsAccumulator> {
|
||||
self.substituted_row_ranges.as_deref()
|
||||
}
|
||||
|
||||
/// Returns a shared handle to the substituted-row collector of this scan.
|
||||
pub(crate) fn substituted_row_ranges_ref(&self) -> Option<SubstitutedRowsAccumulatorRef> {
|
||||
self.substituted_row_ranges.clone()
|
||||
}
|
||||
|
||||
/// Returns the collector of the `(region, partition expression)` pairs this scan read.
|
||||
pub(crate) fn observed_slices(&self) -> Option<&ObservedPartitionExprs> {
|
||||
self.observed_slices.as_deref()
|
||||
}
|
||||
|
||||
/// Returns a shared handle to the collector of the slices this scan read.
|
||||
pub(crate) fn observed_slices_ref(&self) -> Option<ObservedPartitionExprsRef> {
|
||||
self.observed_slices.clone()
|
||||
}
|
||||
|
||||
/// Returns the substituted cut `file` states for its own bytes, when this scan reads
|
||||
/// physical row sequences.
|
||||
///
|
||||
/// The cut is a statement about the file's **bytes**, not about who allocated the
|
||||
/// numbers in them, so it is applied to every file that states one. A **local** file
|
||||
/// carries a substitution as well: compaction substitutes a file-level constant for
|
||||
/// the rows of its foreign inputs and states the bound on its output
|
||||
/// ([`crate::sst::file::substituted_up_to_after_merge`]). Leaving those rows in the
|
||||
/// result delivers rows the caller already received once, because their numbers are
|
||||
/// not the numbers this region published either.
|
||||
///
|
||||
/// The file's `preserve_row_sequence` marker takes no part: it describes whether the
|
||||
/// *writer* kept per-row numbering, while an import (a repartition's staging apply
|
||||
/// included) only rewrites the handle's metadata and re-marks the file, leaving its
|
||||
/// bytes untouched. The cut is the only statement about which rows a substitution
|
||||
/// produced, so a re-marked file that still carries one is filtered by it.
|
||||
pub(crate) fn substituted_sequence_cut(
|
||||
&self,
|
||||
file: &FileHandle,
|
||||
) -> Option<SubstitutedSequenceCut> {
|
||||
if !self.read_row_sequence {
|
||||
return None;
|
||||
}
|
||||
// `None` means no row of the column was substituted; `Some(0)` means the column
|
||||
// carries no per-row numbering at all, so every row is substituted.
|
||||
file.meta_ref()
|
||||
.substituted_up_to
|
||||
.map(|cut| SubstitutedSequenceCut { cut })
|
||||
}
|
||||
|
||||
/// The row filter of a physical-sequence read of `file`: `(candidate creator cursor,
|
||||
/// +inf)`.
|
||||
///
|
||||
/// The numbers in an adopted file's column were allocated by the region that created
|
||||
/// it, so the only cursor that bounds them is the creator's — and even that one only
|
||||
/// inside the partition expression the file states, because the cursor is keyed by
|
||||
/// `(region, expression)`. Several expressions may be candidates for one file (a file
|
||||
/// that states none, or one spanning several), so the least advanced candidate bounds
|
||||
/// the file as a whole: re-reading a consumed row can be recovered from, silently
|
||||
/// dropping a live one cannot.
|
||||
///
|
||||
/// This is a **file-level** bound, not a per-row decision: it is the candidate
|
||||
/// selection of [`cursor_slice_may_hold_file_rows`] followed by one sequence range for
|
||||
/// the whole file, so a file whose rows belong to different expressions at different
|
||||
/// progress is read from the least advanced of them and may repeat rows of the others.
|
||||
///
|
||||
/// `None` means this scan has no cursor for the file's creator, or the file is not
|
||||
/// foreign at all; [`Self::foreign_row_sequence_filter`] is what a reader calls, and
|
||||
/// it fails closed instead of reading a foreign file without a creator cursor.
|
||||
///
|
||||
/// # Why the upper end is unbounded
|
||||
///
|
||||
/// No upper bound of the creator's domain survives adoption, so none is used here.
|
||||
/// The scan's own `H` is a number this region's sequence space issued; comparing it
|
||||
/// with the file's numbers silently drops live rows — a creator that has published
|
||||
/// `10..=12` while its cursor sits at `9` is filtered by `(9, 6]` when the holder's
|
||||
/// `H` is 6, and once the holder's cursor reaches the file's admission barrier the
|
||||
/// file is pruned as well, so those three rows are never delivered at all.
|
||||
///
|
||||
/// The two bounds that *would* be provable are not available to the reader:
|
||||
///
|
||||
/// * the creator's own `committed_sequence` is not carried by the handle — admission
|
||||
/// overwrites `FileMeta::sequence` with the holder's barrier
|
||||
/// (`handle_copy_region`/`handle_manifest`), so the value in it is this region's;
|
||||
/// * the maximum of the file's physical `__sequence` column would be provable from the
|
||||
/// file, but the manifest does not record it and deriving it costs a metadata fetch
|
||||
/// per foreign file on every round.
|
||||
///
|
||||
/// Unbounded above is therefore the conservative and provable choice: a row above the
|
||||
/// creator's cursor is a row that cursor has not consumed, and the creator's watermark
|
||||
/// advances exactly that cursor at the end of the round
|
||||
/// ([`crate::read::scan_util`] reports which slices were read), so the read is not
|
||||
/// repeated once the round commits. Rows of an adopted file were all committed before
|
||||
/// the file was admitted, so no reader can observe a "future" number this way either.
|
||||
pub(crate) fn creator_domain_sequence_range(
|
||||
&self,
|
||||
file: &FileHandle,
|
||||
) -> Result<Option<SequenceRange>> {
|
||||
if !self.read_row_sequence {
|
||||
return Ok(None);
|
||||
}
|
||||
// A physical-sequence read only exists inside an exact `(C, H]` delta. If this
|
||||
// scan could not prove one at all (`sequence_range` is `None`, e.g. a local file
|
||||
// whose barrier cannot be trusted), the foreign file fails closed like every other
|
||||
// uncertain case — but neither `C` nor `H` bounds *this* file's numbers, so the
|
||||
// range itself is not reused below.
|
||||
if self.sequence_range.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let meta = file.meta_ref();
|
||||
if meta.region_id == self.region_metadata().region_id {
|
||||
// This region allocated the numbers, so its own cursor already bounds them.
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(shards) = self
|
||||
.creator_cursor_shards
|
||||
.as_ref()
|
||||
.and_then(|shards| shards.get(&meta.region_id.as_u64()))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut cursor = None;
|
||||
for shard in shards {
|
||||
if cursor_slice_may_hold_file_rows(shard, meta)? {
|
||||
cursor = Some(
|
||||
cursor.map_or(shard.seq, |current: SequenceNumber| current.min(shard.seq)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(cursor.map(|min| SequenceRange::Gt { min }))
|
||||
}
|
||||
|
||||
/// The candidate creator cursor slices of `file`, as the reader compiles them:
|
||||
/// `(partition expression identity, last consumed sequence)` pairs whose expression
|
||||
/// may select a row of the file.
|
||||
///
|
||||
/// This is the same candidate selection as [`Self::creator_domain_sequence_range`]:
|
||||
/// the file-level bound it produces stays, and the reader uses the candidates to decide
|
||||
/// per row which cursor applies.
|
||||
fn creator_slice_cursors(&self, file: &FileHandle) -> Result<Option<CreatorSliceCursors>> {
|
||||
if !self.read_row_sequence || !self.is_foreign_file(file) {
|
||||
return Ok(None);
|
||||
}
|
||||
let meta = file.meta_ref();
|
||||
let Some(shards) = self
|
||||
.creator_cursor_shards
|
||||
.as_ref()
|
||||
.and_then(|shards| shards.get(&meta.region_id.as_u64()))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut cursors = Vec::new();
|
||||
for shard in shards {
|
||||
let Some(identity) = shard.partition_expr.as_ref() else {
|
||||
// A whole-domain cursor is the region-keyed statement of an older producer:
|
||||
// it applies to every row, so the least advanced cursor of the region is the
|
||||
// most precise answer available and the per-row split adds nothing.
|
||||
return Ok(None);
|
||||
};
|
||||
if cursor_slice_may_hold_file_rows(shard, meta)? {
|
||||
cursors.push((identity.clone(), shard.seq));
|
||||
}
|
||||
}
|
||||
if cursors.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(Arc::new(cursors)))
|
||||
}
|
||||
|
||||
/// Whether `file` was created by another region, i.e. its rows carry a number this
|
||||
/// region never allocated.
|
||||
pub(crate) fn is_foreign_file(&self, file: &FileHandle) -> bool {
|
||||
file.meta_ref().region_id != self.region_metadata().region_id
|
||||
}
|
||||
|
||||
/// The row filter a physical-sequence read applies to `file`.
|
||||
///
|
||||
/// `Ok(None)` means the file carries this region's own numbers (or this scan is not a
|
||||
/// physical-sequence read at all), so the scan's own `(C, H]` bounds it as it stands
|
||||
/// and the caller keeps its per-file trust decision.
|
||||
///
|
||||
/// A foreign file is filtered by `(creator cursor, +inf)`
|
||||
/// ([`Self::creator_domain_sequence_range`]), with **or without** a substituted cut in
|
||||
/// the file: its rows were numbered in the creator's domain, which this region's
|
||||
/// cursor does not bound. A file whose creator this scan has no cursor slice for fails
|
||||
/// closed instead of falling back to the holder's `(C, H]`: comparing two sequence
|
||||
/// domains silently drops live rows, and reading the file unfiltered delivers every
|
||||
/// already consumed row again on every round.
|
||||
///
|
||||
/// The corresponding selection rule lives in [`exact_sequence_range`]: a foreign file
|
||||
/// of a physical-sequence read is never pruned by this region's cursor, because
|
||||
/// `C >= admission barrier` says nothing about the creator's numbering.
|
||||
pub(crate) fn foreign_row_sequence_filter(
|
||||
&self,
|
||||
file: &FileHandle,
|
||||
) -> Result<Option<SequenceRange>> {
|
||||
if !self.read_row_sequence || !self.is_foreign_file(file) {
|
||||
return Ok(None);
|
||||
}
|
||||
match self.creator_domain_sequence_range(file)? {
|
||||
Some(range) => Ok(Some(range)),
|
||||
None => {
|
||||
let (min_seq, max_seq) = match self.sequence_range {
|
||||
Some(SequenceRange::GtLtEq { min, max }) => (min, max),
|
||||
Some(SequenceRange::Gt { min }) => (min, 0),
|
||||
Some(SequenceRange::LtEq { max }) => (0, max),
|
||||
None => (0, 0),
|
||||
};
|
||||
let meta = file.meta_ref();
|
||||
SequenceRangeUnsupportedSnafu {
|
||||
region_id: self.region_metadata().region_id,
|
||||
min_seq,
|
||||
max_seq,
|
||||
reason: format!(
|
||||
"the physical-sequence read of adopted file {} has no cursor slice of its creator region {}, so its rows cannot be split into consumed and live ones",
|
||||
meta.file_id, meta.region_id
|
||||
),
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn range_pre_filter_mode(&self, source_count: usize) -> PreFilterMode {
|
||||
if source_count <= 1 {
|
||||
// Duplicated rows in the same source is not a normal case and we don't provide
|
||||
@@ -2020,6 +2394,67 @@ fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `meta` **may** hold rows of the value domain the cursor slice `shard` was
|
||||
/// consumed in, i.e. whether `shard.seq` is one of the candidate cursors of this file.
|
||||
///
|
||||
/// This is a *file-level* selection, not a per-row decision. The caller takes the least
|
||||
/// advanced candidate cursor and bounds the whole file with it
|
||||
/// ([`ScanInput::creator_domain_sequence_range`]), which is what keeps the read safe: a row
|
||||
/// of a slice that was not selected is never re-read, and a row of a selected slice is only
|
||||
/// re-read. Making the decision per row instead would need the file's rows evaluated
|
||||
/// against each slice expression, which this reader does not do — the only per-row filter
|
||||
/// of a physical-sequence read is the sequence comparison in
|
||||
/// [`crate::read::scan_util::filter_flat_batch_by_sequence`].
|
||||
///
|
||||
/// The candidates are selected by comparing partition expressions, never by projecting them
|
||||
/// onto a numeric interval: an expression this build can represent may use operators
|
||||
/// (`<>`, `OR`, an iceberg hash, a non-integer value) that such a projection cannot
|
||||
/// express, and approximating one there is how a live slice stops being read.
|
||||
///
|
||||
/// * a whole-domain slice (`partition_expr: None`) is a candidate for every file;
|
||||
/// * a file that states no expression covers its region's complete value domain, so every
|
||||
/// slice of the region is a candidate — selecting only some would drop live rows;
|
||||
/// * otherwise the slice is a candidate when the two expressions can be satisfied by a
|
||||
/// common row, which is the overlap question the partition crate already answers for
|
||||
/// repartition planning (`partition::overlap::associate_from_to`, used the same way by
|
||||
/// `partition::subtask::create_subtasks`, `src/partition/src/subtask.rs:37`, over the
|
||||
/// [`Collider`] atomics of `partition::overlap::atomic_exprs_overlap`,
|
||||
/// `src/partition/src/overlap.rs:31`). It splits both expressions into atomic
|
||||
/// alternatives and normalizes their values in one collider, so the answer does not
|
||||
/// depend on how either expression is written;
|
||||
/// * an expression that cannot be analysed is a candidate as well: re-reading a consumed
|
||||
/// row is recoverable, dropping a live one is not.
|
||||
///
|
||||
/// [`Collider`]: partition::collider::Collider
|
||||
fn cursor_slice_may_hold_file_rows(
|
||||
shard: &CursorShard,
|
||||
meta: &crate::sst::file::FileMeta,
|
||||
) -> crate::error::Result<bool> {
|
||||
let Some(shard_expr) = shard.partition_expr.as_deref() else {
|
||||
return Ok(true);
|
||||
};
|
||||
// Decoding can only fail for a cursor this build did not produce (the query layer
|
||||
// validates the identity before it hands it to a scan), and the conservative reading
|
||||
// of an unknown domain is the creator's whole value domain.
|
||||
let Some(shard_expr) =
|
||||
PartitionExpr::from_json_str(shard_expr).context(InvalidPartitionExprSnafu {
|
||||
expr: shard_expr.to_string(),
|
||||
})?
|
||||
else {
|
||||
return Ok(true);
|
||||
};
|
||||
let Some(file_expr) = meta.partition_expr.as_ref() else {
|
||||
return Ok(true);
|
||||
};
|
||||
|
||||
let shard_exprs = [shard_expr];
|
||||
let file_exprs = [file_expr.as_ref().clone()];
|
||||
match associate_from_to(&shard_exprs, &file_exprs) {
|
||||
Ok(assoc) => Ok(assoc.first().is_some_and(|overlaps| !overlaps.is_empty())),
|
||||
Err(_) => Ok(true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the SST files for a scan and, when requested, determines whether
|
||||
/// the selected files support an exact sequence-range scan.
|
||||
///
|
||||
@@ -2033,12 +2468,50 @@ fn pre_filter_mode(append_mode: bool, merge_mode: MergeMode) -> PreFilterMode {
|
||||
/// proves Flow has already consumed the entire file, so such a file is excluded
|
||||
/// before the capability check. An unknown bound cannot prove this exclusion.
|
||||
///
|
||||
/// A foreign file is different: the parquet reader virtualizes every row to its
|
||||
/// target-local `FileMeta.sequence`. Consequently, a present sequence is the
|
||||
/// only trust requirement for a foreign file; its source marker is irrelevant.
|
||||
/// A foreign file without that barrier is retained as a failed-closed error so
|
||||
/// it cannot be mistaken for a local sequence domain. This check is performed
|
||||
/// even when another exact-range capability condition would return `None`.
|
||||
/// A foreign file is different: outside a physical-sequence read the parquet
|
||||
/// reader virtualizes every row to its target-local `FileMeta.sequence`.
|
||||
/// Consequently, a present sequence is the only trust requirement for a foreign
|
||||
/// file; its source marker is irrelevant. A foreign file without that barrier is
|
||||
/// retained as a failed-closed error so it cannot be mistaken for a local
|
||||
/// sequence domain. This check is performed even when another exact-range
|
||||
/// capability condition would return `None`.
|
||||
///
|
||||
/// That virtualization is also what makes the `C >= barrier` exclusion sound for a
|
||||
/// foreign file in those modes: every one of its rows reads as the barrier, so a
|
||||
/// barrier at or below `C` hides the whole file. A physical-sequence read
|
||||
/// (`read_row_sequence`) does not virtualize; it keeps the file's own numbers, which
|
||||
/// were issued in the *creator's* domain, so the barrier is nothing but an admission
|
||||
/// timestamp and `C >= barrier` proves nothing about them. Such a file is never
|
||||
/// excluded here — its rows are filtered by the creator's cursor instead
|
||||
/// ([`ScanInput::foreign_row_sequence_filter`]) — because excluding it would drop the
|
||||
/// live rows above that cursor for good.
|
||||
///
|
||||
/// The file's `preserve_row_sequence` marker does not gate a foreign file either
|
||||
/// way, here or when the reader picks the sequence column. It describes whether
|
||||
/// the file's *writer* kept per-row numbering, whereas an import (a repartition's
|
||||
/// staging apply included) only rewrites the handle's metadata and copies the
|
||||
/// bytes verbatim, so it says nothing about the column a physical-sequence read
|
||||
/// finds ([`ScanInput::substituted_sequence_cut`] is what a substitution leaves
|
||||
/// behind). A source file stating `preserve_row_sequence = false` with no cut
|
||||
/// therefore belongs to the plateau of a source table whose option is off: Flow
|
||||
/// never reads one, because it only asks for this mode on a region whose
|
||||
/// `preserve_row_sequence` option is on, and the option requirement below denies
|
||||
/// every other region an exact range. Such a file fails closed there instead of
|
||||
/// being read as an ordinary file.
|
||||
///
|
||||
/// A **local** file can state that substitution fact as well: a merge substitutes a
|
||||
/// file-level constant for the rows of its foreign inputs (and of a legacy all-zero
|
||||
/// one) and records the bound it produced
|
||||
/// ([`crate::sst::file::substituted_up_to_after_merge`]), so a local file may carry
|
||||
/// `preserve_row_sequence = false` **and** a cut. A physical-sequence read hides the
|
||||
/// rows at or below the cut and reports their time windows
|
||||
/// ([`ScanInput::substituted_sequence_cut`]), and every row above the cut carries a
|
||||
/// number this region allocated, which the reader's own `(C, H]` row filter bounds per
|
||||
/// row (`read/scan_util.rs`). Such a file is attributable and must not deny the region
|
||||
/// its exact range — one merge of an adopted file, repeated by every round of
|
||||
/// compaction, would otherwise fail every later delta closed for good. Outside that
|
||||
/// mode nothing hides the substituted rows, so a local file with neither the marker nor
|
||||
/// a cut (or with a cut but no physical-sequence read) keeps failing closed.
|
||||
pub(crate) fn exact_sequence_range(
|
||||
request: &ScanRequest,
|
||||
version: &crate::region::version::Version,
|
||||
@@ -2047,6 +2520,75 @@ pub(crate) fn exact_sequence_range(
|
||||
return Ok((Vec::new(), None));
|
||||
}
|
||||
|
||||
if request.read_across_invalid_boundary {
|
||||
// A read that may cross an invalid boundary prunes at file granularity only.
|
||||
// A file whose admission barrier is at or below the cursor was fully consumed,
|
||||
// so it cannot contribute to the missing windows; a file without a barrier
|
||||
// cannot be proven disjoint, so it is kept (conservative). Row-level exactness
|
||||
// is deliberately not requested: returning no `SequenceRange` keeps every row
|
||||
// of the selected files, and the caller only needs their timestamps. The
|
||||
// result may therefore be a superset of the affected windows, which is safe
|
||||
// because those windows are recomputed.
|
||||
let after = request.memtable_min_sequence;
|
||||
let time_index = version.metadata.time_index_column();
|
||||
let unit = time_index
|
||||
.column_schema
|
||||
.data_type
|
||||
.as_timestamp()
|
||||
.expect("Time index must have timestamp-compatible type")
|
||||
.unit();
|
||||
let time_range =
|
||||
build_time_range_predicate(&time_index.column_schema.name, unit, &request.filters);
|
||||
let files = version
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.values())
|
||||
.filter(|file| file_in_range(file, &time_range))
|
||||
.filter(|file| match (after, file.meta_ref().sequence) {
|
||||
(Some(after), Some(sequence)) => sequence.get() > after,
|
||||
_ => true,
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
// A file without an admission barrier cannot be pruned: keeping it would
|
||||
// silently degrade discovery into a full scan, which is forbidden. Report the
|
||||
// incomplete candidate set instead, using the shared "exactness unavailable"
|
||||
// vocabulary so the caller can decide whether to fail or accept a superset.
|
||||
let unprunable = files
|
||||
.iter()
|
||||
.filter(|file| file.meta_ref().sequence.is_none())
|
||||
.count();
|
||||
if unprunable > 0 {
|
||||
return SequenceRangeUnsupportedSnafu {
|
||||
region_id: version.metadata.region_id,
|
||||
min_seq: after.unwrap_or_default(),
|
||||
max_seq: after.unwrap_or_default(),
|
||||
reason: format!(
|
||||
"recovery discovery cannot prove its candidate file set is complete: {unprunable} of {} selected files carry no admission barrier, so it would read the whole region",
|
||||
files.len()
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
if files.is_empty() && version.memtables.is_empty() {
|
||||
// An empty candidate set is reported, never silently treated as "no
|
||||
// window": the caller decides whether to accept it or advance instead.
|
||||
// A non-empty memtable is a candidate too: its rows carry sequences the
|
||||
// region itself assigned, so discovery must read it (the scan keeps no
|
||||
// row-level range here, which only widens the discovered window set).
|
||||
return SequenceRangeUnsupportedSnafu {
|
||||
region_id: version.metadata.region_id,
|
||||
min_seq: after.unwrap_or_default(),
|
||||
max_seq: after.unwrap_or_default(),
|
||||
reason: "recovery discovery found no candidate file above the cursor, so it cannot report an empty window set as complete"
|
||||
.to_string(),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
return Ok((files, None));
|
||||
}
|
||||
|
||||
let time_index = version.metadata.time_index_column();
|
||||
let unit = time_index
|
||||
.column_schema
|
||||
@@ -2070,7 +2612,17 @@ pub(crate) fn exact_sequence_range(
|
||||
.filter(|file| file_in_range(file, &time_range))
|
||||
{
|
||||
let meta = file.meta_ref();
|
||||
// A physical-sequence read of a foreign file keeps the creator's own numbers, and
|
||||
// its admission barrier belongs to this region's domain: it says when the holder
|
||||
// published the file, not how far the creator's numbering has been consumed.
|
||||
// `C >= barrier` therefore proves nothing about those rows, and excluding the file
|
||||
// here would drop the live rows above the creator's cursor for good (they would
|
||||
// never be read again, because this exclusion repeats on every round). Its rows are
|
||||
// filtered by the creator's cursor instead.
|
||||
let keeps_foreign_sequence_domain =
|
||||
request.read_row_sequence && meta.region_id != version.metadata.region_id;
|
||||
let selected = (!request.exact_sequence_range
|
||||
|| keeps_foreign_sequence_domain
|
||||
|| min.is_none_or(|min| meta.sequence.is_none_or(|sequence| sequence.get() > min)))
|
||||
&& match (sst_min_sequence, meta.sequence) {
|
||||
(Some(min_sequence), Some(file_sequence)) => file_sequence > min_sequence,
|
||||
@@ -2093,8 +2645,17 @@ pub(crate) fn exact_sequence_range(
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
// A local file whose marker is unset is still attributable when it states
|
||||
// the cut a substitution left in its bytes: the physical-sequence read
|
||||
// hides the rows at or below the cut and reports their windows, and every
|
||||
// row above it carries this region's numbering, which the reader's own row
|
||||
// filter bounds. Only a local file with neither the marker nor such a cut
|
||||
// leaves rows this read cannot attribute.
|
||||
let cut_hides_substituted_rows =
|
||||
request.read_row_sequence && meta.substituted_up_to.is_some();
|
||||
if meta.region_id == version.metadata.region_id
|
||||
&& !file.is_effective_target_sequence_trusted(version.metadata.region_id)
|
||||
&& !cut_hides_substituted_rows
|
||||
&& meta.sequence.is_none_or(|barrier| barrier.get() > min)
|
||||
{
|
||||
// Match the capability helper's short-circuit behavior: once
|
||||
@@ -3839,6 +4400,101 @@ mod tests {
|
||||
assert!(exact_sequence_range(&request, &version).is_err());
|
||||
}
|
||||
|
||||
/// A physical-sequence read admits an imported file whatever its `preserve_row_sequence`
|
||||
/// marker says: an import (a repartition's staging apply included) only re-marks the
|
||||
/// handle and copies the bytes, so the column and the file's own cut still describe the
|
||||
/// rows. The missing-barrier error stays, and the marker keeps gating ordinary reads.
|
||||
#[test]
|
||||
fn test_exact_sequence_selection_admits_imported_file_for_physical_read() {
|
||||
use std::num::NonZeroU64;
|
||||
|
||||
use crate::test_util::new_noop_file_purger;
|
||||
|
||||
let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
|
||||
let mutable = crate::memtable::time_partition::TimePartitions::new(
|
||||
metadata.clone(),
|
||||
Arc::new(crate::test_util::memtable_util::EmptyMemtableBuilder::default()),
|
||||
0,
|
||||
None,
|
||||
);
|
||||
let request = ScanRequest {
|
||||
exact_sequence_range: true,
|
||||
read_row_sequence: true,
|
||||
memtable_min_sequence: Some(5),
|
||||
memtable_max_sequence: Some(10),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for (sequence, marked, expected_range, expected_error) in [
|
||||
(NonZeroU64::new(6), false, true, false),
|
||||
(NonZeroU64::new(6), true, true, false),
|
||||
(None, false, false, true),
|
||||
(None, true, false, true),
|
||||
] {
|
||||
let version = crate::region::version::VersionBuilder::new(
|
||||
metadata.clone(),
|
||||
mutable.new_with_part_duration(None, None),
|
||||
)
|
||||
.options(crate::region::options::RegionOptions {
|
||||
preserve_row_sequence: true,
|
||||
..Default::default()
|
||||
})
|
||||
.add_files(
|
||||
new_noop_file_purger(),
|
||||
[FileMeta {
|
||||
region_id: RegionId::new(1, 2),
|
||||
sequence,
|
||||
preserve_row_sequence: marked,
|
||||
..Default::default()
|
||||
}]
|
||||
.into_iter(),
|
||||
)
|
||||
.build();
|
||||
let result = exact_sequence_range(&request, &version);
|
||||
if expected_error {
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(crate::error::Error::RegionSequenceDomainBroken { .. })
|
||||
),
|
||||
"a foreign file without an admission barrier must stay failed closed"
|
||||
);
|
||||
} else {
|
||||
let (files, range) = result.unwrap();
|
||||
assert_eq!(1, files.len());
|
||||
assert_eq!(expected_range, range.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
// A region whose option is off cannot serve an exact range at all, so the excluded
|
||||
// plateau (a source file with `preserve_row_sequence = false` and no cut) still fails
|
||||
// closed there instead of being read as an ordinary file.
|
||||
let version = crate::region::version::VersionBuilder::new(
|
||||
metadata,
|
||||
mutable.new_with_part_duration(None, None),
|
||||
)
|
||||
.options(crate::region::options::RegionOptions {
|
||||
preserve_row_sequence: false,
|
||||
..Default::default()
|
||||
})
|
||||
.add_files(
|
||||
new_noop_file_purger(),
|
||||
[FileMeta {
|
||||
region_id: RegionId::new(1, 2),
|
||||
sequence: NonZeroU64::new(6),
|
||||
..Default::default()
|
||||
}]
|
||||
.into_iter(),
|
||||
)
|
||||
.build();
|
||||
let (files, range) = exact_sequence_range(&request, &version).unwrap();
|
||||
assert_eq!(1, files.len());
|
||||
assert_eq!(
|
||||
None, range,
|
||||
"a region that does not preserve row sequences keeps denying the exact range"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_parallel_flat_source_stops_after_receiver_dropped() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
@@ -47,6 +47,7 @@ use crate::read::last_row::FlatLastTimestampSelector;
|
||||
use crate::read::pruner::PartitionPruner;
|
||||
use crate::read::range::{RangeMeta, RowGroupIndex};
|
||||
use crate::read::scan_region::StreamContext;
|
||||
use crate::read::substituted_rows::filter_flat_batch_by_substituted_sequence;
|
||||
use crate::read::{BoxedRecordBatchStream, ScannerMetrics};
|
||||
use crate::sst::file::{FileTimeRange, RegionFileId};
|
||||
use crate::sst::index::bloom_filter::applier::BloomFilterIndexApplyMetrics;
|
||||
@@ -1534,8 +1535,11 @@ pub(crate) async fn scan_flat_file_ranges(
|
||||
///
|
||||
/// `file_sequence_trusted` is the per-file trust decision. Foreign reader
|
||||
/// batches have already been virtualized to the target-local file barrier, so
|
||||
/// they are filtered using the effective batch sequence. Local untrusted files
|
||||
/// pass through because exact capability excludes them before row filtering.
|
||||
/// they are filtered using the effective batch sequence. A local file whose marker is
|
||||
/// unset is left untouched only when it has no substituted cut: the exact-range
|
||||
/// capability excludes such a file from the region's range before row filtering. A
|
||||
/// local file that states a cut is filtered like a trusted one, because its cut already
|
||||
/// hid the rows a substitution produced.
|
||||
pub(crate) fn filter_flat_batch_by_sequence(
|
||||
record_batch: RecordBatch,
|
||||
sequence_range: Option<SequenceRange>,
|
||||
@@ -1612,14 +1616,86 @@ pub fn build_flat_file_range_scan_stream(
|
||||
part_metrics.inc_build_reader_cost(build_cost);
|
||||
|
||||
let may_compat = range.compat_batch();
|
||||
let file_sequence_trusted = range
|
||||
.file_handle()
|
||||
.is_effective_target_sequence_trusted(stream_ctx.input.region_metadata().region_id);
|
||||
// The substituted cut of a physical-sequence read: rows at or below it carry a
|
||||
// number a substitution produced, so they are hidden and their time range is
|
||||
// reported.
|
||||
let substituted_cut = stream_ctx.input.substituted_row_ranges().and_then(|windows| {
|
||||
stream_ctx
|
||||
.input
|
||||
.substituted_sequence_cut(range.file_handle())
|
||||
.map(|cut| (cut, windows))
|
||||
});
|
||||
// Which rows of this file this round has already consumed, and which ones it
|
||||
// may still report:
|
||||
//
|
||||
// * a local file's rows were admitted by this region, so the scan's own `(C, H]`
|
||||
// applies as it stands; the rows a substitution produced in it are taken out by
|
||||
// the cut above, which is why that cut is not "foreign files only";
|
||||
// * a foreign file's rows were numbered in the creator's domain, which this
|
||||
// region's cursor does not bound. The creator's cursor slice the file belongs
|
||||
// to is the filter a physical-sequence read (`read_row_sequence`) asks for,
|
||||
// and it applies with or without a substituted cut: without it the file would
|
||||
// be read whole and every already consumed row delivered again. A foreign
|
||||
// file whose creator has no cursor slice fails closed.
|
||||
let (file_sequence_range, file_sequence_trusted) =
|
||||
match stream_ctx.input.foreign_row_sequence_filter(range.file_handle())? {
|
||||
Some(creator_range) => (Some(creator_range), true),
|
||||
None => (
|
||||
stream_ctx.input.sequence_range,
|
||||
// A local file whose marker is unset is attributable above its
|
||||
// substituted cut: the cut was applied just above (it is only
|
||||
// computed when a physical-sequence read hides those rows and
|
||||
// reports their windows), and what is left carries this region's
|
||||
// own numbering. Skipping the row filter here would deliver rows
|
||||
// the caller already consumed, which is exactly the row the
|
||||
// exact-range capability promises not to do.
|
||||
range
|
||||
.file_handle()
|
||||
.is_effective_target_sequence_trusted(
|
||||
stream_ctx.input.region_metadata().region_id,
|
||||
)
|
||||
|| substituted_cut.is_some(),
|
||||
),
|
||||
};
|
||||
|
||||
// Which `(region, partition expression)` this read observed: the creator of
|
||||
// the file and the expression the file states for its own rows. A cursor entry
|
||||
// keyed by a region alone cannot say which part of that region's domain a
|
||||
// round consumed, so the owner of the cursor learns the narrower key from the
|
||||
// read itself. The expression travels as its own identity, never as an
|
||||
// interval projected out of it: a projection would have to guess a comparison
|
||||
// semantics for every operator it cannot express, and a file that states no
|
||||
// expression at all is the only case that covers the complete domain.
|
||||
//
|
||||
// A local file is reported too: its numbers belong to this region's own
|
||||
// domain, and a reader that reported only adopted files would leave a
|
||||
// region's slices unobservable as soon as compaction rewrote them into local
|
||||
// ones, which would stall the cursor instead of advancing it.
|
||||
if let Some(observed) = stream_ctx.input.observed_slices() {
|
||||
let meta = range.file_handle().meta_ref();
|
||||
observed.record(meta.region_id.as_u64(), meta.partition_expr.as_deref())?;
|
||||
}
|
||||
|
||||
while let Some(record_batch) = reader.next_batch().await? {
|
||||
// Hides the rows a substitution produced and reports the windows they
|
||||
// occupy, so the caller recomputes exactly those windows.
|
||||
let record_batch = match substituted_cut {
|
||||
Some((cut, windows)) => {
|
||||
let Some(record_batch) = filter_flat_batch_by_substituted_sequence(
|
||||
record_batch,
|
||||
Some(cut),
|
||||
windows,
|
||||
)?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
record_batch
|
||||
}
|
||||
None => record_batch,
|
||||
};
|
||||
let Some(record_batch) = filter_flat_batch_by_sequence(
|
||||
record_batch,
|
||||
stream_ctx.input.sequence_range,
|
||||
file_sequence_range,
|
||||
file_sequence_trusted,
|
||||
)? else {
|
||||
continue;
|
||||
|
||||
@@ -50,6 +50,7 @@ use crate::read::scan_util::{
|
||||
scan_flat_file_ranges, scan_flat_mem_ranges, should_split_flat_batches_for_merge,
|
||||
};
|
||||
use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream, spawn_compact_stream};
|
||||
use crate::read::substituted_rows::SubstitutedRowRangesStream;
|
||||
use crate::read::{BoxedRecordBatchStream, ScannerMetrics, scan_util};
|
||||
use crate::region::options::MergeMode;
|
||||
use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE;
|
||||
@@ -414,10 +415,19 @@ impl SeqScan {
|
||||
metrics,
|
||||
);
|
||||
|
||||
Ok(Box::pin(RecordBatchStreamWrapper::new(
|
||||
let stream: SendableRecordBatchStream = Box::pin(RecordBatchStreamWrapper::new(
|
||||
input.mapper.output_schema(),
|
||||
Box::pin(record_batch_stream),
|
||||
)))
|
||||
));
|
||||
// The rows this scan hid and the slices it read (a physical-sequence read only)
|
||||
// travel with the result, so the caller learns which windows it has to recompute
|
||||
// and which cursor slices it consumed.
|
||||
Ok(SubstitutedRowRangesStream::wrap(
|
||||
stream,
|
||||
input.substituted_row_ranges_ref(),
|
||||
input.observed_slices_ref(),
|
||||
input.region_metadata().region_id.as_u64(),
|
||||
))
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
|
||||
@@ -465,6 +465,11 @@ async fn build_uncached_series_partition_range(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only this region's own `(C, H]` and the file's trust decision bound these
|
||||
// rows: a physical row-sequence read needs the creator's cursor slice and the
|
||||
// substituted cut of an adopted file as well, which this per-series path cannot
|
||||
// apply, so such a read is refused when the scan is built
|
||||
// (`ScanRegion::series_scan`) instead of being approximated here.
|
||||
let stream = scan_series_file_ranges(
|
||||
part_metrics.clone(),
|
||||
ranges,
|
||||
|
||||
@@ -668,10 +668,14 @@ impl SeriesScan {
|
||||
metrics,
|
||||
);
|
||||
|
||||
Ok(Box::pin(RecordBatchStreamWrapper::new(
|
||||
let stream: SendableRecordBatchStream = Box::pin(RecordBatchStreamWrapper::new(
|
||||
input.mapper.output_schema(),
|
||||
Box::pin(record_batch_stream),
|
||||
)))
|
||||
));
|
||||
// No substitution and no observed slices travel with this result: the per-series
|
||||
// path never reads physical row sequences (`ScanRegion::series_scan` refuses
|
||||
// `ScanRequest::read_row_sequence`), so there is no proof to carry.
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Rows a substitution produced, which a scan drops instead of delivering.
|
||||
//!
|
||||
//! A region that adopted a file from another region cannot tell, row by row, which of
|
||||
//! the adopted rows its incremental consumers already saw: an assigned barrier makes
|
||||
//! all of them look published by the edit. A scan that asks for the physical sequence
|
||||
//! column (`ScanRequest::read_row_sequence`) therefore drops every row whose number
|
||||
//! is at or below the file's own substituted cut
|
||||
//! ([`FileMeta::substituted_up_to`](crate::sst::file::FileMeta::substituted_up_to)) and
|
||||
//! reports the timestamps of the dropped rows here. Flow recomputes exactly the windows
|
||||
//! that intersect them instead of double counting the rows it did see.
|
||||
//!
|
||||
//! The same read reports which `(region, partition expression)` pairs it read at all
|
||||
//! ([`ObservedPartitionExprs`], one [`ObservedPartitionExpr`] per pair): a cursor entry keyed
|
||||
//! by a region alone cannot say which part of the region's value domain a round consumed, so
|
||||
//! the owner of the cursor has to learn it from the read that consumed it.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use common_recordbatch::adapter::{
|
||||
ObservedPartitionExpr, RecordBatchMetrics, SubstitutedRange, SubstitutedRowRanges,
|
||||
};
|
||||
use common_recordbatch::{OrderOption, RecordBatchStream, SendableRecordBatchStream};
|
||||
use common_time::Timestamp;
|
||||
use common_time::timestamp::TimeUnit;
|
||||
use datatypes::arrow::array::BooleanArray;
|
||||
use datatypes::arrow::compute::filter_record_batch;
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use datatypes::schema::SchemaRef;
|
||||
use futures::Stream;
|
||||
use partition::expr::PartitionExpr;
|
||||
use snafu::ResultExt;
|
||||
use store_api::storage::SequenceNumber;
|
||||
|
||||
use crate::error::{ComputeArrowSnafu, Result, SerializePartitionExprSnafu};
|
||||
use crate::read::timestamp_array_to_i64_slice;
|
||||
use crate::sst::parquet::flat_format::{sequence_column_index, time_index_column_index};
|
||||
|
||||
/// The substituted cut a file states for its own bytes.
|
||||
///
|
||||
/// Rows whose physical sequence is at or below `cut` carry a number a substitution
|
||||
/// produced, so a scan that reads physical sequences drops them and reports their
|
||||
/// timestamps.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct SubstitutedSequenceCut {
|
||||
/// Inclusive upper bound of the substituted numbers.
|
||||
pub(crate) cut: SequenceNumber,
|
||||
}
|
||||
|
||||
/// Accumulates the timestamp ranges of the rows a scan substituted.
|
||||
///
|
||||
/// Shared by every reader of one scan: the ranges are keyed in milliseconds since the
|
||||
/// Unix epoch and merged when read, so the caller sees a sorted, non-overlapping set of
|
||||
/// `[start, end]` ranges per region.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct SubstitutedRowsAccumulator {
|
||||
/// Raw `(start_millis, end_millis)` ranges, both inclusive.
|
||||
ranges: Mutex<Vec<(i64, i64)>>,
|
||||
}
|
||||
|
||||
pub(crate) type SubstitutedRowsAccumulatorRef = Arc<SubstitutedRowsAccumulator>;
|
||||
|
||||
impl SubstitutedRowsAccumulator {
|
||||
/// Creates an empty accumulator.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Records that the rows in `[start_millis, end_millis]` were substituted.
|
||||
pub(crate) fn record(&self, start_millis: i64, end_millis: i64) {
|
||||
self.lock().push((start_millis, end_millis));
|
||||
}
|
||||
|
||||
/// Locks the recorded ranges.
|
||||
///
|
||||
/// A panic while the ranges are held cannot leave them inconsistent (a push is the
|
||||
/// only mutation), so a poisoned lock is recovered instead of failing the scan.
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<(i64, i64)>> {
|
||||
self.ranges.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Returns the merged ranges of `region_id`, sorted and non-overlapping.
|
||||
pub(crate) fn entries(&self, region_id: u64) -> Vec<SubstitutedRowRanges> {
|
||||
let mut ranges = self.lock().clone();
|
||||
if ranges.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
ranges.sort_unstable();
|
||||
let mut merged: Vec<(i64, i64)> = Vec::with_capacity(ranges.len());
|
||||
for (start, end) in ranges {
|
||||
match merged.last_mut() {
|
||||
// Both ends are inclusive, so `start == last_end + 1` is still contiguous.
|
||||
Some(last) if start <= last.1.saturating_add(1) => {
|
||||
last.1 = last.1.max(end);
|
||||
}
|
||||
_ => merged.push((start, end)),
|
||||
}
|
||||
}
|
||||
vec![SubstitutedRowRanges {
|
||||
region_id,
|
||||
ranges: merged
|
||||
.into_iter()
|
||||
.map(|(start, end)| SubstitutedRange {
|
||||
start_millis: start,
|
||||
end_millis: end,
|
||||
})
|
||||
.collect(),
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates the partition expressions of the regions a physical-sequence read
|
||||
/// observed, i.e. one [`ObservedPartitionExpr`] per `(region, partition expression)` pair.
|
||||
///
|
||||
/// Shared by every reader of one scan and deduplicated on insert, so the caller sees each
|
||||
/// pair once however many files (and partitions) stated it. A pair states the creator of
|
||||
/// the file that was read and the identity of the partition expression that file states
|
||||
/// for its own rows; a file that states none observed its region's complete value domain.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ObservedPartitionExprs {
|
||||
slices: Mutex<BTreeSet<ObservedPartitionExpr>>,
|
||||
}
|
||||
|
||||
pub(crate) type ObservedPartitionExprsRef = Arc<ObservedPartitionExprs>;
|
||||
|
||||
impl ObservedPartitionExprs {
|
||||
/// Creates an empty accumulator.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Records that rows of `(region_id, partition_expr)` were read.
|
||||
///
|
||||
/// The expression is recorded as the identity the cursor format carries
|
||||
/// (`PartitionExpr::as_json_str()`), canonicalized first because that is the form
|
||||
/// `PartitionExpr::from_json_str` hands back: an identity recorded here then compares
|
||||
/// equal to the cursor entry of the same expression instead of only to a byte-identical
|
||||
/// rewrite of it. `None` is the region's complete value domain, which is what a file
|
||||
/// stating no expression observed.
|
||||
pub(crate) fn record(
|
||||
&self,
|
||||
region_id: u64,
|
||||
partition_expr: Option<&PartitionExpr>,
|
||||
) -> Result<()> {
|
||||
let partition_expr = partition_expr
|
||||
.map(|expr| expr.clone().canonicalize().as_json_str())
|
||||
.transpose()
|
||||
.context(SerializePartitionExprSnafu)?;
|
||||
// A poisoned lock cannot leave the set inconsistent (an insert is the only
|
||||
// mutation), so it is recovered instead of failing the scan.
|
||||
self.slices
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.insert(ObservedPartitionExpr::new(region_id, partition_expr));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the observed pairs, sorted and deduplicated.
|
||||
pub(crate) fn entries(&self) -> Vec<ObservedPartitionExpr> {
|
||||
self.slices
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the rows of `record_batch` whose physical sequence is at or below `cut`.
|
||||
///
|
||||
/// The batch must still carry the flat format's internal columns, i.e. this runs before
|
||||
/// any projection that drops them. Returns `None` when every row is substituted. The
|
||||
/// substituted rows' timestamp range is recorded in `ranges`, so the caller can report
|
||||
/// which time windows it has to recompute.
|
||||
pub(crate) fn filter_flat_batch_by_substituted_sequence(
|
||||
record_batch: RecordBatch,
|
||||
substituted: Option<SubstitutedSequenceCut>,
|
||||
ranges: &SubstitutedRowsAccumulator,
|
||||
) -> Result<Option<RecordBatch>> {
|
||||
let Some(SubstitutedSequenceCut { cut }) = substituted else {
|
||||
return Ok(Some(record_batch));
|
||||
};
|
||||
if record_batch.num_rows() == 0 {
|
||||
return Ok(Some(record_batch));
|
||||
}
|
||||
|
||||
let sequence_column = record_batch.column(sequence_column_index(record_batch.num_columns()));
|
||||
let sequences = sequence_column
|
||||
.as_any()
|
||||
.downcast_ref::<datatypes::arrow::array::UInt64Array>()
|
||||
.ok_or_else(|| {
|
||||
crate::error::InvalidRecordBatchSnafu {
|
||||
reason: "the sequence column of a flat batch must be UInt64".to_string(),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
// `Some(0)` is the file's own statement that its column carries no per-row numbering at
|
||||
// all (a legacy import), not a bound it only partly reaches: every row is substituted, even
|
||||
// when a producer left real numbers behind. Dropping all of them can only make the caller
|
||||
// recompute the whole file.
|
||||
let substituted_all = cut == 0;
|
||||
// `true` keeps the row: its number is above every substituted number, so this region never
|
||||
// manufactured it from a substitution.
|
||||
let keep = BooleanArray::from_iter(
|
||||
sequences
|
||||
.values()
|
||||
.iter()
|
||||
.map(|value| !substituted_all && *value > cut),
|
||||
);
|
||||
let keep_count = keep.true_count();
|
||||
if keep_count == record_batch.num_rows() {
|
||||
return Ok(Some(record_batch));
|
||||
}
|
||||
|
||||
record_substituted_time_range(&record_batch, &keep, ranges)?;
|
||||
if keep_count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let filtered = filter_record_batch(&record_batch, &keep).context(ComputeArrowSnafu)?;
|
||||
Ok(Some(filtered))
|
||||
}
|
||||
|
||||
/// Records the timestamp range of the rows `keep` rejects.
|
||||
fn record_substituted_time_range(
|
||||
record_batch: &RecordBatch,
|
||||
keep: &BooleanArray,
|
||||
ranges: &SubstitutedRowsAccumulator,
|
||||
) -> Result<()> {
|
||||
let time_index = record_batch.column(time_index_column_index(record_batch.num_columns()));
|
||||
let datatypes::arrow::datatypes::DataType::Timestamp(unit, _) = time_index.data_type() else {
|
||||
return crate::error::InvalidRecordBatchSnafu {
|
||||
reason: "the time index column of a flat batch must be a timestamp".to_string(),
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
let unit = to_time_unit(*unit);
|
||||
let values: &[i64] = timestamp_array_to_i64_slice(time_index);
|
||||
|
||||
let mut range: Option<(i64, i64)> = None;
|
||||
for (idx, keep_row) in keep.values().iter().enumerate() {
|
||||
if keep_row {
|
||||
continue;
|
||||
}
|
||||
let value = values[idx];
|
||||
range = Some(match range {
|
||||
Some((start, end)) => (start.min(value), end.max(value)),
|
||||
None => (value, value),
|
||||
});
|
||||
}
|
||||
let Some((start, end)) = range else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Report in milliseconds so a consumer that owns time windows can align them without
|
||||
// knowing this region's time unit. The start floors and the end ceils, which can only
|
||||
// widen the range: a caller recomputes a superset, never misses a substituted row.
|
||||
let start_millis = Timestamp::new(start, unit)
|
||||
.convert_to(TimeUnit::Millisecond)
|
||||
.map(|ts| ts.value())
|
||||
.unwrap_or(start);
|
||||
let end_millis = Timestamp::new(end, unit)
|
||||
.convert_to_ceil(TimeUnit::Millisecond)
|
||||
.map(|ts| ts.value())
|
||||
.unwrap_or(end);
|
||||
ranges.record(start_millis, end_millis);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Maps the arrow time unit of the time index column to the engine's.
|
||||
fn to_time_unit(unit: datatypes::arrow::datatypes::TimeUnit) -> TimeUnit {
|
||||
match unit {
|
||||
datatypes::arrow::datatypes::TimeUnit::Second => TimeUnit::Second,
|
||||
datatypes::arrow::datatypes::TimeUnit::Millisecond => TimeUnit::Millisecond,
|
||||
datatypes::arrow::datatypes::TimeUnit::Microsecond => TimeUnit::Microsecond,
|
||||
datatypes::arrow::datatypes::TimeUnit::Nanosecond => TimeUnit::Nanosecond,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a scan stream so its terminal metrics carry what the scan substituted and read.
|
||||
///
|
||||
/// Mirrors how a region reports its snapshot watermark: the proof travels with the
|
||||
/// result instead of a side channel, so a caller that stops reading early never
|
||||
/// observes a range set that belongs to rows it did not receive.
|
||||
pub(crate) struct SubstitutedRowRangesStream {
|
||||
stream: SendableRecordBatchStream,
|
||||
ranges: SubstitutedRowsAccumulatorRef,
|
||||
observed_slices: Option<ObservedPartitionExprsRef>,
|
||||
region_id: u64,
|
||||
}
|
||||
|
||||
impl SubstitutedRowRangesStream {
|
||||
/// Wraps `stream`, or returns it unchanged when the scan reads no physical sequences.
|
||||
pub(crate) fn wrap(
|
||||
stream: SendableRecordBatchStream,
|
||||
ranges: Option<SubstitutedRowsAccumulatorRef>,
|
||||
observed_slices: Option<ObservedPartitionExprsRef>,
|
||||
region_id: u64,
|
||||
) -> SendableRecordBatchStream {
|
||||
match ranges {
|
||||
Some(ranges) => Box::pin(Self {
|
||||
stream,
|
||||
ranges,
|
||||
observed_slices,
|
||||
region_id,
|
||||
}),
|
||||
None => stream,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RecordBatchStream for SubstitutedRowRangesStream {
|
||||
fn name(&self) -> &str {
|
||||
self.stream.name()
|
||||
}
|
||||
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.stream.schema()
|
||||
}
|
||||
|
||||
fn output_ordering(&self) -> Option<&[OrderOption]> {
|
||||
self.stream.output_ordering()
|
||||
}
|
||||
|
||||
fn metrics(&self) -> Option<RecordBatchMetrics> {
|
||||
let mut metrics = self.stream.metrics().unwrap_or_default();
|
||||
let substituted = self.ranges.entries(self.region_id);
|
||||
if !substituted.is_empty() {
|
||||
metrics.substituted_row_ranges = substituted;
|
||||
}
|
||||
if let Some(observed) = &self.observed_slices {
|
||||
let slices = observed.entries();
|
||||
if !slices.is_empty() {
|
||||
metrics.observed_slices = slices;
|
||||
}
|
||||
}
|
||||
Some(metrics)
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for SubstitutedRowRangesStream {
|
||||
type Item = common_recordbatch::error::Result<common_recordbatch::RecordBatch>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
Pin::new(&mut self.stream).poll_next(cx)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.stream.size_hint()
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@ use crate::read::scan_util::{
|
||||
scan_flat_mem_ranges,
|
||||
};
|
||||
use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream};
|
||||
use crate::read::substituted_rows::SubstitutedRowRangesStream;
|
||||
use crate::read::{ScannerMetrics, scan_util};
|
||||
|
||||
/// Scans a region without providing any output ordering guarantee.
|
||||
@@ -239,10 +240,19 @@ impl UnorderedScan {
|
||||
metrics,
|
||||
);
|
||||
|
||||
Ok(Box::pin(RecordBatchStreamWrapper::new(
|
||||
let stream: SendableRecordBatchStream = Box::pin(RecordBatchStreamWrapper::new(
|
||||
input.mapper.output_schema(),
|
||||
Box::pin(record_batch_stream),
|
||||
)))
|
||||
));
|
||||
// The rows this scan hid and the slices it read (a physical-sequence read only)
|
||||
// travel with the result, so the caller learns which windows it has to recompute
|
||||
// and which cursor slices it consumed.
|
||||
Ok(SubstitutedRowRangesStream::wrap(
|
||||
stream,
|
||||
input.substituted_row_ranges_ref(),
|
||||
input.observed_slices_ref(),
|
||||
input.region_metadata().region_id.as_u64(),
|
||||
))
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
|
||||
+636
-60
@@ -555,6 +555,37 @@ impl MitoRegion {
|
||||
self.compare_exchange_state(expect, RegionRoleState::Leader(RegionLeaderState::Editing))
|
||||
}
|
||||
|
||||
/// Opens the `Editing` window a background publication holds while it allocates its
|
||||
/// boundary, persists it and makes it visible.
|
||||
///
|
||||
/// While the window is open the worker loop queues write and bulk-write requests
|
||||
/// instead of admitting them (see `worker::handle_write`), and region edits are
|
||||
/// queued behind it as well. A publication that reassigns which rows the region
|
||||
/// owns therefore allocates its boundary without any write being attributed a
|
||||
/// sequence at or below it, and the queued writes are only admitted after the new
|
||||
/// layout is visible, so they obtain a sequence strictly above the boundary.
|
||||
///
|
||||
/// **Call this from the worker loop.** Only the loop can prove that no write
|
||||
/// context is in flight when the window opens, which is what makes the boundary it
|
||||
/// allocates afterwards strictly above every sequence already attributed to a row.
|
||||
pub(crate) fn begin_publish_window(&self, expect: RegionLeaderState) -> Result<()> {
|
||||
self.manifest_ctx
|
||||
.open_staging_window(self.region_id, expect, RegionLeaderState::Editing)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Closes the window opened by [`Self::begin_publish_window`] for a publication that does
|
||||
/// not end staging.
|
||||
///
|
||||
/// `next` is `Writable` once the layout is visible, or the pre-window state when the
|
||||
/// publication failed and nothing was published. The caller must let the worker loop
|
||||
/// admit the writes it queued (see `BackgroundNotify::EditingWindowClosed`). A staging
|
||||
/// exit releases through [`Self::publish_staged_manifests`] instead, which also degrades
|
||||
/// the region by the result of its commit.
|
||||
pub(crate) fn end_publish_window(&self, next: RegionLeaderState) -> Result<()> {
|
||||
self.manifest_ctx.end_publish_window(self.region_id, next)
|
||||
}
|
||||
|
||||
/// Sets the staging state.
|
||||
///
|
||||
/// You should call this method in the worker loop.
|
||||
@@ -623,6 +654,53 @@ impl MitoRegion {
|
||||
&self,
|
||||
state: SettableRegionRoleState,
|
||||
drain_stalled_writes: impl Future<Output = ()>,
|
||||
) -> Result<()> {
|
||||
self.set_role_state_gracefully_impl(state, false, drain_stalled_writes)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Same as [`Self::set_role_state_gracefully`] for a worker-loop caller that already
|
||||
/// opened the publish window of a staging exit (see [`Self::begin_publish_window`]).
|
||||
pub(crate) async fn set_role_state_gracefully_in_publish_window(
|
||||
&self,
|
||||
state: SettableRegionRoleState,
|
||||
) -> Result<()> {
|
||||
// The window is already open, so the publish releases it and the caller admits the
|
||||
// writes it queued: there is nothing to drain here.
|
||||
self.set_role_state_gracefully_impl(state, true, async {})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn set_role_state_gracefully_impl(
|
||||
&self,
|
||||
state: SettableRegionRoleState,
|
||||
window_open: bool,
|
||||
drain_stalled_writes: impl Future<Output = ()>,
|
||||
) -> Result<()> {
|
||||
let result = self
|
||||
.set_role_state_gracefully_locked(state, window_open, drain_stalled_writes)
|
||||
.await;
|
||||
if window_open
|
||||
&& result.is_err()
|
||||
&& self.state() == RegionRoleState::Leader(RegionLeaderState::Editing)
|
||||
{
|
||||
// The publish never ran, so the staged layout is still pending: never leave
|
||||
// writes queued behind a window nobody will release.
|
||||
if let Err(e) = self.end_publish_window(RegionLeaderState::Staging) {
|
||||
error!(
|
||||
e;
|
||||
"Failed to release the publish window of region {}", self.region_id
|
||||
);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn set_role_state_gracefully_locked(
|
||||
&self,
|
||||
state: SettableRegionRoleState,
|
||||
window_open: bool,
|
||||
drain_stalled_writes: impl Future<Output = ()>,
|
||||
) -> Result<()> {
|
||||
let mut manager: RwLockWriteGuard<'_, RegionManifestManager> =
|
||||
self.manifest_ctx.manifest_manager.write().await;
|
||||
@@ -652,6 +730,13 @@ impl MitoRegion {
|
||||
manager = self.manifest_ctx.manifest_manager.write().await;
|
||||
pending
|
||||
}
|
||||
RegionRoleState::Leader(RegionLeaderState::Editing) if window_open => {
|
||||
info!(
|
||||
"Exiting staging mode for region {} inside its publish window",
|
||||
self.region_id
|
||||
);
|
||||
self.exit_staging_on_success_in_window(&mut manager).await?
|
||||
}
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable) => {
|
||||
// Already in desired state - no-op
|
||||
info!("Region {} already in normal leader mode", self.region_id);
|
||||
@@ -1232,11 +1317,17 @@ impl MitoRegion {
|
||||
|
||||
/// Commits the staged edits as one manifest version and ends staging.
|
||||
///
|
||||
/// The caller must hold the manifest write lock and pass it via `manager`. The commit runs in
|
||||
/// [RegionLeaderState::EndingStaging], which stalls writes and holds role changes back (see
|
||||
/// [ManifestContext::leave_ending_staging] for the state it leaves for). If the region stays
|
||||
/// staging, its staged edits are kept for a retry and the error is retryable; otherwise they
|
||||
/// are dropped.
|
||||
/// The caller must hold the manifest write lock and pass it via `manager`. The publish
|
||||
/// runs in the publish window (see [`Self::begin_publish_window`]), the `Editing` state
|
||||
/// that stalls writes and holds role changes back, and releases it: to `Writable` once
|
||||
/// the staged layout is visible, or back to `Staging` when nothing was published, so the
|
||||
/// staged edits are kept for a retry and the error is retryable. A failure that ends the
|
||||
/// region's leadership releases it to `Follower` or `Downgrading` instead (see
|
||||
/// [`Self::publish_staged_manifests`]).
|
||||
///
|
||||
/// A caller outside the worker loop opens the window itself, while the worker loop opens
|
||||
/// it first and then calls [`Self::exit_staging_on_success_in_window`], so that the
|
||||
/// boundary it allocates is above every sequence already attributed to a row.
|
||||
///
|
||||
/// Returns `Ok(None)` when there was nothing to commit.
|
||||
///
|
||||
@@ -1245,24 +1336,123 @@ impl MitoRegion {
|
||||
pub(crate) async fn end_staging_locked(
|
||||
&self,
|
||||
manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
|
||||
) -> Result<Option<PendingManifestHook>> {
|
||||
match self.manifest_ctx.current_state() {
|
||||
RegionRoleState::Leader(RegionLeaderState::Staging) => {
|
||||
// No window is open, so this caller is not the worker loop: it opens the
|
||||
// window itself before publishing.
|
||||
self.begin_publish_window(RegionLeaderState::Staging)?;
|
||||
}
|
||||
RegionRoleState::Leader(RegionLeaderState::Editing) => {}
|
||||
current_state => {
|
||||
return RegionStateSnafu {
|
||||
region_id: self.region_id,
|
||||
state: current_state,
|
||||
expect: RegionRoleState::Leader(RegionLeaderState::Staging),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
}
|
||||
self.publish_staged_manifests(manager).await
|
||||
}
|
||||
|
||||
/// Publishes the staged layout inside a publish window the worker loop already
|
||||
/// opened (see [`Self::begin_publish_window`]).
|
||||
///
|
||||
/// The caller must hold the manifest write lock and pass it via `manager`, and must
|
||||
/// have opened the window before acquiring it.
|
||||
pub(crate) async fn exit_staging_on_success_in_window(
|
||||
&self,
|
||||
manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
|
||||
) -> Result<Option<PendingManifestHook>> {
|
||||
let current_state = self.manifest_ctx.current_state();
|
||||
ensure!(
|
||||
current_state == RegionRoleState::Leader(RegionLeaderState::Staging),
|
||||
current_state == RegionRoleState::Leader(RegionLeaderState::Editing),
|
||||
RegionStateSnafu {
|
||||
region_id: self.region_id,
|
||||
state: current_state,
|
||||
expect: RegionRoleState::Leader(RegionLeaderState::Staging),
|
||||
expect: RegionRoleState::Leader(RegionLeaderState::Editing),
|
||||
}
|
||||
);
|
||||
self.publish_staged_manifests(manager).await
|
||||
}
|
||||
|
||||
let Some(staged_actions) = manager.staged_actions() else {
|
||||
info!(
|
||||
"No staged actions for region {}, exiting staging mode without changes",
|
||||
self.region_id
|
||||
);
|
||||
self.exit_staging()?;
|
||||
return Ok(None);
|
||||
/// Merges the staged actions and publishes the merged layout at the boundary `B`,
|
||||
/// then releases the publish window.
|
||||
///
|
||||
/// A successful publish makes the layout visible, so the window is released to
|
||||
/// `Writable` and the writes it queued are admitted afterwards: they allocate
|
||||
/// `B + 1` or later. A failure publishes nothing: the region returns to `Staging`, which
|
||||
/// keeps the staged edits — and, when its commit may have landed, the bytes to retry with
|
||||
/// (see [`RegionManifestManager::commit_staged`]) — unless the failure ends its leadership.
|
||||
/// A conflict with another writer, an expired Leader lease or a downgrade that began while
|
||||
/// the window was open release the window to `Follower` or `Downgrading`, which is where an
|
||||
/// end of staging that cannot retry has to land (see
|
||||
/// [`ManifestContext::leave_ending_staging`]).
|
||||
async fn publish_staged_manifests(
|
||||
&self,
|
||||
manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
|
||||
) -> Result<Option<PendingManifestHook>> {
|
||||
let result = self.publish_staged_manifests_locked(manager).await;
|
||||
// Releasing the window and leaving staging are one step here: the state the release
|
||||
// decides from the result is the state the region keeps.
|
||||
let next_state = self.manifest_ctx.leave_ending_staging(
|
||||
self.region_id,
|
||||
self.manifest_ctx.take_publish_window_opened_at(),
|
||||
&result,
|
||||
);
|
||||
if next_state != RegionRoleState::Leader(RegionLeaderState::Staging) {
|
||||
// Only a retry of the end commit publishes the staged actions: the staged layout
|
||||
// left with staging. The listings gate on the state and do not rely on this.
|
||||
manager.unset_staging_manifest();
|
||||
// The frozen payload left with the staged actions (a commit that landed, or one that
|
||||
// no longer can), so the write gate follows the region state again.
|
||||
self.manifest_ctx.set_staging_end_pending(false);
|
||||
}
|
||||
match result {
|
||||
// The region stays staging and keeps its staged edits, so publishing them can be
|
||||
// retried. The checks that reject the exit itself are not retryable: they reject
|
||||
// the staged layout, not a write that may land later.
|
||||
//
|
||||
// An end of staging refused for a Leader lease the region still awaits is neither:
|
||||
// the exit itself is fine, the region may just not own the region yet, and the
|
||||
// caller retries it once the lease arrives. It is surfaced as it is — as the callers
|
||||
// that check the lease before opening the window see it (see
|
||||
// [`ManifestContext::ensure_leader_lease_or_downgrading`]) — so the caller can tell
|
||||
// the missing lease from a rejected layout.
|
||||
Err(e)
|
||||
if next_state == RegionRoleState::Leader(RegionLeaderState::Staging)
|
||||
&& !matches!(
|
||||
e,
|
||||
Error::Unexpected { .. } | Error::RegionLeaseNotReceived { .. }
|
||||
) =>
|
||||
{
|
||||
Err(Arc::new(e)).context(EndStagingSnafu {
|
||||
region_id: self.region_id,
|
||||
})
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
async fn publish_staged_manifests_locked(
|
||||
&self,
|
||||
manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
|
||||
) -> Result<Option<PendingManifestHook>> {
|
||||
// A staging region stages its actions in memory and writes nothing, so the staged
|
||||
// actions are the ones recorded while the region was `Staging`. The window state is
|
||||
// `Editing`, which is why they are asked for unconditionally.
|
||||
let staged_actions = match manager.staged_actions() {
|
||||
Some(actions) => actions.clone(),
|
||||
None => {
|
||||
info!(
|
||||
"No staged actions for region {}, exiting staging mode without changes",
|
||||
self.region_id
|
||||
);
|
||||
// Even if nothing is staged, the region still exits staging mode: the window
|
||||
// release in `publish_staged_manifests` does that.
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
let expect_change = staged_actions.actions.iter().any(|a| a.is_change());
|
||||
let expect_partition_expr_change = staged_actions
|
||||
@@ -1289,9 +1479,11 @@ impl MitoRegion {
|
||||
}
|
||||
);
|
||||
|
||||
if let Some(RegionMetaAction::Change(change)) =
|
||||
staged_actions.actions.iter().find(|a| a.is_change())
|
||||
{
|
||||
// The partition-expr action is applied through the committed payload below; the staging
|
||||
// exit reads neither it nor the merged edit's origin to decide anything here.
|
||||
let (_, merged_change, mut merged_edit) =
|
||||
staged_actions.clone().split_region_change_and_edit();
|
||||
if let Some(change) = &merged_change {
|
||||
// In staging exit we only allow metadata-only updates. A `Change`
|
||||
// action is accepted only when column definitions are unchanged;
|
||||
// otherwise it is treated as a schema change and rejected.
|
||||
@@ -1304,49 +1496,140 @@ impl MitoRegion {
|
||||
);
|
||||
}
|
||||
|
||||
// A region that still awaits its Leader lease may not own the region yet, so it
|
||||
// allocates no boundary and persists nothing: this error returns it to `Staging`, which
|
||||
// keeps the staged layout for a retry, unless a downgrade began meanwhile or its Leader
|
||||
// deadline passed (see [`ManifestContext::leave_ending_staging`]). Nothing was sent to
|
||||
// the manifest here, so the write gate stays as the previous attempt left it.
|
||||
self.manifest_ctx
|
||||
.ensure_leader_lease_or_downgrading(self.region_id)?;
|
||||
let ending_started_at = self.manifest_ctx.begin_ending_staging(self.region_id)?;
|
||||
let mut result = self.manifest_ctx.commit_staged_locked(manager).await;
|
||||
if let Ok((pending, committed)) = &mut result {
|
||||
|
||||
// The staging exit may reassign which rows this region owns: rows moved
|
||||
// between regions and, optionally, a new partition range. Allocate the holder's
|
||||
// admission `B = last_sequence + 1` **before** persisting and write a committed
|
||||
// watermark of at least `B` into the merged edit, so the manifest and the in-memory
|
||||
// `Version` agree and a later full rebuild returns `H >= B`.
|
||||
//
|
||||
// The publish window is what makes the re-mark valid: it is opened in the worker loop
|
||||
// before `B` is allocated, so no write context is mid-flight and every ordinary write is
|
||||
// queued until the layout is visible. `B` is therefore above every sequence already
|
||||
// attributed to a row of this region, and every write admitted afterwards obtains
|
||||
// `B + 1` or later.
|
||||
//
|
||||
// The staging exit publishes no sequence boundary: a repartition rewrites no bytes and
|
||||
// substitutes no row number. What it does publish is the holder's re-mark on every file
|
||||
// it makes visible (see below), which is exactly why an earlier substitution must survive
|
||||
// it: `FileMeta::substituted_up_to` is copied verbatim and never cleared here. That per-file
|
||||
// record is the only statement the engine keeps about substituted rows. The re-mark
|
||||
// clears `preserve_row_sequence` only for the files that changed hands: a file this
|
||||
// region already owned keeps it, because its numbers are still the ones this region
|
||||
// allocated.
|
||||
//
|
||||
// The in-memory `last_sequence` is deliberately **not** advanced here: the edit
|
||||
// raises it to `B` through `committed_sequence` when it is applied, so a failed
|
||||
// manifest write cannot leave an advanced allocation behind.
|
||||
//
|
||||
// An attempt whose delta may have landed already froze this payload: it is re-sent as
|
||||
// it is, so neither the merge nor the allocation of `B` nor the re-marking of the files
|
||||
// runs again, and a retry cannot publish a second admission.
|
||||
let retried = manager.staged_attempt_pending();
|
||||
if retried {
|
||||
info!(
|
||||
"Successfully committed staged manifests for region {}, new version: {}",
|
||||
self.region_id,
|
||||
pending.version()
|
||||
"Retrying the end commit of region {} with the payload it already sent",
|
||||
self.region_id
|
||||
);
|
||||
// Apply the committed changes to in-memory version control
|
||||
let (staged_partition_expr_change, staged_change, staged_edit) =
|
||||
std::mem::take(committed).split_region_change_and_edit();
|
||||
if let Some(change) = staged_partition_expr_change {
|
||||
let mut new_metadata = self.version().metadata.as_ref().clone();
|
||||
new_metadata.set_partition_expr(change.partition_expr);
|
||||
self.version_control.alter_metadata(new_metadata.into());
|
||||
} else {
|
||||
let boundary = self.version_control.current().last_sequence + 1;
|
||||
merged_edit.committed_sequence = Some(
|
||||
merged_edit
|
||||
.committed_sequence
|
||||
.map_or(boundary, |committed| committed.max(boundary)),
|
||||
);
|
||||
// Re-mark every file this publish makes visible at `B`: a stale barrier
|
||||
// below `B` would let file-level pruning skip data that only becomes
|
||||
// visible now. The re-mark is a statement about the *handle* in this
|
||||
// region's domain; the bytes keep their numbering.
|
||||
//
|
||||
// `preserve_row_sequence` is judged by **ownership**, not by the publish.
|
||||
// Only a file that changed hands is re-marked as untrusted: its `region_id`
|
||||
// belongs to another region, so the rows carry numbers this region never
|
||||
// allocated and are attributed by the creator's cursor and by the file's own
|
||||
// `substituted_up_to` cut instead of by that marker. A file this region
|
||||
// already owned (`region_id == self.region_id`) kept its bytes *and* its
|
||||
// numbers: a repartition that leaves it here changes who publishes it, not
|
||||
// what its rows say, so the marker is kept exactly as the payload states it.
|
||||
// Clearing it would make every later exact `(C, H]` read of this region fail
|
||||
// closed (`read/scan_region.rs::exact_sequence_range`) although the file
|
||||
// never left, so its new rows could never be read again.
|
||||
for file in &mut merged_edit.files_to_add {
|
||||
file.sequence = std::num::NonZeroU64::new(boundary);
|
||||
if file.region_id != self.region_id {
|
||||
file.preserve_row_sequence = false;
|
||||
}
|
||||
}
|
||||
if let Some(change) = staged_change {
|
||||
self.version_control.alter_metadata(change.metadata);
|
||||
}
|
||||
self.version_control
|
||||
.apply_edit(Some(staged_edit), &[], self.file_purger.clone());
|
||||
}
|
||||
let result = result.map(|(pending, _)| pending);
|
||||
let next_state =
|
||||
self.manifest_ctx
|
||||
.leave_ending_staging(self.region_id, ending_started_at, &result);
|
||||
if next_state != RegionRoleState::Leader(RegionLeaderState::Staging) {
|
||||
// Only a retry commits the staged actions. The listings gate on the state and do not
|
||||
// rely on this.
|
||||
manager.unset_staging_manifest();
|
||||
}
|
||||
|
||||
match result {
|
||||
// A retry of the request commits the kept edits.
|
||||
Err(e) if next_state == RegionRoleState::Leader(RegionLeaderState::Staging) => {
|
||||
Err(Arc::new(e)).context(EndStagingSnafu {
|
||||
region_id: self.region_id,
|
||||
})
|
||||
// Persist the **final merged edit exactly once**: keep the metadata /
|
||||
// partition actions in order and drop every original edit. The manifest
|
||||
// builder inserts files by id, so leaving an original edit in the list would
|
||||
// overwrite the barrier this publish establishes (and the reopened region
|
||||
// would disagree with the in-memory version).
|
||||
let mut persisted_actions = RegionMetaActionList::default();
|
||||
for action in staged_actions.actions.iter() {
|
||||
if !action.is_edit() {
|
||||
persisted_actions.actions.push(action.clone());
|
||||
}
|
||||
result => result.map(Some),
|
||||
}
|
||||
persisted_actions
|
||||
.actions
|
||||
.push(RegionMetaAction::Edit(merged_edit));
|
||||
if !retried {
|
||||
// The merged payload becomes the staged one: it is what the commit persists and
|
||||
// what a retry re-sends, and no other edit may join it until it is committed as
|
||||
// one version (`stage` refuses them while the attempt is kept).
|
||||
manager.replace_staged_actions(persisted_actions);
|
||||
}
|
||||
let commit = self.manifest_ctx.commit_staged_locked(manager).await;
|
||||
// Keep the write gate in step with the payload: a commit that may have landed keeps its
|
||||
// bytes for a retry, and the boundary it carries is what the retry publishes, so ordinary
|
||||
// writes stay refused until that retry completes or the staged actions are dropped.
|
||||
self.manifest_ctx
|
||||
.set_staging_end_pending(manager.staged_attempt_pending());
|
||||
let (pending, committed) = commit?;
|
||||
let new_version = pending.version();
|
||||
info!(
|
||||
"Successfully submitted merged staged manifests for region {}, new version: {}",
|
||||
self.region_id, new_version
|
||||
);
|
||||
|
||||
// Apply the committed changes to in-memory version control as one publish.
|
||||
// The partition expression, the metadata and the merged edit land in the
|
||||
// same `Version`, so a concurrent scan cannot pair the new partition
|
||||
// expression with the previous file set or edit boundary.
|
||||
let (committed_partition_expr_change, committed_change, committed_edit) =
|
||||
committed.split_region_change_and_edit();
|
||||
let new_metadata = if let Some(change) = committed_partition_expr_change {
|
||||
let mut new_metadata = self.version().metadata.as_ref().clone();
|
||||
new_metadata.set_partition_expr(change.partition_expr);
|
||||
Some(new_metadata.into())
|
||||
} else {
|
||||
committed_change.map(|change| change.metadata)
|
||||
};
|
||||
self.version_control.apply_edit_with_metadata(
|
||||
new_metadata,
|
||||
Some(committed_edit),
|
||||
&[],
|
||||
self.file_purger.clone(),
|
||||
);
|
||||
|
||||
// Clear all staging manifests and transit state. The window release is done by
|
||||
// `publish_staged_manifests`, which keeps the state machine in one place.
|
||||
if let Err(e) = manager.clear_staging_manifest_and_dir().await {
|
||||
error!(e; "Failed to clear staging manifest dir for region {}", self.region_id);
|
||||
}
|
||||
|
||||
// Return the hook payload; the caller invokes the hook after dropping the lock.
|
||||
Ok(Some(pending))
|
||||
}
|
||||
|
||||
pub fn expected_partition_expr_version(&self) -> u64 {
|
||||
@@ -1377,6 +1660,17 @@ impl MitoRegion {
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Returns whether the region waits for a retry of its end-of-staging commit that may already
|
||||
/// have landed.
|
||||
///
|
||||
/// While it does, ordinary and bulk writes are refused rather than admitted: the region is
|
||||
/// still `Staging` (the exit failed) but its frozen payload already fixes the boundary `B` it
|
||||
/// publishes, so a write attributed a sequence at or below `B` could reach a reader as
|
||||
/// `C >= B` before the published files are visible, and a later reader would prune them.
|
||||
pub(crate) fn staging_end_pending(&self) -> bool {
|
||||
self.manifest_ctx.staging_end_pending()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MitoRegion {
|
||||
@@ -1495,6 +1789,15 @@ pub(crate) struct ManifestContext {
|
||||
/// During the staging mode, the region metadata in [`VersionControlRef`] is not updated,
|
||||
/// so we need to store the partition info separately.
|
||||
staging_partition_info: Mutex<Option<StagingPartitionInfo>>,
|
||||
/// Whether the region waits for a retry of its end-of-staging commit.
|
||||
///
|
||||
/// The end commit may have landed without the region learning its version, and the payload
|
||||
/// it wrote freezes the boundary `B` it publishes. Until that commit completes, a write that
|
||||
/// is attributed a sequence at or below `B` would let a reader report `C >= B` before the
|
||||
/// published files are visible, and a later reader prunes them as already consumed. The
|
||||
/// write gate therefore refuses such writes (see `MitoRegion::staging_end_pending`), which
|
||||
/// the worker reads here instead of under the manifest lock it cannot take.
|
||||
staging_end_pending: AtomicBool,
|
||||
/// Optional region hook for observing manifest mutations.
|
||||
hook: Option<RegionHookRef>,
|
||||
}
|
||||
@@ -1514,16 +1817,36 @@ impl ManifestContext {
|
||||
reload_pending: false,
|
||||
catching_up: false,
|
||||
stopped: false,
|
||||
window_opened_at: None,
|
||||
}),
|
||||
catchup_promoted_at: AtomicU64::new(0),
|
||||
replay_publication_uncertain: AtomicBool::new(false),
|
||||
leader_deadline: Deadline::default(),
|
||||
node_lease,
|
||||
staging_partition_info: Mutex::new(None),
|
||||
staging_end_pending: AtomicBool::new(false),
|
||||
hook,
|
||||
}
|
||||
}
|
||||
|
||||
/// Records whether the region waits for a retry of its end-of-staging commit, whose payload
|
||||
/// may already have landed (see [`Self::staging_end_pending`]).
|
||||
///
|
||||
/// The caller must keep it in step with the manifest manager: it is set after a commit that
|
||||
/// kept its bytes to retry, and cleared when those bytes are committed or dropped.
|
||||
pub(crate) fn set_staging_end_pending(&self, pending: bool) {
|
||||
self.staging_end_pending.store(pending, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Returns whether a retry of the end-of-staging commit is pending.
|
||||
///
|
||||
/// While it is, the region still stages writes but no longer knows whether the boundary its
|
||||
/// frozen payload publishes is durable, so ordinary writes are refused instead of being
|
||||
/// attributed a sequence at or below it.
|
||||
pub(crate) fn staging_end_pending(&self) -> bool {
|
||||
self.staging_end_pending.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Returns the region hook if one is registered.
|
||||
pub(crate) fn hook(&self) -> Option<RegionHookRef> {
|
||||
self.hook.clone()
|
||||
@@ -1570,31 +1893,81 @@ impl ManifestContext {
|
||||
///
|
||||
/// It holds the lock of [Self::begin_downgrade], so a downgrade either has left staging
|
||||
/// already, or begins after the returned instant.
|
||||
///
|
||||
/// Only the tests of the staging-exit drain contract enter [RegionLeaderState::EndingStaging]
|
||||
/// (see `stalled_requests::add_staging_drain` and the `StagingEnded` notification). A
|
||||
/// publication opens the same window in [RegionLeaderState::Editing] instead (see
|
||||
/// [MitoRegion::begin_publish_window]), which the worker stalls writes and edits for in the
|
||||
/// same way, and releases it through [Self::leave_ending_staging].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn begin_ending_staging(&self, region_id: RegionId) -> Result<Instant> {
|
||||
let _fence = self.promotion_fence.lock().unwrap();
|
||||
self.open_staging_window(
|
||||
region_id,
|
||||
RegionLeaderState::Staging,
|
||||
RegionLeaderState::EndingStaging,
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens the window in which the region publishes a new sequence boundary: `expect` becomes
|
||||
/// the stall state `window`, and the instant it opened is returned and kept for
|
||||
/// [Self::leave_ending_staging], which reads it back when it releases the window.
|
||||
///
|
||||
/// It holds the lock of [Self::begin_downgrade], so a downgrade either has left staging
|
||||
/// already, or begins after the returned instant.
|
||||
fn open_staging_window(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
expect: RegionLeaderState,
|
||||
window: RegionLeaderState,
|
||||
) -> Result<Instant> {
|
||||
let mut fence = self.promotion_fence.lock().unwrap();
|
||||
self.state
|
||||
.compare_exchange(
|
||||
RegionRoleState::Leader(RegionLeaderState::Staging),
|
||||
RegionRoleState::Leader(RegionLeaderState::EndingStaging),
|
||||
RegionRoleState::Leader(expect),
|
||||
RegionRoleState::Leader(window),
|
||||
)
|
||||
.map_err(|actual| {
|
||||
RegionStateSnafu {
|
||||
region_id,
|
||||
state: actual,
|
||||
expect: RegionRoleState::Leader(RegionLeaderState::Staging),
|
||||
expect: RegionRoleState::Leader(expect),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
Ok(Instant::now())
|
||||
let opened_at = Instant::now();
|
||||
fence.window_opened_at = Some(opened_at);
|
||||
Ok(opened_at)
|
||||
}
|
||||
|
||||
/// Leaves [RegionLeaderState::EndingStaging], entered at `ending_started_at`, after the end
|
||||
/// commit returned `result`. Returns the state the region leaves it for, which is in order:
|
||||
/// Returns when the open window opened, and forgets it, for the publication that releases
|
||||
/// it.
|
||||
///
|
||||
/// The worker loop opens the window and a background task releases it, so the instant is
|
||||
/// kept here instead of being threaded through the calls in between. A window nobody opened
|
||||
/// counts as one that opens now, so no downgrade wins over its release.
|
||||
pub(crate) fn take_publish_window_opened_at(&self) -> Instant {
|
||||
self.promotion_fence
|
||||
.lock()
|
||||
.unwrap()
|
||||
.window_opened_at
|
||||
.take()
|
||||
.unwrap_or_else(Instant::now)
|
||||
}
|
||||
|
||||
/// Leaves the window opened at `ending_started_at` — [RegionLeaderState::EndingStaging] for
|
||||
/// a staging exit that entered it, [RegionLeaderState::Editing] for a publication that took
|
||||
/// the worker's publish window — after the end commit returned `result`. Returns the state
|
||||
/// the region leaves it for, which is in order:
|
||||
/// - Follower if the commit conflicted with another writer or failed on an expired lease;
|
||||
/// - Downgrading if a downgrade began meanwhile;
|
||||
/// - Follower if the Leader lease has expired;
|
||||
/// - Writable if the commit succeeded;
|
||||
/// - Staging otherwise, keeping the staging partition info for a retry.
|
||||
///
|
||||
/// This is the release of the `Editing` window too: the publication that persists a new
|
||||
/// sequence boundary releases the window to the state this returns, which is what lets it
|
||||
/// degrade to the states a failed end of staging requires (see
|
||||
/// [`MitoRegion::publish_staged_manifests`]).
|
||||
pub(crate) fn leave_ending_staging<T>(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
@@ -1614,8 +1987,27 @@ impl ManifestContext {
|
||||
Ok(_) => RegionRoleState::Leader(RegionLeaderState::Writable),
|
||||
Err(_) => RegionRoleState::Leader(RegionLeaderState::Staging),
|
||||
};
|
||||
// Role changes leave a region that is ending staging alone.
|
||||
self.state.store(next_state);
|
||||
// Role changes leave a region that is ending staging alone, and the worker stalls them
|
||||
// for a region in its publish window, so the decision applies. A state that changed
|
||||
// anyway (a fenced instance) keeps what it has.
|
||||
let next_state = match self.state.fetch_update(|state| {
|
||||
matches!(
|
||||
state,
|
||||
RegionRoleState::Leader(
|
||||
RegionLeaderState::EndingStaging | RegionLeaderState::Editing
|
||||
)
|
||||
)
|
||||
.then_some(next_state)
|
||||
}) {
|
||||
Ok(_) => next_state,
|
||||
Err(actual) => {
|
||||
warn!(
|
||||
"Region {} left its end-of-staging window for {:?} concurrently, keeping it",
|
||||
region_id, actual
|
||||
);
|
||||
actual
|
||||
}
|
||||
};
|
||||
if next_state != RegionRoleState::Leader(RegionLeaderState::Staging) {
|
||||
self.clear_staging_partition_info();
|
||||
}
|
||||
@@ -1626,6 +2018,37 @@ impl ManifestContext {
|
||||
next_state
|
||||
}
|
||||
|
||||
/// Closes the publish window opened by [`MitoRegion::begin_publish_window`] for a
|
||||
/// publication that does not end staging (see [Self::leave_ending_staging] for the one that
|
||||
/// does, which also degrades the region by its result).
|
||||
///
|
||||
/// The staging partition info is only dropped when the region becomes writable:
|
||||
/// that means the staged layout is visible, so the staging information is obsolete.
|
||||
/// Returning to `Staging` keeps it, because the staged layout is still pending.
|
||||
pub(crate) fn end_publish_window(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
next: RegionLeaderState,
|
||||
) -> Result<()> {
|
||||
self.state
|
||||
.compare_exchange(
|
||||
RegionRoleState::Leader(RegionLeaderState::Editing),
|
||||
RegionRoleState::Leader(next),
|
||||
)
|
||||
.map_err(|actual| {
|
||||
RegionStateSnafu {
|
||||
region_id,
|
||||
state: actual,
|
||||
expect: RegionRoleState::Leader(RegionLeaderState::Editing),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
if next == RegionLeaderState::Writable {
|
||||
self.clear_staging_partition_info();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn manifest_version(&self) -> ManifestVersion {
|
||||
self.manifest_manager
|
||||
.read()
|
||||
@@ -1991,6 +2414,10 @@ impl ManifestContext {
|
||||
/// Commits the staged actions of `manager` as one version under a caller-held write lock.
|
||||
/// Returns a [`PendingManifestHook`] to [`fire`](PendingManifestHook::fire) after dropping
|
||||
/// the lock, and the committed actions.
|
||||
///
|
||||
/// The staged actions are the merged payload of the exit (see
|
||||
/// [`RegionManifestManager::replace_staged_actions`]) and, when an attempt may have been
|
||||
/// written, [`RegionManifestManager::commit_staged`] re-sends the same bytes.
|
||||
pub(crate) async fn commit_staged_locked(
|
||||
&self,
|
||||
manager: &mut RegionManifestManager,
|
||||
@@ -2630,6 +3057,13 @@ struct PromotionFence {
|
||||
/// Whether the region was stopped (closed, dropped or its worker cleaned up), so no promotion
|
||||
/// applies. The manifest manager also knows it, but a promotion decides under this lock only.
|
||||
stopped: bool,
|
||||
/// When the publish window the region holds opened (see
|
||||
/// [`ManifestContext::open_staging_window`]), while it is open.
|
||||
///
|
||||
/// The release compares it with [`Self::downgrade_started_at`], so a downgrade that begins
|
||||
/// during the window wins over the publication's result. It is kept under this lock because
|
||||
/// opening the window and beginning a downgrade are the two events that must not interleave.
|
||||
window_opened_at: Option<Instant>,
|
||||
}
|
||||
|
||||
/// Regions indexed by ids.
|
||||
@@ -3794,6 +4228,148 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A repartition records no sequence boundary of its own, at either end: the
|
||||
/// staging apply re-homes whole files and the staging exit re-marks them, and
|
||||
/// neither rewrites a byte nor substitutes a row number. The exit still re-marks
|
||||
/// every file it makes visible at the holder's admission, and it must not invent a
|
||||
/// substituted cut for bytes it copied verbatim.
|
||||
#[tokio::test]
|
||||
async fn test_end_staging_keeps_the_substituted_cut_of_its_files() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let region = build_test_region(&env).await;
|
||||
|
||||
let mut manager = region.manifest_ctx.manifest_manager.write().await;
|
||||
region.set_staging(&mut manager).await.unwrap();
|
||||
let mut edit = empty_edit();
|
||||
edit.files_to_add.push(super::FileMeta {
|
||||
region_id: RegionId::new(1, 2),
|
||||
file_id: FileId::random(),
|
||||
substituted_up_to: Some(0),
|
||||
..Default::default()
|
||||
});
|
||||
for action in [
|
||||
RegionMetaAction::PartitionExprChange(RegionPartitionExprChange {
|
||||
partition_expr: Some("expr_a".to_string()),
|
||||
}),
|
||||
RegionMetaAction::Edit(edit),
|
||||
] {
|
||||
manager
|
||||
.update(RegionMetaActionList::with_action(action), true)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
// The staged edit raised the allocator to its own committed sequence, so the
|
||||
// exit's admission sits above it.
|
||||
let staged_sequence = region.version_control.current().last_sequence + 1;
|
||||
region.version_control.update_last_sequence(staged_sequence);
|
||||
let admission = staged_sequence + 1;
|
||||
|
||||
region.end_staging_locked(&mut manager).await.unwrap();
|
||||
drop(manager);
|
||||
|
||||
let published = region
|
||||
.version()
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.values())
|
||||
.next()
|
||||
.expect("published file")
|
||||
.meta_ref()
|
||||
.clone();
|
||||
assert_eq!(
|
||||
Some(admission),
|
||||
published.sequence.map(|sequence| sequence.get())
|
||||
);
|
||||
assert!(!published.preserve_row_sequence);
|
||||
// A cut describes the bytes, so copying the file verbatim keeps it.
|
||||
assert_eq!(Some(0), published.substituted_up_to);
|
||||
}
|
||||
|
||||
/// The staging exit re-marks the files it makes visible at the holder's admission, but
|
||||
/// the `preserve_row_sequence` marker is judged by **ownership**: a repartition that
|
||||
/// leaves a file in the region it already belonged to changes the partition expression
|
||||
/// and who publishes the layout, not the numbers in the bytes. Clearing the marker of
|
||||
/// such a file would deny every later exact `(C, H]` read of the region
|
||||
/// (`read/scan_region.rs::exact_sequence_range` fails closed on a local file without it)
|
||||
/// even though the file never left. A file adopted from another region still has its
|
||||
/// marker cleared: its rows carry numbers this region never allocated.
|
||||
#[tokio::test]
|
||||
async fn test_end_staging_keeps_the_marker_of_a_file_it_already_owned() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let region = build_test_region(&env).await;
|
||||
let local_region_id = region.region_id;
|
||||
let adopted_region_id = RegionId::new(1, 2);
|
||||
|
||||
let mut manager = region.manifest_ctx.manifest_manager.write().await;
|
||||
region.set_staging(&mut manager).await.unwrap();
|
||||
let mut edit = empty_edit();
|
||||
let local_file_id = FileId::random();
|
||||
edit.files_to_add.push(super::FileMeta {
|
||||
region_id: local_region_id,
|
||||
file_id: local_file_id,
|
||||
preserve_row_sequence: true,
|
||||
..Default::default()
|
||||
});
|
||||
let adopted_file_id = FileId::random();
|
||||
edit.files_to_add.push(super::FileMeta {
|
||||
region_id: adopted_region_id,
|
||||
file_id: adopted_file_id,
|
||||
preserve_row_sequence: true,
|
||||
..Default::default()
|
||||
});
|
||||
for action in [
|
||||
RegionMetaAction::PartitionExprChange(RegionPartitionExprChange {
|
||||
partition_expr: Some("expr_a".to_string()),
|
||||
}),
|
||||
RegionMetaAction::Edit(edit),
|
||||
] {
|
||||
manager
|
||||
.update(RegionMetaActionList::with_action(action), true)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let staged_sequence = region.version_control.current().last_sequence + 1;
|
||||
region.version_control.update_last_sequence(staged_sequence);
|
||||
let admission = staged_sequence + 1;
|
||||
|
||||
region.end_staging_locked(&mut manager).await.unwrap();
|
||||
drop(manager);
|
||||
|
||||
let version = region.version();
|
||||
let files = version
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.values())
|
||||
.map(|file| file.meta_ref().clone())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(2, files.len());
|
||||
|
||||
let local = files
|
||||
.iter()
|
||||
.find(|file| file.file_id == local_file_id)
|
||||
.expect("local file published");
|
||||
// The barrier is re-stamped for every file the publish makes visible.
|
||||
assert_eq!(
|
||||
Some(admission),
|
||||
local.sequence.map(|sequence| sequence.get())
|
||||
);
|
||||
// The numbers in it are this region's, so the marker survives the publish.
|
||||
assert!(local.preserve_row_sequence);
|
||||
|
||||
let adopted = files
|
||||
.iter()
|
||||
.find(|file| file.file_id == adopted_file_id)
|
||||
.expect("adopted file published");
|
||||
assert_eq!(
|
||||
Some(admission),
|
||||
adopted.sequence.map(|sequence| sequence.get())
|
||||
);
|
||||
// Its rows were numbered elsewhere: the creator's cursor attributes them.
|
||||
assert!(!adopted.preserve_row_sequence);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_end_staging_change_with_same_columns_success() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
|
||||
@@ -716,18 +716,20 @@ impl RegionOpener {
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(committed_in_manifest) = manifest.committed_sequence {
|
||||
let committed_after_replay = version_control.committed_sequence();
|
||||
if committed_in_manifest > committed_after_replay {
|
||||
info!(
|
||||
"Overriding committed sequence, region: {}, flushed_sequence: {}, committed_sequence: {} -> {}",
|
||||
self.region_id,
|
||||
version_control.current().version.flushed_sequence,
|
||||
version_control.committed_sequence(),
|
||||
committed_in_manifest
|
||||
);
|
||||
version_control.set_committed_sequence(committed_in_manifest);
|
||||
}
|
||||
// Recovery reports the commit watermark the manifest recorded. The flushed
|
||||
// frontier itself keeps the value the WAL and the manifest name; only the commit
|
||||
// watermark (and through it `last_sequence`) is raised when the manifest is ahead.
|
||||
let recovered_committed = manifest.committed_sequence.unwrap_or_default();
|
||||
let committed_after_replay = version_control.committed_sequence();
|
||||
if recovered_committed > committed_after_replay {
|
||||
info!(
|
||||
"Overriding committed sequence, region: {}, flushed_sequence: {}, committed_sequence: {} -> {}",
|
||||
self.region_id,
|
||||
version_control.current().version.flushed_sequence,
|
||||
committed_after_replay,
|
||||
recovered_committed
|
||||
);
|
||||
version_control.set_committed_sequence(recovered_committed);
|
||||
}
|
||||
|
||||
let now = self.time_provider.current_time_millis();
|
||||
|
||||
@@ -155,9 +155,31 @@ impl VersionControl {
|
||||
edit: Option<RegionEdit>,
|
||||
memtables_to_remove: &[MemtableId],
|
||||
purger: FilePurgerRef,
|
||||
) {
|
||||
self.apply_edit_with_metadata(None, edit, memtables_to_remove, purger);
|
||||
}
|
||||
|
||||
/// Applies an optional metadata update and an optional edit as **one**
|
||||
/// [Version] publish.
|
||||
///
|
||||
/// Publishing both together keeps a concurrent reader from observing the
|
||||
/// new metadata (e.g. a changed partition expression) together with the
|
||||
/// previous file set or sequence boundary, which would break the invariant
|
||||
/// that one scan sees one consistent file set and partition rule.
|
||||
pub(crate) fn apply_edit_with_metadata(
|
||||
&self,
|
||||
metadata: Option<RegionMetadataRef>,
|
||||
edit: Option<RegionEdit>,
|
||||
memtables_to_remove: &[MemtableId],
|
||||
purger: FilePurgerRef,
|
||||
) {
|
||||
let version = self.current().version;
|
||||
let builder = VersionBuilder::from_version(version);
|
||||
let builder = if let Some(metadata) = metadata {
|
||||
builder.metadata(metadata)
|
||||
} else {
|
||||
builder
|
||||
};
|
||||
let committed_sequence = edit.as_ref().and_then(|e| e.committed_sequence);
|
||||
let builder = if let Some(edit) = edit {
|
||||
builder.apply_edit(edit, purger)
|
||||
@@ -217,6 +239,11 @@ impl VersionControl {
|
||||
}
|
||||
|
||||
/// Alter metadata of the region without rebuilding memtables.
|
||||
///
|
||||
/// Production paths that must keep metadata and files consistent publish both
|
||||
/// through [Self::apply_edit_with_metadata]; this metadata-only helper is kept
|
||||
/// for tests that need an isolated metadata publish.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn alter_metadata(&self, metadata: RegionMetadataRef) {
|
||||
let version = self.current().version;
|
||||
let new_version = Arc::new(
|
||||
@@ -258,9 +285,14 @@ impl VersionControl {
|
||||
}
|
||||
|
||||
/// Truncate current version.
|
||||
///
|
||||
/// Truncation drops rows from the region. The rows it keeps keep their own
|
||||
/// numbers, so the truncation publishes no sequence boundary: what a reader can
|
||||
/// no longer explain is stated per file by `FileMeta` and by the absence of the
|
||||
/// removed files.
|
||||
pub(crate) fn truncate(&self, truncate_kind: TruncateKind) {
|
||||
let version = self.current().version;
|
||||
|
||||
let current = self.current();
|
||||
let version = current.version;
|
||||
match truncate_kind {
|
||||
TruncateKind::All {
|
||||
truncated_entry_id,
|
||||
@@ -301,12 +333,16 @@ impl VersionControl {
|
||||
}
|
||||
|
||||
/// Discards all memtables while preserving persisted SST files.
|
||||
///
|
||||
/// Like [Self::truncate] this drops rows; the rows that stay keep their own
|
||||
/// numbers, so it publishes no sequence boundary.
|
||||
pub(crate) fn discard_unflushed(
|
||||
&self,
|
||||
discarded_entry_id: EntryId,
|
||||
discarded_sequence: SequenceNumber,
|
||||
) {
|
||||
let version = self.current().version;
|
||||
let current = self.current();
|
||||
let version = current.version;
|
||||
let memtable_builder = version.memtables.mutable.memtable_builder().clone();
|
||||
let new_mutable =
|
||||
Self::new_mutable_from_version(&version, version.metadata.clone(), memtable_builder);
|
||||
|
||||
@@ -240,6 +240,16 @@ impl RemapManifest {
|
||||
}
|
||||
);
|
||||
|
||||
// The substituted cut describes the bytes, so the same physical file reached through
|
||||
// two overlapping source regions must state the same one.
|
||||
ensure!(
|
||||
existing.substituted_up_to == new.substituted_up_to,
|
||||
error::InconsistentFileSnafu {
|
||||
file_id: existing.file_id,
|
||||
reason: "substituted_up_to mismatch",
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -253,6 +263,7 @@ impl RemapManifest {
|
||||
manifest.truncated_entry_id = previous_manifest.truncated_entry_id;
|
||||
manifest.compaction_time_window = previous_manifest.compaction_time_window;
|
||||
manifest.committed_sequence = previous_manifest.committed_sequence;
|
||||
// Never regress a boundary recorded on the kept region.
|
||||
} else {
|
||||
// new region
|
||||
manifest.flushed_entry_id = 0;
|
||||
|
||||
@@ -1193,6 +1193,11 @@ pub(crate) enum BackgroundNotify {
|
||||
},
|
||||
/// The catchup again of a region that awaited its Leader lease has finished.
|
||||
CaughtUpAgain(CaughtUpAgain),
|
||||
/// The staging edit of a region landed: open the publish window in the worker loop
|
||||
/// and publish the staged layout in the background.
|
||||
ExitStaging(ExitStagingRequest),
|
||||
/// A publish window that queued ordinary writes was released: admit them again.
|
||||
EditingWindowClosed,
|
||||
/// The region became writable and may have pending tails to replay.
|
||||
RegionBecameWritable,
|
||||
/// A lease ended the region's wait for its Leader lease, so the work the wait deferred may
|
||||
@@ -1231,6 +1236,15 @@ pub(crate) enum BackgroundNotify {
|
||||
},
|
||||
}
|
||||
|
||||
/// Notifies that the staged layout of a region must be published.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ExitStagingRequest {
|
||||
/// Region id.
|
||||
pub(crate) region_id: RegionId,
|
||||
/// Result sender of the apply staging request.
|
||||
pub(crate) sender: OptionOutputTx,
|
||||
}
|
||||
|
||||
impl BackgroundNotify {
|
||||
/// Whether the worker dispatches pending requests after handling this notification.
|
||||
///
|
||||
@@ -1263,6 +1277,11 @@ impl BackgroundNotify {
|
||||
| Self::RegionFenced
|
||||
| Self::RegionReloaded { .. }
|
||||
| Self::CaughtUpAgain(_)
|
||||
// The publish window opens and publishes in the background; the writes it
|
||||
// queues are admitted by the `EditingWindowClosed` it sends when it ends.
|
||||
| Self::ExitStaging(_)
|
||||
// Admits the queued writes itself, then dispatches.
|
||||
| Self::EditingWindowClosed
|
||||
| Self::RegionBecameWritable
|
||||
| Self::LeaderLeaseWaitEnded
|
||||
| Self::RegionCannotReplay { .. }
|
||||
|
||||
+229
-1
@@ -33,7 +33,7 @@ use serde::{Deserialize, Serialize};
|
||||
use smallvec::SmallVec;
|
||||
use store_api::metadata::ColumnMetadata;
|
||||
use store_api::region_request::PathType;
|
||||
use store_api::storage::{ColumnId, FileId, IndexVersion, RegionId};
|
||||
use store_api::storage::{ColumnId, FileId, IndexVersion, RegionId, SequenceNumber};
|
||||
|
||||
use crate::access_layer::AccessLayerRef;
|
||||
use crate::cache::CacheManagerRef;
|
||||
@@ -393,6 +393,19 @@ pub struct FileMeta {
|
||||
/// restore this capability for untrusted inputs.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub preserve_row_sequence: bool,
|
||||
/// Upper bound of the physical `__sequence` values that a compaction *substituted*
|
||||
/// with a file-level constant. Rows at or below it may carry a number this region
|
||||
/// never allocated for them, so a reader may not compare them with a cursor.
|
||||
/// `Some(0)` = the column carries no per-row numbering at all (legacy import).
|
||||
///
|
||||
/// The value is a bound, not a verdict: a row above it still carries a number its
|
||||
/// writer allocated. A merge takes the maximum of the constants its own reader
|
||||
/// substituted (see [`substituted_row_constant`]) and of the bounds its inputs
|
||||
/// already carried, so an output never loses a substitution an input had.
|
||||
/// `None` (also the value of every older manifest that lacks the field) means no
|
||||
/// row of the column was substituted.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub substituted_up_to: Option<SequenceNumber>,
|
||||
/// Physical encoding, omitted for legacy Parquet files.
|
||||
#[serde(default, skip_serializing_if = "FileFormat::is_parquet")]
|
||||
pub format: FileFormat,
|
||||
@@ -718,6 +731,58 @@ pub(crate) fn known_max_input_sequence<'a>(
|
||||
max
|
||||
}
|
||||
|
||||
/// Returns the constant a reader substitutes for *every* row of `input` when it reads
|
||||
/// the file inside `target_region_id`'s sequence domain, or `None` when the physical
|
||||
/// column is kept as it is.
|
||||
///
|
||||
/// Mirrors the two substituting branches of the Parquet reader in their order
|
||||
/// (`sst/parquet/reader.rs`): a **foreign** file (`region_id` of another region) and a
|
||||
/// local file whose per-row numbering is not trusted and whose footer proves an
|
||||
/// all-zero `__sequence` column. `footer_all_zero` is that footer fact
|
||||
/// ([`need_override_sequence`](crate::sst::parquet::format::need_override_sequence)),
|
||||
/// which is a property of the statistics and never of the rows.
|
||||
pub(crate) fn substituted_row_constant(
|
||||
input: &FileMeta,
|
||||
target_region_id: RegionId,
|
||||
footer_all_zero: bool,
|
||||
) -> Option<SequenceNumber> {
|
||||
let substitutes =
|
||||
input.region_id != target_region_id || (!input.preserve_row_sequence && footer_all_zero);
|
||||
if !substitutes {
|
||||
return None;
|
||||
}
|
||||
input.sequence.map(|sequence| sequence.get())
|
||||
}
|
||||
|
||||
/// Returns the [`FileMeta::substituted_up_to`] bound the merge of `inputs` states on its
|
||||
/// output: the maximum of every constant the merge's own reader substituted and of every
|
||||
/// bound the inputs already carried, or `None` when neither exists.
|
||||
///
|
||||
/// `footer_all_zero` is the input's own all-zero `__sequence` footer fact, in the same
|
||||
/// order as `inputs` ([`substituted_row_constant`] takes it per input).
|
||||
///
|
||||
/// Inheriting an input's bound is not optional: a row substituted by an earlier merge
|
||||
/// stays substituted, and taking only this round's constants would re-expose it as a
|
||||
/// number a cursor may be compared with whenever this round's constants are smaller.
|
||||
pub(crate) fn substituted_up_to_after_merge<'a>(
|
||||
target_region_id: RegionId,
|
||||
inputs: impl IntoIterator<Item = (&'a FileMeta, bool)>,
|
||||
) -> Option<SequenceNumber> {
|
||||
let mut bound: Option<SequenceNumber> = None;
|
||||
let mut raise = |at: SequenceNumber| {
|
||||
bound = Some(bound.map_or(at, |current| current.max(at)));
|
||||
};
|
||||
for (input, footer_all_zero) in inputs {
|
||||
if let Some(inherited) = input.substituted_up_to {
|
||||
raise(inherited);
|
||||
}
|
||||
if let Some(constant) = substituted_row_constant(input, target_region_id, footer_all_zero) {
|
||||
raise(constant);
|
||||
}
|
||||
}
|
||||
bound
|
||||
}
|
||||
|
||||
impl FileHandle {
|
||||
/// Creates a new logical SST reference. Index replacements must reuse its lifetime.
|
||||
pub fn new(meta: impl Into<FileMetaRef>, file_purger: FilePurgerRef) -> FileHandle {
|
||||
@@ -1965,4 +2030,167 @@ mod tests {
|
||||
let tantivy = fulltext_column(FulltextBackend::Tantivy);
|
||||
assert!(file_meta(0).is_index_consistent_with_region(&tantivy, &IndexOptions::default()));
|
||||
}
|
||||
|
||||
/// A manifest written before the cut existed deserializes to `None`, which means "no row
|
||||
/// of this file was substituted", and a `None` cut is not written back.
|
||||
#[test]
|
||||
fn test_file_meta_substituted_up_to_backward_compatibility() {
|
||||
// `FileMeta` of an older manifest: every field below is what such a manifest holds,
|
||||
// and `substituted_up_to` is simply absent.
|
||||
let legacy = r#"{
|
||||
"region_id": 0,
|
||||
"file_id": "bc5896ec-e4d8-4017-a80d-f2de73188d55",
|
||||
"time_range": [
|
||||
{"value": 0, "unit": "Millisecond"},
|
||||
{"value": 0, "unit": "Millisecond"}
|
||||
],
|
||||
"level": 0,
|
||||
"file_size": 1024,
|
||||
"sequence": 7,
|
||||
"num_rows": 3,
|
||||
"num_row_groups": 1,
|
||||
"preserve_row_sequence": true
|
||||
}"#;
|
||||
let meta: FileMeta = serde_json::from_str(legacy).unwrap();
|
||||
assert_eq!(None, meta.substituted_up_to);
|
||||
assert_eq!(Some(NonZeroU64::new(7).unwrap()), meta.sequence);
|
||||
|
||||
// The field is optional on the wire: `None` is omitted, so an older reader sees the
|
||||
// manifest it wrote.
|
||||
let encoded = serde_json::to_value(&meta).unwrap();
|
||||
assert!(encoded.get("substituted_up_to").is_none());
|
||||
|
||||
// `Some(0)` is a real value ("the column carries no per-row numbering at all"), so it
|
||||
// must survive both directions.
|
||||
let legacy_import = FileMeta {
|
||||
substituted_up_to: Some(0),
|
||||
..meta.clone()
|
||||
};
|
||||
let encoded = serde_json::to_value(&legacy_import).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::json!(0),
|
||||
encoded["substituted_up_to"],
|
||||
"a zero cut records that the column carries no per-row numbering"
|
||||
);
|
||||
let decoded: FileMeta = serde_json::from_value(encoded).unwrap();
|
||||
assert_eq!(legacy_import, decoded);
|
||||
}
|
||||
|
||||
/// A foreign input's rows are read at the input's own file-level bound, so the merged
|
||||
/// column carries that constant.
|
||||
#[test]
|
||||
fn test_substituted_up_to_from_foreign_input() {
|
||||
let target = RegionId::new(1, 1);
|
||||
let foreign = FileMeta {
|
||||
region_id: RegionId::new(1, 2),
|
||||
sequence: NonZeroU64::new(7),
|
||||
// Trust and the cut are independent: this file's own numbering is usable, but the
|
||||
// rows this merge writes are the constant `7`, not the creator's numbers.
|
||||
preserve_row_sequence: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Some(7),
|
||||
substituted_up_to_after_merge(target, [(&foreign, false)]),
|
||||
"a foreign input is substituted at the handle bound"
|
||||
);
|
||||
// Without a bound the reader keeps the source numbers, so the merge states no
|
||||
// constant of its own.
|
||||
let unbounded = FileMeta {
|
||||
sequence: None,
|
||||
..foreign.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
None,
|
||||
substituted_up_to_after_merge(target, [(&unbounded, false)])
|
||||
);
|
||||
}
|
||||
|
||||
/// A local input whose per-row numbering is not trusted and whose footer proves an all-zero
|
||||
/// `__sequence` column is substituted at the handle bound, and a repartition can re-stamp
|
||||
/// that bound above every foreign one.
|
||||
#[test]
|
||||
fn test_substituted_up_to_from_local_all_zero_input() {
|
||||
let target = RegionId::new(1, 1);
|
||||
let local = FileMeta {
|
||||
region_id: target,
|
||||
sequence: NonZeroU64::new(9),
|
||||
preserve_row_sequence: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Some(9),
|
||||
substituted_up_to_after_merge(target, [(&local, true)]),
|
||||
"an all-zero local input is normalized to its handle bound"
|
||||
);
|
||||
// A footer that is not all-zero keeps the physical column: nothing is substituted.
|
||||
assert_eq!(
|
||||
None,
|
||||
substituted_up_to_after_merge(target, [(&local, false)])
|
||||
);
|
||||
|
||||
// The local all-zero constant can exceed a foreign one, so the output must reach it.
|
||||
let foreign = FileMeta {
|
||||
region_id: RegionId::new(1, 2),
|
||||
sequence: NonZeroU64::new(4),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Some(9),
|
||||
substituted_up_to_after_merge(target, [(&foreign, false), (&local, true)])
|
||||
);
|
||||
}
|
||||
|
||||
/// An input that already carries a cut stays substituted even when this round substitutes
|
||||
/// nothing, or substitutes less.
|
||||
#[test]
|
||||
fn test_substituted_up_to_inherits_input_bound() {
|
||||
let target = RegionId::new(1, 1);
|
||||
let trusted_input = FileMeta {
|
||||
region_id: target,
|
||||
sequence: NonZeroU64::new(5),
|
||||
preserve_row_sequence: true,
|
||||
substituted_up_to: Some(12),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Some(12),
|
||||
substituted_up_to_after_merge(target, [(&trusted_input, false)]),
|
||||
"a cut an input carries is inherited, not recomputed from fresh constants"
|
||||
);
|
||||
|
||||
let foreign = FileMeta {
|
||||
region_id: RegionId::new(1, 2),
|
||||
sequence: NonZeroU64::new(4),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Some(12),
|
||||
substituted_up_to_after_merge(target, [(&foreign, false), (&trusted_input, false)]),
|
||||
"a smaller fresh constant never lowers an inherited cut"
|
||||
);
|
||||
}
|
||||
|
||||
/// A merge of purely local, trusted inputs substitutes nothing, so the output states no
|
||||
/// cut and the next exact read is a plain incremental one.
|
||||
#[test]
|
||||
fn test_substituted_up_to_of_trusted_local_merge_is_none() {
|
||||
let target = RegionId::new(1, 1);
|
||||
let first = FileMeta {
|
||||
region_id: target,
|
||||
sequence: NonZeroU64::new(3),
|
||||
preserve_row_sequence: true,
|
||||
..Default::default()
|
||||
};
|
||||
let second = FileMeta {
|
||||
region_id: target,
|
||||
sequence: NonZeroU64::new(5),
|
||||
preserve_row_sequence: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
None,
|
||||
substituted_up_to_after_merge(target, [(&first, false), (&second, false)])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,10 +20,10 @@ use std::ops::{BitAnd, Range};
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::v1::{OpType, SemanticType};
|
||||
use common_telemetry::error;
|
||||
use common_telemetry::{debug, error};
|
||||
use datafusion::physical_plan::PhysicalExpr;
|
||||
use datafusion::physical_plan::expressions::DynamicFilterPhysicalExpr;
|
||||
use datatypes::arrow::array::{Array as _, ArrayRef, BooleanArray};
|
||||
use datatypes::arrow::array::{Array as _, ArrayRef, BooleanArray, BooleanBufferBuilder};
|
||||
use datatypes::arrow::buffer::BooleanBuffer;
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use datatypes::schema::Schema;
|
||||
@@ -36,7 +36,7 @@ use parquet::file::statistics::Statistics;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::codec::PrimaryKeyEncoding;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::storage::{ColumnId, TimeSeriesRowSelector};
|
||||
use store_api::storage::{ColumnId, SequenceNumber, SequenceRange, TimeSeriesRowSelector};
|
||||
use table::predicate::Predicate;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
@@ -51,7 +51,7 @@ use crate::read::prune::FlatPruneReader;
|
||||
use crate::sst::file::FileHandle;
|
||||
use crate::sst::parquet::flat_format::{
|
||||
DecodedPrimaryKeys, FlatReadFormat, decode_primary_keys, primary_key_column_index,
|
||||
time_index_column_index,
|
||||
sequence_column_index, time_index_column_index,
|
||||
};
|
||||
use crate::sst::parquet::json_align::ProjectedRecordBatchStream;
|
||||
use crate::sst::parquet::prefilter::primary_key_filter_mask;
|
||||
@@ -592,10 +592,46 @@ impl PreFilterMode {
|
||||
|
||||
/// Context for partition expression filtering.
|
||||
pub(crate) struct PartitionFilterContext {
|
||||
pub(crate) region_partition_physical_expr: Arc<dyn PhysicalExpr>,
|
||||
/// Schema containing only columns referenced by the partition expression.
|
||||
/// Physical expression that selects the rows belonging to this region, or `None` when
|
||||
/// the file states this region's own expression (every row of it belongs here).
|
||||
pub(crate) region_partition_physical_expr: Option<Arc<dyn PhysicalExpr>>,
|
||||
/// Schema containing only the columns referenced by the expressions of this context.
|
||||
/// This is used to build a minimal RecordBatch for partition filter evaluation.
|
||||
pub(crate) partition_schema: Arc<Schema>,
|
||||
/// The creator's cursor slices a physical-sequence read of an adopted file may hold
|
||||
/// rows of, compiled for per-row evaluation
|
||||
/// ([`ScanRequest::creator_cursor_shards`](store_api::storage::ScanRequest)).
|
||||
///
|
||||
/// The slices are the creator's own partition expressions, so they do not overlap and
|
||||
/// at most one of them selects a given row. Empty for every other read.
|
||||
pub(crate) creator_slices: Vec<CreatorSliceFilter>,
|
||||
/// Cursor applied to a row of the creator's domain that no slice expression selects.
|
||||
/// `None` when [`Self::creator_slices`] is empty.
|
||||
///
|
||||
/// A row no slice explains is attributed to the least advanced candidate: re-reading a
|
||||
/// consumed row is recoverable, dropping a live one is not.
|
||||
pub(crate) fallback_cursor: Option<SequenceNumber>,
|
||||
/// The file's own substituted cut
|
||||
/// (`FileMeta::substituted_up_to`), when it states one.
|
||||
///
|
||||
/// A row at or below the cut carries a sequence a substitution produced, so its number
|
||||
/// says nothing about progress. Such a row is left for the substitution rule, which
|
||||
/// hides it **and** reports its time range for recomputation; deciding it here instead
|
||||
/// would drop it without that report.
|
||||
pub(crate) substituted_cut: Option<SequenceNumber>,
|
||||
}
|
||||
|
||||
/// Candidate creator cursor slices of one adopted file, as the scan side selects them:
|
||||
/// `(partition expression identity, last consumed sequence)` pairs.
|
||||
pub(crate) type CreatorSliceCursors = Arc<Vec<(String, SequenceNumber)>>;
|
||||
|
||||
/// One candidate creator-cursor slice, compiled for per-row evaluation.
|
||||
pub(crate) struct CreatorSliceFilter {
|
||||
/// The slice's partition expression.
|
||||
pub(crate) filter: Arc<dyn PhysicalExpr>,
|
||||
/// Last sequence consumed in that slice: a row this expression selects is delivered
|
||||
/// only when its own sequence is above this value.
|
||||
pub(crate) cursor: SequenceNumber,
|
||||
}
|
||||
|
||||
/// Common fields for a range to read and filter batches.
|
||||
@@ -660,14 +696,29 @@ impl RangeBase {
|
||||
};
|
||||
|
||||
// Apply partition filter
|
||||
if let Some(partition_filter) = &self.partition_filter {
|
||||
if let Some(partition_filter) = &self.partition_filter
|
||||
&& (partition_filter.region_partition_physical_expr.is_some()
|
||||
|| !partition_filter.creator_slices.is_empty())
|
||||
{
|
||||
let record_batch = self.project_record_batch_for_pruning_flat(
|
||||
&input,
|
||||
&partition_filter.partition_schema,
|
||||
&mut tag_decode_state,
|
||||
)?;
|
||||
let partition_mask = self.evaluate_partition_filter(&record_batch, partition_filter)?;
|
||||
mask = mask.bitand(&partition_mask);
|
||||
if let Some(region_partition_physical_expr) =
|
||||
&partition_filter.region_partition_physical_expr
|
||||
{
|
||||
let partition_mask =
|
||||
self.evaluate_partition_filter(&record_batch, region_partition_physical_expr)?;
|
||||
mask = mask.bitand(&partition_mask);
|
||||
}
|
||||
// Which rows of the file this round has already consumed: decided per row by
|
||||
// the creator slice the row belongs to, not by one bound for the whole file.
|
||||
if !partition_filter.creator_slices.is_empty() {
|
||||
let sequence_mask =
|
||||
self.evaluate_creator_slices(&input, &record_batch, partition_filter)?;
|
||||
mask = mask.bitand(&sequence_mask);
|
||||
}
|
||||
}
|
||||
|
||||
let num_selected = mask.count_set_bits();
|
||||
@@ -895,10 +946,9 @@ impl RangeBase {
|
||||
fn evaluate_partition_filter(
|
||||
&self,
|
||||
record_batch: &RecordBatch,
|
||||
partition_filter: &PartitionFilterContext,
|
||||
region_partition_physical_expr: &Arc<dyn PhysicalExpr>,
|
||||
) -> Result<BooleanBuffer> {
|
||||
let columnar_value = partition_filter
|
||||
.region_partition_physical_expr
|
||||
let columnar_value = region_partition_physical_expr
|
||||
.evaluate(record_batch)
|
||||
.context(EvalPartitionFilterSnafu)?;
|
||||
let array = columnar_value
|
||||
@@ -921,6 +971,89 @@ impl RangeBase {
|
||||
Ok(mask)
|
||||
}
|
||||
|
||||
/// Computes the mask of rows a physical-sequence read of an adopted file has **not**
|
||||
/// consumed yet.
|
||||
///
|
||||
/// A row is delivered only when its own sequence is above the cursor of the creator
|
||||
/// slice whose expression selects it: the slice the row belongs to decides, not one
|
||||
/// bound for the whole file. That keeps the read free of re-reads when the file was
|
||||
/// written under one coarse expression while the creator's domain has since been split
|
||||
/// into narrower ones whose cursors advanced differently, and free of lost rows when
|
||||
/// the file's own expression is narrower than the rows it holds.
|
||||
///
|
||||
/// A row no slice expression selects is attributed to the least advanced candidate
|
||||
/// ([`PartitionFilterContext::fallback_cursor`]) and reported, because dropping it
|
||||
/// would lose live data while re-reading it only repeats a consumed row.
|
||||
fn evaluate_creator_slices(
|
||||
&self,
|
||||
input: &RecordBatch,
|
||||
record_batch: &RecordBatch,
|
||||
partition_filter: &PartitionFilterContext,
|
||||
) -> Result<BooleanBuffer> {
|
||||
let num_rows = record_batch.num_rows();
|
||||
let slices = &partition_filter.creator_slices;
|
||||
|
||||
// Per slice, the rows whose own sequence is above that slice's cursor.
|
||||
let sequence_column = input.column(sequence_column_index(input.num_columns()));
|
||||
let fallback_cursor = partition_filter.fallback_cursor.unwrap_or_default();
|
||||
let mut not_consumed = Vec::with_capacity(slices.len() + 1);
|
||||
for slice in slices {
|
||||
let mask = SequenceRange::Gt { min: slice.cursor }
|
||||
.filter(sequence_column)
|
||||
.context(ComputeArrowSnafu)?;
|
||||
not_consumed.push(mask);
|
||||
}
|
||||
let fallback_mask = SequenceRange::Gt {
|
||||
min: fallback_cursor,
|
||||
}
|
||||
.filter(sequence_column)
|
||||
.context(ComputeArrowSnafu)?;
|
||||
|
||||
// Per row, the slice whose expression selects it.
|
||||
let mut selected = Vec::with_capacity(slices.len());
|
||||
for slice in slices {
|
||||
selected.push(self.evaluate_partition_filter(record_batch, &slice.filter)?);
|
||||
}
|
||||
|
||||
let substituted_mask = match partition_filter.substituted_cut {
|
||||
// Rows at or below the cut are the substitution rule's business.
|
||||
Some(cut) => Some(
|
||||
SequenceRange::LtEq { max: cut }
|
||||
.filter(sequence_column)
|
||||
.context(ComputeArrowSnafu)?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let mut kept = BooleanBufferBuilder::new(num_rows);
|
||||
let mut unmatched = 0;
|
||||
for row in 0..num_rows {
|
||||
if substituted_mask
|
||||
.as_ref()
|
||||
.is_some_and(|mask| mask.value(row))
|
||||
{
|
||||
kept.append(true);
|
||||
continue;
|
||||
}
|
||||
let keep = match selected.iter().position(|mask| mask.value(row)) {
|
||||
Some(index) => not_consumed[index].value(row),
|
||||
None => {
|
||||
unmatched += 1;
|
||||
fallback_mask.value(row)
|
||||
}
|
||||
};
|
||||
kept.append(keep);
|
||||
}
|
||||
if unmatched > 0 {
|
||||
debug!(
|
||||
"{} of {} rows of an adopted file match no creator cursor slice; bounding them by the least advanced cursor {}",
|
||||
unmatched, num_rows, fallback_cursor
|
||||
);
|
||||
}
|
||||
|
||||
Ok(kept.finish())
|
||||
}
|
||||
|
||||
/// Projects the input `RecordBatch` to match the given schema.
|
||||
///
|
||||
/// This is used for partition expression evaluation. The schema should only contain
|
||||
@@ -1176,7 +1309,10 @@ mod tests {
|
||||
pre_filter_mode: PreFilterMode::All,
|
||||
partition_filter: Some(PartitionFilterContext {
|
||||
partition_schema: partition_schema.clone(),
|
||||
region_partition_physical_expr: partition_expr.clone(),
|
||||
region_partition_physical_expr: Some(partition_expr.clone()),
|
||||
creator_slices: Vec::new(),
|
||||
fallback_cursor: None,
|
||||
substituted_cut: None,
|
||||
}),
|
||||
};
|
||||
for (skip_fields, skip_tags, expected) in [
|
||||
@@ -1266,11 +1402,16 @@ mod tests {
|
||||
true,
|
||||
)]));
|
||||
base.partition_filter = Some(PartitionFilterContext {
|
||||
region_partition_physical_expr: partition_col("tag_0")
|
||||
.eq(Value::String("".into()))
|
||||
.try_as_physical_expr(schema.arrow_schema())
|
||||
.unwrap(),
|
||||
region_partition_physical_expr: Some(
|
||||
partition_col("tag_0")
|
||||
.eq(Value::String("".into()))
|
||||
.try_as_physical_expr(schema.arrow_schema())
|
||||
.unwrap(),
|
||||
),
|
||||
partition_schema: schema.clone(),
|
||||
creator_slices: Vec::new(),
|
||||
fallback_cursor: None,
|
||||
substituted_cut: None,
|
||||
});
|
||||
let temporary = base
|
||||
.project_record_batch_for_pruning_flat(&batch, &schema, &mut TagDecodeState::new())
|
||||
@@ -1332,10 +1473,15 @@ mod tests {
|
||||
.gt_eq(Value::String("a".into()))
|
||||
.and(partition_col("tag_0").lt(Value::String("c".into())));
|
||||
base.partition_filter = Some(PartitionFilterContext {
|
||||
region_partition_physical_expr: partition_expr
|
||||
.try_as_physical_expr(partition_schema.arrow_schema())
|
||||
.unwrap(),
|
||||
region_partition_physical_expr: Some(
|
||||
partition_expr
|
||||
.try_as_physical_expr(partition_schema.arrow_schema())
|
||||
.unwrap(),
|
||||
),
|
||||
partition_schema,
|
||||
creator_slices: Vec::new(),
|
||||
fallback_cursor: None,
|
||||
substituted_cut: None,
|
||||
});
|
||||
|
||||
let filtered = base
|
||||
|
||||
@@ -58,8 +58,8 @@ use crate::cache::{
|
||||
prepare_sst_meta,
|
||||
};
|
||||
use crate::error::{
|
||||
ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result, SerializePartitionExprSnafu,
|
||||
UnexpectedSnafu,
|
||||
InvalidPartitionExprSnafu, ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result,
|
||||
SerializePartitionExprSnafu, UnexpectedSnafu,
|
||||
};
|
||||
use crate::metrics::{READ_ROWS_TOTAL, READ_STAGE_ELAPSED};
|
||||
use crate::read::prune::FlatPruneReader;
|
||||
@@ -76,7 +76,8 @@ use crate::sst::index::inverted_index::applier::{
|
||||
InvertedIndexApplierRef, InvertedIndexApplyMetrics,
|
||||
};
|
||||
use crate::sst::parquet::file_range::{
|
||||
FileRangeContext, FileRangeContextRef, PartitionFilterContext, PreFilterMode, RangeBase,
|
||||
CreatorSliceCursors, CreatorSliceFilter, FileRangeContext, FileRangeContextRef,
|
||||
PartitionFilterContext, PreFilterMode, RangeBase,
|
||||
};
|
||||
use crate::sst::parquet::flat_format::{FlatReadFormat, primary_key_column_index};
|
||||
use crate::sst::parquet::format::{INTERNAL_COLUMN_NUM, need_override_sequence};
|
||||
@@ -214,6 +215,21 @@ pub struct ParquetReaderBuilder {
|
||||
expected_metadata: Option<RegionMetadataRef>,
|
||||
/// Whether this reader is for compaction.
|
||||
compaction: bool,
|
||||
/// Force every row's sequence to the file's admission barrier, whatever the
|
||||
/// file's own sequence column and trust markers say.
|
||||
///
|
||||
/// Used only by Flow recovery window discovery, which needs the timestamps of
|
||||
/// the rows a harness cannot trust row by row; ordinary reads leave it `false`
|
||||
/// and keep the foreign/legacy conditional override.
|
||||
force_sequence_override: bool,
|
||||
/// Keep the physical `__sequence` column of a foreign file instead of virtualizing
|
||||
/// it at the handle's barrier.
|
||||
///
|
||||
/// Used only by Flow's incremental read with `ScanRequest::read_row_sequence`,
|
||||
/// which then hides the rows at or below the file's substituted cut. Every other
|
||||
/// reader leaves it `false`: compaction and ordinary queries depend on the
|
||||
/// substitution.
|
||||
read_row_sequence: bool,
|
||||
/// Mode to pre-filter columns.
|
||||
pre_filter_mode: PreFilterMode,
|
||||
/// Whether to run the reduced-column predicate prefilter pass.
|
||||
@@ -222,6 +238,13 @@ pub struct ParquetReaderBuilder {
|
||||
postpone_time_index_filter: bool,
|
||||
/// Whether to decode primary key values eagerly when reading primary key format SSTs.
|
||||
decode_primary_key_values: bool,
|
||||
/// Candidate creator-cursor slices of a physical-sequence read of an adopted file:
|
||||
/// `(partition expression identity, last consumed sequence)` pairs
|
||||
/// ([`ScanRequest::creator_cursor_shards`](store_api::storage::ScanRequest)).
|
||||
///
|
||||
/// The scan side has already dropped the slices whose expression cannot hold rows of
|
||||
/// this file. Every reader but that one leaves it `None`.
|
||||
creator_slice_cursors: Option<CreatorSliceCursors>,
|
||||
page_index_policy: PageIndexPolicy,
|
||||
defer_optional_page_index: bool,
|
||||
/// Scan-wide hint for rows in a decoded batch.
|
||||
@@ -260,10 +283,13 @@ impl ParquetReaderBuilder {
|
||||
fulltext_index_appliers: [None, None],
|
||||
expected_metadata: None,
|
||||
compaction: false,
|
||||
force_sequence_override: false,
|
||||
read_row_sequence: false,
|
||||
pre_filter_mode: PreFilterMode::All,
|
||||
enable_predicate_prefilter: true,
|
||||
postpone_time_index_filter: false,
|
||||
decode_primary_key_values: false,
|
||||
creator_slice_cursors: None,
|
||||
page_index_policy: Default::default(),
|
||||
defer_optional_page_index: false,
|
||||
batch_size: DEFAULT_READ_BATCH_SIZE,
|
||||
@@ -358,6 +384,41 @@ impl ParquetReaderBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Forces the row-level sequence override to the file's admission barrier.
|
||||
///
|
||||
/// Only Flow recovery window discovery sets this: it needs the timestamps of
|
||||
/// every selected file's rows and must not depend on the file's sequence column
|
||||
/// or on its trust markers.
|
||||
#[must_use]
|
||||
pub fn force_sequence_override(mut self, force_sequence_override: bool) -> Self {
|
||||
self.force_sequence_override = force_sequence_override;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the candidate creator-cursor slices of a physical-sequence read of an adopted
|
||||
/// file: `(partition expression identity, last consumed sequence)` pairs.
|
||||
///
|
||||
/// The reader compiles each identity into a row filter and keeps a row only when its
|
||||
/// own sequence is above the cursor of the slice whose expression selects it
|
||||
/// (`PartitionFilterContext::creator_slices`), so the file's rows are split by the
|
||||
/// domain they belong to instead of by one bound for the whole file.
|
||||
#[must_use]
|
||||
pub(crate) fn creator_slice_cursors(mut self, cursors: Option<CreatorSliceCursors>) -> Self {
|
||||
self.creator_slice_cursors = cursors;
|
||||
self
|
||||
}
|
||||
|
||||
/// Reads the physical `__sequence` of a foreign file instead of substituting the
|
||||
/// handle's barrier for every row.
|
||||
///
|
||||
/// Only Flow's incremental read sets this; the caller hides the rows a
|
||||
/// substitution produced (see `ScanRequest::read_row_sequence`).
|
||||
#[must_use]
|
||||
pub(crate) fn read_row_sequence(mut self, read_row_sequence: bool) -> Self {
|
||||
self.read_row_sequence = read_row_sequence;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the pre-filter mode.
|
||||
#[must_use]
|
||||
pub(crate) fn pre_filter_mode(mut self, pre_filter_mode: PreFilterMode) -> Self {
|
||||
@@ -514,7 +575,34 @@ impl ParquetReaderBuilder {
|
||||
);
|
||||
}
|
||||
let file_meta = self.file_handle.meta_ref();
|
||||
let override_sequence = if is_foreign {
|
||||
let override_sequence = if self.force_sequence_override {
|
||||
// Recovery discovery: virtualize every row at the file's own admission
|
||||
// barrier. The rows may carry a foreign or legacy sequence column, and
|
||||
// discovery only needs their timestamps, so the barrier is the only
|
||||
// sequence that can be trusted.
|
||||
file_meta.sequence.map(|sequence| sequence.get())
|
||||
} else if self.read_row_sequence && is_foreign {
|
||||
// A physical-sequence read keeps an adopted file's own column: the foreign
|
||||
// branch below would make every row look published by the import, which is
|
||||
// exactly what the caller needs to split apart.
|
||||
//
|
||||
// `preserve_row_sequence` deliberately takes no part here. It describes
|
||||
// whether the *writer* kept per-row numbering, whereas an import (including
|
||||
// a repartition's staging apply) only re-marks the handle and copies the
|
||||
// bytes: the column still holds the numbers their creator allocated. Flow
|
||||
// judges which rows a substitution produced by the file's own
|
||||
// `substituted_up_to` cut, not by the marker, so a file an import re-marked
|
||||
// with `preserve_row_sequence = false` still carries a readable column.
|
||||
//
|
||||
// A source file stating `preserve_row_sequence = false` and no cut is
|
||||
// outside the model (the plateau of a source table whose option is off):
|
||||
// its column may carry no per-row numbering at all, and there is no cut to
|
||||
// hide those rows with. Flow never asks for such a region — the region-level
|
||||
// `preserve_row_sequence` option still denies it the exact range before this
|
||||
// reader runs — so this branch never sees one; it must not be treated as an
|
||||
// ordinary file if it ever does.
|
||||
None
|
||||
} else if is_foreign {
|
||||
file_meta.sequence.map(|sequence| sequence.get())
|
||||
} else if file_meta.preserve_row_sequence {
|
||||
None
|
||||
@@ -716,6 +804,10 @@ impl ParquetReaderBuilder {
|
||||
/// precise filtering gathers these columns temporarily before compatibility.
|
||||
/// Compare partition expressions from expected metadata and file metadata,
|
||||
/// and build a partition filter if they differ.
|
||||
///
|
||||
/// It also compiles the candidate creator-cursor slices of a physical-sequence read
|
||||
/// (`Self::creator_slice_cursors`) into row filters: both are per-row expressions over
|
||||
/// the same minimal schema, so one projection of the batch serves all of them.
|
||||
fn build_partition_filter(
|
||||
&self,
|
||||
read_format: &FlatReadFormat,
|
||||
@@ -730,17 +822,45 @@ impl ParquetReaderBuilder {
|
||||
let (region_partition_expr, is_same_region_partition) =
|
||||
Self::is_same_region_partition(region_partition_expr_str, file_partition_expr_ref)?;
|
||||
|
||||
if is_same_region_partition {
|
||||
// A file stating this region's own expression holds only this region's rows, so it
|
||||
// needs no region filter; the creator slices below are independent of that.
|
||||
let region_partition_expr = if is_same_region_partition {
|
||||
None
|
||||
} else {
|
||||
region_partition_expr
|
||||
};
|
||||
|
||||
let slice_cursors = self
|
||||
.creator_slice_cursors
|
||||
.as_deref()
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or_default();
|
||||
if region_partition_expr.is_none() && slice_cursors.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let Some(region_partition_expr) = region_partition_expr else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// Collect columns referenced by the partition expression.
|
||||
// Collect columns referenced by every expression this context evaluates.
|
||||
let mut referenced_columns = HashSet::new();
|
||||
region_partition_expr.collect_column_names(&mut referenced_columns);
|
||||
if let Some(expr) = ®ion_partition_expr {
|
||||
expr.collect_column_names(&mut referenced_columns);
|
||||
}
|
||||
let mut creator_slices = Vec::with_capacity(slice_cursors.len());
|
||||
for (identity, cursor) in slice_cursors {
|
||||
let Some(expr) = PartitionExpr::from_json_str(identity)
|
||||
.context(InvalidPartitionExprSnafu { expr: identity })?
|
||||
else {
|
||||
// An identity this build cannot read back cannot be evaluated, and
|
||||
// approximating it would decide a row's domain by guesswork: leave the
|
||||
// whole context out so the caller keeps the conservative file-level bound.
|
||||
debug!(
|
||||
"Cannot read back creator cursor slice expression {}; falling back to the file-level bound",
|
||||
identity
|
||||
);
|
||||
return Ok(None);
|
||||
};
|
||||
expr.collect_column_names(&mut referenced_columns);
|
||||
creator_slices.push((expr, *cursor));
|
||||
}
|
||||
|
||||
// Build a partition_schema containing only referenced columns.
|
||||
let partition_schema = Arc::new(datatypes::schema::Schema::new(
|
||||
@@ -771,12 +891,28 @@ impl ParquetReaderBuilder {
|
||||
));
|
||||
|
||||
let region_partition_physical_expr = region_partition_expr
|
||||
.try_as_physical_expr(partition_schema.arrow_schema())
|
||||
.map(|expr| expr.try_as_physical_expr(partition_schema.arrow_schema()))
|
||||
.transpose()
|
||||
.context(SerializePartitionExprSnafu)?;
|
||||
let creator_slices = creator_slices
|
||||
.into_iter()
|
||||
.map(|(expr, cursor)| {
|
||||
Ok(CreatorSliceFilter {
|
||||
filter: expr
|
||||
.try_as_physical_expr(partition_schema.arrow_schema())
|
||||
.context(SerializePartitionExprSnafu)?,
|
||||
cursor,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let fallback_cursor = creator_slices.iter().map(|slice| slice.cursor).min();
|
||||
|
||||
Ok(Some(PartitionFilterContext {
|
||||
region_partition_physical_expr,
|
||||
partition_schema,
|
||||
creator_slices,
|
||||
fallback_cursor,
|
||||
substituted_cut: self.file_handle.meta_ref().substituted_up_to,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
+81
-7
@@ -80,8 +80,8 @@ use crate::memtable::bulk::CompactDispatcher;
|
||||
use crate::metrics::{REGION_COUNT, REQUEST_WAIT_TIME, WRITE_STALLING};
|
||||
use crate::region::opener::PartitionExprFetcherRef;
|
||||
use crate::region::{
|
||||
CatchupRegions, CatchupRegionsRef, MitoRegionRef, OpeningRegions, OpeningRegionsRef, RegionMap,
|
||||
RegionMapRef,
|
||||
CatchupRegions, CatchupRegionsRef, MitoRegionRef, OpeningRegions, OpeningRegionsRef,
|
||||
RegionLeaderState, RegionMap, RegionMapRef,
|
||||
};
|
||||
use crate::request::{
|
||||
BackgroundNotify, BuildIndexRequest, BulkInsertRequest, DdlRequest, OptionOutputTx,
|
||||
@@ -1869,7 +1869,11 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
}
|
||||
BackgroundNotify::RegionEdit(req) => self.handle_region_edit_result(req).await,
|
||||
BackgroundNotify::CopyRegionFromFinished(req) => {
|
||||
self.handle_copy_region_from_finished(req)
|
||||
self.handle_copy_region_from_finished(req).await
|
||||
}
|
||||
BackgroundNotify::ExitStaging(req) => self.handle_exit_staging_request(req),
|
||||
BackgroundNotify::EditingWindowClosed => {
|
||||
self.handle_editing_window_closed(region_id).await
|
||||
}
|
||||
BackgroundNotify::RegionFenced => {}
|
||||
BackgroundNotify::RegionReloaded { old, result } => {
|
||||
@@ -1919,6 +1923,21 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Admits the writes queued by a publish window that has been released.
|
||||
///
|
||||
/// The window has already restored the region role state (writable when the publish
|
||||
/// is visible, staging when it failed), so the queued writes and the region edits
|
||||
/// queued behind the window can be handled now.
|
||||
async fn handle_editing_window_closed(&mut self, region_id: RegionId) {
|
||||
if self.regions.get_region(region_id).is_none() {
|
||||
self.fail_region_stalled_requests_as_not_found(®ion_id);
|
||||
self.reject_region_requests_as_not_found(region_id);
|
||||
return;
|
||||
}
|
||||
self.handle_region_stalled_requests(®ion_id, false).await;
|
||||
self.dispatch_pending_region_requests(region_id).await;
|
||||
}
|
||||
|
||||
/// Handles `set_region_role_gracefully`.
|
||||
async fn set_role_state_gracefully(
|
||||
&mut self,
|
||||
@@ -1938,6 +1957,24 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
region.manifest_ctx.begin_downgrade(region_id);
|
||||
self.cancel_tail_replay(region_id);
|
||||
}
|
||||
// A staging exit published from here reassigns which rows the region owns, so
|
||||
// it must hold the publish window: open it now, in the loop, where no write
|
||||
// context is in flight. The background task then publishes inside the opened
|
||||
// window and every write the loop handles meanwhile is queued until the new
|
||||
// layout is visible.
|
||||
let publish_window =
|
||||
if region_role_state == SettableRegionRoleState::Leader && region.is_staging() {
|
||||
if let Err(e) = region.begin_publish_window(RegionLeaderState::Staging) {
|
||||
let _ = sender.send(SetRegionRoleStateResponse::invalid_transition(
|
||||
BoxedError::new(e),
|
||||
));
|
||||
return;
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let worker_sender = self.sender.clone();
|
||||
#[cfg(feature = "hdfs-object-store")]
|
||||
let sweep_older_than = self.config.gc.unknown_file_lingering_time;
|
||||
#[cfg(feature = "hdfs-object-store")]
|
||||
@@ -1946,10 +1983,22 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
// We need to do this in background as we need the manifest lock.
|
||||
common_runtime::spawn_global(async move {
|
||||
let drain = drain_ended_staging(&request_sender, region_id);
|
||||
match region
|
||||
.set_role_state_gracefully(region_role_state, drain)
|
||||
.await
|
||||
{
|
||||
let result = if publish_window {
|
||||
// The window is already open, so the publish released it and this call
|
||||
// admits the writes the loop queued: nothing is left to drain.
|
||||
region
|
||||
.set_role_state_gracefully_in_publish_window(region_role_state)
|
||||
.await
|
||||
} else {
|
||||
region
|
||||
.set_role_state_gracefully(region_role_state, drain)
|
||||
.await
|
||||
};
|
||||
// Never leave writes queued behind a window that has been released.
|
||||
if publish_window {
|
||||
resume_queued_writes(&worker_sender, region_id).await;
|
||||
}
|
||||
match result {
|
||||
Ok(()) => {
|
||||
let last_entry_id = region.version_control.current().last_entry_id;
|
||||
let _ = sender.send(SetRegionRoleStateResponse::success(
|
||||
@@ -2022,6 +2071,31 @@ impl<S> RegionWorkerLoop<S> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the worker loop to admit the writes a released publish window queued.
|
||||
///
|
||||
/// A publish window (see `MitoRegion::begin_publish_window`) turns ordinary writes into
|
||||
/// stalled requests. The background task that releases the window cannot admit them
|
||||
/// itself, so it sends this notification: the worker loop then handles the stalled
|
||||
/// requests of the region, which is where the sequence ordering between the publish and
|
||||
/// the queued writes is decided.
|
||||
pub(crate) async fn resume_queued_writes(
|
||||
sender: &Sender<WorkerRequestWithTime>,
|
||||
region_id: RegionId,
|
||||
) {
|
||||
if let Err(e) = sender
|
||||
.send(WorkerRequestWithTime::new(WorkerRequest::Background {
|
||||
region_id,
|
||||
notify: BackgroundNotify::EditingWindowClosed,
|
||||
}))
|
||||
.await
|
||||
{
|
||||
warn!(
|
||||
"Failed to send the editing window closed notification to the worker, region_id: {}, error: {}",
|
||||
region_id, e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper that only calls event listener in tests.
|
||||
#[derive(Default, Clone)]
|
||||
pub(crate) struct WorkerListener {
|
||||
|
||||
@@ -19,16 +19,23 @@ use store_api::region_request::ApplyStagingManifestRequest;
|
||||
use store_api::storage::RegionId;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::error::{RegionStateSnafu, Result, StagingPartitionExprMismatchSnafu, UnexpectedSnafu};
|
||||
use crate::error::{
|
||||
RegionNotFoundSnafu, RegionStateSnafu, Result, StagingPartitionExprMismatchSnafu,
|
||||
UnexpectedSnafu,
|
||||
};
|
||||
use crate::manifest::action::{RegionEdit, RegionManifest};
|
||||
use crate::manifest::storage::manifest_dir;
|
||||
use crate::manifest::storage::staging::{StagingBlobStorage, staging_blob_path};
|
||||
use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState};
|
||||
use crate::request::{OptionOutputTx, RegionEditRequest, WorkerRequest, WorkerRequestWithTime};
|
||||
use crate::request::{
|
||||
BackgroundNotify, ExitStagingRequest, OptionOutputTx, RegionEditRequest, WorkerRequest,
|
||||
WorkerRequestWithTime,
|
||||
};
|
||||
use crate::sst::location::region_dir_from_table_dir;
|
||||
use crate::worker::RegionWorkerLoop;
|
||||
use crate::worker::drain_ended_staging;
|
||||
use crate::worker::handle_reload::notify_if_fenced;
|
||||
use crate::worker::resume_queued_writes;
|
||||
|
||||
impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
pub(crate) async fn handle_apply_staging_manifest_request(
|
||||
@@ -156,20 +163,19 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
sender.send(result.map(|_| 0));
|
||||
return;
|
||||
};
|
||||
let manager = region.manifest_ctx.manifest_manager.write().await;
|
||||
let drain = drain_ended_staging(&worker_sender, region_id);
|
||||
let hook_payload = match region.end_staging(manager, drain).await {
|
||||
Ok(payload) => payload,
|
||||
Err(e) => {
|
||||
notify_if_fenced(&worker_sender, ®ion).await;
|
||||
sender.send(Err(e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(pending) = hook_payload {
|
||||
pending.fire().await;
|
||||
}
|
||||
sender.send(Ok(0));
|
||||
// The staged layout must be published inside the worker's publish window,
|
||||
// which only the worker loop can open: forwarding the exit back to the
|
||||
// loop keeps the boundary above every sequence already attributed to a
|
||||
// row and keeps ordinary writes queued until the layout is visible.
|
||||
let _ = worker_sender
|
||||
.send(WorkerRequestWithTime::new(WorkerRequest::Background {
|
||||
region_id,
|
||||
notify: BackgroundNotify::ExitStaging(ExitStagingRequest {
|
||||
region_id,
|
||||
sender,
|
||||
}),
|
||||
}))
|
||||
.await;
|
||||
} else {
|
||||
sender.send(
|
||||
UnexpectedSnafu {
|
||||
@@ -181,6 +187,48 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Handles a staging exit whose staging edit has landed: opens the publish window in
|
||||
/// the worker loop and publishes the merged layout in the background.
|
||||
pub(crate) fn handle_exit_staging_request(&mut self, request: ExitStagingRequest) {
|
||||
let region_id = request.region_id;
|
||||
let sender = request.sender;
|
||||
let Some(region) = self.regions.get_region(region_id) else {
|
||||
sender.send(Err(RegionNotFoundSnafu { region_id }.build()));
|
||||
return;
|
||||
};
|
||||
|
||||
// Opening the window here, in the loop, is what makes the boundary the publish
|
||||
// allocates a barrier: the loop is the only place that can prove no write context
|
||||
// is in flight, and every write it handles from now on is queued until the window
|
||||
// is released (see `handle_write.rs`).
|
||||
if let Err(e) = region.begin_publish_window(RegionLeaderState::Staging) {
|
||||
sender.send(Err(e));
|
||||
return;
|
||||
}
|
||||
|
||||
let worker_sender = self.sender.clone();
|
||||
common_runtime::spawn_global(async move {
|
||||
let manager = region.manifest_ctx.manifest_manager.write().await;
|
||||
let drain = drain_ended_staging(&worker_sender, region_id);
|
||||
let hook_payload = match region.end_staging(manager, drain).await {
|
||||
Ok(payload) => payload,
|
||||
Err(e) => {
|
||||
// The publish released the window back to `Staging`; the writes it
|
||||
// queued must still be admitted and forwarded to their waiters.
|
||||
notify_if_fenced(&worker_sender, ®ion).await;
|
||||
resume_queued_writes(&worker_sender, region_id).await;
|
||||
sender.send(Err(e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(pending) = hook_payload {
|
||||
pending.fire().await;
|
||||
}
|
||||
resume_queued_writes(&worker_sender, region_id).await;
|
||||
sender.send(Ok(0));
|
||||
});
|
||||
}
|
||||
|
||||
/// Fetches the staging manifest from the central region's staging blob storage.
|
||||
///
|
||||
/// The `central_region_id` is used to locate the staging directory because the staging
|
||||
|
||||
@@ -13,12 +13,13 @@
|
||||
// limitations under the License.
|
||||
|
||||
use common_telemetry::{debug, error, info};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use snafu::{OptionExt, ensure};
|
||||
use store_api::logstore::LogStore;
|
||||
use store_api::region_engine::MitoCopyRegionFromResponse;
|
||||
use store_api::region_request::PathType;
|
||||
use store_api::storage::{FileId, RegionId};
|
||||
|
||||
use crate::error::{InvalidRequestSnafu, MissingManifestSnafu, Result};
|
||||
use crate::error::{InvalidRequestSnafu, MissingManifestSnafu, RegionNotFoundSnafu, Result};
|
||||
use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList};
|
||||
use crate::region::{
|
||||
FileDescriptor, MitoRegionRef, RegionFileCopier, RegionLeaderState, RegionMetadataLoader,
|
||||
@@ -28,9 +29,9 @@ use crate::request::{
|
||||
};
|
||||
use crate::sst::file::{self, FileMeta};
|
||||
use crate::sst::location::region_dir_from_table_dir;
|
||||
use crate::worker::{RegionWorkerLoop, WorkerRequestWithTime};
|
||||
use crate::worker::{RegionWorkerLoop, WorkerRequestWithTime, resume_queued_writes};
|
||||
|
||||
impl<S> RegionWorkerLoop<S> {
|
||||
impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
pub(crate) fn handle_copy_region_from_request(&mut self, request: CopyRegionFromRequest) {
|
||||
let region_id = request.region_id;
|
||||
let source_region_id = request.source_region_id;
|
||||
@@ -73,6 +74,16 @@ impl<S> RegionWorkerLoop<S> {
|
||||
);
|
||||
let worker_sender = self.sender.clone();
|
||||
|
||||
// Hold the publish window for the whole copy. The boundary the copy allocates
|
||||
// must be above every sequence already attributed to a row, and no write may be
|
||||
// admitted before the copied files are visible: the loop is the only place that
|
||||
// can prove no write context is in flight, so open the window here and keep it
|
||||
// open until the copied edit is applied (see `handle_copy_region_from_finished`).
|
||||
if let Err(e) = region.begin_publish_window(RegionLeaderState::Writable) {
|
||||
let _ = sender.send(Err(e));
|
||||
return;
|
||||
}
|
||||
|
||||
common_runtime::spawn_global(async move {
|
||||
let (region_edit, source_file_ids) = match Self::copy_region_from(
|
||||
®ion,
|
||||
@@ -85,51 +96,27 @@ impl<S> RegionWorkerLoop<S> {
|
||||
{
|
||||
Ok(region_files) => region_files,
|
||||
Err(e) => {
|
||||
// Nothing was published, so return the region to its pre-window state
|
||||
// and admit the writes the window queued.
|
||||
if let Err(release) = region.end_publish_window(RegionLeaderState::Writable) {
|
||||
error!(release; "Failed to release the copy publish window of region {}", region_id);
|
||||
}
|
||||
resume_queued_writes(&worker_sender, region_id).await;
|
||||
let _ = sender.send(Err(e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
match region_edit {
|
||||
Some(region_edit)
|
||||
if region_edit
|
||||
.files_to_add
|
||||
.iter()
|
||||
.any(|file| file.level == file::LEVEL_SHARED) =>
|
||||
{
|
||||
// Shared references and their target admission sequence must enter
|
||||
// the serialized edit lane, not the asynchronous physical-copy path.
|
||||
// The response lists installed references, including shared SSTs
|
||||
// whose objects stay in place; it is not a physical COPY count.
|
||||
let copied_file_ids = region_edit
|
||||
.files_to_add
|
||||
.iter()
|
||||
.map(|file| file.file_id)
|
||||
.collect();
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
if worker_sender
|
||||
.send(WorkerRequestWithTime::new(WorkerRequest::EditRegion(
|
||||
crate::request::RegionEditRequest::new(
|
||||
region_id,
|
||||
region_edit,
|
||||
false,
|
||||
tx,
|
||||
),
|
||||
)))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
let _ = sender.send(crate::error::RegionNotFoundSnafu { region_id }.fail());
|
||||
return;
|
||||
}
|
||||
let result = match rx.await {
|
||||
Ok(result) => {
|
||||
result.map(|_| MitoCopyRegionFromResponse { copied_file_ids })
|
||||
}
|
||||
Err(error) => Err(error).context(crate::error::RecvSnafu),
|
||||
};
|
||||
let _ = sender.send(result);
|
||||
}
|
||||
// The edit — including shared references — is published by the worker
|
||||
// loop inside the window opened above: it persists the boundary and the
|
||||
// file set, then makes them visible in one version. Routing the shared
|
||||
// case back as a region edit instead would queue it behind that very
|
||||
// window, because the region is `Editing` for the whole copy, so the
|
||||
// copy would wait for an edit the loop only starts after the window is
|
||||
// released by the copy itself. The response lists installed references,
|
||||
// including shared SSTs whose objects stay in place; it is not a
|
||||
// physical COPY count.
|
||||
Some(region_edit) => {
|
||||
if let Err(e) = worker_sender
|
||||
.send(WorkerRequestWithTime::new(WorkerRequest::Background {
|
||||
@@ -145,9 +132,19 @@ impl<S> RegionWorkerLoop<S> {
|
||||
.await
|
||||
{
|
||||
error!(e; "Failed to send copy region from finished notification to worker, region_id: {}", region_id);
|
||||
if let Err(release) = region.end_publish_window(RegionLeaderState::Writable)
|
||||
{
|
||||
error!(release; "Failed to release the copy publish window of region {}", region_id);
|
||||
}
|
||||
resume_queued_writes(&worker_sender, region_id).await;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Nothing to publish: release the window before acknowledging.
|
||||
if let Err(e) = region.end_publish_window(RegionLeaderState::Writable) {
|
||||
error!(e; "Failed to release the copy publish window of region {}", region_id);
|
||||
}
|
||||
resume_queued_writes(&worker_sender, region_id).await;
|
||||
let _ = sender.send(Ok(MitoCopyRegionFromResponse {
|
||||
copied_file_ids: source_file_ids,
|
||||
}));
|
||||
@@ -156,15 +153,17 @@ impl<S> RegionWorkerLoop<S> {
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn handle_copy_region_from_finished(&mut self, request: CopyRegionFromFinished) {
|
||||
pub(crate) async fn handle_copy_region_from_finished(
|
||||
&mut self,
|
||||
request: CopyRegionFromFinished,
|
||||
) {
|
||||
let region_id = request.region_id;
|
||||
let sender = request.sender;
|
||||
let region = match self.regions.writable_region(region_id) {
|
||||
Ok(region) => region,
|
||||
Err(e) => {
|
||||
let _ = sender.send(Err(e));
|
||||
return;
|
||||
}
|
||||
// The state is `Editing` while the publish window is open, so it cannot be looked
|
||||
// up through `writable_region`.
|
||||
let Some(region) = self.regions.get_region(region_id) else {
|
||||
let _ = sender.send(RegionNotFoundSnafu { region_id }.fail());
|
||||
return;
|
||||
};
|
||||
|
||||
let copied_file_ids = request
|
||||
@@ -174,11 +173,18 @@ impl<S> RegionWorkerLoop<S> {
|
||||
.map(|file_meta| file_meta.file_id)
|
||||
.collect();
|
||||
|
||||
// Publish the copied files and the boundary in one version, then release the
|
||||
// window: the queued writes are admitted afterwards and obtain a sequence above
|
||||
// the boundary (see `handle_editing_window_closed`).
|
||||
region
|
||||
.version_control
|
||||
.apply_edit(Some(request.edit), &[], region.file_purger.clone());
|
||||
if let Err(e) = region.end_publish_window(RegionLeaderState::Writable) {
|
||||
error!(e; "Failed to release the copy publish window of region {}", region_id);
|
||||
}
|
||||
|
||||
let _ = sender.send(Ok(MitoCopyRegionFromResponse { copied_file_ids }));
|
||||
self.handle_editing_window_closed(region_id).await;
|
||||
}
|
||||
|
||||
/// Returns the region edit and source file IDs, including shared logical references.
|
||||
@@ -257,6 +263,17 @@ impl<S> RegionWorkerLoop<S> {
|
||||
parallelism,
|
||||
)
|
||||
.await?;
|
||||
let edit_sequence = region.version_control.current().last_sequence + 1;
|
||||
// Backfill the barrier on the copied files in the same publish: a barrier-less
|
||||
// copy would be reported as an incomplete discovery candidate set forever, so
|
||||
// the degraded path could never make progress. The rows are virtualized at the
|
||||
// barrier, which is exactly what `remap_copied_file_meta` refuses to trust from
|
||||
// the source domain.
|
||||
let mut new_file_metas = new_file_metas;
|
||||
for file in &mut new_file_metas {
|
||||
file.sequence = std::num::NonZeroU64::new(edit_sequence);
|
||||
file.preserve_row_sequence = false;
|
||||
}
|
||||
let edit = RegionEdit {
|
||||
files_to_add: new_file_metas,
|
||||
files_to_remove: vec![],
|
||||
@@ -264,16 +281,15 @@ impl<S> RegionWorkerLoop<S> {
|
||||
compaction_time_window: None,
|
||||
flushed_entry_id: None,
|
||||
flushed_sequence: None,
|
||||
committed_sequence: None,
|
||||
// Publish a committed watermark with the files, so a later full rebuild
|
||||
// starts above the copied rows instead of re-reading them.
|
||||
committed_sequence: Some(edit_sequence),
|
||||
..Default::default()
|
||||
};
|
||||
if edit
|
||||
.files_to_add
|
||||
.iter()
|
||||
.any(|file| file.level == file::LEVEL_SHARED)
|
||||
{
|
||||
return Ok((Some(edit), source_file_ids));
|
||||
}
|
||||
// Shared references are persisted on this path too. Handing them to the region
|
||||
// edit lane instead would drop them back onto the publish window the copy holds,
|
||||
// which is `Editing` for the whole copy, so they must be persisted and published
|
||||
// in the window like physically copied files (see `handle_copy_region_from_request`).
|
||||
let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone()));
|
||||
info!(
|
||||
"Applying {:?} to region {target_region_id}, reason: CopyRegionFrom",
|
||||
@@ -281,7 +297,7 @@ impl<S> RegionWorkerLoop<S> {
|
||||
);
|
||||
let version = region
|
||||
.manifest_ctx
|
||||
.update_manifest(RegionLeaderState::Writable, action_list, false)
|
||||
.update_manifest(RegionLeaderState::Editing, action_list, false)
|
||||
.await?;
|
||||
info!(
|
||||
"Successfully update manifest version to {version}, region: {target_region_id}, reason: CopyRegionFrom"
|
||||
|
||||
@@ -439,7 +439,19 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
waiters.reply_with(|| Err(error.clone()).context(EditRegionSnafu { region_id }));
|
||||
return RegionEditDispatch::Rejected;
|
||||
}
|
||||
|
||||
// An edit re-homes files; it records no region-level sequence boundary. The
|
||||
// numbers an imported file carries are its creator's, and a substitution is
|
||||
// stated per file by `FileMeta::substituted_up_to`, which the holder-side
|
||||
// re-mark keeps verbatim: the re-mark re-stamps `sequence` and clears
|
||||
// `preserve_row_sequence` for the files that changed hands, but it never invents
|
||||
// or clears a cut. That per-file record is the only statement of that kind the
|
||||
// engine keeps.
|
||||
//
|
||||
// `prepare_region_edit` already assigned the destination sequence to the
|
||||
// added files (keeping the source sequence of adopted shared files) and cleared
|
||||
// `preserve_row_sequence` only for the files whose `region_id` is another
|
||||
// region's; a file this region already owned keeps the marker it states, because
|
||||
// its row numbers were allocated here.
|
||||
// Allow retrieving `is_staging` before spawn the edit region task.
|
||||
let is_staging = region.is_staging();
|
||||
let expect_state = if is_staging {
|
||||
@@ -853,6 +865,9 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
let request_sender = self.sender.clone();
|
||||
let manifest_ctx = region.manifest_ctx.clone();
|
||||
let durability_barrier = self.wal.durability_barrier(region_id, ®ion.provider);
|
||||
// Discarding unflushed data drops rows the region owned; the rows that stay
|
||||
// keep their own numbers, so the action records no sequence boundary.
|
||||
let commit_watermark = region.version_control.current().last_sequence;
|
||||
|
||||
common_runtime::spawn_global(async move {
|
||||
// The frontier moves to the last written entry and sequence, so replaying the
|
||||
@@ -865,7 +880,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
compaction_time_window: None,
|
||||
flushed_entry_id: Some(discarded_entry_id),
|
||||
flushed_sequence: Some(discarded_sequence),
|
||||
committed_sequence: None,
|
||||
committed_sequence: Some(discarded_sequence.max(commit_watermark)),
|
||||
..Default::default()
|
||||
};
|
||||
let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit));
|
||||
@@ -1053,7 +1068,17 @@ fn prepare_region_edit(region: &MitoRegionRef, edit: &mut RegionEdit) -> Result<
|
||||
};
|
||||
for file in &mut edit.files_to_add {
|
||||
file.sequence = existing_sequence(file).or(sequence);
|
||||
file.preserve_row_sequence = false;
|
||||
// The marker is judged by ownership. An adopted file's `region_id` belongs to
|
||||
// another region, so its rows carry numbers this region never allocated and are
|
||||
// attributed by the creator's cursor and the file's own `substituted_up_to` cut:
|
||||
// its marker is cleared. A file this region already owned kept its bytes and its
|
||||
// numbering, so it keeps the marker the caller states. A repartition's staging
|
||||
// apply lands here as an edit too, and it must not clear the marker of a file
|
||||
// that merely stays in this region: that would deny every later exact `(C, H]`
|
||||
// read of the region (`read/scan_region.rs::exact_sequence_range`).
|
||||
if file.region_id != region_id {
|
||||
file.preserve_row_sequence = false;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -81,7 +81,9 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
let truncated_entry_id = version_data.last_entry_id;
|
||||
let truncated_sequence = version_data.committed_sequence;
|
||||
|
||||
// Write region truncated to manifest.
|
||||
// Write region truncated to manifest. Truncation drops rows, but the
|
||||
// rows it keeps carry their own numbers, so the action records no
|
||||
// sequence boundary.
|
||||
let truncate = RegionTruncate {
|
||||
region_id,
|
||||
kind: TruncateKind::All {
|
||||
|
||||
@@ -25,9 +25,9 @@ use store_api::logstore::LogStore;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::error::{
|
||||
InvalidRequestSnafu, PartitionExprVersionMismatchSnafu, RegionLeaseExpiredSnafu,
|
||||
RegionNotFoundSnafu, RegionStateSnafu, RejectWriteInStagingSnafu, RejectWriteSnafu, Result,
|
||||
UnacknowledgedWriteSnafu,
|
||||
EndStagingPendingSnafu, InvalidRequestSnafu, PartitionExprVersionMismatchSnafu,
|
||||
RegionLeaseExpiredSnafu, RegionNotFoundSnafu, RegionStateSnafu, RejectWriteInStagingSnafu,
|
||||
RejectWriteSnafu, Result, UnacknowledgedWriteSnafu,
|
||||
};
|
||||
use crate::metrics;
|
||||
use crate::metrics::{
|
||||
@@ -430,6 +430,17 @@ impl<S> RegionWorkerLoop<S> {
|
||||
.send(RejectWriteInStagingSnafu { region_id }.fail());
|
||||
continue;
|
||||
}
|
||||
// A frozen end-of-staging payload already fixes the boundary it publishes, so a
|
||||
// write admitted now could be attributed a sequence at or below it and report a
|
||||
// commit watermark `C >= B` before the published files are visible. Refuse it with
|
||||
// the retryable error of the pending commit instead of queueing it: the region is
|
||||
// `Staging` again, so nothing would release such a queue.
|
||||
if region.staging_end_pending() {
|
||||
sender_req
|
||||
.sender
|
||||
.send(EndStagingPendingSnafu { region_id }.fail());
|
||||
continue;
|
||||
}
|
||||
let expected_version = region.expected_partition_expr_version();
|
||||
if let Err(e) = check_partition_expr_version(
|
||||
region_id,
|
||||
@@ -585,6 +596,14 @@ impl<S> RegionWorkerLoop<S> {
|
||||
.send(RejectWriteInStagingSnafu { region_id }.fail());
|
||||
continue;
|
||||
}
|
||||
// See `process_write_requests`: a bulk write is refused for the same reason while the
|
||||
// region waits for its end-of-staging commit to be retried.
|
||||
if region.staging_end_pending() {
|
||||
bulk_req
|
||||
.sender
|
||||
.send(EndStagingPendingSnafu { region_id }.fail());
|
||||
continue;
|
||||
}
|
||||
let expected_version = region.expected_partition_expr_version();
|
||||
if let Err(e) = check_partition_expr_version(
|
||||
region_id,
|
||||
|
||||
Reference in New Issue
Block a user