You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by ag...@apache.org on 2026/07/03 14:03:26 UTC

(datafusion-ballista) branch main updated: feat(scheduler): allow submitting an already-built physical plan (#1924)

This is an automated email from the ASF dual-hosted git repository.

andygrove pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datafusion-ballista.git


The following commit(s) were added to refs/heads/main by this push:
     new 6472c7f21 feat(scheduler): allow submitting an already-built physical plan (#1924)
6472c7f21 is described below

commit 6472c7f21ad1a824b123037b2f18669bd1538bca
Author: Andy Grove <ag...@apache.org>
AuthorDate: Fri Jul 3 08:03:21 2026 -0600

    feat(scheduler): allow submitting an already-built physical plan (#1924)
    
    Add a physical_plan field to ExecuteQueryParams.query so clients can
    submit an ExecutionPlan directly, bypassing logical plan creation on
    the scheduler. DefaultDistributedPlanner::plan_query_stages already
    splits physical plans into shuffle stages at RepartitionExec(Hash)
    boundaries, so this unblocks distributing plans that contain
    custom/FFI operators with no logical-plan representation.
    
    Thread the decoded plan through the existing job-submission event
    path (SchedulerServer::submit_job -> QueryStageSchedulerEvent::JobQueued
    -> SchedulerState::submit_job -> TaskManager::submit_job) as a new
    SubmitPlan enum (Logical | Physical) instead of a bare LogicalPlan.
    Physical-plan jobs always use the static distributed planner and skip
    create_physical_plan/EXPLAIN handling entirely; AQE is not available
    for this path since it requires a logical plan to re-plan against.
    
    Add execute_physical_plan() in ballista-core as a client-side helper
    that mirrors DistributedQueryExec's submission flow (serialize with
    the physical extension codec, submit, poll status, fetch partitions).
---
 Cargo.lock                                         |   1 +
 ballista/client/Cargo.toml                         |   1 +
 ballista/client/tests/physical_plan_submission.rs  | 132 +++++++++++++++++++++
 ballista/core/proto/ballista.proto                 |   5 +
 .../core/src/execution_plans/distributed_query.rs  |  86 ++++++++++++++
 ballista/core/src/execution_plans/mod.rs           |   2 +-
 ballista/core/src/serde/generated/ballista.rs      |   8 +-
 ballista/scheduler/src/scheduler_server/event.rs   |  27 ++++-
 ballista/scheduler/src/scheduler_server/grpc.rs    |  40 +++++--
 ballista/scheduler/src/scheduler_server/mod.rs     |  15 ++-
 ballista/scheduler/src/state/mod.rs                |  14 +--
 ballista/scheduler/src/state/task_manager.rs       |  94 +++++++++------
 ballista/scheduler/src/test_utils.rs               |  14 ++-
 13 files changed, 377 insertions(+), 62 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 369a96718..eec4cd1d7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1012,6 +1012,7 @@ dependencies = [
  "tokio",
  "tonic",
  "url",
+ "uuid",
 ]
 
 [[package]]
diff --git a/ballista/client/Cargo.toml b/ballista/client/Cargo.toml
index e8d4eb990..f3d9d2e3e 100644
--- a/ballista/client/Cargo.toml
+++ b/ballista/client/Cargo.toml
@@ -46,6 +46,7 @@ datafusion-proto = { workspace = true }
 env_logger = { workspace = true }
 rstest = { workspace = true }
 tempfile = { workspace = true }
+uuid = { workspace = true }
 tonic = { workspace = true }
 
 [features]
diff --git a/ballista/client/tests/physical_plan_submission.rs b/ballista/client/tests/physical_plan_submission.rs
new file mode 100644
index 000000000..140ecdf22
--- /dev/null
+++ b/ballista/client/tests/physical_plan_submission.rs
@@ -0,0 +1,132 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! End-to-end test for submitting an already-built physical plan directly to a
+//! Ballista scheduler, bypassing logical plan creation on the scheduler side.
+
+mod common;
+
+#[cfg(test)]
+#[cfg(feature = "standalone")]
+mod physical_plan_submission_tests {
+    use crate::common::setup_test_cluster;
+    use ballista_core::config::BallistaConfig;
+    use ballista_core::execution_plans::execute_physical_plan;
+    use ballista_core::extension::SessionConfigExt;
+    use datafusion::arrow::array::Int32Array;
+    use datafusion::arrow::datatypes::{DataType, Field, Schema};
+    use datafusion::arrow::record_batch::RecordBatch;
+    use datafusion::common::test_util::batches_to_sort_string;
+    use datafusion::datasource::MemTable;
+    use datafusion::physical_expr::expressions::Column;
+    use datafusion::physical_plan::repartition::RepartitionExec;
+    use datafusion::physical_plan::{self, ExecutionPlan, Partitioning};
+    use datafusion::prelude::{SessionConfig, SessionContext};
+    use datafusion_proto::protobuf::PhysicalPlanNode;
+    use std::sync::Arc;
+
+    /// Builds a two-partition `MemTable`-backed scan wrapped in a hash
+    /// `RepartitionExec`, i.e. a physical plan with a shuffle boundary that
+    /// `plan_query_stages` will split into two stages.
+    async fn build_physical_plan() -> (Arc<dyn ExecutionPlan>, SessionContext) {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("id", DataType::Int32, false),
+            Field::new("value", DataType::Int32, false),
+        ]));
+
+        let batch1 = RecordBatch::try_new(
+            schema.clone(),
+            vec![
+                Arc::new(Int32Array::from(vec![1, 2, 3])),
+                Arc::new(Int32Array::from(vec![10, 20, 30])),
+            ],
+        )
+        .unwrap();
+        let batch2 = RecordBatch::try_new(
+            schema.clone(),
+            vec![
+                Arc::new(Int32Array::from(vec![4, 5])),
+                Arc::new(Int32Array::from(vec![40, 50])),
+            ],
+        )
+        .unwrap();
+
+        let table = MemTable::try_new(schema, vec![vec![batch1], vec![batch2]]).unwrap();
+
+        let ctx = SessionContext::new();
+        ctx.register_table("t", Arc::new(table)).unwrap();
+
+        let scan = ctx
+            .table("t")
+            .await
+            .unwrap()
+            .create_physical_plan()
+            .await
+            .unwrap();
+
+        let repartitioned: Arc<dyn ExecutionPlan> = Arc::new(
+            RepartitionExec::try_new(
+                scan,
+                Partitioning::Hash(vec![Arc::new(Column::new("id", 0))], 4),
+            )
+            .unwrap(),
+        );
+
+        (repartitioned, ctx)
+    }
+
+    /// Submits a hand-built physical plan (scan -> hash repartition) directly to
+    /// a standalone Ballista cluster via the new physical-plan submission path,
+    /// and checks that the rows returned match what executing the same plan
+    /// locally produces. The plan's `RepartitionExec(Hash)` boundary means the
+    /// scheduler must have split it into two shuffle stages for this to work.
+    #[tokio::test]
+    async fn should_execute_submitted_physical_plan_across_shuffle_stages() {
+        let (host, port) = setup_test_cluster().await;
+        let scheduler_url = format!("http://{host}:{port}");
+
+        let (plan, ctx) = build_physical_plan().await;
+
+        let expected = physical_plan::collect(plan.clone(), ctx.task_ctx())
+            .await
+            .unwrap();
+
+        let session_config = SessionConfig::new_with_ballista();
+        let codec = session_config.ballista_physical_extension_codec();
+        let session_id = uuid::Uuid::new_v4().to_string();
+
+        let stream = execute_physical_plan::<PhysicalPlanNode>(
+            scheduler_url,
+            &BallistaConfig::default(),
+            plan,
+            codec.as_ref(),
+            session_id,
+            session_config,
+        )
+        .await
+        .expect("physical plan job should be submitted and executed");
+
+        let actual = physical_plan::common::collect(stream)
+            .await
+            .expect("collecting results from the submitted physical plan");
+
+        assert_eq!(
+            batches_to_sort_string(&expected),
+            batches_to_sort_string(&actual)
+        );
+    }
+}
diff --git a/ballista/core/proto/ballista.proto b/ballista/core/proto/ballista.proto
index 2154b1a17..50a3e25e7 100644
--- a/ballista/core/proto/ballista.proto
+++ b/ballista/core/proto/ballista.proto
@@ -630,6 +630,11 @@ message ExecuteQueryParams {
   oneof query {
     bytes logical_plan = 1;
     bytes substrait_plan = 6;
+    // An already-built physical plan, serialized with the scheduler's
+    // physical extension codec. Lets clients bypass logical-plan creation
+    // on the scheduler, e.g. for plans containing custom operators that
+    // have no logical-plan representation.
+    bytes physical_plan = 7;
   }
   // reserved after removing deprecated `sql` query type.
   reserved 2;
diff --git a/ballista/core/src/execution_plans/distributed_query.rs b/ballista/core/src/execution_plans/distributed_query.rs
index a7d79ef82..137cde103 100644
--- a/ballista/core/src/execution_plans/distributed_query.rs
+++ b/ballista/core/src/execution_plans/distributed_query.rs
@@ -46,6 +46,7 @@ use datafusion::prelude::SessionConfig;
 use datafusion_proto::logical_plan::{
     AsLogicalPlan, DefaultLogicalExtensionCodec, LogicalExtensionCodec,
 };
+use datafusion_proto::physical_plan::{AsExecutionPlan, PhysicalExtensionCodec};
 use futures::{Stream, StreamExt, TryFutureExt, TryStreamExt};
 use log::{debug, error, info};
 use parking_lot::Mutex;
@@ -321,6 +322,91 @@ impl<T: 'static + AsLogicalPlan> ExecutionPlan for DistributedQueryExec<T> {
     }
 }
 
+/// Submits an already-built physical plan directly to a Ballista scheduler for
+/// distributed execution, bypassing logical plan creation on the scheduler side.
+///
+/// This is a lower-level entry point than [DistributedQueryExec]: instead of a
+/// [LogicalPlan] that the scheduler turns into a physical plan itself, the caller
+/// supplies the physical plan up front - e.g. for plans containing custom
+/// operators that have no logical-plan representation.
+pub async fn execute_physical_plan<U: 'static + AsExecutionPlan>(
+    scheduler_url: String,
+    config: &BallistaConfig,
+    physical_plan: Arc<dyn ExecutionPlan>,
+    codec: &dyn PhysicalExtensionCodec,
+    session_id: String,
+    session_config: SessionConfig,
+) -> Result<SendableRecordBatchStream> {
+    let plan_message =
+        U::try_from_physical_plan(physical_plan.clone(), codec).map_err(|e| {
+            DataFusionError::Internal(format!("failed to serialize physical plan: {e:?}"))
+        })?;
+    let mut buf: Vec<u8> = vec![];
+    plan_message.try_encode(&mut buf).map_err(|e| {
+        DataFusionError::Execution(format!("failed to encode physical plan: {e:?}"))
+    })?;
+
+    let settings = session_config
+        .options()
+        .entries()
+        .iter()
+        .map(
+            |datafusion::config::ConfigEntry { key, value, .. }| KeyValuePair {
+                key: key.to_owned(),
+                value: value.clone(),
+            },
+        )
+        .collect();
+    let operation_id = uuid::Uuid::now_v7().to_string();
+    let query = ExecuteQueryParams {
+        query: Some(Query::PhysicalPlan(buf)),
+        settings,
+        session_id: session_id.clone(),
+        operation_id,
+    };
+
+    let max_message_size = config.grpc_client_max_message_size();
+    let grpc_config = GrpcClientConfig::from(config);
+    let metrics = Arc::new(ExecutionPlanMetricsSet::new());
+    let job_id_handle = Arc::new(Mutex::new(None));
+    let partition = 0;
+
+    let stream: std::pin::Pin<Box<dyn Stream<Item = Result<RecordBatch>> + Send>> =
+        if session_config.ballista_config().client_pull() {
+            Box::pin(
+                execute_query_pull(
+                    scheduler_url,
+                    session_id,
+                    query,
+                    max_message_size,
+                    grpc_config,
+                    metrics,
+                    job_id_handle,
+                    partition,
+                    session_config,
+                )
+                .await?,
+            )
+        } else {
+            Box::pin(
+                execute_query_push(
+                    scheduler_url,
+                    query,
+                    max_message_size,
+                    grpc_config,
+                    metrics,
+                    job_id_handle,
+                    partition,
+                    session_config,
+                )
+                .await?,
+            )
+        };
+
+    let schema = physical_plan.schema();
+    Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
+}
+
 /// Client will periodically invoke scheduler to check
 /// job status. There is preconfigured wait period between
 /// pulls, which increases query latency.
diff --git a/ballista/core/src/execution_plans/mod.rs b/ballista/core/src/execution_plans/mod.rs
index f62368509..7c27f26d8 100644
--- a/ballista/core/src/execution_plans/mod.rs
+++ b/ballista/core/src/execution_plans/mod.rs
@@ -32,7 +32,7 @@ use std::path::{Path, PathBuf};
 pub use chaos_exec::ChaosExec;
 use datafusion::common::exec_err;
 pub use distributed_explain_analyze::DistributedExplainAnalyzeExec;
-pub use distributed_query::DistributedQueryExec;
+pub use distributed_query::{DistributedQueryExec, execute_physical_plan};
 pub use shuffle_reader::{CoalescePlan, PartitionGroup, ShuffleReaderExec};
 pub use shuffle_reader::{stats_for_partition, stats_for_partitions};
 pub use shuffle_writer::DEFAULT_SHUFFLE_CHANNEL_CAPACITY;
diff --git a/ballista/core/src/serde/generated/ballista.rs b/ballista/core/src/serde/generated/ballista.rs
index 269827145..d07154666 100644
--- a/ballista/core/src/serde/generated/ballista.rs
+++ b/ballista/core/src/serde/generated/ballista.rs
@@ -958,7 +958,7 @@ pub struct ExecuteQueryParams {
     /// client and scheduler
     #[prost(string, tag = "5")]
     pub operation_id: ::prost::alloc::string::String,
-    #[prost(oneof = "execute_query_params::Query", tags = "1, 6")]
+    #[prost(oneof = "execute_query_params::Query", tags = "1, 6, 7")]
     pub query: ::core::option::Option<execute_query_params::Query>,
 }
 /// Nested message and enum types in `ExecuteQueryParams`.
@@ -969,6 +969,12 @@ pub mod execute_query_params {
         LogicalPlan(::prost::alloc::vec::Vec<u8>),
         #[prost(bytes, tag = "6")]
         SubstraitPlan(::prost::alloc::vec::Vec<u8>),
+        /// An already-built physical plan, serialized with the scheduler's
+        /// physical extension codec. Lets clients bypass logical-plan creation
+        /// on the scheduler, e.g. for plans containing custom operators that
+        /// have no logical-plan representation.
+        #[prost(bytes, tag = "7")]
+        PhysicalPlan(::prost::alloc::vec::Vec<u8>),
     }
 }
 #[derive(Clone, PartialEq, ::prost::Message)]
diff --git a/ballista/scheduler/src/scheduler_server/event.rs b/ballista/scheduler/src/scheduler_server/event.rs
index c02c14a99..2cb7e718b 100644
--- a/ballista/scheduler/src/scheduler_server/event.rs
+++ b/ballista/scheduler/src/scheduler_server/event.rs
@@ -18,12 +18,35 @@
 use std::fmt::{Debug, Formatter};
 
 use datafusion::logical_expr::LogicalPlan;
+use datafusion::physical_plan::ExecutionPlan;
 
 use crate::state::execution_graph::RunningTaskInfo;
 use ballista_core::{JobId, JobStatusSubscriber, serde::protobuf::TaskStatus};
 use datafusion::prelude::SessionContext;
 use std::sync::Arc;
 
+/// A plan submitted for execution by a client.
+///
+/// Most jobs are submitted as a [LogicalPlan] which the scheduler optimizes
+/// and turns into a physical plan itself. A client may instead submit an
+/// already-built physical plan directly, bypassing logical planning on the
+/// scheduler entirely - e.g. for plans containing custom operators that have
+/// no logical-plan representation. Physical-plan jobs always use the static
+/// distributed planner; the adaptive query planner (AQE) requires a logical
+/// plan and is not available for this path.
+// `LogicalPlan` is much larger than `Arc<dyn ExecutionPlan>`, but `SubmitPlan`
+// values are only ever handled by reference or already boxed by their callers
+// (e.g. `QueryStageSchedulerEvent::JobQueued::plan`), so the size difference
+// does not cause repeated large stack copies in practice.
+#[allow(clippy::large_enum_variant)]
+#[derive(Clone)]
+pub enum SubmitPlan {
+    /// A logical plan that the scheduler will plan into a physical plan.
+    Logical(LogicalPlan),
+    /// An already-built physical plan supplied directly by the client.
+    Physical(Arc<dyn ExecutionPlan>),
+}
+
 /// Events that drive the query stage scheduler state machine.
 #[derive(Clone)]
 pub enum QueryStageSchedulerEvent {
@@ -35,8 +58,8 @@ pub enum QueryStageSchedulerEvent {
         job_name: String,
         /// Session context for the job.
         session_ctx: Arc<SessionContext>,
-        /// Logical plan to execute.
-        plan: Box<LogicalPlan>,
+        /// Plan to execute, either logical or an already-built physical plan.
+        plan: Box<SubmitPlan>,
         /// Timestamp when the job was queued.
         queued_at: u64,
         /// job status subscriber
diff --git a/ballista/scheduler/src/scheduler_server/grpc.rs b/ballista/scheduler/src/scheduler_server/grpc.rs
index 14a6952da..1d3492669 100644
--- a/ballista/scheduler/src/scheduler_server/grpc.rs
+++ b/ballista/scheduler/src/scheduler_server/grpc.rs
@@ -51,9 +51,8 @@ use {
 
 use crate::cluster::{bind_task_bias, bind_task_round_robin};
 use crate::config::TaskDistributionPolicy;
-use crate::scheduler_server::event::QueryStageSchedulerEvent;
+use crate::scheduler_server::event::{QueryStageSchedulerEvent, SubmitPlan};
 use ballista_core::serde::protobuf::get_job_status_result::FlightProxy;
-use datafusion::logical_expr::LogicalPlan;
 use datafusion::physical_plan::{DisplayFormatType, ExecutionPlan};
 use datafusion::prelude::SessionContext;
 use std::ops::Deref;
@@ -414,8 +413,8 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> SchedulerGrpc
             })?;
 
             debug!(
-                "Decoded logical plan for execution:\n{}",
-                plan.display_indent()
+                "Decoded plan for execution:\n{}",
+                Self::describe_submitted_plan(&plan)
             );
             log::trace!("setting job name: {job_name}");
 
@@ -499,8 +498,8 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> SchedulerGrpc
             };
 
             debug!(
-                "Decoded logical plan for execution:\n{}",
-                plan.display_indent()
+                "Decoded plan for execution:\n{}",
+                Self::describe_submitted_plan(&plan)
             );
 
             log::trace!("setting job name: {job_name}");
@@ -785,7 +784,7 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> SchedulerServer<T
         &self,
         query: Query,
         session_ctx: &SessionContext,
-    ) -> BResult<LogicalPlan> {
+    ) -> BResult<SubmitPlan> {
         match query {
             Query::LogicalPlan(message) => T::try_decode(message.as_slice())
                 .and_then(|m| {
@@ -794,8 +793,22 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> SchedulerServer<T
                         self.state.codec.logical_extension_codec(),
                     )
                 })
+                .map(SubmitPlan::Logical)
                 .map_err(|e| e.into()),
 
+            Query::PhysicalPlan(message) => {
+                let task_ctx = session_ctx.task_ctx();
+                U::try_decode(message.as_slice())
+                    .and_then(|m| {
+                        m.try_into_physical_plan(
+                            task_ctx.as_ref(),
+                            self.state.codec.physical_extension_codec(),
+                        )
+                    })
+                    .map(SubmitPlan::Physical)
+                    .map_err(|e| e.into())
+            }
+
             #[cfg(not(feature = "substrait"))]
             Query::SubstraitPlan(_) => {
                 Err(BallistaError::NotImplemented("Received query type \"Substrait\", enable \"substrait\" feature to support Substrait plans.".to_string()))
@@ -807,11 +820,24 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> SchedulerServer<T
                 let ctx = session_ctx.clone();
                 from_substrait_plan(&ctx.state(), &plan)
                     .await
+                    .map(SubmitPlan::Logical)
                     .map_err(|e| e.into())
             }
         }
     }
 
+    /// Returns a human-readable representation of a submitted plan, for logging.
+    fn describe_submitted_plan(plan: &SubmitPlan) -> String {
+        match plan {
+            SubmitPlan::Logical(plan) => plan.display_indent().to_string(),
+            SubmitPlan::Physical(plan) => {
+                datafusion::physical_plan::displayable(plan.as_ref())
+                    .indent(false)
+                    .to_string()
+            }
+        }
+    }
+
     fn flight_proxy_config(&self) -> Option<FlightProxy> {
         self.state
             .config
diff --git a/ballista/scheduler/src/scheduler_server/mod.rs b/ballista/scheduler/src/scheduler_server/mod.rs
index 17b955a98..5886c65e0 100644
--- a/ballista/scheduler/src/scheduler_server/mod.rs
+++ b/ballista/scheduler/src/scheduler_server/mod.rs
@@ -25,7 +25,6 @@ use ballista_core::serde::protobuf::TaskStatus;
 use ballista_core::{JobId, JobStatusSubscriber};
 
 use datafusion::execution::context::SessionState;
-use datafusion::logical_expr::LogicalPlan;
 use datafusion::prelude::{SessionConfig, SessionContext};
 use datafusion_proto::logical_plan::AsLogicalPlan;
 use datafusion_proto::physical_plan::AsExecutionPlan;
@@ -36,7 +35,7 @@ use crate::metrics::SchedulerMetricsCollector;
 use ballista_core::serde::scheduler::{ExecutorData, ExecutorMetadata};
 use log::{debug, error, warn};
 
-use crate::scheduler_server::event::QueryStageSchedulerEvent;
+use crate::scheduler_server::event::{QueryStageSchedulerEvent, SubmitPlan};
 use crate::scheduler_server::query_stage_scheduler::QueryStageScheduler;
 
 use crate::state::executor_manager::ExecutorManager;
@@ -222,7 +221,7 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> SchedulerServer<T
         &self,
         job_name: &str,
         ctx: Arc<SessionContext>,
-        plan: &LogicalPlan,
+        plan: &SubmitPlan,
         subscriber: Option<JobStatusSubscriber>,
     ) -> Result<JobId> {
         log::debug!("Received submit request for job {job_name}");
@@ -438,6 +437,7 @@ mod test {
         ExecutorSpecification,
     };
 
+    use crate::scheduler_server::event::SubmitPlan;
     use crate::scheduler_server::{SchedulerServer, timestamp_millis};
 
     use crate::test_utils::{
@@ -484,7 +484,14 @@ mod test {
         // Submit job
         scheduler
             .state
-            .submit_job(&job_id, "", ctx, &plan, 0, None)
+            .submit_job(
+                &job_id,
+                "",
+                ctx,
+                &SubmitPlan::Logical(plan.clone()),
+                0,
+                None,
+            )
             .await
             .expect("submitting plan");
 
diff --git a/ballista/scheduler/src/state/mod.rs b/ballista/scheduler/src/state/mod.rs
index 726894235..6ee5f59f5 100644
--- a/ballista/scheduler/src/state/mod.rs
+++ b/ballista/scheduler/src/state/mod.rs
@@ -17,7 +17,7 @@
 
 use crate::cluster::{BallistaCluster, BoundTask, ExecutorSlot};
 use crate::config::SchedulerConfig;
-use crate::scheduler_server::event::QueryStageSchedulerEvent;
+use crate::scheduler_server::event::{QueryStageSchedulerEvent, SubmitPlan};
 use crate::state::execution_graph::TaskDescription;
 use crate::state::executor_manager::ExecutorManager;
 use crate::state::session_manager::SessionManager;
@@ -28,7 +28,6 @@ use ballista_core::serde::BallistaCodec;
 use ballista_core::serde::protobuf::TaskStatus;
 use ballista_core::{JobId, JobStatusSubscriber};
 use datafusion::execution::context::SessionContext;
-use datafusion::logical_expr::LogicalPlan;
 use datafusion_proto::logical_plan::AsLogicalPlan;
 use datafusion_proto::physical_plan::AsExecutionPlan;
 use log::{debug, error, info, warn};
@@ -366,21 +365,14 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> SchedulerState<T,
         job_id: &JobId,
         job_name: &str,
         session_ctx: Arc<SessionContext>,
-        logical_plan: &LogicalPlan,
+        plan: &SubmitPlan,
         queued_at: u64,
         subscriber: Option<JobStatusSubscriber>,
     ) -> Result<()> {
         let start = Instant::now();
 
         self.task_manager
-            .submit_job(
-                job_id,
-                job_name,
-                session_ctx,
-                logical_plan,
-                queued_at,
-                subscriber,
-            )
+            .submit_job(job_id, job_name, session_ctx, plan, queued_at, subscriber)
             .await?;
 
         let elapsed = start.elapsed();
diff --git a/ballista/scheduler/src/state/task_manager.rs b/ballista/scheduler/src/state/task_manager.rs
index 7bcbd6853..404d3dacb 100644
--- a/ballista/scheduler/src/state/task_manager.rs
+++ b/ballista/scheduler/src/state/task_manager.rs
@@ -18,7 +18,7 @@
 use crate::cluster::JobState;
 use crate::config::SchedulerConfig;
 use crate::planner::DefaultDistributedPlanner;
-use crate::scheduler_server::event::QueryStageSchedulerEvent;
+use crate::scheduler_server::event::{QueryStageSchedulerEvent, SubmitPlan};
 use crate::state::aqe::AdaptiveExecutionGraph;
 use crate::state::distributed_explain::handle_explain_plan;
 use crate::state::execution_graph::{
@@ -37,7 +37,6 @@ use ballista_core::{JobId, JobStatusSubscriber};
 use dashmap::DashMap;
 use datafusion::execution::config::SessionConfig;
 use datafusion::execution::context::SessionContext;
-use datafusion::logical_expr::LogicalPlan;
 use datafusion::physical_plan::ExecutionPlan;
 use datafusion_proto::logical_plan::AsLogicalPlan;
 use datafusion_proto::physical_plan::{AsExecutionPlan, PhysicalExtensionCodec};
@@ -283,47 +282,76 @@ impl<T: 'static + AsLogicalPlan, U: 'static + AsExecutionPlan> TaskManager<T, U>
         job_id: &JobId,
         job_name: &str,
         ctx: Arc<SessionContext>,
-        logical_plan: &LogicalPlan,
+        plan: &SubmitPlan,
         queued_at: u64,
         subscriber: Option<JobStatusSubscriber>,
     ) -> Result<()> {
         let mut planner = DefaultDistributedPlanner::new();
         let session_state = ctx.state();
         let session_config = session_state.config();
-        let mut graph = if session_config.ballista_adaptive_query_planner_enabled() {
-            debug!("Using adaptive query planner (AQE) for job planning");
-            warn!(
-                "Adaptive Query Planning is EXPERIMENTAL, should be used for testing purposes only!"
-            );
-            Box::new(
-                AdaptiveExecutionGraph::try_new(
+
+        let mut graph = match plan {
+            SubmitPlan::Logical(logical_plan) => {
+                if session_config.ballista_adaptive_query_planner_enabled() {
+                    debug!("Using adaptive query planner (AQE) for job planning");
+                    warn!(
+                        "Adaptive Query Planning is EXPERIMENTAL, should be used for testing purposes only!"
+                    );
+                    Box::new(
+                        AdaptiveExecutionGraph::try_new(
+                            &self.scheduler_id,
+                            job_id,
+                            job_name,
+                            &ctx,
+                            logical_plan,
+                            queued_at,
+                        )
+                        .await?,
+                    ) as ExecutionGraphBox
+                } else {
+                    debug!("Using static query planner for job planning");
+                    let session_config = Arc::new(ctx.copied_config());
+
+                    let physical_plan =
+                        ctx.state().create_physical_plan(logical_plan).await?;
+                    let physical_plan =
+                        handle_explain_plan(job_id, &ctx, logical_plan, physical_plan)
+                            .await?;
+
+                    Box::new(StaticExecutionGraph::new(
+                        &self.scheduler_id,
+                        job_id,
+                        job_name,
+                        &ctx.session_id(),
+                        physical_plan,
+                        queued_at,
+                        session_config,
+                        &mut planner,
+                        Some(logical_plan.display_indent().to_string()),
+                    )?) as ExecutionGraphBox
+                }
+            }
+            SubmitPlan::Physical(physical_plan) => {
+                if session_config.ballista_adaptive_query_planner_enabled() {
+                    return Err(BallistaError::NotImplemented(
+                        "Adaptive query planning (AQE) does not support jobs submitted as an already-built physical plan; disable AQE for this session or submit a logical plan instead.".to_string(),
+                    ));
+                }
+                debug!("Using static query planner for physical-plan job submission");
+                let session_config = Arc::new(ctx.copied_config());
+
+                Box::new(StaticExecutionGraph::new(
                     &self.scheduler_id,
                     job_id,
                     job_name,
-                    &ctx,
-                    logical_plan,
+                    &ctx.session_id(),
+                    physical_plan.clone(),
                     queued_at,
-                )
-                .await?,
-            ) as ExecutionGraphBox
-        } else {
-            debug!("Using static query planner for job planning");
-            let session_config = Arc::new(ctx.copied_config());
-
-            let plan = ctx.state().create_physical_plan(logical_plan).await?;
-            let plan = handle_explain_plan(job_id, &ctx, logical_plan, plan).await?;
-
-            Box::new(StaticExecutionGraph::new(
-                &self.scheduler_id,
-                job_id,
-                job_name,
-                &ctx.session_id(),
-                plan,
-                queued_at,
-                session_config,
-                &mut planner,
-                Some(logical_plan.display_indent().to_string()),
-            )?) as ExecutionGraphBox
+                    session_config,
+                    &mut planner,
+                    None,
+                )?) as ExecutionGraphBox
+            }
         };
         let string_plan =
             datafusion::physical_plan::displayable(graph.physical_plan().as_ref())
diff --git a/ballista/scheduler/src/test_utils.rs b/ballista/scheduler/src/test_utils.rs
index 4f7b29651..3ced8108e 100644
--- a/ballista/scheduler/src/test_utils.rs
+++ b/ballista/scheduler/src/test_utils.rs
@@ -54,7 +54,7 @@ use datafusion::prelude::{CsvReadOptions, JoinType, col};
 use datafusion::test_util::scan_empty_with_partitions;
 
 use crate::cluster::BallistaCluster;
-use crate::scheduler_server::event::QueryStageSchedulerEvent;
+use crate::scheduler_server::event::{QueryStageSchedulerEvent, SubmitPlan};
 
 use crate::state::execution_graph::{
     ExecutionGraph, ExecutionStage, StaticExecutionGraph, TaskDescription,
@@ -503,7 +503,10 @@ impl SchedulerTest {
             .create_or_update_session("session_id", &self.session_config)
             .await?;
 
-        let job_id = self.scheduler.submit_job(job_name, ctx, plan, None).await?;
+        let job_id = self
+            .scheduler
+            .submit_job(job_name, ctx, &SubmitPlan::Logical(plan.clone()), None)
+            .await?;
 
         Ok(job_id)
     }
@@ -642,7 +645,12 @@ impl SchedulerTest {
 
         let job_id = self
             .scheduler
-            .submit_job(job_name, ctx, plan, subscriber)
+            .submit_job(
+                job_name,
+                ctx,
+                &SubmitPlan::Logical(plan.clone()),
+                subscriber,
+            )
             .await?;
 
         let mut receiver = self.status_receiver.take().unwrap();


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org