Copilot commented on code in PR #62434:
URL: https://github.com/apache/doris/pull/62434#discussion_r3071267460


##########
be/src/exec/operator/set_sink_operator.cpp:
##########
@@ -101,6 +92,24 @@ Status SetSinkOperatorX<is_intersect>::sink(RuntimeState* 
state, Block* in_block
         COUNTER_SET(local_state._hash_table_size, (int64_t)hash_table_size);
         COUNTER_SET(local_state._valid_element_in_hash_table, 
valid_element_in_hash_tbl);
 
+        // Process runtime filters BEFORE enabling the probe pipeline.
+        //
+        // For Set operators (INTERSECT/EXCEPT), the probe side can shrink the 
hash table
+        // via _refresh_hash_table() after set_ready() enables it. If RF 
processing is
+        // deferred to close(), get_hash_table_size() may return the shrunk 
size, causing
+        // RuntimeFilterWrapper::init() to under-estimate cardinality. This 
breaks the
+        // invariant (unique_column_values <= hash_table_size <= max_in_num) 
and triggers
+        // a spurious error in RuntimeFilterWrapper::insert().
+        //
+        // Note: Set operators do not override finishdependency(), so the 
pipeline task
+        // will NOT wait for synced_filter_size before closing. This means 
processing here
+        // (before the sync response) is equivalent to processing in close() — 
in both
+        // cases _synced_size is likely unavailable and local_size is used 
instead.
+        if (local_state._runtime_filter_producer_helper) {
+            
RETURN_IF_ERROR(local_state._runtime_filter_producer_helper->process(
+                    state, &build_block, hash_table_size));

Review Comment:
   `process()` is now invoked without any exception handling, while the 
previous `close()` path wrapped the call in a `try/catch (Exception&)` and 
converted it into a `Status::InternalError`. If `process()` (or code it calls) 
can throw, this change can turn a handled query error into an uncaught 
exception that may terminate the query/task. Consider restoring the `try/catch` 
wrapper here (or making `process()` no-throw and documenting/enforcing that 
contract), and include similar diagnostic context as the removed `close()` 
error path.
   ```suggestion
               try {
                   
RETURN_IF_ERROR(local_state._runtime_filter_producer_helper->process(
                           state, &build_block, hash_table_size));
               } catch (const Exception& e) {
                   return Status::InternalError(
                           "Failed to process runtime filter in 
SetSinkOperatorX::sink: " +
                           std::string(e.what()));
               }
   ```



##########
be/src/exec/runtime_filter/runtime_filter_wrapper.cpp:
##########
@@ -93,6 +93,10 @@ Status RuntimeFilterWrapper::insert(const ColumnPtr& column, 
size_t start) {
         if (_hybrid_set->size() > _max_in_num) [[unlikely]] {
             _hybrid_set->clear();
             set_state(State::DISABLED, fmt::format("reach max in num: {}", 
_max_in_num));
+            // Report an error because this indicates a logic bug in the 
caller:
+            // init(hash_table_size) should have disabled the filter if 
hash_table_size > max_in_num,
+            // and the number of unique column values cannot exceed 
hash_table_size. If we reach
+            // here, the caller passed an incorrect (too small) 
hash_table_size to init().
             return Status::InternalError(

Review Comment:
   The PR description (and the new regression test comment) says the fix “makes 
insert() gracefully disable instead of returning an error,” but `insert()` 
still returns `Status::InternalError` in the overflow path (and the new comment 
explicitly justifies returning an error). Please align behavior and messaging: 
either (a) change `insert()` to return OK after disabling (if that is the 
intended behavior), or (b) update the PR description and the regression test 
comments to match the current “disable + error” behavior.



##########
be/src/exec/runtime_filter/runtime_filter_producer_helper_set.h:
##########
@@ -53,6 +53,22 @@ class RuntimeFilterProducerHelperSet : public 
RuntimeFilterProducerHelper {
         RETURN_IF_ERROR(_publish(state));
         return Status::OK();
     }
+
+protected:
+    void _init_expr(const VExprContextSPtrs& build_expr_ctxs,
+                    const std::vector<TRuntimeFilterDesc>& 
runtime_filter_descs) override {
+        for (const auto& desc : runtime_filter_descs) {
+            // Set operators (INTERSECT/EXCEPT) always use HASH_SHUFFLE or 
BUCKET_HASH_SHUFFLE,
+            // never broadcast. The constructor hardcodes 
is_broadcast_join=false. Verify that
+            // FE agrees, otherwise the sync_filter_size logic would be 
incorrect.
+            if (desc.is_broadcast_join) {
+                throw Exception(ErrorCode::INTERNAL_ERROR,
+                                "Set operator runtime filter should not be 
broadcast, filter_id={}",
+                                desc.filter_id);
+            }
+        }
+        RuntimeFilterProducerHelper::_init_expr(build_expr_ctxs, 
runtime_filter_descs);

Review Comment:
   Throwing an exception during `_init_expr()` will fail the query if FE ever 
sends an unexpected `is_broadcast_join=true`. If this is meant as a hard 
invariant, consider using a debug assertion (`DCHECK`) plus a release-safe 
behavior (e.g., disabling sync-filter-size logic / disabling the RF) so 
production queries don’t hard-fail due to descriptor mismatches. At minimum, it 
would help to include more context in the error (e.g., plan node id / fragment 
id if available) to speed up diagnosis.
   ```suggestion
           std::vector<TRuntimeFilterDesc> sanitized_runtime_filter_descs = 
runtime_filter_descs;
           for (auto& desc : sanitized_runtime_filter_descs) {
               // Set operators (INTERSECT/EXCEPT) always use HASH_SHUFFLE or 
BUCKET_HASH_SHUFFLE,
               // never broadcast. The constructor hardcodes 
is_broadcast_join=false. Keep a debug
               // invariant check, but sanitize the unexpected FE flag in 
release builds so query
               // initialization does not hard-fail and the helper remains 
consistent with its
               // non-broadcast behavior.
               DCHECK(!desc.is_broadcast_join);
               if (desc.is_broadcast_join) {
                   desc.is_broadcast_join = false;
               }
           }
           RuntimeFilterProducerHelper::_init_expr(build_expr_ctxs, 
sanitized_runtime_filter_descs);
   ```



##########
regression-test/suites/query_p0/runtime_filter/set_operator_in_filter.groovy:
##########
@@ -0,0 +1,141 @@
+// 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.
+
+// Regression test for race condition in Set operator (INTERSECT/EXCEPT) with
+// IN_FILTER runtime filter type.
+//
+// Before the fix, when runtime_filter_type=1 (IN) and 
runtime_filter_max_in_num
+// was small, a race between the build sink's close() and the probe's hash 
table
+// refresh could cause RuntimeFilterWrapper::insert() to fail with 
InternalError.
+// The fix moves RF processing to sink(eos) before set_ready(), and also makes
+// insert() gracefully disable instead of returning an error.
+
+suite("set_operator_in_filter") {
+    sql "DROP TABLE IF EXISTS set_rf_t1"
+    sql "DROP TABLE IF EXISTS set_rf_t2"
+    sql "DROP TABLE IF EXISTS set_rf_t3"
+
+    sql """
+        CREATE TABLE set_rf_t1 (
+            k1 INT NOT NULL,
+            v1 VARCHAR(64) NOT NULL
+        )
+        DUPLICATE KEY(k1)
+        DISTRIBUTED BY HASH(k1) BUCKETS 3
+        PROPERTIES("replication_num" = "1");
+    """
+
+    sql """
+        CREATE TABLE set_rf_t2 (
+            k1 INT NOT NULL,
+            v1 VARCHAR(64) NOT NULL
+        )
+        DUPLICATE KEY(k1)
+        DISTRIBUTED BY HASH(k1) BUCKETS 3
+        PROPERTIES("replication_num" = "1");
+    """
+
+    sql """
+        CREATE TABLE set_rf_t3 (
+            k1 INT NOT NULL,
+            v1 VARCHAR(64) NOT NULL
+        )
+        DUPLICATE KEY(k1)
+        DISTRIBUTED BY HASH(k1) BUCKETS 3
+        PROPERTIES("replication_num" = "1");
+    """
+
+    // Insert >10 unique values into t1 so that with max_in_num=10 the IN 
filter
+    // would overflow. This is the key condition that triggers the original 
bug.
+    sql """
+        INSERT INTO set_rf_t1 VALUES
+        (1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e'),
+        (6,'f'),(7,'g'),(8,'h'),(9,'i'),(10,'j'),
+        (11,'k'),(12,'l'),(13,'m'),(14,'n'),(15,'o'),
+        (16,'p'),(17,'q'),(18,'r'),(19,'s'),(20,'t');
+    """
+
+    // t2 shares some values with t1 (for INTERSECT) and has extras (for 
EXCEPT)
+    sql """
+        INSERT INTO set_rf_t2 VALUES
+        (1,'a'),(3,'c'),(5,'e'),(7,'g'),(9,'i'),
+        (11,'k'),(13,'m'),(15,'o'),(17,'q'),(19,'s'),
+        (21,'u'),(22,'v');
+    """
+
+    // t3 is the probe-side table for the join that triggers RF generation
+    sql """
+        INSERT INTO set_rf_t3 VALUES
+        (1,'x'),(3,'x'),(5,'x'),(7,'x'),(9,'x'),
+        (11,'x'),(13,'x'),(15,'x'),(100,'x'),(200,'x');
+    """
+
+    sql "sync"
+
+    // Use pure IN_FILTER type with a small max_in_num to reproduce the 
conditions
+    // that triggered the race condition bug.
+    sql "set runtime_filter_type = 1"
+    sql "set runtime_filter_max_in_num = 10"
+    sql "set disable_join_reorder = true"
+
+    // INTERSECT with join: the INTERSECT probe shrinks the hash table, which
+    // previously could race with RF processing in the build sink's close().
+    order_qt_intersect_in_rf """
+        SELECT T.k1 FROM (
+            SELECT k1 FROM set_rf_t1
+            INTERSECT
+            SELECT k1 FROM set_rf_t2
+        ) T JOIN set_rf_t3 ON T.k1 = set_rf_t3.k1;
+    """
+
+    // EXCEPT with join: similar scenario but with EXCEPT semantics.
+    order_qt_except_in_rf """
+        SELECT T.k1 FROM (
+            SELECT k1 FROM set_rf_t1
+            EXCEPT
+            SELECT k1 FROM set_rf_t2
+        ) T JOIN set_rf_t3 ON T.k1 = set_rf_t3.k1;
+    """
+

Review Comment:
   This suite changes session-level knobs but doesn’t restore them at the end. 
If the regression framework reuses the same session across suites, these 
settings can leak and create hard-to-debug failures in unrelated tests. 
Consider capturing the prior values and restoring them in a `try/finally` (or 
explicitly resetting to known defaults at the end of the suite).
   ```suggestion
       def originalRuntimeFilterType = sql "show variables like 
'runtime_filter_type'"
       def originalRuntimeFilterMaxInNum = sql "show variables like 
'runtime_filter_max_in_num'"
       def originalDisableJoinReorder = sql "show variables like 
'disable_join_reorder'"
       def savedRuntimeFilterType = originalRuntimeFilterType[0][1]
       def savedRuntimeFilterMaxInNum = originalRuntimeFilterMaxInNum[0][1]
       def savedDisableJoinReorder = originalDisableJoinReorder[0][1]
   
       try {
           sql "set runtime_filter_type = 1"
           sql "set runtime_filter_max_in_num = 10"
           sql "set disable_join_reorder = true"
   
           // INTERSECT with join: the INTERSECT probe shrinks the hash table, 
which
           // previously could race with RF processing in the build sink's 
close().
           order_qt_intersect_in_rf """
               SELECT T.k1 FROM (
                   SELECT k1 FROM set_rf_t1
                   INTERSECT
                   SELECT k1 FROM set_rf_t2
               ) T JOIN set_rf_t3 ON T.k1 = set_rf_t3.k1;
           """
   
           // EXCEPT with join: similar scenario but with EXCEPT semantics.
           order_qt_except_in_rf """
               SELECT T.k1 FROM (
                   SELECT k1 FROM set_rf_t1
                   EXCEPT
                   SELECT k1 FROM set_rf_t2
               ) T JOIN set_rf_t3 ON T.k1 = set_rf_t3.k1;
           """
       } finally {
           sql "set runtime_filter_type = ${savedRuntimeFilterType}"
           sql "set runtime_filter_max_in_num = ${savedRuntimeFilterMaxInNum}"
           sql "set disable_join_reorder = ${savedDisableJoinReorder}"
       }
   ```



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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to