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

yiguolei pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 441cd03013d [fix](runtime-filter) Publish merged filter under the 
merge-context lock (#71289)
441cd03013d is described below

commit 441cd03013dbfc68069556e95c6bcb358c72da04
Author: Jerry Hu <[email protected]>
AuthorDate: Thu Dec 3 10:40:19 2026 +0800

    [fix](runtime-filter) Publish merged filter under the merge-context lock 
(#71289)
    
    ### Background
    
    For a global runtime filter, the producers of every fragment instance
    send their partial filters
    to one merge coordinator on one BE. `merge()` accumulates them in
    `GlobalMergeContext::merger`;
    when the expected producer count is reached, the merged filter is
    serialized and published.
    Serializing a Bloom filter returns a raw pointer into the merger-owned
    buffer. A recursive CTE
    rebuilds its recursive-part fragments every round, and
    `reset_global_rf()` replaces the merger,
    stage, `done`, and the publish callback owners under
    `GlobalMergeContext::mtx`.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #58916 (introduced the reset path), #61130 (added the reset
    lock, left the publish outside it)
    PR Type: Bugfix
    
    Problem Summary: `merge()` released `GlobalMergeContext::mtx` before
    publishing and then read the
    merger, stage, `done`, targets, and callback owners unlocked. A
    concurrent `reset_global_rf()`
    could destroy the merger between `serialize()` and the `memcpy()` of its
    Bloom buffer, an ASAN
    heap-use-after-free observed once in a branch-4.2 P0 run; the other
    reads were data races. The
    publish now runs under the same lock that the reset takes.
    
    ### Details
    
    - **Frequency:** Intermittent. One branch-4.2 P0 ASAN crash
    (`heap-use-after-free`, READ of size
    1048576); it needs a recursive CTE whose recursive join publishes a
    global RF across an
      Exchange.
    - **Root cause:** the unlocked publish read `merger`, `stage`, `done`,
    `targetv2_info`, and
    `publish_callbacks`, all of which `reset()` replaces or clears under the
    same mutex; the old
    merger is freed when the last reference drops, between `serialize()` and
    `memcpy()`.
    - **Why existing tests missed it:** the unit test only called `init()`,
    and the regression suite
    could stay an IN set (protobuf copy, no raw pointer) or fall back to a
    bucket-shuffle plan for
    small `parallel_pipeline_task_num`, which makes the RF local and skips
    the global merge; P0
      fuzzes that variable and `enable_runtime_filter_prune`. The suite pins
    `enable_bucket_shuffle_join = false` and `enable_runtime_filter_prune =
    false`, asserts
    `INNER JOIN(PARTITIONED)`, and forces `runtime_filter_type = 2` so the
    raw-pointer Bloom path
      runs on every round.
    - **Fix:** `merge()` calls `_send_rf_to_target()` while still holding
    `cnt_val.mtx`: the
    readiness check, the merge, the serialization and copy of the Bloom
    buffer, and the publish
    state (`done`, `stage`, `publish_callbacks`) are atomic with respect to
    `reset()` under the
    same lock. `send_filter_size()` already holds this lock across its RPCs,
    so the scope is
    consistent. A round reset may wait for the publish to be issued
    (serialize + copy + async RPC
      submission); that is bounded and happens once per round.
    - **Other paths and branches:**
    `send_filter_size()`/`sync_filter_size()` already synchronize
    with `reset()`; the local merge path replaces the whole
    `LocalMergeContext` and keeps it alive
    through `shared_ptr`. The bug exists on master, branch-4.1, and
    branch-4.2; branch-4.0 has no
      `reset_global_rf()`.
    - **Configs and defaults:** None.
    
    ### Testing
    
    - `BUILD_TYPE=ASAN ./build.sh --be -j 64`: passed, ASAN-instrumented;
    glibc 2.17 check passed.
    - `./run-be-ut.sh --run --filter='RuntimeFilterMgrTest.*'`: passed
    (5/5).
    - Local ASAN FE + BE cluster: `rf_merge_context_reuse` passed with the
    pinned partitioned plan and
    the forced-Bloom case; `query_p0/runtime_filter` 11/11 passed; no ASAN
    report in the BE log.
    - `build-support/check-build-hygiene.sh`, `clang-format --dry-run
    --Werror`, and clang-tidy on the
      changed lines passed.
    
    ### Notes for Reviewers
    
    The publish (including the asynchronous RPC submission) now runs under
    `cnt_val.mtx`; the reset
    RPC waits for that submission but never for RPC completion. Direct and
    tree publish keep their
    existing behavior. Pre-existing and out of scope: `debug_string()` reads
    the merger without the
    lock, and `_send_reset_global_rf` does not check `controller.Failed()`
    after `brpc::Join`.
    
    ### Release note
    
    Fix a rare BE crash (heap-use-after-free) in recursive CTE queries that
    use a global runtime
    filter across an Exchange, where a round switch could free the merged
    Bloom filter or reset its
    publish state while it was being published.
    
    ### Check List (For Author)
    
    - Behavior changed: No
    - Does this need documentation: No
    - Pre-submission status: Ready
    
    ### AI Disclosure
    
    - Tool: Claude Code (deepseek-flash)
    - Generated: Code change, regression test and its expected output, and
    this message
    - Human review: Pending
---
 be/src/exec/runtime_filter/runtime_filter_mgr.cpp  | 23 ++++++++++------
 .../data/recursive_cte/rf_merge_context_reuse.out  |  7 +++++
 .../recursive_cte/rf_merge_context_reuse.groovy    | 31 +++++++++++++++++++++-
 3 files changed, 52 insertions(+), 9 deletions(-)

diff --git a/be/src/exec/runtime_filter/runtime_filter_mgr.cpp 
b/be/src/exec/runtime_filter/runtime_filter_mgr.cpp
index 29912f5c441..a984a02ec04 100644
--- a/be/src/exec/runtime_filter/runtime_filter_mgr.cpp
+++ b/be/src/exec/runtime_filter/runtime_filter_mgr.cpp
@@ -592,15 +592,22 @@ Status 
RuntimeFilterMergeControllerEntity::merge(std::shared_ptr<QueryContext> q
         RETURN_IF_ERROR(cnt_val.merger->merge_from(tmp_filter.get(), 
&is_ready));
 
         cnt_val.arrive_id.insert(UniqueId(request->fragment_instance_id()));
-    }
 
-    if (is_ready) {
-        return _send_rf_to_target(cnt_val,
-                                  query_ctx->ignore_runtime_filter_error()
-                                          ? std::weak_ptr<QueryContext> {}
-                                          : query_ctx,
-                                  merge_time, request->query_id(), 
query_ctx->execution_timeout(),
-                                  query_ctx->query_options());
+        if (is_ready) {
+            // Publish while `cnt_val.mtx` is still held. reset_global_rf() 
replaces and destroys
+            // `merger` under the same lock, while serialize() hands out a raw 
pointer into the
+            // merger's filter buffer and the publish state (`done`, `stage`,
+            // `publish_callbacks`) belongs to the current stage. Keeping the 
readiness check and
+            // the whole publish in one critical section makes them atomic 
with respect to a
+            // recursive CTE round reset; otherwise the merger can be 
destroyed between
+            // serialize() and the memcpy of its buffer.
+            return _send_rf_to_target(cnt_val,
+                                      query_ctx->ignore_runtime_filter_error()
+                                              ? std::weak_ptr<QueryContext> {}
+                                              : query_ctx,
+                                      merge_time, request->query_id(),
+                                      query_ctx->execution_timeout(), 
query_ctx->query_options());
+        }
     }
     return Status::OK();
 }
diff --git a/regression-test/data/recursive_cte/rf_merge_context_reuse.out 
b/regression-test/data/recursive_cte/rf_merge_context_reuse.out
index 1d2d81f8316..a18c7e83256 100644
--- a/regression-test/data/recursive_cte/rf_merge_context_reuse.out
+++ b/regression-test/data/recursive_cte/rf_merge_context_reuse.out
@@ -4,3 +4,10 @@
 2
 3
 4
+
+-- !recursive_bloom --
+1
+2
+3
+4
+
diff --git a/regression-test/suites/recursive_cte/rf_merge_context_reuse.groovy 
b/regression-test/suites/recursive_cte/rf_merge_context_reuse.groovy
index 05fec4b26a4..654c8b5eec9 100644
--- a/regression-test/suites/recursive_cte/rf_merge_context_reuse.groovy
+++ b/regression-test/suites/recursive_cte/rf_merge_context_reuse.groovy
@@ -19,6 +19,16 @@ suite('rf_merge_context_reuse') {
     sql '''create table rf_merge_reuse_edges (src int, dst int) duplicate 
key(src)
             distributed by hash(src) buckets 4 properties ("replication_num" = 
"1")'''
     sql 'insert into rf_merge_reuse_edges values (1, 2), (2, 3), (3, 4)'
+    // Keep the probe scan in its own fragment. With bucket shuffle enabled 
the regulator may put
+    // it into the join fragment (BUCKET_SHUFFLE) for small 
parallel_pipeline_task_num values,
+    // which turns the RF into a local filter: no global merge coordinator, no 
publish, and no
+    // round reset on that path. P0 fuzzes parallel_pipeline_task_num, so pin 
the plan instead of
+    // letting the coverage depend on the connection.
+    sql 'set enable_bucket_shuffle_join = false'
+    // P0 fuzzes enable_runtime_filter_prune as well. The pruner keeps this RF 
today (the build
+    // side has no usable statistics), but pin the setting so the plan 
assertions below cannot
+    // depend on the pruner's future decisions.
+    sql 'set enable_runtime_filter_prune = false'
 
     String plan = sql('''explain with recursive numbers(n) as (
                             select cast(1 as int)
@@ -28,7 +38,7 @@ suite('rf_merge_context_reuse') {
                          ) select n from numbers order by n''').toString()
     // The recursive join must publish RFs across an Exchange on every round;
     // a constants-only recursive query never exercises the merge-context 
reset.
-    assertTrue(plan.contains('INNER JOIN('), plan)
+    assertTrue(plan.contains('INNER JOIN(PARTITIONED)'), plan)
     assertTrue(plan.contains('runtime filters: RF'), plan)
     assertTrue(plan.contains('-> src'), plan)
     assertTrue(plan.contains('VEXCHANGE'), plan)
@@ -39,4 +49,23 @@ suite('rf_merge_context_reuse') {
                             select cast(e.dst as int) from 
rf_merge_reuse_edges e
                             inner join [shuffle] numbers r on e.src = r.n 
where r.n < 4
                           ) select n from numbers order by n'''
+
+    // A merged Bloom filter is serialized as a raw pointer into the merger's 
buffer and then
+    // copied by the coordinator, while a small IN set is copied through 
protobuf. Force Bloom
+    // (runtime_filter_type = 2) so the recursive rounds also exercise that 
copy path, which a
+    // round reset must not invalidate.
+    sql 'set runtime_filter_type = 2'
+    String bloomPlan = sql('''explain with recursive numbers(n) as (
+                            select cast(1 as int)
+                            union all
+                            select cast(e.dst as int) from 
rf_merge_reuse_edges e
+                            inner join [shuffle] numbers r on e.src = r.n 
where r.n < 4
+                         ) select n from numbers order by n''').toString()
+    assertTrue(bloomPlan.contains('runtime filters: RF') && 
bloomPlan.contains('[bloom]'), bloomPlan)
+    order_qt_recursive_bloom '''with recursive numbers(n) as (
+                            select cast(1 as int)
+                            union all
+                            select cast(e.dst as int) from 
rf_merge_reuse_edges e
+                            inner join [shuffle] numbers r on e.src = r.n 
where r.n < 4
+                          ) select n from numbers order by n'''
 }


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

Reply via email to