milenkovicm commented on code in PR #2588:
URL: 
https://github.com/apache/datafusion-ballista/pull/2588#discussion_r4302542131


##########
python/src/query_planner.rs:
##########
@@ -0,0 +1,529 @@
+// 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.
+
+use crate::codec;
+use crate::ffi_planner_workaround::decode_file_formats_locally;
+use ballista_core::extension::SessionConfigExt;
+use ballista_core::planner::BallistaQueryPlanner;
+use datafusion::catalog::Session;
+use datafusion::common::{DataFusionError, Result};
+use datafusion::execution::config::SessionConfig;
+use datafusion::execution::context::QueryPlanner;
+use datafusion::logical_expr::LogicalPlan;
+use datafusion::physical_plan::ExecutionPlan;
+use datafusion_ffi::execution::FFI_TaskContextProvider;
+use datafusion_ffi::proto::logical_extension_codec::FFI_LogicalExtensionCodec;
+use 
datafusion_ffi::proto::physical_extension_codec::FFI_PhysicalExtensionCodec;
+use datafusion_ffi::query_planner::FFI_QueryPlanner;
+use datafusion_proto::logical_plan::LogicalExtensionCodec;
+use datafusion_proto::physical_plan::PhysicalExtensionCodec;
+use datafusion_proto::protobuf::LogicalPlanNode;
+use pyo3::exceptions::PyValueError;
+use pyo3::prelude::*;
+use pyo3::types::{PyCapsule, PyDict};
+use std::collections::HashMap;
+use std::ptr::NonNull;
+use std::sync::{Arc, OnceLock};
+use tokio::runtime::{Handle, Runtime};
+use url::Url;
+
+const DEFAULT_SCHEDULER_PORT: u16 = 50050;
+
+#[pyclass(
+    name = "BallistaExtension",
+    module = "ballista._internal_ballista",
+    skip_from_py_object
+)]
+pub(crate) struct PyBallistaExtension {
+    address: String,
+    config_overrides: Option<HashMap<String, String>>,
+}
+
+#[pymethods]
+impl PyBallistaExtension {
+    #[new]
+    #[pyo3(signature = (address, config_overrides=None))]
+    fn new(address: String, config_overrides: Option<HashMap<String, String>>) 
-> Self {
+        Self {
+            address,
+            config_overrides,
+        }
+    }
+
+    /// Phase one of `SessionContext.with_extensions`: contribute the Ballista
+    /// codecs, bound against the context they will run on.
+    fn __datafusion_session_components__<'py>(
+        &self,
+        py: Python<'py>,
+        session_ctx: Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, PyAny>> {
+        ballista_extension_components(py, session_ctx)
+    }
+
+    /// Phase two of `SessionContext.with_extensions`: contribute the Ballista
+    /// planner. `session_ctx` already carries the final codec chains.
+    ///
+    /// Ballista plans every query on the scheduler, so it replaces `fallback`
+    /// rather than delegating to it.
+    fn __datafusion_session_planner__<'py>(
+        &self,
+        py: Python<'py>,
+        session_ctx: Bound<'py, PyAny>,
+        _fallback: Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, PyCapsule>> {
+        ballista_extension_planner(
+            py,
+            session_ctx,
+            self.address.clone(),
+            self.config_overrides.clone(),
+        )
+    }
+}
+
+#[pyclass(
+    name = "BallistaLogicalExtensionCodec",
+    module = "ballista._internal_ballista",
+    skip_from_py_object
+)]
+pub(crate) struct PyBallistaLogicalExtensionCodec {
+    logical_codec: Arc<dyn LogicalExtensionCodec>,
+    ffi_logical_codec: FFI_LogicalExtensionCodec,
+    // Retain the source context for the legacy low-level API. Atomic extension
+    // installation leaves this empty so the returned context owns the 
provider.
+    _session_ctx: Option<Py<PyAny>>,
+}
+
+#[pymethods]
+impl PyBallistaLogicalExtensionCodec {
+    #[new]
+    fn new(session_ctx: Bound<'_, PyAny>) -> PyResult<Self> {
+        let _user_logical_codec: Arc<dyn LogicalExtensionCodec> =
+            (&ffi_logical_codec_from_python(session_ctx.clone())?).into();
+        let logical_codec: Arc<dyn LogicalExtensionCodec> =
+            Arc::new(codec::PyBallistaLogicalExtensionCodec::default());
+        let task_ctx_provider = 
ffi_task_ctx_provider_from_python(session_ctx.clone())?;
+        let ffi_logical_codec = FFI_LogicalExtensionCodec::new(
+            Arc::clone(&logical_codec),
+            Some(tokio_runtime_handle()),
+            task_ctx_provider,
+        );
+
+        Ok(Self {
+            logical_codec,
+            ffi_logical_codec,
+            _session_ctx: Some(session_ctx.unbind()),
+        })
+    }
+
+    #[pyo3(signature = (_session=None))]
+    fn __datafusion_logical_extension_codec__<'py>(
+        &self,
+        py: Python<'py>,
+        _session: Option<Bound<'py, PyAny>>,
+    ) -> PyResult<Bound<'py, PyCapsule>> {
+        PyCapsule::new_with_value(
+            py,
+            self.ffi_logical_codec.clone(),
+            cr"datafusion_logical_extension_codec",
+        )
+    }
+}
+
+#[pyclass(
+    name = "BallistaPhysicalExtensionCodec",
+    module = "ballista._internal_ballista",
+    skip_from_py_object
+)]
+pub(crate) struct PyBallistaPhysicalExtensionCodec {
+    ffi_physical_codec: FFI_PhysicalExtensionCodec,
+    // Retain the source context for the legacy low-level API. Atomic extension
+    // installation leaves this empty so the returned context owns the 
provider.
+    _session_ctx: Option<Py<PyAny>>,
+    // Retain the Python logical codec as well as its native Arc.
+    _logical_codec: Py<PyAny>,
+}
+
+impl PyBallistaPhysicalExtensionCodec {
+    fn from_logical_codec(
+        session_ctx: Bound<'_, PyAny>,
+        logical_codec: Arc<dyn LogicalExtensionCodec>,
+        logical_codec_object: Py<PyAny>,
+    ) -> PyResult<Self> {
+        let ffi_physical_codec =
+            ballista_physical_ffi_codec(session_ctx.clone(), logical_codec)?;
+
+        Ok(Self {
+            ffi_physical_codec,
+            _session_ctx: Some(session_ctx.unbind()),
+            _logical_codec: logical_codec_object,
+        })
+    }
+}
+
+#[pymethods]
+impl PyBallistaPhysicalExtensionCodec {
+    #[new]
+    fn new(
+        session_ctx: Bound<'_, PyAny>,
+        logical_codec: Bound<'_, PyAny>,
+    ) -> PyResult<Self> {
+        let native_logical_codec = {
+            let logical_codec =
+                logical_codec.extract::<PyRef<'_, 
PyBallistaLogicalExtensionCodec>>()?;
+            Arc::clone(&logical_codec.logical_codec)
+        };
+        Self::from_logical_codec(
+            session_ctx,
+            native_logical_codec,
+            logical_codec.unbind(),
+        )
+    }
+
+    #[pyo3(signature = (_session=None))]
+    fn __datafusion_physical_extension_codec__<'py>(
+        &self,
+        py: Python<'py>,
+        _session: Option<Bound<'py, PyAny>>,
+    ) -> PyResult<Bound<'py, PyCapsule>> {
+        PyCapsule::new_with_value(
+            py,
+            self.ffi_physical_codec.clone(),
+            cr"datafusion_physical_extension_codec",
+        )
+    }
+}
+
+#[pyclass(
+    name = "BallistaQueryPlanner",
+    module = "ballista._internal_ballista",
+    skip_from_py_object
+)]
+pub(crate) struct PyBallistaQueryPlanner {
+    address: String,
+    config: ballista_core::config::BallistaConfig,
+    logical_codec: Arc<dyn LogicalExtensionCodec>,
+    fallback_logical_codec: FFI_LogicalExtensionCodec,
+    fallback_physical_codec: FFI_PhysicalExtensionCodec,
+    // Retain the source context for the legacy low-level API. Atomic extension
+    // installation leaves this empty so the returned context owns the 
provider.
+    _session_ctx: Option<Py<PyAny>>,
+}
+
+#[pymethods]
+impl PyBallistaQueryPlanner {
+    #[new]
+    #[pyo3(signature = (address, session_ctx, config_overrides=None))]
+    fn new(
+        address: String,
+        session_ctx: Bound<'_, PyAny>,
+        config_overrides: Option<HashMap<String, String>>,
+    ) -> PyResult<Self> {
+        let logical_codec = 
PyBallistaLogicalExtensionCodec::new(session_ctx.clone())?;
+        let fallback_physical_codec = ballista_physical_ffi_codec(
+            session_ctx.clone(),
+            Arc::clone(&logical_codec.logical_codec),
+        )?;
+        Self::from_codecs(
+            address,
+            session_ctx,
+            config_overrides,
+            logical_codec.logical_codec,
+            logical_codec.ffi_logical_codec,
+            fallback_physical_codec,
+        )
+    }
+
+    #[pyo3(signature = (_session=None))]
+    fn __datafusion_query_planner__<'py>(
+        &self,
+        py: Python<'py>,
+        _session: Option<Bound<'py, PyAny>>,
+    ) -> PyResult<Bound<'py, PyCapsule>> {
+        let planner: Arc<dyn QueryPlanner + Send + Sync> =
+            Arc::new(LazyBallistaQueryPlanner {
+                address: self.address.clone(),
+                config: self.config.clone(),
+                logical_codec: Arc::clone(&self.logical_codec),
+                _session_ctx: self
+                    ._session_ctx
+                    .as_ref()
+                    .map(|session_ctx| session_ctx.clone_ref(py)),
+            });
+        let ffi = FFI_QueryPlanner::new_with_ffi_codecs(
+            planner,
+            self.fallback_logical_codec.clone(),
+            self.fallback_physical_codec.clone(),
+        );
+        let ffi = decode_file_formats_locally(ffi);
+
+        // This exact name is the ABI consumed by datafusion-python.
+        PyCapsule::new_with_value(py, ffi, cr"datafusion_query_planner")
+    }
+}
+
+impl PyBallistaQueryPlanner {
+    fn from_codecs(
+        address: String,
+        session_ctx: Bound<'_, PyAny>,
+        config_overrides: Option<HashMap<String, String>>,
+        logical_codec: Arc<dyn LogicalExtensionCodec>,
+        fallback_logical_codec: FFI_LogicalExtensionCodec,
+        fallback_physical_codec: FFI_PhysicalExtensionCodec,
+    ) -> PyResult<Self> {
+        let mut session_config = SessionConfig::new_with_ballista();
+        if let Some(overrides) = config_overrides {
+            for (key, value) in overrides {
+                if !key.starts_with("ballista.") {
+                    return Err(PyValueError::new_err(format!(
+                        "unsupported Ballista configuration key: {key}"
+                    )));
+                }
+                session_config
+                    .options_mut()
+                    .set(&key, &value)
+                    .map_err(|error| 
PyValueError::new_err(error.to_string()))?;
+            }
+        }
+
+        Ok(Self {
+            address,
+            config: session_config.ballista_config(),
+            logical_codec,
+            fallback_logical_codec,
+            fallback_physical_codec,
+            _session_ctx: Some(session_ctx.unbind()),
+        })
+    }
+}
+
+struct LazyBallistaQueryPlanner {
+    address: String,
+    config: ballista_core::config::BallistaConfig,
+    logical_codec: Arc<dyn LogicalExtensionCodec>,
+    _session_ctx: Option<Py<PyAny>>,
+}
+
+impl std::fmt::Debug for LazyBallistaQueryPlanner {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("LazyBallistaQueryPlanner")
+            .field("address", &self.address)
+            .field("config", &self.config)
+            .finish_non_exhaustive()
+    }
+}
+
+#[async_trait::async_trait]
+impl QueryPlanner for LazyBallistaQueryPlanner {
+    async fn create_physical_plan(
+        &self,
+        logical_plan: &LogicalPlan,
+        session: &dyn Session,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        if matches!(logical_plan, LogicalPlan::Analyze(_)) {

Review Comment:
   this should work now 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to