feat(mito): render scan details in tree explain plans (#10926)

* feat(mito): render scan details in tree explain plans

Signed-off-by: luofucong <luofc@foxmail.com>

* remove some obsolete todos

Signed-off-by: luofucong <luofc@foxmail.com>

---------

Signed-off-by: luofucong <luofc@foxmail.com>
This commit is contained in:
LFC authored and GitHub committed 2026-12-04 08:59:15 +00:00
1 parent c2e7262068
commit 9a8df3b73a
13 files changed
+121 -63

No files matched your search

-1
View File
@@ -37,7 +37,6 @@ pub struct GlobalOptions {
pub tokio_console_addr: Option<String>,
}
// TODO(LFC): Move logging and tracing options into global options, like the runtime options.
/// All the options of GreptimeDB.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
-1
View File
@@ -247,7 +247,6 @@ macro_rules! define_from_tonic_status {
.and_then(|s| s.parse().ok())
.unwrap_or($crate::ext::RetryHint::NonRetryable);
// TODO(LFC): Make the error variant defined automatically.
Self::$Variant {
code,
msg,
@@ -39,7 +39,6 @@ macro_rules! json_is {
impl Default for $name {
fn default() -> Self {
Self {
// TODO(LFC): Use a more clear type here instead of "Binary" for Json input, once we have a "Json" type.
signature: Signature::uniform(
1,
vec![DataType::Binary, DataType::BinaryView],
@@ -33,7 +33,6 @@ pub(crate) struct JsonPathExistsFunction {
impl Default for JsonPathExistsFunction {
fn default() -> Self {
Self {
// TODO(LFC): Use a more clear type here instead of "Binary" for Json input, once we have a "Json" type.
signature: helper::one_of_sigs2(
vec![DataType::Binary, DataType::BinaryView, DataType::Null],
vec![DataType::Utf8, DataType::Utf8View, DataType::Null],
@@ -32,7 +32,6 @@ pub(crate) struct JsonPathMatchFunction {
impl Default for JsonPathMatchFunction {
fn default() -> Self {
Self {
// TODO(LFC): Use a more clear type here instead of "Binary" for Json input, once we have a "Json" type.
signature: helper::one_of_sigs2(
vec![DataType::Binary, DataType::BinaryView],
vec![DataType::Utf8, DataType::Utf8View],
@@ -32,7 +32,6 @@ pub(crate) struct JsonToStringFunction {
impl Default for JsonToStringFunction {
fn default() -> Self {
Self {
// TODO(LFC): Use a more clear type here instead of "Binary" for Json input, once we have a "Json" type.
signature: Signature::uniform(
1,
vec![
@@ -58,7 +58,6 @@ impl RecordBatch {
// corresponding to view arrays. What we can do is to only cast them.
// As to "temporary": we are planing to use Arrow's RecordBatch directly in the read path.
// the casting here will be removed in the end.
// TODO(LFC): Remove the casting here once `Batch` is no longer used.
let arrow_arrays = Self::cast_view_arrays(schema.arrow_schema(), arrow_arrays)?;
let df_record_batch = DfRecordBatch::try_new(schema.arrow_schema().clone(), arrow_arrays)
@@ -83,7 +82,6 @@ impl RecordBatch {
// corresponding to view arrays. What we can do is to only cast them.
// As to "temporary": we are planing to use Arrow's RecordBatch directly in the read path.
// the casting here will be removed in the end.
// TODO(LFC): Remove the casting here once `Batch` is no longer used.
let arrow_arrays = Self::cast_view_arrays(&arrow_schema, arrow_arrays)?;
let df_record_batch = DfRecordBatch::try_new(arrow_schema, arrow_arrays)
-1
View File
@@ -368,7 +368,6 @@ impl DataType for JsonType {
fn create_mutable_vector(&self, capacity: usize) -> Box<dyn MutableVector> {
match &self.format {
JsonFormat::Jsonb => Box::new(BinaryVectorBuilder::with_capacity(capacity)),
// TODO(LFC): Carry JsonSettings in JsonFormat::Json2 and use with_settings here.
JsonFormat::Json2(x) => Box::new(JsonVectorBuilder::new(x.as_ref().clone(), capacity)),
}
}
+74 -4
View File
@@ -28,11 +28,11 @@ use common_error::status_code::StatusCode;
use common_recordbatch::{DfRecordBatch, RecordBatches};
use common_test_util::flight::encode_to_flight_data;
use common_time::Timestamp;
use datafusion::physical_plan::VerboseDisplay;
use datafusion::physical_plan::expressions::{
BinaryExpr, Column, DynamicFilterPhysicalExpr, lit as physical_lit,
};
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
use datafusion::physical_plan::{VerboseDisplay, displayable};
use datafusion_common::ScalarValue;
use datafusion_expr::{Operator, col, lit};
use datatypes::arrow::array::{
@@ -63,6 +63,7 @@ use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME;
use store_api::storage::{
FileId, RegionId, ScanRequest, TimeSeriesDistribution, TimeSeriesRowSelector,
};
use table::table::scan::RegionScanExec;
use crate::config::MitoConfig;
use crate::error::Error;
@@ -2940,6 +2941,78 @@ async fn test_max_concurrent_scan_files_with_format(flat_format: bool, estimated
}
}
#[tokio::test]
async fn test_scan_tree_render() -> Result<(), Box<dyn std::error::Error>> {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
for (id, append_mode, distribution, expected) in [
(
1,
false,
None,
"\
┌───────────────────────────┐
│ RegionScanExec │
│ -------------------- │
│ SeqScan │
│ │
│ partitions: 1 │
│ region: 1(0, 1) │
└───────────────────────────┘
",
),
(
2,
true,
None,
"\
┌───────────────────────────┐
│ RegionScanExec │
│ -------------------- │
│ UnorderedScan │
│ │
│ partitions: 1 │
│ region: 2(0, 2) │
└───────────────────────────┘
",
),
(
3,
false,
Some(TimeSeriesDistribution::PerSeries),
"\
┌───────────────────────────┐
│ RegionScanExec │
│ -------------------- │
│ SeriesScan │
│ │
│ mode: legacy │
│ partitions: 1 │
│ region: 3(0, 3) │
└───────────────────────────┘
",
),
] {
let region_id = RegionId::new(0, id);
let create = CreateRequestBuilder::new()
.insert_option("append_mode", &append_mode.to_string())
.build();
engine
.handle_request(region_id, RegionRequest::Create(create))
.await?;
let request = ScanRequest {
distribution,
..Default::default()
};
let scanner = engine.handle_query(region_id, request.clone()).await?;
let plan = RegionScanExec::new(scanner, request, None)?;
let tree = displayable(&plan).tree_render().to_string();
assert_eq!(expected, tree, "Expected:\n{expected}Actual:\n{tree}");
}
Ok(())
}
#[tokio::test]
async fn test_series_scan() {
test_series_scan_with_format(false).await;
@@ -6555,7 +6628,6 @@ async fn test_mito_handle_query_raw_series_candidate_projection_and_mvcc() {
use common_query::series_frame::{series_frame_ordering, unpack_raw_series};
use datafusion::execution::TaskContext;
use datafusion::physical_plan::ExecutionPlan;
use table::table::scan::RegionScanExec;
let native_scanner = engine
.handle_query(region_id, request.clone())
.await
@@ -7430,7 +7502,6 @@ async fn test_mito_raw_series_int64_predicate_uses_original_precision() {
use datafusion::execution::TaskContext;
use datafusion::physical_plan::ExecutionPlan;
use datatypes::series::SeriesOrdering;
use table::table::scan::RegionScanExec;
let native_request = ScanRequest {
projection: Some(vec![2, 3]),
filters: vec![
@@ -7763,7 +7834,6 @@ async fn test_mito_raw_series_invalid_binding_before_legacy_read() {
// wrappers installed after planning must be caught at execute time.
use datafusion::execution::TaskContext;
use datafusion::physical_plan::ExecutionPlan;
use table::table::scan::RegionScanExec;
let dynamic_request = ScanRequest {
distribution: Some(TimeSeriesDistribution::PerSeries),
preserve_pk_dictionary_encoding: true,
+41 -3
View File
@@ -34,6 +34,7 @@ use common_telemetry::tracing::Instrument;
use common_telemetry::{debug, error, tracing, warn};
use common_time::range::TimestampRange;
use datafusion::optimizer::simplify_expressions::ExprSimplifier;
use datafusion::physical_plan::DisplayFormatType;
use datafusion::physical_plan::expressions::DynamicFilterPhysicalExpr;
use datafusion_common::pruning::PruningStatistics;
use datafusion_common::{Column, ScalarValue, ToDFSchema};
@@ -52,7 +53,9 @@ use serde_json::{Value as JsonValue, json};
use smallvec::SmallVec;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef};
use store_api::region_engine::{PartitionRange, RegionScannerRef, ScannerProperties};
use store_api::region_engine::{
PartitionRange, RegionScanner, RegionScannerRef, ScannerProperties,
};
use store_api::storage::{
ColumnId, RegionId, ScanRequest, SequenceNumber, SequenceRange, TimeSeriesDistribution,
TimeSeriesRowSelector,
@@ -77,6 +80,7 @@ use crate::read::flat_projection::FlatProjectionMapper;
use crate::read::range::{FileRangeBuilder, MemRangeBuilder, RangeMeta, RowGroupIndex};
use crate::read::range_cache::{ScanRequestFingerprint, implied_time_range_from_exprs};
use crate::read::read_columns::ReadColumns;
use crate::read::scan_util::PartitionMetricsList;
use crate::read::seq_scan::SeqScan;
use crate::read::series_scan::SeriesScan;
use crate::read::stream::ScanBatchStream;
@@ -175,7 +179,7 @@ impl Scanner {
/// Sets the target partitions for the scanner. It can controls the parallelism of the scanner.
pub(crate) fn set_target_partitions(&mut self, target_partitions: usize) {
use store_api::region_engine::{PrepareRequest, RegionScanner};
use store_api::region_engine::PrepareRequest;
let request = PrepareRequest::default().with_target_partitions(target_partitions);
match self {
@@ -2329,8 +2333,42 @@ impl StreamContext {
.collect()
}
/// Formats a region scanner for an EXPLAIN plan.
pub(crate) fn format_scan(
&self,
scanner: &dyn RegionScanner,
metrics: &PartitionMetricsList,
mode: Option<&str>,
format: DisplayFormatType,
f: &mut fmt::Formatter,
) -> fmt::Result {
let name = scanner.name();
let region = self.input.mapper.metadata().region_id;
match format {
DisplayFormatType::TreeRender => {
let partitions = scanner.properties().num_partitions();
write!(f, "{name}\nregion={region}\npartitions={partitions}")?;
if let Some(mode) = mode {
write!(f, "\nmode={mode}")?;
}
}
DisplayFormatType::Default | DisplayFormatType::Verbose => {
let verbose = matches!(format, DisplayFormatType::Verbose);
write!(f, "{name}: region={region}, ")?;
self.format_for_explain(verbose, f)?;
if let Some(mode) = mode {
write!(f, r#", "mode":"{mode}""#)?;
}
if verbose {
metrics.format_verbose_metrics(f)?;
}
}
}
Ok(())
}
/// Format the context for explain.
pub(crate) fn format_for_explain(&self, verbose: bool, f: &mut fmt::Formatter) -> fmt::Result {
fn format_for_explain(&self, verbose: bool, f: &mut fmt::Formatter) -> fmt::Result {
let (mut num_mem_ranges, mut num_file_ranges, mut num_other_ranges) = (0, 0, 0);
for range_meta in &self.ranges {
for idx in &range_meta.row_group_indices {
+2 -15
View File
@@ -772,21 +772,8 @@ impl RegionScanner for SeqScan {
impl DisplayAs for SeqScan {
fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"SeqScan: region={}, ",
self.stream_ctx.input.mapper.metadata().region_id
)?;
match t {
// TODO(LFC): Implement all the "TreeRender" display format.
DisplayFormatType::Default | DisplayFormatType::TreeRender => {
self.stream_ctx.format_for_explain(false, f)
}
DisplayFormatType::Verbose => {
self.stream_ctx.format_for_explain(true, f)?;
self.metrics_list.format_verbose_metrics(f)
}
}
self.stream_ctx
.format_scan(self, &self.metrics_list, None, t, f)
}
}
+2 -18
View File
@@ -916,24 +916,8 @@ impl RegionScanner for SeriesScan {
impl DisplayAs for SeriesScan {
fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"SeriesScan: region={}, ",
self.stream_ctx.input.mapper.metadata().region_id
)?;
match t {
DisplayFormatType::Default | DisplayFormatType::TreeRender => {
self.stream_ctx.format_for_explain(false, f)?;
}
DisplayFormatType::Verbose => {
self.stream_ctx.format_for_explain(true, f)?;
}
}
write!(f, ", \"mode\":\"{}\"", self.mode.as_str())?;
if matches!(t, DisplayFormatType::Verbose) {
self.metrics_list.format_verbose_metrics(f)?;
}
Ok(())
self.stream_ctx
.format_scan(self, &self.metrics_list, Some(self.mode.as_str()), t, f)
}
}
+2 -14
View File
@@ -384,20 +384,8 @@ impl RegionScanner for UnorderedScan {
impl DisplayAs for UnorderedScan {
fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"UnorderedScan: region={}, ",
self.stream_ctx.input.mapper.metadata().region_id
)?;
match t {
DisplayFormatType::Default | DisplayFormatType::TreeRender => {
self.stream_ctx.format_for_explain(false, f)
}
DisplayFormatType::Verbose => {
self.stream_ctx.format_for_explain(true, f)?;
self.metrics_list.format_verbose_metrics(f)
}
}
self.stream_ctx
.format_scan(self, &self.metrics_list, None, t, f)
}
}