fix(mito2): attribute rows only after the partition filter, and refuse an empty shard map

Three defects the reviewer reproduced on a shared SST:

- Cursor attribution saw every row of the batch, including rows the region
  partition filter had already excluded, so a sibling's unowned row refused
  the whole read. Attribution now runs only on rows that survived the filter;
  an owned row no piece selects still refuses.

- A piece whose identity parsed back as no expression took a fallback that
  returned Ok(None) and dropped the region partition filter, letting a
  sibling region's rows through. The fallback now collapses the candidates
  to the agreed sequence range and keeps the filter, so a whole-domain piece
  and an empty identity deliver the same rows.

- `creator_cursor_shards = Some(empty)` bypassed the no-shard refusal under
  `read_row_sequence`. A map whose every vector is empty now refuses with the
  same reason.

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9 committed 2026-12-03 19:55:10 +08:00
1 parent a1d59042a0
commit d93fbf2e6a
4 files changed
+378 -14

No files matched your search

@@ -21,7 +21,8 @@ use store_api::region_request::{AlterKind, RegionAlterRequest, RegionRequest, Se
use store_api::storage::{CursorShard, RegionId, ScanRequest};
use super::scan_slice_test::{
create_region, legacy_scan, piece_cursor, piece_scan, scan_error, scan_row_sequences,
create_region, legacy_scan, piece_cursor, piece_identity, piece_scan, scan_error,
scan_row_sequences,
};
use crate::config::MitoConfig;
use crate::engine::MitoEngine;
@@ -193,6 +194,47 @@ async fn create_target(engine: &MitoEngine, target: RegionId) {
.unwrap();
}
/// Creates the target region of a repartition, stating the value domain it owns.
async fn create_target_with_expr(engine: &MitoEngine, target: RegionId, partition_expr: String) {
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.partition_expr_json(Some(partition_expr))
.build();
engine
.handle_request(target, RegionRequest::Create(request))
.await
.unwrap();
}
/// Creates an append-only source region wide enough to hold the series `1`, `4` and `7`, writes
/// one row of each and flushes them.
///
/// The file holds rows of several regions' value domains — the shared SST these tests need —
/// numbered 1, 2 and 3 by the region that allocated them.
async fn build_shared_source_file(
engine: &MitoEngine,
source: RegionId,
) -> crate::sst::file::FileMeta {
let request = CreateRequestBuilder::new()
.insert_option("append_mode", "true")
.insert_option("preserve_row_sequence", "true")
.partition_expr_json(Some(piece_identity("0", "8")))
.build();
let schema = test_util::rows_schema(&request);
engine
.handle_request(source, RegionRequest::Create(request))
.await
.unwrap();
let mut rows = test_util::build_rows_for_key("1", 0, 1, 0);
rows.extend(test_util::build_rows_for_key("4", 1, 2, 0));
rows.extend(test_util::build_rows_for_key("7", 2, 3, 0));
test_util::put_rows(engine, source, Rows { schema, rows }).await;
test_util::flush_region(engine, source, None).await;
only_file(engine, source)
}
/// A row no candidate piece selects cannot be attributed to a piece, and the least advanced
/// cursor only answers for the pieces that carry it: with the candidates disagreeing, delivering
/// the row would duplicate the rows a more advanced piece has already consumed.
@@ -558,3 +600,129 @@ async fn test_piece_scan_refuses_an_unattributed_row_inside_the_union_of_the_ran
"the file's per-row rule is the one that must refuse the row: {err}"
);
}
/// A shared file holds the rows of several regions' value domains, and the region filter is what
/// excludes the rows of the others. Those rows have no piece in this region's shard map, so
/// attributing them would refuse a read whose own rows are all attributable.
#[tokio::test]
async fn test_piece_scan_exempts_the_rows_the_region_filter_excludes() {
let mut env = TestEnv::with_prefix("test_piece_scan_region_filter_excluded_rows").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 3);
let target = RegionId::new(1, 1);
// The same file adopted a second time: the region window decides which of its rows a read
// owns, so one region excludes the row of series 7 and the other one owns it.
let sibling = RegionId::new(1, 2);
let source_file = build_shared_source_file(&engine, source).await;
create_target_with_expr(&engine, target, piece_identity("0", "5")).await;
create_target_with_expr(&engine, sibling, piece_identity("0", "9")).await;
adopt_file(&engine, target, source_file.clone()).await;
adopt_file(&engine, sibling, source_file).await;
// Two pieces, cursors 0 and 1: the row of series 1 (number 1) is owed by `[0, 3)`, the row of
// series 4 (number 2) by `[3, 5)`, and the row of series 7 belongs to another region's domain.
let shards = || vec![piece_cursor("0", "3", 0), piece_cursor("3", "5", 1)];
let rows = scan_row_sequences(&engine, target, piece_scan(source, shards(), 0, 10)).await;
assert_eq!(
vec![(0, 1), (1000, 2)],
rows,
"the rows of the region's own domain are delivered, and the sibling's row is excluded \
before anything attributes it to a piece"
);
// The same file read through a region window that owns the row of series 7 as well: no cursor
// selects it, so the read still refuses instead of delivering it.
let err = scan_error(&engine, sibling, piece_scan(source, shards(), 0, 10)).await;
assert!(
matches!(err, Error::SequenceRangeUnsupported { .. }),
"a row inside the region window that no piece selects must fail the read: {err}"
);
}
/// A shard identity the parser reads back as no expression names no piece, so the file can only
/// be bounded by the rows every candidate agrees on. The region filter is what keeps a shared
/// file's other rows out, and it must survive that fallback: widening the read to them would
/// deliver the rows of another region.
#[tokio::test]
async fn test_piece_scan_keeps_the_region_filter_for_an_identity_without_an_expression() {
let mut env = TestEnv::with_prefix("test_piece_scan_identity_without_expression").await;
let engine = env.create_engine(MitoConfig::default()).await;
let source = RegionId::new(1, 2);
let target = RegionId::new(1, 1);
let source_file = build_shared_source_file(&engine, source).await;
create_target_with_expr(&engine, target, piece_identity("0", "5")).await;
adopt_file(&engine, target, source_file).await;
// A cursor of 0 owes every row of the target's domain.
let expected = vec![(0, 1), (1000, 2)];
let rows = scan_row_sequences(
&engine,
target,
piece_scan(source, vec![CursorShard::whole_domain(0)], 0, 10),
)
.await;
assert_eq!(
expected, rows,
"a whole-domain cursor keeps the region filter"
);
// The same cursor stating an empty identity, which parses back as no expression at all.
let rows = scan_row_sequences(
&engine,
target,
piece_scan(
source,
vec![CursorShard::new(Some(String::new()), 0)],
0,
10,
),
)
.await;
assert_eq!(
expected, rows,
"an identity that states no expression must not widen the read to the sibling's rows"
);
}
/// A request that states a cursor-shard map holding no shard states no cursor at all, so the read
/// cannot tell which rows it already consumed and must refuse instead of reading them unfiltered.
#[tokio::test]
async fn test_piece_scan_refuses_a_shard_map_without_a_shard() {
let mut env = TestEnv::with_prefix("test_piece_scan_shard_map_without_shard").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region = RegionId::new(1, 1);
// Two rows that never reach a file: only the cursor decides which of them the read owes.
let schema = create_region(&engine, region, "primary_key").await;
test_util::put_rows(
&engine,
region,
Rows {
schema,
rows: test_util::build_rows_for_key("1", 0, 2, 0),
},
)
.await;
// One entry whose vector holds no shard.
let mut request = piece_scan(region, Vec::new(), 1, 20);
let err = scan_error(&engine, region, request.clone()).await;
assert!(
matches!(err, Error::SequenceRangeUnsupported { .. }),
"a shard map holding no shard states no cursor, so the read must refuse: {err}"
);
assert!(
err.to_string().contains("states no cursor shard"),
"the refusal must name the missing cursor shard: {err}"
);
// A map with no entry at all.
request.creator_cursor_shards = Some(Arc::new(BTreeMap::new()));
let err = scan_error(&engine, region, request).await;
assert!(
matches!(err, Error::SequenceRangeUnsupported { .. }),
"a map with no entry states no cursor either, so the read must refuse: {err}"
);
}
+14
View File
@@ -493,6 +493,20 @@ impl ScanRegion {
if !self.request.read_row_sequence {
return Ok(Some(shards));
}
if shards
.values()
.all(|region_shards| region_shards.is_empty())
{
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: "a physical-sequence read states no cursor shard, so it cannot tell \
which rows it already consumed"
.to_string(),
}
.fail();
}
let Some(SequenceRange::GtLtEq {
min: floor,
max: own_upper,
+116 -2
View File
@@ -469,7 +469,7 @@ impl RangeBase {
// piece 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)?;
self.evaluate_creator_slices(&input, &record_batch, partition_filter, &mask)?;
mask = mask.bitand(&sequence_mask);
}
}
@@ -740,11 +740,17 @@ impl RangeBase {
/// A row no piece expression selects has no piece to attribute it to, so it takes
/// [`PartitionFilterContext::fallback_range`], which exists only when every candidate
/// carries the same range. Otherwise the read fails rather than guessing.
///
/// Only a row the read still delivers is attributed: `surviving` holds the rows the earlier
/// filters of `precise_filter_flat` kept, and a row they excluded — another region's row in
/// a shared file, say — has no piece here because this region's shard map says nothing about
/// it.
fn evaluate_creator_slices(
&self,
input: &RecordBatch,
record_batch: &RecordBatch,
partition_filter: &PartitionFilterContext,
surviving: &BooleanBuffer,
) -> Result<BooleanBuffer> {
let num_rows = input.num_rows();
let slices = &partition_filter.creator_slices;
@@ -779,6 +785,10 @@ impl RangeBase {
let mut kept = BooleanBufferBuilder::new(num_rows);
for row in 0..num_rows {
if !surviving.value(row) {
kept.append(false);
continue;
}
// The pieces are disjoint, so at most one expression selects a row, and a whole-domain
// piece selects every row. If more than one selects it, a piece that still owes the
// row is enough: one piece's range never widens another's.
@@ -898,9 +908,11 @@ mod tests {
new_record_batch_with_custom_sequence, sst_region_metadata,
sst_region_metadata_with_encoding,
};
use api::v1::OpType;
use datafusion_expr::{col, lit};
use datatypes::arrow::array::{
BinaryDictionaryBuilder, TimestampMillisecondArray, UInt8Array, UInt64Array,
BinaryDictionaryBuilder, StringDictionaryBuilder, TimestampMillisecondArray, UInt8Array,
UInt64Array,
};
use datatypes::arrow::datatypes::UInt32Type;
use datatypes::prelude::ConcreteDataType;
@@ -1194,6 +1206,108 @@ mod tests {
}
}
/// A flat batch of `(tag_0, sequence)` rows, encoded the way a file states the numbers its
/// allocating region assigned.
fn piece_batch(rows: &[(&str, u64)]) -> RecordBatch {
let metadata = Arc::new(sst_region_metadata());
let flat_schema = to_flat_sst_arrow_schema(&metadata, &FlatSchemaOptions::default());
let mut tag_0 = StringDictionaryBuilder::<UInt32Type>::new();
let mut tag_1 = StringDictionaryBuilder::<UInt32Type>::new();
let mut pk = BinaryDictionaryBuilder::<UInt32Type>::new();
let mut field = Vec::with_capacity(rows.len());
let mut ts = Vec::with_capacity(rows.len());
let mut sequences = Vec::with_capacity(rows.len());
let mut op_types = Vec::with_capacity(rows.len());
for (index, (tag, sequence)) in rows.iter().enumerate() {
tag_0.append_value(tag);
tag_1.append_value(tag);
pk.append(&crate::test_util::sst_util::new_primary_key(&[tag, tag]))
.unwrap();
field.push(index as u64);
ts.push(index as i64);
sequences.push(*sequence);
op_types.push(OpType::Put as u8);
}
RecordBatch::try_new(
flat_schema,
vec![
Arc::new(tag_0.finish()),
Arc::new(tag_1.finish()),
Arc::new(UInt64Array::from(field)),
Arc::new(TimestampMillisecondArray::from(ts)),
Arc::new(pk.finish()),
Arc::new(UInt64Array::from(sequences)),
Arc::new(UInt8Array::from(op_types)),
],
)
.unwrap()
}
/// A shared file holds the rows of several regions' value domains, and the region filter is
/// what excludes the rows of the others. Those rows carry no cursor of this region's shard
/// map, so attributing them would refuse a read whose own rows are all attributable.
///
/// The pieces `[0, 3)` and `[3, 5)` are cursors 0 and 1 of the region that allocated the file's
/// numbers, which owns the series `1` and `4` but not the series `7`.
#[test]
fn test_precise_filter_flat_attributes_only_the_rows_the_filters_keep() {
// The series `1`, `4` and `7`, numbered 1..3 by their creator.
let batch = piece_batch(&[("1", 1), ("4", 2), ("7", 3)]);
let batch_schema = batch.schema();
let tag_field = batch_schema.field(0);
let partition_schema = Arc::new(Schema::new(vec![ColumnSchema::new(
"tag_0".to_string(),
ConcreteDataType::from_arrow_type(tag_field.data_type()),
tag_field.is_nullable(),
)]));
let piece = |lo: &str, hi: &str, seq: u64| CreatorSliceFilter {
filter: Some(
partition_col("tag_0")
.gt_eq(Value::String(lo.into()))
.and(partition_col("tag_0").lt(Value::String(hi.into())))
.try_as_physical_expr(partition_schema.arrow_schema())
.unwrap(),
),
range: SequenceRange::Gt { min: seq },
};
let base = |owned_until: &str| {
let mut base = new_test_range_base(vec![]);
base.partition_filter = Some(PartitionFilterContext {
region_partition_physical_expr: Some(
partition_col("tag_0")
.gt_eq(Value::String("0".into()))
.and(partition_col("tag_0").lt(Value::String(owned_until.into())))
.try_as_physical_expr(partition_schema.arrow_schema())
.unwrap(),
),
partition_schema: partition_schema.clone(),
creator_slices: vec![piece("0", "3", 0), piece("3", "5", 1)],
fallback_range: None,
});
base
};
// The region owns the series `1` and `4`: the row of series `7` is excluded before
// anything attributes it to a piece, so the read keeps the two rows it owes.
let filtered = base("5")
.precise_filter_flat(batch.clone(), false, false)
.unwrap()
.expect("the rows of the region's own domain are delivered");
assert_eq!(2, filtered.num_rows());
// A region window that owns the series `7` as well leaves its row unattributed, and the
// candidates disagree on the rows they owe, so the read refuses instead of delivering it.
let err = base("9")
.precise_filter_flat(batch, false, false)
.unwrap_err();
assert!(
matches!(err, crate::error::Error::SequenceRangeUnsupported { .. }),
"a row inside the region window that no piece selects must fail the read: {err}"
);
}
#[test]
fn test_compute_filter_mask_flat_does_not_postfilter_physical_filters() {
let metadata: RegionMetadataRef = Arc::new(sst_region_metadata());
+79 -11
View File
@@ -790,15 +790,6 @@ impl ParquetReaderBuilder {
.map(|metadata| metadata.region_id)
.unwrap_or_else(|| read_format.metadata().region_id);
let meta = self.file_handle.meta_ref();
let refuse = |detail: &str| -> Result<()> {
agreed_piece_rows_or_refuse(
scan_region_id,
&format!("file {} of region {}", meta.file_id, meta.region_id),
cursors,
detail,
)
.map(|_| ())
};
let mut piece_exprs = Vec::with_capacity(cursors.len());
for cursor in cursors {
// A whole-domain cursor selects every row: it takes part in the per-row rule as a
@@ -814,10 +805,20 @@ impl ParquetReaderBuilder {
}
})?
else {
refuse(
// The identity names no piece this build can read back, so no row can be
// attributed to one: collapse the candidates into the single whole-domain piece
// they agree on, the way the memtable side does, and keep the region filter. A
// file another region shares holds rows this region's cursors say nothing about,
// and only that filter can exclude them.
let agreed = agreed_piece_rows_or_refuse(
scan_region_id,
&format!("file {} of region {}", meta.file_id, meta.region_id),
cursors,
"it cannot read back the partition expression of one of its candidate pieces",
)?;
return Ok(None);
piece_exprs.clear();
piece_exprs.extend(agreed.map(|range| (None, range)));
break;
};
expr.collect_column_names(&mut referenced_columns);
piece_exprs.push((Some(expr), cursor.rows_owed()));
@@ -2998,6 +2999,73 @@ mod tests {
}
}
/// A shared file holds the rows of several regions' value domains, and the region filter is
/// what excludes the rows of the others. A candidate piece whose identity the parser reads
/// back as no expression cannot decide a piece, so the file is bounded by the rows every
/// candidate agrees on — but the region filter must survive that fallback: it is the only
/// thing that keeps another region's rows out, and a whole-domain piece cannot replace it.
#[tokio::test]
async fn test_partition_filter_keeps_the_region_filter_when_a_piece_states_no_expression() {
let source = crate::test_util::sst_util::sst_region_metadata_with_encoding(
PrimaryKeyEncoding::Sparse,
);
let props = WriterProperties::builder()
.set_key_value_metadata(Some(vec![parquet::file::metadata::KeyValue::new(
crate::sst::parquet::PARQUET_METADATA_KEY.to_string(),
source.to_json().unwrap(),
)]))
.build();
let store = ObjectStore::new(Memory::default()).unwrap();
// One file of six rows, of which the series `b` row belongs to another region's domain.
let (fixture, metadata) = prefilter_test_builder_with(
store.clone(),
2,
3,
PageIndexPolicy::Skip,
Some(props),
Predicate::new(vec![col("tag_0").eq(lit("a"))]),
CacheStrategy::Disabled,
)
.await;
let mut expected = metadata.as_ref().clone();
expected.set_partition_expr(Some(
partition::expr::col("tag_0")
.eq(datatypes::value::Value::String("a".into()))
.as_json_str()
.unwrap(),
));
let expected = Arc::new(expected);
for (cursors, expected_rows) in [
(vec![CursorShard::whole_domain(0)], 5),
(vec![CursorShard::new(Some(String::new()), 0)], 5),
] {
// No predicate: the region filter of the reader is the only statement about the
// file's value domains.
let mut reader = ParquetReaderBuilder::new(
"prefilter_test".into(),
PathType::Bare,
fixture.file_handle.clone(),
store.clone(),
)
.expected_metadata(Some(expected.clone()))
.read_row_sequence(true)
.creator_slice_cursors(Some(Arc::new(cursors.clone())))
.build()
.await
.unwrap()
.unwrap();
let mut rows = 0;
while let Some(batch) = reader.next_record_batch().await.unwrap() {
rows += batch.num_rows();
}
assert_eq!(
expected_rows, rows,
"{cursors:?}: the region filter keeps the rows of the other domain out"
);
}
}
#[rstest::rstest]
#[case(None)]
#[case(Some(false))]