mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
feat(mito2,query,store-api): read each row by the cursor of the piece it belongs to
A region can hold several slices of one creator's value domain after a repartition, each at its own position, but the read gave every row one floor for the whole region: files used the least advanced slice and both memtable kinds used the same single number, so a lagging sibling re-delivered the rows a more advanced piece had already consumed. Select the piece per row — the slice's expression on the row's own columns — and apply that piece's cursor and its stated upper bound, for files and for both memtable kinds. A piece that cannot be resolved fails the read when the candidates disagree instead of silently using the least cursor, and a slice whose bound sits below its own cursor is refused rather than turned into an empty range. Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
Vendored
+25
-1
@@ -39,6 +39,7 @@ use crate::error::{ComputeArrowSnafu, Result};
|
||||
use crate::metrics::{CACHE_BYTES, CACHE_EVICTION, RANGE_CACHE_WORKER_EVENTS};
|
||||
use crate::read::BoxedRecordBatchStream;
|
||||
use crate::read::range_cache::RangeScanCacheKey;
|
||||
use crate::read::substituted_rows::ForeignFileRowCreators;
|
||||
use crate::sst::file::FileHandle;
|
||||
use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE;
|
||||
|
||||
@@ -140,6 +141,10 @@ impl RangeResultCache {
|
||||
}
|
||||
|
||||
/// Replays a cached result or subscribes to one reader-owned streaming scan.
|
||||
///
|
||||
/// `replay_evidence` is the reading scan's `ForeignFileRowCreators`, which is told when the
|
||||
/// result this call returns did not decode the files of the caller's own scan: the creators
|
||||
/// of the rows such a result delivers are then not recoverable from this call.
|
||||
#[tracing::instrument(name = "range_result_lookup", skip_all)]
|
||||
pub(crate) async fn read<F, Fut>(
|
||||
self: &Arc<Self>,
|
||||
@@ -147,6 +152,7 @@ impl RangeResultCache {
|
||||
part_metrics: Arc<dyn RangeCacheMetricsReport>,
|
||||
files: Vec<FileHandle>,
|
||||
scope: RangeCacheScope,
|
||||
replay_evidence: Option<&ForeignFileRowCreators>,
|
||||
build: F,
|
||||
) -> Result<(BoxedRecordBatchStream, usize)>
|
||||
where
|
||||
@@ -157,6 +163,12 @@ impl RangeResultCache {
|
||||
let load = match cache.get_or_register(key, files, scope) {
|
||||
RangeCacheLookup::Hit(value) => {
|
||||
part_metrics.inc_range_cache_hit();
|
||||
// The rows of a completed range were decoded by whichever scan built it: the
|
||||
// files they came from are not read again, so their creators cannot be named
|
||||
// from this call.
|
||||
if let Some(creators) = replay_evidence {
|
||||
creators.record_replay_unknown();
|
||||
}
|
||||
let batch_size = value.value().estimated_batch_size;
|
||||
return Ok((cached_flat_range_stream(value), batch_size));
|
||||
}
|
||||
@@ -190,7 +202,19 @@ impl RangeResultCache {
|
||||
let batch_size = *batch_size;
|
||||
let cursor = match owner_cursor {
|
||||
Some(cursor) => Some(cursor),
|
||||
None => shared.subscribe().await,
|
||||
None => {
|
||||
let cursor = shared.subscribe().await;
|
||||
// Another caller built this range, so the rows come from its source. Its files
|
||||
// were decoded there, and whether that source recorded them into this scan's
|
||||
// `ForeignFileRowCreators` is not knowable here, so this call cannot state an
|
||||
// answer for the rows it delivers.
|
||||
if cursor.is_some()
|
||||
&& let Some(creators) = replay_evidence
|
||||
{
|
||||
creators.record_replay_unknown();
|
||||
}
|
||||
cursor
|
||||
}
|
||||
};
|
||||
let Some(mut cursor) = cursor else {
|
||||
// An oversized range has closed admission. This caller has not emitted
|
||||
|
||||
+31
-4
@@ -74,6 +74,14 @@ mod row_selector_test;
|
||||
#[cfg(test)]
|
||||
mod scan_corrupt;
|
||||
#[cfg(test)]
|
||||
mod scan_slice_bounds_test;
|
||||
#[cfg(test)]
|
||||
mod scan_slice_cache_test;
|
||||
#[cfg(test)]
|
||||
mod scan_slice_fail_closed_test;
|
||||
#[cfg(test)]
|
||||
mod scan_slice_test;
|
||||
#[cfg(test)]
|
||||
mod scan_test;
|
||||
#[cfg(test)]
|
||||
mod sequence_test;
|
||||
@@ -1528,6 +1536,14 @@ fn validate_sequence_fences(
|
||||
exact_sequence_range_available: bool,
|
||||
extension_provider_blocks_exact: bool,
|
||||
) -> Result<()> {
|
||||
// A read that may cross a boundary a stale cursor can no longer explain prunes at file
|
||||
// granularity and reads no row-level sequence range, so the sequence fences below do not
|
||||
// apply: the caller only needs the timestamps of the surviving rows, and rejecting the
|
||||
// request would deadlock recovery.
|
||||
if request.read_across_invalid_boundary {
|
||||
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 +1584,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 +1633,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()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
// 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.
|
||||
|
||||
use store_api::storage::{CursorShard, RegionId};
|
||||
|
||||
use super::scan_test::{
|
||||
adopt_foreign_file, build_foreign_source_file, create_foreign_target, creator_cursor_scan,
|
||||
partition_str_slice_cursor, scan_flat_row_sequences,
|
||||
};
|
||||
use crate::config::MitoConfig;
|
||||
use crate::test_util::TestEnv;
|
||||
|
||||
/// A creator slice that states the last sequence its delta covers bounds an adopted file from
|
||||
/// above as well: a row above that bound was numbered after the delta this read stands for,
|
||||
/// so delivering it here reports identity the caller has not consumed yet while its marker
|
||||
/// stays below the row's number.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_drops_adopted_rows_above_creator_upper_bound() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_creator_upper_bound").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
// The creator's file states the numbers 1..5 and no cut, so the cursor decides alone.
|
||||
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 6, true, None);
|
||||
|
||||
// The delta is `(1, 3]`: rows 4 and 5 carry numbers the creator's cursor did not consume
|
||||
// and its bound does not cover, so this round must not read them.
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![CursorShard::whole_domain(1).with_until(3)],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vec![(1000, 2), (2000, 3)],
|
||||
rows,
|
||||
"the rows above the creator's upper bound belong to a later delta, not to this read"
|
||||
);
|
||||
|
||||
// The bound is a filter on the creator's domain, not a change of the cursor: stating a
|
||||
// bound that covers every row delivers every row above the cursor, as before.
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![CursorShard::whole_domain(1).with_until(5)],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)], rows);
|
||||
}
|
||||
|
||||
/// A slice that states no upper bound keeps the unbounded `(cursor, +inf)` filter it always
|
||||
/// had: the bound is optional evidence, and a read that lacks it must not lose a row that no
|
||||
/// bound excludes.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_reads_above_cursor_without_creator_upper_bound() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_without_upper_bound").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_foreign_source_file(&engine, source, 5, true).await;
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 6, true, None);
|
||||
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(source, vec![CursorShard::whole_domain(1)], 0, 10),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)],
|
||||
rows,
|
||||
"without a bound every row above the creator's cursor is still owed"
|
||||
);
|
||||
}
|
||||
|
||||
/// Several candidate slices: the file-level upper bound is the **least** bound any of them
|
||||
/// states, because the file-level filter cannot tell which slice a row belongs to. The
|
||||
/// counterexample this pins: the slice holding the file's rows proves the delta ends at 3
|
||||
/// while another candidate's bound reaches 9, and reading up to 9 delivers rows 4 and 5,
|
||||
/// which no slice yields this round.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_takes_the_least_creator_upper_bound() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_least_upper_bound").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
// One file stating no expression, so every slice of the creator is a candidate for it.
|
||||
// Its five rows carry the tag `0`, i.e. they all fall in the `[0, 5)` slice.
|
||||
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
|
||||
assert_eq!(None, source_file.partition_expr);
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 6, true, None);
|
||||
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
// The slice the file's rows belong to: consumed up to 1, delta ends at 3.
|
||||
partition_str_slice_cursor("0", "5", 1).with_until(3),
|
||||
// A candidate that overlaps no row of this file, with a looser bound.
|
||||
partition_str_slice_cursor("5", "9", 3).with_until(9),
|
||||
],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vec![(1000, 2), (2000, 3)],
|
||||
rows,
|
||||
"the file-level bound is the least bound of the candidates, so row 4 is left out"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// 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.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use api::v1::Rows;
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use datafusion_common::ScalarValue;
|
||||
use datafusion_expr::{col, lit};
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_request::RegionRequest;
|
||||
use store_api::storage::{RegionId, TimeSeriesRowSelector};
|
||||
|
||||
use super::scan_test::{
|
||||
adopt_foreign_file, create_foreign_target, creator_cursor_scan, manifest_files,
|
||||
partition_str_slice_cursor, scan_partition_rows_and_foreign_creators,
|
||||
};
|
||||
use crate::config::MitoConfig;
|
||||
use crate::test_util;
|
||||
use crate::test_util::{CreateRequestBuilder, TestEnv};
|
||||
|
||||
/// A range result is only reusable for a read whose **per-piece** selection is the same.
|
||||
///
|
||||
/// A physical-sequence read decides each row of an adopted file by the creator cursor slice
|
||||
/// that selects it, and bounds the file by `(least advanced cursor, least until]`. Neither is
|
||||
/// stated by the file, so two reads of the same file under the same region-level `(C, H]`
|
||||
/// deliver different rows once a piece cursor or an `until` advances; a cache key that only
|
||||
/// records `(C, H]` replays the first read's rows to all of them.
|
||||
///
|
||||
/// The counterexample this pins: `(cursor 0, until 6]` caches the rows 1..6, `(cursor 3,
|
||||
/// until 8]` requires the rows 4..8, and `(cursor 0, until 2]` requires the rows 1..2 and
|
||||
/// nothing above its `until`. Replaying the first result delivers the rows 1..6 to all three:
|
||||
/// rows an advanced piece already consumed, rows the new range requires that are missing, and
|
||||
/// rows above the new `until`.
|
||||
///
|
||||
/// The `LastRow` selector is what puts this read on the sequential scan, the only path that
|
||||
/// fills the range result cache: without it an append-only region reads through the unordered
|
||||
/// scan, which bypasses the cache entirely.
|
||||
#[tokio::test]
|
||||
async fn test_range_cache_never_replays_a_range_read_under_other_creator_cursors() {
|
||||
let mut env = TestEnv::with_prefix("test_range_cache_creator_cursor_slices").await;
|
||||
let engine = env
|
||||
.create_engine(MitoConfig {
|
||||
// The flat format is the one the range result cache covers.
|
||||
default_flat_format: true,
|
||||
range_result_cache_size: ReadableSize::mb(64),
|
||||
..Default::default()
|
||||
})
|
||||
.await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
// Eight rows numbered 1..8, one per series, all of them in one file of the creator. The
|
||||
// holder adopts that file as a foreign file.
|
||||
let create = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.build();
|
||||
let schema = test_util::rows_schema(&create);
|
||||
engine
|
||||
.handle_request(source, RegionRequest::Create(create))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut rows = Vec::new();
|
||||
for series in 0..8_usize {
|
||||
rows.extend(test_util::build_rows_for_key(
|
||||
&series.to_string(),
|
||||
series,
|
||||
series + 1,
|
||||
0,
|
||||
));
|
||||
}
|
||||
test_util::put_rows(&engine, source, Rows { schema, rows }).await;
|
||||
test_util::flush_region(&engine, source, None).await;
|
||||
let source_file = manifest_files(&engine, source)
|
||||
.await
|
||||
.into_values()
|
||||
.next()
|
||||
.expect("flushed file");
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 20, true, None);
|
||||
|
||||
// The `(cursor, until]` of the one piece the rows of the adopted file belong to. The
|
||||
// region-level `(0, 20]` is the same in every read, so only the slice separates them; the
|
||||
// tag filter is what makes the range eligible for the cache.
|
||||
let request = |cursor: u64, until: u64| {
|
||||
let mut request = creator_cursor_scan(
|
||||
source,
|
||||
vec![partition_str_slice_cursor("0", "9", cursor).with_until(until)],
|
||||
0,
|
||||
20,
|
||||
);
|
||||
request.filters = vec![col("tag_0").gt_eq(lit(ScalarValue::Utf8(Some("0".to_string()))))];
|
||||
request.series_row_selector = Some(TimeSeriesRowSelector::LastRow { after_merge: false });
|
||||
request
|
||||
};
|
||||
|
||||
let first = scan_partition_rows_and_foreign_creators(&engine, target, request(0, 6))
|
||||
.await
|
||||
.0;
|
||||
assert_eq!(
|
||||
vec![0, 1000, 2000, 3000, 4000, 5000],
|
||||
first,
|
||||
"the first read delivers the rows above its cursor and up to its `until`"
|
||||
);
|
||||
|
||||
// Wait for the completed range result: the same read then replays it, which it reports by
|
||||
// saying that the files its rows came from are not readable from that call.
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let (rows, creators) =
|
||||
scan_partition_rows_and_foreign_creators(&engine, target, request(0, 6)).await;
|
||||
assert_eq!(first, rows, "a replay delivers the rows it replayed");
|
||||
if creators.is_none() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the range result cache did not replay the range within the timeout");
|
||||
|
||||
// An advanced piece cursor with a higher `until`: the rows 4..8 are what this range
|
||||
// requires, and the rows 1..3 are already consumed.
|
||||
let advanced = scan_partition_rows_and_foreign_creators(&engine, target, request(3, 8))
|
||||
.await
|
||||
.0;
|
||||
assert_eq!(
|
||||
vec![3000, 4000, 5000, 6000, 7000],
|
||||
advanced,
|
||||
"a read under an advanced piece cursor must not replay the rows of the earlier read: \
|
||||
only its own `(cursor, until]` decides"
|
||||
);
|
||||
|
||||
// A narrower `until`: no row above it may be delivered, whatever an earlier read of the
|
||||
// same files cached.
|
||||
let bounded = scan_partition_rows_and_foreign_creators(&engine, target, request(0, 2))
|
||||
.await
|
||||
.0;
|
||||
assert_eq!(
|
||||
vec![0, 1000],
|
||||
bounded,
|
||||
"a range result must never deliver a row above the `until` of the read it serves"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
// 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.
|
||||
|
||||
use api::v1::Rows;
|
||||
use futures::TryStreamExt;
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_request::RegionRequest;
|
||||
use store_api::storage::{CursorShard, RegionId};
|
||||
|
||||
use super::scan_test::{
|
||||
adopt_foreign_file, build_foreign_source_file, create_foreign_target, creator_cursor_scan,
|
||||
manifest_files, partition_str_slice_cursor, physical_sequence_scan, scan_flat_row_sequences,
|
||||
};
|
||||
use crate::config::MitoConfig;
|
||||
use crate::error::Error;
|
||||
use crate::test_util;
|
||||
use crate::test_util::{CreateRequestBuilder, TestEnv};
|
||||
|
||||
/// The same rule at the memtable end of a scan: the per-piece rule of this region's own
|
||||
/// memtable is built from the region's own cursor slices, so a slice set the read cannot
|
||||
/// apply per row (a slice covering the whole value domain, or an identity this build cannot
|
||||
/// read back) keeps the region-level floor only while every candidate carries it. With
|
||||
/// several cursor values the floor delivers the rows a more advanced piece consumed, so the
|
||||
/// read fails just like it does for a file of an adopted creator.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_fails_closed_when_memtable_pieces_are_unresolved() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed_memtable_pieces").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let region = RegionId::new(1, 1);
|
||||
|
||||
// Five rows in the time-series memtable (numbers 1..5): no flush, so no file takes part
|
||||
// in the read.
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.insert_option("sst_format", "primary_key")
|
||||
.build();
|
||||
let schema = test_util::rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
test_util::put_rows(
|
||||
&engine,
|
||||
region,
|
||||
Rows {
|
||||
schema,
|
||||
rows: test_util::build_rows_for_key("1", 0, 5, 0),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// A whole-domain slice at 3 next to a piece slice at 1: no row of the memtable can be
|
||||
// attributed to a piece, and the region-level floor (1) would deliver the rows 2 and 3
|
||||
// the more advanced piece has already consumed.
|
||||
let err = match engine
|
||||
.scan_batch(
|
||||
region,
|
||||
creator_cursor_scan(
|
||||
region,
|
||||
vec![
|
||||
CursorShard::whole_domain(3),
|
||||
partition_str_slice_cursor("0", "5", 1),
|
||||
],
|
||||
1,
|
||||
20,
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Err(err) => err,
|
||||
Ok(mut stream) => match stream.try_next().await {
|
||||
Err(err) => err,
|
||||
Ok(_) => panic!("an unresolvable memtable piece with disagreeing cursors must fail"),
|
||||
},
|
||||
};
|
||||
let message = format!("{err}");
|
||||
assert!(
|
||||
message.contains("exact sequence range unavailable"),
|
||||
"the shared exact-range contract prefix must reach the caller: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("the memtable of region")
|
||||
&& message.contains("covers the whole value domain"),
|
||||
"the failure must name the memtable and say what could not be resolved: {message}"
|
||||
);
|
||||
|
||||
// One cursor value for every candidate: the region-level floor is the per-row answer, so
|
||||
// the rows above 1 are delivered exactly as before.
|
||||
let mut rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
region,
|
||||
creator_cursor_scan(
|
||||
region,
|
||||
vec![
|
||||
CursorShard::whole_domain(1),
|
||||
partition_str_slice_cursor("0", "5", 1),
|
||||
],
|
||||
1,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
rows.sort_unstable();
|
||||
assert_eq!(
|
||||
vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)],
|
||||
rows,
|
||||
"one cursor value for every piece is the region-level floor of the whole read"
|
||||
);
|
||||
}
|
||||
|
||||
/// A creator this scan has no cursor slice for fails closed. Reading the file against this
|
||||
/// region's own `(C, H]` compares two sequence domains, and reading it unfiltered delivers
|
||||
/// every already consumed row again on every round; the scan reports the shared
|
||||
/// "exact range unavailable" contract instead of choosing one of them.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_fails_closed_without_creator_cursor() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed").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_foreign_source_file(&engine, source, 3, true).await;
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 4, true, None);
|
||||
|
||||
// No creator slice, and no cut either: the file states nothing this scan can filter
|
||||
// with.
|
||||
let mut stream = engine
|
||||
.scan_batch(target, physical_sequence_scan(true), true)
|
||||
.await
|
||||
.unwrap();
|
||||
let err = match stream.try_next().await {
|
||||
Err(err) => err,
|
||||
Ok(_) => panic!("a foreign file without a creator cursor must fail closed"),
|
||||
};
|
||||
let message = format!("{err}");
|
||||
assert!(
|
||||
message.contains("exact sequence range unavailable"),
|
||||
"the shared exact-range contract prefix must reach the caller: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("no cursor slice of its creator region"),
|
||||
"the failure must say what is missing: {message}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The `Display` of `err` and of every cause below it, one per line.
|
||||
///
|
||||
/// A file-level decision is taken while the file is pruned, and the pruner reports a failed
|
||||
/// file through a wrapper whose own `Display` does not repeat the cause, so the failure is
|
||||
/// found in the chain.
|
||||
fn error_chain(err: &Error) -> String {
|
||||
let mut text = format!("{err}");
|
||||
let mut source = std::error::Error::source(err);
|
||||
while let Some(cause) = source {
|
||||
text.push('\n');
|
||||
text.push_str(&format!("{cause}"));
|
||||
source = cause.source();
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The counterexample to the file-level fallback of a physical-sequence read: when the
|
||||
/// per-row rule of a file cannot be applied, the file is bounded by the **least** advanced
|
||||
/// candidate. That floor is exact only while every candidate carries it — with several cursor
|
||||
/// values it re-delivers the rows a more advanced piece has already consumed, so the read
|
||||
/// fails instead of degrading an exact read into a duplicate.
|
||||
///
|
||||
/// Two shapes the per-row rule cannot apply, both on a file of an adopted creator: a slice
|
||||
/// identity this build cannot read back, and a slice covering the whole value domain.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_fails_closed_when_pieces_disagree_and_piece_is_unresolved() {
|
||||
let mut env =
|
||||
TestEnv::with_prefix("test_read_row_sequence_fails_closed_disagreeing_pieces").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
// One file stating no expression, so every slice of the creator is a candidate for it.
|
||||
let (_, source_file) = build_foreign_source_file(&engine, source, 5, true).await;
|
||||
assert_eq!(None, source_file.partition_expr);
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 6, true, None);
|
||||
|
||||
// The JSON `"MaxValue"` is a partition *bound*, not an expression: this build cannot read
|
||||
// it back, so the file cannot be split per row. The two candidates carry different
|
||||
// cursors, so the file-level floor (1) would deliver the rows 2 and 3 a piece consumed up
|
||||
// to 3 again.
|
||||
let unreadable = |cursor| CursorShard::new(Some("\"MaxValue\"".to_string()), cursor);
|
||||
let mut stream = engine
|
||||
.scan_batch(
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![partition_str_slice_cursor("0", "5", 1), unreadable(3)],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let err = match stream.try_next().await {
|
||||
Err(err) => err,
|
||||
Ok(_) => {
|
||||
panic!("an unreadable slice identity with disagreeing cursors must fail the read")
|
||||
}
|
||||
};
|
||||
let message = error_chain(&err);
|
||||
assert!(
|
||||
message.contains("exact sequence range unavailable"),
|
||||
"the shared exact-range contract prefix must reach the caller: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("cannot resolve a per-piece cursor"),
|
||||
"the failure must say what could not be resolved: {message}"
|
||||
);
|
||||
|
||||
// One cursor value for every candidate: the file-level floor *is* the per-row answer, so
|
||||
// the unreadable identity keeps today's fallback and the rows above it are delivered.
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![partition_str_slice_cursor("0", "5", 1), unreadable(1)],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)],
|
||||
rows,
|
||||
"with one cursor value the file-level floor is exact and nothing is dropped"
|
||||
);
|
||||
|
||||
// A whole-domain slice cannot be evaluated per row either: it applies to every row, so no
|
||||
// slice expression can tell which piece a row belongs to. With disagreeing cursors the
|
||||
// same rule applies.
|
||||
let mut stream = engine
|
||||
.scan_batch(
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
CursorShard::whole_domain(3),
|
||||
partition_str_slice_cursor("0", "5", 1),
|
||||
],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let err = match stream.try_next().await {
|
||||
Err(err) => err,
|
||||
Ok(_) => panic!("a whole-domain slice with disagreeing cursors must fail the read"),
|
||||
};
|
||||
let message = error_chain(&err);
|
||||
assert!(
|
||||
message.contains("cannot resolve a per-piece cursor")
|
||||
&& message.contains("covers the whole value domain"),
|
||||
"the failure must say that the slice covers the whole domain: {message}"
|
||||
);
|
||||
|
||||
// The same whole-domain read with one cursor value for every candidate keeps the
|
||||
// file-level floor, exactly as before.
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
CursorShard::whole_domain(1),
|
||||
partition_str_slice_cursor("0", "5", 1),
|
||||
],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vec![(1000, 2), (2000, 3), (3000, 4), (4000, 5)],
|
||||
rows,
|
||||
"one cursor value for every piece is the file-level floor of the whole file"
|
||||
);
|
||||
}
|
||||
|
||||
/// The third shape the per-row rule cannot answer: a row of the file that **no** candidate
|
||||
/// expression selects, i.e. a row outside the value domain of every piece of the creator.
|
||||
///
|
||||
/// Such a row has no piece to attribute it to, so only the least advanced candidate is left.
|
||||
/// That floor is exact while every candidate carries the same cursor value — it then *is* what
|
||||
/// the row's own piece states — and says nothing once they differ: it delivers the rows a more
|
||||
/// advanced piece already consumed, so the read fails instead of replaying them.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_fails_closed_when_no_piece_selects_a_row() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_fails_closed_unselected_row").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
// One file of the creator: four rows of the series `k0 = "1"`, inside the domain of the
|
||||
// left piece (`k0 < "5"`), and one row of `k0 = "9"`, outside the domain of both candidates.
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.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, 4, 0);
|
||||
rows.extend(test_util::build_rows_for_key("9", 4, 5, 0));
|
||||
test_util::put_rows(&engine, source, Rows { schema, rows }).await;
|
||||
test_util::flush_region(&engine, source, None).await;
|
||||
let source_file = manifest_files(&engine, source)
|
||||
.await
|
||||
.into_values()
|
||||
.next()
|
||||
.expect("flushed file");
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 6, true, None);
|
||||
|
||||
// The candidates carry 5 and 2. The row at 5 (`k0 = "9"`) belongs to no piece, and the
|
||||
// least advanced cursor (2) does not stand for the pieces: it would deliver the rows 3 and
|
||||
// 4 the left piece already consumed up to 5.
|
||||
let mut stream = engine
|
||||
.scan_batch(
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "5", 5),
|
||||
partition_str_slice_cursor("5", "9", 2),
|
||||
],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let err = match stream.try_next().await {
|
||||
Err(err) => err,
|
||||
Ok(_) => panic!("a row no candidate selects with disagreeing cursors must fail the read"),
|
||||
};
|
||||
let message = error_chain(&err);
|
||||
assert!(
|
||||
message.contains("exact sequence range unavailable"),
|
||||
"the shared exact-range contract prefix must reach the caller: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("cannot resolve a per-piece cursor"),
|
||||
"the failure must say what could not be resolved: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("match no candidate creator cursor slice") && message.contains("(2..=5)"),
|
||||
"the failure must name the unselected row and the cursors' own span: {message}"
|
||||
);
|
||||
|
||||
// One cursor value for every candidate: the least advanced cursor is then every piece's
|
||||
// cursor, so the row outside both domains keeps today's treatment and nothing is dropped.
|
||||
let mut rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "5", 2),
|
||||
partition_str_slice_cursor("5", "9", 2),
|
||||
],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
rows.sort_unstable();
|
||||
assert_eq!(
|
||||
vec![(2000, 3), (3000, 4), (4000, 5)],
|
||||
rows,
|
||||
"with one cursor value the row no candidate selects is bounded by it exactly, so the \
|
||||
rows above 2 are delivered and the rows at or below it are not"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
// 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.
|
||||
|
||||
use api::v1::Rows;
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_request::RegionRequest;
|
||||
use store_api::storage::{CursorShard, RegionId};
|
||||
|
||||
use super::scan_test::{
|
||||
adopt_foreign_file, build_foreign_source_file, create_foreign_target, creator_cursor_scan,
|
||||
manifest_files, partition_slice, partition_slice_cursor, partition_str_slice,
|
||||
partition_str_slice_cursor, scan_flat_row_sequences,
|
||||
};
|
||||
use crate::config::MitoConfig;
|
||||
use crate::test_util;
|
||||
use crate::test_util::{CreateRequestBuilder, TestEnv};
|
||||
|
||||
/// The cursor is keyed by `(region, expression slice)`: a file is filtered by the slice it
|
||||
/// belongs to, not by the region projection of the creator's slices.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_picks_the_intersecting_creator_slice() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_picks_intersecting_slice").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
// The creator's file states the numbers 1..12 and belongs to its `[50, 100)` slice; the
|
||||
// cut 3 says a substitution produced the first three of them.
|
||||
let (_, mut source_file) = build_foreign_source_file(&engine, source, 12, true).await;
|
||||
source_file.partition_expr = Some(partition_slice(50, 100).into());
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 4, true, Some(3));
|
||||
|
||||
// `[0, 50)` is at 3 and the file's own `[50, 100)` at 10: the lower bound is 10, so only
|
||||
// the rows 11 and 12 are delivered. The region projection of the same cursor (`min` = 3)
|
||||
// would deliver the rows 4..12 again, which is exactly the duplication this keying
|
||||
// removes.
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
partition_slice_cursor(0, 50, 3),
|
||||
partition_slice_cursor(50, 100, 10),
|
||||
],
|
||||
1,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(vec![(10_000, 11), (11_000, 12)], rows);
|
||||
|
||||
// The mirror image: `[0, 50)` at 10 and the file's own `[50, 100)` at 3. The lower bound
|
||||
// is the file's slice, so the rows 4..12 are delivered — the other slice's cursor must
|
||||
// not be applied to a file it does not cover.
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
partition_slice_cursor(0, 50, 10),
|
||||
partition_slice_cursor(50, 100, 3),
|
||||
],
|
||||
1,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let expected = (4_u64..=12)
|
||||
.map(|seq| (((seq - 1) * 1000) as i64, seq))
|
||||
.collect::<Vec<(i64, u64)>>();
|
||||
assert_eq!(expected, rows);
|
||||
}
|
||||
|
||||
/// Two files of **one** creator region, each stating a different expression of its domain,
|
||||
/// with different consumed progress on the two expressions: a merged read delivers exactly
|
||||
/// the rows above the cursor of the expression each file states.
|
||||
///
|
||||
/// The numbers are allocated in write order, so the slices are cross-wired on purpose: the
|
||||
/// right slice (`k0 >= 50`) holds the *older* numbers (1..6) while the left slice
|
||||
/// (`k0 < 50`) holds the newer ones (7..12). A read that applied the left cursor to both
|
||||
/// files would lose the right slice's rows 3..6 (the left cursor is higher than the right
|
||||
/// one), and a read that applied the region projection (`min` = 2) to both would deliver
|
||||
/// the left slice's 7..10 again. Only selecting the slice each file belongs to delivers
|
||||
/// both correctly.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_filters_each_creator_expression_by_its_own_cursor() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_filters_each_expression").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.build();
|
||||
let schema = test_util::rows_schema(&request);
|
||||
engine
|
||||
.handle_request(source, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
test_util::put_rows(
|
||||
&engine,
|
||||
source,
|
||||
Rows {
|
||||
schema: schema.clone(),
|
||||
rows: test_util::build_rows_for_key("0", 0, 6, 0),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
test_util::flush_region(&engine, source, None).await;
|
||||
let mut right_file = manifest_files(&engine, source)
|
||||
.await
|
||||
.into_values()
|
||||
.next()
|
||||
.expect("first flushed file");
|
||||
assert_eq!(None, right_file.partition_expr);
|
||||
right_file.partition_expr = Some(partition_slice(50, 100).into());
|
||||
|
||||
test_util::put_rows(
|
||||
&engine,
|
||||
source,
|
||||
Rows {
|
||||
schema,
|
||||
rows: test_util::build_rows_for_key("0", 6, 12, 0),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
test_util::flush_region(&engine, source, None).await;
|
||||
let mut left_file = manifest_files(&engine, source)
|
||||
.await
|
||||
.into_values()
|
||||
.find(|file| file.file_id != right_file.file_id)
|
||||
.expect("second flushed file");
|
||||
assert_eq!(None, left_file.partition_expr);
|
||||
left_file.partition_expr = Some(partition_slice(0, 50).into());
|
||||
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, right_file, 13, true, None);
|
||||
adopt_foreign_file(&engine, target, left_file, 14, true, None);
|
||||
|
||||
// The left expression was consumed up to 10, the right one only up to 2.
|
||||
let mut rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
partition_slice_cursor(0, 50, 10),
|
||||
partition_slice_cursor(50, 100, 2),
|
||||
],
|
||||
1,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
rows.sort_unstable();
|
||||
|
||||
assert_eq!(
|
||||
vec![
|
||||
(2000, 3),
|
||||
(3000, 4),
|
||||
(4000, 5),
|
||||
(5000, 6),
|
||||
(10000, 11),
|
||||
(11000, 12)
|
||||
],
|
||||
rows,
|
||||
"each file is filtered by the cursor of the expression it states: the right slice \
|
||||
keeps the rows above 2 (no loss) and the left slice starts above 10 (no duplicate)"
|
||||
);
|
||||
}
|
||||
|
||||
/// The counterexample per-row selection exists for: **one** file of one creator holds rows
|
||||
/// of two of its expressions, and the two cursors advanced differently.
|
||||
///
|
||||
/// The file was written under the coarse expression `k0 >= "0" AND k0 < "9"`, which the
|
||||
/// creator's domain has since been split out of. Its rows belong to `k0 < "5"` (consumed up
|
||||
/// to 5) and to `k0 >= "5"` (consumed up to 2). The least advanced cursor of the file is 2,
|
||||
/// so a file-level bound would deliver the already consumed rows 3, 4 and 5 again; the most
|
||||
/// advanced one (5) would drop the live row 6. Only splitting the rows by the expression
|
||||
/// each of them satisfies delivers the row at 6 and nothing else.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_splits_one_file_by_the_expression_of_each_row() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_splits_by_row_expression").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
// One file of the creator: five rows of the left expression (numbers 1..5) and one row
|
||||
// of the right one (number 6).
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.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, 5, 0);
|
||||
rows.extend(test_util::build_rows_for_key("6", 5, 6, 0));
|
||||
test_util::put_rows(&engine, source, Rows { schema, rows }).await;
|
||||
test_util::flush_region(&engine, source, None).await;
|
||||
|
||||
let mut source_file = manifest_files(&engine, source)
|
||||
.await
|
||||
.into_values()
|
||||
.next()
|
||||
.expect("flushed file");
|
||||
// The coarse expression the file was written under: it holds rows of both slices.
|
||||
source_file.partition_expr = Some(partition_str_slice("0", "9").into());
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 7, true, None);
|
||||
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "5", 5),
|
||||
partition_str_slice_cursor("5", "9", 2),
|
||||
],
|
||||
1,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
vec![(5000, 6)],
|
||||
rows,
|
||||
"the row at 6 belongs to the slice consumed up to 2 and must be delivered; the rows \
|
||||
at 3, 4 and 5 belong to the slice consumed up to 5 and must not be delivered again"
|
||||
);
|
||||
|
||||
// The same read with only `field_0` projected: the tag column the slice expressions
|
||||
// reference is added to the read columns as an internal column, so the per-row decision
|
||||
// still works and the output schema stays the projected one.
|
||||
let mut request = creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "5", 5),
|
||||
partition_str_slice_cursor("5", "9", 2),
|
||||
],
|
||||
1,
|
||||
20,
|
||||
);
|
||||
request.projection = Some(vec![1]);
|
||||
let rows = scan_flat_row_sequences(&engine, target, request).await;
|
||||
assert_eq!(
|
||||
vec![(5000, 6)],
|
||||
rows,
|
||||
"the partition column is read even though the scan does not project it"
|
||||
);
|
||||
}
|
||||
|
||||
/// Several candidate slices may select one row, and then the **least advanced** of their
|
||||
/// cursors decides it — exactly like the time-series and bulk memtable filters
|
||||
/// (`Batch::filter_by_creator_slices`, `creator_slice_mask`), which take the minimum over the
|
||||
/// candidates that select a row. Taking the first match instead drops the rows a less advanced
|
||||
/// piece still holds.
|
||||
///
|
||||
/// The counterexample this pins: the retired records `A = [0,8): 1` and `B = [5,9): 0` — the
|
||||
/// domain was not split cleanly, so both select a row at `k0 = 7` — and a merged holder file
|
||||
/// holding one row at `k0 = 7, sequence = 1`. The row is required because
|
||||
/// `1 > min(1, 0) = 0`; taking `A` first, as the reader did, drops it. It matches candidates,
|
||||
/// so the fail-closed rule for a row no candidate selects does not apply.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_takes_the_least_cursor_when_several_slices_select_a_row() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_least_cursor_of_several").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let source = RegionId::new(1, 2);
|
||||
let target = RegionId::new(1, 1);
|
||||
|
||||
// One file of the creator holding one row of the series `k0 = "7"`, numbered 1, under a
|
||||
// coarse statement (`k0 >= "0" AND k0 < "9"`) that covers both retired records: the file
|
||||
// merges the rows of both pieces. The bounds are single characters, so their lexicographic
|
||||
// order (the order of the string tag column) is the numeric order of the tag values.
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.build();
|
||||
let schema = test_util::rows_schema(&request);
|
||||
engine
|
||||
.handle_request(source, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
test_util::put_rows(
|
||||
&engine,
|
||||
source,
|
||||
Rows {
|
||||
schema,
|
||||
rows: test_util::build_rows_for_key("7", 0, 1, 0),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
test_util::flush_region(&engine, source, None).await;
|
||||
|
||||
let mut source_file = manifest_files(&engine, source)
|
||||
.await
|
||||
.into_values()
|
||||
.next()
|
||||
.expect("flushed file");
|
||||
source_file.partition_expr = Some(partition_str_slice("0", "9").into());
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 2, true, None);
|
||||
|
||||
// `A` is consumed up to 1, `B` only up to 0, and the row at 7 falls into both domains.
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(
|
||||
source,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "8", 1),
|
||||
partition_str_slice_cursor("5", "9", 0),
|
||||
],
|
||||
0,
|
||||
10,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
vec![(0, 1)],
|
||||
rows,
|
||||
"the row at sequence 1 is above the least advanced of the slices that select it (0), so \
|
||||
it must be delivered even though the first matching slice is consumed up to 1"
|
||||
);
|
||||
}
|
||||
|
||||
/// The same per-row rule for a **memtable** of this region: a memtable row is filtered by
|
||||
/// the cursor of the piece its own tag values fall into, not by the single floor of the
|
||||
/// region.
|
||||
///
|
||||
/// The region's own pieces are the only candidates, because a memtable holds the rows this
|
||||
/// region allocated. The rows of the piece consumed up to 5 (the rows at 3, 4 and 5) are
|
||||
/// not delivered again, and the row at 6 of the piece consumed up to 2 still is.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_splits_memtable_rows_by_the_expression_of_each_row() {
|
||||
let mut env =
|
||||
TestEnv::with_prefix("test_read_row_sequence_splits_memtable_rows_by_expression").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let region = RegionId::new(1, 1);
|
||||
|
||||
// Five rows of the left expression (numbers 1..5) and one row of the right one
|
||||
// (number 6), all of them in the memtable: no flush, so no file takes part in the read.
|
||||
// The primary-key SST format keeps the time-series memtable (the flat format would put
|
||||
// the rows in the bulk memtable, which does not apply the per-piece rule), and
|
||||
// `preserve_row_sequence` keeps the exact `(C, H]` delta admissible.
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.insert_option("sst_format", "primary_key")
|
||||
.build();
|
||||
let schema = test_util::rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut rows = test_util::build_rows_for_key("1", 0, 5, 0);
|
||||
rows.extend(test_util::build_rows_for_key("6", 5, 6, 0));
|
||||
test_util::put_rows(&engine, region, Rows { schema, rows }).await;
|
||||
|
||||
// One cursor value for every piece: the delivered rows are exactly the rows above the
|
||||
// region-level floor 2, which is what the read delivered before the per-row rule.
|
||||
let mut rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
region,
|
||||
creator_cursor_scan(
|
||||
region,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "5", 2),
|
||||
partition_str_slice_cursor("5", "9", 2),
|
||||
],
|
||||
2,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
rows.sort_unstable();
|
||||
assert_eq!(
|
||||
vec![(2000, 3), (3000, 4), (4000, 5), (5000, 6)],
|
||||
rows,
|
||||
"one cursor value for every piece is the region-level floor of the whole read"
|
||||
);
|
||||
|
||||
// The pieces advanced differently: the rows of the left one (3, 4 and 5) are consumed,
|
||||
// the row at 6 belongs to the right one and stays live.
|
||||
let mut rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
region,
|
||||
creator_cursor_scan(
|
||||
region,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "5", 5),
|
||||
partition_str_slice_cursor("5", "9", 2),
|
||||
],
|
||||
2,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
rows.sort_unstable();
|
||||
assert_eq!(
|
||||
vec![(5000, 6)],
|
||||
rows,
|
||||
"each memtable row is filtered by the cursor of the piece it belongs to: the rows at \
|
||||
3, 4 and 5 were consumed by the piece advanced to 5, the row at 6 was not"
|
||||
);
|
||||
}
|
||||
|
||||
/// The same per-row rule for a **bulk** memtable: a bulk part keeps the tag columns and the
|
||||
/// physical sequence of every row as real columns, so the piece a row belongs to is resolved
|
||||
/// per row there too, instead of by the single floor of the region.
|
||||
///
|
||||
/// As above, the rows of the piece consumed up to 5 (3, 4 and 5) are not delivered again
|
||||
/// while the row at 6 of the piece consumed up to 2 still is.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_splits_bulk_memtable_rows_by_the_expression_of_each_row() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_splits_bulk_memtable_rows").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
let region = RegionId::new(1, 1);
|
||||
|
||||
// Five rows of the left expression (numbers 1..5) and one row of the right one
|
||||
// (number 6), all of them in the bulk memtable: no flush, so no file takes part in the
|
||||
// read, and `preserve_row_sequence` keeps the exact `(C, H]` delta admissible.
|
||||
let request = CreateRequestBuilder::new()
|
||||
.insert_option("append_mode", "true")
|
||||
.insert_option("preserve_row_sequence", "true")
|
||||
.insert_option("memtable.type", "bulk")
|
||||
.build();
|
||||
let schema = test_util::rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut rows = test_util::build_rows_for_key("1", 0, 5, 0);
|
||||
rows.extend(test_util::build_rows_for_key("6", 5, 6, 0));
|
||||
test_util::put_rows(&engine, region, Rows { schema, rows }).await;
|
||||
|
||||
// The rows really are in a bulk memtable, so the read below goes through a bulk part
|
||||
// and the per-row rule there, not through the time-series memtable.
|
||||
assert!(
|
||||
matches!(
|
||||
engine
|
||||
.get_region(region)
|
||||
.unwrap()
|
||||
.version_control
|
||||
.current()
|
||||
.version
|
||||
.options
|
||||
.memtable,
|
||||
Some(crate::region::options::MemtableOptions::Bulk(_))
|
||||
),
|
||||
"the region must hold the bulk memtable"
|
||||
);
|
||||
|
||||
// One cursor value for every piece: the delivered rows are exactly the rows above the
|
||||
// region-level floor 2, which is what the read delivered before the per-row rule.
|
||||
let mut rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
region,
|
||||
creator_cursor_scan(
|
||||
region,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "5", 2),
|
||||
partition_str_slice_cursor("5", "9", 2),
|
||||
],
|
||||
2,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
rows.sort_unstable();
|
||||
assert_eq!(
|
||||
vec![(2000, 3), (3000, 4), (4000, 5), (5000, 6)],
|
||||
rows,
|
||||
"one cursor value for every piece is the region-level floor of the whole read"
|
||||
);
|
||||
|
||||
// The pieces advanced differently: the rows of the left one (3, 4 and 5) are consumed,
|
||||
// the row at 6 belongs to the right one and stays live.
|
||||
let mut rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
region,
|
||||
creator_cursor_scan(
|
||||
region,
|
||||
vec![
|
||||
partition_str_slice_cursor("0", "5", 5),
|
||||
partition_str_slice_cursor("5", "9", 2),
|
||||
],
|
||||
2,
|
||||
20,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
rows.sort_unstable();
|
||||
assert_eq!(
|
||||
vec![(5000, 6)],
|
||||
rows,
|
||||
"each bulk memtable row is filtered by the cursor of the piece it belongs to: the \
|
||||
rows at 3, 4 and 5 were consumed by the piece advanced to 5, the row at 6 was not"
|
||||
);
|
||||
}
|
||||
|
||||
/// A `cut = None` adopted file is filtered by the creator's cursor exactly like one that
|
||||
/// states a cut. Its numbers were allocated in the creator's domain whether or not a
|
||||
/// substitution touched them, so the holder's own `(C, H]` neither bounds them nor may
|
||||
/// replace the creator's slice.
|
||||
#[tokio::test]
|
||||
async fn test_read_row_sequence_filters_adopted_file_without_cut_by_creator_cursor() {
|
||||
let mut env = TestEnv::with_prefix("test_read_row_sequence_filters_adopted_without_cut").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_foreign_source_file(&engine, source, 5, true).await;
|
||||
create_foreign_target(&engine, target).await;
|
||||
adopt_foreign_file(&engine, target, source_file, 6, true, None);
|
||||
|
||||
// The creator consumed up to 3, so only its rows 4 and 5 are still owed. The holder's
|
||||
// own cursor (0 in this scan) would deliver all five again.
|
||||
let rows = scan_flat_row_sequences(
|
||||
&engine,
|
||||
target,
|
||||
creator_cursor_scan(source, vec![CursorShard::whole_domain(3)], 0, 10),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
vec![(3000, 4), (4000, 5)],
|
||||
rows,
|
||||
"an adopted file without a cut is still bounded by the creator's cursor"
|
||||
);
|
||||
}
|
||||
+1885
-37
File diff suppressed because it is too large
Load Diff
+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
|
||||
|
||||
@@ -28,6 +28,7 @@ use datatypes::arrow::record_batch::RecordBatch;
|
||||
use mito_codec::key_values::KeyValue;
|
||||
pub use mito_codec::key_values::KeyValues;
|
||||
use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec};
|
||||
use partition::expr::PartitionExpr;
|
||||
use snafu::ensure;
|
||||
use store_api::codec::PrimaryKeyEncoding;
|
||||
use store_api::metadata::{RegionMetadata, RegionMetadataRef};
|
||||
@@ -95,6 +96,16 @@ pub(crate) fn group_by_sequence<T>(
|
||||
/// Should be unique under the same region.
|
||||
pub type MemtableId = u32;
|
||||
|
||||
/// The cursor of one piece a memtable row may belong to, as
|
||||
/// [`RangesOptions::creator_slices`] takes it: the partition expression selecting the piece,
|
||||
/// the last sequence consumed inside it, and — when the producer states one — the last
|
||||
/// sequence the delta of the piece covers.
|
||||
pub type CreatorSliceCursor = (PartitionExpr, SequenceNumber, Option<SequenceNumber>);
|
||||
|
||||
/// The cursor of each piece a memtable row may belong to
|
||||
/// ([`RangesOptions::creator_slices`]).
|
||||
pub type CreatorSliceCursors = Arc<Vec<CreatorSliceCursor>>;
|
||||
|
||||
/// Options for querying ranges from a memtable.
|
||||
#[derive(Clone)]
|
||||
pub struct RangesOptions {
|
||||
@@ -106,6 +117,20 @@ pub struct RangesOptions {
|
||||
pub predicate: PredicateGroup,
|
||||
/// Sequence range to filter the data.
|
||||
pub sequence: Option<SequenceRange>,
|
||||
/// The cursor of each piece a row of this memtable may belong to, as
|
||||
/// [`CreatorSliceCursor`] triples: `(partition expression, last consumed sequence, last
|
||||
/// sequence the piece's delta covers)`.
|
||||
///
|
||||
/// When present, a row is delivered only when its own sequence is above the cursor of
|
||||
/// the piece it belongs to: the cursor of the piece replaces the single floor
|
||||
/// [`Self::sequence`] states, which is the minimum of the pieces and therefore cannot
|
||||
/// tell a row of a more advanced piece from a consumed one. The piece's `until` narrows
|
||||
/// the upper end [`Self::sequence`] states, so a row numbered above the piece's delta is
|
||||
/// not delivered by a read of this one; a piece that states no `until` keeps that end
|
||||
/// alone.
|
||||
///
|
||||
/// `None` (or an empty vector) keeps the region-level floor as the whole rule.
|
||||
pub creator_slices: Option<CreatorSliceCursors>,
|
||||
/// Maximum number of rows readers should produce in one batch.
|
||||
pub batch_size: usize,
|
||||
}
|
||||
@@ -117,6 +142,7 @@ impl Default for RangesOptions {
|
||||
pre_filter_mode: PreFilterMode::All,
|
||||
predicate: PredicateGroup::default(),
|
||||
sequence: None,
|
||||
creator_slices: None,
|
||||
batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
|
||||
}
|
||||
}
|
||||
@@ -130,6 +156,7 @@ impl RangesOptions {
|
||||
pre_filter_mode: PreFilterMode::All,
|
||||
predicate: PredicateGroup::default(),
|
||||
sequence: None,
|
||||
creator_slices: None,
|
||||
batch_size: crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
|
||||
}
|
||||
}
|
||||
@@ -155,6 +182,17 @@ impl RangesOptions {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the cursor of each piece a row may belong to.
|
||||
///
|
||||
/// See [`Self::creator_slices`]: the cursor of the piece a row belongs to replaces the
|
||||
/// single floor of [`Self::sequence`], and the `until` of that piece narrows the upper
|
||||
/// end of it.
|
||||
#[must_use]
|
||||
pub fn with_creator_slices(mut self, creator_slices: Option<CreatorSliceCursors>) -> Self {
|
||||
self.creator_slices = creator_slices;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the maximum number of rows readers should produce in one batch.
|
||||
#[must_use]
|
||||
pub fn with_batch_size(mut self, batch_size: usize) -> Self {
|
||||
@@ -163,6 +201,55 @@ impl RangesOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the inclusive upper end `range` states, when it states one.
|
||||
pub(crate) fn sequence_range_upper(range: Option<&SequenceRange>) -> Option<SequenceNumber> {
|
||||
match range {
|
||||
Some(SequenceRange::LtEq { max } | SequenceRange::GtLtEq { max, .. }) => Some(*max),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The sequence range the rows of one creator cursor slice are read with: above the slice's
|
||||
/// cursor and at or below `min(read_fence, until)`.
|
||||
///
|
||||
/// `until` is the last sequence the slice's delta covers ([`CreatorSliceCursor`]);
|
||||
/// `read_fence` is the upper end the read's own sequence range states. The slice's bound
|
||||
/// narrows the fence and never widens it — the fence is what the snapshot allows — while a
|
||||
/// slice that states no bound keeps the fence alone, exactly as before the bound existed.
|
||||
pub(crate) fn creator_slice_sequence_range(
|
||||
cursor: SequenceNumber,
|
||||
until: Option<SequenceNumber>,
|
||||
read_fence: Option<SequenceNumber>,
|
||||
) -> SequenceRange {
|
||||
match (read_fence, until) {
|
||||
(Some(fence), Some(until)) => SequenceRange::GtLtEq {
|
||||
min: cursor,
|
||||
max: fence.min(until),
|
||||
},
|
||||
(Some(fence), None) => SequenceRange::GtLtEq {
|
||||
min: cursor,
|
||||
max: fence,
|
||||
},
|
||||
(None, Some(until)) => SequenceRange::GtLtEq {
|
||||
min: cursor,
|
||||
max: until,
|
||||
},
|
||||
(None, None) => SequenceRange::Gt { min: cursor },
|
||||
}
|
||||
}
|
||||
|
||||
/// The **least** inclusive upper bound a set of candidate slices states, or `None` when none
|
||||
/// of them states one.
|
||||
///
|
||||
/// A slice that states no bound is unbounded above and never narrows the set; a row whose
|
||||
/// piece is one of several candidates is bounded by the least bound among them, the only
|
||||
/// bound every candidate proves.
|
||||
pub(crate) fn least_slice_until<'a>(
|
||||
untils: impl Iterator<Item = &'a Option<SequenceNumber>>,
|
||||
) -> Option<SequenceNumber> {
|
||||
untils.filter_map(|until| *until).min()
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct MemtableStats {
|
||||
/// The estimated bytes allocated by this memtable from heap.
|
||||
|
||||
@@ -58,10 +58,10 @@ use crate::memtable::bulk::part::{
|
||||
use crate::memtable::bulk::part_reader::BulkPartBatchIter;
|
||||
use crate::memtable::stats::WriteMetrics;
|
||||
use crate::memtable::{
|
||||
AllocTracker, BoxedBatchIterator, BoxedRecordBatchIterator, EncodedBulkPart, EncodedRange,
|
||||
IterBuilder, KeyValues, MemScanMetrics, Memtable, MemtableBuilder, MemtableId, MemtableRange,
|
||||
MemtableRangeContext, MemtableRanges, MemtableRef, MemtableStats, RangesOptions,
|
||||
group_by_sequence,
|
||||
AllocTracker, BoxedBatchIterator, BoxedRecordBatchIterator, CreatorSliceCursors,
|
||||
EncodedBulkPart, EncodedRange, IterBuilder, KeyValues, MemScanMetrics, Memtable,
|
||||
MemtableBuilder, MemtableId, MemtableRange, MemtableRangeContext, MemtableRanges, MemtableRef,
|
||||
MemtableStats, RangesOptions, group_by_sequence,
|
||||
};
|
||||
use crate::read::flat_dedup::{FlatDedupIterator, FlatLastNonNull, FlatLastRow};
|
||||
use crate::read::flat_merge::FlatMergeIterator;
|
||||
@@ -535,6 +535,7 @@ impl Memtable for BulkMemtable {
|
||||
) -> Result<MemtableRanges> {
|
||||
let predicate = options.predicate;
|
||||
let sequence = options.sequence;
|
||||
let creator_slices = options.creator_slices;
|
||||
let mut ranges = BTreeMap::new();
|
||||
let mut range_id = 0;
|
||||
|
||||
@@ -565,6 +566,7 @@ impl Memtable for BulkMemtable {
|
||||
part: unordered_bulk_part,
|
||||
context: context.clone(),
|
||||
sequence,
|
||||
creator_slices: creator_slices.clone(),
|
||||
}),
|
||||
predicate.clone(),
|
||||
)),
|
||||
@@ -587,11 +589,13 @@ impl Memtable for BulkMemtable {
|
||||
part: part.clone(),
|
||||
context: context.clone(),
|
||||
sequence,
|
||||
creator_slices: creator_slices.clone(),
|
||||
}),
|
||||
PartToMerge::Multi { part, .. } => Box::new(MultiBulkRangeIterBuilder {
|
||||
part: part.clone(),
|
||||
context: context.clone(),
|
||||
sequence,
|
||||
creator_slices: creator_slices.clone(),
|
||||
}),
|
||||
PartToMerge::Encoded { part, file_id } => {
|
||||
Box::new(EncodedBulkRangeIterBuilder {
|
||||
@@ -599,6 +603,7 @@ impl Memtable for BulkMemtable {
|
||||
part: part.clone(),
|
||||
context: context.clone(),
|
||||
sequence,
|
||||
creator_slices: creator_slices.clone(),
|
||||
})
|
||||
}
|
||||
};
|
||||
@@ -902,6 +907,8 @@ pub struct BulkRangeIterBuilder {
|
||||
pub part: BulkPart,
|
||||
pub context: Arc<BulkIterContext>,
|
||||
pub sequence: Option<SequenceRange>,
|
||||
/// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]).
|
||||
pub creator_slices: Option<CreatorSliceCursors>,
|
||||
}
|
||||
|
||||
/// Iterator builder for multi bulk range
|
||||
@@ -909,6 +916,8 @@ struct MultiBulkRangeIterBuilder {
|
||||
part: MultiBulkPart,
|
||||
context: Arc<BulkIterContext>,
|
||||
sequence: Option<SequenceRange>,
|
||||
/// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]).
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
}
|
||||
|
||||
impl IterBuilder for BulkRangeIterBuilder {
|
||||
@@ -940,7 +949,8 @@ impl IterBuilder for BulkRangeIterBuilder {
|
||||
self.sequence,
|
||||
series_count,
|
||||
metrics,
|
||||
);
|
||||
)
|
||||
.with_creator_slices(self.creator_slices.clone());
|
||||
|
||||
Ok(Box::new(iter))
|
||||
}
|
||||
@@ -971,10 +981,12 @@ impl IterBuilder for MultiBulkRangeIterBuilder {
|
||||
_time_range: Option<(Timestamp, Timestamp)>,
|
||||
metrics: Option<MemScanMetrics>,
|
||||
) -> Result<BoxedRecordBatchIterator> {
|
||||
match self
|
||||
.part
|
||||
.read(self.context.clone(), self.sequence, metrics)?
|
||||
{
|
||||
match self.part.read(
|
||||
self.context.clone(),
|
||||
self.sequence,
|
||||
self.creator_slices.clone(),
|
||||
metrics,
|
||||
)? {
|
||||
Some(iter) => Ok(iter),
|
||||
// All batches were pruned by the predicate. Return an empty iterator.
|
||||
None => Ok(Box::new(std::iter::empty())),
|
||||
@@ -996,6 +1008,8 @@ struct EncodedBulkRangeIterBuilder {
|
||||
part: EncodedBulkPart,
|
||||
context: Arc<BulkIterContext>,
|
||||
sequence: Option<SequenceRange>,
|
||||
/// Cursor of each piece a row may belong to ([`RangesOptions::creator_slices`]).
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
}
|
||||
|
||||
impl IterBuilder for EncodedBulkRangeIterBuilder {
|
||||
@@ -1015,10 +1029,12 @@ impl IterBuilder for EncodedBulkRangeIterBuilder {
|
||||
_time_range: Option<(Timestamp, Timestamp)>,
|
||||
metrics: Option<MemScanMetrics>,
|
||||
) -> Result<BoxedRecordBatchIterator> {
|
||||
if let Some(iter) = self
|
||||
.part
|
||||
.read(self.context.clone(), self.sequence, metrics)?
|
||||
{
|
||||
if let Some(iter) = self.part.read(
|
||||
self.context.clone(),
|
||||
self.sequence,
|
||||
self.creator_slices.clone(),
|
||||
metrics,
|
||||
)? {
|
||||
Ok(iter)
|
||||
} else {
|
||||
// Return an empty iterator if no data to read
|
||||
@@ -1222,8 +1238,8 @@ impl PartToMerge {
|
||||
);
|
||||
Some(Box::new(iter) as BoxedRecordBatchIterator)
|
||||
}
|
||||
PartToMerge::Multi { part, .. } => part.read(context, None, None)?,
|
||||
PartToMerge::Encoded { part, .. } => part.read(context, None, None)?,
|
||||
PartToMerge::Multi { part, .. } => part.read(context, None, None, None)?,
|
||||
PartToMerge::Encoded { part, .. } => part.read(context, None, None, None)?,
|
||||
};
|
||||
if plans.is_empty() {
|
||||
Ok(iter)
|
||||
|
||||
@@ -68,7 +68,9 @@ use crate::error::{
|
||||
use crate::memtable::bulk::context::{BulkIterContext, BulkIterContextRef};
|
||||
use crate::memtable::bulk::part_reader::EncodedBulkPartIter;
|
||||
use crate::memtable::time_series::{ValueBuilder, Values};
|
||||
use crate::memtable::{BoxedRecordBatchIterator, MemScanMetrics, MemtableStats};
|
||||
use crate::memtable::{
|
||||
BoxedRecordBatchIterator, CreatorSliceCursors, MemScanMetrics, MemtableStats,
|
||||
};
|
||||
use crate::sst::SeriesEstimator;
|
||||
use crate::sst::index::IndexOutput;
|
||||
use crate::sst::parquet::flat_format::primary_key_column_index;
|
||||
@@ -1343,6 +1345,7 @@ impl EncodedBulkPart {
|
||||
&self,
|
||||
context: BulkIterContextRef,
|
||||
sequence: Option<SequenceRange>,
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
mem_scan_metrics: Option<MemScanMetrics>,
|
||||
) -> Result<Option<BoxedRecordBatchIterator>> {
|
||||
// Compute skip_fields for row group pruning from the configured pre-filter mode.
|
||||
@@ -1363,7 +1366,8 @@ impl EncodedBulkPart {
|
||||
row_groups_to_read,
|
||||
sequence,
|
||||
mem_scan_metrics,
|
||||
)?;
|
||||
)?
|
||||
.with_creator_slices(creator_slices);
|
||||
Ok(Some(Box::new(iter) as BoxedRecordBatchIterator))
|
||||
}
|
||||
}
|
||||
@@ -1918,6 +1922,7 @@ impl MultiBulkPart {
|
||||
&self,
|
||||
context: BulkIterContextRef,
|
||||
sequence: Option<SequenceRange>,
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
mem_scan_metrics: Option<MemScanMetrics>,
|
||||
) -> Result<Option<BoxedRecordBatchIterator>> {
|
||||
if self.batches.is_empty() {
|
||||
@@ -1936,7 +1941,8 @@ impl MultiBulkPart {
|
||||
sequence,
|
||||
self.series_count,
|
||||
mem_scan_metrics,
|
||||
);
|
||||
)
|
||||
.with_creator_slices(creator_slices);
|
||||
Ok(Some(Box::new(iter) as BoxedRecordBatchIterator))
|
||||
}
|
||||
|
||||
@@ -2241,6 +2247,7 @@ mod tests {
|
||||
),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.expect("expect at least one row group");
|
||||
@@ -2301,7 +2308,7 @@ mod tests {
|
||||
.unwrap(),
|
||||
);
|
||||
let reader = part
|
||||
.read(context, None, None)
|
||||
.read(context, None, None, None)
|
||||
.unwrap()
|
||||
.expect("expect at least one row group");
|
||||
let mut total_rows_read = 0;
|
||||
@@ -2335,7 +2342,7 @@ mod tests {
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(part.read(context, None, None).unwrap().is_none());
|
||||
assert!(part.read(context, None, None, None).unwrap().is_none());
|
||||
|
||||
check_prune_row_group(&part, None, 310);
|
||||
|
||||
@@ -3584,7 +3591,7 @@ mod tests {
|
||||
.unwrap(),
|
||||
);
|
||||
let reader = multi
|
||||
.read(context, None, None)
|
||||
.read(context, None, None, None)
|
||||
.unwrap()
|
||||
.expect("should have results");
|
||||
let total_rows: usize = reader.map(|r| r.unwrap().num_rows()).sum();
|
||||
@@ -3603,7 +3610,7 @@ mod tests {
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(multi.read(context, None, None).unwrap().is_none());
|
||||
assert!(multi.read(context, None, None, None).unwrap().is_none());
|
||||
|
||||
// No predicate => all 6 rows.
|
||||
let context = Arc::new(
|
||||
@@ -3617,7 +3624,7 @@ mod tests {
|
||||
.unwrap(),
|
||||
);
|
||||
let reader = multi
|
||||
.read(context, None, None)
|
||||
.read(context, None, None, None)
|
||||
.unwrap()
|
||||
.expect("should have results");
|
||||
let total_rows: usize = reader.map(|r| r.unwrap().num_rows()).sum();
|
||||
|
||||
@@ -12,26 +12,42 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
use std::ops::BitAnd;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use datatypes::arrow::array::BooleanArray;
|
||||
use common_telemetry::debug;
|
||||
use datatypes::arrow::array::{Array, ArrayRef, BooleanArray, BooleanBufferBuilder};
|
||||
use datatypes::arrow::buffer::BooleanBuffer;
|
||||
use datatypes::arrow::datatypes::{Field, Schema};
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use datatypes::data_type::DataType;
|
||||
use mito_codec::row_converter::PrimaryKeyFilter;
|
||||
use parquet::arrow::ProjectionMask;
|
||||
use parquet::arrow::arrow_reader::ParquetRecordBatchReader;
|
||||
use snafu::ResultExt;
|
||||
use store_api::storage::SequenceRange;
|
||||
use store_api::codec::PrimaryKeyEncoding;
|
||||
use store_api::storage::{ColumnId, SequenceNumber, SequenceRange};
|
||||
|
||||
use crate::error::{self, ComputeArrowSnafu, DecodeArrowRowGroupSnafu};
|
||||
use crate::error::{
|
||||
self, ComputeArrowSnafu, DecodeArrowRowGroupSnafu, EvalPartitionFilterSnafu,
|
||||
SequenceRangeUnsupportedSnafu, SerializePartitionExprSnafu, UnexpectedSnafu,
|
||||
};
|
||||
use crate::memtable::bulk::context::{BulkIterContext, BulkIterContextRef};
|
||||
use crate::memtable::bulk::part::EncodedBulkPart;
|
||||
use crate::memtable::bulk::row_group_reader::MemtableRowGroupReaderBuilder;
|
||||
use crate::memtable::{MemScanMetrics, MemScanMetricsData};
|
||||
use crate::memtable::{
|
||||
CreatorSliceCursor, CreatorSliceCursors, MemScanMetrics, MemScanMetricsData,
|
||||
creator_slice_sequence_range, least_slice_until, sequence_range_upper,
|
||||
};
|
||||
use crate::metrics::{READ_ROWS_TOTAL, READ_STAGE_ELAPSED};
|
||||
use crate::sst::parquet::file_range::TagDecodeState;
|
||||
use crate::sst::parquet::flat_format::{primary_key_column_index, sequence_column_index};
|
||||
use crate::sst::parquet::flat_format::{
|
||||
DecodedPrimaryKeys, decode_primary_keys, primary_key_column_index, sequence_column_index,
|
||||
};
|
||||
use crate::sst::parquet::prefilter::{CachedPrimaryKeyFilter, prefilter_flat_batch_by_primary_key};
|
||||
use crate::sst::tag_maybe_to_dictionary_field;
|
||||
|
||||
/// Iterator for reading data inside a bulk part.
|
||||
pub struct EncodedBulkPartIter {
|
||||
@@ -41,6 +57,9 @@ pub struct EncodedBulkPartIter {
|
||||
builder: MemtableRowGroupReaderBuilder,
|
||||
/// Sequence number filter.
|
||||
sequence: Option<SequenceRange>,
|
||||
/// Cursor of each piece a row of this part may belong to
|
||||
/// ([`crate::memtable::RangesOptions::creator_slices`]).
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
/// Cached skip_fields for current row group.
|
||||
current_skip_fields: bool,
|
||||
/// Primary key filter for prefiltering before convert_batch.
|
||||
@@ -92,6 +111,7 @@ impl EncodedBulkPartIter {
|
||||
current_reader: init_reader,
|
||||
builder,
|
||||
sequence,
|
||||
creator_slices: None,
|
||||
current_skip_fields,
|
||||
pk_filter,
|
||||
metrics: MemScanMetricsData {
|
||||
@@ -108,6 +128,12 @@ impl EncodedBulkPartIter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the cursor of each piece a row of this part may belong to.
|
||||
pub fn with_creator_slices(mut self, creator_slices: Option<CreatorSliceCursors>) -> Self {
|
||||
self.creator_slices = creator_slices;
|
||||
self
|
||||
}
|
||||
|
||||
/// Fetches next non-empty record batch.
|
||||
pub(crate) fn next_record_batch(&mut self) -> error::Result<Option<RecordBatch>> {
|
||||
let start = Instant::now();
|
||||
@@ -123,6 +149,7 @@ impl EncodedBulkPartIter {
|
||||
if let Some(batch) = apply_combined_filters(
|
||||
&self.context,
|
||||
&self.sequence,
|
||||
self.creator_slices.as_deref().map(Vec::as_slice),
|
||||
batch,
|
||||
self.current_skip_fields,
|
||||
self.pk_filter
|
||||
@@ -151,6 +178,7 @@ impl EncodedBulkPartIter {
|
||||
if let Some(batch) = apply_combined_filters(
|
||||
&self.context,
|
||||
&self.sequence,
|
||||
self.creator_slices.as_deref().map(Vec::as_slice),
|
||||
batch,
|
||||
self.current_skip_fields,
|
||||
self.pk_filter
|
||||
@@ -222,6 +250,9 @@ pub struct BulkPartBatchIter {
|
||||
context: BulkIterContextRef,
|
||||
/// Sequence number filter.
|
||||
sequence: Option<SequenceRange>,
|
||||
/// Cursor of each piece a row of this part may belong to
|
||||
/// ([`crate::memtable::RangesOptions::creator_slices`]).
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
/// Primary key filter for prefiltering before convert_batch.
|
||||
pk_filter: Option<CachedPrimaryKeyFilter>,
|
||||
/// Metrics for this iterator.
|
||||
@@ -245,6 +276,7 @@ impl BulkPartBatchIter {
|
||||
batches: VecDeque::from(batches),
|
||||
context,
|
||||
sequence,
|
||||
creator_slices: None,
|
||||
pk_filter,
|
||||
metrics: MemScanMetricsData {
|
||||
total_series: series_count,
|
||||
@@ -271,6 +303,12 @@ impl BulkPartBatchIter {
|
||||
)
|
||||
}
|
||||
|
||||
/// Sets the cursor of each piece a row of this part may belong to.
|
||||
pub fn with_creator_slices(mut self, creator_slices: Option<CreatorSliceCursors>) -> Self {
|
||||
self.creator_slices = creator_slices;
|
||||
self
|
||||
}
|
||||
|
||||
fn report_mem_scan_metrics(&mut self) {
|
||||
if let Some(mem_scan_metrics) = self.mem_scan_metrics.take() {
|
||||
mem_scan_metrics.merge_inner(&self.metrics);
|
||||
@@ -305,6 +343,7 @@ impl BulkPartBatchIter {
|
||||
let Some(filtered_batch) = apply_combined_filters(
|
||||
&self.context,
|
||||
&self.sequence,
|
||||
self.creator_slices.as_deref().map(Vec::as_slice),
|
||||
projected_batch,
|
||||
skip_fields,
|
||||
self.pk_filter
|
||||
@@ -373,14 +412,21 @@ impl Drop for BulkPartBatchIter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies both predicate filtering and sequence filtering in a single pass.
|
||||
/// Applies the predicate, sequence and creator-cursor filtering in a single pass.
|
||||
/// Returns None if the filtered batch is empty.
|
||||
///
|
||||
/// `sequence` bounds every row by the region-level sequence range and
|
||||
/// `creator_slices` bounds each row by the cursor of the piece it belongs to
|
||||
/// (`RangesOptions::creator_slices`); the two are combined so the per-piece rule replaces the
|
||||
/// lower floor of the region-level range and narrows its upper end by the bound the piece
|
||||
/// states.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if the format is not flat.
|
||||
fn apply_combined_filters(
|
||||
context: &BulkIterContext,
|
||||
sequence: &Option<SequenceRange>,
|
||||
creator_slices: Option<&[CreatorSliceCursor]>,
|
||||
record_batch: RecordBatch,
|
||||
skip_fields: bool,
|
||||
pk_filter: Option<&mut dyn PrimaryKeyFilter>,
|
||||
@@ -436,15 +482,16 @@ fn apply_combined_filters(
|
||||
let sequence_filter = sequence
|
||||
.filter(&sequence_column)
|
||||
.context(ComputeArrowSnafu)?;
|
||||
// Combine with existing filter using AND operation
|
||||
combined_filter = match combined_filter {
|
||||
None => Some(sequence_filter),
|
||||
Some(existing_filter) => {
|
||||
let and_result = datatypes::arrow::compute::and(&existing_filter, &sequence_filter)
|
||||
.context(ComputeArrowSnafu)?;
|
||||
Some(and_result)
|
||||
}
|
||||
};
|
||||
combined_filter = Some(and_mask(combined_filter, sequence_filter)?);
|
||||
}
|
||||
|
||||
// Filters rows by the cursor of the piece each row belongs to. A piece that states an
|
||||
// upper bound narrows the read's fence, which is the upper end `sequence` states.
|
||||
let read_fence = sequence_range_upper(sequence.as_ref());
|
||||
if let Some(creator_mask) =
|
||||
creator_slice_mask(context, creator_slices, read_fence, &record_batch)?
|
||||
{
|
||||
combined_filter = Some(and_mask(combined_filter, creator_mask)?);
|
||||
}
|
||||
|
||||
// Apply the combined filter if any filters were applied
|
||||
@@ -466,6 +513,336 @@ fn apply_combined_filters(
|
||||
Ok(Some(filtered_batch))
|
||||
}
|
||||
|
||||
/// Combines `next` into the mask accumulated so far with a logical AND.
|
||||
fn and_mask(current: Option<BooleanArray>, next: BooleanArray) -> error::Result<BooleanArray> {
|
||||
match current {
|
||||
None => Ok(next),
|
||||
Some(existing) => {
|
||||
datatypes::arrow::compute::and(&existing, &next).context(ComputeArrowSnafu)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the mask of rows of `record_batch` a physical-sequence read has **not** consumed
|
||||
/// yet, or `None` when the region-level bound is the whole rule.
|
||||
///
|
||||
/// A bulk part keeps the tag columns and the physical sequence of every row as real
|
||||
/// columns, so the piece a row belongs to is resolved per row: the candidate partition
|
||||
/// expressions are evaluated over the whole batch, and a row is kept only when its own
|
||||
/// `__sequence` is above the cursor of the candidate that selects it and at or below
|
||||
/// `min(read_fence, until)` of that candidate — `read_fence` being the upper end the read's
|
||||
/// own sequence range states and `until` the last sequence the piece's delta covers. This is
|
||||
/// the bulk memtable counterpart of the per-row slice selection a physical-sequence read of an
|
||||
/// SST applies (`FileRangeContext::evaluate_creator_slices`).
|
||||
///
|
||||
/// A row whose piece cannot be decided is answered by [`unresolved_creator_slices`]: the
|
||||
/// least advanced cursor is exact while every candidate carries it, and the read fails
|
||||
/// otherwise. That covers a row no candidate selects and an expression that cannot be
|
||||
/// resolved, planned or evaluated. When several candidates select one row, the least advanced
|
||||
/// of their cursors and the least of the bounds they state decide: the row is kept when it is
|
||||
/// above one of them and below all of them.
|
||||
///
|
||||
/// `None` or an empty set applies no filter, and so does a set whose cursors all carry one
|
||||
/// value and state no bound: that value is the region-level floor the read already states.
|
||||
fn creator_slice_mask(
|
||||
context: &BulkIterContext,
|
||||
slices: Option<&[CreatorSliceCursor]>,
|
||||
read_fence: Option<SequenceNumber>,
|
||||
record_batch: &RecordBatch,
|
||||
) -> error::Result<Option<BooleanArray>> {
|
||||
let Some(slices) = slices.filter(|slices| !slices.is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let sequence_column = record_batch.column(sequence_column_index(record_batch.num_columns()));
|
||||
|
||||
// A row no slice explains is attributed to the least advanced candidate, bounded by the
|
||||
// least bound the candidates state: the only bound every one of them proves.
|
||||
let fallback = slices
|
||||
.iter()
|
||||
.map(|(_, cursor, _)| *cursor)
|
||||
.min()
|
||||
.unwrap_or_default();
|
||||
let fallback_until = least_slice_until(slices.iter().map(|(_, _, until)| until));
|
||||
let fallback_mask = creator_slice_sequence_range(fallback, fallback_until, read_fence)
|
||||
.filter(sequence_column)
|
||||
.context(ComputeArrowSnafu)?;
|
||||
|
||||
// One cursor value for every piece is the floor of the region: which piece a row belongs
|
||||
// to cannot change the outcome, so the batch needs no evaluation. A stated bound still
|
||||
// narrows every row alike, and the fallback mask above is exactly that rule.
|
||||
if slices.iter().all(|(_, cursor, _)| *cursor == fallback) {
|
||||
// Without a stated bound the read's own range is the whole rule, as it always was.
|
||||
return if fallback_until.is_none() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(fallback_mask))
|
||||
};
|
||||
}
|
||||
|
||||
// Per row, the candidate slice whose expression holds.
|
||||
let selected = match creator_slice_selection(context, slices, record_batch) {
|
||||
Ok(selected) => selected,
|
||||
Err(e) => {
|
||||
// Deciding a row's piece by guesswork would drop rows, and the least advanced
|
||||
// cursor only answers for the pieces that carry it.
|
||||
return unresolved_creator_slices(
|
||||
context,
|
||||
slices,
|
||||
fallback_mask,
|
||||
&format!("the slice expressions cannot be resolved: {e}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
// Per candidate, the rows whose own sequence is above its cursor, and the rows at or below
|
||||
// the bound it states (`None` = unbounded above, so the read's fence is the only end).
|
||||
let mut not_consumed = Vec::with_capacity(slices.len());
|
||||
let mut within_bound = Vec::with_capacity(slices.len());
|
||||
for (_, cursor, until) in slices {
|
||||
not_consumed.push(
|
||||
SequenceRange::Gt { min: *cursor }
|
||||
.filter(sequence_column)
|
||||
.context(ComputeArrowSnafu)?,
|
||||
);
|
||||
let bound = until.map(|until| read_fence.map_or(until, |fence| fence.min(until)));
|
||||
within_bound.push(
|
||||
bound
|
||||
.map(|max| {
|
||||
SequenceRange::LtEq { max }
|
||||
.filter(sequence_column)
|
||||
.context(ComputeArrowSnafu)
|
||||
})
|
||||
.transpose()?,
|
||||
);
|
||||
}
|
||||
|
||||
let num_rows = record_batch.num_rows();
|
||||
let mut kept = BooleanBufferBuilder::new(num_rows);
|
||||
let mut unmatched = 0;
|
||||
for row in 0..num_rows {
|
||||
let mut matched = false;
|
||||
let mut keep = false;
|
||||
let mut within = true;
|
||||
// The slices are disjoint, so at most one expression selects a row. If more than one
|
||||
// does (a domain that was not split cleanly), any candidate above its cursor keeps
|
||||
// the row — the least advanced cursor among them — while every one of them must
|
||||
// still cover the row with the bound it states.
|
||||
for (index, mask) in selected.iter().enumerate() {
|
||||
if mask.value(row) {
|
||||
matched = true;
|
||||
keep |= not_consumed[index].value(row);
|
||||
if let Some(bound) = &within_bound[index] {
|
||||
within &= bound.value(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
keep &= within;
|
||||
if !matched {
|
||||
unmatched += 1;
|
||||
keep = fallback_mask.value(row);
|
||||
}
|
||||
kept.append(keep);
|
||||
}
|
||||
if unmatched > 0 {
|
||||
debug!(
|
||||
"{} of {} rows of a bulk part match no creator cursor slice (least advanced cursor {})",
|
||||
unmatched, num_rows, fallback
|
||||
);
|
||||
return unresolved_creator_slices(
|
||||
context,
|
||||
slices,
|
||||
fallback_mask,
|
||||
&format!(
|
||||
"{unmatched} of {num_rows} rows of the part match no candidate expression, so \
|
||||
the piece they belong to cannot be resolved"
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Some(BooleanArray::from(kept.finish())))
|
||||
}
|
||||
|
||||
/// The mask of rows an unresolvable piece of a bulk part is bounded by, or a failure when the
|
||||
/// candidate cursors disagree.
|
||||
///
|
||||
/// This is the one rule for every row of a bulk part whose piece cannot be resolved — no
|
||||
/// candidate expression selects it, or one cannot be resolved, planned or evaluated. When the
|
||||
/// candidates all carry the **same** cursor value, that value is the least advanced one and
|
||||
/// the mask is exact: it keeps exactly the rows the per-row rule keeps, so the fallback stays,
|
||||
/// silently and without any evaluation of its own. When they carry several values, the least
|
||||
/// advanced one keeps the rows a more advanced piece has already consumed: that is a
|
||||
/// **duplicate**, not a replay, and an exact read must not degrade that way without saying so.
|
||||
/// The bounds the error reports are the cursors' own span, which is the disagreement the read
|
||||
/// cannot resolve.
|
||||
fn unresolved_creator_slices(
|
||||
context: &BulkIterContext,
|
||||
slices: &[CreatorSliceCursor],
|
||||
fallback_mask: BooleanArray,
|
||||
detail: &str,
|
||||
) -> error::Result<Option<BooleanArray>> {
|
||||
let Some(min) = slices.iter().map(|(_, cursor, _)| *cursor).min() else {
|
||||
return Ok(Some(fallback_mask));
|
||||
};
|
||||
let max = slices
|
||||
.iter()
|
||||
.map(|(_, cursor, _)| *cursor)
|
||||
.max()
|
||||
.unwrap_or(min);
|
||||
if min == max {
|
||||
return Ok(Some(fallback_mask));
|
||||
}
|
||||
let region_id = context.read_format().metadata().region_id;
|
||||
SequenceRangeUnsupportedSnafu {
|
||||
region_id,
|
||||
min_seq: min,
|
||||
max_seq: max,
|
||||
reason: format!(
|
||||
"the per-piece cursor of a bulk memtable part of region {} cannot be resolved while \
|
||||
the pieces of the region disagree on the last consumed sequence ({}..={}): bounding \
|
||||
every row by the least advanced cursor {} would deliver the rows a more advanced \
|
||||
piece has already consumed. {}",
|
||||
region_id, min, max, min, detail
|
||||
),
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
|
||||
/// Evaluates the candidate creator cursor slice expressions against the tag columns of
|
||||
/// `record_batch` and returns the mask of rows each expression selects.
|
||||
///
|
||||
/// The expressions are planned against a probe batch holding only the columns they
|
||||
/// reference, the same way a physical-sequence read of an SST compiles them. Fails when a
|
||||
/// referenced column is neither carried by the batch nor decodable from its primary key, or
|
||||
/// when an expression cannot be planned or evaluated.
|
||||
fn creator_slice_selection(
|
||||
context: &BulkIterContext,
|
||||
slices: &[CreatorSliceCursor],
|
||||
record_batch: &RecordBatch,
|
||||
) -> error::Result<Vec<BooleanBuffer>> {
|
||||
let metadata = context.read_format().metadata();
|
||||
let mut referenced = HashSet::new();
|
||||
for (expr, ..) in slices {
|
||||
expr.collect_column_names(&mut referenced);
|
||||
}
|
||||
|
||||
let mut fields = Vec::with_capacity(referenced.len());
|
||||
let mut columns = Vec::with_capacity(referenced.len());
|
||||
let mut decoded_pks: Option<DecodedPrimaryKeys> = None;
|
||||
for column_metadata in &metadata.column_metadatas {
|
||||
let name = &column_metadata.column_schema.name;
|
||||
if !referenced.remove(name) {
|
||||
continue;
|
||||
}
|
||||
let column_id = column_metadata.column_id;
|
||||
let Some((field, column)) =
|
||||
creator_slice_probe_column(context, column_id, record_batch, &mut decoded_pks)?
|
||||
else {
|
||||
return UnexpectedSnafu {
|
||||
reason: format!(
|
||||
"a creator cursor slice references column '{}' (id {}), which the bulk part batch neither carries nor encodes in its primary key",
|
||||
name, column_id
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
fields.push(field);
|
||||
columns.push(column);
|
||||
}
|
||||
if let Some(missing) = referenced.into_iter().next() {
|
||||
return UnexpectedSnafu {
|
||||
reason: format!(
|
||||
"a creator cursor slice references column '{}', which this region does not have",
|
||||
missing
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
|
||||
let probe =
|
||||
RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).context(ComputeArrowSnafu)?;
|
||||
let mut selected = Vec::with_capacity(slices.len());
|
||||
for (expr, ..) in slices {
|
||||
let filter = expr
|
||||
.try_as_physical_expr(probe.schema_ref())
|
||||
.context(SerializePartitionExprSnafu)?;
|
||||
let columnar_value = filter.evaluate(&probe).context(EvalPartitionFilterSnafu)?;
|
||||
let array = columnar_value
|
||||
.into_array(probe.num_rows())
|
||||
.context(EvalPartitionFilterSnafu)?;
|
||||
let boolean = array
|
||||
.as_any()
|
||||
.downcast_ref::<BooleanArray>()
|
||||
.ok_or_else(|| {
|
||||
UnexpectedSnafu {
|
||||
reason: format!(
|
||||
"a partition expression must evaluate to a boolean array, got {:?}",
|
||||
array.data_type()
|
||||
),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
// A null result is "not selected", the same rule the region partition filter applies.
|
||||
let mut mask = boolean.values().clone();
|
||||
if let Some(nulls) = boolean.nulls() {
|
||||
mask = mask.bitand(nulls.inner());
|
||||
}
|
||||
selected.push(mask);
|
||||
}
|
||||
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
/// Returns the field and the array of `column_id` for the rows of `record_batch`.
|
||||
///
|
||||
/// The column is taken from the batch when the projection carries it, and otherwise decoded
|
||||
/// from the primary key the batch states, the way the predicate filters resolve a tag
|
||||
/// outside the projection. `None` means the column cannot be resolved at all.
|
||||
fn creator_slice_probe_column(
|
||||
context: &BulkIterContext,
|
||||
column_id: ColumnId,
|
||||
record_batch: &RecordBatch,
|
||||
decoded_pks: &mut Option<DecodedPrimaryKeys>,
|
||||
) -> error::Result<Option<(Arc<Field>, ArrayRef)>> {
|
||||
if let Some(index) = context.read_format().projected_index_by_id(column_id) {
|
||||
let Some(field) = record_batch.schema_ref().fields().get(index).cloned() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
return Ok(Some((field, record_batch.column(index).clone())));
|
||||
}
|
||||
|
||||
let metadata = context.read_format().metadata();
|
||||
let (Some(pk_index), Some(column_metadata)) = (
|
||||
metadata.primary_key_index(column_id),
|
||||
metadata.column_by_id(column_id),
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let decoded = match decoded_pks {
|
||||
Some(decoded) => decoded,
|
||||
None => decoded_pks.insert(decode_primary_keys(
|
||||
context.base.codec.as_ref(),
|
||||
record_batch,
|
||||
)?),
|
||||
};
|
||||
let pk_index = if context.base.codec.encoding() == PrimaryKeyEncoding::Sparse {
|
||||
None
|
||||
} else {
|
||||
Some(pk_index)
|
||||
};
|
||||
let data_type = &column_metadata.column_schema.data_type;
|
||||
let column = decoded.get_tag_column(column_id, pk_index, data_type)?;
|
||||
let field = tag_maybe_to_dictionary_field(
|
||||
data_type,
|
||||
&Arc::new(Field::new(
|
||||
&column_metadata.column_schema.name,
|
||||
data_type.as_arrow_type(),
|
||||
column_metadata.column_schema.is_nullable(),
|
||||
)),
|
||||
);
|
||||
|
||||
Ok(Some((field, column)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
@@ -773,4 +1150,298 @@ mod tests {
|
||||
let result: Vec<_> = iter.map(|rb| rb.unwrap()).collect();
|
||||
assert_eq!(expect_batches, result);
|
||||
}
|
||||
|
||||
/// A bulk part resolves the piece of every row from its own tag columns, so a slice
|
||||
/// expression over a column the part neither carries nor encodes in its primary key
|
||||
/// cannot be evaluated. Bounding the part by the least advanced cursor is exact only while
|
||||
/// every candidate carries it: with several cursor values it re-delivers the rows a more
|
||||
/// advanced piece has already consumed, so the read fails instead.
|
||||
#[test]
|
||||
fn test_bulk_part_fails_closed_when_slices_disagree_and_probe_is_unresolved() {
|
||||
use datatypes::value::Value;
|
||||
use partition::expr::Operand;
|
||||
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("key1", DataType::Utf8, false),
|
||||
Field::new("field1", DataType::Int64, false),
|
||||
Field::new(
|
||||
"timestamp",
|
||||
DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Millisecond, None),
|
||||
false,
|
||||
),
|
||||
Field::new(
|
||||
"__primary_key",
|
||||
DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Binary)),
|
||||
false,
|
||||
),
|
||||
Field::new("__sequence", DataType::UInt64, false),
|
||||
Field::new("__op_type", DataType::UInt8, false),
|
||||
]));
|
||||
|
||||
// Three rows of two series, numbered 3, 4 and 6.
|
||||
let keys = ["key1", "key1", "key2"];
|
||||
let key1 = Arc::new(StringArray::from_iter_values(keys));
|
||||
let field1 = Arc::new(Int64Array::from(vec![0, 0, 0]));
|
||||
let timestamp = Arc::new(datatypes::arrow::array::TimestampMillisecondArray::from(
|
||||
vec![0, 1000, 2000],
|
||||
));
|
||||
let values = Arc::new(BinaryArray::from_iter_values(
|
||||
keys.iter().map(|key| new_primary_key(&[*key])),
|
||||
));
|
||||
let primary_key = Arc::new(DictionaryArray::new(
|
||||
UInt32Array::from(vec![0, 0, 1]),
|
||||
values,
|
||||
));
|
||||
let sequence = Arc::new(UInt64Array::from(vec![3, 4, 6]));
|
||||
let op_type = Arc::new(UInt8Array::from(vec![1, 1, 1]));
|
||||
let record_batch = RecordBatch::try_new(
|
||||
schema,
|
||||
vec![key1, field1, timestamp, primary_key, sequence, op_type],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1));
|
||||
builder
|
||||
.push_column_metadata(ColumnMetadata {
|
||||
column_schema: ColumnSchema::new(
|
||||
"key1",
|
||||
ConcreteDataType::string_datatype(),
|
||||
false,
|
||||
),
|
||||
semantic_type: SemanticType::Tag,
|
||||
column_id: 0,
|
||||
})
|
||||
.push_column_metadata(ColumnMetadata {
|
||||
column_schema: ColumnSchema::new(
|
||||
"field1",
|
||||
ConcreteDataType::int64_datatype(),
|
||||
false,
|
||||
),
|
||||
semantic_type: SemanticType::Field,
|
||||
column_id: 1,
|
||||
})
|
||||
.push_column_metadata(ColumnMetadata {
|
||||
column_schema: ColumnSchema::new(
|
||||
"timestamp",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
),
|
||||
semantic_type: SemanticType::Timestamp,
|
||||
column_id: 2,
|
||||
})
|
||||
.primary_key(vec![0]);
|
||||
// The projection drops `field1`, so the batch carries no value of it, and it is not a
|
||||
// primary-key column either: the probe of a slice over it cannot be built.
|
||||
let context = Arc::new(
|
||||
BulkIterContext::new(
|
||||
Arc::new(builder.build().unwrap()),
|
||||
Some(&[0, 2]),
|
||||
None,
|
||||
false,
|
||||
crate::sst::parquet::DEFAULT_READ_BATCH_SIZE,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
// Two candidate pieces over the column the part cannot state.
|
||||
let slices = |left: u64, right: u64| {
|
||||
let slices = vec![
|
||||
(
|
||||
partition::expr::col("field1").gt_eq(Operand::Value(Value::Int64(0))),
|
||||
left,
|
||||
None,
|
||||
),
|
||||
(
|
||||
partition::expr::col("field1").lt(Operand::Value(Value::Int64(0))),
|
||||
right,
|
||||
None,
|
||||
),
|
||||
];
|
||||
Some(Arc::new(slices))
|
||||
};
|
||||
let sequence_filter = Some(SequenceRange::GtLtEq { min: 2, max: 100 });
|
||||
|
||||
// Cursors 5 and 2: the least advanced one (2) would deliver the rows 3 and 4 the piece
|
||||
// consumed up to 5 has already consumed.
|
||||
let mut iter = BulkPartBatchIter::from_single(
|
||||
record_batch.clone(),
|
||||
context.clone(),
|
||||
sequence_filter,
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.with_creator_slices(slices(5, 2));
|
||||
let err = match iter.next() {
|
||||
Some(Err(err)) => err,
|
||||
Some(Ok(_)) => panic!("an unresolvable piece with disagreeing cursors must fail"),
|
||||
None => panic!("the read must fail instead of yielding no batch at all"),
|
||||
};
|
||||
let message = format!("{err}");
|
||||
assert!(
|
||||
message.contains("exact sequence range unavailable"),
|
||||
"the shared exact-range contract prefix must reach the caller: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("cannot be resolved while the pieces"),
|
||||
"the failure must say that the pieces disagree: {message}"
|
||||
);
|
||||
|
||||
// Both cursors 2: one cursor value for every piece is the region floor, so every row
|
||||
// above it is delivered without any evaluation of the expressions, exactly as before.
|
||||
let iter =
|
||||
BulkPartBatchIter::from_single(record_batch.clone(), context, sequence_filter, 0, None)
|
||||
.with_creator_slices(slices(2, 2));
|
||||
let result: Vec<_> = iter.map(|rb| rb.unwrap()).collect();
|
||||
assert_eq!(1, result.len());
|
||||
let sequences = result[0]
|
||||
.column(result[0].num_columns() - 2)
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
vec![3, 4, 6],
|
||||
sequences.values().to_vec(),
|
||||
"one cursor value for every piece keeps the part-level floor of the whole region"
|
||||
);
|
||||
}
|
||||
|
||||
/// A row numbered above the upper bound of its own slice belongs to a later delta: the
|
||||
/// bulk part resolves the piece of every row from its tag columns and narrows the read's
|
||||
/// fence by the bound that piece states, so the row is not delivered. A slice that states
|
||||
/// no bound keeps the fence alone, exactly as before the bound existed.
|
||||
#[test]
|
||||
fn test_bulk_part_does_not_deliver_rows_above_the_creator_slice_upper_bound() {
|
||||
use datatypes::value::Value;
|
||||
use partition::expr::Operand;
|
||||
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("key1", DataType::Utf8, false),
|
||||
Field::new("field1", DataType::Int64, false),
|
||||
Field::new(
|
||||
"timestamp",
|
||||
DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Millisecond, None),
|
||||
false,
|
||||
),
|
||||
Field::new(
|
||||
"__primary_key",
|
||||
DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Binary)),
|
||||
false,
|
||||
),
|
||||
Field::new("__sequence", DataType::UInt64, false),
|
||||
Field::new("__op_type", DataType::UInt8, false),
|
||||
]));
|
||||
|
||||
// Two series, numbered 3, 4 and 6 for the first and 7 for the second.
|
||||
let keys = ["a", "a", "a", "z"];
|
||||
let key1 = Arc::new(StringArray::from_iter_values(keys));
|
||||
let field1 = Arc::new(Int64Array::from(vec![0, 0, 0, 0]));
|
||||
let timestamp = Arc::new(datatypes::arrow::array::TimestampMillisecondArray::from(
|
||||
vec![0, 1000, 2000, 3000],
|
||||
));
|
||||
let values = Arc::new(BinaryArray::from_iter_values(
|
||||
keys.iter().map(|key| new_primary_key(&[*key])),
|
||||
));
|
||||
let primary_key = Arc::new(DictionaryArray::new(
|
||||
UInt32Array::from(vec![0, 0, 0, 1]),
|
||||
values,
|
||||
));
|
||||
let sequence = Arc::new(UInt64Array::from(vec![3, 4, 6, 7]));
|
||||
let op_type = Arc::new(UInt8Array::from(vec![1, 1, 1, 1]));
|
||||
let record_batch = RecordBatch::try_new(
|
||||
schema,
|
||||
vec![key1, field1, timestamp, primary_key, sequence, op_type],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1));
|
||||
builder
|
||||
.push_column_metadata(ColumnMetadata {
|
||||
column_schema: ColumnSchema::new(
|
||||
"key1",
|
||||
ConcreteDataType::string_datatype(),
|
||||
false,
|
||||
),
|
||||
semantic_type: SemanticType::Tag,
|
||||
column_id: 0,
|
||||
})
|
||||
.push_column_metadata(ColumnMetadata {
|
||||
column_schema: ColumnSchema::new(
|
||||
"field1",
|
||||
ConcreteDataType::int64_datatype(),
|
||||
false,
|
||||
),
|
||||
semantic_type: SemanticType::Field,
|
||||
column_id: 1,
|
||||
})
|
||||
.push_column_metadata(ColumnMetadata {
|
||||
column_schema: ColumnSchema::new(
|
||||
"timestamp",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
),
|
||||
semantic_type: SemanticType::Timestamp,
|
||||
column_id: 2,
|
||||
})
|
||||
.primary_key(vec![0]);
|
||||
|
||||
let context = Arc::new(
|
||||
BulkIterContext::new(Arc::new(builder.build().unwrap()), None, None, false, 1).unwrap(),
|
||||
);
|
||||
// The read's own fence is 10: it admits every row of the part, so only the per-piece
|
||||
// rule can hold the row at 7 back.
|
||||
let sequence_filter = Some(SequenceRange::GtLtEq { min: 4, max: 10 });
|
||||
let slice_lt =
|
||||
|| partition::expr::col("key1").lt(Operand::Value(Value::String("m".into())));
|
||||
let slice_ge =
|
||||
|| partition::expr::col("key1").gt_eq(Operand::Value(Value::String("m".into())));
|
||||
let read = |slices: Vec<(
|
||||
partition::expr::PartitionExpr,
|
||||
SequenceNumber,
|
||||
Option<SequenceNumber>,
|
||||
)>| {
|
||||
let iter = BulkPartBatchIter::from_single(
|
||||
record_batch.clone(),
|
||||
context.clone(),
|
||||
sequence_filter,
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.with_creator_slices(Some(Arc::new(slices)));
|
||||
let batches: Vec<_> = iter.map(|rb| rb.unwrap()).collect();
|
||||
let mut sequences = Vec::new();
|
||||
for batch in batches {
|
||||
let column = batch
|
||||
.column(batch.num_columns() - 2)
|
||||
.as_any()
|
||||
.downcast_ref::<UInt64Array>()
|
||||
.unwrap();
|
||||
sequences.extend_from_slice(column.values());
|
||||
}
|
||||
sequences
|
||||
};
|
||||
|
||||
// Both slices state the same delta end, 6. The row at 6 belongs to the piece consumed
|
||||
// up to 4 and is owed; the row at 7 belongs to the other piece, whose bound it is
|
||||
// above, so it is left to the delta that covers it.
|
||||
assert_eq!(
|
||||
vec![6],
|
||||
read(vec![(slice_lt(), 4, Some(6)), (slice_ge(), 5, Some(6)),]),
|
||||
"a row above its piece's upper bound is not part of this delta"
|
||||
);
|
||||
|
||||
// Without a stated bound the fence is the whole rule, as it always was: the row at 7
|
||||
// is above the cursor of its piece (5) and at or below the fence, so it is delivered.
|
||||
assert_eq!(
|
||||
vec![6, 7],
|
||||
read(vec![(slice_lt(), 4, None), (slice_ge(), 5, None)]),
|
||||
"without a bound every row above the piece's cursor is still owed"
|
||||
);
|
||||
|
||||
// A bound at or above the fence changes nothing: the fence is the tighter end.
|
||||
assert_eq!(
|
||||
vec![6, 7],
|
||||
read(vec![(slice_lt(), 4, Some(10)), (slice_ge(), 5, Some(10)),]),
|
||||
"the bound narrows the fence, it never widens it"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,6 +226,7 @@ impl Memtable for SimpleBulkMemtable {
|
||||
) -> error::Result<MemtableRanges> {
|
||||
let predicate = options.predicate;
|
||||
let sequence = options.sequence;
|
||||
let creator_slices = options.creator_slices;
|
||||
let start_time = Instant::now();
|
||||
let read_column_ids = read_column_ids_from_projection(&self.region_metadata, projection);
|
||||
let projection = Arc::new(self.build_projection(projection));
|
||||
@@ -256,11 +257,17 @@ impl Memtable for SimpleBulkMemtable {
|
||||
let contexts = values
|
||||
.into_par_iter()
|
||||
.filter_map(|v| {
|
||||
// This memtable holds one series for the whole region and keeps no
|
||||
// primary key, so a row cannot be attributed to a piece: the per-piece
|
||||
// filter falls back to the least advanced cursor of the set, which is the
|
||||
// region-level floor.
|
||||
let filtered = match v.to_batch(
|
||||
&[],
|
||||
&self.region_metadata,
|
||||
&projection,
|
||||
sequence,
|
||||
creator_slices.as_deref().map(Vec::as_slice),
|
||||
None,
|
||||
self.dedup,
|
||||
self.merge_mode,
|
||||
) {
|
||||
|
||||
@@ -37,7 +37,7 @@ use datatypes::vectors::{
|
||||
TimestampNanosecondVector, TimestampSecondVector, UInt8Vector, UInt64Vector,
|
||||
};
|
||||
use mito_codec::key_values::KeyValue;
|
||||
use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodecExt};
|
||||
use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodec, PrimaryKeyCodecExt};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::storage::{ColumnId, SequenceNumber, SequenceRange};
|
||||
@@ -53,9 +53,9 @@ use crate::memtable::simple_bulk_memtable::SimpleBulkMemtable;
|
||||
use crate::memtable::stats::WriteMetrics;
|
||||
use crate::memtable::{
|
||||
AllocTracker, BatchToRecordBatchContext, BoxedBatchIterator, BoxedRecordBatchIterator,
|
||||
IterBuilder, KeyValues, MemScanMetrics, Memtable, MemtableBuilder, MemtableId, MemtableRange,
|
||||
MemtableRangeContext, MemtableRanges, MemtableRef, MemtableStats, RangesOptions,
|
||||
read_column_ids_from_projection,
|
||||
CreatorSliceCursor, CreatorSliceCursors, IterBuilder, KeyValues, MemScanMetrics, Memtable,
|
||||
MemtableBuilder, MemtableId, MemtableRange, MemtableRangeContext, MemtableRanges, MemtableRef,
|
||||
MemtableStats, RangesOptions, read_column_ids_from_projection, sequence_range_upper,
|
||||
};
|
||||
use crate::metrics::{
|
||||
MEMTABLE_ACTIVE_FIELD_BUILDER_COUNT, MEMTABLE_ACTIVE_SERIES_COUNT, READ_ROWS_TOTAL,
|
||||
@@ -370,6 +370,7 @@ impl Memtable for TimeSeriesMemtable {
|
||||
) -> Result<MemtableRanges> {
|
||||
let predicate = options.predicate;
|
||||
let sequence = options.sequence;
|
||||
let creator_slices = options.creator_slices;
|
||||
let read_column_ids = read_column_ids_from_projection(&self.region_metadata, projection);
|
||||
let projection = if let Some(projection) = projection {
|
||||
projection.iter().copied().collect()
|
||||
@@ -390,6 +391,7 @@ impl Memtable for TimeSeriesMemtable {
|
||||
dedup: self.dedup,
|
||||
merge_mode: self.merge_mode,
|
||||
sequence,
|
||||
creator_slices,
|
||||
batch_to_record_batch,
|
||||
});
|
||||
let context = Arc::new(MemtableRangeContext::new(self.id, builder, predicate));
|
||||
@@ -546,6 +548,7 @@ impl SeriesSet {
|
||||
}
|
||||
|
||||
/// Iterates all series in [SeriesSet].
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn iter_series(
|
||||
&self,
|
||||
projection: HashSet<ColumnId>,
|
||||
@@ -553,6 +556,7 @@ impl SeriesSet {
|
||||
dedup: bool,
|
||||
merge_mode: MergeMode,
|
||||
sequence: Option<SequenceRange>,
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
mem_scan_metrics: Option<MemScanMetrics>,
|
||||
) -> Result<Iter> {
|
||||
let primary_key_schema = primary_key_schema(&self.region_metadata);
|
||||
@@ -573,6 +577,7 @@ impl SeriesSet {
|
||||
dedup,
|
||||
merge_mode,
|
||||
sequence,
|
||||
creator_slices,
|
||||
mem_scan_metrics,
|
||||
)
|
||||
}
|
||||
@@ -623,6 +628,9 @@ struct Iter {
|
||||
dedup: bool,
|
||||
merge_mode: MergeMode,
|
||||
sequence: Option<SequenceRange>,
|
||||
/// The cursor of each piece a row may belong to, when this read states them
|
||||
/// ([`RangesOptions::creator_slices`]).
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
metrics: Metrics,
|
||||
mem_scan_metrics: Option<MemScanMetrics>,
|
||||
}
|
||||
@@ -640,6 +648,7 @@ impl Iter {
|
||||
dedup: bool,
|
||||
merge_mode: MergeMode,
|
||||
sequence: Option<SequenceRange>,
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
mem_scan_metrics: Option<MemScanMetrics>,
|
||||
) -> Result<Self> {
|
||||
let predicate = predicate
|
||||
@@ -669,6 +678,7 @@ impl Iter {
|
||||
dedup,
|
||||
merge_mode,
|
||||
sequence,
|
||||
creator_slices,
|
||||
metrics: Metrics::default(),
|
||||
mem_scan_metrics,
|
||||
})
|
||||
@@ -742,12 +752,15 @@ impl Iterator for Iter {
|
||||
self.last_key = Some(primary_key.clone());
|
||||
|
||||
let values = series.compact(&self.metadata);
|
||||
let creator_slices = self.creator_slices.as_deref().map(Vec::as_slice);
|
||||
let batch = values.and_then(|v| {
|
||||
v.to_batch(
|
||||
primary_key,
|
||||
&self.metadata,
|
||||
&self.projection,
|
||||
self.sequence,
|
||||
creator_slices,
|
||||
Some(self.codec.as_ref()),
|
||||
self.dedup,
|
||||
self.merge_mode,
|
||||
)
|
||||
@@ -1221,12 +1234,21 @@ pub struct Values {
|
||||
impl Values {
|
||||
/// Converts [Values] to `Batch`, applies the optional sequence filter, sorts the batch
|
||||
/// according to `timestamp, sequence` desc, and applies dedup/merge according to `merge_mode`.
|
||||
///
|
||||
/// `creator_slices` is the cursor of each piece a row may belong to
|
||||
/// ([`RangesOptions::creator_slices`]): when present, a row is additionally kept only
|
||||
/// when its sequence is above the cursor of the piece its tag values fall into, which
|
||||
/// replaces the single floor `sequence` states. `codec` decodes the primary key the
|
||||
/// piece is resolved from.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn to_batch(
|
||||
&self,
|
||||
primary_key: &[u8],
|
||||
metadata: &RegionMetadataRef,
|
||||
projection: &HashSet<ColumnId>,
|
||||
sequence: Option<SequenceRange>,
|
||||
creator_slices: Option<&[CreatorSliceCursor]>,
|
||||
codec: Option<&dyn PrimaryKeyCodec>,
|
||||
dedup: bool,
|
||||
merge_mode: MergeMode,
|
||||
) -> Result<Batch> {
|
||||
@@ -1253,6 +1275,12 @@ impl Values {
|
||||
// - avoid dropping a timestamp when the newest row is out of range
|
||||
// - avoid filling null fields from rows that should be excluded by the sequence filter.
|
||||
batch.filter_by_sequence(sequence)?;
|
||||
// The cursor of the piece this series belongs to replaces the single floor of
|
||||
// `sequence`: the floor is the least advanced piece of the region, so it cannot tell
|
||||
// a row of a more advanced piece from a consumed one. The piece's own upper bound
|
||||
// narrows the read's fence, which is the upper end `sequence` states.
|
||||
let read_fence = sequence_range_upper(sequence.as_ref());
|
||||
batch.filter_by_creator_slices(creator_slices, read_fence, metadata, codec)?;
|
||||
|
||||
match (dedup, merge_mode) {
|
||||
// append-only, keep duplicate rows.
|
||||
@@ -1357,6 +1385,9 @@ struct TimeSeriesIterBuilder {
|
||||
predicate: PredicateGroup,
|
||||
dedup: bool,
|
||||
sequence: Option<SequenceRange>,
|
||||
/// The cursor of each piece a row may belong to
|
||||
/// ([`RangesOptions::creator_slices`]).
|
||||
creator_slices: Option<CreatorSliceCursors>,
|
||||
merge_mode: MergeMode,
|
||||
batch_to_record_batch: Arc<BatchToRecordBatchContext>,
|
||||
}
|
||||
@@ -1369,6 +1400,7 @@ impl IterBuilder for TimeSeriesIterBuilder {
|
||||
self.dedup,
|
||||
self.merge_mode,
|
||||
self.sequence,
|
||||
self.creator_slices.clone(),
|
||||
metrics,
|
||||
)?;
|
||||
if self.merge_mode == MergeMode::LastNonNull {
|
||||
@@ -1611,6 +1643,8 @@ mod tests {
|
||||
&schema,
|
||||
&[0, 1, 2, 3, 4].into_iter().collect(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
MergeMode::LastRow,
|
||||
)
|
||||
@@ -1681,6 +1715,8 @@ mod tests {
|
||||
&schema,
|
||||
&projection,
|
||||
Some(SequenceRange::LtEq { max: 2 }),
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
MergeMode::LastNonNull,
|
||||
)
|
||||
@@ -1728,6 +1764,8 @@ mod tests {
|
||||
&schema,
|
||||
&projection,
|
||||
Some(SequenceRange::Gt { min: 1 }),
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
MergeMode::LastNonNull,
|
||||
)
|
||||
@@ -2001,6 +2039,351 @@ mod tests {
|
||||
assert_eq!((0..100i64).collect::<Vec<_>>(), v0_all);
|
||||
}
|
||||
|
||||
/// A memtable row is filtered by the cursor of the piece it belongs to, never by the
|
||||
/// single floor of the region: the floor is the least advanced piece, so it delivers the
|
||||
/// rows a more advanced piece already consumed.
|
||||
#[test]
|
||||
fn test_memtable_filters_rows_by_creator_slice_cursor() {
|
||||
use partition::expr::{Operand, col};
|
||||
|
||||
let schema = schema_for_test();
|
||||
let memtable = TimeSeriesMemtable::new(schema.clone(), 1, None, false, MergeMode::LastRow);
|
||||
|
||||
let column_schema = schema
|
||||
.column_metadatas
|
||||
.iter()
|
||||
.map(|c| api::v1::ColumnSchema {
|
||||
column_name: c.column_schema.name.clone(),
|
||||
datatype: ColumnDataTypeWrapper::try_from(c.column_schema.data_type.clone())
|
||||
.unwrap()
|
||||
.datatype() as i32,
|
||||
semantic_type: c.semantic_type as i32,
|
||||
..Default::default()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// Writes one row per call with an explicit sequence, so the rows of one series can
|
||||
// be numbered independently of the others.
|
||||
let write_row = |k0: &str, ts: i64, sequence: u64| {
|
||||
let mutation = Mutation {
|
||||
op_type: 1,
|
||||
sequence,
|
||||
rows: Some(Rows {
|
||||
schema: column_schema.clone(),
|
||||
rows: vec![row(vec![
|
||||
ValueData::StringValue(k0.to_string()),
|
||||
ValueData::I64Value(0),
|
||||
ValueData::TimestampMillisecondValue(ts),
|
||||
ValueData::I64Value(ts),
|
||||
ValueData::F64Value(0.0),
|
||||
])],
|
||||
}),
|
||||
write_hint: None,
|
||||
};
|
||||
let kvs = KeyValues::new(schema.as_ref(), mutation).unwrap();
|
||||
memtable.write(&kvs).unwrap();
|
||||
};
|
||||
|
||||
// `k0 < "m"` is the piece consumed up to 5, `k0 >= "m"` the one consumed up to 2.
|
||||
write_row("a", 0, 3);
|
||||
write_row("a", 1, 4);
|
||||
write_row("z", 2, 6);
|
||||
|
||||
let read = |slices: Vec<(
|
||||
partition::expr::PartitionExpr,
|
||||
SequenceNumber,
|
||||
Option<SequenceNumber>,
|
||||
)>| {
|
||||
let options = RangesOptions::default()
|
||||
.with_sequence(Some(SequenceRange::GtLtEq { min: 2, max: 100 }))
|
||||
.with_creator_slices(Some(Arc::new(slices)));
|
||||
let mut iter = memtable.ranges(None, options).unwrap().build(None).unwrap();
|
||||
let mut rows = Vec::new();
|
||||
for batch in iter.by_ref() {
|
||||
let batch = batch.unwrap();
|
||||
let timestamps = batch.timestamps().to_arrow_array();
|
||||
let timestamps = timestamps
|
||||
.as_any()
|
||||
.downcast_ref::<datatypes::arrow::array::TimestampMillisecondArray>()
|
||||
.unwrap();
|
||||
for (idx, sequence) in batch.sequences().iter_data().enumerate() {
|
||||
rows.push((timestamps.value(idx), sequence.unwrap()));
|
||||
}
|
||||
}
|
||||
rows.sort_unstable();
|
||||
rows
|
||||
};
|
||||
|
||||
let slice_lt = || col("k0").lt(Operand::Value(Value::String("m".into())));
|
||||
let slice_ge = || col("k0").gt_eq(Operand::Value(Value::String("m".into())));
|
||||
|
||||
// The region-level floor (2) keeps the rows at 3, 4 and 6, but the piece of the
|
||||
// first two is consumed up to 5: only the row of the piece consumed up to 2 is
|
||||
// delivered.
|
||||
assert_eq!(
|
||||
vec![(2, 6)],
|
||||
read(vec![(slice_lt(), 5, None), (slice_ge(), 2, None)]),
|
||||
"the rows at 3 and 4 belong to the piece consumed up to 5 and are not delivered \
|
||||
again, the row at 6 belongs to the piece consumed up to 2 and is"
|
||||
);
|
||||
|
||||
// One cursor value for every piece is the region-level floor: the delivered rows are
|
||||
// exactly the rows above the floor, whatever piece they belong to.
|
||||
assert_eq!(
|
||||
vec![(0, 3), (1, 4), (2, 6)],
|
||||
read(vec![(slice_lt(), 2, None), (slice_ge(), 2, None)]),
|
||||
"with one cursor value the rows are exactly the rows above the region floor"
|
||||
);
|
||||
|
||||
// A series no candidate expression selects cannot be attributed to a piece while the
|
||||
// candidates disagree: bounding it by the least advanced cursor (2) would deliver the
|
||||
// rows the piece at 5 already consumed, so the read fails instead of replaying them.
|
||||
let options = RangesOptions::default()
|
||||
.with_sequence(Some(SequenceRange::GtLtEq { min: 2, max: 100 }))
|
||||
.with_creator_slices(Some(Arc::new(vec![
|
||||
(
|
||||
col("k0").lt(Operand::Value(Value::String("a".into()))),
|
||||
5,
|
||||
None,
|
||||
),
|
||||
(
|
||||
col("k0").gt_eq(Operand::Value(Value::String("z".into()))),
|
||||
2,
|
||||
None,
|
||||
),
|
||||
])));
|
||||
let mut iter = memtable.ranges(None, options).unwrap().build(None).unwrap();
|
||||
let err = iter
|
||||
.find_map(|batch| batch.err())
|
||||
.expect("a row no candidate explains fails the read while the cursors disagree");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("cannot be resolved while the pieces"),
|
||||
"the failure names the unresolved piece: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A batch whose piece cannot be resolved is bounded by the least advanced cursor only
|
||||
/// while every candidate carries it. With several cursor values that floor re-delivers
|
||||
/// the rows a more advanced piece has already consumed — a duplicate, not a replay — so
|
||||
/// the read fails instead of degrading silently.
|
||||
///
|
||||
/// The piece is unresolvable here because the slice expressions reference `v0`, a *field*
|
||||
/// column: a memtable batch states the tags of its series only, so the probe batch of the
|
||||
/// piece cannot be built.
|
||||
#[test]
|
||||
fn test_memtable_fails_closed_when_slices_disagree_and_piece_is_unresolved() {
|
||||
use partition::expr::{Operand, col};
|
||||
|
||||
let schema = schema_for_test();
|
||||
let memtable = TimeSeriesMemtable::new(schema.clone(), 1, None, false, MergeMode::LastRow);
|
||||
|
||||
let column_schema = schema
|
||||
.column_metadatas
|
||||
.iter()
|
||||
.map(|c| api::v1::ColumnSchema {
|
||||
column_name: c.column_schema.name.clone(),
|
||||
datatype: ColumnDataTypeWrapper::try_from(c.column_schema.data_type.clone())
|
||||
.unwrap()
|
||||
.datatype() as i32,
|
||||
semantic_type: c.semantic_type as i32,
|
||||
..Default::default()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// Rows 3 and 4 belong to the series `a`, row 6 to the series `z`.
|
||||
for (k0, ts, sequence) in [("a", 0, 3), ("a", 1, 4), ("z", 2, 6)] {
|
||||
let mutation = Mutation {
|
||||
op_type: 1,
|
||||
sequence,
|
||||
rows: Some(Rows {
|
||||
schema: column_schema.clone(),
|
||||
rows: vec![row(vec![
|
||||
ValueData::StringValue(k0.to_string()),
|
||||
ValueData::I64Value(0),
|
||||
ValueData::TimestampMillisecondValue(ts),
|
||||
ValueData::I64Value(ts),
|
||||
ValueData::F64Value(0.0),
|
||||
])],
|
||||
}),
|
||||
write_hint: None,
|
||||
};
|
||||
memtable
|
||||
.write(&KeyValues::new(schema.as_ref(), mutation).unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Two candidate pieces over a column the batch states no value for.
|
||||
let slices = |left: u64, right: u64| {
|
||||
vec![
|
||||
(col("v0").gt_eq(Operand::Value(Value::Int64(0))), left, None),
|
||||
(col("v0").lt(Operand::Value(Value::Int64(0))), right, None),
|
||||
]
|
||||
};
|
||||
let options = |pieces| {
|
||||
RangesOptions::default()
|
||||
.with_sequence(Some(SequenceRange::GtLtEq { min: 2, max: 100 }))
|
||||
.with_creator_slices(Some(Arc::new(pieces)))
|
||||
};
|
||||
|
||||
// Cursors 5 and 2: the least advanced one (2) would deliver the rows 3 and 4 again,
|
||||
// which the piece consumed up to 5 already consumed.
|
||||
let mut iter = memtable
|
||||
.ranges(None, options(slices(5, 2)))
|
||||
.unwrap()
|
||||
.build(None)
|
||||
.unwrap();
|
||||
let err = match iter.next() {
|
||||
Some(Err(err)) => err,
|
||||
Some(Ok(_)) => panic!("an unresolvable piece with disagreeing cursors must fail"),
|
||||
None => panic!("the read must fail instead of yielding no batch at all"),
|
||||
};
|
||||
let message = format!("{err}");
|
||||
assert!(
|
||||
message.contains("exact sequence range unavailable"),
|
||||
"the shared exact-range contract prefix must reach the caller: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("cannot be resolved while the pieces"),
|
||||
"the failure must say that the pieces disagree: {message}"
|
||||
);
|
||||
|
||||
// Both cursors 2: one cursor value for every piece is the region floor, so the batch
|
||||
// is bounded by it without any evaluation of its own and the rows above 2 are
|
||||
// delivered exactly as before.
|
||||
let mut iter = memtable
|
||||
.ranges(None, options(slices(2, 2)))
|
||||
.unwrap()
|
||||
.build(None)
|
||||
.unwrap();
|
||||
let mut rows = Vec::new();
|
||||
for batch in iter.by_ref() {
|
||||
let batch = batch.unwrap();
|
||||
let timestamps = batch.timestamps().to_arrow_array();
|
||||
let timestamps = timestamps
|
||||
.as_any()
|
||||
.downcast_ref::<datatypes::arrow::array::TimestampMillisecondArray>()
|
||||
.unwrap();
|
||||
for (idx, sequence) in batch.sequences().iter_data().enumerate() {
|
||||
rows.push((timestamps.value(idx), sequence.unwrap()));
|
||||
}
|
||||
}
|
||||
rows.sort_unstable();
|
||||
assert_eq!(
|
||||
vec![(0, 3), (1, 4), (2, 6)],
|
||||
rows,
|
||||
"one cursor value for every piece keeps the batch-level floor of the whole region"
|
||||
);
|
||||
}
|
||||
|
||||
/// A row numbered above the upper bound of its own slice belongs to a later delta: the
|
||||
/// piece's bound narrows the read's fence, so the memtable does not deliver it. A slice
|
||||
/// that states no bound keeps the fence alone, exactly as before the bound existed.
|
||||
#[test]
|
||||
fn test_memtable_does_not_deliver_rows_above_the_creator_slice_upper_bound() {
|
||||
use partition::expr::{Operand, col};
|
||||
|
||||
let schema = schema_for_test();
|
||||
let memtable = TimeSeriesMemtable::new(schema.clone(), 1, None, false, MergeMode::LastRow);
|
||||
|
||||
let column_schema = schema
|
||||
.column_metadatas
|
||||
.iter()
|
||||
.map(|c| api::v1::ColumnSchema {
|
||||
column_name: c.column_schema.name.clone(),
|
||||
datatype: ColumnDataTypeWrapper::try_from(c.column_schema.data_type.clone())
|
||||
.unwrap()
|
||||
.datatype() as i32,
|
||||
semantic_type: c.semantic_type as i32,
|
||||
..Default::default()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let write_row = |k0: &str, ts: i64, sequence: u64| {
|
||||
let mutation = Mutation {
|
||||
op_type: 1,
|
||||
sequence,
|
||||
rows: Some(Rows {
|
||||
schema: column_schema.clone(),
|
||||
rows: vec![row(vec![
|
||||
ValueData::StringValue(k0.to_string()),
|
||||
ValueData::I64Value(0),
|
||||
ValueData::TimestampMillisecondValue(ts),
|
||||
ValueData::I64Value(ts),
|
||||
ValueData::F64Value(0.0),
|
||||
])],
|
||||
}),
|
||||
write_hint: None,
|
||||
};
|
||||
let kvs = KeyValues::new(schema.as_ref(), mutation).unwrap();
|
||||
memtable.write(&kvs).unwrap();
|
||||
};
|
||||
|
||||
// `k0 < "m"` is the piece consumed up to 4, `k0 >= "m"` the one consumed up to 5.
|
||||
write_row("a", 0, 3);
|
||||
write_row("a", 1, 4);
|
||||
write_row("a", 2, 6);
|
||||
write_row("z", 3, 7);
|
||||
|
||||
let slice_lt = || col("k0").lt(Operand::Value(Value::String("m".into())));
|
||||
let slice_ge = || col("k0").gt_eq(Operand::Value(Value::String("m".into())));
|
||||
let read = |slices: Vec<(
|
||||
partition::expr::PartitionExpr,
|
||||
SequenceNumber,
|
||||
Option<SequenceNumber>,
|
||||
)>| {
|
||||
// The read's own fence is 10: it admits every row of the memtable, so only the
|
||||
// per-piece rule can hold the row at 7 back.
|
||||
let options = RangesOptions::default()
|
||||
.with_sequence(Some(SequenceRange::GtLtEq { min: 4, max: 10 }))
|
||||
.with_creator_slices(Some(Arc::new(slices)));
|
||||
let mut iter = memtable.ranges(None, options).unwrap().build(None).unwrap();
|
||||
let mut rows = Vec::new();
|
||||
for batch in iter.by_ref() {
|
||||
let batch = batch.unwrap();
|
||||
let timestamps = batch.timestamps().to_arrow_array();
|
||||
let timestamps = timestamps
|
||||
.as_any()
|
||||
.downcast_ref::<datatypes::arrow::array::TimestampMillisecondArray>()
|
||||
.unwrap();
|
||||
for (idx, sequence) in batch.sequences().iter_data().enumerate() {
|
||||
rows.push((timestamps.value(idx), sequence.unwrap()));
|
||||
}
|
||||
}
|
||||
rows.sort_unstable();
|
||||
rows
|
||||
};
|
||||
|
||||
// Both slices state the same delta end, 6. The row at 6 belongs to the piece consumed
|
||||
// up to 4 and is owed; the row at 7 belongs to the other piece, whose bound it is
|
||||
// above, so it is left to the delta that covers it.
|
||||
assert_eq!(
|
||||
vec![(2, 6)],
|
||||
read(vec![(slice_lt(), 4, Some(6)), (slice_ge(), 5, Some(6)),]),
|
||||
"a row above its piece's upper bound is not part of this delta"
|
||||
);
|
||||
|
||||
// The same rows with the bounds the defect report states: a piece already consumed up
|
||||
// to 9 whose delta ends at 6 still cannot deliver the row at 7.
|
||||
assert_eq!(
|
||||
vec![(2, 6)],
|
||||
read(vec![(slice_lt(), 4, Some(6)), (slice_ge(), 9, Some(6)),]),
|
||||
"a bound below the piece's cursor states no window at all, and delivers nothing"
|
||||
);
|
||||
|
||||
// Without a stated bound the fence is the whole rule, as it always was: the row at 7
|
||||
// is above the cursor of its piece (5) and at or below the fence, so it is delivered.
|
||||
assert_eq!(
|
||||
vec![(2, 6), (3, 7)],
|
||||
read(vec![(slice_lt(), 4, None), (slice_ge(), 5, None)]),
|
||||
"without a bound every row above the piece's cursor is still owed"
|
||||
);
|
||||
|
||||
// A bound at or above the fence changes nothing: the fence is the tighter end.
|
||||
assert_eq!(
|
||||
vec![(2, 6), (3, 7)],
|
||||
read(vec![(slice_lt(), 4, Some(10)), (slice_ge(), 5, Some(10)),]),
|
||||
"the bound narrows the fence, it never widens it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_memtable_concurrent_write_read() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
@@ -2211,6 +2594,7 @@ mod tests {
|
||||
dedup,
|
||||
merge_mode,
|
||||
sequence,
|
||||
creator_slices: None,
|
||||
batch_to_record_batch: adapter_context,
|
||||
}
|
||||
}
|
||||
|
||||
+317
-22
@@ -40,17 +40,21 @@ pub mod stream;
|
||||
pub(crate) mod substituted_rows;
|
||||
pub(crate) mod unordered_scan;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use api::v1::OpType;
|
||||
use arrow_schema::SchemaRef;
|
||||
use common_telemetry::debug;
|
||||
use common_time::Timestamp;
|
||||
use datafusion::physical_plan::PhysicalExpr;
|
||||
use datafusion_common::arrow::array::UInt8Array;
|
||||
use datatypes::arrow;
|
||||
use datatypes::arrow::array::{Array, ArrayRef};
|
||||
use datatypes::arrow::array::{Array, ArrayRef, BooleanArray};
|
||||
use datatypes::arrow::compute::SortOptions;
|
||||
use datatypes::arrow::datatypes::{Field, Schema};
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use datatypes::arrow::row::{RowConverter, SortField};
|
||||
use datatypes::prelude::{ConcreteDataType, DataType, ScalarVector};
|
||||
@@ -67,13 +71,16 @@ use futures::TryStreamExt;
|
||||
use futures::stream::BoxStream;
|
||||
use mito_codec::row_converter::{CompositeValues, DensePrimaryKeyCodec, PrimaryKeyCodec};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::storage::{ColumnId, SequenceNumber, SequenceRange};
|
||||
|
||||
use crate::error::{
|
||||
ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu, InvalidBatchSnafu,
|
||||
Result,
|
||||
ComputeArrowSnafu, ComputeVectorSnafu, ConvertVectorSnafu, DecodeSnafu,
|
||||
EvalPartitionFilterSnafu, InvalidBatchSnafu, Result, SequenceRangeUnsupportedSnafu,
|
||||
};
|
||||
use crate::memtable::{
|
||||
BoxedRecordBatchIterator, CreatorSliceCursor, creator_slice_sequence_range, least_slice_until,
|
||||
};
|
||||
use crate::memtable::BoxedRecordBatchIterator;
|
||||
|
||||
pub(crate) fn timestamp_array_to_i64_slice(arr: &ArrayRef) -> &[i64] {
|
||||
use datatypes::arrow::array::{
|
||||
@@ -144,6 +151,113 @@ struct DensePkCache {
|
||||
values: Vec<Option<Value>>,
|
||||
}
|
||||
|
||||
/// Builds the one-row batch of tag values the primary key of a batch states, holding the
|
||||
/// columns the candidate creator cursor slices reference.
|
||||
///
|
||||
/// A time-series memtable batch is one series, so the tag values of the whole batch are the
|
||||
/// values of that series and one row is enough to decide which piece it belongs to. The
|
||||
/// values are extracted from the decoded primary key, which is how the memtable states its
|
||||
/// tags.
|
||||
///
|
||||
/// `None` means the piece cannot be decided: a referenced column is missing from the region
|
||||
/// or is not part of its primary key, or a value does not convert to the column's type. The
|
||||
/// caller then applies [`Batch::unresolved_creator_cursor`] to the candidate cursors.
|
||||
fn creator_slice_probe_batch(
|
||||
metadata: &RegionMetadataRef,
|
||||
slices: &[CreatorSliceCursor],
|
||||
pk_values: &CompositeValues,
|
||||
) -> Option<RecordBatch> {
|
||||
let mut referenced = HashSet::new();
|
||||
for (expr, ..) in slices {
|
||||
expr.collect_column_names(&mut referenced);
|
||||
}
|
||||
|
||||
let mut fields = Vec::with_capacity(referenced.len());
|
||||
let mut columns = Vec::with_capacity(referenced.len());
|
||||
for column_metadata in &metadata.column_metadatas {
|
||||
let name = &column_metadata.column_schema.name;
|
||||
if !referenced.remove(name) {
|
||||
continue;
|
||||
}
|
||||
let column_id = column_metadata.column_id;
|
||||
// Only a primary-key column carries a value the memtable batch states.
|
||||
let pk_index = metadata.primary_key_index(column_id)?;
|
||||
let value = match pk_values {
|
||||
CompositeValues::Dense(values) => &values.get(pk_index)?.1,
|
||||
CompositeValues::Sparse(values) => values.get_or_null(column_id),
|
||||
};
|
||||
let data_type = &column_metadata.column_schema.data_type;
|
||||
let scalar = value.try_to_scalar_value(data_type).ok()?;
|
||||
let array = Helper::try_from_scalar_value(scalar, 1, Some(data_type))
|
||||
.ok()?
|
||||
.to_arrow_array();
|
||||
fields.push(Field::new(
|
||||
name,
|
||||
data_type.as_arrow_type(),
|
||||
column_metadata.column_schema.is_nullable(),
|
||||
));
|
||||
columns.push(array);
|
||||
}
|
||||
if !referenced.is_empty() {
|
||||
// A referenced column this region does not have cannot be evaluated.
|
||||
return None;
|
||||
}
|
||||
|
||||
RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).ok()
|
||||
}
|
||||
|
||||
/// The least and the greatest cursor value of a candidate slice set.
|
||||
///
|
||||
/// Equal bounds mean every candidate carries the same cursor value — the only case in which
|
||||
/// the least advanced cursor is exact for a piece that cannot be resolved.
|
||||
fn creator_cursor_range(slices: &[CreatorSliceCursor]) -> (SequenceNumber, SequenceNumber) {
|
||||
let min = slices
|
||||
.iter()
|
||||
.map(|(_, cursor, _)| *cursor)
|
||||
.min()
|
||||
.unwrap_or_default();
|
||||
let max = slices
|
||||
.iter()
|
||||
.map(|(_, cursor, _)| *cursor)
|
||||
.max()
|
||||
.unwrap_or(min);
|
||||
(min, max)
|
||||
}
|
||||
|
||||
/// The least of two slices' upper bounds: a slice that states none is unbounded above, so it
|
||||
/// never narrows the pair, and two slices that state none stay unbounded.
|
||||
fn least_until(
|
||||
left: Option<SequenceNumber>,
|
||||
right: Option<SequenceNumber>,
|
||||
) -> Option<SequenceNumber> {
|
||||
match (left, right) {
|
||||
(Some(left), Some(right)) => Some(left.min(right)),
|
||||
(Some(bound), None) | (None, Some(bound)) => Some(bound),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates a partition expression against the single row of a probe batch, treating a
|
||||
/// null result as "not selected" (the same rule the region partition filter applies).
|
||||
fn evaluate_partition_filter(filter: &dyn PhysicalExpr, probe: &RecordBatch) -> Result<bool> {
|
||||
let columnar_value = filter.evaluate(probe).context(EvalPartitionFilterSnafu)?;
|
||||
let array = columnar_value
|
||||
.into_array(probe.num_rows())
|
||||
.context(EvalPartitionFilterSnafu)?;
|
||||
let boolean =
|
||||
array
|
||||
.as_any()
|
||||
.downcast_ref::<BooleanArray>()
|
||||
.context(crate::error::UnexpectedSnafu {
|
||||
reason: format!(
|
||||
"a partition expression must evaluate to a boolean array, got {:?}",
|
||||
array.data_type()
|
||||
),
|
||||
})?;
|
||||
|
||||
Ok(boolean.is_valid(0) && boolean.value(0))
|
||||
}
|
||||
|
||||
impl Batch {
|
||||
/// Creates a new batch.
|
||||
pub fn new(
|
||||
@@ -417,24 +531,205 @@ impl Batch {
|
||||
|
||||
/// Filters rows by the given `sequence`. Only preserves rows with sequence less than or equal to `sequence`.
|
||||
pub fn filter_by_sequence(&mut self, sequence: Option<SequenceRange>) -> Result<()> {
|
||||
let seq_range = match sequence {
|
||||
None => return Ok(()),
|
||||
Some(seq_range) => {
|
||||
let (Some(first), Some(last)) = (self.first_sequence(), self.last_sequence())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let is_subset = match seq_range {
|
||||
SequenceRange::Gt { min } => min < first,
|
||||
SequenceRange::LtEq { max } => max >= last,
|
||||
SequenceRange::GtLtEq { min, max } => min < first && max >= last,
|
||||
};
|
||||
if is_subset {
|
||||
return Ok(());
|
||||
}
|
||||
seq_range
|
||||
}
|
||||
match sequence {
|
||||
None => Ok(()),
|
||||
Some(seq_range) => self.filter_by_sequence_range(seq_range),
|
||||
}
|
||||
}
|
||||
|
||||
/// Filters rows by the cursor of the piece each row belongs to.
|
||||
///
|
||||
/// One [`Batch`] of a time-series memtable holds one series, so every row of it belongs
|
||||
/// to the same piece and the piece is resolved once for the whole batch: the partition
|
||||
/// expression of each candidate slice is evaluated against the batch's primary-key (tag)
|
||||
/// values, and the rows are kept when their own sequence is above that slice's cursor and
|
||||
/// at or below `min(read_fence, until)`, where `read_fence` is the upper end of the read's
|
||||
/// own sequence range ([`Self::filter_by_sequence`]) and `until` is the last sequence the
|
||||
/// piece's delta covers. This is the memtable counterpart of the per-row slice selection
|
||||
/// of a physical-sequence read of an SST: a region whose pieces advanced independently
|
||||
/// delivers neither a row a more advanced piece consumed again nor drops a row a less
|
||||
/// advanced one still holds, and a row numbered above its own piece's bound is left to the
|
||||
/// delta that covers it.
|
||||
///
|
||||
/// A batch whose piece **cannot be resolved** is decided by
|
||||
/// [`Self::unresolved_creator_cursor`]: the least advanced cursor is exact when every
|
||||
/// candidate carries it, and the read fails otherwise, because that floor re-delivers
|
||||
/// the rows a more advanced piece has already consumed.
|
||||
///
|
||||
/// `None` or an empty set applies no filter, and a set whose cursors and bounds all agree
|
||||
/// needs no evaluation at all — they are the region's floor and ceiling, and the outcome is
|
||||
/// exactly [`Self::filter_by_sequence`] with them.
|
||||
pub fn filter_by_creator_slices(
|
||||
&mut self,
|
||||
slices: Option<&[CreatorSliceCursor]>,
|
||||
read_fence: Option<SequenceNumber>,
|
||||
metadata: &RegionMetadataRef,
|
||||
codec: Option<&dyn PrimaryKeyCodec>,
|
||||
) -> Result<()> {
|
||||
let Some(slices) = slices.filter(|slices| !slices.is_empty()) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(&(_, first, first_until)) = slices.first() else {
|
||||
return Ok(());
|
||||
};
|
||||
// One cursor value and one bound for every piece is the rule of the region: which
|
||||
// piece a row belongs to cannot change the outcome, so the batch needs no evaluation.
|
||||
let (cursor, until) = if slices
|
||||
.iter()
|
||||
.all(|(_, seq, until)| *seq == first && *until == first_until)
|
||||
{
|
||||
(first, first_until)
|
||||
} else {
|
||||
self.creator_slice_cursor(slices, metadata, codec)?
|
||||
};
|
||||
|
||||
self.filter_by_sequence_range(creator_slice_sequence_range(cursor, until, read_fence))
|
||||
}
|
||||
|
||||
/// Returns the cursor and the upper bound of the piece the rows of `self` belong to, or
|
||||
/// the floor the batch must be bounded by when the piece cannot be resolved
|
||||
/// ([`Self::unresolved_creator_cursor`]).
|
||||
///
|
||||
/// The candidate expressions are the pieces a row may belong to; they are disjoint, so
|
||||
/// at most one of them selects a series. If more than one does (a domain that was not
|
||||
/// split cleanly), the least advanced cursor among them is used — it never drops a row a
|
||||
/// conservatively bounded read would have delivered — together with the least upper bound
|
||||
/// among them, the only bound every one of the matching pieces proves.
|
||||
fn creator_slice_cursor(
|
||||
&self,
|
||||
slices: &[CreatorSliceCursor],
|
||||
metadata: &RegionMetadataRef,
|
||||
codec: Option<&dyn PrimaryKeyCodec>,
|
||||
) -> Result<(SequenceNumber, Option<SequenceNumber>)> {
|
||||
let Some(codec) = codec else {
|
||||
// Without a primary key the pieces cannot be told apart.
|
||||
return Self::unresolved_creator_cursor(
|
||||
metadata,
|
||||
slices,
|
||||
"the batch states no primary key codec, so its tag values are unknown",
|
||||
);
|
||||
};
|
||||
let pk_values = match self.pk_values() {
|
||||
Some(pk_values) => Cow::Borrowed(pk_values),
|
||||
None => match codec.decode(self.primary_key()) {
|
||||
Ok(pk_values) => Cow::Owned(pk_values),
|
||||
Err(e) => {
|
||||
return Self::unresolved_creator_cursor(
|
||||
metadata,
|
||||
slices,
|
||||
&format!("the primary key of the batch cannot be decoded: {e}"),
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
let Some(probe) = creator_slice_probe_batch(metadata, slices, &pk_values) else {
|
||||
return Self::unresolved_creator_cursor(
|
||||
metadata,
|
||||
slices,
|
||||
"the probe batch of the series' tag values cannot be built: a slice expression \
|
||||
references a column that is not part of this region's primary key, or a value \
|
||||
does not convert to the column's type",
|
||||
);
|
||||
};
|
||||
|
||||
let mut matched: Option<(SequenceNumber, Option<SequenceNumber>)> = None;
|
||||
for (expr, cursor, until) in slices {
|
||||
let selected = match expr.try_as_physical_expr(&probe.schema()) {
|
||||
Ok(filter) => match evaluate_partition_filter(filter.as_ref(), &probe) {
|
||||
Ok(selected) => selected,
|
||||
Err(e) => {
|
||||
return Self::unresolved_creator_cursor(
|
||||
metadata,
|
||||
slices,
|
||||
&format!("a slice expression cannot be evaluated: {e}"),
|
||||
);
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
return Self::unresolved_creator_cursor(
|
||||
metadata,
|
||||
slices,
|
||||
&format!("a slice expression cannot be planned: {e}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
if selected {
|
||||
// Disjoint expressions match at most once; a domain that was not split
|
||||
// cleanly is bounded by its least advanced piece, in both ends.
|
||||
matched = Some(match matched {
|
||||
None => (*cursor, *until),
|
||||
Some((cursor_now, until_now)) => {
|
||||
(cursor_now.min(*cursor), least_until(until_now, *until))
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
match matched {
|
||||
Some(matched) => Ok(matched),
|
||||
None => Self::unresolved_creator_cursor(
|
||||
metadata,
|
||||
slices,
|
||||
"no candidate expression selects the series of the batch",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The floor to bound a batch by when the piece its rows belong to cannot be resolved.
|
||||
///
|
||||
/// One rule decides every such case. When the candidate slices of the region all carry
|
||||
/// the **same** cursor value, that value is the least advanced one and bounding the batch
|
||||
/// by it delivers exactly the rows the per-piece rule delivers: the floor stays, silent
|
||||
/// and without any evaluation of its own. The upper end is then the least bound the
|
||||
/// candidates state, the only one every candidate proves — a candidate that states none is
|
||||
/// unbounded above and narrows nothing. When they carry several cursor values, the least
|
||||
/// advanced one is not exact — it delivers the rows a more advanced piece has already
|
||||
/// consumed, so the batch would be *duplicated*, not merely replayed — and an exact read
|
||||
/// must not degrade that way without saying so, so the read fails with
|
||||
/// [`crate::error::Error::SequenceRangeUnsupported`].
|
||||
fn unresolved_creator_cursor(
|
||||
metadata: &RegionMetadataRef,
|
||||
slices: &[CreatorSliceCursor],
|
||||
detail: &str,
|
||||
) -> Result<(SequenceNumber, Option<SequenceNumber>)> {
|
||||
let (min, max) = creator_cursor_range(slices);
|
||||
let until = least_slice_until(slices.iter().map(|(_, _, until)| until));
|
||||
debug!(
|
||||
"Cannot resolve the creator cursor slice of a batch of region {} (candidate cursors {}..={}), detail: {}",
|
||||
metadata.region_id, min, max, detail
|
||||
);
|
||||
if min == max {
|
||||
return Ok((min, until));
|
||||
}
|
||||
SequenceRangeUnsupportedSnafu {
|
||||
region_id: metadata.region_id,
|
||||
min_seq: min,
|
||||
max_seq: max,
|
||||
reason: format!(
|
||||
"the per-piece cursor of a time-series memtable batch of region {} cannot be \
|
||||
resolved while the pieces of the region disagree on the last consumed \
|
||||
sequence ({}..={}): bounding the batch by the least advanced cursor {} would \
|
||||
deliver the rows a more advanced piece has already consumed. {}",
|
||||
metadata.region_id, min, max, min, detail
|
||||
),
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
|
||||
/// Applies `seq_range` to the rows of the batch, skipping the mask when every row
|
||||
/// already satisfies it.
|
||||
fn filter_by_sequence_range(&mut self, seq_range: SequenceRange) -> Result<()> {
|
||||
let (Some(first), Some(last)) = (self.first_sequence(), self.last_sequence()) else {
|
||||
return Ok(());
|
||||
};
|
||||
let is_subset = match seq_range {
|
||||
SequenceRange::Gt { min } => min < first,
|
||||
SequenceRange::LtEq { max } => max >= last,
|
||||
SequenceRange::GtLtEq { min, max } => min < first && max >= last,
|
||||
};
|
||||
if is_subset {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let seqs = self.sequences.as_arrow();
|
||||
let predicate = seq_range.filter(seqs).context(ComputeArrowSnafu)?;
|
||||
|
||||
@@ -33,7 +33,7 @@ use datatypes::value::scalar_value_to_timestamp;
|
||||
#[cfg(any(test, feature = "test"))]
|
||||
use futures::TryStreamExt;
|
||||
use store_api::region_engine::PartitionRange;
|
||||
use store_api::storage::{FileId, RegionId, SequenceRange, TimeSeriesRowSelector};
|
||||
use store_api::storage::{FileId, RegionId, SequenceNumber, SequenceRange, TimeSeriesRowSelector};
|
||||
use table::predicate::is_string_timestamp_literal;
|
||||
|
||||
use crate::cache::CacheStrategy;
|
||||
@@ -47,6 +47,7 @@ use crate::read::read_columns::ReadColumns;
|
||||
use crate::read::scan_region::StreamContext;
|
||||
use crate::read::scan_util::PartitionMetrics;
|
||||
use crate::read::series_reader::SeriesRange;
|
||||
use crate::read::substituted_rows::ForeignFileRowCreators;
|
||||
use crate::region::options::MergeMode;
|
||||
#[cfg(any(test, feature = "test"))]
|
||||
use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE;
|
||||
@@ -138,6 +139,24 @@ impl ScanRequestFingerprintBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/// One candidate creator cursor slice of a file, as the range-cache key records it.
|
||||
///
|
||||
/// A physical-sequence read decides each row of the file by the cursor of the slice that
|
||||
/// selects it, and bounds the whole file by the least advanced cursor and the least upper bound
|
||||
/// of the same candidates. Both outcomes depend on the candidate set, which the file itself
|
||||
/// does not state: after a piece cursor advances or an `until` changes, the same files under
|
||||
/// the same region-level `(C, H]` deliver different rows.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct CreatorCursorSlice {
|
||||
/// Identity of the slice's partition expression (`None` = the whole value domain).
|
||||
pub(crate) partition_expr: Option<String>,
|
||||
/// Last sequence consumed in the slice's domain (exclusive lower bound).
|
||||
pub(crate) cursor: SequenceNumber,
|
||||
/// Last sequence the read's delta covers in that domain
|
||||
/// ([`CursorShard::until`](store_api::storage::CursorShard::until)).
|
||||
pub(crate) until: Option<SequenceNumber>,
|
||||
}
|
||||
|
||||
/// Inputs affecting a file read's output.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
struct FileReadFingerprint {
|
||||
@@ -147,6 +166,14 @@ struct FileReadFingerprint {
|
||||
preserve_row_sequence: bool,
|
||||
snapshot_sequence: Option<u64>,
|
||||
pre_filter_mode: PreFilterMode,
|
||||
/// Whether this read keeps the file's own `__sequence` and splits its rows by creator
|
||||
/// cursor slices (`ScanInput::read_row_sequence`), instead of virtualizing the sequence at
|
||||
/// the file's admission barrier.
|
||||
read_row_sequence: bool,
|
||||
/// The candidate creator cursor slices this read decides the file's rows by, in a stable
|
||||
/// order; `None` when it applies no per-piece rule to the file
|
||||
/// (`ScanInput::creator_cursor_slices`).
|
||||
creator_slices: Option<Arc<Vec<CreatorCursorSlice>>>,
|
||||
}
|
||||
|
||||
/// Non-copiable struct of the fingerprint.
|
||||
@@ -235,6 +262,19 @@ impl ScanRequestFingerprint {
|
||||
+ self.file_reads.as_ref().map_or(0, |files| {
|
||||
mem::size_of::<Vec<FileReadFingerprint>>()
|
||||
+ files.capacity() * mem::size_of::<FileReadFingerprint>()
|
||||
+ files
|
||||
.iter()
|
||||
.filter_map(|file| file.creator_slices.as_ref())
|
||||
.map(|slices| {
|
||||
mem::size_of::<Vec<CreatorCursorSlice>>()
|
||||
+ slices.capacity() * mem::size_of::<CreatorCursorSlice>()
|
||||
+ slices
|
||||
.iter()
|
||||
.filter_map(|slice| slice.partition_expr.as_ref())
|
||||
.map(String::capacity)
|
||||
.sum::<usize>()
|
||||
})
|
||||
.sum::<usize>()
|
||||
})
|
||||
+ self.inner.read_columns.estimated_size()
|
||||
+ self.inner.read_column_types.capacity() * mem::size_of::<Option<ConcreteDataType>>()
|
||||
@@ -523,6 +563,13 @@ fn build_range_cache_key_inner(
|
||||
}
|
||||
let handle = stream_ctx.input.file_from_index(*index);
|
||||
let file = handle.meta_ref();
|
||||
// The per-piece rule of a physical-sequence read decides this file's rows from a set
|
||||
// the file itself does not state (`ScanInput::creator_cursor_slices`), so a result
|
||||
// built under one set must never be replayed under another. A set that cannot be
|
||||
// stated makes the range uncacheable; the read itself reports the same failure.
|
||||
let Ok(creator_slices) = stream_ctx.input.creator_cursor_slices(handle) else {
|
||||
return None;
|
||||
};
|
||||
files.push((
|
||||
(handle.file_id().file_id(), index.row_group_index),
|
||||
FileReadFingerprint {
|
||||
@@ -535,6 +582,8 @@ fn build_range_cache_key_inner(
|
||||
|| stream_ctx.range_pre_filter_mode(part_range),
|
||||
|pruner| pruner.pre_filter_mode(index.index - stream_ctx.input.num_memtables()),
|
||||
),
|
||||
read_row_sequence: stream_ctx.input.read_row_sequence,
|
||||
creator_slices,
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -647,6 +696,7 @@ impl CachedRangeReader<'_> {
|
||||
self.metrics,
|
||||
files,
|
||||
scope,
|
||||
self.stream_ctx.input.foreign_file_row_creators(),
|
||||
build,
|
||||
)
|
||||
.await
|
||||
@@ -689,7 +739,7 @@ where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Result<(BoxedRecordBatchStream, usize)>>,
|
||||
{
|
||||
load_shared_range(strategy, key, part_metrics, Vec::new(), scope, build).await
|
||||
load_shared_range(strategy, key, part_metrics, Vec::new(), scope, None, build).await
|
||||
}
|
||||
|
||||
async fn load_shared_range<F, Fut>(
|
||||
@@ -698,6 +748,7 @@ async fn load_shared_range<F, Fut>(
|
||||
part_metrics: &PartitionMetrics,
|
||||
files: Vec<crate::sst::file::FileHandle>,
|
||||
scope: RangeCacheScope,
|
||||
replay_evidence: Option<&ForeignFileRowCreators>,
|
||||
build: F,
|
||||
) -> Result<(BoxedRecordBatchStream, usize)>
|
||||
where
|
||||
@@ -713,6 +764,7 @@ where
|
||||
part_metrics.range_cache_metrics_reporter(),
|
||||
files,
|
||||
scope,
|
||||
replay_evidence,
|
||||
build,
|
||||
)
|
||||
.await
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1622,23 +1622,42 @@ pub fn build_flat_file_range_scan_stream(
|
||||
.substituted_sequence_cut(range.file_handle())
|
||||
.map(|cut| (cut, windows))
|
||||
});
|
||||
let file_sequence_trusted = range
|
||||
.file_handle()
|
||||
.is_effective_target_sequence_trusted(stream_ctx.input.region_metadata().region_id)
|
||||
// A local file whose marker is unset is attributable above its substituted cut,
|
||||
// which is applied just below.
|
||||
|| substituted_cut.is_some();
|
||||
// Which rows of this file this round has already consumed: whichever region
|
||||
// allocated a row's number decides, through the cursor of the piece the row
|
||||
// belongs to (with or without the cut above). Only a file whose region states no
|
||||
// cursor this scan can use falls back to the scan's own `(C, H]`, which bounds a
|
||||
// local file's numbering, and fails closed for a foreign one.
|
||||
let (file_sequence_range, file_sequence_trusted) =
|
||||
match stream_ctx.input.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, which was applied just above.
|
||||
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. Local files are
|
||||
// reported too, so a region's own slices stay observable after compaction rewrote
|
||||
// adopted rows into local ones.
|
||||
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.
|
||||
// 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,
|
||||
)?
|
||||
let Some(record_batch) =
|
||||
filter_flat_batch_by_substituted_sequence(record_batch, Some(cut), windows)?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
@@ -1648,12 +1667,24 @@ pub fn build_flat_file_range_scan_stream(
|
||||
};
|
||||
let Some(record_batch) = filter_flat_batch_by_sequence(
|
||||
record_batch,
|
||||
stream_ctx.input.sequence_range,
|
||||
file_sequence_range,
|
||||
file_sequence_trusted,
|
||||
)? else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Evidence for the caller: rows of a file another region created are reaching
|
||||
// this read's output. Recorded after this region's own row filters, so a file
|
||||
// opened, pruned or filtered down to nothing is not reported; a later stage of
|
||||
// the same query may still drop these rows, which makes the answer an
|
||||
// over-approximation rather than a claim about the final result.
|
||||
if let Some(creators) = stream_ctx.input.foreign_file_row_creators()
|
||||
&& record_batch.num_rows() > 0
|
||||
&& stream_ctx.input.is_foreign_file(range.file_handle())
|
||||
{
|
||||
creators.record(range.file_handle().meta_ref().region_id.as_u64());
|
||||
}
|
||||
|
||||
if let Some(flat_compat) = may_compat {
|
||||
let batch = flat_compat.compat(record_batch)?;
|
||||
yield batch;
|
||||
|
||||
@@ -30,7 +30,8 @@ use futures::{StreamExt, TryStreamExt};
|
||||
use snafu::ensure;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::region_engine::{
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScanSnapshotIdentity,
|
||||
ScannerProperties,
|
||||
};
|
||||
use store_api::storage::TimeSeriesRowSelector;
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -419,11 +420,15 @@ impl SeqScan {
|
||||
input.mapper.output_schema(),
|
||||
Box::pin(record_batch_stream),
|
||||
));
|
||||
// The rows this scan hid (a physical-sequence read only) travel with the result, so the
|
||||
// caller learns which time windows it has to recompute.
|
||||
// The rows this scan hid, the slices it read (both a physical-sequence read only) and
|
||||
// the other regions' files it delivered rows from travel with the result, so the
|
||||
// caller learns which windows it has to recompute, which cursor slices it consumed
|
||||
// and which adopted files reached its output.
|
||||
Ok(SubstitutedRowRangesStream::wrap(
|
||||
stream,
|
||||
input.substituted_row_ranges_ref(),
|
||||
input.observed_slices_ref(),
|
||||
input.foreign_file_row_creators_ref(),
|
||||
input.region_metadata().region_id.as_u64(),
|
||||
))
|
||||
}
|
||||
@@ -671,8 +676,8 @@ impl RegionScanner for SeqScan {
|
||||
self.properties.set_query_load_region_id(region_id);
|
||||
}
|
||||
|
||||
fn snapshot_sequence(&self) -> Option<u64> {
|
||||
self.stream_ctx.input.snapshot_sequence
|
||||
fn snapshot_identity(&self) -> Option<ScanSnapshotIdentity> {
|
||||
Some(self.stream_ctx.input.snapshot_identity())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -51,7 +51,7 @@ use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::metric_engine_consts::is_metric_engine_internal_column;
|
||||
use store_api::region_engine::{
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RawLabelSource, RegionScanner,
|
||||
ScannerProperties, SendableRawSeriesStream,
|
||||
ScanSnapshotIdentity, ScannerProperties, SendableRawSeriesStream,
|
||||
};
|
||||
use store_api::storage::consts::{ReservedColumnId, is_internal_column};
|
||||
use table::predicate::Predicate;
|
||||
@@ -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(
|
||||
@@ -1189,8 +1193,8 @@ impl RegionScanner for SeriesScan {
|
||||
self.properties.set_query_load_region_id(region_id);
|
||||
}
|
||||
|
||||
fn snapshot_sequence(&self) -> Option<u64> {
|
||||
self.stream_ctx.input.snapshot_sequence
|
||||
fn snapshot_identity(&self) -> Option<ScanSnapshotIdentity> {
|
||||
Some(self.stream_ctx.input.snapshot_identity())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,13 +17,20 @@
|
||||
//! A physical-sequence read (`ScanRequest::read_row_sequence`) 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 records
|
||||
//! the timestamps of the dropped rows here, so the caller recomputes those windows.
|
||||
//! the timestamps of the dropped rows here, so the caller recomputes those windows. The same
|
||||
//! read records which `(region, partition expression)` pairs it read
|
||||
//! ([`ObservedPartitionExprs`]). Every read — physical-sequence or full — records which other
|
||||
//! regions' files it delivered rows from ([`ForeignFileRowCreators`]).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use common_recordbatch::adapter::{RecordBatchMetrics, SubstitutedRange, SubstitutedRowRanges};
|
||||
use common_recordbatch::adapter::{
|
||||
ObservedPartitionExpr, RecordBatchMetrics, SubstitutedRange, SubstitutedRowRanges,
|
||||
};
|
||||
use common_recordbatch::{OrderOption, RecordBatchStream, SendableRecordBatchStream};
|
||||
use common_time::Timestamp;
|
||||
use common_time::timestamp::TimeUnit;
|
||||
@@ -32,10 +39,11 @@ 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};
|
||||
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};
|
||||
|
||||
@@ -99,6 +107,120 @@ impl SubstitutedRowsAccumulator {
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates the partition expressions of the regions a physical-sequence read observed, one
|
||||
/// [`ObservedPartitionExpr`] per `(region, partition expression)` pair.
|
||||
///
|
||||
/// Shared by every reader of one scan and deduplicated on insert.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ObservedPartitionExprs {
|
||||
slices: Mutex<BTreeSet<ObservedPartitionExpr>>,
|
||||
}
|
||||
|
||||
pub(crate) type ObservedPartitionExprsRef = Arc<ObservedPartitionExprs>;
|
||||
|
||||
impl ObservedPartitionExprs {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Records that rows of `(region_id, partition_expr)` were read.
|
||||
///
|
||||
/// The expression is stored as its canonical identity (`PartitionExpr::as_json_str()`),
|
||||
/// which is the form a cursor entry carries. `None` is the region's complete value domain.
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates the creator regions of the adopted files this scan delivered rows from, i.e.
|
||||
/// the regions that created a file whose rows reached this scan's output.
|
||||
///
|
||||
/// Shared by every reader of one scan and deduplicated on insert.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ForeignFileRowCreators {
|
||||
creators: Mutex<BTreeSet<u64>>,
|
||||
/// Set when rows reached this scan's output without passing a reader that records them,
|
||||
/// so the recorded set does not describe everything the scan delivered.
|
||||
replay_unknown: AtomicBool,
|
||||
}
|
||||
|
||||
pub(crate) type ForeignFileRowCreatorsRef = Arc<ForeignFileRowCreators>;
|
||||
|
||||
impl ForeignFileRowCreators {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Records that at least one row of a file `creator_region_id` created survived this
|
||||
/// region's own row filters and entered the scan's output.
|
||||
///
|
||||
/// The evidence is reported per creator region rather than per file because a caller can
|
||||
/// only act on the creator: the numbers in the row are the creator's, and it is the
|
||||
/// creator's watermark that has to cover them.
|
||||
pub(crate) fn record(&self, creator_region_id: u64) {
|
||||
// A poisoned lock cannot leave the set inconsistent (an insert is the only
|
||||
// mutation), so it is recovered instead of failing the scan.
|
||||
self.creators
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.insert(creator_region_id);
|
||||
}
|
||||
|
||||
/// Records that this scan delivered rows this accumulator cannot speak for, so its answer
|
||||
/// is unknown instead of "delivered none".
|
||||
///
|
||||
/// A range result replayed from the range cache, or read from a range another scan's
|
||||
/// source produced, was decoded by a reader of that other scan: no file of this scan's
|
||||
/// read was opened, so nothing here names the creators of the rows it delivered. The rows
|
||||
/// are real, and a consumer must not hear that none of them came from another region.
|
||||
pub(crate) fn record_replay_unknown(&self) {
|
||||
self.replay_unknown.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Returns the recorded creator regions, sorted and deduplicated.
|
||||
pub(crate) fn entries(&self) -> Vec<u64> {
|
||||
self.creators
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.iter()
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns the answer this scan states: the creator regions whose rows it delivered, or
|
||||
/// `None` when it cannot say which those were.
|
||||
pub(crate) fn answer(&self) -> Option<Vec<u64>> {
|
||||
if self.replay_unknown.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
Some(self.entries())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -207,7 +329,8 @@ fn to_time_unit(unit: datatypes::arrow::datatypes::TimeUnit) -> TimeUnit {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a scan stream so its terminal metrics carry what the scan substituted.
|
||||
/// Wraps a scan stream so its terminal metrics carry what the scan substituted and read, and
|
||||
/// which adopted files it delivered rows from.
|
||||
///
|
||||
/// 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
|
||||
@@ -215,22 +338,28 @@ fn to_time_unit(unit: datatypes::arrow::datatypes::TimeUnit) -> TimeUnit {
|
||||
pub(crate) struct SubstitutedRowRangesStream {
|
||||
stream: SendableRecordBatchStream,
|
||||
ranges: Option<SubstitutedRowsAccumulatorRef>,
|
||||
observed_slices: Option<ObservedPartitionExprsRef>,
|
||||
foreign_file_row_creators: Option<ForeignFileRowCreatorsRef>,
|
||||
region_id: u64,
|
||||
}
|
||||
|
||||
impl SubstitutedRowRangesStream {
|
||||
/// Wraps `stream`, or returns it unchanged when the scan reports no range.
|
||||
/// Wraps `stream`, or returns it unchanged when the scan reports none of the three.
|
||||
pub(crate) fn wrap(
|
||||
stream: SendableRecordBatchStream,
|
||||
ranges: Option<SubstitutedRowsAccumulatorRef>,
|
||||
observed_slices: Option<ObservedPartitionExprsRef>,
|
||||
foreign_file_row_creators: Option<ForeignFileRowCreatorsRef>,
|
||||
region_id: u64,
|
||||
) -> SendableRecordBatchStream {
|
||||
if ranges.is_none() {
|
||||
if ranges.is_none() && observed_slices.is_none() && foreign_file_row_creators.is_none() {
|
||||
return stream;
|
||||
}
|
||||
Box::pin(Self {
|
||||
stream,
|
||||
ranges,
|
||||
observed_slices,
|
||||
foreign_file_row_creators,
|
||||
region_id,
|
||||
})
|
||||
}
|
||||
@@ -257,6 +386,19 @@ impl RecordBatchStream for SubstitutedRowRangesStream {
|
||||
metrics.substituted_row_ranges = substituted;
|
||||
}
|
||||
}
|
||||
if let Some(observed) = &self.observed_slices {
|
||||
let slices = observed.entries();
|
||||
if !slices.is_empty() {
|
||||
metrics.observed_slices = slices;
|
||||
}
|
||||
}
|
||||
// An answer, not an absence: this read states which adopted files it delivered rows
|
||||
// from even when that is none, so the caller can tell "delivered none" from the
|
||||
// unknown an earlier build's payload states. A read that replayed a range states
|
||||
// nothing, because it did not open the files that produced the rows.
|
||||
if let Some(creators) = &self.foreign_file_row_creators {
|
||||
metrics.foreign_file_row_creators = creators.answer();
|
||||
}
|
||||
Some(metrics)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ use futures::{Stream, StreamExt};
|
||||
use snafu::ensure;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::region_engine::{
|
||||
PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
|
||||
PrepareRequest, QueryScanContext, RegionScanner, ScanSnapshotIdentity, ScannerProperties,
|
||||
};
|
||||
|
||||
use crate::error::{PartitionOutOfRangeSnafu, Result};
|
||||
@@ -244,11 +244,15 @@ impl UnorderedScan {
|
||||
input.mapper.output_schema(),
|
||||
Box::pin(record_batch_stream),
|
||||
));
|
||||
// The rows this scan hid (a physical-sequence read only) travel with the result, so the
|
||||
// caller learns which time windows it has to recompute.
|
||||
// The rows this scan hid, the slices it read (both a physical-sequence read only) and
|
||||
// the other regions' files it delivered rows from travel with the result, so the
|
||||
// caller learns which windows it has to recompute, which cursor slices it consumed
|
||||
// and which adopted files reached its output.
|
||||
Ok(SubstitutedRowRangesStream::wrap(
|
||||
stream,
|
||||
input.substituted_row_ranges_ref(),
|
||||
input.observed_slices_ref(),
|
||||
input.foreign_file_row_creators_ref(),
|
||||
input.region_metadata().region_id.as_u64(),
|
||||
))
|
||||
}
|
||||
@@ -390,8 +394,8 @@ impl RegionScanner for UnorderedScan {
|
||||
self.properties.set_query_load_region_id(region_id);
|
||||
}
|
||||
|
||||
fn snapshot_sequence(&self) -> Option<u64> {
|
||||
self.stream_ctx.input.snapshot_sequence
|
||||
fn snapshot_identity(&self) -> Option<ScanSnapshotIdentity> {
|
||||
Some(self.stream_ctx.input.snapshot_identity())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,14 +36,15 @@ 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;
|
||||
|
||||
use crate::cache::CacheStrategy;
|
||||
use crate::error::{
|
||||
ComputeArrowSnafu, DecodeStatsSnafu, EvalPartitionFilterSnafu, InvalidRecordBatchSnafu,
|
||||
NewRecordBatchSnafu, RecordBatchSnafu, Result, StatsNotPresentSnafu, UnexpectedSnafu,
|
||||
NewRecordBatchSnafu, RecordBatchSnafu, Result, SequenceRangeUnsupportedSnafu,
|
||||
StatsNotPresentSnafu, UnexpectedSnafu,
|
||||
};
|
||||
use crate::read::compat::FlatCompatBatch;
|
||||
use crate::read::last_row::FlatRowGroupLastRowCachedReader;
|
||||
@@ -51,7 +52,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 +593,64 @@ 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 bounded by the least advanced candidate. That bound is the
|
||||
/// row's own piece's answer only while every candidate carries it: when the candidates
|
||||
/// disagree, the read fails with
|
||||
/// [`SequenceRangeUnsupported`](crate::error::Error::SequenceRangeUnsupported) instead of
|
||||
/// delivering the rows a more advanced piece has already consumed.
|
||||
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,
|
||||
}
|
||||
|
||||
/// The least and the greatest cursor value of a candidate slice set.
|
||||
///
|
||||
/// Equal bounds mean every candidate carries the same cursor value — the only case in which
|
||||
/// [`PartitionFilterContext::fallback_cursor`] bounds a row no candidate selects exactly.
|
||||
fn creator_cursor_span(slices: &[CreatorSliceFilter]) -> (SequenceNumber, SequenceNumber) {
|
||||
let mut span: Option<(SequenceNumber, SequenceNumber)> = None;
|
||||
for slice in slices {
|
||||
span = Some(match span {
|
||||
None => (slice.cursor, slice.cursor),
|
||||
Some((min, max)) => (min.min(slice.cursor), max.max(slice.cursor)),
|
||||
});
|
||||
}
|
||||
span.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Common fields for a range to read and filter batches.
|
||||
@@ -660,14 +715,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 +965,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 +990,145 @@ 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.
|
||||
///
|
||||
/// When several candidates select one row — a domain that was not split cleanly, whose
|
||||
/// expressions overlap — the **least advanced** of their cursors decides: the row is kept
|
||||
/// when any of them has not consumed it, which is the conservative direction and the one
|
||||
/// the time-series and bulk memtable filters already take
|
||||
/// (`Batch::filter_by_creator_slices` and `creator_slice_mask`). Letting the first
|
||||
/// matching candidate decide would drop a row a less advanced piece still holds.
|
||||
///
|
||||
/// A row no slice expression selects has no piece to attribute it to, so only the least
|
||||
/// advanced candidate ([`PartitionFilterContext::fallback_cursor`]) can bound it. That
|
||||
/// bound is exact while every candidate carries the same cursor value — it then *is* the
|
||||
/// row's own piece's answer — and states nothing about the row once the candidates differ:
|
||||
/// it delivers the rows a more advanced piece has already consumed, which is a duplicate,
|
||||
/// not a replay, so the read fails with
|
||||
/// [`SequenceRangeUnsupported`](crate::error::Error::SequenceRangeUnsupported) instead.
|
||||
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;
|
||||
// The candidates' own span, resolved on the first row no candidate selects: while
|
||||
// every candidate carries the same value the fallback below is that row's answer and
|
||||
// the span is never asked for.
|
||||
let mut cursor_span: Option<(SequenceNumber, SequenceNumber)> = None;
|
||||
for row in 0..num_rows {
|
||||
// A row at or below the substituted cut is re-read on purpose by the substitution
|
||||
// rule, so no cursor decision — and no disagreement — applies to it.
|
||||
if substituted_mask
|
||||
.as_ref()
|
||||
.is_some_and(|mask| mask.value(row))
|
||||
{
|
||||
kept.append(true);
|
||||
continue;
|
||||
}
|
||||
// Disjoint slice expressions match a row at most once, which is the common case:
|
||||
// one bit test answers it. A domain that was not split cleanly can match several,
|
||||
// and their cursors may differ — the least advanced of them is the only bound that
|
||||
// is exact for every candidate, so the first match must not decide the row. The
|
||||
// memtable filters take the same minimum (`Batch::filter_by_creator_slices` and
|
||||
// the bulk `creator_slice_mask`), i.e. they OR the candidates' `not_consumed`
|
||||
// masks, which is the same row decision.
|
||||
let mut selecting = selected
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, mask)| mask.value(row));
|
||||
let keep = match selecting.next() {
|
||||
Some((first, _)) => {
|
||||
let mut least = first;
|
||||
for (index, _) in selecting {
|
||||
if slices[index].cursor < slices[least].cursor {
|
||||
least = index;
|
||||
}
|
||||
}
|
||||
not_consumed[least].value(row)
|
||||
}
|
||||
None => {
|
||||
unmatched += 1;
|
||||
let (min, max) =
|
||||
*cursor_span.get_or_insert_with(|| creator_cursor_span(slices));
|
||||
if min != max {
|
||||
let region_id = self.read_format.metadata().region_id;
|
||||
return SequenceRangeUnsupportedSnafu {
|
||||
region_id,
|
||||
min_seq: min,
|
||||
max_seq: max,
|
||||
reason: format!(
|
||||
"the physical-sequence read of a file of region {} cannot \
|
||||
resolve a per-piece cursor: {} of {} rows of the file match no \
|
||||
candidate creator cursor slice, while the candidate slices of \
|
||||
that region disagree on the last consumed sequence ({}..={}), \
|
||||
so bounding those rows by the least advanced cursor {} would \
|
||||
deliver the rows a more advanced piece has already consumed",
|
||||
region_id, unmatched, num_rows, min, max, min
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
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 {}, which every candidate carries",
|
||||
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 +1384,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 +1477,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 +1548,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
|
||||
|
||||
@@ -49,7 +49,7 @@ use partition::expr::PartitionExpr;
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef};
|
||||
use store_api::region_request::PathType;
|
||||
use store_api::storage::{ColumnId, FileId};
|
||||
use store_api::storage::{ColumnId, FileId, RegionId, SequenceNumber};
|
||||
use table::predicate::Predicate;
|
||||
|
||||
use crate::cache::index::result_cache::PredicateKey;
|
||||
@@ -58,8 +58,8 @@ use crate::cache::{
|
||||
prepare_sst_meta,
|
||||
};
|
||||
use crate::error::{
|
||||
ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result, SerializePartitionExprSnafu,
|
||||
UnexpectedSnafu,
|
||||
InvalidPartitionExprSnafu, ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result,
|
||||
SequenceRangeUnsupportedSnafu, 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,13 @@ 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.
|
||||
///
|
||||
@@ -230,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.
|
||||
@@ -268,11 +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,
|
||||
@@ -367,6 +384,30 @@ 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.
|
||||
///
|
||||
@@ -534,7 +575,13 @@ impl ParquetReaderBuilder {
|
||||
);
|
||||
}
|
||||
let file_meta = self.file_handle.meta_ref();
|
||||
let override_sequence = if self.read_row_sequence && 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 instead of the
|
||||
// substitution below. `preserve_row_sequence` takes no part: an import only
|
||||
// re-marks the handle and copies the bytes, and the file's own
|
||||
@@ -737,11 +784,62 @@ impl ParquetReaderBuilder {
|
||||
Ok((region_partition_expr, is_same))
|
||||
}
|
||||
|
||||
/// Fails when the candidate creator cursor slices of `file` disagree on the last consumed
|
||||
/// sequence, and succeeds when they all carry the same value.
|
||||
///
|
||||
/// The one caller is the per-row rule of a physical-sequence read: an identity this build
|
||||
/// cannot read back cannot be evaluated, and approximating it would decide a row's domain
|
||||
/// by guesswork, so the file is left with its file-level bound — the least advanced
|
||||
/// candidate. That floor is exact while every candidate carries it; once they differ, it
|
||||
/// delivers the rows a more advanced piece has already consumed again, so the read fails
|
||||
/// with [`SequenceRangeUnsupported`](crate::error::Error::SequenceRangeUnsupported)
|
||||
/// instead of degrading an exact read into a duplicate.
|
||||
///
|
||||
/// The bounds the error reports are the cursors' own span, which is the disagreement the
|
||||
/// read cannot resolve.
|
||||
fn reject_disagreeing_slice_cursors(
|
||||
&self,
|
||||
file: &FileHandle,
|
||||
region_id: RegionId,
|
||||
slice_cursors: &[(String, SequenceNumber)],
|
||||
) -> Result<()> {
|
||||
let Some(min) = slice_cursors.iter().map(|(_, cursor)| *cursor).min() else {
|
||||
return Ok(());
|
||||
};
|
||||
let max = slice_cursors
|
||||
.iter()
|
||||
.map(|(_, cursor)| *cursor)
|
||||
.max()
|
||||
.unwrap_or(min);
|
||||
if min == max {
|
||||
return Ok(());
|
||||
}
|
||||
let meta = file.meta_ref();
|
||||
SequenceRangeUnsupportedSnafu {
|
||||
region_id,
|
||||
min_seq: min,
|
||||
max_seq: max,
|
||||
reason: format!(
|
||||
"the physical-sequence read of file {} of region {} cannot resolve a per-piece \
|
||||
cursor: it cannot read back the partition expression of its candidate slice, \
|
||||
while the candidate slices of that region disagree on the last consumed \
|
||||
sequence ({}..={}), so bounding the file by the least advanced cursor {} would \
|
||||
deliver the rows a more advanced piece has already consumed",
|
||||
meta.file_id, meta.region_id, min, max, min
|
||||
),
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
|
||||
/// Builds the dependency-only schema for row-level partition evaluation.
|
||||
/// Its indices are independent of both Parquet and converted batch projections;
|
||||
/// 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,
|
||||
@@ -756,17 +854,52 @@ 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. Only an
|
||||
// unresolvable piece leaves the file-level bound, and that bound is the least
|
||||
// advanced candidate: exact while every candidate carries it, a duplicate of
|
||||
// the rows a more advanced piece consumed otherwise.
|
||||
debug!(
|
||||
"Cannot read back creator cursor slice expression {}; bounding the file by its least advanced candidate",
|
||||
identity
|
||||
);
|
||||
self.reject_disagreeing_slice_cursors(
|
||||
&self.file_handle,
|
||||
read_format.metadata().region_id,
|
||||
slice_cursors,
|
||||
)?;
|
||||
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(
|
||||
@@ -797,12 +930,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,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user