Skip to content

fix: preserve hash join dynamic filters across recursive CTE iterations - #26669

Merged
jayzhan211 merged 7 commits into
apache:mainfrom
Kristofferjoha:fix/hashjoin-recursive-26641
Oct 25, 2026
Merged

jayzhan211 merged 7 commits into
apache:mainfrom
Kristofferjoha:fix/hashjoin-recursive-26641

Conversation

@Kristofferjoha

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Closes #26641.

Rationale for this change

Hash joins inside recursive CTEs read every probe-side row on each iteration because their dynamic filters stop updating the scan. This prevents pruning during recursive queries such as graph walks.

What changes are included in this PR?

  • Reset the existing shared dynamic filter instead of dropping it.
  • Clear the build accumulator for each execution.
  • Update prepared-build test callers to propagate reset errors.
  • Add a recursive join regression test in cte.slt.

Depends on #26056 for DynamicFilterPhysicalExpr::reset(). It hasnt been merged yet, however it has been approved, so i tought i was safe to use its implementation.

What is the testing strategy for this PR?

The new cte.slt case checks that the recursive query returns 1–5 and that the probe scan outputs 4 rows and prunes 396 rows across four iterations.

Are there any user-facing changes?

The public HashJoinExecBuilder::reset_state method now returns Result<Self>; callers must handle the result.

@github-actions github-actions Bot added physical-expr Changes to the physical-expr crates sqllogictest SQL Logic Tests (.slt) physical-plan Changes to the physical-plan crate labels Oct 23, 2026
@Kristofferjoha

Copy link
Copy Markdown
Contributor Author

Hi @jayzhan211, I opened PRs for both #26641 and #26642. Would you be able to take a look when you have time? Both depend on #26056.

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: In datafusion/physical-plan/src/execution_plan.rs around line 1999 (outside the diff), the reset_plan_states docs still list "uses dynamic filters" as a reason a plan can't be re-executed. With this PR, a hash join with a dynamic filter can be re-executed after a reset. The remaining constraint is that the reset copy shares the filter with the original, so the two shouldn't run at the same time. Could you update that bullet?

 /// While this function enables plan reuse, it does not allow the same plan to be executed if it (OR):
 ///
-/// * uses dynamic filters,
+/// * uses dynamic filters and the original plan (or another reset copy) is still
+///   executing, because operators such as `HashJoinExec` and `AggregateExec`
+///   reset their shared dynamic filter in place,
 /// * represents a recursive query.


/// Reset task-local runtime state while retaining the immutable prepared build.
pub fn reset_state(mut self) -> Self {
pub fn reset_state(mut self) -> Result<Self> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HashJoinExecBuilder::reset_state has been public since 53.0.0, so changing it to return Result<Self> is a breaking change, and it isn't declared yet (no api change label or upgrade-guide entry). I think we can avoid the break: the only fallible step is remapping lit(true) inside DynamicFilterPhysicalExpr::reset(), and lit(true) has no column references, so the remap never changes anything. Since #26056 hasn't merged yet, reset() could be infallible there, and then this method keeps returning Self (I compile-checked this and the reset tests pass):

-    pub fn reset(&self) -> Result<()> {
-        let new_expr = Self::remap_children(
-            &self.children,
-            self.remapped_children.as_ref(),
-            lit(true),
-        )?;
-
+    pub fn reset(&self) {
+        // `true` has no column references, so no child remapping is needed.
         let mut current = self.inner.write();
         let new_generation = current.generation + 1;
         *current = Inner {
             expression_id: current.expression_id,
             generation: new_generation,
-            expr: new_expr,
+            expr: lit(true),
             is_complete: false,
         };
         drop(current);
 
         let _ = self.state_watch.send(FilterState::InProgress {
             generation: new_generation,
         });
-        Ok(())
     }
-    pub fn reset_state(mut self) -> Result<Self> {
+    pub fn reset_state(mut self) -> Self {
         self.exec.left_fut = Default::default();
 
         if let Some(dynamic_filter) = &mut self.exec.dynamic_filter {
-            dynamic_filter.filter.reset()?;
+            dynamic_filter.filter.reset();

The ? / .unwrap() at the other reset() and reset_state() call sites go away too. If you'd rather keep Result, could you add the api change label and a note in docs/source/library-user-guide/upgrading/56.0.0.md?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, reset() made infallible and kept HashJoinExecBuilder::reset_state() returning Self. Callers updated and CTE regression and tests passes.


# Hash join dynamic filters must remain shared with the probe scan across
# recursive iterations (#26641). Each iteration looks up a different key, so
# retaining a stale bound would also truncate the recursive result.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I don't think the second sentence holds. When I removed dynamic_filter.filter.reset()? from reset_state, this result query still passed. Each iteration's new accumulator publishes fresh bounds before the probe scan opens, so only the EXPLAIN ANALYZE block below catches the missing reset. Maybe reword it so the comment says which query covers what:

 # Hash join dynamic filters must remain shared with the probe scan across
-# recursive iterations (#26641). Each iteration looks up a different key, so
-# retaining a stale bound would also truncate the recursive result.
+# recursive iterations (#26641). Each iteration looks up a different key; the
+# EXPLAIN ANALYZE below checks that the filter is reset and republished, so the
+# probe scan prunes rows on every iteration.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, updated the comment

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @Kristofferjoha !

@jayzhan211
jayzhan211 added this pull request to the merge queue Oct 25, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 25, 2026
@jayzhan211

Copy link
Copy Markdown
Contributor

I'll fix the conflicts

…ive-26641

# Conflicts:
#	datafusion/physical-expr/src/expressions/dynamic_filters/mod.rs
#	datafusion/physical-plan/src/aggregates/mod.rs
#	datafusion/sqllogictest/test_files/cte.slt
@github-actions

Copy link
Copy Markdown

Thank you for opening this pull request!

Reviewer note: cargo-semver-checks reported the current version number is not SemVer-compatible with the changes in this pull request (compared against the base branch).

Details
     Cloning e3fe60c8b3326849cacd97499f2ba0971cc70d07
    Building datafusion-physical-expr v55.1.0 (current)
       Built [  26.679s] (current)
     Parsing datafusion-physical-expr v55.1.0 (current)
      Parsed [   0.039s] (current)
    Building datafusion-physical-expr v55.1.0 (baseline)
       Built [   5.376s] (baseline)
     Parsing datafusion-physical-expr v55.1.0 (baseline)
      Parsed [   0.039s] (baseline)
    Checking datafusion-physical-expr v55.1.0 -> v55.1.0 (no change; assume patch)
     Checked [   0.248s] 229 checks: 228 pass, 1 fail, 0 warn, 31 skip

--- failure inherent_method_now_returns_unit: inherent method now returns unit ---

Description:
A publicly-visible method that used to return a value now returns `()`.
       impl: https://github.com/obi1kenobi/cargo-semver-checks/tree/v0.51.0/src/lints/inherent_method_now_returns_unit.ron
Failed in:
  datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr::reset in /home/runner/work/datafusion/datafusion/datafusion/physical-expr/src/expressions/dynamic_filters/mod.rs:349

     Summary semver requires new major version: 1 major and 0 minor checks failed
    Finished [  33.594s] datafusion-physical-expr
    Building datafusion-physical-plan v55.1.0 (current)
       Built [  19.400s] (current)
     Parsing datafusion-physical-plan v55.1.0 (current)
      Parsed [   0.161s] (current)
    Building datafusion-physical-plan v55.1.0 (baseline)
       Built [   8.603s] (baseline)
     Parsing datafusion-physical-plan v55.1.0 (baseline)
      Parsed [   0.160s] (baseline)
    Checking datafusion-physical-plan v55.1.0 -> v55.1.0 (no change; assume patch)
     Checked [   0.509s] 229 checks: 229 pass, 31 skip
     Summary no semver update required
    Finished [  29.988s] datafusion-physical-plan

@github-actions github-actions Bot added the auto detected api change Auto detected API change label Oct 25, 2026
@jayzhan211
jayzhan211 added this pull request to the merge queue Oct 25, 2026
Merged via the queue into apache:main with commit aedc0d5 Oct 25, 2026
45 checks passed
/// While this function enables plan reuse, it does not allow the same plan to be executed if it (OR):
///
/// * uses dynamic filters,
/// * uses dynamic filters and the original plan (or another reset copy) is still

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like this is just adding a patch for a symptom rather than fixing the root cause.

One example is that we now hit another corner cases like #27453

We probably need to reasses how recursive CTEs and dynamic filters interact -- for example, maybe we need to separate out the "resetting a plan during execution for the next run of a recursive CTE" and "resetting a plan so it can be reused for another query execution"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe my question is more like given the docs

/// Reset any internal state within this [`ExecutionPlan`].
///
/// This method is called when an [`ExecutionPlan`] needs to be re-executed,
/// such as in recursive queries. Unlike [`ExecutionPlan::replace_children`], this method
/// ensures that any stateful components (e.g., [`DynamicFilterPhysicalExpr`])
/// are reset to their initial state.
///
/// The default implementation simply calls [`ExecutionPlan::replace_children`] with the existing children,
/// effectively creating a new instance of the [`ExecutionPlan`] with the same children but without
/// necessarily resetting any internal state. Implementations that require resetting of some
/// internal state should override this method to provide the necessary logic.
///
/// This method should *not* reset state recursively for children, as it is expected that
/// it will be called from within a walk of the execution plan tree so that it will be called on each child later
/// or was already called on each child.
///
/// Note to implementers: unlike [`ExecutionPlan::replace_children`] this method does not accept new children as an argument,
/// thus it is expected that any cached plan properties will remain valid after the reset.
///
/// [`DynamicFilterPhysicalExpr`]: datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr
fn reset_state(self: Arc<Self>) -> Result<Arc<dyn ExecutionPlan>> {
let children = self.children().into_iter().cloned().collect();
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
)
}
say

    /// This method is called when an [`ExecutionPlan`] needs to be re-executed,
    /// such as in recursive queries. Unlike [`ExecutionPlan::replace_children`], this method
    /// ensures that any stateful components (e.g., [`DynamicFilterPhysicalExpr`])
    /// are reset to their initial state.

Why did we add a caveat to these docs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto detected api change Auto detected API change physical-expr Changes to the physical-expr crates physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt) v56.0.0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hash join dynamic filters don't prune inside recursive CTEs

4 participants