Skip to main content

common_recordbatch/
adapter.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::{self, Display};
16use std::future::Future;
17use std::marker::PhantomData;
18use std::pin::Pin;
19use std::str::FromStr;
20use std::sync::atomic::{AtomicU64, Ordering};
21use std::sync::{Arc, Mutex};
22use std::task::{Context, Poll};
23
24use common_base::readable_size::ReadableSize;
25use common_error::ext::BoxedError;
26use common_telemetry::tracing::{Span, info_span};
27use common_time::util::format_nanoseconds_human_readable;
28use datafusion::arrow::compute::cast;
29use datafusion::arrow::datatypes::SchemaRef as DfSchemaRef;
30use datafusion::error::Result as DfResult;
31use datafusion::execution::context::ExecutionProps;
32use datafusion::logical_expr::Expr;
33use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
34use datafusion::logical_expr::utils::conjunction;
35use datafusion::physical_expr::create_physical_expr;
36use datafusion::physical_plan::metrics::{BaselineMetrics, CustomMetricValue, MetricValue};
37use datafusion::physical_plan::{
38    DisplayFormatType, ExecutionPlan, ExecutionPlanVisitor, PhysicalExpr,
39    RecordBatchStream as DfRecordBatchStream, accept,
40};
41use datafusion_common::arrow::error::ArrowError;
42use datafusion_common::{DataFusionError, ToDFSchema};
43use datatypes::arrow::array::Array;
44use datatypes::arrow::datatypes::DataType as ArrowDataType;
45use datatypes::schema::{ColumnExtType, Schema, SchemaRef};
46use futures::ready;
47use jsonb;
48use pin_project::pin_project;
49use snafu::ResultExt;
50
51use crate::error::{self, Result};
52use crate::filter::batch_filter;
53use crate::{
54    DfRecordBatch, DfSendableRecordBatchStream, OrderOption, RecordBatch, RecordBatchStream,
55    SendableRecordBatchStream, Stream,
56};
57
58const REGION_SCAN_EXEC_NAME: &str = "RegionScanExec";
59pub const SERIES_SCAN_EXEC_NAME: &str = "SeriesScanExec";
60
61type FutureStream =
62    Pin<Box<dyn std::future::Future<Output = Result<SendableRecordBatchStream>> + Send>>;
63
64/// Casts the `RecordBatch`es of `stream` against the `output_schema`.
65#[pin_project]
66pub struct RecordBatchStreamTypeAdapter<T, E> {
67    #[pin]
68    stream: T,
69    projected_schema: DfSchemaRef,
70    projection: Vec<usize>,
71    predicate: Option<Arc<dyn PhysicalExpr>>,
72    phantom: PhantomData<E>,
73}
74
75impl<T, E> RecordBatchStreamTypeAdapter<T, E>
76where
77    T: Stream<Item = std::result::Result<DfRecordBatch, E>>,
78    E: std::error::Error + Send + Sync + 'static,
79{
80    pub fn new(projected_schema: DfSchemaRef, stream: T, projection: Option<Vec<usize>>) -> Self {
81        let projection = if let Some(projection) = projection {
82            projection
83        } else {
84            (0..projected_schema.fields().len()).collect()
85        };
86
87        Self {
88            stream,
89            projected_schema,
90            projection,
91            predicate: None,
92            phantom: Default::default(),
93        }
94    }
95
96    pub fn with_filter(mut self, filters: Vec<Expr>) -> Result<Self> {
97        let filters = if let Some(expr) = conjunction(filters) {
98            let df_schema = self
99                .projected_schema
100                .clone()
101                .to_dfschema_ref()
102                .context(error::PhysicalExprSnafu)?;
103
104            let filters = create_physical_expr(
105                &expr,
106                &df_schema,
107                &ExecutionProps::new(),
108                &PhysicalPlanningContext::default(),
109            )
110            .context(error::PhysicalExprSnafu)?;
111            Some(filters)
112        } else {
113            None
114        };
115        self.predicate = filters;
116        Ok(self)
117    }
118}
119
120impl<T, E> DfRecordBatchStream for RecordBatchStreamTypeAdapter<T, E>
121where
122    T: Stream<Item = std::result::Result<DfRecordBatch, E>>,
123    E: std::error::Error + Send + Sync + 'static,
124{
125    fn schema(&self) -> DfSchemaRef {
126        self.projected_schema.clone()
127    }
128}
129
130impl<T, E> Stream for RecordBatchStreamTypeAdapter<T, E>
131where
132    T: Stream<Item = std::result::Result<DfRecordBatch, E>>,
133    E: std::error::Error + Send + Sync + 'static,
134{
135    type Item = DfResult<DfRecordBatch>;
136
137    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
138        let this = self.project();
139
140        let batch = futures::ready!(this.stream.poll_next(cx))
141            .map(|r| r.map_err(|e| DataFusionError::External(Box::new(e))));
142
143        let projected_schema = this.projected_schema.clone();
144        let projection = this.projection.clone();
145        let predicate = this.predicate.clone();
146
147        let batch = batch.map(|b| {
148            b.and_then(|b| {
149                let projected_column = b.project(&projection)?;
150                if projected_column.schema().fields.len() != projected_schema.fields.len() {
151                   return Err(DataFusionError::ArrowError(Box::new(ArrowError::SchemaError(format!(
152                        "Trying to cast a RecordBatch into an incompatible schema. RecordBatch: {}, Target: {}",
153                        projected_column.schema(),
154                        projected_schema,
155                    ))), None));
156                }
157
158                let mut columns = Vec::with_capacity(projected_schema.fields.len());
159                for (idx,field) in projected_schema.fields.iter().enumerate() {
160                    let column = projected_column.column(idx);
161                    let extype = field.metadata().get("greptime:type").and_then(|s| ColumnExtType::from_str(s).ok());
162                    let output = custom_cast(&column, field.data_type(), extype)?;
163                    columns.push(output)
164                }
165                let record_batch = DfRecordBatch::try_new(projected_schema, columns)?;
166                let record_batch = if let Some(predicate) = predicate {
167                    batch_filter(&record_batch, &predicate)?
168                } else {
169                    record_batch
170                };
171                Ok(record_batch)
172            })
173        });
174
175        Poll::Ready(batch)
176    }
177
178    #[inline]
179    fn size_hint(&self) -> (usize, Option<usize>) {
180        self.stream.size_hint()
181    }
182}
183
184/// Greptime SendableRecordBatchStream -> DataFusion RecordBatchStream.
185/// The reverse one is [RecordBatchStreamAdapter].
186pub struct DfRecordBatchStreamAdapter {
187    stream: SendableRecordBatchStream,
188}
189
190impl DfRecordBatchStreamAdapter {
191    pub fn new(stream: SendableRecordBatchStream) -> Self {
192        Self { stream }
193    }
194}
195
196impl DfRecordBatchStream for DfRecordBatchStreamAdapter {
197    fn schema(&self) -> DfSchemaRef {
198        self.stream.schema().arrow_schema().clone()
199    }
200}
201
202impl Stream for DfRecordBatchStreamAdapter {
203    type Item = DfResult<DfRecordBatch>;
204
205    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
206        match Pin::new(&mut self.stream).poll_next(cx) {
207            Poll::Pending => Poll::Pending,
208            Poll::Ready(Some(recordbatch)) => match recordbatch {
209                Ok(recordbatch) => Poll::Ready(Some(Ok(recordbatch.into_df_record_batch()))),
210                Err(e) => Poll::Ready(Some(Err(DataFusionError::External(Box::new(
211                    BoxedError::new(e),
212                ))))),
213            },
214            Poll::Ready(None) => Poll::Ready(None),
215        }
216    }
217
218    #[inline]
219    fn size_hint(&self) -> (usize, Option<usize>) {
220        self.stream.size_hint()
221    }
222}
223
224/// DataFusion [SendableRecordBatchStream](DfSendableRecordBatchStream) -> Greptime [RecordBatchStream].
225/// The reverse one is [DfRecordBatchStreamAdapter].
226/// It can collect metrics from DataFusion execution plan.
227pub struct RecordBatchStreamAdapter {
228    schema: SchemaRef,
229    stream: DfSendableRecordBatchStream,
230    metrics: Option<BaselineMetrics>,
231    /// Aggregated plan-level metrics. Resolved after an [ExecutionPlan] is finished.
232    metrics_2: Metrics,
233    query_load_region_id: Option<u64>,
234    query_stat_counters: Option<RegionQueryStatCounters>,
235    /// Display plan and metrics in verbose mode.
236    explain_verbose: bool,
237    span: Span,
238}
239
240/// Query statistic counters owned by a region.
241#[derive(Debug, Clone)]
242pub struct RegionQueryStatCounters {
243    /// The total query CPU time in nanoseconds.
244    pub query_cpu_time: Arc<AtomicU64>,
245    /// The total scanned bytes.
246    pub query_scanned_bytes: Arc<AtomicU64>,
247}
248
249/// Json encoded metrics. Contains metric from a whole plan tree.
250enum Metrics {
251    Unavailable,
252    Unresolved(Arc<dyn ExecutionPlan>),
253    PartialResolved(Arc<dyn ExecutionPlan>, RecordBatchMetrics),
254    Resolved(RecordBatchMetrics),
255}
256
257impl RecordBatchStreamAdapter {
258    pub fn try_new(stream: DfSendableRecordBatchStream) -> Result<Self> {
259        let schema =
260            Arc::new(Schema::try_from(stream.schema()).context(error::SchemaConversionSnafu)?);
261        Ok(Self {
262            schema,
263            stream,
264            metrics: None,
265            metrics_2: Metrics::Unavailable,
266            query_load_region_id: None,
267            query_stat_counters: None,
268            explain_verbose: false,
269            span: Span::current(),
270        })
271    }
272
273    pub fn try_new_with_span(stream: DfSendableRecordBatchStream, span: Span) -> Result<Self> {
274        let schema =
275            Arc::new(Schema::try_from(stream.schema()).context(error::SchemaConversionSnafu)?);
276        let subspan = info_span!(parent: &span, "RecordBatchStreamAdapter");
277        Ok(Self {
278            schema,
279            stream,
280            metrics: None,
281            metrics_2: Metrics::Unavailable,
282            query_load_region_id: None,
283            query_stat_counters: None,
284            explain_verbose: false,
285            span: subspan,
286        })
287    }
288
289    pub fn set_metrics2(&mut self, plan: Arc<dyn ExecutionPlan>) {
290        self.metrics_2 = Metrics::Unresolved(plan)
291    }
292
293    fn record_query_stats_on_drop(&self) {
294        let Some(counters) = &self.query_stat_counters else {
295            return;
296        };
297
298        match &self.metrics_2 {
299            Metrics::Unresolved(df_plan) => {
300                let metrics = collect_lightweight_query_load_metrics(
301                    df_plan.as_ref(),
302                    self.query_load_region_id,
303                );
304                record_query_stats(counters, &metrics);
305            }
306            Metrics::PartialResolved(_, metrics) | Metrics::Resolved(metrics) => {
307                record_query_stats(counters, metrics);
308            }
309            Metrics::Unavailable => {}
310        }
311    }
312
313    pub fn set_query_load_region_id(&mut self, region_id: Option<u64>) {
314        self.query_load_region_id = region_id;
315    }
316
317    pub fn set_query_stat_counters(&mut self, counters: Option<RegionQueryStatCounters>) {
318        self.query_stat_counters = counters;
319    }
320
321    /// Set the verbose mode for displaying plan and metrics.
322    pub fn set_explain_verbose(&mut self, verbose: bool) {
323        self.explain_verbose = verbose;
324    }
325
326    fn collect_plan_metrics(&self, df_plan: &Arc<dyn ExecutionPlan>) -> RecordBatchMetrics {
327        collect_full_metrics(
328            df_plan.as_ref(),
329            self.explain_verbose,
330            self.query_load_region_id,
331        )
332    }
333
334    fn collect_partial_metrics(
335        df_plan: &dyn ExecutionPlan,
336        explain_verbose: bool,
337        query_load_region_id: Option<u64>,
338    ) -> RecordBatchMetrics {
339        if explain_verbose {
340            // Verbose in-progress snapshots have the same complete topology as
341            // the final snapshot, but use compact (Default) plan formatting.
342            collect_full_metrics(df_plan, false, query_load_region_id)
343        } else {
344            collect_lightweight_query_load_metrics(df_plan, query_load_region_id)
345        }
346    }
347
348    fn update_plan_metrics(&mut self, final_metrics: bool) {
349        if final_metrics {
350            let df_plan = match &self.metrics_2 {
351                Metrics::Unresolved(df_plan) | Metrics::PartialResolved(df_plan, _) => {
352                    df_plan.clone()
353                }
354                Metrics::Unavailable | Metrics::Resolved(_) => return,
355            };
356            let metrics = self.collect_plan_metrics(&df_plan);
357            self.metrics_2 = Metrics::Resolved(metrics);
358        } else {
359            let explain_verbose = self.explain_verbose;
360            let query_load_region_id = self.query_load_region_id;
361            match &mut self.metrics_2 {
362                Metrics::Unresolved(df_plan) => {
363                    let df_plan = df_plan.clone();
364                    let metrics = Self::collect_partial_metrics(
365                        df_plan.as_ref(),
366                        explain_verbose,
367                        query_load_region_id,
368                    );
369                    self.metrics_2 = Metrics::PartialResolved(df_plan, metrics);
370                }
371                Metrics::PartialResolved(df_plan, metrics) => {
372                    *metrics = Self::collect_partial_metrics(
373                        df_plan.as_ref(),
374                        explain_verbose,
375                        query_load_region_id,
376                    );
377                }
378                Metrics::Unavailable | Metrics::Resolved(_) => {}
379            }
380        }
381    }
382}
383
384fn is_region_scan_name(name: &str) -> bool {
385    name == REGION_SCAN_EXEC_NAME || name == SERIES_SCAN_EXEC_NAME
386}
387
388/// Extracts total `output_bytes` from region scan plan nodes.
389pub fn region_scan_output_bytes(metrics: &RecordBatchMetrics) -> usize {
390    metrics
391        .plan_metrics
392        .iter()
393        .filter(|pm| is_region_scan_name(&pm.plan_name))
394        .flat_map(|pm| &pm.metrics)
395        .filter_map(|(name, value)| (name == "output_bytes").then_some(*value))
396        .sum()
397}
398
399fn record_query_stats(counters: &RegionQueryStatCounters, metrics: &RecordBatchMetrics) {
400    counters
401        .query_cpu_time
402        .fetch_add(metrics.elapsed_compute as u64, Ordering::Relaxed);
403    counters
404        .query_scanned_bytes
405        .fetch_add(region_scan_output_bytes(metrics) as u64, Ordering::Relaxed);
406}
407
408/// Collects the complete plan metrics used by terminal metrics and verbose analyze output.
409fn collect_full_metrics(
410    df_plan: &dyn ExecutionPlan,
411    explain_verbose: bool,
412    query_load_region_id: Option<u64>,
413) -> RecordBatchMetrics {
414    let mut metric_collector = MetricCollector::new(explain_verbose);
415    accept(df_plan, &mut metric_collector).unwrap();
416    metric_collector.record_batch_metrics.query_load_region_id = query_load_region_id;
417    metric_collector.record_batch_metrics
418}
419
420/// Collects the minimal metrics needed for query-load reporting before EOF.
421///
422/// This intentionally avoids [`MetricCollector`]'s full per-plan aggregation,
423/// sorting, and plan formatting work on the normal query hot path. The result
424/// is still enough for early-stop/cancellation paths to report per-region CPU
425/// time, scanned bytes, and physical-region attribution.
426fn collect_lightweight_query_load_metrics(
427    df_plan: &dyn ExecutionPlan,
428    query_load_region_id: Option<u64>,
429) -> RecordBatchMetrics {
430    let mut metrics = RecordBatchMetrics {
431        query_load_region_id,
432        ..Default::default()
433    };
434    collect_lightweight_query_load_metrics_inner(df_plan, 0, &mut metrics);
435    metrics
436}
437
438/// Recursively walks the physical plan and reads raw metric values without
439/// formatting plan nodes.
440fn collect_lightweight_query_load_metrics_inner(
441    df_plan: &dyn ExecutionPlan,
442    level: usize,
443    record_batch_metrics: &mut RecordBatchMetrics,
444) {
445    let is_region_scan = is_region_scan_name(df_plan.name());
446    let mut region_scan_output_bytes = None;
447
448    if let Some(metrics) = df_plan.metrics() {
449        for metric in metrics.iter() {
450            let value = metric.value();
451            match value {
452                MetricValue::ElapsedCompute(elapsed_compute) => {
453                    record_batch_metrics.elapsed_compute += elapsed_compute.value();
454                }
455                MetricValue::CurrentMemoryUsage(memory_usage) => {
456                    record_batch_metrics.memory_usage += memory_usage.value();
457                }
458                _ => {}
459            }
460
461            if is_region_scan && value.name() == "output_bytes" {
462                *region_scan_output_bytes.get_or_insert(0) += value.as_usize();
463            }
464        }
465    }
466
467    if let Some(output_bytes) = region_scan_output_bytes {
468        record_batch_metrics.plan_metrics.push(PlanMetrics {
469            plan: df_plan.name().to_string(),
470            plan_name: df_plan.name().to_string(),
471            level,
472            metrics: vec![("output_bytes".to_string(), output_bytes)],
473            native: None,
474        });
475    }
476
477    for child in df_plan.children() {
478        collect_lightweight_query_load_metrics_inner(
479            child.as_ref(),
480            level + 1,
481            record_batch_metrics,
482        );
483    }
484}
485
486impl RecordBatchStream for RecordBatchStreamAdapter {
487    fn name(&self) -> &str {
488        "RecordBatchStreamAdapter"
489    }
490
491    fn schema(&self) -> SchemaRef {
492        self.schema.clone()
493    }
494
495    fn metrics(&self) -> Option<RecordBatchMetrics> {
496        match &self.metrics_2 {
497            Metrics::Unresolved(df_plan) => {
498                if self.explain_verbose {
499                    Some(Self::collect_partial_metrics(
500                        df_plan.as_ref(),
501                        true,
502                        self.query_load_region_id,
503                    ))
504                } else {
505                    None
506                }
507            }
508            Metrics::PartialResolved(df_plan, metrics) => Some(if self.explain_verbose {
509                Self::collect_partial_metrics(df_plan.as_ref(), true, self.query_load_region_id)
510            } else {
511                metrics.clone()
512            }),
513            Metrics::Resolved(metrics) => Some(metrics.clone()),
514            Metrics::Unavailable => None,
515        }
516    }
517
518    fn output_ordering(&self) -> Option<&[OrderOption]> {
519        None
520    }
521}
522
523impl Stream for RecordBatchStreamAdapter {
524    type Item = Result<RecordBatch>;
525
526    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
527        let timer = self
528            .metrics
529            .as_ref()
530            .map(|m| m.elapsed_compute().clone())
531            .unwrap_or_default();
532        let _guard = timer.timer();
533        let poll_span = info_span!(parent: &self.span, "poll_next");
534        let _entered = poll_span.enter();
535        match Pin::new(&mut self.stream).poll_next(cx) {
536            Poll::Pending => Poll::Pending,
537            Poll::Ready(Some(df_record_batch)) => {
538                let df_record_batch = df_record_batch?;
539                self.update_plan_metrics(false);
540                Poll::Ready(Some(Ok(RecordBatch::from_df_record_batch(
541                    self.schema(),
542                    df_record_batch,
543                ))))
544            }
545            Poll::Ready(None) => {
546                self.update_plan_metrics(true);
547                Poll::Ready(None)
548            }
549        }
550    }
551
552    #[inline]
553    fn size_hint(&self) -> (usize, Option<usize>) {
554        self.stream.size_hint()
555    }
556}
557
558impl Drop for RecordBatchStreamAdapter {
559    fn drop(&mut self) {
560        self.record_query_stats_on_drop();
561    }
562}
563
564/// An [ExecutionPlanVisitor] to collect metrics from a [ExecutionPlan].
565pub struct MetricCollector {
566    current_level: usize,
567    pub record_batch_metrics: RecordBatchMetrics,
568    verbose: bool,
569}
570
571impl MetricCollector {
572    pub fn new(verbose: bool) -> Self {
573        Self {
574            current_level: 0,
575            record_batch_metrics: RecordBatchMetrics::default(),
576            verbose,
577        }
578    }
579}
580
581impl ExecutionPlanVisitor for MetricCollector {
582    type Error = std::convert::Infallible;
583
584    fn pre_visit(&mut self, plan: &dyn ExecutionPlan) -> std::result::Result<bool, Self::Error> {
585        // skip if no metric available
586        let Some(metric) = plan.metrics() else {
587            self.record_batch_metrics.plan_metrics.push(PlanMetrics {
588                plan: plan.name().to_string(),
589                plan_name: plan.name().to_string(),
590                level: self.current_level,
591                metrics: vec![],
592                native: None,
593            });
594            self.current_level += 1;
595            return Ok(true);
596        };
597
598        // scrape plan metrics
599        let metric = metric
600            .aggregate_by_name()
601            .sorted_for_display()
602            .timestamps_removed();
603        let mut plan_metric = PlanMetrics {
604            plan: one_line(plan, self.verbose).to_string(),
605            plan_name: plan.name().to_string(),
606            level: self.current_level,
607            metrics: Vec::with_capacity(metric.iter().size_hint().0),
608            native: None,
609        };
610        for m in metric.iter() {
611            // An operator that runs nodes inside itself registers the tree as one of its metric
612            // values. It travels here, where a plain value cannot: the tree is structure, not a
613            // figure, so it is reported apart from the flat list instead of being flattened into it.
614            if let MetricValue::Custom { name, value } = m.value()
615                && name.as_ref() == NATIVE_TREE_METRIC
616            {
617                if let Some(tree) = value.as_any().downcast_ref::<NativeTreeMetric>() {
618                    plan_metric.native = Some(tree.report());
619                }
620                continue;
621            }
622            plan_metric
623                .metrics
624                .push((m.value().name().to_string(), m.value().as_usize()));
625
626            // aggregate high-level metrics
627            match m.value() {
628                MetricValue::ElapsedCompute(ec) => {
629                    self.record_batch_metrics.elapsed_compute += ec.value()
630                }
631                MetricValue::CurrentMemoryUsage(m) => {
632                    self.record_batch_metrics.memory_usage += m.value()
633                }
634                _ => {}
635            }
636        }
637        self.record_batch_metrics.plan_metrics.push(plan_metric);
638
639        self.current_level += 1;
640        Ok(true)
641    }
642
643    fn post_visit(&mut self, _plan: &dyn ExecutionPlan) -> std::result::Result<bool, Self::Error> {
644        self.current_level -= 1;
645        Ok(true)
646    }
647}
648
649/// Returns a single-line summary of the root of the plan.
650/// If the `verbose` flag is set, it will display detailed information about the plan.
651fn one_line(plan: &dyn ExecutionPlan, verbose: bool) -> impl fmt::Display + '_ {
652    struct Wrapper<'a> {
653        plan: &'a dyn ExecutionPlan,
654        format_type: DisplayFormatType,
655    }
656
657    impl fmt::Display for Wrapper<'_> {
658        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659            self.plan.fmt_as(self.format_type, f)?;
660            writeln!(f)
661        }
662    }
663
664    let format_type = if verbose {
665        DisplayFormatType::Verbose
666    } else {
667        DisplayFormatType::Default
668    };
669    Wrapper { plan, format_type }
670}
671
672/// [`RecordBatchMetrics`] carrys metrics value
673/// from datanode to frontend through gRPC
674#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
675pub struct RecordBatchMetrics {
676    // High-level aggregated metrics
677    /// CPU consumption in nanoseconds
678    pub elapsed_compute: usize,
679    /// Memory used by the plan in bytes
680    pub memory_usage: usize,
681    // Detailed per-plan metrics
682    /// An ordered list of plan metrics, from top to bottom in post-order.
683    pub plan_metrics: Vec<PlanMetrics>,
684    /// Region id that should receive query-load metrics for this scan.
685    #[serde(default, skip_serializing_if = "Option::is_none")]
686    pub query_load_region_id: Option<u64>,
687    /// Per-region watermark for incremental-read checkpoint advancement.
688    ///
689    /// The watermark is the latest sequence (`seq`) this query round safely read
690    /// for each participating region. Flow uses it to decide where the next
691    /// incremental round can resume.
692    ///
693    /// - `Some(seq)`: the query proved it safely read up to `seq`; downstream
694    ///   may advance the checkpoint to this value.
695    /// - `None`: the region participated but the query could not prove a safe
696    ///   read upper-bound, so the checkpoint must not advance for this region.
697    ///
698    /// Omitted when empty for backward compatibility.
699    #[serde(default, skip_serializing_if = "Vec::is_empty")]
700    pub region_watermarks: Vec<RegionWatermarkEntry>,
701}
702
703#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
704pub struct RegionWatermarkEntry {
705    pub region_id: u64,
706    #[serde(default, skip_serializing_if = "Option::is_none")]
707    pub watermark: Option<u64>,
708}
709
710/// Determines if a metric name represents a time measurement that should be formatted.
711pub fn is_time_metric(metric_name: &str) -> bool {
712    metric_name.contains("elapsed") || metric_name.contains("time") || metric_name.contains("cost")
713}
714
715/// Determines if a metric name represents a bytes measurement that should be formatted.
716pub fn is_bytes_metric(metric_name: &str) -> bool {
717    metric_name.contains("bytes") || metric_name.contains("mem")
718}
719
720/// Renders `bytes` the way a plan line reports a memory figure.
721pub fn format_bytes_human_readable(bytes: usize) -> String {
722    format!("{}", ReadableSize(bytes as u64))
723}
724
725/// Renders one metric as `label: value`, the way every `ANALYZE` line reports it.
726///
727/// A time is a readable duration, a byte count a readable size, and anything else a plain integer.
728/// This is the one formatter for a plan line, so a node rendered by its own operator and a node
729/// rendered by the collector read alike.
730pub fn format_metric(label: &str, value: usize) -> String {
731    if is_time_metric(label) {
732        format!("{}: {}", label, format_nanoseconds_human_readable(value))
733    } else if is_bytes_metric(label) {
734        format!("{}: {}", label, format_bytes_human_readable(value))
735    } else {
736        format!("{}: {}", label, value)
737    }
738}
739
740/// Only display `plan_metrics` with indent `  ` (2 spaces).
741///
742/// An operator's own figures go at the end of its own line, which is the line that names it. An
743/// operator whose line continues - one that renders the nodes it runs below itself - therefore
744/// keeps those figures rather than receiving every figure of the subtree it drew, and the lines it
745/// drew keep the figures and the indentation they were rendered with, shifted to sit under it.
746impl Display for RecordBatchMetrics {
747    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
748        for metric in &self.plan_metrics {
749            let indent = metric.level * 2;
750            let mut lines = metric.plan.trim_end().lines();
751            write!(
752                f,
753                "{:indent$}{} metrics=[",
754                " ",
755                lines.next().unwrap_or_default(),
756            )?;
757            for (label, value) in &metric.metrics {
758                write!(f, "{}, ", format_metric(label, *value))?;
759            }
760            writeln!(f, "]")?;
761            for line in lines {
762                writeln!(f, "{:indent$}{line}", " ")?;
763            }
764        }
765
766        Ok(())
767    }
768}
769
770#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
771pub struct PlanMetrics {
772    /// The plan name
773    pub plan: String,
774    /// The stable execution plan name.
775    #[serde(default)]
776    pub plan_name: String,
777    /// The level of the plan, starts from 0
778    pub level: usize,
779    /// An ordered key-value list of metrics.
780    /// Key is metric label and value is metric value.
781    pub metrics: Vec<(String, usize)>,
782    /// The tree of nodes an operator runs inside itself, when it runs one.
783    ///
784    /// Such an operator reports its own figures through `metrics` and each node it runs through
785    /// this: they are not the same operator, so they are not the same entry. Absent for every other
786    /// operator, and for a record written before this field existed.
787    #[serde(default, skip_serializing_if = "Option::is_none")]
788    pub native: Option<NativeTreeMetrics>,
789}
790
791/// One node of a tree an operator runs inside itself, with the figures that node recorded.
792///
793/// The shape is the plan line's own: the node's line without figures, the figures, and the nodes
794/// that consume its output, in the order the operator feeds them.
795#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone, PartialEq, Eq)]
796pub struct NativeTreeMetrics {
797    /// The node's line without figures, as `<kind>: <what it computes>`.
798    pub line: String,
799    /// An ordered key-value list of the figures this node recorded.
800    #[serde(default)]
801    pub metrics: Vec<(String, usize)>,
802    /// The nodes that consume this one's output.
803    #[serde(default)]
804    pub children: Vec<NativeTreeMetrics>,
805}
806
807/// Builds the tree a reader sees, when it asks for it.
808type NativeTreeReader = Arc<dyn Fn() -> NativeTreeMetrics + Send + Sync>;
809
810/// The tree an operator runs, registered as one of that operator's metrics.
811///
812/// It is a metric value so it travels with the operator's own figures through the same collection
813/// and the same record: a plan's figures are only final once it ran, which is when `ANALYZE` reads
814/// them, so what is registered is how to read the tree rather than a copy of it.
815pub struct NativeTreeMetric {
816    /// Reads the tree as it is now. `None` for a value created to accumulate a combination.
817    reader: Option<NativeTreeReader>,
818    /// A report this value took over while combining with another, which wins over `reader`.
819    adopted: Mutex<Option<NativeTreeMetrics>>,
820}
821
822/// The name an operator registers its tree under.
823///
824/// It carries the same `native.` prefix as the per-node figures so a reader that lists an
825/// operator's own figures leaves it out.
826pub const NATIVE_TREE_METRIC: &str = "native.tree";
827
828impl NativeTreeMetric {
829    /// Registers `reader` as the way to read the tree when it is asked for.
830    pub fn new(reader: impl Fn() -> NativeTreeMetrics + Send + Sync + 'static) -> Self {
831        Self {
832            reader: Some(Arc::new(reader)),
833            adopted: Mutex::new(None),
834        }
835    }
836
837    /// The tree with the figures it has now.
838    pub fn report(&self) -> NativeTreeMetrics {
839        if let Some(adopted) = self
840            .adopted
841            .lock()
842            .unwrap_or_else(|poisoned| poisoned.into_inner())
843            .clone()
844        {
845            return adopted;
846        }
847        self.reader
848            .as_ref()
849            .map_or_else(NativeTreeMetrics::default, |reader| reader())
850    }
851}
852
853impl std::fmt::Display for NativeTreeMetric {
854    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
855        write!(f, "a tree of {} nodes", self.report().node_count())
856    }
857}
858
859impl std::fmt::Debug for NativeTreeMetric {
860    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
861        f.debug_struct("NativeTreeMetric").finish_non_exhaustive()
862    }
863}
864
865impl NativeTreeMetrics {
866    /// How many nodes this node and everything below it cover.
867    pub fn node_count(&self) -> usize {
868        1 + self
869            .children
870            .iter()
871            .map(NativeTreeMetrics::node_count)
872            .sum::<usize>()
873    }
874}
875
876impl CustomMetricValue for NativeTreeMetric {
877    /// A value to accumulate a combination into: it holds nothing until it combines with one.
878    fn new_empty(&self) -> Arc<dyn CustomMetricValue> {
879        Arc::new(Self {
880            reader: None,
881            adopted: Mutex::new(None),
882        })
883    }
884
885    /// Combining takes the report of `other`, because one operator registers one tree: what a
886    /// combination of two registrations would mean is not defined, and cannot happen today.
887    fn aggregate(&self, other: Arc<dyn CustomMetricValue + 'static>) {
888        let Some(other) = other.as_any().downcast_ref::<Self>() else {
889            return;
890        };
891        *self
892            .adopted
893            .lock()
894            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(other.report());
895    }
896
897    fn as_any(&self) -> &dyn std::any::Any {
898        self
899    }
900
901    fn is_eq(&self, other: &Arc<dyn CustomMetricValue>) -> bool {
902        other
903            .as_any()
904            .downcast_ref::<Self>()
905            .is_some_and(|other| other.report() == self.report())
906    }
907}
908
909enum AsyncRecordBatchStreamAdapterState {
910    Uninit(FutureStream),
911    Ready(SendableRecordBatchStream),
912    Failed,
913}
914
915pub struct AsyncRecordBatchStreamAdapter {
916    schema: SchemaRef,
917    state: AsyncRecordBatchStreamAdapterState,
918}
919
920impl AsyncRecordBatchStreamAdapter {
921    pub fn new(schema: SchemaRef, stream: FutureStream) -> Self {
922        Self {
923            schema,
924            state: AsyncRecordBatchStreamAdapterState::Uninit(stream),
925        }
926    }
927}
928
929impl RecordBatchStream for AsyncRecordBatchStreamAdapter {
930    fn schema(&self) -> SchemaRef {
931        self.schema.clone()
932    }
933
934    fn output_ordering(&self) -> Option<&[OrderOption]> {
935        None
936    }
937
938    fn metrics(&self) -> Option<RecordBatchMetrics> {
939        None
940    }
941}
942
943impl Stream for AsyncRecordBatchStreamAdapter {
944    type Item = Result<RecordBatch>;
945
946    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
947        loop {
948            match &mut self.state {
949                AsyncRecordBatchStreamAdapterState::Uninit(stream_future) => {
950                    match ready!(Pin::new(stream_future).poll(cx)) {
951                        Ok(stream) => {
952                            self.state = AsyncRecordBatchStreamAdapterState::Ready(stream);
953                            continue;
954                        }
955                        Err(e) => {
956                            self.state = AsyncRecordBatchStreamAdapterState::Failed;
957                            return Poll::Ready(Some(Err(e)));
958                        }
959                    };
960                }
961                AsyncRecordBatchStreamAdapterState::Ready(stream) => {
962                    return Poll::Ready(ready!(Pin::new(stream).poll_next(cx)));
963                }
964                AsyncRecordBatchStreamAdapterState::Failed => return Poll::Ready(None),
965            }
966        }
967    }
968
969    // This is not supported for lazy stream.
970    #[inline]
971    fn size_hint(&self) -> (usize, Option<usize>) {
972        (0, None)
973    }
974}
975
976/// Custom cast function that handles Map -> Binary (JSON) conversion
977fn custom_cast(
978    array: &dyn Array,
979    target_type: &ArrowDataType,
980    extype: Option<ColumnExtType>,
981) -> std::result::Result<Arc<dyn Array>, ArrowError> {
982    if let ArrowDataType::Map(_, _) = array.data_type()
983        && let ArrowDataType::Binary = target_type
984    {
985        return convert_map_to_json_binary(array, extype);
986    }
987
988    cast(array, target_type)
989}
990
991/// Convert a Map array to a Binary array containing JSON data
992fn convert_map_to_json_binary(
993    array: &dyn Array,
994    extype: Option<ColumnExtType>,
995) -> std::result::Result<Arc<dyn Array>, ArrowError> {
996    use datatypes::arrow::array::{BinaryArray, MapArray};
997    use serde_json::Value;
998
999    let map_array = array
1000        .as_any()
1001        .downcast_ref::<MapArray>()
1002        .ok_or_else(|| ArrowError::CastError("Failed to downcast to MapArray".to_string()))?;
1003
1004    let mut json_values = Vec::with_capacity(map_array.len());
1005
1006    for i in 0..map_array.len() {
1007        if map_array.is_null(i) {
1008            json_values.push(None);
1009        } else {
1010            // Extract the map entry at index i
1011            let map_entry = map_array.value(i);
1012            let key_value_array = map_entry
1013                .as_any()
1014                .downcast_ref::<datatypes::arrow::array::StructArray>()
1015                .ok_or_else(|| {
1016                    ArrowError::CastError("Failed to downcast to StructArray".to_string())
1017                })?;
1018
1019            // Convert to JSON object
1020            let mut json_obj = serde_json::Map::with_capacity(key_value_array.len());
1021
1022            for j in 0..key_value_array.len() {
1023                if key_value_array.is_null(j) {
1024                    continue;
1025                }
1026                let key_field = key_value_array.column(0);
1027                let value_field = key_value_array.column(1);
1028
1029                if key_field.is_null(j) {
1030                    continue;
1031                }
1032
1033                let key = key_field
1034                    .as_any()
1035                    .downcast_ref::<datatypes::arrow::array::StringArray>()
1036                    .ok_or_else(|| {
1037                        ArrowError::CastError("Failed to downcast key to StringArray".to_string())
1038                    })?
1039                    .value(j);
1040
1041                let value = if value_field.is_null(j) {
1042                    Value::Null
1043                } else {
1044                    let value_str = value_field
1045                        .as_any()
1046                        .downcast_ref::<datatypes::arrow::array::StringArray>()
1047                        .ok_or_else(|| {
1048                            ArrowError::CastError(
1049                                "Failed to downcast value to StringArray".to_string(),
1050                            )
1051                        })?
1052                        .value(j);
1053                    Value::String(value_str.to_string())
1054                };
1055
1056                json_obj.insert(key.to_string(), value);
1057            }
1058
1059            let json_value = Value::Object(json_obj);
1060            let json_bytes = match extype {
1061                Some(ColumnExtType::Json) => {
1062                    let json_string = match serde_json::to_string(&json_value) {
1063                        Ok(s) => s,
1064                        Err(e) => {
1065                            return Err(ArrowError::CastError(format!(
1066                                "Failed to serialize JSON: {}",
1067                                e
1068                            )));
1069                        }
1070                    };
1071                    match jsonb::parse_value_standard_mode(json_string.as_bytes()) {
1072                        Ok(jsonb_value) => jsonb_value.to_vec(),
1073                        Err(e) => {
1074                            return Err(ArrowError::CastError(format!(
1075                                "Failed to serialize JSONB: {}",
1076                                e
1077                            )));
1078                        }
1079                    }
1080                }
1081                _ => match serde_json::to_vec(&json_value) {
1082                    Ok(b) => b,
1083                    Err(e) => {
1084                        return Err(ArrowError::CastError(format!(
1085                            "Failed to serialize JSON: {}",
1086                            e
1087                        )));
1088                    }
1089                },
1090            };
1091            json_values.push(Some(json_bytes));
1092        }
1093    }
1094
1095    let binary_array = BinaryArray::from_iter(json_values);
1096    Ok(Arc::new(binary_array))
1097}
1098
1099#[cfg(test)]
1100mod test {
1101    use std::collections::VecDeque;
1102    use std::time::Duration;
1103
1104    use common_error::ext::{ErrorExt, PlainError};
1105    use common_error::mock::MockError;
1106    use common_error::status_code::StatusCode;
1107    use datafusion::execution::TaskContext;
1108    use datafusion::physical_expr::{EquivalenceProperties, Partitioning};
1109    use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
1110    use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricBuilder, MetricsSet};
1111    use datafusion::physical_plan::{DisplayAs, PlanProperties};
1112    use datafusion_common::tree_node::TreeNodeRecursion;
1113    use datatypes::arrow::array::{ArrayRef, MapArray, StringArray, StructArray};
1114    use datatypes::arrow::buffer::OffsetBuffer;
1115    use datatypes::arrow::datatypes::Field;
1116    use datatypes::prelude::ConcreteDataType;
1117    use datatypes::schema::ColumnSchema;
1118    use datatypes::vectors::Int32Vector;
1119    use futures::StreamExt;
1120    use serde_json::json;
1121    use snafu::IntoError;
1122
1123    use super::*;
1124    use crate::error::Error;
1125    use crate::{RecordBatchStreamWrapper, RecordBatches};
1126
1127    #[derive(Debug)]
1128    struct TestMetricsExec {
1129        properties: Arc<PlanProperties>,
1130        metrics: ExecutionPlanMetricsSet,
1131        format_plan: bool,
1132        plan_name: &'static str,
1133    }
1134
1135    impl TestMetricsExec {
1136        fn new(schema: DfSchemaRef) -> Self {
1137            Self::with_output_bytes(schema, &[24])
1138        }
1139
1140        fn new_without_plan_formatting(schema: DfSchemaRef) -> Self {
1141            Self::with_output_bytes_and_formatting(schema, &[24], false, REGION_SCAN_EXEC_NAME)
1142        }
1143
1144        fn with_output_bytes(schema: DfSchemaRef, output_bytes_by_partition: &[usize]) -> Self {
1145            Self::with_output_bytes_and_formatting(
1146                schema,
1147                output_bytes_by_partition,
1148                true,
1149                REGION_SCAN_EXEC_NAME,
1150            )
1151        }
1152
1153        fn with_output_bytes_and_formatting(
1154            schema: DfSchemaRef,
1155            output_bytes_by_partition: &[usize],
1156            format_plan: bool,
1157            plan_name: &'static str,
1158        ) -> Self {
1159            let metrics = ExecutionPlanMetricsSet::new();
1160            let elapsed_compute = MetricBuilder::new(&metrics).elapsed_compute(0);
1161            elapsed_compute.add_duration(Duration::from_nanos(42));
1162            for (partition, output_bytes) in output_bytes_by_partition.iter().copied().enumerate() {
1163                let metric = MetricBuilder::new(&metrics).output_bytes(partition);
1164                metric.add(output_bytes);
1165            }
1166
1167            Self {
1168                properties: Arc::new(PlanProperties::new(
1169                    EquivalenceProperties::new(schema),
1170                    Partitioning::UnknownPartitioning(output_bytes_by_partition.len().max(1)),
1171                    EmissionType::Incremental,
1172                    Boundedness::Bounded,
1173                )),
1174                metrics,
1175                format_plan,
1176                plan_name,
1177            }
1178        }
1179    }
1180
1181    impl DisplayAs for TestMetricsExec {
1182        fn fmt_as(&self, t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1183            assert!(
1184                self.format_plan,
1185                "non-verbose lightweight partial metrics must not format the plan"
1186            );
1187            write!(f, "{}", self.plan_name)?;
1188            if matches!(t, DisplayFormatType::Verbose) {
1189                write!(f, ": files=[file-1.parquet]")?;
1190            }
1191            Ok(())
1192        }
1193    }
1194
1195    impl ExecutionPlan for TestMetricsExec {
1196        fn name(&self) -> &str {
1197            self.plan_name
1198        }
1199
1200        fn properties(&self) -> &Arc<PlanProperties> {
1201            &self.properties
1202        }
1203
1204        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
1205            vec![]
1206        }
1207
1208        fn apply_expressions(
1209            &self,
1210            _f: &mut dyn FnMut(
1211                &Arc<dyn PhysicalExpr>,
1212            ) -> datafusion_common::Result<TreeNodeRecursion>,
1213        ) -> datafusion_common::Result<TreeNodeRecursion> {
1214            Ok(TreeNodeRecursion::Continue)
1215        }
1216
1217        fn with_new_children(
1218            self: Arc<Self>,
1219            _children: Vec<Arc<dyn ExecutionPlan>>,
1220        ) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
1221            Ok(self)
1222        }
1223
1224        fn execute(
1225            &self,
1226            _partition: usize,
1227            _context: Arc<TaskContext>,
1228        ) -> datafusion_common::Result<DfSendableRecordBatchStream> {
1229            unreachable!("the test passes a separate stream to RecordBatchStreamAdapter")
1230        }
1231
1232        fn metrics(&self) -> Option<MetricsSet> {
1233            Some(self.metrics.clone_inner())
1234        }
1235    }
1236
1237    #[test]
1238    fn test_lightweight_query_load_metrics_sums_series_scan_output_bytes() {
1239        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1240            "a",
1241            ConcreteDataType::int32_datatype(),
1242            false,
1243        )]));
1244        let plan = TestMetricsExec::with_output_bytes_and_formatting(
1245            schema.arrow_schema().clone(),
1246            &[24, 18],
1247            true,
1248            SERIES_SCAN_EXEC_NAME,
1249        );
1250
1251        let metrics = collect_lightweight_query_load_metrics(&plan, Some(42));
1252
1253        assert_eq!(region_scan_output_bytes(&metrics), 42);
1254        assert_eq!(metrics.plan_metrics[0].plan_name, SERIES_SCAN_EXEC_NAME);
1255
1256        let full_metrics = collect_full_metrics(&plan, false, Some(42));
1257        assert_eq!(region_scan_output_bytes(&full_metrics), 42);
1258    }
1259
1260    #[test]
1261    fn test_lightweight_query_load_metrics_sums_region_scan_output_bytes() {
1262        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1263            "a",
1264            ConcreteDataType::int32_datatype(),
1265            false,
1266        )]));
1267        let plan = TestMetricsExec::with_output_bytes(schema.arrow_schema().clone(), &[24, 18]);
1268
1269        let metrics = collect_lightweight_query_load_metrics(&plan, Some(42));
1270
1271        assert_eq!(metrics.query_load_region_id, Some(42));
1272        assert_eq!(region_scan_output_bytes(&metrics), 42);
1273        assert_eq!(metrics.plan_metrics.len(), 1);
1274        assert_eq!(
1275            metrics.plan_metrics[0].metrics,
1276            vec![("output_bytes".to_string(), 42)]
1277        );
1278    }
1279
1280    #[tokio::test]
1281    async fn test_record_batch_stream_adapter_collects_lightweight_partial_metrics() {
1282        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1283            "a",
1284            ConcreteDataType::int32_datatype(),
1285            false,
1286        )]));
1287        let batch1 = RecordBatch::new(
1288            schema.clone(),
1289            vec![Arc::new(Int32Vector::from_slice([1])) as _],
1290        )
1291        .unwrap()
1292        .into_df_record_batch();
1293        let batch2 = RecordBatch::new(
1294            schema.clone(),
1295            vec![Arc::new(Int32Vector::from_slice([2])) as _],
1296        )
1297        .unwrap()
1298        .into_df_record_batch();
1299        let df_stream = Box::pin(
1300            datafusion::physical_plan::stream::RecordBatchStreamAdapter::new(
1301                schema.arrow_schema().clone(),
1302                futures::stream::iter(vec![Ok(batch1), Ok(batch2)]),
1303            ),
1304        );
1305        let plan = Arc::new(TestMetricsExec::new_without_plan_formatting(
1306            schema.arrow_schema().clone(),
1307        ));
1308
1309        let mut adapter = RecordBatchStreamAdapter::try_new(df_stream).unwrap();
1310        adapter.set_metrics2(plan);
1311        adapter.set_query_load_region_id(Some(42));
1312
1313        assert!(adapter.metrics().is_none());
1314        assert!(adapter.next().await.unwrap().is_ok());
1315        let metrics = adapter
1316            .metrics()
1317            .expect("non-verbose queries need partial query-load metrics before EOF");
1318        assert_eq!(metrics.elapsed_compute, 42);
1319        assert_eq!(metrics.query_load_region_id, Some(42));
1320        assert_eq!(region_scan_output_bytes(&metrics), 24);
1321        assert_eq!(metrics.plan_metrics.len(), 1);
1322        assert_eq!(metrics.plan_metrics[0].plan, REGION_SCAN_EXEC_NAME);
1323        assert_eq!(metrics.plan_metrics[0].plan_name, REGION_SCAN_EXEC_NAME);
1324        assert!(
1325            metrics.plan_metrics[0]
1326                .metrics
1327                .iter()
1328                .any(|(name, value)| name == "output_bytes" && *value == 24)
1329        );
1330    }
1331
1332    #[tokio::test]
1333    async fn test_record_batch_stream_adapter_uses_compact_partial_and_verbose_final_metrics() {
1334        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1335            "a",
1336            ConcreteDataType::int32_datatype(),
1337            false,
1338        )]));
1339        let batch = RecordBatch::new(
1340            schema.clone(),
1341            vec![Arc::new(Int32Vector::from_slice([1])) as _],
1342        )
1343        .unwrap()
1344        .into_df_record_batch();
1345        let df_stream = Box::pin(
1346            datafusion::physical_plan::stream::RecordBatchStreamAdapter::new(
1347                schema.arrow_schema().clone(),
1348                futures::stream::iter(vec![Ok(batch)]),
1349            ),
1350        );
1351        let plan = Arc::new(TestMetricsExec::new(schema.arrow_schema().clone()));
1352        let mut adapter = RecordBatchStreamAdapter::try_new(df_stream).unwrap();
1353        adapter.set_metrics2(plan);
1354        adapter.set_explain_verbose(true);
1355
1356        adapter.next().await.unwrap().unwrap();
1357        let partial = adapter.metrics().unwrap();
1358        assert_eq!(partial.plan_metrics.len(), 1);
1359        assert_eq!(partial.plan_metrics[0].plan.trim_end(), "RegionScanExec");
1360        assert!(!partial.plan_metrics[0].plan.contains("files"));
1361
1362        assert!(adapter.next().await.is_none());
1363        let final_metrics = adapter.metrics().unwrap();
1364        assert!(final_metrics.plan_metrics[0].plan.contains("files"));
1365    }
1366
1367    #[test]
1368    fn test_record_batch_stream_adapter_reuses_partial_query_stats_on_drop() {
1369        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1370            "a",
1371            ConcreteDataType::int32_datatype(),
1372            false,
1373        )]));
1374        let df_stream = Box::pin(
1375            datafusion::physical_plan::stream::RecordBatchStreamAdapter::new(
1376                schema.arrow_schema().clone(),
1377                futures::stream::empty::<datafusion::error::Result<DfRecordBatch>>(),
1378            ),
1379        );
1380        let counters = RegionQueryStatCounters {
1381            query_cpu_time: Arc::new(AtomicU64::new(10)),
1382            query_scanned_bytes: Arc::new(AtomicU64::new(20)),
1383        };
1384        let stale_metrics = RecordBatchMetrics {
1385            elapsed_compute: 1,
1386            plan_metrics: vec![PlanMetrics {
1387                plan: REGION_SCAN_EXEC_NAME.to_string(),
1388                plan_name: REGION_SCAN_EXEC_NAME.to_string(),
1389                level: 0,
1390                metrics: vec![("output_bytes".to_string(), 2)],
1391                native: None,
1392            }],
1393            ..Default::default()
1394        };
1395        let adapter = RecordBatchStreamAdapter {
1396            schema: schema.clone(),
1397            stream: df_stream,
1398            metrics: None,
1399            metrics_2: Metrics::PartialResolved(
1400                Arc::new(TestMetricsExec::new(schema.arrow_schema().clone())),
1401                stale_metrics,
1402            ),
1403            query_load_region_id: None,
1404            query_stat_counters: Some(counters.clone()),
1405            explain_verbose: false,
1406            span: Span::current(),
1407        };
1408
1409        drop(adapter);
1410
1411        assert_eq!(counters.query_cpu_time.load(Ordering::Relaxed), 11);
1412        assert_eq!(counters.query_scanned_bytes.load(Ordering::Relaxed), 22);
1413    }
1414
1415    #[tokio::test]
1416    async fn test_async_recordbatch_stream_adaptor() {
1417        struct MaybeErrorRecordBatchStream {
1418            items: Vec<Result<RecordBatch>>,
1419        }
1420
1421        impl RecordBatchStream for MaybeErrorRecordBatchStream {
1422            fn schema(&self) -> SchemaRef {
1423                unimplemented!()
1424            }
1425
1426            fn output_ordering(&self) -> Option<&[OrderOption]> {
1427                None
1428            }
1429
1430            fn metrics(&self) -> Option<RecordBatchMetrics> {
1431                None
1432            }
1433        }
1434
1435        impl Stream for MaybeErrorRecordBatchStream {
1436            type Item = Result<RecordBatch>;
1437
1438            fn poll_next(
1439                mut self: Pin<&mut Self>,
1440                _: &mut Context<'_>,
1441            ) -> Poll<Option<Self::Item>> {
1442                if let Some(batch) = self.items.pop() {
1443                    Poll::Ready(Some(Ok(batch?)))
1444                } else {
1445                    Poll::Ready(None)
1446                }
1447            }
1448        }
1449
1450        fn new_future_stream(
1451            maybe_recordbatches: Result<Vec<Result<RecordBatch>>>,
1452        ) -> FutureStream {
1453            Box::pin(async move {
1454                maybe_recordbatches
1455                    .map(|items| Box::pin(MaybeErrorRecordBatchStream { items }) as _)
1456            })
1457        }
1458
1459        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1460            "a",
1461            ConcreteDataType::int32_datatype(),
1462            false,
1463        )]));
1464        let batch1 = RecordBatch::new(
1465            schema.clone(),
1466            vec![Arc::new(Int32Vector::from_slice([1])) as _],
1467        )
1468        .unwrap();
1469        let batch2 = RecordBatch::new(
1470            schema.clone(),
1471            vec![Arc::new(Int32Vector::from_slice([2])) as _],
1472        )
1473        .unwrap();
1474
1475        let success_stream = new_future_stream(Ok(vec![Ok(batch1.clone()), Ok(batch2.clone())]));
1476        let adapter = AsyncRecordBatchStreamAdapter::new(schema.clone(), success_stream);
1477        let collected = RecordBatches::try_collect(Box::pin(adapter)).await.unwrap();
1478        assert_eq!(
1479            collected,
1480            RecordBatches::try_new(schema.clone(), vec![batch2.clone(), batch1.clone()]).unwrap()
1481        );
1482
1483        let poll_err_stream = new_future_stream(Ok(vec![
1484            Ok(batch1.clone()),
1485            Err(error::ExternalSnafu
1486                .into_error(BoxedError::new(MockError::new(StatusCode::Unknown)))),
1487        ]));
1488        let adapter = AsyncRecordBatchStreamAdapter::new(schema.clone(), poll_err_stream);
1489        let err = RecordBatches::try_collect(Box::pin(adapter))
1490            .await
1491            .unwrap_err();
1492        assert!(
1493            matches!(err, Error::External { .. }),
1494            "unexpected err {err}"
1495        );
1496
1497        let failed_to_init_stream =
1498            new_future_stream(Err(error::ExternalSnafu
1499                .into_error(BoxedError::new(MockError::new(StatusCode::Internal)))));
1500        let adapter = AsyncRecordBatchStreamAdapter::new(schema.clone(), failed_to_init_stream);
1501        let err = RecordBatches::try_collect(Box::pin(adapter))
1502            .await
1503            .unwrap_err();
1504        assert!(
1505            matches!(err, Error::External { .. }),
1506            "unexpected err {err}"
1507        );
1508    }
1509
1510    /// Invariant: both stream adapters must forward the original error as a
1511    /// typed `BoxedError` inside `DataFusionError::External`, so downstream
1512    /// status code recovery (the `Error::PollStream` arm of `Error::status_code`)
1513    /// keeps the original status code.
1514    #[test]
1515    fn test_df_record_batch_stream_adapter_preserves_typed_errors() {
1516        fn chain_has_marker(err: &(dyn std::error::Error + 'static), marker: &str) -> bool {
1517            let mut current = Some(err);
1518            while let Some(error) = current {
1519                if error.to_string().contains(marker) {
1520                    return true;
1521                }
1522                current = error.source();
1523            }
1524            false
1525        }
1526
1527        fn assert_typed_external(
1528            df_error: &DataFusionError,
1529            expected: StatusCode,
1530            context: &str,
1531            marker: &str,
1532        ) {
1533            let DataFusionError::External(payload) = df_error else {
1534                panic!("{context}: expected DataFusionError::External, got {df_error:?}");
1535            };
1536            let Some(boxed) = payload.downcast_ref::<BoxedError>() else {
1537                panic!("{context}: external payload lost its typed BoxedError: {payload:?}");
1538            };
1539            assert_eq!(
1540                boxed.status_code(),
1541                expected,
1542                "{context}: original status code lost"
1543            );
1544            assert!(
1545                chain_has_marker(boxed, marker),
1546                "{context}: original error lost from the source chain: {payload:?}"
1547            );
1548        }
1549
1550        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1551            "a",
1552            ConcreteDataType::int32_datatype(),
1553            false,
1554        )]));
1555        let batch = RecordBatch::new(
1556            schema.clone(),
1557            vec![Arc::new(Int32Vector::from_slice([1])) as _],
1558        )
1559        .unwrap();
1560        let expected_df_batch = batch.clone().into_df_record_batch();
1561
1562        // A stream is consumed once, so every adapter under test gets its own
1563        // fresh equivalent stream. Sequence: Pending -> batch -> typed error -> EOF.
1564        let make_stream = |marker: &str, status: StatusCode| -> SendableRecordBatchStream {
1565            let typed_error = error::ExternalSnafu
1566                .into_error(BoxedError::new(PlainError::new(marker.to_string(), status)));
1567            let mut items: VecDeque<Poll<Option<Result<RecordBatch>>>> = VecDeque::from([
1568                Poll::Pending,
1569                Poll::Ready(Some(Ok(batch.clone()))),
1570                Poll::Ready(Some(Err(typed_error))),
1571                Poll::Ready(None),
1572            ]);
1573            Box::pin(RecordBatchStreamWrapper::new(
1574                schema.clone(),
1575                futures::stream::poll_fn(move |_| items.pop_front().unwrap_or(Poll::Ready(None))),
1576            ))
1577        };
1578
1579        let waker = futures::task::noop_waker_ref();
1580        let mut cx = Context::from_waker(waker);
1581
1582        for status in [
1583            StatusCode::InvalidArguments,
1584            StatusCode::Internal,
1585            StatusCode::Unknown,
1586            StatusCode::RequestOutdated,
1587        ] {
1588            // Unique per case, so a match proves the *original* error survived.
1589            let marker = format!("df-record-batch-stream-adapter-typed-error-marker-{status}");
1590
1591            // Greptime -> DataFusion forward adapter.
1592            let mut df_adapter = DfRecordBatchStreamAdapter::new(make_stream(&marker, status));
1593            assert_eq!(df_adapter.schema(), schema.arrow_schema().clone());
1594            assert!(
1595                matches!(Pin::new(&mut df_adapter).poll_next(&mut cx), Poll::Pending),
1596                "Pending must be preserved"
1597            );
1598            let Poll::Ready(Some(Ok(df_batch))) = Pin::new(&mut df_adapter).poll_next(&mut cx)
1599            else {
1600                panic!("expected the forwarded batch");
1601            };
1602            assert_eq!(df_batch.schema(), schema.arrow_schema().clone());
1603            assert_eq!(df_batch, expected_df_batch);
1604            let Poll::Ready(Some(Err(df_error))) = Pin::new(&mut df_adapter).poll_next(&mut cx)
1605            else {
1606                panic!("expected the forwarded error");
1607            };
1608            assert_typed_external(
1609                &df_error,
1610                status,
1611                &format!("forward adapter, status {status}"),
1612                &marker,
1613            );
1614            assert!(
1615                matches!(
1616                    Pin::new(&mut df_adapter).poll_next(&mut cx),
1617                    Poll::Ready(None)
1618                ),
1619                "EOF must be preserved"
1620            );
1621
1622            // DataFusion -> Greptime adapter over another fresh equivalent
1623            // stream: Pending, batch, schema and EOF stay unchanged, and the
1624            // error is reported exactly once.
1625            let df_stream: DfSendableRecordBatchStream = Box::pin(DfRecordBatchStreamAdapter::new(
1626                make_stream(&marker, status),
1627            ));
1628            let mut roundtrip = RecordBatchStreamAdapter::try_new(df_stream).unwrap();
1629            assert_eq!(roundtrip.schema().arrow_schema(), schema.arrow_schema());
1630            assert!(
1631                matches!(Pin::new(&mut roundtrip).poll_next(&mut cx), Poll::Pending),
1632                "Pending must be preserved"
1633            );
1634            let Poll::Ready(Some(Ok(roundtrip_batch))) =
1635                Pin::new(&mut roundtrip).poll_next(&mut cx)
1636            else {
1637                panic!("expected the roundtripped batch");
1638            };
1639            assert_eq!(roundtrip_batch.schema, roundtrip.schema());
1640            assert_eq!(roundtrip_batch.df_record_batch(), &expected_df_batch);
1641            let Poll::Ready(Some(Err(roundtrip_error))) =
1642                Pin::new(&mut roundtrip).poll_next(&mut cx)
1643            else {
1644                panic!("expected the roundtripped error");
1645            };
1646            let Error::PollStream {
1647                error: df_error, ..
1648            } = &roundtrip_error
1649            else {
1650                panic!("expected a poll stream error, got {roundtrip_error:?}");
1651            };
1652            assert_eq!(roundtrip_error.status_code(), status);
1653            let expected_output = match status {
1654                StatusCode::Internal => "Internal error: 1003".to_string(),
1655                StatusCode::Unknown => "Internal error: 1000".to_string(),
1656                _ => marker.clone(),
1657            };
1658            assert_eq!(roundtrip_error.output_msg(), expected_output);
1659            assert_typed_external(
1660                df_error,
1661                status,
1662                &format!("roundtrip adapter, status {status}"),
1663                &marker,
1664            );
1665            assert!(
1666                matches!(
1667                    Pin::new(&mut roundtrip).poll_next(&mut cx),
1668                    Poll::Ready(None)
1669                ),
1670                "the roundtrip stream must end after the error"
1671            );
1672        }
1673    }
1674
1675    #[test]
1676    fn test_convert_map_to_json_binary() {
1677        let keys = StringArray::from(vec![Some("a"), Some("b"), Some("c"), Some("x")]);
1678        let values = StringArray::from(vec![Some("1"), None, Some("3"), Some("42")]);
1679        let key_field = Arc::new(Field::new("key", ArrowDataType::Utf8, false));
1680        let value_field = Arc::new(Field::new("value", ArrowDataType::Utf8, true));
1681        let struct_type = ArrowDataType::Struct(vec![key_field, value_field].into());
1682
1683        let entries_field = Arc::new(Field::new("entries", struct_type, false));
1684
1685        let struct_array = StructArray::from(vec![
1686            (
1687                Arc::new(Field::new("key", ArrowDataType::Utf8, false)),
1688                Arc::new(keys) as ArrayRef,
1689            ),
1690            (
1691                Arc::new(Field::new("value", ArrowDataType::Utf8, true)),
1692                Arc::new(values) as ArrayRef,
1693            ),
1694        ]);
1695
1696        let offsets = OffsetBuffer::from_lengths([3, 0, 1]);
1697        let nulls = datatypes::arrow::buffer::NullBuffer::from(vec![true, false, true]);
1698
1699        let map_array = MapArray::new(
1700            entries_field,
1701            offsets,
1702            struct_array,
1703            Some(nulls), // nulls
1704            false,
1705        );
1706
1707        let result = convert_map_to_json_binary(&map_array, None).unwrap();
1708        let binary_array = result
1709            .as_any()
1710            .downcast_ref::<datatypes::arrow::array::BinaryArray>()
1711            .unwrap();
1712
1713        let expected_jsons = [
1714            Some(r#"{"a":"1","b":null,"c":"3"}"#),
1715            None,
1716            Some(r#"{"x":"42"}"#),
1717        ];
1718
1719        for (i, _) in expected_jsons.iter().enumerate() {
1720            if let Some(expected) = &expected_jsons[i] {
1721                assert!(!binary_array.is_null(i));
1722                let actual_bytes = binary_array.value(i);
1723                let actual_str = std::str::from_utf8(actual_bytes).unwrap();
1724                assert_eq!(actual_str, *expected);
1725            } else {
1726                assert!(binary_array.is_null(i));
1727            }
1728        }
1729
1730        let result_json =
1731            convert_map_to_json_binary(&map_array, Some(ColumnExtType::Json)).unwrap();
1732        let binary_array_json = result_json
1733            .as_any()
1734            .downcast_ref::<datatypes::arrow::array::BinaryArray>()
1735            .unwrap();
1736
1737        for (i, _) in expected_jsons.iter().enumerate() {
1738            if expected_jsons[i].is_some() {
1739                assert!(!binary_array_json.is_null(i));
1740                let actual_bytes = binary_array_json.value(i);
1741                assert_ne!(actual_bytes, expected_jsons[i].unwrap().as_bytes());
1742            } else {
1743                assert!(binary_array_json.is_null(i));
1744            }
1745        }
1746    }
1747
1748    #[test]
1749    fn test_record_query_stats_updates_region_counters() {
1750        let counters = RegionQueryStatCounters {
1751            query_cpu_time: Arc::new(AtomicU64::new(10)),
1752            query_scanned_bytes: Arc::new(AtomicU64::new(20)),
1753        };
1754        let metrics = RecordBatchMetrics {
1755            elapsed_compute: 2_000_000,
1756            plan_metrics: vec![PlanMetrics {
1757                plan: "RegionScanExec: region=1".to_string(),
1758                plan_name: REGION_SCAN_EXEC_NAME.to_string(),
1759                level: 0,
1760                metrics: vec![("output_bytes".to_string(), 42)],
1761                native: None,
1762            }],
1763            ..Default::default()
1764        };
1765
1766        record_query_stats(&counters, &metrics);
1767
1768        assert_eq!(counters.query_cpu_time.load(Ordering::Relaxed), 2_000_010);
1769        assert_eq!(counters.query_scanned_bytes.load(Ordering::Relaxed), 62);
1770    }
1771
1772    #[test]
1773    fn test_record_batch_stream_adapter_records_query_stats_on_drop() {
1774        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
1775            "a",
1776            ConcreteDataType::int32_datatype(),
1777            false,
1778        )]));
1779        let df_stream = Box::pin(
1780            datafusion::physical_plan::stream::RecordBatchStreamAdapter::new(
1781                schema.arrow_schema().clone(),
1782                futures::stream::empty::<datafusion::error::Result<DfRecordBatch>>(),
1783            ),
1784        );
1785        let counters = RegionQueryStatCounters {
1786            query_cpu_time: Arc::new(AtomicU64::new(10)),
1787            query_scanned_bytes: Arc::new(AtomicU64::new(20)),
1788        };
1789        let metrics = RecordBatchMetrics {
1790            elapsed_compute: 2_000_000,
1791            plan_metrics: vec![PlanMetrics {
1792                plan: "RegionScanExec: region=1".to_string(),
1793                plan_name: REGION_SCAN_EXEC_NAME.to_string(),
1794                level: 0,
1795                metrics: vec![("output_bytes".to_string(), 42)],
1796                native: None,
1797            }],
1798            ..Default::default()
1799        };
1800        let adapter = RecordBatchStreamAdapter {
1801            schema,
1802            stream: df_stream,
1803            metrics: None,
1804            metrics_2: Metrics::Resolved(metrics),
1805            query_load_region_id: None,
1806            query_stat_counters: Some(counters.clone()),
1807            explain_verbose: false,
1808            span: Span::current(),
1809        };
1810
1811        drop(adapter);
1812
1813        assert_eq!(counters.query_cpu_time.load(Ordering::Relaxed), 2_000_010);
1814        assert_eq!(counters.query_scanned_bytes.load(Ordering::Relaxed), 62);
1815    }
1816
1817    #[test]
1818    fn test_recordbatch_metrics_deserializes_without_region_watermarks() {
1819        let metrics: RecordBatchMetrics = serde_json::from_value(json!({
1820            "elapsed_compute": 12,
1821            "memory_usage": 34,
1822            "plan_metrics": []
1823        }))
1824        .unwrap();
1825
1826        assert!(metrics.region_watermarks.is_empty());
1827        assert_eq!(metrics.elapsed_compute, 12);
1828        assert_eq!(metrics.memory_usage, 34);
1829    }
1830
1831    #[test]
1832    fn test_plan_metrics_deserializes_without_plan_name() {
1833        let metrics: RecordBatchMetrics = serde_json::from_value(json!({
1834            "elapsed_compute": 12,
1835            "memory_usage": 34,
1836            "plan_metrics": [{
1837                "plan": "SeqScan: region=1",
1838                "level": 0,
1839                "metrics": []
1840            }]
1841        }))
1842        .unwrap();
1843
1844        assert_eq!(metrics.plan_metrics[0].plan_name, "");
1845    }
1846
1847    #[test]
1848    fn test_recordbatch_metrics_region_watermarks_serde_roundtrip() {
1849        let metrics = RecordBatchMetrics {
1850            region_watermarks: vec![
1851                RegionWatermarkEntry {
1852                    region_id: 1,
1853                    watermark: Some(100),
1854                },
1855                RegionWatermarkEntry {
1856                    region_id: 2,
1857                    watermark: None,
1858                },
1859            ],
1860            ..Default::default()
1861        };
1862
1863        let value = serde_json::to_value(&metrics).unwrap();
1864        assert_eq!(
1865            value.get("region_watermarks").unwrap(),
1866            &json!([
1867                { "region_id": 1, "watermark": 100 },
1868                { "region_id": 2 }
1869            ])
1870        );
1871
1872        let decoded: RecordBatchMetrics = serde_json::from_value(value).unwrap();
1873        assert_eq!(decoded.region_watermarks, metrics.region_watermarks);
1874    }
1875
1876    fn plan_metrics(level: usize, plan: &str, metrics: &[(&str, usize)]) -> PlanMetrics {
1877        PlanMetrics {
1878            plan: plan.to_string(),
1879            plan_name: "Test".to_string(),
1880            level,
1881            metrics: metrics
1882                .iter()
1883                .map(|(label, value)| (label.to_string(), *value))
1884                .collect(),
1885            native: None,
1886        }
1887    }
1888
1889    /// A one-line operator keeps its figures on its line, rendered as before: this is the shape
1890    /// every operator other than one that draws a subtree has always had.
1891    #[test]
1892    fn a_single_line_plan_keeps_its_figures_on_its_line() {
1893        let metrics = RecordBatchMetrics {
1894            plan_metrics: vec![
1895                plan_metrics(0, "CooperativeExec", &[("elapsed_compute", 1_000_000)]),
1896                plan_metrics(1, "RegionScanExec", &[("output_bytes", 2048)]),
1897            ],
1898            ..Default::default()
1899        };
1900
1901        assert_eq!(
1902            metrics.to_string(),
1903            " CooperativeExec metrics=[elapsed_compute: 1.0ms, ]\n  RegionScanExec metrics=[output_bytes: 2.0KiB, ]\n"
1904        );
1905    }
1906
1907    /// An operator that draws nodes below itself keeps its own figures on its own - first - line.
1908    /// Its subtree keeps the figures and the indentation it was rendered with, shifted to sit under
1909    /// the operator it hangs from.
1910    #[test]
1911    fn a_multi_line_plan_receives_its_figures_before_the_subtree_it_drew() {
1912        let metrics = RecordBatchMetrics {
1913            plan_metrics: vec![
1914                plan_metrics(
1915                    1,
1916                    "FusedSeriesExec: rate(x[5m])\n  Window: rate, metrics=[output_values: 3]\n    Input: source=0",
1917                    &[("elapsed_compute", 2_000_000)],
1918                ),
1919                plan_metrics(2, "RegionScanExec", &[("output_bytes", 4096)]),
1920            ],
1921            ..Default::default()
1922        };
1923
1924        assert_eq!(
1925            metrics.to_string(),
1926            concat!(
1927                "  FusedSeriesExec: rate(x[5m]) metrics=[elapsed_compute: 2.0ms, ]\n",
1928                "    Window: rate, metrics=[output_values: 3]\n",
1929                "      Input: source=0\n",
1930                "    RegionScanExec metrics=[output_bytes: 4.0KiB, ]\n",
1931            )
1932        );
1933    }
1934
1935    /// A record written before the native tree was carried here still reads, and a record without
1936    /// one does not grow a field: the payload is optional on the wire in both directions.
1937    #[test]
1938    fn a_plan_record_without_a_native_tree_reads_and_writes_no_field() {
1939        let older: PlanMetrics = serde_json::from_str(
1940            r#"{"plan":"CooperativeExec","plan_name":"CooperativeExec","level":0,"metrics":[]}"#,
1941        )
1942        .expect("a record written before the field existed reads");
1943
1944        assert_eq!(older.native, None);
1945        let written = serde_json::to_value(&older).unwrap();
1946        assert!(written.get("native").is_none());
1947    }
1948
1949    /// A tree crosses the record as structure: each node's line, its own figures, and its children.
1950    #[test]
1951    fn a_native_tree_round_trips_through_the_record() {
1952        let tree = NativeTreeMetrics {
1953            line: "Map: abs".to_string(),
1954            metrics: vec![("output_values".to_string(), 4)],
1955            children: vec![NativeTreeMetrics {
1956                line: "Input: raw samples source=0".to_string(),
1957                metrics: vec![],
1958                children: vec![],
1959            }],
1960        };
1961        let record = RecordBatchMetrics {
1962            plan_metrics: vec![PlanMetrics {
1963                plan: "FusedSeriesExec: abs(rate(x[5m]))".to_string(),
1964                plan_name: "FusedSeriesExec".to_string(),
1965                level: 0,
1966                metrics: vec![],
1967                native: Some(tree.clone()),
1968            }],
1969            ..Default::default()
1970        };
1971
1972        let written = serde_json::to_string(&record).unwrap();
1973        let read: RecordBatchMetrics = serde_json::from_str(&written).unwrap();
1974
1975        assert_eq!(read.plan_metrics[0].native, Some(tree));
1976    }
1977
1978    #[test]
1979    fn test_recordbatch_metrics_skips_empty_region_watermarks_on_serialize() {
1980        let value = serde_json::to_value(RecordBatchMetrics::default()).unwrap();
1981        assert!(value.get("region_watermarks").is_none());
1982    }
1983}