You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "viirya (via GitHub)" <gi...@apache.org> on 2026/09/21 06:48:25 UTC
[PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
viirya opened a new pull request, #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071
## Which issue does this PR close?
Closes #1204.
## Rationale for this change
Comet currently repeats native plan construction for tasks executing the same
native block. For workloads with many short tasks and wide expression trees,
this adds CPU and allocation overhead.
This PR allows tasks within the same executor, Spark stage attempt, and native
block to execute the same DataFusion physical plan using their partition IDs.
It requires no changes to DataFusion.
## What changes are included in this PR?
- Add an executor-local cache for decoded protobuf plan definitions.
- Add a stage-scoped registry for sharing actual DataFusion physical operators.
Task-specific inputs are bound through TaskContext.
- Support eligible JVM-input pipelines containing projection, filter,
COUNT/SUM/AVG/MIN/MAX aggregates, partitioned hash joins, and full sorts.
- Isolate execution by stage attempt and partition, and attribute metrics by
partition. Retries, speculative attempts, and duplicate partition claims use
private native plans.
- Fall back to private native plans for unsupported blocks, including native
file scans, shuffle operators, Top-K, and positive sort offsets.
- Use weak registry references so physical plans and their metrics can be
released when the last task releases its reference. Idle gaps may therefore
cause rebuilding.
- Keep both configuration options internal and disabled by default.
Initial shared-plan construction currently holds the registry mutex, which
can block lookups for unrelated plans.
## How are these changes tested?
Correctness and lifecycle validation:
- 22 native shared-plan tests and 11 decoded-plan cache tests.
- 155 tests across CometExecSuite and CometExecIteratorLifecycleSuite.
- Spark SQL `dev/local-ci.sh spark sql_core-1` with both options enabled:
12,861 passed, 0 failed.
- Coverage includes actual operator identity, concurrent partitions, output
equivalence with private plans, retry isolation, partition metrics,
aggregate modes, DISTINCT aggregates, and plan/metrics reclamation.
- Rust formatting, Clippy, JVM formatting, and license checks passed during
development.
The PR branch retains the implementation and correctness tests byte-for-byte
from the validated development branch. After extracting this branch, diff,
Rust formatting, and CI suite-registration checks were rerun; the full test
suites were not rerun.
Performance measurements used Spark 4.1.3, local[4], 1,024 partitions, and
32 rows per partition on an Apple M4 Max. Timing measurements used two JVM
runs, alternating disabled/enabled modes, with four warmups and eight timed
iterations per mode and case in each run.
| Workload | Task CPU | Process CPU | Rust allocated bytes | Query elapsed time |
|---|---:|---:|---:|---:|
| 16-column projection/filter | -39.7% | -24.9% | -56.1% | -4.0% |
| 64-column projection/filter | -55.8% | -46.7% | -65.6% | -12.6% |
Allocation was measured separately with diagnostic instrumentation and
represents cumulative requested Rust allocation bytes, not peak memory.
Both decoded-plan caching and physical-plan sharing were enabled, so these
results do not isolate their individual contributions.
Wide aggregates did not show a meaningful elapsed-time improvement, and the
measurements did not establish a reduction in peak process memory. These
results describe a local short-task workload, not multi-executor production
performance.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#discussion_r4073736402
##########
native/core/src/execution/plan_cache.rs:
##########
@@ -0,0 +1,455 @@
+// 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.
+
+//! Executor-local reuse of immutable protobuf plans and bounded single-flight cache (#1204).
+//!
+//! The definition cache here owns protobuf data only. `shared_pipeline` separately uses the
+//! generic cache for audited immutable physical trees. Neither cache may retain task resources.
+//! Different partitions' scan payloads must remain different definition-cache keys.
+
+use std::collections::HashMap;
+use std::sync::{Arc, LazyLock};
+use std::time::Instant;
+
+use datafusion_comet_proto::spark_operator::Operator;
+use once_cell::sync::OnceCell;
+use parking_lot::Mutex;
+
+use super::operators::ExecutionError;
+use super::serde::deserialize_op;
+
+const MAX_ENTRIES: usize = 64;
+const MAX_ENCODED_BYTES: usize = 8 * 1024 * 1024;
+
+// Process-local because tasks do not share a SessionContext. This cache owns only immutable
+// protobuf data, never storage clients, JNI references or task resources. Exact bytes are
+// compared, so neither hash collisions nor another query's configuration can change the decoded
+// result. Retention is bounded by entry count and encoded bytes, and release_runtime clears it.
+// The byte budget accounts for keys, not the decoded Rust heap (which can be larger).
+static PLAN_CACHE: LazyLock<PlanCache<Operator>> =
+ LazyLock::new(|| PlanCache::new(MAX_ENTRIES, MAX_ENCODED_BYTES));
+
+pub(super) fn decode_plan(
Review Comment:
`CometExecRDD.compute` injects per-partition planning data for native scans (`PlanDataInjector.injectPlanData`), so every task in those stages sends different bytes. With the cache on, each of those tasks misses, copies its full plan into a new entry, and evicts entries that other stages could have reused. Could we skip the cache when per-partition plan data was injected, or key on the base plan instead? A test showing that a stage with distinct per-task bytes doesn't evict a reusable entry would help guard this.
##########
native/core/src/execution/jni_api.rs:
##########
@@ -967,11 +994,35 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_executePlan(
.with_shuffle_partition_pusher(
exec_context.shuffle_partition_pusher.clone(),
);
- let (scans, shuffle_scans, root_op) = planner.create_plan(
- &exec_context.spark_plan,
- &mut exec_context.input_sources.clone(),
- exec_context.partition_count,
- )?;
+ let (scans, shuffle_scans, root_op) =
+ if let Some(key) = &exec_context.shared_plan_key {
+ let shared = super::shared_pipeline::get_or_build(
Review Comment:
If the shared build fails, for example when `convert_tree` hits `Unexpected operator in shared tree`, the `?` here fails the task. Could we fall back to `planner.create_plan` in that case and log it? Admission and the planner agree today, but a later planner change that adds a wrapper operator would otherwise break queries whenever the flag is on.
##########
spark/src/test/scala/org/apache/spark/CometExecIteratorLifecycleSuite.scala:
##########
@@ -192,12 +235,15 @@ class CometExecIteratorLifecycleSuite extends CometTestBase {
schema,
CometArrowStream.NATIVE_TIMEZONE,
"lifecycle-test")
- val limitOp =
- CometExecUtils.getLimitNativePlan(Seq(PrettyAttribute("test", LongType)), 100).get
+ val scanOp =
Review Comment:
Could you explain the change from the limit plan to a bare scan plan here? It looks like the original limit case is no longer covered by this lifecycle test.
##########
spark/src/test/scala/org/apache/comet/exec/CometExecSuite.scala:
##########
@@ -90,6 +93,114 @@ class CometExecSuite extends CometTestBase {
}
}
+ test("native plan cache setting crosses JNI for both enabled and disabled execution") {
+ for (enabled <- Seq("true", "false")) {
+ withSQLConf(CometConf.COMET_EXEC_PLAN_CACHE_ENABLED.key -> enabled) {
+ val configs = ConfigMap.parseFrom(CometExecIterator.serializeCometSQLConfs())
+ assert(configs.getEntriesMap.get(CometConf.COMET_EXEC_PLAN_CACHE_ENABLED.key) == enabled)
+ withParquetTable((0 until 32).map(i => (i, i + 1)), "plan_cache_input") {
+ checkSparkAnswerAndOperator(
+ sql("SELECT _1 + 1 FROM plan_cache_input WHERE _2 > 8"),
+ Seq(classOf[CometProjectExec]))
+ }
+ }
+ }
+ }
+
+ test("shared native pipelines across task waves and AQE") {
+ for (enabled <- Seq("true", "false"); aqe <- Seq("true", "false")) {
+ withSQLConf(
+ CometConf.COMET_EXEC_SHARED_PLAN_ENABLED.key -> enabled,
+ CometConf.COMET_EXEC_PLAN_CACHE_ENABLED.key -> "false",
+ CometConf.COMET_EXPLAIN_NATIVE_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe,
+ SQLConf.ARROW_EXECUTION_MAX_RECORDS_PER_BATCH.key -> "17") {
+ val configs = ConfigMap.parseFrom(CometExecIterator.serializeCometSQLConfs())
+ assert(configs.getEntriesMap.get(CometConf.COMET_EXEC_SHARED_PLAN_ENABLED.key) == enabled)
+ for (_ <- 0 until 2) {
+ val df = spark.range(0, 1000, 1, 16).where("id > 100").selectExpr("id + 10 AS value")
+ val (_, nativePlan) = checkSparkAnswerAndOperator(df, Seq(classOf[CometProjectExec]))
+ val projects = stripAQEPlan(nativePlan).collect { case p: CometProjectExec => p }
+ assert(projects.nonEmpty)
+ assert(projects.head.metrics("output_rows").value == 899L)
+ }
+ val empty = spark.range(0, 100, 1, 16).where("id < 0").selectExpr("id + 10 AS value")
+ checkSparkAnswerAndOperator(empty, Seq(classOf[CometProjectExec]))
+ // Stateful expressions in an otherwise eligible JVM-input block use private plans.
+ val stateful = spark
+ .range(0, 100, 1, 16)
+ .selectExpr("spark_partition_id() AS partition", "monotonically_increasing_id() AS id")
+ checkSparkAnswerAndOperator(stateful, Seq(classOf[CometProjectExec]))
+ }
+ }
+ }
+
+ test("shared DataFusion stateful operators across Spark partitions") {
Review Comment:
These tests use `checkSparkAnswerAndOperator`, which passes whether or not a shared tree was used. I think the post-shuffle Final aggregates and joins here read through `ShuffleScan`, so they probably run on private plans even with the flag on. Could we expose a small counter or test hook for shared-tree binds and assert on it? Asserting the expected fallback cases would be useful too.
##########
spark/src/test/scala/org/apache/comet/exec/CometExecSuite.scala:
##########
@@ -63,7 +63,10 @@ class CometExecSuite extends CometTestBase {
override protected def test(testName: String, testTags: Tag*)(testFun: => Any)(implicit
pos: Position): Unit = {
super.test(testName, testTags: _*) {
- withSQLConf(CometConf.COMET_SHUFFLE_ENABLED.key -> "true") {
+ withSQLConf(
+ CometConf.COMET_SHUFFLE_ENABLED.key -> "true",
+ CometConf.COMET_EXEC_PLAN_CACHE_ENABLED.key -> "true",
+ CometConf.COMET_EXEC_SHARED_PLAN_ENABLED.key -> "true") {
Review Comment:
This override (and the matching one in `CometExecIteratorLifecycleSuite`) turns on both flags for every existing test in the suite. The flag-off path, which is what users run by default, loses that coverage here. Could we enable the flags only in the new tests, or run the affected tests in both modes?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#issuecomment-5782248930
Review follow-up in ffdbbd2df833c99902c44dbc1f436520342badf3:
- Removed the decoded-plan cache and its config rather than splitting it into another PR. The existing off/cache-only measurements showed only approximately 0.2%–1.4% elapsed-time reductions, insufficient evidence to justify its retention, eviction, and synchronization complexity. This PR now focuses on physical-plan sharing.
- Added private-plan fallback for shared construction failures, explicit shared-task metrics and path assertions, restored default-mode suite coverage, and retained the original limit lifecycle test alongside a separately verified shared-scan case.
- Local validation passed: 23 native shared-pipeline tests, one native metrics test, and 176 JVM tests across CometExecSuite, CometExecIteratorLifecycleSuite, and CometTaskMetricsSuite. Rust formatting, Clippy, JVM formatting/style, and suite-registration checks also passed. The Spark 4.1 SQL gate has been requested with `run-spark-4.1-tests`; its result is pending.
Still outstanding: sharing-only versus disabled measurements after cache removal; TPC-H/TPC-DS admission and actual-bind coverage with normal defaults preserved apart from enabling sharing; and documenting/validating the execution-state assumptions for admitted DataFusion operators. The targeted positive-path tests deliberately configure eligible inputs and are not evidence of default-workload coverage.
The metrics-scaling finding remains open. We plan to address it through partition-specific metrics access in DataFusion, integrate that API, and rerun the matched large-stage/long-lived-task benchmark. The remaining sharing config defaults to false, which limits default-user exposure but does not resolve the performance issue for users who enable it. I updated the PR description to distinguish current validation from historical measurements and outstanding work.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#discussion_r4115855158
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2196 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
Review Comment:
If construction fails deterministically, for example the `Unexpected operator in shared tree` case this fallback exists for, nothing records the failure. Every later task with that key repeats the failing build while holding the process-wide registry lock. All shared-mode tasks on the executor queue behind it, and each one logs a warning before planning privately. Could a failed key be remembered, for example with a tombstone entry that sends later lookups straight to private planning, with the warning logged once per key?
##########
native/core/src/execution/jni_api.rs:
##########
@@ -1162,7 +1218,12 @@ pub extern "system" fn Java_org_apache_comet_Native_releasePlan(
fn update_metrics(env: &mut Env, exec_context: &mut ExecutionContext) -> CometResult<()> {
if let Some(native_query) = &exec_context.root_op {
let metrics = exec_context.metrics.as_obj();
- update_comet_metric(env, metrics, native_query)
+ update_comet_metric(
+ env,
+ metrics,
+ native_query,
+ exec_context.shared_attempt.as_deref(),
Review Comment:
`update_metrics` now reports only this attempt's metrics, but `log_plan_metrics` just below still renders `plan.native_plan` with `DisplayableExecutionPlan::with_metrics`. For a shared attempt that is the shared root, so the output aggregates every partition that has run on the tree so far. The log line carries this task's partition number, but the numbers are cumulative across the stage. The scan leaf also shows nothing because `SharedInputExec` has no metrics. This is the output people use when debugging spills. Could shared attempts log metrics selected through `AttemptState::metrics_for`, or at least say in the log line that the numbers are cumulative?
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2196 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+/// Only shared construction is recoverable: it has not imported task-owned input streams.
+/// Binding or execution errors must propagate rather than retrying consumed resources.
+pub(super) fn try_build<T>(
+ build: impl FnOnce() -> std::result::Result<T, ExecutionError>,
+) -> Option<T> {
+ match build() {
+ Ok(plan) => Some(plan),
+ Err(error) => {
+ log::warn!("Cannot construct shared native plan; using a private plan: {error}");
+ None
+ }
+ }
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
+ .with_sql_text_pool(plan)
+ .with_input_plans(Arc::clone(&input_plans));
+ let (_, _, original) = planner.create_plan(plan, &mut vec![], 1)?;
+ let identity = Arc::new(());
+ let mut mapping = Vec::new();
+ convert_tree(
+ &original.native_plan,
+ &identity,
+ &input_plans.lock(),
+ &mut mapping,
+ partition_count,
+ )?;
+ let root = convert_spark_tree(&original, &mapping)?;
+ let mut definitions = Vec::new();
+ input_definitions(plan, &mut definitions);
+ let scan_definitions = definitions
+ .into_iter()
+ .map(|p| {
+ let mut p = p.clone();
+ if let Some(OpStruct::NativeScan(scan)) = p.op_struct.as_mut() {
+ scan.file_partition = None;
Review Comment:
`supports` rejects `NativeScan`, so this `file_partition` reset can never run. The same goes for the `NativeScan` arm in `input_definitions` and the two `self.input_plan(...)` hooks in the `NativeScan` branch of `planner.rs` (lines 1647 and 1769). The `spark_plan` doc comment at `jni_api.rs:398` still says the plan may be shared across task attempts, which stopped being true when the decoded cache went away, and the `Arc` is no longer needed. In the tests, `full_sort_and_cancellation_have_private_state` still loops over a single `(None, None)` and mentions Top-K's threshold. Could these leftovers from earlier revisions go? The admission code is the audit boundary for this feature, so it should only describe what is actually admitted.
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2196 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+/// Only shared construction is recoverable: it has not imported task-owned input streams.
+/// Binding or execution errors must propagate rather than retrying consumed resources.
+pub(super) fn try_build<T>(
+ build: impl FnOnce() -> std::result::Result<T, ExecutionError>,
+) -> Option<T> {
+ match build() {
+ Ok(plan) => Some(plan),
+ Err(error) => {
+ log::warn!("Cannot construct shared native plan; using a private plan: {error}");
+ None
+ }
+ }
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
Review Comment:
The builder relies on `PhysicalPlanner::new` defaulting to `TEST_EXEC_CONTEXT_ID`. That is what makes the `Scan` branch in `planner.rs` build a `ScanExec` with no input, and that branch is documented as unit-test only. A later change to the test path would then silently change production shared builds. Could the builder ask for placeholder scans explicitly, for example keyed off `input_plans` being set?
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2154 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use prost::Message;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+pub(super) fn cache_bytes<'a>(plan: &Operator, original: &'a [u8]) -> std::borrow::Cow<'a, [u8]> {
+ fn has_files(plan: &Operator) -> bool {
+ matches!(plan.op_struct, Some(OpStruct::NativeScan(_)))
+ || plan.children.iter().any(has_files)
+ }
+ if has_files(plan) {
+ std::borrow::Cow::Owned(template_bytes(plan))
+ } else {
+ std::borrow::Cow::Borrowed(original)
+ }
+}
+
+/// Legacy file-list normalization. Native scans are currently rejected by admission,
+/// so this does not expand the set of trees eligible for sharing.
+pub(super) fn template_bytes(plan: &Operator) -> Vec<u8> {
+ fn normalize(plan: &mut Operator) {
+ if let Some(OpStruct::NativeScan(scan)) = plan.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ for child in &mut plan.children {
+ normalize(child);
+ }
+ }
+ let mut template = plan.clone();
+ normalize(&mut template);
+ template.encode_to_vec()
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
+ .with_sql_text_pool(plan)
+ .with_input_plans(Arc::clone(&input_plans));
+ let (_, _, original) = planner.create_plan(plan, &mut vec![], 1)?;
+ let identity = Arc::new(());
+ let mut mapping = Vec::new();
+ convert_tree(
+ &original.native_plan,
+ &identity,
+ &input_plans.lock(),
+ &mut mapping,
+ partition_count,
+ )?;
+ let root = convert_spark_tree(&original, &mapping)?;
+ let mut definitions = Vec::new();
+ input_definitions(plan, &mut definitions);
+ let scan_definitions = definitions
+ .into_iter()
+ .map(|p| {
+ let mut p = p.clone();
+ if let Some(OpStruct::NativeScan(scan)) = p.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ p
+ })
+ .collect();
+ Ok(Arc::new(Self {
+ root,
+ scan_definitions,
+ identity,
+ partition_count,
+ claimed_partitions: Mutex::new(HashSet::new()),
+ }))
+ }
+
+ #[cfg(test)]
+ fn bind(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ self.bind_definitions(
+ planner,
+ inputs,
+ &self.scan_definitions.iter().collect::<Vec<_>>(),
+ 0,
+ )
+ }
+
+ pub fn try_bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<Option<BoundAttempt>, ExecutionError> {
+ if !self.try_claim_partition(planner.partition() as usize) {
+ return Ok(None);
+ }
+ self.bind_plan(planner, inputs, task_plan).map(Some)
+ }
+
+ fn bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ let mut definitions = Vec::new();
+ input_definitions(task_plan, &mut definitions);
+ self.bind_definitions(planner, inputs, &definitions, planner.partition() as usize)
+ }
+
+ fn bind_definitions(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ definitions: &[&Operator],
+ partition: usize,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ if partition >= self.partition_count || definitions.len() != self.scan_definitions.len() {
+ return Err(ExecutionError::GeneralError(
+ "Shared input binding count mismatch".into(),
+ ));
+ }
+ let mut scans = Vec::new();
+ let mut bound_inputs = Vec::new();
+ for definition in definitions {
+ let (jvm_scans, _, input) = planner.create_plan(definition, inputs, 1)?;
+ scans.extend(jvm_scans);
+ bound_inputs.push(Arc::clone(&input.native_plan));
+ }
+ let attempt = Arc::new(AttemptState {
+ inputs: bound_inputs,
+ _owner: Arc::clone(self),
+ identity: Arc::clone(&self.identity),
+ started: (0..definitions.len())
+ .map(|_| AtomicBool::new(false))
+ .collect(),
+ partition,
+ });
+ Ok((scans, attempt))
+ }
+}
+
+/// Owned by one Spark task attempt. The shared tree contains no input readers,
+/// memory pools or TaskContext belonging to an attempt. Metrics are partition-labelled.
+#[derive(Debug)]
+pub(crate) struct AttemptState {
+ inputs: Vec<Arc<dyn ExecutionPlan>>,
+ _owner: Arc<SharedPipeline>,
+ identity: Arc<()>,
+ started: Vec<AtomicBool>,
+ partition: usize,
+}
+
+impl AttemptState {
+ pub fn partition(&self) -> usize {
+ self.partition
+ }
+
+ pub fn task_context(self: &Arc<Self>, session: &SessionContext) -> Arc<TaskContext> {
+ let context = TaskContext::from(session);
+ let config = context
+ .session_config()
+ .clone()
+ .with_extension(Arc::clone(self));
+ Arc::new(context.with_session_config(config))
+ }
+
+ pub fn metrics_for(&self, plan: &Arc<dyn ExecutionPlan>) -> Option<MetricsSet> {
+ if let Some(input) = plan.downcast_ref::<SharedInputExec>() {
+ if !Arc::ptr_eq(&self.identity, &input.identity) {
+ return None;
+ }
+ self.inputs[input.index].metrics()
+ } else {
+ plan.metrics().map(|metrics| {
+ let mut selected = MetricsSet::new();
+ for metric in metrics
+ .iter()
+ .filter(|m| m.partition() == Some(self.partition))
Review Comment:
One thing to check when you integrate apache/datafusion#25583. It removes the snapshot cost, but each executed partition still leaves its metric handles in every operator's `ExecutionPlanMetricsSet` until the tree drops. That's six baseline metrics per operator plus the operator-specific ones. In the long-task case one tree serves the whole stage, so this is native memory that grows with stage size and that no pool accounts for. Could the rerun of the 8,192-partition benchmark also report retained bytes? If it turns out to be material, the partition cap you prototyped bounds both the CPU and the memory side.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#issuecomment-5765361206
Review follow-up:
- The JNI signature assertion is fixed in c2e48d2a4225e38436b5669e1af881b468d09838. The full `CometNativeShuffleSuite` passed locally on Spark 4.1 (57 tests).
- I completed matched off / decoded-cache-only / sharing measurements. All 144 timed Spark samples matched a Comet-disabled reference. The table below compares sharing with **decoded-cache-only**, so protobuf caching is enabled on both sides.
| Workload | Partitions | Cache-only elapsed | Sharing elapsed | Elapsed change | Task CPU change |
|---|---:|---:|---:|---:|---:|
| Ordinary projection/filter, 16 columns | 1,024 | 506 ms | 494 ms | -2.4% | -38.6% |
| Ordinary projection/filter, 64 columns | 1,024 | 1,408 ms | 1,215 ms | -13.7% | -55.6% |
| Long-task projection/filter, 16 columns | 1,024 | 731 ms | 521 ms | -28.7% | -42.8% |
| Long-task projection/filter, 16 columns | 8,192 | 5,908 ms | 8,005 ms | +35.5% | +21.6% |
These are pooled medians from two sequential JVMs on M4 Max, Spark 4.1.3, `local[4]`, 32 input rows per partition. The ordinary workload uses Range input, batch size 8,192, four warmups and eight measured rounds per mode/JVM. The long-task workload uses RDD row input and batch size 16. Partition 0 pauses after the first batch until the other tasks complete. It uses two warmups and four measured rounds per mode/JVM, with assertions checking the gate and task completion order. The ordinary and long-task workloads should not be compared directly with each other. Mode order rotates between rounds.
The separate release-mode native probe also completed three repetitions per configuration with real operators and a held partition-0 stream. Cumulative snapshot/filter time in sharing mode was 51.3 ms, 3.90 s and 133.6 s at 1,024, 8,192 and 32,768 partitions. Cache-only was 0.142 ms, 1.11 ms and 4.84 ms. These are mechanism timings over the completed short partitions, not Spark query timings.
The metrics finding remains open. The long-task Spark result confirms a regression, while the native probe establishes the snapshot scaling mechanism. The short-task gains do not justify merging the current reporting path. A bound on the number of partitions served by each physical tree is a possible approach without changing DataFusion, but its reuse/construction tradeoff still needs validation. I have not applied that change or treated this issue as resolved. Per-key registry build slots address a separate lock-contention issue.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#discussion_r4067192287
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2154 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use prost::Message;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+pub(super) fn cache_bytes<'a>(plan: &Operator, original: &'a [u8]) -> std::borrow::Cow<'a, [u8]> {
+ fn has_files(plan: &Operator) -> bool {
+ matches!(plan.op_struct, Some(OpStruct::NativeScan(_)))
+ || plan.children.iter().any(has_files)
+ }
+ if has_files(plan) {
+ std::borrow::Cow::Owned(template_bytes(plan))
+ } else {
+ std::borrow::Cow::Borrowed(original)
+ }
+}
+
+/// Legacy file-list normalization. Native scans are currently rejected by admission,
+/// so this does not expand the set of trees eligible for sharing.
+pub(super) fn template_bytes(plan: &Operator) -> Vec<u8> {
+ fn normalize(plan: &mut Operator) {
+ if let Some(OpStruct::NativeScan(scan)) = plan.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ for child in &mut plan.children {
+ normalize(child);
+ }
+ }
+ let mut template = plan.clone();
+ normalize(&mut template);
+ template.encode_to_vec()
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
+ .with_sql_text_pool(plan)
+ .with_input_plans(Arc::clone(&input_plans));
+ let (_, _, original) = planner.create_plan(plan, &mut vec![], 1)?;
+ let identity = Arc::new(());
+ let mut mapping = Vec::new();
+ convert_tree(
+ &original.native_plan,
+ &identity,
+ &input_plans.lock(),
+ &mut mapping,
+ partition_count,
+ )?;
+ let root = convert_spark_tree(&original, &mapping)?;
+ let mut definitions = Vec::new();
+ input_definitions(plan, &mut definitions);
+ let scan_definitions = definitions
+ .into_iter()
+ .map(|p| {
+ let mut p = p.clone();
+ if let Some(OpStruct::NativeScan(scan)) = p.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ p
+ })
+ .collect();
+ Ok(Arc::new(Self {
+ root,
+ scan_definitions,
+ identity,
+ partition_count,
+ claimed_partitions: Mutex::new(HashSet::new()),
+ }))
+ }
+
+ #[cfg(test)]
+ fn bind(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ self.bind_definitions(
+ planner,
+ inputs,
+ &self.scan_definitions.iter().collect::<Vec<_>>(),
+ 0,
+ )
+ }
+
+ pub fn try_bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<Option<BoundAttempt>, ExecutionError> {
+ if !self.try_claim_partition(planner.partition() as usize) {
+ return Ok(None);
+ }
+ self.bind_plan(planner, inputs, task_plan).map(Some)
+ }
+
+ fn bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ let mut definitions = Vec::new();
+ input_definitions(task_plan, &mut definitions);
+ self.bind_definitions(planner, inputs, &definitions, planner.partition() as usize)
+ }
+
+ fn bind_definitions(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ definitions: &[&Operator],
+ partition: usize,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ if partition >= self.partition_count || definitions.len() != self.scan_definitions.len() {
+ return Err(ExecutionError::GeneralError(
+ "Shared input binding count mismatch".into(),
+ ));
+ }
+ let mut scans = Vec::new();
+ let mut bound_inputs = Vec::new();
+ for definition in definitions {
+ let (jvm_scans, _, input) = planner.create_plan(definition, inputs, 1)?;
+ scans.extend(jvm_scans);
+ bound_inputs.push(Arc::clone(&input.native_plan));
+ }
+ let attempt = Arc::new(AttemptState {
+ inputs: bound_inputs,
+ _owner: Arc::clone(self),
+ identity: Arc::clone(&self.identity),
+ started: (0..definitions.len())
+ .map(|_| AtomicBool::new(false))
+ .collect(),
+ partition,
+ });
+ Ok((scans, attempt))
+ }
+}
+
+/// Owned by one Spark task attempt. The shared tree contains no input readers,
+/// memory pools or TaskContext belonging to an attempt. Metrics are partition-labelled.
+#[derive(Debug)]
+pub(crate) struct AttemptState {
+ inputs: Vec<Arc<dyn ExecutionPlan>>,
+ _owner: Arc<SharedPipeline>,
+ identity: Arc<()>,
+ started: Vec<AtomicBool>,
+ partition: usize,
+}
+
+impl AttemptState {
+ pub fn partition(&self) -> usize {
+ self.partition
+ }
+
+ pub fn task_context(self: &Arc<Self>, session: &SessionContext) -> Arc<TaskContext> {
+ let context = TaskContext::from(session);
+ let config = context
+ .session_config()
+ .clone()
+ .with_extension(Arc::clone(self));
+ Arc::new(context.with_session_config(config))
+ }
+
+ pub fn metrics_for(&self, plan: &Arc<dyn ExecutionPlan>) -> Option<MetricsSet> {
+ if let Some(input) = plan.downcast_ref::<SharedInputExec>() {
+ if !Arc::ptr_eq(&self.identity, &input.identity) {
+ return None;
+ }
+ self.inputs[input.index].metrics()
+ } else {
+ plan.metrics().map(|metrics| {
+ let mut selected = MetricsSet::new();
+ for metric in metrics
+ .iter()
+ .filter(|m| m.partition() == Some(self.partition))
Review Comment:
Thanks for identifying this. After investigating the alternatives, we plan to propose an upstream DataFusion PR to add partition-specific metrics access. The intent is to support indexed retrieval in `ExecutionPlanMetricsSet` and expose it through `ExecutionPlan`, so Comet can retrieve a task's metrics without cloning and scanning metrics from all previously executed partitions. A convenience API that still filters a full snapshot would not address the underlying cost.
We also experimented with bounding the number of partitions sharing each tree. That removed the large-stage regression in our local benchmark, but it sacrifices plan reuse and introduces scheduling-dependent tradeoffs. We would prefer to address the metrics API in DataFusion rather than make that workaround part of Comet's design.
Both new configs are currently disabled by default, so this does not affect users running with the defaults. Users explicitly enabling physical-plan sharing can still encounter this issue; it remains unresolved until the upstream API improvement is available and integrated. We will follow up with the DataFusion PR and rerun the matched large-stage/long-lived-task benchmark against the cache-only control after integration.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#discussion_r4127282625
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2196 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
Review Comment:
Addressed in `b02b2b9f3`. Failed builds now leave a tombstone, so subsequent lookups for that key fall back directly to private planning without repeating construction or logging.
Tombstones share the registry’s 64-entry / 8-MiB key limits and can be evicted under capacity pressure. The warning is therefore once per **resident failed key**, rather than once for the executor’s lifetime. Keys that cannot be retained remain subject to those limits. Added regression coverage for failed-key suppression, capacity limits, and preservation of live entries.
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2196 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+/// Only shared construction is recoverable: it has not imported task-owned input streams.
+/// Binding or execution errors must propagate rather than retrying consumed resources.
+pub(super) fn try_build<T>(
+ build: impl FnOnce() -> std::result::Result<T, ExecutionError>,
+) -> Option<T> {
+ match build() {
+ Ok(plan) => Some(plan),
+ Err(error) => {
+ log::warn!("Cannot construct shared native plan; using a private plan: {error}");
+ None
+ }
+ }
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
Review Comment:
Addressed in `b02b2b9f3`. Setting `input_plans` now explicitly requests placeholder scans without importing task inputs. Shared construction no longer depends on `TEST_EXEC_CONTEXT_ID` to obtain that behavior.
Added a regression test using a non-test execution ID and no task inputs.
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2196 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+/// Only shared construction is recoverable: it has not imported task-owned input streams.
+/// Binding or execution errors must propagate rather than retrying consumed resources.
+pub(super) fn try_build<T>(
+ build: impl FnOnce() -> std::result::Result<T, ExecutionError>,
+) -> Option<T> {
+ match build() {
+ Ok(plan) => Some(plan),
+ Err(error) => {
+ log::warn!("Cannot construct shared native plan; using a private plan: {error}");
+ None
+ }
+ }
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
+ .with_sql_text_pool(plan)
+ .with_input_plans(Arc::clone(&input_plans));
+ let (_, _, original) = planner.create_plan(plan, &mut vec![], 1)?;
+ let identity = Arc::new(());
+ let mut mapping = Vec::new();
+ convert_tree(
+ &original.native_plan,
+ &identity,
+ &input_plans.lock(),
+ &mut mapping,
+ partition_count,
+ )?;
+ let root = convert_spark_tree(&original, &mapping)?;
+ let mut definitions = Vec::new();
+ input_definitions(plan, &mut definitions);
+ let scan_definitions = definitions
+ .into_iter()
+ .map(|p| {
+ let mut p = p.clone();
+ if let Some(OpStruct::NativeScan(scan)) = p.op_struct.as_mut() {
+ scan.file_partition = None;
Review Comment:
Addressed in `b02b2b9f3`. Removed the unreachable native-scan normalization and input-recording paths, made the deserialized `spark_plan` task-local without the unnecessary `Arc`, and removed the single-iteration sort-test loop and obsolete Top-K comments.
The contributor guide now documents the admitted operators and expressions, together with the execution-state assumptions to audit when expanding admission or upgrading DataFusion.
##########
native/core/src/execution/jni_api.rs:
##########
@@ -1162,7 +1218,12 @@ pub extern "system" fn Java_org_apache_comet_Native_releasePlan(
fn update_metrics(env: &mut Env, exec_context: &mut ExecutionContext) -> CometResult<()> {
if let Some(native_query) = &exec_context.root_op {
let metrics = exec_context.metrics.as_obj();
- update_comet_metric(env, metrics, native_query)
+ update_comet_metric(
+ env,
+ metrics,
+ native_query,
+ exec_context.shared_attempt.as_deref(),
Review Comment:
Addressed using the explicit-labeling option in `b02b2b9f3`. Shared-plan explain logs now say that their metrics are cumulative across the shared tree’s partitions and that task-local scan metrics are omitted. Private-plan logs are labeled task-local.
This clarifies the existing display behavior; it does not implement a partition-specific explain renderer. SQL metric reporting continues to select the current attempt’s metrics.
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2154 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use prost::Message;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+pub(super) fn cache_bytes<'a>(plan: &Operator, original: &'a [u8]) -> std::borrow::Cow<'a, [u8]> {
+ fn has_files(plan: &Operator) -> bool {
+ matches!(plan.op_struct, Some(OpStruct::NativeScan(_)))
+ || plan.children.iter().any(has_files)
+ }
+ if has_files(plan) {
+ std::borrow::Cow::Owned(template_bytes(plan))
+ } else {
+ std::borrow::Cow::Borrowed(original)
+ }
+}
+
+/// Legacy file-list normalization. Native scans are currently rejected by admission,
+/// so this does not expand the set of trees eligible for sharing.
+pub(super) fn template_bytes(plan: &Operator) -> Vec<u8> {
+ fn normalize(plan: &mut Operator) {
+ if let Some(OpStruct::NativeScan(scan)) = plan.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ for child in &mut plan.children {
+ normalize(child);
+ }
+ }
+ let mut template = plan.clone();
+ normalize(&mut template);
+ template.encode_to_vec()
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
+ .with_sql_text_pool(plan)
+ .with_input_plans(Arc::clone(&input_plans));
+ let (_, _, original) = planner.create_plan(plan, &mut vec![], 1)?;
+ let identity = Arc::new(());
+ let mut mapping = Vec::new();
+ convert_tree(
+ &original.native_plan,
+ &identity,
+ &input_plans.lock(),
+ &mut mapping,
+ partition_count,
+ )?;
+ let root = convert_spark_tree(&original, &mapping)?;
+ let mut definitions = Vec::new();
+ input_definitions(plan, &mut definitions);
+ let scan_definitions = definitions
+ .into_iter()
+ .map(|p| {
+ let mut p = p.clone();
+ if let Some(OpStruct::NativeScan(scan)) = p.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ p
+ })
+ .collect();
+ Ok(Arc::new(Self {
+ root,
+ scan_definitions,
+ identity,
+ partition_count,
+ claimed_partitions: Mutex::new(HashSet::new()),
+ }))
+ }
+
+ #[cfg(test)]
+ fn bind(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ self.bind_definitions(
+ planner,
+ inputs,
+ &self.scan_definitions.iter().collect::<Vec<_>>(),
+ 0,
+ )
+ }
+
+ pub fn try_bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<Option<BoundAttempt>, ExecutionError> {
+ if !self.try_claim_partition(planner.partition() as usize) {
+ return Ok(None);
+ }
+ self.bind_plan(planner, inputs, task_plan).map(Some)
+ }
+
+ fn bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ let mut definitions = Vec::new();
+ input_definitions(task_plan, &mut definitions);
+ self.bind_definitions(planner, inputs, &definitions, planner.partition() as usize)
+ }
+
+ fn bind_definitions(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ definitions: &[&Operator],
+ partition: usize,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ if partition >= self.partition_count || definitions.len() != self.scan_definitions.len() {
+ return Err(ExecutionError::GeneralError(
+ "Shared input binding count mismatch".into(),
+ ));
+ }
+ let mut scans = Vec::new();
+ let mut bound_inputs = Vec::new();
+ for definition in definitions {
+ let (jvm_scans, _, input) = planner.create_plan(definition, inputs, 1)?;
+ scans.extend(jvm_scans);
+ bound_inputs.push(Arc::clone(&input.native_plan));
+ }
+ let attempt = Arc::new(AttemptState {
+ inputs: bound_inputs,
+ _owner: Arc::clone(self),
+ identity: Arc::clone(&self.identity),
+ started: (0..definitions.len())
+ .map(|_| AtomicBool::new(false))
+ .collect(),
+ partition,
+ });
+ Ok((scans, attempt))
+ }
+}
+
+/// Owned by one Spark task attempt. The shared tree contains no input readers,
+/// memory pools or TaskContext belonging to an attempt. Metrics are partition-labelled.
+#[derive(Debug)]
+pub(crate) struct AttemptState {
+ inputs: Vec<Arc<dyn ExecutionPlan>>,
+ _owner: Arc<SharedPipeline>,
+ identity: Arc<()>,
+ started: Vec<AtomicBool>,
+ partition: usize,
+}
+
+impl AttemptState {
+ pub fn partition(&self) -> usize {
+ self.partition
+ }
+
+ pub fn task_context(self: &Arc<Self>, session: &SessionContext) -> Arc<TaskContext> {
+ let context = TaskContext::from(session);
+ let config = context
+ .session_config()
+ .clone()
+ .with_extension(Arc::clone(self));
+ Arc::new(context.with_session_config(config))
+ }
+
+ pub fn metrics_for(&self, plan: &Arc<dyn ExecutionPlan>) -> Option<MetricsSet> {
+ if let Some(input) = plan.downcast_ref::<SharedInputExec>() {
+ if !Arc::ptr_eq(&self.identity, &input.identity) {
+ return None;
+ }
+ self.inputs[input.index].metrics()
+ } else {
+ plan.metrics().map(|metrics| {
+ let mut selected = MetricsSet::new();
+ for metric in metrics
+ .iter()
+ .filter(|m| m.partition() == Some(self.partition))
Review Comment:
@andygrove Agreed. Partition-indexed retrieval addresses the snapshot/filtering cost, but it does not remove metric handles retained by the operators.
I will include retained native bytes in the matched 8,192-partition rerun after integrating the upstream API, distinguishing bytes retained while the tree remains alive from allocation volume and peak RSS, and checking reclamation after the final owner drops.
This remains outstanding. If retained memory is material, the partition cap remains an option to evaluate alongside its effect on reuse and construction cost.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#issuecomment-5879258081
@andygrove Thanks for the detailed review. The PR is now draft, and the description says “Part of #1204.” I agree that useful reuse on a realistic workload and resolution of the metrics-scaling issue remain merge requirements.
The review fixes are in `b02b2b9f3`; `d42857ef8` subsequently merges upstream and resolves the conflicts. Besides the inline fixes, I added:
- `shared_plan_hits`, counting tasks that successfully bind to a tree retrieved from the registry, separately from `shared_plan_tasks`.
- Separate session-setup and physical-planning timers, reported once per native block root.
- Admission rules and an execution-state checklist in the contributor guide.
Local validation after the upstream merge passed 25 shared-pipeline native tests, one metrics-conversion test, and 186 JVM tests across the execution, lifecycle, and task-metrics suites. Formatting and Clippy also passed.
I completed the setup profiling at `b02b2b9f3`, before the upstream merge. Each suite ran in a fresh JVM with Spark 4.1.3, `local[4]`, SF1 Parquet, sharing enabled, and normal algorithm defaults. All 22 TPC-H and 103 TPC-DS queries ran twice; the first pass was warmup.
| Measured pass | Native block/task invocations | Session setup | Physical planning | Other setup |
|---|---:|---:|---:|---:|
| TPC-H | 436 | 110.75 ms | 52.85 ms | 11.53 ms |
| TPC-DS | 3,419 | 850.03 ms | 466.97 ms | 107.64 ms |
These are elapsed timers summed across invocations, not executor CPU time or query wall time. Session setup accounted for **67.7% and 64.5% of session-plus-planning time**, respectively. Both suites still had zero registry hits; all 45 admitted invocations had one partition.
This supports your suggestion to investigate session setup before widening admission solely for performance. It does not yet establish that UDF registration itself dominates: the next useful split is session construction versus function registration. Any optimization there must preserve task-local configuration, memory pools, and runtime resources.
Upstream metrics API integration, the matched large-stage rerun including retained bytes, and demonstrated useful reuse on a realistic workload remain outstanding. I am keeping the PR draft while those are addressed.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#issuecomment-5784102784
@andygrove I completed the default-settings TPC applicability measurements and a follow-up to explain the zero registry hits.
This used Spark 4.1.3, `local[4]`, and SF=1 Parquet data. Apart from enabling sharing and configuring Comet/local resources, AQE, native scans, shuffle mode (`auto`), direct shuffle reads, and the initial 200 shuffle partitions retained their defaults. All 22 TPC-H queries and 103 TPC-DS query variants completed.
| Suite | Queries with an eligible block | Eligible native plan invocations / all invocations | Distinct eligible scopes | Registry hits |
|---|---:|---:|---:|---:|
| TPC-H | 11/22 | 13/436 (3.0%) | 13 | 0 |
| TPC-DS | 17/103 | 32/3,415 (0.94%) | 32 | 0 |
The invocation denominator counts task-level JNI `createPlan` calls, including private-only native shuffle writers; it is not a count of distinct Spark operators or Spark tasks.
There are two related limitations:
- Most native blocks fail sharing admission. Among rejected invocations, 384/423 for TPC-H and 2,700/3,383 for TPC-DS contain at least one of `NativeScan`, `ShuffleScan`, or `ShuffleWriter` (union counts, without double-counting overlaps). Admission applies recursively to the entire native block, so supported operators above an excluded input still use a private native plan. Other restrictions include expression forms and operator features such as Top-K.
- Every eligible scope had only one invocation. I reran the 28 queries with eligible blocks and recorded the native `partition_count`: **all 45 eligible blocks had exactly one partition**, again with zero hits. For example, TPC-H Q1 admits its final sort above a coalesced AQE shuffle read, while the preceding scan/aggregate/shuffle work remains private. Thus the query-level eligibility percentages do not translate into useful sharing in this run. An idle gap in the weak registry is not needed to explain these misses.
The 28 queries with eligible blocks also passed result comparisons with sharing disabled. SF=1 is a limitation: larger data can change AQE partitioning and join choices, so these results do not establish zero reuse at every scale. They do establish that this default-settings run provides no evidence of a TPC benefit.
The sharing-only microbenchmarks after decoded-cache removal still show a benefit for the controlled 64-column projection/filter workload (about 54% lower task CPU and 12% lower elapsed time), but the 1/16/64-expression SUM workloads show no clear speedup. The upstream DataFusion metrics API PR has now been approved; integrating it and rerunning the large-stage test remains separate outstanding work. It will not change these admission restrictions or single-partition scopes.
**Would improving useful TPC coverage under default settings be a merge requirement for this PR?** Assuming the metrics issue and other outstanding review items are addressed, would the current limited, default-off scope be acceptable with coverage expansion in follow-up work, or should we expand it here first?
If wider TPC coverage is required before merging, it would help to agree on the target workloads/scale and expected multi-partition reuse. We would need additional time to implement and validate the excluded scan/shuffle paths and relevant expressions, including task-specific input binding and execution-state correctness. I would like to align on that scope before extending the PR further.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#discussion_r4064985175
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2154 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use prost::Message;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+pub(super) fn cache_bytes<'a>(plan: &Operator, original: &'a [u8]) -> std::borrow::Cow<'a, [u8]> {
+ fn has_files(plan: &Operator) -> bool {
+ matches!(plan.op_struct, Some(OpStruct::NativeScan(_)))
+ || plan.children.iter().any(has_files)
+ }
+ if has_files(plan) {
+ std::borrow::Cow::Owned(template_bytes(plan))
+ } else {
+ std::borrow::Cow::Borrowed(original)
+ }
+}
+
+/// Legacy file-list normalization. Native scans are currently rejected by admission,
+/// so this does not expand the set of trees eligible for sharing.
+pub(super) fn template_bytes(plan: &Operator) -> Vec<u8> {
+ fn normalize(plan: &mut Operator) {
+ if let Some(OpStruct::NativeScan(scan)) = plan.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ for child in &mut plan.children {
+ normalize(child);
+ }
+ }
+ let mut template = plan.clone();
+ normalize(&mut template);
+ template.encode_to_vec()
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
+ .with_sql_text_pool(plan)
+ .with_input_plans(Arc::clone(&input_plans));
+ let (_, _, original) = planner.create_plan(plan, &mut vec![], 1)?;
+ let identity = Arc::new(());
+ let mut mapping = Vec::new();
+ convert_tree(
+ &original.native_plan,
+ &identity,
+ &input_plans.lock(),
+ &mut mapping,
+ partition_count,
+ )?;
+ let root = convert_spark_tree(&original, &mapping)?;
+ let mut definitions = Vec::new();
+ input_definitions(plan, &mut definitions);
+ let scan_definitions = definitions
+ .into_iter()
+ .map(|p| {
+ let mut p = p.clone();
+ if let Some(OpStruct::NativeScan(scan)) = p.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ p
+ })
+ .collect();
+ Ok(Arc::new(Self {
+ root,
+ scan_definitions,
+ identity,
+ partition_count,
+ claimed_partitions: Mutex::new(HashSet::new()),
+ }))
+ }
+
+ #[cfg(test)]
+ fn bind(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ self.bind_definitions(
+ planner,
+ inputs,
+ &self.scan_definitions.iter().collect::<Vec<_>>(),
+ 0,
+ )
+ }
+
+ pub fn try_bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<Option<BoundAttempt>, ExecutionError> {
+ if !self.try_claim_partition(planner.partition() as usize) {
+ return Ok(None);
+ }
+ self.bind_plan(planner, inputs, task_plan).map(Some)
+ }
+
+ fn bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ let mut definitions = Vec::new();
+ input_definitions(task_plan, &mut definitions);
+ self.bind_definitions(planner, inputs, &definitions, planner.partition() as usize)
+ }
+
+ fn bind_definitions(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ definitions: &[&Operator],
+ partition: usize,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ if partition >= self.partition_count || definitions.len() != self.scan_definitions.len() {
+ return Err(ExecutionError::GeneralError(
+ "Shared input binding count mismatch".into(),
+ ));
+ }
+ let mut scans = Vec::new();
+ let mut bound_inputs = Vec::new();
+ for definition in definitions {
+ let (jvm_scans, _, input) = planner.create_plan(definition, inputs, 1)?;
+ scans.extend(jvm_scans);
+ bound_inputs.push(Arc::clone(&input.native_plan));
+ }
+ let attempt = Arc::new(AttemptState {
+ inputs: bound_inputs,
+ _owner: Arc::clone(self),
+ identity: Arc::clone(&self.identity),
+ started: (0..definitions.len())
+ .map(|_| AtomicBool::new(false))
+ .collect(),
+ partition,
+ });
+ Ok((scans, attempt))
+ }
+}
+
+/// Owned by one Spark task attempt. The shared tree contains no input readers,
+/// memory pools or TaskContext belonging to an attempt. Metrics are partition-labelled.
+#[derive(Debug)]
+pub(crate) struct AttemptState {
+ inputs: Vec<Arc<dyn ExecutionPlan>>,
+ _owner: Arc<SharedPipeline>,
+ identity: Arc<()>,
+ started: Vec<AtomicBool>,
+ partition: usize,
+}
+
+impl AttemptState {
+ pub fn partition(&self) -> usize {
+ self.partition
+ }
+
+ pub fn task_context(self: &Arc<Self>, session: &SessionContext) -> Arc<TaskContext> {
+ let context = TaskContext::from(session);
+ let config = context
+ .session_config()
+ .clone()
+ .with_extension(Arc::clone(self));
+ Arc::new(context.with_session_config(config))
+ }
+
+ pub fn metrics_for(&self, plan: &Arc<dyn ExecutionPlan>) -> Option<MetricsSet> {
+ if let Some(input) = plan.downcast_ref::<SharedInputExec>() {
+ if !Arc::ptr_eq(&self.identity, &input.identity) {
+ return None;
+ }
+ self.inputs[input.index].metrics()
+ } else {
+ plan.metrics().map(|metrics| {
+ let mut selected = MetricsSet::new();
+ for metric in metrics
+ .iter()
+ .filter(|m| m.partition() == Some(self.partition))
Review Comment:
Agreed. I reproduced this with actual DataFusion operators in a release build, with partition 0's stream kept alive while the remaining partitions execute and complete. For a 16-expression projection/filter tree, the median cumulative snapshot/filter time over three runs was 51.3 ms at 1,024 partitions and 3.90 s at 8,192 partitions. The matched decoded-cache-only control took 0.142 ms and 1.11 ms, respectively. These are native mechanism measurements, not Spark query timings.
The current DataFusion metrics API returns a full snapshot, so merely caching each task's handles after an initial full scan would move the quadratic work rather than remove it. I am evaluating options without modifying DataFusion and am adding the matched Spark cache-only versus sharing comparison with a long-lived task. This issue remains unresolved; the existing benchmark results do not justify the current reporting path.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#discussion_r4075324481
##########
native/core/src/execution/jni_api.rs:
##########
@@ -967,11 +994,35 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_executePlan(
.with_shuffle_partition_pusher(
exec_context.shuffle_partition_pusher.clone(),
);
- let (scans, shuffle_scans, root_op) = planner.create_plan(
- &exec_context.spark_plan,
- &mut exec_context.input_sources.clone(),
- exec_context.partition_count,
- )?;
+ let (scans, shuffle_scans, root_op) =
+ if let Some(key) = &exec_context.shared_plan_key {
+ let shared = super::shared_pipeline::get_or_build(
Review Comment:
Implemented in ffdbbd2df833c99902c44dbc1f436520342badf3. Shared-tree construction/conversion errors now log a warning and fall back to private planning. The regression test introduces an unsupported wrapper around a real DataFusion tree, verifies that conversion fails without leaving a registry entry, and verifies the private plan's output. Binding and execution errors still propagate: once task-owned input streams may have been imported, retrying them would not be safe.
##########
native/core/src/execution/plan_cache.rs:
##########
@@ -0,0 +1,455 @@
+// 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.
+
+//! Executor-local reuse of immutable protobuf plans and bounded single-flight cache (#1204).
+//!
+//! The definition cache here owns protobuf data only. `shared_pipeline` separately uses the
+//! generic cache for audited immutable physical trees. Neither cache may retain task resources.
+//! Different partitions' scan payloads must remain different definition-cache keys.
+
+use std::collections::HashMap;
+use std::sync::{Arc, LazyLock};
+use std::time::Instant;
+
+use datafusion_comet_proto::spark_operator::Operator;
+use once_cell::sync::OnceCell;
+use parking_lot::Mutex;
+
+use super::operators::ExecutionError;
+use super::serde::deserialize_op;
+
+const MAX_ENTRIES: usize = 64;
+const MAX_ENCODED_BYTES: usize = 8 * 1024 * 1024;
+
+// Process-local because tasks do not share a SessionContext. This cache owns only immutable
+// protobuf data, never storage clients, JNI references or task resources. Exact bytes are
+// compared, so neither hash collisions nor another query's configuration can change the decoded
+// result. Retention is bounded by entry count and encoded bytes, and release_runtime clears it.
+// The byte budget accounts for keys, not the decoded Rust heap (which can be larger).
+static PLAN_CACHE: LazyLock<PlanCache<Operator>> =
+ LazyLock::new(|| PlanCache::new(MAX_ENTRIES, MAX_ENCODED_BYTES));
+
+pub(super) fn decode_plan(
Review Comment:
Addressed in ffdbbd2df833c99902c44dbc1f436520342badf3 by removing the decoded-plan cache and its config entirely. The standalone measurements showed only approximately 0.2%–1.4% lower elapsed time than both flags disabled, which does not justify maintaining this cache. Injected per-task plan bytes are now decoded without entering a native definition cache, so they cannot evict reusable definitions. The physical registry still rejects native file scans.
##########
spark/src/test/scala/org/apache/comet/exec/CometExecSuite.scala:
##########
@@ -90,6 +93,114 @@ class CometExecSuite extends CometTestBase {
}
}
+ test("native plan cache setting crosses JNI for both enabled and disabled execution") {
+ for (enabled <- Seq("true", "false")) {
+ withSQLConf(CometConf.COMET_EXEC_PLAN_CACHE_ENABLED.key -> enabled) {
+ val configs = ConfigMap.parseFrom(CometExecIterator.serializeCometSQLConfs())
+ assert(configs.getEntriesMap.get(CometConf.COMET_EXEC_PLAN_CACHE_ENABLED.key) == enabled)
+ withParquetTable((0 until 32).map(i => (i, i + 1)), "plan_cache_input") {
+ checkSparkAnswerAndOperator(
+ sql("SELECT _1 + 1 FROM plan_cache_input WHERE _2 > 8"),
+ Seq(classOf[CometProjectExec]))
+ }
+ }
+ }
+ }
+
+ test("shared native pipelines across task waves and AQE") {
+ for (enabled <- Seq("true", "false"); aqe <- Seq("true", "false")) {
+ withSQLConf(
+ CometConf.COMET_EXEC_SHARED_PLAN_ENABLED.key -> enabled,
+ CometConf.COMET_EXEC_PLAN_CACHE_ENABLED.key -> "false",
+ CometConf.COMET_EXPLAIN_NATIVE_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe,
+ SQLConf.ARROW_EXECUTION_MAX_RECORDS_PER_BATCH.key -> "17") {
+ val configs = ConfigMap.parseFrom(CometExecIterator.serializeCometSQLConfs())
+ assert(configs.getEntriesMap.get(CometConf.COMET_EXEC_SHARED_PLAN_ENABLED.key) == enabled)
+ for (_ <- 0 until 2) {
+ val df = spark.range(0, 1000, 1, 16).where("id > 100").selectExpr("id + 10 AS value")
+ val (_, nativePlan) = checkSparkAnswerAndOperator(df, Seq(classOf[CometProjectExec]))
+ val projects = stripAQEPlan(nativePlan).collect { case p: CometProjectExec => p }
+ assert(projects.nonEmpty)
+ assert(projects.head.metrics("output_rows").value == 899L)
+ }
+ val empty = spark.range(0, 100, 1, 16).where("id < 0").selectExpr("id + 10 AS value")
+ checkSparkAnswerAndOperator(empty, Seq(classOf[CometProjectExec]))
+ // Stateful expressions in an otherwise eligible JVM-input block use private plans.
+ val stateful = spark
+ .range(0, 100, 1, 16)
+ .selectExpr("spark_partition_id() AS partition", "monotonically_increasing_id() AS id")
+ checkSparkAnswerAndOperator(stateful, Seq(classOf[CometProjectExec]))
+ }
+ }
+ }
+
+ test("shared DataFusion stateful operators across Spark partitions") {
Review Comment:
Added `shared_plan_tasks` SQL metrics and explicit path assertions in ffdbbd2df833c99902c44dbc1f436520342badf3. Projection/filter tests assert the exact task count; positive sort, post-shuffle Final aggregate, and broadcast hash join tests arrange eligible JVM inputs and assert nonzero counts only when sharing is enabled, with AQE both on and off. A separate test verifies that the executed block actually contains a serialized ShuffleScan and asserts zero shared tasks. Native-scan and stateful-expression fallback cases also assert zero.
This metric counts tasks bound to a shared tree, not registry hits; native tests continue to verify actual operator identity. The broader output-equivalence tests have been renamed so their names do not imply that every case was admitted. I also found that the direct-read setting alone is not enough to infer the input representation: some exchange plans still serialize as ordinary Scan inputs, so the fallback test checks the serialized plan itself.
##########
spark/src/test/scala/org/apache/comet/exec/CometExecSuite.scala:
##########
@@ -63,7 +63,10 @@ class CometExecSuite extends CometTestBase {
override protected def test(testName: String, testTags: Tag*)(testFun: => Any)(implicit
pos: Position): Unit = {
super.test(testName, testTags: _*) {
- withSQLConf(CometConf.COMET_SHUFFLE_ENABLED.key -> "true") {
+ withSQLConf(
+ CometConf.COMET_SHUFFLE_ENABLED.key -> "true",
+ CometConf.COMET_EXEC_PLAN_CACHE_ENABLED.key -> "true",
+ CometConf.COMET_EXEC_SHARED_PLAN_ENABLED.key -> "true") {
Review Comment:
Fixed in ffdbbd2df833c99902c44dbc1f436520342badf3. The suite-wide sharing/cache overrides are removed, restoring default-path coverage for existing tests. The cache flag itself is gone. New sharing tests enable the feature locally, and the lifecycle regressions run with sharing disabled and enabled. The lifecycle test's synthetic TaskContext now carries SQLConf through local properties, as real Spark tasks do; otherwise its empty properties silently selected the default setting.
##########
spark/src/test/scala/org/apache/spark/CometExecIteratorLifecycleSuite.scala:
##########
@@ -192,12 +235,15 @@ class CometExecIteratorLifecycleSuite extends CometTestBase {
schema,
CometArrowStream.NATIVE_TIMEZONE,
"lifecycle-test")
- val limitOp =
- CometExecUtils.getLimitNativePlan(Seq(PrettyAttribute("test", LongType)), 100).get
+ val scanOp =
Review Comment:
You are right: I replaced the limit with a scan to enter an admitted sharing path, but that should have been an additional case. In ffdbbd2df833c99902c44dbc1f436520342badf3, the limit case is restored and tested with sharing off/on. A separate scan case is also tested in both modes, and inspects the final native metrics report to assert whether a shared tree was actually bound before the injected metrics-update failure. All nine lifecycle tests pass.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#discussion_r4064182764
##########
spark/src/main/scala/org/apache/comet/Native.scala:
##########
@@ -77,7 +77,8 @@ class Native extends NativeBase {
taskCPUs: Long,
keyUnwrapper: CometFileKeyUnwrapper,
taskContext: TaskContext,
- classLoader: ClassLoader): Long
+ classLoader: ClassLoader,
+ sharedPlanScope: String = ""): Long
Review Comment:
### Correctness
[P2] Could you reconcile the existing signature test with this API change? `CometNativeShuffleSuite` still asserts that `createPlan.getParameterTypes.last` is `ClassLoader`. Appending `sharedPlanScope` makes it `String`, even with both new flags disabled. The current Spark 4.1 shuffle job fails at `CometNativeShuffleSuite.scala:109` with exactly that mismatch, leaving Required Checks failed. Please update the test to the intended signature, or pass the scope through the existing configuration argument if preserving the signature remains the contract.
[Failing current-merge job](https://github.com/apache/datafusion-comet/actions/runs/35570336827/job/106243253739)
##########
native/core/src/execution/shared_pipeline.rs:
##########
@@ -0,0 +1,2154 @@
+// 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.
+
+//! Stage-attempt scoped DataFusion trees, using unmodified upstream operators.
+//! Inputs are task-local; each shared partition executes at most once.
+
+use super::operators::{ExecutionError, ScanExec};
+use super::planner::PhysicalPlanner;
+use super::spark_plan::SparkPlan;
+use arrow::array::RecordBatch;
+use arrow::datatypes::SchemaRef;
+use datafusion::common::{internal_err, tree_node::TreeNodeRecursion, Result};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode};
+use datafusion::physical_plan::filter::FilterExec;
+use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
+use datafusion::physical_plan::metrics::MetricsSet;
+use datafusion::physical_plan::projection::ProjectionExec;
+use datafusion::physical_plan::sorts::sort::SortExec;
+use datafusion::physical_plan::{
+ ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
+ PlanProperties, RecordBatchStream, ReplaceChildrenOptions, SendableRecordBatchStream,
+};
+use datafusion::prelude::SessionContext;
+use datafusion_comet_proto::spark_expression::{agg_expr, expr::ExprStruct, AggExpr, Expr};
+use datafusion_comet_proto::spark_operator::{operator::OpStruct, Operator};
+use futures::{Stream, StreamExt};
+use jni::objects::{Global, JObject};
+use parking_lot::Mutex;
+use prost::Message;
+use std::collections::{HashMap, HashSet};
+use std::fmt::Formatter;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Weak};
+use std::task::{Context, Poll};
+
+// The registry owns only weak references: the last task drops the physical tree and metrics.
+// An executor has no reliable stage-completion callback, so idle gaps deliberately end reuse.
+static PHYSICAL_PLANS: LazyLock<ScopedPlans> = LazyLock::new(ScopedPlans::default);
+
+#[derive(Default)]
+struct ScopedPlans {
+ entries: Mutex<HashMap<Vec<u8>, Weak<SharedPipeline>>>,
+}
+
+impl ScopedPlans {
+ fn get_or_build(
+ &self,
+ key: &[u8],
+ build: impl FnOnce() -> std::result::Result<Arc<SharedPipeline>, ExecutionError>,
+ ) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ let mut entries = self.entries.lock();
+ entries.retain(|_, plan| plan.strong_count() != 0);
+ if let Some(plan) = entries.get(key).and_then(Weak::upgrade) {
+ return Ok(plan);
+ }
+ // First construction is serialized; failures never become resident entries.
+ let plan = build()?;
+ if entries.len() < 64
+ && key.len() <= 8 * 1024 * 1024
+ && entries.keys().map(Vec::len).sum::<usize>() + key.len() <= 8 * 1024 * 1024
+ {
+ entries.insert(key.to_vec(), Arc::downgrade(&plan));
+ }
+ Ok(plan)
+ }
+}
+
+pub(super) fn clear() {
+ PHYSICAL_PLANS.entries.lock().clear();
+}
+
+/// JVM scope includes driver-generated block identity, stage ID and stage attempt.
+pub(super) fn scoped_key(scope: &[u8], key: &[u8]) -> Vec<u8> {
+ let mut result = Vec::with_capacity(8 + scope.len() + key.len());
+ result.extend_from_slice(&(scope.len() as u64).to_le_bytes());
+ result.extend_from_slice(scope);
+ result.extend_from_slice(key);
+ result
+}
+
+/// Length-prefix every field so distinct plans/configurations cannot alias. Configuration order
+/// is immaterial. Partition index and attempt identity intentionally do not participate: admitted
+/// expressions cannot depend on either. task_cpus also participates because it sets the session
+/// target_partitions independently of serialized Spark config. Resources arrive through binding.
+pub(super) fn cache_key(
+ bytes: &[u8],
+ config: &HashMap<String, String>,
+ batch_size: i32,
+ partition_count: i32,
+ task_cpus: i64,
+) -> Vec<u8> {
+ fn append(key: &mut Vec<u8>, bytes: &[u8]) {
+ key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
+ key.extend_from_slice(bytes);
+ }
+ let mut key = Vec::new();
+ append(&mut key, bytes);
+ key.extend_from_slice(&batch_size.to_le_bytes());
+ key.extend_from_slice(&partition_count.to_le_bytes());
+ key.extend_from_slice(&task_cpus.to_le_bytes());
+ let mut entries: Vec<_> = config.iter().collect();
+ entries.sort_unstable();
+ for (name, value) in entries {
+ append(&mut key, name.as_bytes());
+ append(&mut key, value.as_bytes());
+ }
+ key
+}
+
+pub(super) fn cache_bytes<'a>(plan: &Operator, original: &'a [u8]) -> std::borrow::Cow<'a, [u8]> {
+ fn has_files(plan: &Operator) -> bool {
+ matches!(plan.op_struct, Some(OpStruct::NativeScan(_)))
+ || plan.children.iter().any(has_files)
+ }
+ if has_files(plan) {
+ std::borrow::Cow::Owned(template_bytes(plan))
+ } else {
+ std::borrow::Cow::Borrowed(original)
+ }
+}
+
+/// Legacy file-list normalization. Native scans are currently rejected by admission,
+/// so this does not expand the set of trees eligible for sharing.
+pub(super) fn template_bytes(plan: &Operator) -> Vec<u8> {
+ fn normalize(plan: &mut Operator) {
+ if let Some(OpStruct::NativeScan(scan)) = plan.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ for child in &mut plan.children {
+ normalize(child);
+ }
+ }
+ let mut template = plan.clone();
+ normalize(&mut template);
+ template.encode_to_vec()
+}
+
+// Preserve the planner's input_plan push order: children are planned left-to-right, including
+// parse_join_parameters. HashJoin may swap physical children afterwards; convert_tree maps each
+// original input Arc to this pre-swap slot, so binding must keep the protobuf child order.
+fn input_definitions<'a>(plan: &'a Operator, result: &mut Vec<&'a Operator>) {
+ if matches!(
+ plan.op_struct,
+ Some(OpStruct::Scan(_) | OpStruct::NativeScan(_))
+ ) {
+ result.push(plan);
+ } else {
+ for child in &plan.children {
+ input_definitions(child, result);
+ }
+ }
+}
+
+pub(super) fn get_or_build(
+ key: &[u8],
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+) -> std::result::Result<Arc<SharedPipeline>, ExecutionError> {
+ PHYSICAL_PLANS.get_or_build(key, || {
+ SharedPipeline::build_partitions(plan, session, partition_count)
+ })
+}
+
+pub(super) fn supports(plan: &Operator) -> bool {
+ match plan.op_struct.as_ref() {
+ Some(OpStruct::Scan(_)) => plan.children.is_empty(),
+ Some(OpStruct::NativeScan(_)) => false,
+ Some(OpStruct::Projection(project)) => {
+ plan.children.len() == 1
+ && project.project_list.iter().all(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::Filter(filter)) => {
+ plan.children.len() == 1
+ && filter.predicate.as_ref().is_some_and(supports_expr)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashJoin(join)) => {
+ plan.children.len() == 2
+ && !join.dynamic_filter_enabled
+ && !join.null_aware_anti_join
+ && join.left_join_keys.iter().all(supports_expr)
+ && join.right_join_keys.iter().all(supports_expr)
+ && join.condition.as_ref().is_none_or(supports_expr)
+ && plan.children.iter().all(supports)
+ }
+ Some(OpStruct::Sort(sort)) => {
+ plan.children.len() == 1
+ && !sort.sort_orders.is_empty()
+ && sort.fetch.is_none()
+ && sort.skip.is_none_or(|n| n == 0)
+ && sort.sort_orders.iter().all(supports_sort_order)
+ && supports(&plan.children[0])
+ }
+ Some(OpStruct::HashAgg(agg)) => {
+ plan.children.len() == 1
+ && agg.grouping_exprs.iter().all(supports_expr)
+ && agg.agg_exprs.iter().all(supports_aggregate)
+ && supports(&plan.children[0])
+ }
+ _ => false,
+ }
+}
+
+fn supports_sort_order(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::SortOrder(order)) => order.child.as_deref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+// DISTINCT is lowered by Spark to grouping/deduplication stages before serialization; AggExpr
+// has no distinct flag. expr_modes changes how buffers are consumed, never which functions or
+// child expressions are admitted here. The original planner supplies the merge definitions.
+fn supports_aggregate(expr: &AggExpr) -> bool {
+ use agg_expr::ExprStruct::*;
+ expr.filter.as_ref().is_none_or(supports_expr)
+ && match expr.expr_struct.as_ref() {
+ Some(Count(e)) => !e.children.is_empty() && e.children.iter().all(supports_expr),
+ Some(Sum(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Avg(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Min(e)) => e.child.as_ref().is_some_and(supports_expr),
+ Some(Max(e)) => e.child.as_ref().is_some_and(supports_expr),
+ _ => false,
+ }
+}
+
+fn supports_expr(expr: &Expr) -> bool {
+ match expr.expr_struct.as_ref() {
+ Some(ExprStruct::Bound(_) | ExprStruct::Literal(_)) => true,
+ Some(ExprStruct::Add(e) | ExprStruct::Subtract(e) | ExprStruct::Multiply(e)) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(
+ ExprStruct::Eq(e)
+ | ExprStruct::Neq(e)
+ | ExprStruct::Gt(e)
+ | ExprStruct::GtEq(e)
+ | ExprStruct::Lt(e)
+ | ExprStruct::LtEq(e)
+ | ExprStruct::And(e)
+ | ExprStruct::Or(e),
+ ) => {
+ e.left.as_deref().is_some_and(supports_expr)
+ && e.right.as_deref().is_some_and(supports_expr)
+ }
+ Some(ExprStruct::IsNull(e) | ExprStruct::IsNotNull(e) | ExprStruct::Not(e)) => {
+ e.child.as_deref().is_some_and(supports_expr)
+ }
+ // In particular: RNGs, partition ID, subqueries, UDFs and unreviewed scalar functions.
+ _ => false,
+ }
+}
+
+#[derive(Debug)]
+pub(super) struct SharedPipeline {
+ pub root: Arc<SparkPlan>,
+ scan_definitions: Vec<Operator>,
+ identity: Arc<()>,
+ partition_count: usize,
+ claimed_partitions: Mutex<HashSet<usize>>,
+}
+
+type BoundAttempt = (Vec<ScanExec>, Arc<AttemptState>);
+
+impl SharedPipeline {
+ /// Never release a claim: upstream metrics persist until the tree is dropped.
+ /// A repeated partition must execute on an ordinary private plan instead.
+ fn try_claim_partition(&self, partition: usize) -> bool {
+ partition < self.partition_count && self.claimed_partitions.lock().insert(partition)
+ }
+
+ #[cfg(test)]
+ fn build(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ Self::build_partitions(plan, session, 1)
+ }
+
+ fn build_partitions(
+ plan: &Operator,
+ session: &Arc<SessionContext>,
+ partition_count: usize,
+ ) -> std::result::Result<Arc<Self>, ExecutionError> {
+ if partition_count == 0 || !supports(plan) {
+ return Err(ExecutionError::GeneralError(
+ "Unsupported shared native pipeline".into(),
+ ));
+ }
+ // TEST_EXEC_CONTEXT_ID is the planner's default. No task inputs/context are imported.
+ let input_plans = Arc::new(Mutex::new(Vec::new()));
+ let planner = PhysicalPlanner::new(Arc::clone(session), 0)
+ .with_sql_text_pool(plan)
+ .with_input_plans(Arc::clone(&input_plans));
+ let (_, _, original) = planner.create_plan(plan, &mut vec![], 1)?;
+ let identity = Arc::new(());
+ let mut mapping = Vec::new();
+ convert_tree(
+ &original.native_plan,
+ &identity,
+ &input_plans.lock(),
+ &mut mapping,
+ partition_count,
+ )?;
+ let root = convert_spark_tree(&original, &mapping)?;
+ let mut definitions = Vec::new();
+ input_definitions(plan, &mut definitions);
+ let scan_definitions = definitions
+ .into_iter()
+ .map(|p| {
+ let mut p = p.clone();
+ if let Some(OpStruct::NativeScan(scan)) = p.op_struct.as_mut() {
+ scan.file_partition = None;
+ }
+ p
+ })
+ .collect();
+ Ok(Arc::new(Self {
+ root,
+ scan_definitions,
+ identity,
+ partition_count,
+ claimed_partitions: Mutex::new(HashSet::new()),
+ }))
+ }
+
+ #[cfg(test)]
+ fn bind(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ self.bind_definitions(
+ planner,
+ inputs,
+ &self.scan_definitions.iter().collect::<Vec<_>>(),
+ 0,
+ )
+ }
+
+ pub fn try_bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<Option<BoundAttempt>, ExecutionError> {
+ if !self.try_claim_partition(planner.partition() as usize) {
+ return Ok(None);
+ }
+ self.bind_plan(planner, inputs, task_plan).map(Some)
+ }
+
+ fn bind_plan(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ task_plan: &Operator,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ let mut definitions = Vec::new();
+ input_definitions(task_plan, &mut definitions);
+ self.bind_definitions(planner, inputs, &definitions, planner.partition() as usize)
+ }
+
+ fn bind_definitions(
+ self: &Arc<Self>,
+ planner: &PhysicalPlanner,
+ inputs: &mut Vec<Arc<Global<JObject<'static>>>>,
+ definitions: &[&Operator],
+ partition: usize,
+ ) -> std::result::Result<(Vec<ScanExec>, Arc<AttemptState>), ExecutionError> {
+ if partition >= self.partition_count || definitions.len() != self.scan_definitions.len() {
+ return Err(ExecutionError::GeneralError(
+ "Shared input binding count mismatch".into(),
+ ));
+ }
+ let mut scans = Vec::new();
+ let mut bound_inputs = Vec::new();
+ for definition in definitions {
+ let (jvm_scans, _, input) = planner.create_plan(definition, inputs, 1)?;
+ scans.extend(jvm_scans);
+ bound_inputs.push(Arc::clone(&input.native_plan));
+ }
+ let attempt = Arc::new(AttemptState {
+ inputs: bound_inputs,
+ _owner: Arc::clone(self),
+ identity: Arc::clone(&self.identity),
+ started: (0..definitions.len())
+ .map(|_| AtomicBool::new(false))
+ .collect(),
+ partition,
+ });
+ Ok((scans, attempt))
+ }
+}
+
+/// Owned by one Spark task attempt. The shared tree contains no input readers,
+/// memory pools or TaskContext belonging to an attempt. Metrics are partition-labelled.
+#[derive(Debug)]
+pub(crate) struct AttemptState {
+ inputs: Vec<Arc<dyn ExecutionPlan>>,
+ _owner: Arc<SharedPipeline>,
+ identity: Arc<()>,
+ started: Vec<AtomicBool>,
+ partition: usize,
+}
+
+impl AttemptState {
+ pub fn partition(&self) -> usize {
+ self.partition
+ }
+
+ pub fn task_context(self: &Arc<Self>, session: &SessionContext) -> Arc<TaskContext> {
+ let context = TaskContext::from(session);
+ let config = context
+ .session_config()
+ .clone()
+ .with_extension(Arc::clone(self));
+ Arc::new(context.with_session_config(config))
+ }
+
+ pub fn metrics_for(&self, plan: &Arc<dyn ExecutionPlan>) -> Option<MetricsSet> {
+ if let Some(input) = plan.downcast_ref::<SharedInputExec>() {
+ if !Arc::ptr_eq(&self.identity, &input.identity) {
+ return None;
+ }
+ self.inputs[input.index].metrics()
+ } else {
+ plan.metrics().map(|metrics| {
+ let mut selected = MetricsSet::new();
+ for metric in metrics
+ .iter()
+ .filter(|m| m.partition() == Some(self.partition))
Review Comment:
### Performance
[P2] Could each attempt retain or access only its own metric handles instead of snapshotting the entire shared tree here? DataFusion 55.1.0's `plan.metrics()` clones its `Vec<Arc<Metric>>` under the operator's mutex before this filter runs. Every executed partition appends metrics, and `releasePlan` calls this path for every task. When overlapping task waves or one long task keep the tree alive, the nth task therefore clones and scans metrics for all n partitions. Total completion-reporting work becomes quadratic in the partitions processed by that tree, whereas private plans only inspect their own metrics.
A focused benchmark of this branch and snapshot representation, using dependency stand-ins and eight metrics per partition, measured median flush times of 0.19 µs, 26.53 µs, 233.53 µs and 1.10 ms at 1, 1,024, 8,192 and 32,768 retained partitions. These are mechanism timings, not Spark query timings. The 64-entry and encoded-key limits do not bound the metrics in one live tree. Please make the reporting cost independent of completed partitions and add a matched large-stage benchmark with a long-lived task plus a cache-only control.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Share native DataFusion plans across tasks within a Spark stage attempt [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #6071:
URL: https://github.com/apache/datafusion-comet/pull/6071#discussion_r4064974991
##########
spark/src/main/scala/org/apache/comet/Native.scala:
##########
@@ -77,7 +77,8 @@ class Native extends NativeBase {
taskCPUs: Long,
keyUnwrapper: CometFileKeyUnwrapper,
taskContext: TaskContext,
- classLoader: ClassLoader): Long
+ classLoader: ClassLoader,
+ sharedPlanScope: String = ""): Long
Review Comment:
Fixed in c2e48d2a4225e38436b5669e1af881b468d09838. I missed this existing assertion when adding `sharedPlanScope`. The test now checks the trailing `TaskContext`, `ClassLoader`, and `String` parameters and has a name that reflects the updated signature. The full `CometNativeShuffleSuite` passed locally on Spark 4.1: 57 tests, 0 failures.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org