diff --git a/src/common/recordbatch/src/adapter.rs b/src/common/recordbatch/src/adapter.rs index ed850ab4983..4d02e05a74f 100644 --- a/src/common/recordbatch/src/adapter.rs +++ b/src/common/recordbatch/src/adapter.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::collections::BTreeSet; use std::fmt::{self, Display}; use std::future::Future; use std::marker::PhantomData; @@ -739,6 +740,74 @@ pub struct RecordBatchMetrics { pub foreign_file_row_creators: Option>, } +/// 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. +/// +/// 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. +#[derive(Debug, Default)] +pub struct ForeignFileRowCreatorReports { + state: Mutex, +} + +#[derive(Debug, Default)] +struct ForeignFileRowCreatorReportsState { + /// The partitions whose stream ended and stated an answer. + reported: BTreeSet, + /// The creator regions those partitions named. + creators: BTreeSet, + /// A partition ended without stating an answer, so no set of partitions can answer for + /// the node. + unknown: bool, + /// How many partitions the reporting node has, as last reported. + partitions: usize, +} + +impl ForeignFileRowCreatorReports { + 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. + /// + /// 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>) { + let mut state = self.lock(); + state.partitions = partitions; + match answer { + Some(creators) => { + state.reported.insert(partition); + state.creators.extend(creators); + } + None => state.unknown = true, + } + } + + /// The creators every partition reported together, or `None` when the partitions do not + /// state such an answer (yet). + pub fn answer(&self) -> Option> { + 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. + if state.unknown || state.partitions == 0 || state.reported.len() != state.partitions { + return None; + } + Some(state.creators.iter().copied().collect()) + } + + /// 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> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } +} + /// The partition expression of one region that a scan read rows of, i.e. one /// `(region, partition expression)` pair. /// @@ -1935,6 +2004,40 @@ mod test { assert_eq!(None, metrics.foreign_file_row_creators); } + /// 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"); + + reports.record(0, 2, Some(vec![7, 9])); + assert_eq!( + None, + reports.answer(), + "one partition answered and another has not" + ); + + reports.record(1, 2, Some(vec![9])); + assert_eq!( + Some(vec![7, 9]), + reports.answer(), + "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])); + reports.record(1, 2, None); + assert_eq!(None, reports.answer()); + + // 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()); + } + /// An affirmative answer of "delivered none" is written as an empty array and read back as /// exactly that, distinct from an omitted field. #[test] diff --git a/src/mito2/src/cache/range_cache.rs b/src/mito2/src/cache/range_cache.rs index 7c58c18cc99..b332dc8e3c9 100644 --- a/src/mito2/src/cache/range_cache.rs +++ b/src/mito2/src/cache/range_cache.rs @@ -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( self: &Arc, @@ -147,6 +152,7 @@ impl RangeResultCache { part_metrics: Arc, files: Vec, 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 diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 0c3c372ff0c..fb094162ba5 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -7545,6 +7545,96 @@ async fn test_read_row_sequence_reports_no_foreign_file_row_creators_for_a_local ); } +/// A read that replays a cached range result does not open the files that produced its rows, so +/// it cannot say which other regions created them: it must answer "unknown" instead of the +/// "delivered none" an empty recorded set would say. +#[tokio::test] +async fn test_range_cache_replay_reports_unknown_foreign_file_row_creators() { + use std::time::Duration; + + let mut env = + TestEnv::with_prefix("test_range_cache_replay_unknown_foreign_row_creators").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); + + // A source region that is not in append mode: its reads go through the ordered scan, which + // is the one that reads and fills the range cache. + let request = CreateRequestBuilder::new().build(); + let schema = test_util::rows_schema(&request); + engine + .handle_request(source, RegionRequest::Create(request.clone())) + .await + .unwrap(); + test_util::put_rows( + &engine, + source, + Rows { + schema, + rows: test_util::build_rows_for_key("0", 0, 5, 0), + }, + ) + .await; + test_util::flush_region(&engine, source, None).await; + let source_file = engine + .get_region(source) + .unwrap() + .manifest_ctx + .manifest() + .await + .files + .values() + .next() + .expect("source file") + .as_ref() + .clone(); + engine + .handle_request(target, RegionRequest::Create(request)) + .await + .unwrap(); + adopt_foreign_file(&engine, target, source_file, 6, false, None); + + // A tag filter selects every row of the file and makes the range eligible for the cache. + let scan = || ScanRequest { + filters: vec![col("tag_0").eq(lit(ScalarValue::Utf8(Some("0".to_string()))))], + ..Default::default() + }; + + // The first read opens the adopted file and names its creator. + let (cold_rows, cold_creators) = + scan_partition_rows_and_foreign_creators(&engine, target, scan()).await; + assert_eq!(vec![0, 1000, 2000, 3000, 4000], cold_rows); + assert_eq!(Some(vec![source.as_u64()]), cold_creators); + + // A later read of the same range replays the completed result once the publisher ran. It + // delivers the same rows without reading the file, so it states no creator at all. + let warm_creators = tokio::time::timeout(Duration::from_secs(10), async { + loop { + let (rows, creators) = + scan_partition_rows_and_foreign_creators(&engine, target, scan()).await; + assert_eq!(cold_rows, rows, "a replay delivers the rows it replayed"); + if creators.is_none() { + return creators; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the range result cache did not replay the range within the timeout"); + assert_eq!( + None, warm_creators, + "a replayed range did not open the files its rows came from, so its creators are \ + unknown rather than none" + ); +} + /// Raw Mito output contains candidates after projection, filtering, and MVCC read processing. #[tokio::test] async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() { diff --git a/src/mito2/src/read/range_cache.rs b/src/mito2/src/read/range_cache.rs index 4caf4636695..679663480f6 100644 --- a/src/mito2/src/read/range_cache.rs +++ b/src/mito2/src/read/range_cache.rs @@ -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; @@ -647,6 +648,7 @@ impl CachedRangeReader<'_> { self.metrics, files, scope, + self.stream_ctx.input.foreign_file_row_creators(), build, ) .await @@ -689,7 +691,7 @@ where F: FnOnce() -> Fut, Fut: Future>, { - 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( @@ -698,6 +700,7 @@ async fn load_shared_range( part_metrics: &PartitionMetrics, files: Vec, scope: RangeCacheScope, + replay_evidence: Option<&ForeignFileRowCreators>, build: F, ) -> Result<(BoxedRecordBatchStream, usize)> where @@ -713,6 +716,7 @@ where part_metrics.range_cache_metrics_reporter(), files, scope, + replay_evidence, build, ) .await diff --git a/src/mito2/src/read/substituted_rows.rs b/src/mito2/src/read/substituted_rows.rs index 02be58b2e94..bb13abda889 100644 --- a/src/mito2/src/read/substituted_rows.rs +++ b/src/mito2/src/read/substituted_rows.rs @@ -24,6 +24,7 @@ use std::collections::BTreeSet; use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; @@ -162,6 +163,9 @@ impl ObservedPartitionExprs { #[derive(Debug, Default)] pub(crate) struct ForeignFileRowCreators { creators: Mutex>, + /// 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; @@ -186,6 +190,17 @@ impl ForeignFileRowCreators { .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 { self.creators @@ -195,6 +210,15 @@ impl ForeignFileRowCreators { .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> { + 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`. @@ -370,9 +394,10 @@ impl RecordBatchStream for SubstitutedRowRangesStream { } // 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. + // 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 = Some(creators.entries()); + metrics.foreign_file_row_creators = creators.answer(); } Some(metrics) } diff --git a/src/query/src/metrics.rs b/src/query/src/metrics.rs index b2ab1876dde..f9041bbe124 100644 --- a/src/query/src/metrics.rs +++ b/src/query/src/metrics.rs @@ -31,6 +31,8 @@ use lazy_static::lazy_static; use prometheus::*; use session::context::QueryContextRef; +use table::table::scan::RegionScanExec; + use crate::dist_plan::MergeScanExec; use crate::error::Result; use crate::options::FlowQueryExtensions; @@ -422,10 +424,10 @@ fn collect_observed_slices( /// /// The answer is `Some` only when **every** region scan that could have read a file stated /// what it delivered, and the region set is then the union of their answers. A scan that -/// reported nothing — a build that predates the field, or a region whose metrics never -/// arrived — latches the whole answer to `None`, because an answer covering part of the read -/// must not claim that nothing came from another region. `Some(vec![])` is an affirmative -/// "delivered none" and survives the merge as the empty set. +/// reported nothing — a build that predates the field, a region whose metrics never arrived, +/// or a plan node that never ended its stream — latches the whole answer to `None`, because an +/// answer covering part of the read must not claim that nothing came from another region. +/// `Some(vec![])` is an affirmative "delivered none" and survives the merge as the empty set. fn collect_foreign_file_row_creators( plan: Arc, own: &RecordBatchMetrics, @@ -445,6 +447,19 @@ fn collect_foreign_file_row_creators( let mut stack = vec![plan]; while let Some(plan) = stack.pop() { + // A region scan keeps the answer its partition streams stated when they ended, which + // 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::() { + let creators = region_scan.foreign_file_row_creators(); + merge_foreign_file_row_creators( + creators.as_deref(), + &mut merged, + &mut conclusive, + &mut unknown, + ); + } if let Some(merge_scan) = plan.downcast_ref::() && !merge_scan.is_flow_sink_scan() { @@ -848,6 +863,127 @@ mod tests { ); } + /// 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>, + } + + impl futures::Stream for ReportedStream { + type Item = common_recordbatch::error::Result; + + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + 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 { + Some(RecordBatchMetrics { + foreign_file_row_creators: self.creators.clone(), + ..Default::default() + }) + } + } + + fn region_scan(creators: Option>) -> Arc { + 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) { + 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])); + 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; + assert_eq!( + Some(vec![7]), + collect_foreign_file_row_creators(plan.clone(), &RecordBatchMetrics::default()), + "the plan states what its region scan delivered" + ); + assert_eq!( + Some(vec![7]), + terminal_recordbatch_metrics_from_plan(plan) + .expect("a conclusive creator answer is terminal metrics") + .foreign_file_row_creators + ); + + // 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; + assert_eq!( + None, + collect_foreign_file_row_creators(plan, &RecordBatchMetrics::default()), + "a scan that states no answer leaves the plan's answer unknown" + ); + } + #[test] fn merge_merge_scan_region_watermarks_marks_missing_watermarks_unproved() { let mut merged = BTreeMap::new(); diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index 5a6af6ffbbe..8c8b732457e 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -24,7 +24,8 @@ use common_query::series_frame::{ PendingBatching, pack_raw_series_with, raw_series_frame_schema_with_ordering, }; use common_recordbatch::adapter::{ - RecordBatchStreamAdapter, RegionQueryStatCounters, SERIES_SCAN_EXEC_NAME, + ForeignFileRowCreatorReports, RecordBatchStreamAdapter, RegionQueryStatCounters, + SERIES_SCAN_EXEC_NAME, }; use common_recordbatch::{ DfRecordBatch, DfSendableRecordBatchStream, MemoryTrackedStream, QueryMemoryTracker, @@ -90,6 +91,14 @@ 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>>>, + /// What the partition streams reported about the adopted files they delivered rows from, + /// each stream reporting when it ends. + /// + /// 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, } impl std::fmt::Debug for RegionScanExec { @@ -328,6 +337,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()), }) } @@ -402,6 +412,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(), }) } @@ -409,6 +420,16 @@ impl RegionScanExec { self.distribution } + /// The creator regions this node's partition streams reported delivering rows from, or + /// `None` when they do not state an answer. + /// + /// A partition states its answer when its stream ends, so a caller asks after the read + /// 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> { + self.foreign_file_row_creators.answer() + } + pub fn with_distinguish_partition_range(&self, distinguish_partition_range: bool) { let mut scanner = self.scanner.lock().unwrap(); // set distinguish_partition_range won't fail @@ -890,6 +911,7 @@ impl ExecutionPlan for SeriesScanExec { span, await_timer: None, dyn_filter: None, + creator_report: None, })) } } @@ -983,6 +1005,11 @@ impl ExecutionPlan for RegionScanExec { span, await_timer: None, dyn_filter, + creator_report: Some(CreatorReport { + reports: self.foreign_file_row_creators.clone(), + partition, + partitions: self.properties.output_partitioning().partition_count(), + }), })) } @@ -1113,12 +1140,21 @@ impl DisplayAs for RegionScanExec { } } +/// Where a partition stream of [`RegionScanExec`] reports what it delivered when it ends. +struct CreatorReport { + reports: Arc, + partition: usize, + partitions: usize, +} + pub struct StreamWithMetricWrapper { stream: SendableRecordBatchStream, metric: StreamMetrics, span: Span, await_timer: Option, dyn_filter: Option>, + /// Where this stream states its terminal creator answer, taken once the stream ended. + creator_report: Option, } impl Stream for StreamWithMetricWrapper { @@ -1162,7 +1198,21 @@ impl Stream for StreamWithMetricWrapper { Err(e) => Poll::Ready(Some(Err(DataFusionError::External(Box::new(e))))), } } - Poll::Ready(None) => Poll::Ready(None), + 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); + report + .reports + .record(report.partition, report.partitions, answer); + } + Poll::Ready(None) + } Poll::Pending => Poll::Pending, } } @@ -1379,6 +1429,106 @@ mod test { ) } + /// A stream that states, when it ends, which other regions' files it delivered rows from, + /// the way a Mito region's stream does. + struct ReportedStream { + inner: SendableRecordBatchStream, + creators: Option>, + } + + impl Stream for ReportedStream { + type Item = common_recordbatch::error::Result; + + fn poll_next( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_next(cx) + } + } + + impl common_recordbatch::RecordBatchStream for ReportedStream { + fn schema(&self) -> SchemaRef { + self.inner.schema() + } + + fn output_ordering(&self) -> Option<&[common_recordbatch::OrderOption]> { + self.inner.output_ordering() + } + + fn metrics(&self) -> Option { + Some(common_recordbatch::adapter::RecordBatchMetrics { + foreign_file_row_creators: self.creators.clone(), + ..Default::default() + }) + } + } + + fn reporting_region_scan(creators: Option>) -> RegionScanExec { + let (schema, _, metadata) = dynamic_filter_test_data(5688, false); + let batches = RecordBatches::try_new(schema, vec![]).unwrap(); + let stream = ReportedStream { + inner: batches.as_stream(), + creators, + }; + let scanner = Box::new(SinglePartitionScanner::new( + Box::pin(stream), + false, + metadata, + None, + )); + RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap() + } + + async fn drain_plan(plan: Arc, context: Arc) { + let partitions = plan.properties().output_partitioning().partition_count(); + for partition in 0..partitions { + let mut stream = plan.execute(partition, context.clone()).unwrap(); + while stream.try_next().await.unwrap().is_some() {} + } + } + + /// What a region scan delivered is stated by its stream when the stream ends, so the node + /// keeps that answer: DataFusion's own metrics carry figures, and a rebuilt + /// `RecordBatchMetrics` cannot recover the answer from them. + #[tokio::test] + async fn test_region_scan_keeps_the_terminal_creator_answer_of_its_stream() { + let ctx = SessionContext::new(); + + let plan = Arc::new(reporting_region_scan(Some(vec![7]))); + assert_eq!( + None, + plan.foreign_file_row_creators(), + "a scan that has not read anything states nothing, not \"delivered none\"" + ); + drain_plan(plan.clone(), ctx.task_ctx()).await; + assert_eq!( + Some(vec![7]), + plan.foreign_file_row_creators(), + "the answer the stream stated when it ended is the node's answer" + ); + + // A stream that states nothing leaves the node's answer unknown: silence is not + // "delivered none". + let plan = Arc::new(reporting_region_scan(None)); + drain_plan(plan.clone(), ctx.task_ctx()).await; + assert_eq!(None, plan.foreign_file_row_creators()); + + // One partition answers and another has nothing to say, so the answer covers only + // part of the read. + let plan = Arc::new( + reporting_region_scan(Some(vec![7])) + .with_new_partitions(vec![vec![], vec![]], 2) + .unwrap(), + ); + drain_plan(plan.clone(), ctx.task_ctx()).await; + assert_eq!( + None, + plan.foreign_file_row_creators(), + "a silent partition makes the read uncovered, not empty" + ); + } + #[test] fn assign_partition_ranges_balances_rows_deterministically() { let ranges: Vec<_> = [100, 200, 150, 250]