1use std::sync::Arc;
16
17use api::v1::meta::ProcedureStatus;
18use common_error::ext::BoxedError;
19use common_meta::cluster::{ClusterInfo, NodeInfo, Role};
20use common_meta::datanode::RegionStat;
21use common_meta::key::flow::flow_state::FlowStat;
22use common_meta::node_manager::DatanodeManagerRef;
23use common_meta::procedure_executor::{ExecutorContext, ProcedureExecutor};
24use common_meta::rpc::procedure;
25use common_procedure::{ProcedureInfo, ProcedureState};
26use common_query::request::QueryRequest;
27use common_recordbatch::adapter::{AsyncRecordBatchStreamAdapter, DfRecordBatchStreamAdapter};
28use common_recordbatch::filter::MetadataFilter;
29use common_recordbatch::util::{ChainedRecordBatchStream, LimitedRecordBatchStream};
30use common_recordbatch::{
31 DfSendableRecordBatchStream, EmptyRecordBatchStream, SendableRecordBatchStream,
32};
33use datafusion::common::tree_node::TreeNodeRecursion;
34use datafusion::common::{Result, ScalarValue};
35use datafusion::execution::TaskContext;
36use datafusion::logical_expr::LogicalPlan;
37use datafusion::physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr};
38use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
39use datafusion::physical_plan::{DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties};
40use datatypes::arrow::datatypes::SchemaRef as ArrowSchemaRef;
41use datatypes::schema::SchemaRef;
42use futures_util::future::try_join_all;
43use meta_client::MetaClientRef;
44use snafu::ResultExt;
45use store_api::compaction_task;
46use store_api::storage::RegionId;
47
48use crate::error;
49use crate::information_schema::{
50 DatanodeInspectKind, DatanodeInspectRequest, InformationExtension,
51};
52
53pub struct DistributedInformationExtension {
54 meta_client: MetaClientRef,
55 datanode_manager: DatanodeManagerRef,
56}
57
58impl DistributedInformationExtension {
59 pub fn new(meta_client: MetaClientRef, datanode_manager: DatanodeManagerRef) -> Self {
60 Self {
61 meta_client,
62 datanode_manager,
63 }
64 }
65
66 async fn inspect_datanode_stream(
67 meta_client: MetaClientRef,
68 datanode_manager: DatanodeManagerRef,
69 request: DatanodeInspectRequest,
70 ) -> crate::error::Result<SendableRecordBatchStream> {
71 let nodes = meta_client
72 .list_nodes(Some(Role::Datanode))
73 .await
74 .map_err(BoxedError::new)
75 .context(crate::error::ListNodesSnafu)?;
76 Self::inspect_nodes(datanode_manager, request, nodes).await
77 }
78
79 async fn inspect_nodes(
81 datanode_manager: DatanodeManagerRef,
82 request: DatanodeInspectRequest,
83 nodes: Vec<NodeInfo>,
84 ) -> crate::error::Result<SendableRecordBatchStream> {
85 let nodes = prune_compaction_nodes(&request, nodes);
86 let limit = request.scan.limit;
87 let plan = request
88 .build_plan()
89 .context(crate::error::DatafusionSnafu)?;
90 let stream = Self::inspect_query_nodes(datanode_manager, plan, nodes).await?;
91 match limit {
92 Some(limit) => Ok(Box::pin(LimitedRecordBatchStream::new(stream, limit))),
93 None => Ok(stream),
94 }
95 }
96
97 async fn inspect_query_stream(
98 meta_client: MetaClientRef,
99 datanode_manager: DatanodeManagerRef,
100 plan: LogicalPlan,
101 ) -> crate::error::Result<SendableRecordBatchStream> {
102 let nodes = meta_client
103 .list_nodes(Some(Role::Datanode))
104 .await
105 .map_err(BoxedError::new)
106 .context(crate::error::ListNodesSnafu)?;
107 Self::inspect_query_nodes(datanode_manager, plan, nodes).await
108 }
109
110 async fn inspect_query_nodes(
112 datanode_manager: DatanodeManagerRef,
113 plan: LogicalPlan,
114 nodes: Vec<NodeInfo>,
115 ) -> crate::error::Result<SendableRecordBatchStream> {
116 let schema = inspection_query_schema(&plan)?;
117 let streams = try_join_all(nodes.into_iter().map(|node| {
118 let datanode_manager = datanode_manager.clone();
119 let plan = plan.clone();
120 async move {
121 let client = datanode_manager.datanode(&node.peer).await;
122 client
123 .handle_query(QueryRequest {
124 plan,
125 region_id: RegionId::default(),
126 header: None,
127 })
128 .await
129 .context(crate::error::HandleQuerySnafu {
130 addr: node.peer.addr,
131 })
132 }
133 }))
134 .await?;
135
136 chain_inspection_streams(streams, schema)
137 }
138}
139
140fn inspection_query_schema(plan: &LogicalPlan) -> crate::error::Result<SchemaRef> {
141 datatypes::schema::Schema::try_from(plan.schema().clone())
142 .map(Arc::new)
143 .map_err(|error| datafusion::common::DataFusionError::External(Box::new(error)))
144 .context(crate::error::DatafusionSnafu)
145}
146
147fn chain_inspection_streams(
148 streams: Vec<SendableRecordBatchStream>,
149 schema: SchemaRef,
150) -> crate::error::Result<SendableRecordBatchStream> {
151 if streams.is_empty() {
152 return Ok(Box::pin(EmptyRecordBatchStream::new(schema)));
153 }
154 Ok(Box::pin(
155 ChainedRecordBatchStream::new(streams).context(crate::error::CreateRecordBatchSnafu)?,
156 ))
157}
158
159#[derive(Debug, Clone)]
160enum InspectPlan {
161 Scan(DatanodeInspectRequest),
162 Query(LogicalPlan),
163}
164
165fn prune_compaction_nodes(request: &DatanodeInspectRequest, nodes: Vec<NodeInfo>) -> Vec<NodeInfo> {
168 if request.kind != DatanodeInspectKind::CompactionTasks {
169 return nodes;
170 }
171 let filter = MetadataFilter::new(&request.scan.filters);
172 nodes
173 .into_iter()
174 .filter(|node| {
175 filter.matches(|name| {
176 (name == compaction_task::NODE_ID)
177 .then_some(ScalarValue::UInt64(Some(node.peer.id)))
178 })
179 })
180 .collect()
181}
182
183struct DistributedInspectExec {
184 plan: InspectPlan,
185 meta_client: MetaClientRef,
186 datanode_manager: DatanodeManagerRef,
187 schema: SchemaRef,
188 arrow_schema: ArrowSchemaRef,
189 properties: Arc<PlanProperties>,
190}
191
192impl std::fmt::Debug for DistributedInspectExec {
193 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194 f.debug_struct("DistributedInspectExec")
195 .field("plan", &self.plan)
196 .field("schema", &self.schema)
197 .finish_non_exhaustive()
198 }
199}
200
201impl DistributedInspectExec {
202 fn new(
203 request: DatanodeInspectRequest,
204 schema: SchemaRef,
205 meta_client: MetaClientRef,
206 datanode_manager: DatanodeManagerRef,
207 ) -> Self {
208 Self::with_plan(
209 InspectPlan::Scan(request),
210 schema,
211 meta_client,
212 datanode_manager,
213 )
214 }
215
216 fn with_plan(
217 plan: InspectPlan,
218 schema: SchemaRef,
219 meta_client: MetaClientRef,
220 datanode_manager: DatanodeManagerRef,
221 ) -> Self {
222 let arrow_schema = schema.arrow_schema().clone();
223 let properties = Arc::new(PlanProperties::new(
224 EquivalenceProperties::new(arrow_schema.clone()),
225 Partitioning::UnknownPartitioning(1),
226 EmissionType::Incremental,
227 Boundedness::Bounded,
228 ));
229 Self {
230 plan,
231 meta_client,
232 datanode_manager,
233 schema,
234 arrow_schema,
235 properties,
236 }
237 }
238}
239
240impl DisplayAs for DistributedInspectExec {
241 fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242 match &self.plan {
243 InspectPlan::Scan(request) => write!(
244 f,
245 "DistributedInspectExec: kind={:?}, scan={}, schema={:?}",
246 request.kind, request.scan, self.arrow_schema
247 ),
248 InspectPlan::Query(plan) => write!(
249 f,
250 "DistributedInspectExec: query={}, schema={:?}",
251 plan.display_indent(),
252 self.arrow_schema
253 ),
254 }
255 }
256}
257
258impl ExecutionPlan for DistributedInspectExec {
259 fn name(&self) -> &str {
260 "DistributedInspectExec"
261 }
262
263 fn schema(&self) -> ArrowSchemaRef {
264 self.arrow_schema.clone()
265 }
266
267 fn properties(&self) -> &Arc<PlanProperties> {
268 &self.properties
269 }
270
271 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
272 vec![]
273 }
274
275 fn apply_expressions(
276 &self,
277 _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
278 ) -> Result<TreeNodeRecursion> {
279 Ok(TreeNodeRecursion::Continue)
280 }
281
282 fn with_new_children(
283 self: Arc<Self>,
284 children: Vec<Arc<dyn ExecutionPlan>>,
285 ) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
286 if children.is_empty() {
287 Ok(self)
288 } else {
289 Err(datafusion::error::DataFusionError::Internal(
290 "DistributedInspectExec is a leaf execution plan and cannot accept children"
291 .to_string(),
292 ))
293 }
294 }
295
296 fn execute(
297 &self,
298 partition: usize,
299 _context: Arc<TaskContext>,
300 ) -> datafusion::error::Result<DfSendableRecordBatchStream> {
301 if partition != 0 {
302 return Err(datafusion::error::DataFusionError::Execution(format!(
303 "DistributedInspectExec invalid partition. Expected 0, got {partition}"
304 )));
305 }
306
307 let meta_client = self.meta_client.clone();
308 let datanode_manager = self.datanode_manager.clone();
309 let plan = self.plan.clone();
310 let schema = self.schema.clone();
311 let future = async move {
312 match plan {
313 InspectPlan::Scan(request) => {
314 DistributedInformationExtension::inspect_datanode_stream(
315 meta_client,
316 datanode_manager,
317 request,
318 )
319 .await
320 }
321 InspectPlan::Query(plan) => {
322 DistributedInformationExtension::inspect_query_stream(
323 meta_client,
324 datanode_manager,
325 plan,
326 )
327 .await
328 }
329 }
330 .map_err(BoxedError::new)
331 .context(common_recordbatch::error::ExternalSnafu)
332 };
333 let stream = AsyncRecordBatchStreamAdapter::new(schema, Box::pin(future));
334 Ok(Box::pin(DfRecordBatchStreamAdapter::new(Box::pin(stream))))
335 }
336}
337
338#[async_trait::async_trait]
339impl InformationExtension for DistributedInformationExtension {
340 type Error = crate::error::Error;
341
342 async fn nodes(&self) -> std::result::Result<Vec<NodeInfo>, Self::Error> {
343 self.meta_client
344 .list_nodes(None)
345 .await
346 .map_err(BoxedError::new)
347 .context(error::ListNodesSnafu)
348 }
349
350 async fn procedures(&self) -> std::result::Result<Vec<(String, ProcedureInfo)>, Self::Error> {
351 let procedures = self
352 .meta_client
353 .list_procedures(&ExecutorContext::default())
354 .await
355 .map_err(BoxedError::new)
356 .context(error::ListProceduresSnafu)?
357 .procedures;
358 let mut result = Vec::with_capacity(procedures.len());
359 for procedure in procedures {
360 let pid = match procedure.id {
361 Some(pid) => pid,
362 None => return error::ProcedureIdNotFoundSnafu {}.fail(),
363 };
364 let pid = procedure::pb_pid_to_pid(&pid)
365 .map_err(BoxedError::new)
366 .context(error::ConvertProtoDataSnafu)?;
367 let status = ProcedureStatus::try_from(procedure.status)
368 .map(|v| v.as_str_name())
369 .unwrap_or("Unknown")
370 .to_string();
371 let procedure_info = ProcedureInfo {
372 id: pid,
373 type_name: procedure.type_name,
374 start_time_ms: procedure.start_time_ms,
375 end_time_ms: procedure.end_time_ms,
376 state: ProcedureState::Running,
377 lock_keys: procedure.lock_keys,
378 };
379 result.push((status, procedure_info));
380 }
381
382 Ok(result)
383 }
384
385 async fn region_stats(&self) -> std::result::Result<Vec<RegionStat>, Self::Error> {
386 self.meta_client
387 .list_region_stats()
388 .await
389 .map_err(BoxedError::new)
390 .context(error::ListRegionStatsSnafu)
391 }
392
393 async fn flow_stats(&self) -> std::result::Result<Option<FlowStat>, Self::Error> {
394 self.meta_client
395 .list_flow_stats()
396 .await
397 .map_err(BoxedError::new)
398 .context(crate::error::ListFlowStatsSnafu)
399 }
400
401 async fn inspect_datanode(
402 &self,
403 request: DatanodeInspectRequest,
404 ) -> std::result::Result<SendableRecordBatchStream, Self::Error> {
405 Self::inspect_datanode_stream(
406 self.meta_client.clone(),
407 self.datanode_manager.clone(),
408 request,
409 )
410 .await
411 }
412
413 fn supports_inspect_query_plan(&self) -> bool {
414 true
415 }
416
417 fn inspect_datanode_query_plan(
418 &self,
419 plan: LogicalPlan,
420 ) -> crate::error::Result<Option<Arc<dyn ExecutionPlan>>> {
421 let schema = inspection_query_schema(&plan)?;
422 Ok(Some(Arc::new(DistributedInspectExec::with_plan(
423 InspectPlan::Query(plan),
424 schema,
425 self.meta_client.clone(),
426 self.datanode_manager.clone(),
427 ))))
428 }
429
430 fn inspect_datanode_plan(
431 &self,
432 request: DatanodeInspectRequest,
433 schema: SchemaRef,
434 ) -> std::result::Result<Option<Arc<dyn ExecutionPlan>>, Self::Error> {
435 Ok(Some(Arc::new(DistributedInspectExec::new(
436 request,
437 schema,
438 self.meta_client.clone(),
439 self.datanode_manager.clone(),
440 ))))
441 }
442}
443
444#[cfg(test)]
445mod tests {
446 use common_meta::node_manager::{DatanodeManager, DatanodeRef};
447 use common_meta::peer::Peer;
448 use datafusion::common::tree_node::TreeNode;
449 use datafusion::datasource::empty::EmptyTable;
450 use datafusion::logical_expr::{Expr, LogicalPlan};
451 use datafusion::physical_plan::sorts::sort::SortExec;
452 use datafusion::prelude::SessionContext;
453 use datatypes::arrow::datatypes::DataType;
454 use meta_client::client::MetaClientBuilder;
455 use store_api::sst_entry::ManifestSstEntry;
456 use store_api::storage::ScanRequest;
457
458 use store_api::compaction_task::CompactionTaskEntry;
459
460 use super::*;
461
462 struct UnusedDatanodeManager;
463
464 #[async_trait::async_trait]
465 impl DatanodeManager for UnusedDatanodeManager {
466 async fn datanode(&self, _node: &Peer) -> DatanodeRef {
467 panic!("this test must not contact datanodes")
468 }
469 }
470
471 fn inspection_nodes() -> Vec<NodeInfo> {
472 [1, 2, 3]
473 .into_iter()
474 .map(|id| NodeInfo {
475 peer: Peer::new(id, format!("datanode-{id}:3001")),
476 last_activity_ts: 0,
477 status: common_meta::cluster::NodeStatus::Standalone,
478 version: String::new(),
479 git_commit: String::new(),
480 start_time_ms: 0,
481 total_cpu_millicores: 0,
482 total_memory_bytes: 0,
483 cpu_usage_millicores: 0,
484 memory_usage_bytes: 0,
485 hostname: String::new(),
486 env_vars: Default::default(),
487 schedulable: None,
488 })
489 .collect()
490 }
491
492 async fn compaction_sql_filters(predicate: Option<&str>) -> Vec<Expr> {
494 let ctx = SessionContext::new();
495 ctx.register_table(
496 "compaction_tasks",
497 Arc::new(EmptyTable::new(
498 CompactionTaskEntry::schema().arrow_schema().clone(),
499 )),
500 )
501 .unwrap();
502 let mut sql = "SELECT * FROM compaction_tasks".to_string();
503 if let Some(predicate) = predicate {
504 sql.push_str(" WHERE ");
505 sql.push_str(predicate);
506 }
507 let plan = ctx.sql(&sql).await.unwrap().into_optimized_plan().unwrap();
508 let mut filters = Vec::new();
509 plan.apply(|plan| {
510 match plan {
511 LogicalPlan::Filter(filter) => filters.push(filter.predicate.clone()),
512 LogicalPlan::TableScan(scan) => filters.extend(scan.filters.iter().cloned()),
513 _ => {}
514 }
515 Ok(TreeNodeRecursion::Continue)
516 })
517 .unwrap();
518 filters
519 }
520
521 #[tokio::test]
522 async fn test_compaction_node_pruning() {
523 for (predicate, expected, expect_cast) in [
524 (Some("node_id = 2"), vec![2], false),
525 (Some("node_id != 2"), vec![1, 3], false),
526 (Some("node_id > 2"), vec![3], false),
527 (Some("node_id >= 2"), vec![2, 3], false),
528 (Some("node_id < 2"), vec![1], false),
529 (Some("node_id <= 2"), vec![1, 2], false),
530 (Some("2 = node_id"), vec![2], false),
531 (Some("2 < node_id"), vec![3], false),
532 (None, vec![1, 2, 3], false),
533 (Some("state = 'running'"), vec![1, 2, 3], false),
534 (Some("node_id = 2 OR table_id = 42"), vec![1, 2, 3], false),
535 (Some("node_id = 2 AND state = 'running'"), vec![2], false),
536 ] {
537 let filters = compaction_sql_filters(predicate).await;
538 let mut has_cast = false;
539 for filter in &filters {
540 filter
541 .apply(|expr| {
542 has_cast |= matches!(expr, Expr::Cast(cast) if cast.field.data_type() == &DataType::Decimal128(20, 0)
543 && matches!(cast.expr.as_ref(), Expr::Column(_)));
544 Ok(TreeNodeRecursion::Continue)
545 })
546 .unwrap();
547 }
548 assert_eq!(has_cast, expect_cast, "optimized predicate: {predicate:?}");
549 let request = DatanodeInspectRequest {
550 kind: DatanodeInspectKind::CompactionTasks,
551 scan: ScanRequest {
552 filters,
553 ..Default::default()
554 },
555 };
556 let actual: Vec<_> = prune_compaction_nodes(&request, inspection_nodes())
557 .into_iter()
558 .map(|node| node.peer.id)
559 .collect();
560 assert_eq!(
561 actual, expected,
562 "{predicate:?}: {:?}",
563 request.scan.filters
564 );
565 }
566 let filters = compaction_sql_filters(Some("node_id = 99")).await;
567 for kind in [
568 DatanodeInspectKind::SstManifest,
569 DatanodeInspectKind::SstStorage,
570 DatanodeInspectKind::SstIndexMeta,
571 DatanodeInspectKind::RegionInfo,
572 ] {
573 let request = DatanodeInspectRequest {
574 kind,
575 scan: ScanRequest {
576 filters: filters.clone(),
577 ..Default::default()
578 },
579 };
580 let actual: Vec<_> = prune_compaction_nodes(&request, inspection_nodes())
581 .into_iter()
582 .map(|node| node.peer.id)
583 .collect();
584 assert_eq!(actual, vec![1, 2, 3]);
585 }
586 }
587
588 #[tokio::test]
589 async fn test_compaction_empty_nodes_preserve_projected_schema() {
590 let filters = compaction_sql_filters(Some("node_id = 99")).await;
591 for nodes in [vec![], inspection_nodes()] {
592 for (projection, expected) in [
593 (
594 vec![3, 0, 2],
595 vec![
596 ("node_id", DataType::UInt64, true),
597 ("task_id", DataType::Utf8, false),
598 ("table_id", DataType::UInt32, false),
599 ],
600 ),
601 (vec![], vec![]),
602 ] {
603 let request = DatanodeInspectRequest {
604 kind: DatanodeInspectKind::CompactionTasks,
605 scan: ScanRequest {
606 projection: Some(projection),
607 filters: filters.clone(),
608 ..Default::default()
609 },
610 };
611 let stream = DistributedInformationExtension::inspect_nodes(
613 Arc::new(UnusedDatanodeManager),
614 request,
615 nodes.clone(),
616 )
617 .await
618 .unwrap();
619 let batches = common_recordbatch::RecordBatches::try_collect(stream)
620 .await
621 .unwrap();
622 assert_eq!(
623 batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
624 0
625 );
626 let schema = batches.schema();
627 let actual: Vec<_> = schema
628 .arrow_schema()
629 .fields()
630 .iter()
631 .map(|field| {
632 (
633 field.name().as_str(),
634 field.data_type().clone(),
635 field.is_nullable(),
636 )
637 })
638 .collect();
639 assert_eq!(actual, expected);
640 }
641 }
642 }
643
644 #[derive(Debug)]
645 struct ManifestScanProvider;
646
647 #[async_trait::async_trait]
648 impl datafusion::catalog::TableProvider for ManifestScanProvider {
649 fn schema(&self) -> ArrowSchemaRef {
650 ManifestSstEntry::schema().arrow_schema().clone()
651 }
652
653 fn table_type(&self) -> datafusion::logical_expr::TableType {
654 datafusion::logical_expr::TableType::View
655 }
656
657 fn supports_filters_pushdown(
658 &self,
659 filters: &[&datafusion::logical_expr::Expr],
660 ) -> Result<Vec<datafusion::logical_expr::TableProviderFilterPushDown>> {
661 Ok(vec![datafusion::logical_expr::TableProviderFilterPushDown::Inexact; filters.len()])
662 }
663
664 async fn scan(
665 &self,
666 _state: &dyn datafusion::catalog::Session,
667 projection: Option<&Vec<usize>>,
668 filters: &[datafusion::logical_expr::Expr],
669 limit: Option<usize>,
670 ) -> Result<Arc<dyn ExecutionPlan>> {
671 let schema = ManifestSstEntry::schema();
672 let schema = match projection {
673 Some(projection) => Arc::new(schema.try_project(projection).unwrap()),
674 None => schema,
675 };
676 Ok(Arc::new(DistributedInspectExec::new(
677 DatanodeInspectRequest {
678 kind: DatanodeInspectKind::SstManifest,
679 scan: ScanRequest {
680 projection: projection.cloned(),
681 filters: filters.to_vec(),
682 limit,
683 ..Default::default()
684 },
685 },
686 schema,
687 Arc::new(MetaClientBuilder::new(0, api::v1::meta::Role::Frontend).build()),
688 Arc::new(UnusedDatanodeManager),
689 )))
690 }
691 }
692
693 #[tokio::test]
694 async fn test_inspection_query_plan_is_lazy_and_preserves_schema() {
695 let ctx = datafusion::prelude::SessionContext::new();
696 let remote = ctx
697 .sql("SELECT count(*), sum(value) FROM (VALUES (1), (2)) AS t(value)")
698 .await
699 .unwrap()
700 .into_unoptimized_plan();
701 let extension = DistributedInformationExtension::new(
702 Arc::new(MetaClientBuilder::new(0, api::v1::meta::Role::Frontend).build()),
703 Arc::new(UnusedDatanodeManager),
704 );
705 assert!(extension.supports_inspect_query_plan());
706 let exec = extension
707 .inspect_datanode_query_plan(remote.clone())
708 .unwrap()
709 .unwrap();
710 assert_eq!(exec.schema(), remote.schema().inner().clone());
711 let inspect = exec.downcast_ref::<DistributedInspectExec>().unwrap();
712 let InspectPlan::Query(plan) = &inspect.plan else {
713 panic!("expected inspection query")
714 };
715 assert_eq!(plan, &remote);
716 assert!(exec.children().is_empty());
717 for _ in 0..2 {
719 let stream = exec.execute(0, ctx.task_ctx()).unwrap();
720 assert_eq!(stream.schema(), exec.schema());
721 drop(stream);
722 }
723 assert!(exec.execute(1, ctx.task_ctx()).is_err());
724 }
725
726 #[tokio::test]
727 async fn test_empty_inspection_query_stream_keeps_output_schema() {
728 use futures_util::StreamExt;
729
730 let ctx = datafusion::prelude::SessionContext::new();
731 let remote = ctx
732 .sql("SELECT count(*), sum(value) FROM (VALUES (1)) AS t(value)")
733 .await
734 .unwrap()
735 .into_unoptimized_plan();
736 let schema = inspection_query_schema(&remote).unwrap();
737 let mut stream = chain_inspection_streams(vec![], schema.clone()).unwrap();
738 assert_eq!(stream.schema(), schema);
739 assert!(stream.next().await.is_none());
740 }
741
742 #[tokio::test]
743 async fn test_sql_manifest_sort_stays_on_frontend() {
744 let ctx = datafusion::prelude::SessionContext::new();
745 ctx.register_table("ssts_manifest", Arc::new(ManifestScanProvider))
746 .unwrap();
747 for sql in [
748 "SELECT region_id, file_id, min_ts, max_ts, file_size FROM ssts_manifest WHERE region_id = 42 ORDER BY min_ts LIMIT 100",
749 "SELECT file_id FROM ssts_manifest WHERE region_id = 42 ORDER BY max_ts DESC LIMIT 10 OFFSET 3",
750 "SELECT min_ts AS ts, file_id FROM ssts_manifest WHERE region_id = 42 ORDER BY ts DESC NULLS FIRST LIMIT 10",
751 "SELECT file_id FROM ssts_manifest WHERE region_id = 42 ORDER BY min_ts, max_ts DESC LIMIT 10",
752 ] {
753 let plan = ctx
754 .sql(sql)
755 .await
756 .unwrap()
757 .create_physical_plan()
758 .await
759 .unwrap();
760 let mut found_scan = false;
761 let mut found_sort = false;
762 plan.apply(|plan| {
763 found_sort |= plan.is::<SortExec>();
764 if let Some(scan) = plan.downcast_ref::<DistributedInspectExec>() {
765 found_scan = true;
766 let InspectPlan::Scan(request) = &scan.plan else {
768 panic!("expected scan plan")
769 };
770 assert_eq!(request.scan.limit, None);
771 let remote = request.clone().build_plan().unwrap();
772 remote.apply(|node| {
773 assert!(!matches!(
774 node,
775 LogicalPlan::Sort(_) | LogicalPlan::Limit(_)
776 ));
777 Ok(TreeNodeRecursion::Continue)
778 })?;
779 }
780 Ok(TreeNodeRecursion::Continue)
781 })
782 .unwrap();
783 assert!(
784 found_scan && found_sort,
785 "{}",
786 datafusion::physical_plan::displayable(plan.as_ref()).indent(true)
787 );
788 }
789 }
790}