Merge branch 'a-scan' into HEAD

This commit is contained in:
discord9
2026-11-27 12:16:04 +08:00
4 changed files with 636 additions and 166 deletions
+91 -1
View File
@@ -46,7 +46,9 @@ use common_grpc::flight::{
FLOW_EXTENSIONS_METADATA_KEY, FlightDecoder, FlightMessage, SNAPSHOT_SEQS_METADATA_KEY,
};
use common_query::Output;
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
use common_recordbatch::adapter::{
ObservedPartitionExpr, RecordBatchMetrics, RegionWatermarkEntry, SubstitutedRowRanges,
};
use common_recordbatch::error::ExternalSnafu;
use common_recordbatch::{OrderOption, RecordBatch, RecordBatchStream, RecordBatchStreamWrapper};
use common_telemetry::tracing::Span;
@@ -261,6 +263,37 @@ impl OutputMetrics {
.collect::<std::collections::BTreeSet<_>>(),
)
}
/// Returns the time ranges of the rows the read substituted, one entry per region,
/// ordered by region id with each region's ranges sorted and non-overlapping.
///
/// An empty list is the protocol's "substituted nothing", never "unknown": a caller
/// that recomputes the windows of substituted rows reads it as "nothing to recompute".
/// `None` means the terminal metrics themselves are not available (yet).
pub fn substituted_row_ranges(&self) -> Option<Vec<SubstitutedRowRanges>> {
Some(self.get()?.substituted_row_ranges)
}
/// Returns the `(region, partition expression)` pairs the read observed, deduplicated
/// and sorted.
///
/// This is what the owner of a `(region, slice)` cursor advances: exactly the slices the
/// read stated it read. An empty list reads as "nothing was read", and `None` as "the
/// terminal metrics are not available (yet)".
pub fn observed_slices(&self) -> Option<Vec<ObservedPartitionExpr>> {
Some(self.get()?.observed_slices)
}
/// Returns the creators of the adopted files the read **delivered rows** from.
///
/// `Some(creators)` — possibly empty — is an answer: `Some(vec![])` says the read delivered
/// no row of another region's file. `None` states nothing: either the read did not state an
/// answer (a build that predates the field, a stream that never ended, a region that never
/// reported) or the terminal metrics are not available (yet), and a consumer that must not
/// count a row above its creator's proved watermark has to read it as "could have".
pub fn foreign_file_row_creators(&self) -> Option<Vec<u64>> {
self.get()?.foreign_file_row_creators
}
}
/// Query output together with a handle for its terminal metrics.
@@ -306,6 +339,27 @@ impl OutputWithMetrics {
self.metrics.participating_regions()
}
/// Returns the time ranges of the rows the read substituted.
///
/// See [`OutputMetrics::substituted_row_ranges`].
pub fn substituted_row_ranges(&self) -> Option<Vec<SubstitutedRowRanges>> {
self.metrics.substituted_row_ranges()
}
/// Returns the `(region, partition expression)` pairs the read observed.
///
/// See [`OutputMetrics::observed_slices`].
pub fn observed_slices(&self) -> Option<Vec<ObservedPartitionExpr>> {
self.metrics.observed_slices()
}
/// Returns the creators of the adopted files the read delivered rows from.
///
/// See [`OutputMetrics::foreign_file_row_creators`].
pub fn foreign_file_row_creators(&self) -> Option<Vec<u64>> {
self.metrics.foreign_file_row_creators()
}
/// Drops the terminal metrics handle and returns the original output.
pub fn into_output(self) -> Output {
self.output
@@ -1518,6 +1572,42 @@ mod tests {
);
}
/// The three facts a scan states about its own read arrive in the terminal metrics message
/// and are read back from the handle: the ranges a read substituted and the slices it
/// observed must not arrive as "nothing" merely because they are not figures.
#[tokio::test]
async fn test_affected_rows_inline_metrics_carry_the_scan_facts() {
let ranges = vec![SubstitutedRowRanges {
region_id: 7,
ranges: vec![common_recordbatch::adapter::SubstitutedRange {
start_millis: 1_000,
end_millis: 2_000,
}],
}];
let slices = vec![ObservedPartitionExpr::new(7, Some("k0 < 10".to_string()))];
let metrics_json = serde_json::to_string(&RecordBatchMetrics {
substituted_row_ranges: ranges.clone(),
observed_slices: slices.clone(),
foreign_file_row_creators: Some(vec![9]),
..Default::default()
})
.unwrap();
let output = output_from_flight_message_stream(
"test-peer".to_string(),
futures_util::stream::iter(vec![Ok(FlightMessage::AffectedRows {
rows: 3,
metrics: Some(metrics_json),
})] as Vec<Result<FlightMessage>>),
)
.await
.unwrap();
assert_eq!(Some(ranges), output.substituted_row_ranges());
assert_eq!(Some(slices), output.observed_slices());
assert_eq!(Some(vec![9]), output.foreign_file_row_creators());
}
#[tokio::test]
async fn test_affected_rows_inline_metrics_do_not_poll_trailer() {
let metrics_json = terminal_metrics_json();
+241 -35
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{self, Display};
use std::future::Future;
use std::marker::PhantomData;
@@ -740,25 +740,39 @@ pub struct RecordBatchMetrics {
pub foreign_file_row_creators: Option<Vec<u64>>,
}
/// The terminal creator answers of one region scan's partition streams, i.e. of a plan node
/// that reads a region on several partitions of DataFusion parallelism.
/// What one region scan's partition streams stated when they ended, i.e. what a plan node that
/// reads a region on several partitions of DataFusion parallelism can answer about its own read.
///
/// Each partition's stream states, when it ends, which other regions' files it delivered rows
/// from ([`RecordBatchMetrics::foreign_file_row_creators`]). The node as a whole states an
/// answer only when every partition it planned to run ended and stated one: a partition that
/// is still running, that never ran, or that ended without an answer leaves the node's answer
/// unknown, because the partitions that did answer cover only part of the read.
/// Each partition's stream states three facts when it ends, and this node keeps them because
/// DataFusion's own metrics keep figures only: the other regions' files it delivered rows from
/// ([`RecordBatchMetrics::foreign_file_row_creators`]), the time ranges of the rows it
/// substituted ([`RecordBatchMetrics::substituted_row_ranges`]) and the
/// `(region, partition expression)` slices it read ([`RecordBatchMetrics::observed_slices`]).
/// A [`crate::RecordBatchStreamAdapter`] rebuilt from a plan's figures states none of them, so a
/// plan-level collector reads them here instead.
///
/// The three facts merge like the read they describe. The node states a creator answer only
/// when every partition it planned to run ended and stated one: a partition that is still
/// running, that never ran, or that ended without an answer leaves that answer unknown,
/// because the partitions that did answer cover only part of the read. The substituted ranges
/// and the observed slices of every partition union instead: a range or slice two partitions
/// both name is one range or slice, because it states what was substituted or read, not how
/// often, and a partition that substituted or read nothing adds nothing.
#[derive(Debug, Default)]
pub struct ForeignFileRowCreatorReports {
state: Mutex<ForeignFileRowCreatorReportsState>,
pub struct TerminalScanReports {
state: Mutex<TerminalScanReportsState>,
}
#[derive(Debug, Default)]
struct ForeignFileRowCreatorReportsState {
struct TerminalScanReportsState {
/// The partitions whose stream ended and stated an answer.
reported: BTreeSet<usize>,
/// The creator regions those partitions named.
creators: BTreeSet<u64>,
/// The row timestamp ranges those partitions substituted, per region.
substituted: BTreeMap<u64, BTreeSet<(i64, i64)>>,
/// The `(region, partition expression)` pairs those partitions read.
observed: BTreeSet<ObservedPartitionExpr>,
/// A partition ended without stating an answer, so no set of partitions can answer for
/// the node.
unknown: bool,
@@ -766,32 +780,55 @@ struct ForeignFileRowCreatorReportsState {
partitions: usize,
}
impl ForeignFileRowCreatorReports {
impl TerminalScanReports {
pub fn new() -> Self {
Self::default()
}
/// Records the answer the stream of `partition` stated when it ended, `partitions` being
/// how many partitions the node runs.
/// Records what the stream of `partition` stated when it ended, `partitions` being how many
/// partitions the node runs, and `answer` the stream's terminal metrics.
///
/// The count travels with the answer rather than with the node: a node whose partition
/// ranges are re-assigned before it runs reports the count it actually ran with, and a
/// report left by an earlier assignment only ever widens the answer, never narrows it.
pub fn record(&self, partition: usize, partitions: usize, answer: Option<Vec<u64>>) {
///
/// A stream that states no metrics at all states no answer: the node's creator answer stays
/// unknown and it adds no range or slice, because a read that stated nothing must not be
/// read as a read that substituted and observed nothing.
pub fn record(&self, partition: usize, partitions: usize, answer: Option<&RecordBatchMetrics>) {
let mut state = self.lock();
state.partitions = partitions;
match answer {
Some(creators) => {
state.reported.insert(partition);
state.creators.extend(creators);
}
let Some(answer) = answer else {
state.unknown = true;
return;
};
state.reported.insert(partition);
// Of the three facts only the creator answer can be unknown on its own: the other two
// state "nothing" by being empty.
match &answer.foreign_file_row_creators {
Some(creators) => state.creators.extend(creators.iter().copied()),
None => state.unknown = true,
}
for entry in &answer.substituted_row_ranges {
state
.substituted
.entry(entry.region_id)
.or_default()
.extend(
entry
.ranges
.iter()
.map(|range| (range.start_millis, range.end_millis)),
);
}
state
.observed
.extend(answer.observed_slices.iter().cloned());
}
/// The creators every partition reported together, or `None` when the partitions do not
/// state such an answer (yet).
pub fn answer(&self) -> Option<Vec<u64>> {
pub fn foreign_file_row_creators(&self) -> Option<Vec<u64>> {
let state = self.lock();
// A node with no partition to report from answers nothing: nothing was read, so
// "delivered none" would be a claim about a read that never happened.
@@ -801,9 +838,60 @@ impl ForeignFileRowCreatorReports {
Some(state.creators.iter().copied().collect())
}
/// The time ranges of the rows the partitions substituted, per region, or `None` when no
/// partition stated an answer (yet).
///
/// Ranges are unioned per region, so a row substituted by two partitions is reported once.
/// An answer of `Some(vec![])` says the read substituted nothing, which is what a caller
/// that recomputes the windows of substituted rows needs to tell apart from a read that has
/// not finished. A range a partition stated is reported even when another partition ended
/// without stating anything: the known windows still have to be recomputed, and dropping
/// them would read as "substituted nothing" for rows that were substituted.
pub fn substituted_row_ranges(&self) -> Option<Vec<SubstitutedRowRanges>> {
let state = self.lock();
if state.reported.is_empty() {
return None;
}
Some(
state
.substituted
.iter()
.map(|(region_id, ranges)| SubstitutedRowRanges {
region_id: *region_id,
ranges: ranges
.iter()
.map(|(start_millis, end_millis)| SubstitutedRange {
start_millis: *start_millis,
end_millis: *end_millis,
})
.collect(),
})
.collect(),
)
}
/// The `(region, partition expression)` pairs the partitions read, or `None` when no
/// partition stated an answer (yet).
///
/// Deduplicated and sorted: a slice two partitions both read is one slice, and a slice a
/// partition stated is reported even when another partition ended without stating one.
pub fn observed_slices(&self) -> Option<Vec<ObservedPartitionExpr>> {
let state = self.lock();
if state.reported.is_empty() {
return None;
}
Some(state.observed.iter().cloned().collect())
}
/// Clears every fact an earlier run stated, so a reused plan cannot report what the run
/// before it read.
pub fn reset(&self) {
*self.lock() = TerminalScanReportsState::default();
}
/// A panic while the state is held cannot leave it inconsistent (an insert is the only
/// mutation), so a poisoned lock is recovered instead of failing the caller.
fn lock(&self) -> std::sync::MutexGuard<'_, ForeignFileRowCreatorReportsState> {
fn lock(&self) -> std::sync::MutexGuard<'_, TerminalScanReportsState> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
}
@@ -2023,35 +2111,153 @@ mod test {
/// The partitions of a region scan answer together: their reports union, and a partition
/// that did not state an answer keeps the node's answer unknown.
#[test]
fn test_foreign_file_row_creator_reports_answer_for_all_partitions() {
let reports = ForeignFileRowCreatorReports::new();
assert_eq!(None, reports.answer(), "no partition reported yet");
fn test_terminal_scan_reports_answer_for_all_partitions() {
// The terminal metrics one partition states when its stream ends.
fn stated(creators: Option<Vec<u64>>) -> RecordBatchMetrics {
RecordBatchMetrics {
foreign_file_row_creators: creators,
..Default::default()
}
}
reports.record(0, 2, Some(vec![7, 9]));
let reports = TerminalScanReports::new();
assert_eq!(
None,
reports.answer(),
reports.foreign_file_row_creators(),
"no partition reported yet"
);
reports.record(0, 2, Some(&stated(Some(vec![7, 9]))));
assert_eq!(
None,
reports.foreign_file_row_creators(),
"one partition answered and another has not"
);
reports.record(1, 2, Some(vec![9]));
reports.record(1, 2, Some(&stated(Some(vec![9]))));
assert_eq!(
Some(vec![7, 9]),
reports.answer(),
reports.foreign_file_row_creators(),
"the delivered creators are the union of what the partitions reported"
);
// A partition that ended without an answer covers part of the read, so no set of
// reported partitions can answer for the node.
let reports = ForeignFileRowCreatorReports::new();
reports.record(0, 2, Some(vec![7]));
let reports = TerminalScanReports::new();
reports.record(0, 2, Some(&stated(Some(vec![7]))));
reports.record(1, 2, None);
assert_eq!(None, reports.answer());
assert_eq!(None, reports.foreign_file_row_creators());
// An answer of "delivered none" from every partition is still an answer.
let reports = ForeignFileRowCreatorReports::new();
reports.record(0, 1, Some(vec![]));
assert_eq!(Some(vec![]), reports.answer());
let reports = TerminalScanReports::new();
reports.record(0, 1, Some(&stated(Some(vec![]))));
assert_eq!(Some(vec![]), reports.foreign_file_row_creators());
}
/// The substituted ranges and the observed slices union across partitions, and a reset
/// leaves nothing a later run could mistake for its own read.
#[test]
fn test_terminal_scan_reports_merge_ranges_and_slices_and_reset() {
let reports = TerminalScanReports::new();
assert_eq!(None, reports.substituted_row_ranges());
assert_eq!(None, reports.observed_slices());
let first = RecordBatchMetrics {
foreign_file_row_creators: Some(vec![]),
substituted_row_ranges: vec![SubstitutedRowRanges {
region_id: 7,
ranges: vec![SubstitutedRange {
start_millis: 10,
end_millis: 20,
}],
}],
observed_slices: vec![ObservedPartitionExpr::whole_domain(7)],
..Default::default()
};
let second = RecordBatchMetrics {
foreign_file_row_creators: Some(vec![]),
substituted_row_ranges: vec![
// The same range one more partition substituted is one range.
SubstitutedRowRanges {
region_id: 7,
ranges: vec![SubstitutedRange {
start_millis: 10,
end_millis: 20,
}],
},
SubstitutedRowRanges {
region_id: 8,
ranges: vec![SubstitutedRange {
start_millis: 30,
end_millis: 40,
}],
},
],
observed_slices: vec![
ObservedPartitionExpr::whole_domain(7),
ObservedPartitionExpr::new(8, Some("k0 < 10".to_string())),
],
..Default::default()
};
reports.record(0, 2, Some(&first));
reports.record(1, 2, Some(&second));
assert_eq!(
Some(vec![
SubstitutedRowRanges {
region_id: 7,
ranges: vec![SubstitutedRange {
start_millis: 10,
end_millis: 20,
}],
},
SubstitutedRowRanges {
region_id: 8,
ranges: vec![SubstitutedRange {
start_millis: 30,
end_millis: 40,
}],
},
]),
reports.substituted_row_ranges()
);
assert_eq!(
Some(vec![
ObservedPartitionExpr::whole_domain(7),
ObservedPartitionExpr::new(8, Some("k0 < 10".to_string())),
]),
reports.observed_slices()
);
reports.reset();
assert_eq!(None, reports.foreign_file_row_creators());
assert_eq!(None, reports.substituted_row_ranges());
assert_eq!(None, reports.observed_slices());
// A partition that states ranges without a creator answer still states its ranges: only
// the creator answer becomes unknown, because only it has an "unknown" of its own.
let ranges_only = RecordBatchMetrics {
substituted_row_ranges: first.substituted_row_ranges.clone(),
..Default::default()
};
let reports = TerminalScanReports::new();
reports.record(0, 1, Some(&ranges_only));
assert_eq!(
Some(vec![SubstitutedRowRanges {
region_id: 7,
ranges: vec![SubstitutedRange {
start_millis: 10,
end_millis: 20,
}],
}]),
reports.substituted_row_ranges()
);
assert_eq!(
None,
reports.foreign_file_row_creators(),
"no creator answer was stated, so that one is unknown"
);
}
/// An affirmative answer of "delivered none" is written as an empty array and read back as
+243 -101
View File
@@ -31,7 +31,7 @@ use lazy_static::lazy_static;
use prometheus::*;
use session::context::QueryContextRef;
use table::table::scan::RegionScanExec;
use table::table::scan::{RegionScanExec, SeriesScanExec};
use crate::dist_plan::MergeScanExec;
use crate::error::Result;
@@ -340,12 +340,25 @@ fn collect_region_watermarks(plan: Arc<dyn ExecutionPlan>) -> Vec<RegionWatermar
finalize_region_watermarks(merged)
}
/// The region scan a plan node reads a region through: the node itself, or the native
/// raw-series leaf that packs one and reads through it.
///
/// Such a scan states what it read through its own report rather than through its stream, so
/// every collector of those facts has to find it the same way.
fn region_scan_of(plan: &Arc<dyn ExecutionPlan>) -> Option<&RegionScanExec> {
if let Some(region_scan) = plan.downcast_ref::<RegionScanExec>() {
return Some(region_scan);
}
plan.downcast_ref::<SeriesScanExec>()
.map(SeriesScanExec::region_scan)
}
/// Collects the time ranges of the rows the plan's region scans substituted.
///
/// `own` carries the ranges of the stream that already reported them (a local region
/// scan in standalone mode), and every merge-scan sub-stage contributes the ranges of
/// its own regions. Ranges are unioned per region, so a row substituted by two branches
/// is reported once.
/// `own` carries the ranges of the stream that already reported them, a local region scan
/// contributes what its partition streams stated when they ended, and every merge-scan
/// sub-stage contributes the ranges of its own regions. Ranges are unioned per region, so a row
/// substituted by two branches is reported once.
fn collect_substituted_row_ranges(
plan: Arc<dyn ExecutionPlan>,
own: &RecordBatchMetrics,
@@ -366,6 +379,15 @@ fn collect_substituted_row_ranges(
let mut stack = vec![plan];
while let Some(plan) = stack.pop() {
// A scan that ran in this process keeps the ranges its partition streams stated when
// they ended. Its stream cannot carry them here: a `RecordBatchMetrics` rebuilt from a
// plan's figures holds numbers, so a range list that crossed that boundary would read
// as "substituted nothing".
if let Some(region_scan) = region_scan_of(&plan)
&& let Some(ranges) = region_scan.substituted_row_ranges()
{
merge(ranges);
}
if let Some(merge_scan) = plan.downcast_ref::<MergeScanExec>()
&& !merge_scan.is_flow_sink_scan()
{
@@ -393,10 +415,10 @@ fn collect_substituted_row_ranges(
/// Collects the `(region, partition expression)` pairs the plan's region scans read.
///
/// `own` carries the slices of the stream that already reported them (a local region scan
/// in standalone mode), and every merge-scan sub-stage contributes the slices of its own
/// regions. A slice reported by two branches is one slice, because it states what was read,
/// not how often.
/// `own` carries the slices of the stream that already reported them, a local region scan
/// contributes what its partition streams stated when they ended, and every merge-scan
/// sub-stage contributes the slices of its own regions. A slice reported by two branches is one
/// slice, because it states what was read, not how often.
fn collect_observed_slices(
plan: Arc<dyn ExecutionPlan>,
own: &RecordBatchMetrics,
@@ -406,6 +428,13 @@ fn collect_observed_slices(
let mut stack = vec![plan];
while let Some(plan) = stack.pop() {
// Same as the substituted ranges: the slices a scan observed are a statement about its
// read, not a figure, so they are read from the scan rather than from its stream.
if let Some(region_scan) = region_scan_of(&plan)
&& let Some(slices) = region_scan.observed_slices()
{
merged.extend(slices);
}
if let Some(merge_scan) = plan.downcast_ref::<MergeScanExec>()
&& !merge_scan.is_flow_sink_scan()
{
@@ -451,7 +480,7 @@ fn collect_foreign_file_row_creators(
// is the only source of it once the stream of a plan that ran in this process is
// rebuilt from the plan's figures. Its silence is a scan that did not report, so it
// latches the answer unknown.
if let Some(region_scan) = plan.downcast_ref::<RegionScanExec>() {
if let Some(region_scan) = region_scan_of(&plan) {
let creators = region_scan.foreign_file_row_creators();
merge_foreign_file_row_creators(
creators.as_deref(),
@@ -464,6 +493,12 @@ fn collect_foreign_file_row_creators(
&& !merge_scan.is_flow_sink_scan()
{
let sub_stage_metrics = merge_scan.sub_stage_metrics();
// A merge scan with no region to read states "delivered none": unlike a node whose
// partitions have not run, it covers a read that happened and that read delivered
// nothing, so its silence here is an answer and not an absence.
if merge_scan.regions().is_empty() {
conclusive = true;
}
// A region without sub-stage metrics never reported, so the read over it is
// unknown even when every other region stated its answer.
if sub_stage_metrics.len() != merge_scan.regions().len() {
@@ -679,6 +714,7 @@ mod tests {
use api::v1::region::{RemoteDynFilterUnregister, RemoteDynFilterUpdate};
use async_trait::async_trait;
use common_recordbatch::{RecordBatchStream, RecordBatches};
use datafusion::arrow::datatypes::Schema as ArrowSchema;
use datafusion::execution::SessionStateBuilder;
use datafusion::physical_plan::empty::EmptyExec;
@@ -693,6 +729,9 @@ mod tests {
use crate::options::{FLOW_RETURN_REGION_SEQ, FLOW_SINK_TABLE_ID};
use crate::region_query::RegionQueryHandler;
/// The partition expression the tests of the observed slices state.
const PARTITION_EXPR: &str = "k0 < 10";
struct NoopRegionQueryHandler;
#[async_trait]
@@ -767,6 +806,18 @@ mod tests {
}
fn test_merge_scan_exec(table_id: u32, query_ctx: QueryContextRef) -> Arc<dyn ExecutionPlan> {
merge_scan_exec(vec![RegionId::new(table_id, 0)], query_ctx)
}
/// A merge scan over `regions`, with a query context that asks for nothing.
fn merge_scan_exec_with_regions(regions: Vec<RegionId>) -> Arc<dyn ExecutionPlan> {
merge_scan_exec(regions, Arc::new(QueryContextBuilder::default().build()))
}
fn merge_scan_exec(
regions: Vec<RegionId>,
query_ctx: QueryContextRef,
) -> Arc<dyn ExecutionPlan> {
let session_state = SessionStateBuilder::new().with_default_features().build();
let plan = LogicalPlanBuilder::empty(false).build().unwrap();
let schema = ArrowSchema::empty();
@@ -775,7 +826,7 @@ mod tests {
MergeScanExec::new(
&session_state,
TableName::new("greptime", "public", "test"),
vec![RegionId::new(table_id, 0)],
regions,
plan,
&schema,
Arc::new(NoopRegionQueryHandler),
@@ -908,104 +959,109 @@ mod tests {
);
}
/// A partition stream that states what a Mito region's stream states when it ends.
struct StatedStream {
inner: common_recordbatch::SendableRecordBatchStream,
terminal: RecordBatchMetrics,
}
impl futures::Stream for StatedStream {
type Item = common_recordbatch::error::Result<common_recordbatch::RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
std::pin::Pin::new(&mut self.inner).poll_next(cx)
}
}
impl RecordBatchStream for StatedStream {
fn schema(&self) -> datatypes::schema::SchemaRef {
self.inner.schema()
}
fn output_ordering(&self) -> Option<&[common_recordbatch::OrderOption]> {
self.inner.output_ordering()
}
fn metrics(&self) -> Option<RecordBatchMetrics> {
Some(self.terminal.clone())
}
}
/// A `RegionScanExec` whose one partition states `terminal` when its stream ends.
fn stated_region_scan(terminal: RecordBatchMetrics) -> Arc<dyn ExecutionPlan> {
use store_api::region_engine::SinglePartitionScanner;
let mut builder = store_api::metadata::RegionMetadataBuilder::new(RegionId::new(1, 1));
builder
.push_column_metadata(store_api::metadata::ColumnMetadata {
column_schema: datatypes::schema::ColumnSchema::new(
"field",
datatypes::data_type::ConcreteDataType::float64_datatype(),
true,
),
semantic_type: api::v1::SemanticType::Field,
column_id: 1,
})
.push_column_metadata(store_api::metadata::ColumnMetadata {
column_schema: datatypes::schema::ColumnSchema::new(
"ts",
datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(),
false,
),
semantic_type: api::v1::SemanticType::Timestamp,
column_id: 2,
})
.primary_key(vec![]);
let metadata = Arc::new(builder.build().unwrap());
let batches = RecordBatches::try_new(metadata.schema.clone(), vec![]).unwrap();
let stream = StatedStream {
inner: batches.as_stream(),
terminal,
};
let scanner = Box::new(SinglePartitionScanner::new(
Box::pin(stream),
false,
metadata,
None,
));
Arc::new(
RegionScanExec::new(scanner, store_api::storage::ScanRequest::default(), None).unwrap(),
)
}
/// Runs `plan` as a plan, through the DataFusion boundary, until its streams ended.
async fn drain_plan(plan: Arc<dyn ExecutionPlan>) {
use datafusion::prelude::SessionContext;
use futures::TryStreamExt;
let ctx = SessionContext::new();
let mut stream = plan.execute(0, ctx.task_ctx()).unwrap();
while stream.try_next().await.unwrap().is_some() {}
}
/// The terminal metrics of a scan that stated only the creators it delivered rows from.
fn creator_answer(creators: Option<Vec<u64>>) -> RecordBatchMetrics {
RecordBatchMetrics {
foreign_file_row_creators: creators,
..Default::default()
}
}
/// A plan that runs in this process states its answer through the region scan that read the
/// region, not through a stream that a rebuilt `RecordBatchMetrics` could still describe.
#[tokio::test]
async fn collect_foreign_file_row_creators_reads_the_local_region_scan() {
use common_recordbatch::adapter::RecordBatchMetrics;
use common_recordbatch::{RecordBatchStream, RecordBatches};
use datafusion::prelude::SessionContext;
use futures::TryStreamExt;
use store_api::region_engine::SinglePartitionScanner;
/// A partition stream that states what a Mito region's stream states when it ends.
struct ReportedStream {
inner: common_recordbatch::SendableRecordBatchStream,
creators: Option<Vec<u64>>,
}
impl futures::Stream for ReportedStream {
type Item = common_recordbatch::error::Result<common_recordbatch::RecordBatch>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
std::pin::Pin::new(&mut self.inner).poll_next(cx)
}
}
impl RecordBatchStream for ReportedStream {
fn schema(&self) -> datatypes::schema::SchemaRef {
self.inner.schema()
}
fn output_ordering(&self) -> Option<&[common_recordbatch::OrderOption]> {
self.inner.output_ordering()
}
fn metrics(&self) -> Option<RecordBatchMetrics> {
Some(RecordBatchMetrics {
foreign_file_row_creators: self.creators.clone(),
..Default::default()
})
}
}
fn region_scan(creators: Option<Vec<u64>>) -> Arc<dyn ExecutionPlan> {
let mut builder = store_api::metadata::RegionMetadataBuilder::new(RegionId::new(1, 1));
builder
.push_column_metadata(store_api::metadata::ColumnMetadata {
column_schema: datatypes::schema::ColumnSchema::new(
"field",
datatypes::data_type::ConcreteDataType::float64_datatype(),
true,
),
semantic_type: api::v1::SemanticType::Field,
column_id: 1,
})
.push_column_metadata(store_api::metadata::ColumnMetadata {
column_schema: datatypes::schema::ColumnSchema::new(
"ts",
datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(),
false,
),
semantic_type: api::v1::SemanticType::Timestamp,
column_id: 2,
})
.primary_key(vec![]);
let metadata = Arc::new(builder.build().unwrap());
let batches = RecordBatches::try_new(metadata.schema.clone(), vec![]).unwrap();
let stream = ReportedStream {
inner: batches.as_stream(),
creators,
};
let scanner = Box::new(SinglePartitionScanner::new(
Box::pin(stream),
false,
metadata,
None,
));
Arc::new(
RegionScanExec::new(scanner, store_api::storage::ScanRequest::default(), None)
.unwrap(),
)
}
async fn drain(plan: Arc<dyn ExecutionPlan>) {
let ctx = SessionContext::new();
let mut stream = plan.execute(0, ctx.task_ctx()).unwrap();
while stream.try_next().await.unwrap().is_some() {}
}
// The scan answered what its stream stated.
let plan = region_scan(Some(vec![7]));
let plan = stated_region_scan(creator_answer(Some(vec![7])));
assert_eq!(
None,
collect_foreign_file_row_creators(plan.clone(), &RecordBatchMetrics::default()),
"a scan whose stream has not ended states nothing"
);
drain(plan.clone()).await;
drain_plan(plan.clone()).await;
assert_eq!(
Some(vec![7]),
collect_foreign_file_row_creators(plan.clone(), &RecordBatchMetrics::default()),
@@ -1020,8 +1076,8 @@ mod tests {
// A scan whose stream stated nothing stays unknown: a read that did not report must
// not be read as "delivered none".
let plan = region_scan(None);
drain(plan.clone()).await;
let plan = stated_region_scan(creator_answer(None));
drain_plan(plan.clone()).await;
assert_eq!(
None,
collect_foreign_file_row_creators(plan, &RecordBatchMetrics::default()),
@@ -1029,6 +1085,92 @@ mod tests {
);
}
/// The ranges a scan substituted and the slices it observed are statements about its read,
/// not figures, so they must survive the DataFusion boundary: the plan is polled to EOF as a
/// plan, and its stream reports only numbers. A read that substituted rows must not reach
/// the caller as "substituted nothing".
#[tokio::test]
async fn substituted_ranges_and_observed_slices_cross_the_datafusion_boundary() {
let plan = stated_region_scan(RecordBatchMetrics {
foreign_file_row_creators: Some(vec![]),
substituted_row_ranges: vec![SubstitutedRowRanges {
region_id: 7,
ranges: vec![SubstitutedRange {
start_millis: 1_000,
end_millis: 2_000,
}],
}],
observed_slices: vec![ObservedPartitionExpr::new(
7,
Some(PARTITION_EXPR.to_string()),
)],
..Default::default()
});
// Nothing is stated before the read ends, so nothing is claimed.
assert!(
terminal_recordbatch_metrics_from_plan(plan.clone()).is_none(),
"a scan whose stream has not ended states nothing"
);
drain_plan(plan.clone()).await;
let metrics = terminal_recordbatch_metrics_from_plan(plan)
.expect("a read that substituted rows and observed slices is terminal metrics");
assert_eq!(
vec![SubstitutedRowRanges {
region_id: 7,
ranges: vec![SubstitutedRange {
start_millis: 1_000,
end_millis: 2_000,
}],
}],
metrics.substituted_row_ranges,
"the substituted ranges must cross the boundary, not read as \"substituted nothing\""
);
assert_eq!(
vec![ObservedPartitionExpr::new(
7,
Some(PARTITION_EXPR.to_string())
)],
metrics.observed_slices,
"the observed slices must cross the boundary"
);
assert_eq!(
Some(vec![]),
metrics.foreign_file_row_creators,
"the same terminal call states the creator answer as well"
);
}
/// A merge scan that lists no region read nothing, so it states "delivered none" instead of
/// leaving the answer unknown: the read over zero regions covers every row it could have
/// delivered, and that read delivered none.
#[test]
fn zero_region_merge_scan_states_delivered_none() {
let plan = merge_scan_exec_with_regions(vec![]);
assert_eq!(
Some(vec![]),
collect_foreign_file_row_creators(plan.clone(), &RecordBatchMetrics::default()),
"a merge scan with no region delivered no adopted row, and states so"
);
assert_eq!(
Some(vec![]),
terminal_recordbatch_metrics_from_plan(plan)
.expect("an affirmative creator answer is terminal metrics")
.foreign_file_row_creators
);
// A merge scan that names a region that never reported stays unknown, so the empty
// answer above is the zero-region read and not a blanket "silence is none".
let plan = merge_scan_exec_with_regions(vec![RegionId::new(43, 0)]);
assert_eq!(
None,
collect_foreign_file_row_creators(plan, &RecordBatchMetrics::default()),
"a region without sub-stage metrics leaves the answer unknown"
);
}
#[test]
fn merge_merge_scan_region_watermarks_marks_missing_watermarks_unproved() {
let mut merged = BTreeMap::new();
+61 -29
View File
@@ -24,8 +24,8 @@ use common_query::series_frame::{
PendingBatching, pack_raw_series_with, raw_series_frame_schema_with_ordering,
};
use common_recordbatch::adapter::{
ForeignFileRowCreatorReports, RecordBatchStreamAdapter, RegionQueryStatCounters,
SERIES_SCAN_EXEC_NAME,
ObservedPartitionExpr, RecordBatchStreamAdapter, RegionQueryStatCounters,
SERIES_SCAN_EXEC_NAME, SubstitutedRowRanges, TerminalScanReports,
};
use common_recordbatch::{
DfRecordBatch, DfSendableRecordBatchStream, MemoryTrackedStream, QueryMemoryTracker,
@@ -91,14 +91,15 @@ pub struct RegionScanExec {
/// Dynamic filters accepted by the scanner and applied to decoded output batches.
/// The wrappers themselves remain live and are updated by their producers.
pushed_dyn_filters: Arc<Mutex<Vec<Arc<dyn PhysicalExpr>>>>,
/// What the partition streams reported about the adopted files they delivered rows from,
/// each stream reporting when it ends.
/// What this node's partition streams stated when they ended: the other regions' files they
/// delivered rows from, the time ranges of the rows they substituted, and the
/// `(region, partition expression)` slices they read.
///
/// The scanner's stream states it, and this node is what a plan-level collector can ask
/// after the read: DataFusion's metrics carry figures, not an answer about what was read,
/// and a rebuilt [`RecordBatchMetrics`] cannot recover one. Shared with the clones that
/// re-assign partition ranges, so an answer stated before a re-assignment is not lost.
foreign_file_row_creators: Arc<ForeignFileRowCreatorReports>,
/// The scanner's stream states them, and this node is what a plan-level collector can ask
/// after the read: DataFusion's metrics carry figures, not an answer about what was read, and
/// a rebuilt [`RecordBatchMetrics`] cannot recover one. Shared with the clones that re-assign
/// partition ranges, so an answer stated before a re-assignment is not lost.
terminal_reports: Arc<TerminalScanReports>,
}
impl std::fmt::Debug for RegionScanExec {
@@ -337,7 +338,7 @@ impl RegionScanExec {
explain_verbose: false,
query_memory_tracker,
pushed_dyn_filters: Arc::new(Mutex::new(Vec::new())),
foreign_file_row_creators: Arc::new(ForeignFileRowCreatorReports::new()),
terminal_reports: Arc::new(TerminalScanReports::new()),
})
}
@@ -412,7 +413,7 @@ impl RegionScanExec {
explain_verbose: self.explain_verbose,
query_memory_tracker: self.query_memory_tracker.clone(),
pushed_dyn_filters: self.pushed_dyn_filters.clone(),
foreign_file_row_creators: self.foreign_file_row_creators.clone(),
terminal_reports: self.terminal_reports.clone(),
})
}
@@ -427,7 +428,23 @@ impl RegionScanExec {
/// finished; a partition that is still running, that never ran or that ended without an
/// answer leaves this unknown instead of answering "delivered none".
pub fn foreign_file_row_creators(&self) -> Option<Vec<u64>> {
self.foreign_file_row_creators.answer()
self.terminal_reports.foreign_file_row_creators()
}
/// The time ranges of the rows this node's partition streams substituted, per region, or
/// `None` when they do not state an answer (yet).
///
/// Empty is the protocol's "substituted nothing": it tells a caller that recomputes the
/// windows of substituted rows that it has nothing to recompute, which is only true once the
/// partitions stated that they substituted nothing.
pub fn substituted_row_ranges(&self) -> Option<Vec<SubstitutedRowRanges>> {
self.terminal_reports.substituted_row_ranges()
}
/// The `(region, partition expression)` pairs this node's partition streams read, or `None`
/// when they do not state an answer (yet).
pub fn observed_slices(&self) -> Option<Vec<ObservedPartitionExpr>> {
self.terminal_reports.observed_slices()
}
pub fn with_distinguish_partition_range(&self, distinguish_partition_range: bool) {
@@ -702,6 +719,12 @@ impl std::fmt::Debug for SeriesScanExec {
}
impl SeriesScanExec {
/// Returns the region scan this leaf packs, which is also what states what the read
/// delivered, substituted and observed once its partition streams ended.
pub fn region_scan(&self) -> &RegionScanExec {
&self.scan
}
/// Returns the immutable label binding supplied to the storage scan.
pub fn scan_binding(&self) -> &RawLabelSource {
&self.scan_binding
@@ -805,6 +828,9 @@ impl ExecutionPlan for SeriesScanExec {
fn reset_state(self: Arc<Self>) -> DfResult<Arc<dyn ExecutionPlan>> {
self.scan.scanner.lock().unwrap().reset_state();
self.scan.pushed_dyn_filters.lock().unwrap().clear();
// What the read stated belongs to the run that read it, so a reused plan starts with
// nothing stated instead of reporting the run before it.
self.scan.terminal_reports.reset();
Ok(self)
}
fn execute(
@@ -911,7 +937,11 @@ impl ExecutionPlan for SeriesScanExec {
span,
await_timer: None,
dyn_filter: None,
creator_report: None,
terminal_report: Some(TerminalReport {
reports: self.scan.terminal_reports.clone(),
partition,
partitions,
}),
}))
}
}
@@ -1005,8 +1035,8 @@ impl ExecutionPlan for RegionScanExec {
span,
await_timer: None,
dyn_filter,
creator_report: Some(CreatorReport {
reports: self.foreign_file_row_creators.clone(),
terminal_report: Some(TerminalReport {
reports: self.terminal_reports.clone(),
partition,
partitions: self.properties.output_partitioning().partition_count(),
}),
@@ -1020,6 +1050,9 @@ impl ExecutionPlan for RegionScanExec {
fn reset_state(self: Arc<Self>) -> DfResult<Arc<dyn ExecutionPlan>> {
self.scanner.lock().unwrap().reset_state();
self.pushed_dyn_filters.lock().unwrap().clear();
// What the read stated belongs to the run that read it, so a reused plan starts with
// nothing stated instead of reporting the run before it.
self.terminal_reports.reset();
Ok(self)
}
@@ -1140,9 +1173,9 @@ impl DisplayAs for RegionScanExec {
}
}
/// Where a partition stream of [`RegionScanExec`] reports what it delivered when it ends.
struct CreatorReport {
reports: Arc<ForeignFileRowCreatorReports>,
/// Where a partition stream of [`RegionScanExec`] states what it read when it ends.
struct TerminalReport {
reports: Arc<TerminalScanReports>,
partition: usize,
partitions: usize,
}
@@ -1153,8 +1186,8 @@ pub struct StreamWithMetricWrapper {
span: Span,
await_timer: Option<Instant>,
dyn_filter: Option<Arc<dyn PhysicalExpr>>,
/// Where this stream states its terminal creator answer, taken once the stream ended.
creator_report: Option<CreatorReport>,
/// Where this stream states what it read, taken once the stream ended.
terminal_report: Option<TerminalReport>,
}
impl Stream for StreamWithMetricWrapper {
@@ -1199,17 +1232,16 @@ impl Stream for StreamWithMetricWrapper {
}
}
Poll::Ready(None) => {
// The stream is over, so what its metrics state now is the terminal answer.
// It is an answer about the rows it delivered, which is what the plan's
// collector must see: DataFusion's own metrics carry figures only.
if let Some(report) = this.creator_report.take() {
let answer = this
.stream
.metrics()
.and_then(|metrics| metrics.foreign_file_row_creators);
// The stream is over, so what its metrics state now is the terminal answer. It
// is an answer about the rows it read, which is what the plan's collector must
// see: DataFusion's own metrics carry figures only, so the creators it delivered
// rows from, the ranges it substituted and the slices it observed can only
// cross that boundary through this report.
if let Some(report) = this.terminal_report.take() {
let answer = this.stream.metrics();
report
.reports
.record(report.partition, report.partitions, answer);
.record(report.partition, report.partitions, answer.as_ref());
}
Poll::Ready(None)
}