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

JkSelf pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gluten.git


The following commit(s) were added to refs/heads/main by this push:
     new 3505830c74 [GLUTEN][VL] Refactor BroadcastHashJoin optimization to use 
fake task building the hash table (#13216)
3505830c74 is described below

commit 3505830c74fa496128d00291b8636a7b8d215743
Author: Ke Jia <[email protected]>
AuthorDate: Mon Nov 23 09:56:02 2026 +0000

    [GLUTEN][VL] Refactor BroadcastHashJoin optimization to use fake task 
building the hash table (#13216)
---
 .../execution/VeloxBroadcastBuildSideCache.scala   |  51 +++-
 .../apache/spark/rpc/GlutenExecutorEndpoint.scala  |   4 +-
 cpp/velox/CMakeLists.txt                           |   2 +-
 cpp/velox/jni/JniHashTable.cc                      | 175 +++++------
 cpp/velox/jni/JniHashTable.h                       |  40 ++-
 cpp/velox/jni/VeloxJniWrapper.cc                   | 201 +++----------
 cpp/velox/operators/hashjoin/BroadcastHashTable.h  |  65 +++++
 cpp/velox/operators/hashjoin/HashTableBuilder.cc   | 324 ---------------------
 cpp/velox/operators/hashjoin/HashTableBuilder.h    | 164 -----------
 .../operators/hashjoin/HashTableTaskBuilder.cc     | 256 ++++++++++++++++
 .../operators/hashjoin/HashTableTaskBuilder.h      |  69 +++++
 cpp/velox/substrait/SubstraitToVeloxPlan.cc        |  19 +-
 12 files changed, 591 insertions(+), 779 deletions(-)

diff --git 
a/backends-velox/src/main/scala/org/apache/gluten/execution/VeloxBroadcastBuildSideCache.scala
 
b/backends-velox/src/main/scala/org/apache/gluten/execution/VeloxBroadcastBuildSideCache.scala
index 02b18b5d2b..3ab7868808 100644
--- 
a/backends-velox/src/main/scala/org/apache/gluten/execution/VeloxBroadcastBuildSideCache.scala
+++ 
b/backends-velox/src/main/scala/org/apache/gluten/execution/VeloxBroadcastBuildSideCache.scala
@@ -21,10 +21,10 @@ import 
org.apache.gluten.backendsapi.velox.VeloxBackendSettings
 import org.apache.gluten.runtime.Runtimes
 import org.apache.gluten.vectorized.HashJoinBuilder
 
-import org.apache.spark.SparkEnv
+import org.apache.spark.{SparkEnv, TaskContext}
 import org.apache.spark.broadcast.Broadcast
 import org.apache.spark.internal.Logging
-import org.apache.spark.sql.execution.ColumnarBuildSideRelation
+import org.apache.spark.sql.execution.{ColumnarBuildSideRelation, SQLExecution}
 import org.apache.spark.sql.execution.joins.BuildSideRelation
 import org.apache.spark.sql.execution.unsafe.UnsafeColumnarBuildSideRelation
 import org.apache.spark.task.TaskResources
@@ -83,19 +83,44 @@ object VeloxBroadcastBuildSideCache
         }
       ).build[String, SerializedBroadcastHashTable]()
 
+  /**
+   * The cache key of the hash table of `buildHashTableId` in SQL execution 
`executionId`.
+   *
+   * Runs of the same physical plan share `buildHashTableId`, but each run 
cleans up its tables when
+   * it ends, asynchronously. Keying by execution as well keeps the cleanup of 
one run from dropping
+   * the table that the next run is building or probing.
+   */
+  def executionCacheKey(buildHashTableId: String, executionId: String): String 
=
+    s"$buildHashTableId:$executionId"
+
+  /**
+   * The cache key of the hash table of `buildHashTableId` in the SQL 
execution of the current task.
+   * This is also called from c++ side.
+   */
+  def taskCacheKey(buildHashTableId: String): String = {
+    val taskContext = TaskContext.get()
+    val executionId =
+      if (taskContext == null) null
+      else taskContext.getLocalProperty(SQLExecution.EXECUTION_ID_KEY)
+    executionCacheKey(buildHashTableId, executionId)
+  }
+
   def getOrBuildBroadcastHashTable(
       broadcast: Broadcast[BuildSideRelation],
       broadcastContext: BroadcastHashJoinContext): BroadcastHashTable = {
 
+    val cacheKey = taskCacheKey(broadcastContext.buildHashTableId)
     buildSideRelationCache
       .get(
-        broadcastContext.buildHashTableId,
+        cacheKey,
         (_: String) => {
+          // The native side caches the table under the id of the context.
+          val context = broadcastContext.copy(buildHashTableId = cacheKey)
           val (pointer, relation, droppedDuplicates) = broadcast.value match {
             case columnar: ColumnarBuildSideRelation =>
-              columnar.buildHashTable(broadcastContext)
+              columnar.buildHashTable(context)
             case unsafe: UnsafeColumnarBuildSideRelation =>
-              unsafe.buildHashTable(broadcastContext)
+              unsafe.buildHashTable(context)
           }
 
           broadcastContext.hashTableMemorySizeMetric.foreach(
@@ -196,12 +221,13 @@ object VeloxBroadcastBuildSideCache
       deserializeHashTableTimeMetric: 
Option[org.apache.spark.sql.execution.metric.SQLMetric] =
         None): BroadcastHashTable = {
 
+    val cacheKey = taskCacheKey(broadcastHashTableId)
     buildSideRelationCache.get(
-      broadcastHashTableId,
+      cacheKey,
       (_: String) => {
-        logInfo(s"Deserializing hash table on executor for broadcast ID: 
$broadcastHashTableId")
+        logInfo(s"Deserializing hash table on executor for broadcast ID: 
$cacheKey")
         val startTime = System.currentTimeMillis()
-        val hashTableHandle = serialized.deserialize(broadcastHashTableId)
+        val hashTableHandle = serialized.deserialize(cacheKey)
         val timeMs = System.currentTimeMillis() - startTime
         deserializeHashTableTimeMetric.foreach(_ += timeMs)
         BroadcastHashTable(
@@ -212,13 +238,14 @@ object VeloxBroadcastBuildSideCache
     )
   }
 
-  /** This is called from c++ side. */
-  def get(broadcastHashtableId: String): Long = {
-    Option(buildSideRelationCache.getIfPresent(broadcastHashtableId))
+  /** This is called from c++ side, with a key from [[taskCacheKey]]. */
+  def get(cacheKey: String): Long = {
+    Option(buildSideRelationCache.getIfPresent(cacheKey))
       .map(_.pointer)
-      .getOrElse(0)
+      .getOrElse(0L)
   }
 
+  /** `broadcastHashtableId` is a key from [[executionCacheKey]]. */
   def invalidateBroadcastHashtable(broadcastHashtableId: String): Unit = {
     // Cleanup operations on the backend are idempotent.
     buildSideRelationCache.invalidate(broadcastHashtableId)
diff --git 
a/backends-velox/src/main/scala/org/apache/spark/rpc/GlutenExecutorEndpoint.scala
 
b/backends-velox/src/main/scala/org/apache/spark/rpc/GlutenExecutorEndpoint.scala
index 49ecef20b3..1a49873e6c 100644
--- 
a/backends-velox/src/main/scala/org/apache/spark/rpc/GlutenExecutorEndpoint.scala
+++ 
b/backends-velox/src/main/scala/org/apache/spark/rpc/GlutenExecutorEndpoint.scala
@@ -62,7 +62,9 @@ class GlutenExecutorEndpoint(val executorId: String, val 
conf: SparkConf)
     case GlutenCleanExecutionResource(executionId, hashIds) =>
       if (executionId != null) {
         hashIds.forEach(
-          resource_id => 
VeloxBroadcastBuildSideCache.invalidateBroadcastHashtable(resource_id))
+          resource_id =>
+            VeloxBroadcastBuildSideCache.invalidateBroadcastHashtable(
+              VeloxBroadcastBuildSideCache.executionCacheKey(resource_id, 
executionId)))
       }
 
     case e =>
diff --git a/cpp/velox/CMakeLists.txt b/cpp/velox/CMakeLists.txt
index 6500d5c446..e31e9d9b59 100644
--- a/cpp/velox/CMakeLists.txt
+++ b/cpp/velox/CMakeLists.txt
@@ -181,7 +181,7 @@ set(VELOX_SRCS
     operators/functions/RowConstructorWithNull.cc
     operators/functions/SparkExprToSubfieldFilterParser.cc
     operators/plannodes/RowVectorStream.cc
-    operators/hashjoin/HashTableBuilder.cc
+    operators/hashjoin/HashTableTaskBuilder.cc
     operators/hashjoin/HashTableSerializer.cc
     operators/reader/FileReaderIterator.cc
     operators/reader/ParquetReaderIterator.cc
diff --git a/cpp/velox/jni/JniHashTable.cc b/cpp/velox/jni/JniHashTable.cc
index 0e5481360a..63c7af3e37 100644
--- a/cpp/velox/jni/JniHashTable.cc
+++ b/cpp/velox/jni/JniHashTable.cc
@@ -24,6 +24,7 @@
 #include "memory/ColumnarBatch.h"
 #include "memory/VeloxColumnarBatch.h"
 #include "operators/hashjoin/HashTableSerializer.h"
+#include "operators/hashjoin/HashTableTaskBuilder.h"
 #include "substrait/algebra.pb.h"
 #include "substrait/type.pb.h"
 #include "velox/core/PlanNode.h"
@@ -36,6 +37,8 @@ void JniHashTableContext::initialize(JNIEnv* env, JavaVM* 
javaVm) {
   const char* classSig = 
"Lorg/apache/gluten/execution/VeloxBroadcastBuildSideCache;";
   jniVeloxBroadcastBuildSideCache_ = createGlobalClassReferenceOrError(env, 
classSig);
   jniGet_ = getStaticMethodId(env, jniVeloxBroadcastBuildSideCache_, "get", 
"(Ljava/lang/String;)J");
+  jniTaskCacheKey_ = getStaticMethodId(
+      env, jniVeloxBroadcastBuildSideCache_, "taskCacheKey", 
"(Ljava/lang/String;)Ljava/lang/String;");
 }
 
 void JniHashTableContext::finalize(JNIEnv* env) {
@@ -63,8 +66,29 @@ std::optional<jlong> JniHashTableContext::callJavaGet(const 
std::string& id) con
   return result;
 }
 
-// Return the velox's hash table.
-std::shared_ptr<HashTableBuilder> nativeHashTableBuild(
+std::optional<std::string> JniHashTableContext::callJavaCacheKey(const 
std::string& hashTableId) const {
+  if (vm_ == nullptr) {
+    return std::nullopt;
+  }
+
+  JNIEnv* env;
+  if (vm_->GetEnv(reinterpret_cast<void**>(&env), jniVersion) != JNI_OK) {
+    throw gluten::GlutenException("JNIEnv was not attached to current thread");
+  }
+
+  const jstring s = env->NewStringUTF(hashTableId.c_str());
+  checkException(env);
+  auto result =
+      
static_cast<jstring>(env->CallStaticObjectMethod(jniVeloxBroadcastBuildSideCache_,
 jniTaskCacheKey_, s));
+  env->DeleteLocalRef(s);
+  checkException(env);
+  auto cacheKey = jStringToCString(env, result);
+  env->DeleteLocalRef(result);
+  return cacheKey;
+}
+
+std::shared_ptr<BroadcastHashTable> nativeHashTableBuild(
+    const std::string& hashTableId,
     const std::vector<std::string>& joinKeys,
     const std::vector<std::string>& filterBuildColumns,
     bool filterPropagatesNulls,
@@ -80,6 +104,9 @@ std::shared_ptr<HashTableBuilder> nativeHashTableBuild(
     uint32_t abandonHashBuildDedupMinRows,
     uint32_t abandonHashBuildDedupMinPct,
     std::vector<std::shared_ptr<ColumnarBatch>>& batches,
+    uint32_t numThreads,
+    folly::Executor* executor,
+    std::shared_ptr<facebook::velox::memory::MemoryPool> queryPool,
     std::shared_ptr<facebook::velox::memory::MemoryPool> memoryPool) {
   auto rowType = std::make_shared<facebook::velox::RowType>(std::move(names), 
std::move(veloxTypeList));
 
@@ -123,148 +150,100 @@ std::shared_ptr<HashTableBuilder> nativeHashTableBuild(
       VELOX_NYI("Unsupported Join type: {}", std::to_string(sJoin));
   }
 
-  std::vector<std::shared_ptr<const 
facebook::velox::core::FieldAccessTypedExpr>> joinKeyTypes;
-  joinKeyTypes.reserve(joinKeys.size());
-  for (const auto& name : joinKeys) {
-    joinKeyTypes.emplace_back(
-        
std::make_shared<facebook::velox::core::FieldAccessTypedExpr>(rowType->findChild(name),
 name));
-  }
-
-  std::vector<uint32_t> filterInputChannels;
-  filterInputChannels.reserve(filterBuildColumns.size());
+  using facebook::velox::core::QueryConfig;
+  HashTableTaskBuildSpec spec;
+  spec.joinType = vJoin;
+  spec.nullAware = isNullAwareAntiJoin;
+  spec.withFilter = hasMixedJoinCondition;
   for (const auto& name : filterBuildColumns) {
-    if (const auto idx = rowType->getChildIdxIfExists(name)) {
-      filterInputChannels.push_back(*idx);
+    if (rowType->containsChild(name) &&
+        std::find(spec.filterBuildColumns.begin(), 
spec.filterBuildColumns.end(), name) ==
+            spec.filterBuildColumns.end()) {
+      spec.filterBuildColumns.push_back(name);
     }
   }
-  std::sort(filterInputChannels.begin(), filterInputChannels.end());
-  filterInputChannels.erase(
-      std::unique(filterInputChannels.begin(), filterInputChannels.end()), 
filterInputChannels.end());
-
-  auto hashTableBuilder = std::make_shared<HashTableBuilder>(
-      vJoin,
-      isNullAwareAntiJoin,
-      hasMixedJoinCondition,
-      bloomFilterPushdownSize,
-      joinKeyTypes,
-      filterInputChannels,
-      filterPropagatesNulls,
-      rowType,
-      memoryPool.get(),
-      minTableRowsForParallelJoinBuild,
-      joinBuildVectorHasherMaxNumDistinct,
-      abandonHashBuildDedupMinRows,
-      abandonHashBuildDedupMinPct);
-
-  for (auto i = 0; i < batches.size(); i++) {
-    auto rowVector = VeloxColumnarBatch::from(memoryPool.get(), 
batches[i])->getRowVector();
-    hashTableBuilder->addInput(rowVector);
-    if (hashTableBuilder->noMoreInput()) {
-      break;
-    }
+  spec.filterPropagatesNulls = filterPropagatesNulls;
+  spec.buildType = rowType;
+  spec.joinKeys = joinKeys;
+  spec.queryConfigs = {
+      {QueryConfig::kMinTableRowsForParallelJoinBuild, 
std::to_string(minTableRowsForParallelJoinBuild)},
+      {QueryConfig::kJoinBuildVectorHasherMaxNumDistinct, 
std::to_string(joinBuildVectorHasherMaxNumDistinct)},
+      {QueryConfig::kAbandonDedupHashMapMinRows, 
std::to_string(abandonHashBuildDedupMinRows)},
+      {QueryConfig::kAbandonDedupHashMapMinPct, 
std::to_string(abandonHashBuildDedupMinPct)},
+      {QueryConfig::kHashProbeBloomFilterPushdownMaxSize,
+       std::to_string(std::max<int64_t>(bloomFilterPushdownSize, 0))},
+  };
+
+  std::vector<facebook::velox::RowVectorPtr> buildVectors;
+  buildVectors.reserve(batches.size());
+  for (const auto& batch : batches) {
+    buildVectors.emplace_back(VeloxColumnarBatch::from(memoryPool.get(), 
batch)->getRowVector());
   }
+  return buildHashTableWithTask(
+      hashTableId, spec, buildVectors, numThreads, executor, 
std::move(queryPool), memoryPool.get());
+}
 
-  return hashTableBuilder;
+std::string getJoinCacheKey(const std::string& hashTableId) {
+  return 
JniHashTableContext::getInstance().callJavaCacheKey(hashTableId).value_or(hashTableId);
 }
 
-long getJoin(const std::string& hashTableId) {
-  const auto handle = 
JniHashTableContext::getInstance().callJavaGet(hashTableId);
+long getJoin(const std::string& cacheKey) {
+  const auto handle = JniHashTableContext::getInstance().callJavaGet(cacheKey);
   if (!handle.has_value()) {
     // The JVM side VeloxBroadcastBuildSideCache holding the pre-built hash 
tables is unreachable,
     // e.g. in the standalone micro benchmark. Report a miss, the same way 
that cache reports one,
     // and let the caller build the hash table from the join's build side 
input instead.
     LOG(WARNING) << "No JVM is attached to this process, cannot look up the 
pre-built hash table for cache key: "
-                 << hashTableId << ". A new hash table will be built from the 
build side input.";
+                 << cacheKey << ". A new hash table will be built from the 
build side input.";
     return 0;
   }
   return handle.value();
 }
 
-size_t serializedHashTableSize(std::shared_ptr<HashTableBuilder> builder) {
-  VELOX_CHECK_NOT_NULL(builder, "Hash table builder cannot be null");
+size_t serializedHashTableSize(const BroadcastHashTable& hashTable) {
+  const auto& table = hashTable.hashTable();
+  VELOX_CHECK_NOT_NULL(table, "Hash table cannot be null");
 
-  auto hashTable = builder->hashTable();
-  VELOX_CHECK_NOT_NULL(hashTable, "Hash table cannot be null");
-
-  auto* hashTableFalse = 
dynamic_cast<facebook::velox::exec::HashTable<false>*>(hashTable.get());
+  auto* hashTableFalse = 
dynamic_cast<facebook::velox::exec::HashTable<false>*>(table.get());
   if (hashTableFalse != nullptr) {
     return HashTableSerializer::serializedSize<false>(hashTableFalse);
   }
 
-  auto* hashTableTrue = 
dynamic_cast<facebook::velox::exec::HashTable<true>*>(hashTable.get());
+  auto* hashTableTrue = 
dynamic_cast<facebook::velox::exec::HashTable<true>*>(table.get());
   VELOX_CHECK_NOT_NULL(hashTableTrue, "Hash table must be either 
HashTable<false> or HashTable<true>");
   return HashTableSerializer::serializedSize<true>(hashTableTrue);
 }
 
-int64_t hashTableMemoryUsage(std::shared_ptr<HashTableBuilder> builder) {
-  VELOX_CHECK_NOT_NULL(builder, "Hash table builder cannot be null");
-  return builder->hashTableMemoryUsage();
-}
-
-void serializeHashTableTo(std::shared_ptr<HashTableBuilder> builder, uint8_t* 
data, size_t size) {
-  VELOX_CHECK_NOT_NULL(builder, "Hash table builder cannot be null");
+void serializeHashTableTo(const BroadcastHashTable& hashTable, uint8_t* data, 
size_t size) {
   VELOX_CHECK_NOT_NULL(data, "Serialized buffer cannot be null");
 
-  auto hashTable = builder->hashTable();
-  VELOX_CHECK_NOT_NULL(hashTable, "Hash table cannot be null");
+  const auto& table = hashTable.hashTable();
+  VELOX_CHECK_NOT_NULL(table, "Hash table cannot be null");
 
-  auto* hashTableFalse = 
dynamic_cast<facebook::velox::exec::HashTable<false>*>(hashTable.get());
+  auto* hashTableFalse = 
dynamic_cast<facebook::velox::exec::HashTable<false>*>(table.get());
   if (hashTableFalse != nullptr) {
     HashTableSerializer::serializeTo<false>(hashTableFalse, data, size);
     return;
   }
 
-  auto* hashTableTrue = 
dynamic_cast<facebook::velox::exec::HashTable<true>*>(hashTable.get());
+  auto* hashTableTrue = 
dynamic_cast<facebook::velox::exec::HashTable<true>*>(table.get());
   VELOX_CHECK_NOT_NULL(hashTableTrue, "Hash table must be either 
HashTable<false> or HashTable<true>");
   HashTableSerializer::serializeTo<true>(hashTableTrue, data, size);
 }
 
-std::shared_ptr<HashTableBuilder>
+std::shared_ptr<BroadcastHashTable>
 deserializeHashTable(const uint8_t* data, size_t size, bool ignoreNullKeys, 
bool joinHasNullKeys) {
   VELOX_CHECK_NOT_NULL(data, "Serialized data cannot be null");
   VELOX_CHECK_GT(size, 0, "Invalid data size");
 
   auto pool = defaultLeafVeloxMemoryPool();
-  auto* poolPtr = pool.get();
-
-  std::unique_ptr<facebook::velox::exec::BaseHashTable> hashTable;
+  std::shared_ptr<facebook::velox::exec::BaseHashTable> hashTable;
   if (ignoreNullKeys) {
-    auto derived = HashTableSerializer::deserialize<true>(data, size, poolPtr);
-    hashTable = std::move(derived);
+    hashTable = HashTableSerializer::deserialize<true>(data, size, pool.get());
   } else {
-    auto derived = HashTableSerializer::deserialize<false>(data, size, 
poolPtr);
-    hashTable = std::move(derived);
+    hashTable = HashTableSerializer::deserialize<false>(data, size, 
pool.get());
   }
-
-  std::vector<std::shared_ptr<const 
facebook::velox::core::FieldAccessTypedExpr>> emptyKeys;
-  std::vector<uint32_t> emptyChannels;
-
-  auto keyTypes = hashTable->rows()->keyTypes();
-  std::vector<std::string> names;
-  for (size_t i = 0; i < keyTypes.size(); ++i) {
-    names.push_back("key" + std::to_string(i));
-  }
-  auto rowType = facebook::velox::ROW(std::move(names), std::move(keyTypes));
-
-  auto builder = std::make_shared<HashTableBuilder>(
-      facebook::velox::core::JoinType::kInner,
-      false,
-      false,
-      -1,
-      emptyKeys,
-      emptyChannels,
-      false,
-      rowType,
-      poolPtr,
-      1000,
-      1000000,
-      100000,
-      0);
-
-  builder->setHashTable(std::move(hashTable));
-  // Restore the joinHasNullKeys flag
-  builder->setJoinHasNullKeys(joinHasNullKeys);
-  return builder;
+  return std::make_shared<BroadcastHashTable>(std::move(hashTable), 
joinHasNullKeys, 0, std::move(pool));
 }
 
 } // namespace gluten
diff --git a/cpp/velox/jni/JniHashTable.h b/cpp/velox/jni/JniHashTable.h
index 531b8c864a..ed77a48325 100644
--- a/cpp/velox/jni/JniHashTable.h
+++ b/cpp/velox/jni/JniHashTable.h
@@ -17,11 +17,12 @@
 
 #pragma once
 
+#include <folly/Executor.h>
 #include <jni.h>
 #include <optional>
 #include "memory/ColumnarBatch.h"
 #include "memory/VeloxMemoryManager.h"
-#include "operators/hashjoin/HashTableBuilder.h"
+#include "operators/hashjoin/BroadcastHashTable.h"
 #include "utils/ObjectStore.h"
 #include "velox/exec/HashTable.h"
 
@@ -59,6 +60,11 @@ class JniHashTableContext {
   // and the native unit tests, where JNI_OnLoad never runs.
   std::optional<jlong> callJavaGet(const std::string& id) const;
 
+  // Returns the key the JVM side VeloxBroadcastBuildSideCache uses for the 
hash table of
+  // 'hashTableId' in the SQL execution of the current task, or std::nullopt 
when no JVM is
+  // attached to this process.
+  std::optional<std::string> callJavaCacheKey(const std::string& hashTableId) 
const;
+
  private:
   JniHashTableContext() : hashTableObjStore_(ObjectStore::create()) {}
 
@@ -73,10 +79,14 @@ class JniHashTableContext {
   std::unique_ptr<ObjectStore> hashTableObjStore_;
   jclass jniVeloxBroadcastBuildSideCache_{nullptr};
   jmethodID jniGet_{nullptr};
+  jmethodID jniTaskCacheKey_{nullptr};
 };
 
-// Return the hash table builder address.
-std::shared_ptr<HashTableBuilder> nativeHashTableBuild(
+// Builds the hash table by running Velox HashBuild in a dedicated task, see
+// buildHashTableWithTask(). The table is also added to HashTableCache under
+// 'hashTableId'. 'memoryPool' converts 'batches' to Velox vectors.
+std::shared_ptr<BroadcastHashTable> nativeHashTableBuild(
+    const std::string& hashTableId,
     const std::vector<std::string>& joinKeys,
     const std::vector<std::string>& filterBuildColumns,
     bool filterPropagatesNulls,
@@ -92,23 +102,29 @@ std::shared_ptr<HashTableBuilder> nativeHashTableBuild(
     uint32_t abandonHashBuildDedupMinRows,
     uint32_t abandonHashBuildDedupMinPct,
     std::vector<std::shared_ptr<ColumnarBatch>>& batches,
+    uint32_t numThreads,
+    folly::Executor* executor,
+    std::shared_ptr<facebook::velox::memory::MemoryPool> queryPool,
     std::shared_ptr<facebook::velox::memory::MemoryPool> memoryPool);
 
-// Returns the handle of the pre-built hash table registered for the given id, 
or 0 if there is
-// none. Safe to call from a process with no JVM attached, in which case it 
always returns 0.
-long getJoin(const std::string& hashTableId);
+// Returns the cache key of the hash table of the join with 'hashTableId' in 
the SQL execution of
+// the current task. Runs of the same plan share 'hashTableId', so the key 
also names the execution
+// to keep the tables of different runs apart. Returns 'hashTableId' when no 
JVM is attached.
+std::string getJoinCacheKey(const std::string& hashTableId);
 
-// Return the exact serialized hash table size for direct buffer allocation.
-size_t serializedHashTableSize(std::shared_ptr<HashTableBuilder> builder);
+// Returns the handle of the pre-built hash table registered under 'cacheKey', 
see
+// getJoinCacheKey(), or 0 if there is none. Safe to call from a process with 
no JVM attached, in
+// which case it always returns 0.
+long getJoin(const std::string& cacheKey);
 
-// Return retained bytes for the hash table, including parallel-build 
subtables.
-int64_t hashTableMemoryUsage(std::shared_ptr<HashTableBuilder> builder);
+// Return the exact serialized hash table size for direct buffer allocation.
+size_t serializedHashTableSize(const BroadcastHashTable& hashTable);
 
 // Serialize hash table directly to a caller-provided buffer.
-void serializeHashTableTo(std::shared_ptr<HashTableBuilder> builder, uint8_t* 
data, size_t size);
+void serializeHashTableTo(const BroadcastHashTable& hashTable, uint8_t* data, 
size_t size);
 
 // Deserialize hash table from broadcast data with explicit ignoreNullKeys 
parameter
-std::shared_ptr<HashTableBuilder>
+std::shared_ptr<BroadcastHashTable>
 deserializeHashTable(const uint8_t* data, size_t size, bool ignoreNullKeys, 
bool joinHasNullKeys = false);
 
 // Initialize the JNI hash table context
diff --git a/cpp/velox/jni/VeloxJniWrapper.cc b/cpp/velox/jni/VeloxJniWrapper.cc
index 79f19f7383..cebe164bd5 100644
--- a/cpp/velox/jni/VeloxJniWrapper.cc
+++ b/cpp/velox/jni/VeloxJniWrapper.cc
@@ -38,7 +38,7 @@
 #include "memory/AllocationListener.h"
 #include "memory/VeloxColumnarBatch.h"
 #include "memory/VeloxMemoryManager.h"
-#include "operators/hashjoin/HashTableBuilder.h"
+#include "operators/hashjoin/BroadcastHashTable.h"
 #include "shuffle/rss/RssPartitionWriter.h"
 #include "substrait/SubstraitToVeloxPlanValidator.h"
 #include "utils/ObjectStore.h"
@@ -1044,145 +1044,33 @@ JNIEXPORT jlong JNICALL 
Java_org_apache_gluten_vectorized_HashJoinBuilder_native
     cb.push_back(ObjectStore::retrieve<ColumnarBatch>(handle));
   }
 
-  auto* executor = VeloxBackend::get()->broadcastHashTableBuildExecutor();
-  if (numThreads == 1 || executor == nullptr) {
-    // Allocate the hash table from the backend-global memory pool because it 
may outlive the runtime that initiated the
-    // build. Driver-side builds are serialized for broadcast, while 
executor-side builds may be cached and reused
-    // across tasks.
-    auto memoryPool = defaultLeafVeloxMemoryPool();
-
-    auto builder = nativeHashTableBuild(
-        hashJoinKeys,
-        filterColumns,
-        filterPropagatesNulls,
-        names,
-        veloxTypeList,
-        joinType,
-        hasMixedJoinCondition,
-        isExistenceJoin,
-        isNullAwareAntiJoin,
-        bloomFilterPushdownSize,
-        minTableRowsForParallelJoinBuild,
-        joinBuildVectorHasherMaxNumDistinct,
-        abandonHashBuildDedupMinRows,
-        abandonHashBuildDedupMinPct,
-        cb,
-        memoryPool);
-
-    auto mainTable = builder->uniqueTable();
-    mainTable->prepareJoinTable(
-        {},
-        facebook::velox::exec::BaseHashTable::kNoSpillInputStartPartitionBit,
-        builder->joinBuildVectorHasherMaxNumDistinct(),
-        builder->dropDuplicates(),
-        nullptr);
-    builder->setHashTable(std::move(mainTable));
-    builder->setHashTableMemoryUsage(builder->hashTable()->allocatedBytes());
-
-    auto* cache = facebook::velox::exec::HashTableCache::instance();
-
-    if (!cache->exist(hashTableId)) {
-      cache->add(hashTableId, builder->hashTable(), 
builder->joinHasNullKeys(), defaultLeafVeloxMemoryPool());
-    }
-
-    return gluten::getHashTableObjStore()->save(builder);
-  }
-
   // Use a dedicated CPU thread pool for the parallel hash-table build. The 
build is CPU-bound,
   // so it must not run on the io executor which is reserved for async IO 
tasks.
-  std::vector<std::shared_ptr<gluten::HashTableBuilder>> 
hashTableBuilders(numThreads);
-  std::vector<std::unique_ptr<facebook::velox::exec::BaseHashTable>> 
otherTables(numThreads);
-  std::vector<folly::Future<folly::Unit>> futures;
-  futures.reserve(numThreads);
-
-  for (size_t t = 0; t < numThreads; ++t) {
-    size_t start = (handleCount * t) / numThreads;
-    size_t end = (handleCount * (t + 1)) / numThreads;
-
-    // Submit task to thread pool
-    auto future = folly::via(executor, [&, t, start, end]() {
-      std::vector<std::shared_ptr<gluten::ColumnarBatch>> threadBatches;
-      threadBatches.reserve(end - start);
-      for (size_t i = start; i < end; ++i) {
-        threadBatches.push_back(cb[i]);
-      }
-
-      // Allocate the hash table from the backend-global memory pool because 
it may outlive the runtime that initiated
-      // the build. Driver-side builds are serialized for broadcast, while 
executor-side builds may be cached and reused
-      // across tasks.
-      auto threadMemoryPool = defaultLeafVeloxMemoryPool();
-
-      auto builder = nativeHashTableBuild(
-          hashJoinKeys,
-          filterColumns,
-          filterPropagatesNulls,
-          names,
-          veloxTypeList,
-          joinType,
-          hasMixedJoinCondition,
-          isExistenceJoin,
-          isNullAwareAntiJoin,
-          bloomFilterPushdownSize,
-          minTableRowsForParallelJoinBuild,
-          joinBuildVectorHasherMaxNumDistinct,
-          abandonHashBuildDedupMinRows,
-          abandonHashBuildDedupMinPct,
-          threadBatches,
-          threadMemoryPool);
-
-      hashTableBuilders[t] = std::move(builder);
-      otherTables[t] = hashTableBuilders[t]->uniqueTable();
-    });
-
-    futures.push_back(std::move(future));
-  }
-
-  // Wait for all tasks to complete
-  folly::collectAll(futures).wait();
-
-  auto mainTable = std::move(otherTables[0]);
-  std::vector<std::unique_ptr<facebook::velox::exec::BaseHashTable>> tables;
-  for (int i = 1; i < numThreads; ++i) {
-    tables.push_back(std::move(otherTables[i]));
-  }
-  int64_t otherTablesMemoryUsage = 0;
-  for (const auto& table : tables) {
-    otherTablesMemoryUsage += table->allocatedBytes();
-  }
-
-  // TODO: Get accurate signal if parallel join build is going to be applied
-  //  from hash table. Currently there is still a chance inside hash table that
-  //  it might decide it is not going to trigger parallel join build.
-  const bool allowParallelJoinBuild = !tables.empty();
-
-  mainTable->prepareJoinTable(
-      std::move(tables),
-      facebook::velox::exec::BaseHashTable::kNoSpillInputStartPartitionBit,
-      hashTableBuilders[0]->joinBuildVectorHasherMaxNumDistinct(),
-      hashTableBuilders[0]->dropDuplicates(),
-      executor);
-
-  for (int i = 1; i < numThreads; ++i) {
-    if (hashTableBuilders[i]->joinHasNullKeys()) {
-      hashTableBuilders[0]->setJoinHasNullKeys(true);
-      break;
-    }
-  }
-
-  hashTableBuilders[0]->setHashTable(std::move(mainTable));
-  hashTableBuilders[0]->setHashTableMemoryUsage(
-      hashTableBuilders[0]->hashTable()->allocatedBytes() + 
otherTablesMemoryUsage);
-
-  auto* cache = facebook::velox::exec::HashTableCache::instance();
-  if (!cache->exist(hashTableId)) {
-    cache->add(
-        hashTableId,
-        hashTableBuilders[0]->hashTable(),
-        hashTableBuilders[0]->joinHasNullKeys(),
-        defaultLeafVeloxMemoryPool());
-  }
-
-  return gluten::getHashTableObjStore()->save(hashTableBuilders[0]);
+  auto* executor = VeloxBackend::get()->broadcastHashTableBuildExecutor();
+  // The build vectors and the table use global pools: the table outlives the
+  // runtime when it is cached or serialized and broadcast.
+  auto hashTable = nativeHashTableBuild(
+      hashTableId,
+      hashJoinKeys,
+      filterColumns,
+      filterPropagatesNulls,
+      names,
+      veloxTypeList,
+      joinType,
+      hasMixedJoinCondition,
+      isExistenceJoin,
+      isNullAwareAntiJoin,
+      bloomFilterPushdownSize,
+      minTableRowsForParallelJoinBuild,
+      joinBuildVectorHasherMaxNumDistinct,
+      abandonHashBuildDedupMinRows,
+      abandonHashBuildDedupMinPct,
+      cb,
+      executor == nullptr ? 1 : std::max(numThreads, 1),
+      executor,
+      getDefaultMemoryManager()->getAggregateMemoryPool(),
+      defaultLeafVeloxMemoryPool());
+  return gluten::getHashTableObjStore()->save(hashTable);
   JNI_METHOD_END(kInvalidObjectHandle)
 }
 
@@ -1193,14 +1081,13 @@ JNIEXPORT jlong JNICALL 
Java_org_apache_gluten_vectorized_HashJoinBuilder_cloneH
     jlong tableHandler) {
   JNI_METHOD_START
   auto cacheKeyStr = jStringToCString(env, cacheKey);
-  auto hashTableHandler = 
ObjectStore::retrieve<gluten::HashTableBuilder>(tableHandler);
+  auto hashTable = 
ObjectStore::retrieve<gluten::BroadcastHashTable>(tableHandler);
   auto* cache = facebook::velox::exec::HashTableCache::instance();
   if (!cache->exist(cacheKeyStr)) {
-    cache->add(
-        cacheKeyStr, hashTableHandler->hashTable(), 
hashTableHandler->joinHasNullKeys(), defaultLeafVeloxMemoryPool());
+    cache->add(cacheKeyStr, hashTable->hashTable(), 
hashTable->joinHasNullKeys(), defaultLeafVeloxMemoryPool());
   }
 
-  return gluten::getHashTableObjStore()->save(hashTableHandler);
+  return gluten::getHashTableObjStore()->save(hashTable);
   JNI_METHOD_END(kInvalidObjectHandle)
 }
 
@@ -1226,16 +1113,16 @@ JNIEXPORT jlong JNICALL 
Java_org_apache_gluten_vectorized_HashJoinBuilder_deseri
     jboolean joinHasNullKeys) {
   JNI_METHOD_START
   auto cacheKeyStr = jStringToCString(env, cacheKey);
-  auto builder = gluten::deserializeHashTable(
+  auto hashTable = gluten::deserializeHashTable(
       reinterpret_cast<const uint8_t*>(address),
       static_cast<size_t>(size),
       static_cast<bool>(ignoreNullKeys),
       static_cast<bool>(joinHasNullKeys));
   auto* cache = facebook::velox::exec::HashTableCache::instance();
   if (!cache->exist(cacheKeyStr)) {
-    cache->add(cacheKeyStr, builder->hashTable(), builder->joinHasNullKeys(), 
defaultLeafVeloxMemoryPool());
+    cache->add(cacheKeyStr, hashTable->hashTable(), 
hashTable->joinHasNullKeys(), defaultLeafVeloxMemoryPool());
   }
-  return gluten::getHashTableObjStore()->save(builder);
+  return gluten::getHashTableObjStore()->save(hashTable);
   JNI_METHOD_END(kInvalidObjectHandle)
 }
 
@@ -1244,8 +1131,7 @@ JNIEXPORT jboolean JNICALL 
Java_org_apache_gluten_vectorized_HashJoinBuilder_get
     jclass,
     jlong hashTableHandle) {
   JNI_METHOD_START
-  auto builder = 
ObjectStore::retrieve<gluten::HashTableBuilder>(hashTableHandle);
-  auto hashTable = builder->hashTable();
+  const auto& hashTable = 
ObjectStore::retrieve<gluten::BroadcastHashTable>(hashTableHandle)->hashTable();
   VELOX_CHECK_NOT_NULL(hashTable, "Hash table cannot be null");
   return 
static_cast<jboolean>(dynamic_cast<facebook::velox::exec::HashTable<true>*>(hashTable.get())
 != nullptr);
   JNI_METHOD_END(false)
@@ -1256,8 +1142,8 @@ JNIEXPORT jboolean JNICALL 
Java_org_apache_gluten_vectorized_HashJoinBuilder_get
     jclass,
     jlong hashTableHandle) {
   JNI_METHOD_START
-  auto builder = 
ObjectStore::retrieve<gluten::HashTableBuilder>(hashTableHandle);
-  return static_cast<jboolean>(builder->joinHasNullKeys());
+  auto hashTable = 
ObjectStore::retrieve<gluten::BroadcastHashTable>(hashTableHandle);
+  return static_cast<jboolean>(hashTable->joinHasNullKeys());
   JNI_METHOD_END(false)
 }
 
@@ -1267,8 +1153,7 @@ 
Java_org_apache_gluten_vectorized_HashJoinBuilder_getHashTableBloomFilterBlocksB
     jclass,
     jlong hashTableHandle) {
   JNI_METHOD_START
-  auto builder = 
ObjectStore::retrieve<gluten::HashTableBuilder>(hashTableHandle);
-  auto hashTable = builder->hashTable();
+  const auto& hashTable = 
ObjectStore::retrieve<gluten::BroadcastHashTable>(hashTableHandle)->hashTable();
   VELOX_CHECK_NOT_NULL(hashTable, "Hash table cannot be null");
 
   auto* baseTable = 
dynamic_cast<facebook::velox::exec::BaseHashTable*>(hashTable.get());
@@ -1294,8 +1179,8 @@ JNIEXPORT jlong JNICALL 
Java_org_apache_gluten_vectorized_HashJoinBuilder_getHas
     jclass,
     jlong hashTableHandle) {
   JNI_METHOD_START
-  auto builder = 
ObjectStore::retrieve<gluten::HashTableBuilder>(hashTableHandle);
-  return static_cast<jlong>(gluten::hashTableMemoryUsage(builder));
+  auto hashTable = 
ObjectStore::retrieve<gluten::BroadcastHashTable>(hashTableHandle);
+  return static_cast<jlong>(hashTable->memoryUsage());
   JNI_METHOD_END(0L)
 }
 
@@ -1304,8 +1189,8 @@ JNIEXPORT jlong JNICALL 
Java_org_apache_gluten_vectorized_HashJoinBuilder_serial
     jclass,
     jlong hashTableHandle) {
   JNI_METHOD_START
-  auto builder = 
ObjectStore::retrieve<gluten::HashTableBuilder>(hashTableHandle);
-  return static_cast<jlong>(gluten::serializedHashTableSize(builder));
+  auto hashTable = 
ObjectStore::retrieve<gluten::BroadcastHashTable>(hashTableHandle);
+  return static_cast<jlong>(gluten::serializedHashTableSize(*hashTable));
   JNI_METHOD_END(0L)
 }
 
@@ -1316,12 +1201,12 @@ JNIEXPORT void JNICALL 
Java_org_apache_gluten_vectorized_HashJoinBuilder_seriali
     jlong address,
     jlong size) {
   JNI_METHOD_START
-  auto builder = 
ObjectStore::retrieve<gluten::HashTableBuilder>(hashTableHandle);
+  auto hashTable = 
ObjectStore::retrieve<gluten::BroadcastHashTable>(hashTableHandle);
   VELOX_CHECK_GT(address, 0, "Serialized hash table buffer address must be 
positive");
   VELOX_CHECK_GE(size, 0, "Serialized hash table buffer size must be 
non-negative");
-  const auto serializedSize = gluten::serializedHashTableSize(builder);
+  const auto serializedSize = gluten::serializedHashTableSize(*hashTable);
   VELOX_CHECK_EQ(static_cast<size_t>(size), serializedSize, "Hash table buffer 
size mismatch");
-  gluten::serializeHashTableTo(builder, reinterpret_cast<uint8_t*>(address), 
serializedSize);
+  gluten::serializeHashTableTo(*hashTable, 
reinterpret_cast<uint8_t*>(address), serializedSize);
   JNI_METHOD_END()
 }
 
diff --git a/cpp/velox/operators/hashjoin/BroadcastHashTable.h 
b/cpp/velox/operators/hashjoin/BroadcastHashTable.h
new file mode 100644
index 0000000000..e4a581b3ae
--- /dev/null
+++ b/cpp/velox/operators/hashjoin/BroadcastHashTable.h
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+
+#include "velox/exec/HashTable.h"
+
+namespace gluten {
+
+/// The hash table of a broadcast hash join, as handed to Java through an
+/// ObjectStore handle.
+class BroadcastHashTable {
+ public:
+  /// 'owner' is kept alive as long as this, e.g. the QueryCtx of the task that
+  /// built 'table'.
+  BroadcastHashTable(
+      std::shared_ptr<facebook::velox::exec::BaseHashTable> table,
+      bool joinHasNullKeys,
+      int64_t memoryUsage,
+      std::shared_ptr<void> owner = nullptr)
+      : owner_(std::move(owner)),
+        table_(std::move(table)),
+        joinHasNullKeys_(joinHasNullKeys),
+        memoryUsage_(memoryUsage) {}
+
+  const std::shared_ptr<facebook::velox::exec::BaseHashTable>& hashTable() 
const {
+    return table_;
+  }
+
+  bool joinHasNullKeys() const {
+    return joinHasNullKeys_;
+  }
+
+  /// Retained bytes of the table, including the tables merged by a parallel
+  /// build.
+  int64_t memoryUsage() const {
+    return memoryUsage_;
+  }
+
+ private:
+  // Declared before 'table_' so that it is released after it.
+  const std::shared_ptr<void> owner_;
+  const std::shared_ptr<facebook::velox::exec::BaseHashTable> table_;
+  const bool joinHasNullKeys_;
+  const int64_t memoryUsage_;
+};
+
+} // namespace gluten
diff --git a/cpp/velox/operators/hashjoin/HashTableBuilder.cc 
b/cpp/velox/operators/hashjoin/HashTableBuilder.cc
deleted file mode 100644
index 676b3b65d2..0000000000
--- a/cpp/velox/operators/hashjoin/HashTableBuilder.cc
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * 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.
- */
-
-#include "operators/hashjoin/HashTableBuilder.h"
-
-#include <algorithm>
-
-#include <iostream>
-
-#include "velox/exec/OperatorUtils.h"
-
-namespace gluten {
-
-HashTableBuilder::HashTableBuilder(
-    facebook::velox::core::JoinType joinType,
-    bool nullAware,
-    bool withFilter,
-    int64_t bloomFilterPushdownSize,
-    const std::vector<facebook::velox::core::FieldAccessTypedExprPtr>& 
joinKeys,
-    const std::vector<column_index_t>& filterInputChannels,
-    bool filterPropagatesNulls,
-    const facebook::velox::RowTypePtr& inputType,
-    facebook::velox::memory::MemoryPool* pool,
-    uint32_t minTableRowsForParallelJoinBuild,
-    uint32_t joinBuildVectorHasherMaxNumDistinct,
-    uint32_t abandonHashBuildDedupMinRows,
-    uint32_t abandonHashBuildDedupMinPct)
-    : joinType_{joinType},
-      nullAware_{nullAware},
-      withFilter_(withFilter),
-      keyChannelMap_(joinKeys.size()),
-      inputType_(inputType),
-      bloomFilterPushdownSize_(bloomFilterPushdownSize),
-      pool_(pool),
-      minTableRowsForParallelJoinBuild_(minTableRowsForParallelJoinBuild),
-      
joinBuildVectorHasherMaxNumDistinct_(joinBuildVectorHasherMaxNumDistinct),
-      abandonHashBuildDedupMinRows_(abandonHashBuildDedupMinRows),
-      abandonHashBuildDedupMinPct_(abandonHashBuildDedupMinPct),
-      filterPropagatesNulls_(filterPropagatesNulls) {
-  dropDuplicates_ =
-      !withFilter_ && (isLeftSemiFilterJoin(joinType_) || 
isLeftSemiProjectJoin(joinType_) || isAntiJoin(joinType_));
-  const auto numKeys = joinKeys.size();
-  keyChannels_.reserve(numKeys);
-
-  for (int i = 0; i < numKeys; ++i) {
-    auto& key = joinKeys[i];
-    auto channel = facebook::velox::exec::exprToChannel(key.get(), inputType_);
-    keyChannelMap_[channel] = i;
-    keyChannels_.emplace_back(channel);
-  }
-
-  // Identify the non-key build side columns and make a decoder for each.
-  if (!dropDuplicates_) {
-    const int32_t numDependents = inputType_->size() - numKeys;
-    if (numDependents > 0) {
-      // Number of join keys (numKeys) may be less then number of input columns
-      // (inputType->size()). In this case numDependents is negative and cannot
-      // be used to call 'reserve'. This happens when we join different probe
-      // side keys with the same build side key: SELECT * FROM t LEFT JOIN u ON
-      // t.k1 = u.k AND t.k2 = u.k.
-      dependentChannels_.reserve(numDependents);
-      decoders_.reserve(numDependents);
-    }
-    for (auto i = 0; i < inputType->size(); ++i) {
-      if (keyChannelMap_.find(i) == keyChannelMap_.end()) {
-        dependentChannels_.emplace_back(i);
-        
decoders_.emplace_back(std::make_unique<facebook::velox::DecodedVector>());
-      }
-    }
-  }
-
-  tableType_ = facebook::velox::exec::hashJoinTableType(joinKeys, inputType, 
dropDuplicates_);
-  setupTable();
-
-  if (isAntiJoin(joinType_) && withFilter_ && filterPropagatesNulls_) {
-    setupFilterForAntiJoins(filterInputChannels);
-  }
-}
-
-void HashTableBuilder::setupFilterForAntiJoins(const 
std::vector<column_index_t>& filterInputChannels) {
-  VELOX_DCHECK(std::is_sorted(dependentChannels_.begin(), 
dependentChannels_.end()));
-
-  for (auto channel : filterInputChannels) {
-    auto keyIter = keyChannelMap_.find(channel);
-    if (keyIter != keyChannelMap_.end()) {
-      keyFilterChannels_.push_back(keyIter->second);
-      continue;
-    }
-
-    auto dependentIter = std::lower_bound(dependentChannels_.begin(), 
dependentChannels_.end(), channel);
-    if (dependentIter == dependentChannels_.end() || *dependentIter != 
channel) {
-      continue;
-    }
-    dependentFilterChannels_.push_back(dependentIter - 
dependentChannels_.begin());
-  }
-}
-
-void HashTableBuilder::removeInputRowsForAntiJoinFilter() {
-  bool changed = false;
-  auto* rawActiveRows = activeRows_.asMutableRange().bits();
-
-  auto removeNulls = [&](facebook::velox::DecodedVector& decoded) {
-    if (decoded.mayHaveNulls()) {
-      changed = true;
-      facebook::velox::bits::andBits(rawActiveRows, 
decoded.nulls(&activeRows_), 0, activeRows_.end());
-    }
-  };
-
-  for (auto channel : keyFilterChannels_) {
-    removeNulls(uniqueTable_->hashers()[channel]->decodedVector());
-  }
-  for (auto channel : dependentFilterChannels_) {
-    removeNulls(*decoders_[channel]);
-  }
-
-  if (changed) {
-    activeRows_.updateBounds();
-  }
-}
-
-bool HashTableBuilder::abandonHashBuildDedupEarly(int64_t numDistinct) const {
-  VELOX_CHECK(dropDuplicates_);
-  return numHashInputRows_ > abandonHashBuildDedupMinRows_ &&
-      (100 * numDistinct / numHashInputRows_) >= abandonHashBuildDedupMinPct_;
-}
-
-void HashTableBuilder::abandonHashBuildDedup() {
-  abandonHashBuildDedup_ = true;
-
-  if (!dropDuplicates_) {
-    uniqueTable_->setAllowDuplicates(true);
-  }
-  lookup_.reset();
-}
-
-// Invoked to set up hash table to build.
-void HashTableBuilder::setupTable() {
-  VELOX_CHECK_NULL(uniqueTable_);
-
-  const auto numKeys = keyChannels_.size();
-  std::vector<std::unique_ptr<facebook::velox::exec::VectorHasher>> keyHashers;
-  keyHashers.reserve(numKeys);
-  for (vector_size_t i = 0; i < numKeys; ++i) {
-    
keyHashers.emplace_back(facebook::velox::exec::VectorHasher::create(tableType_->childAt(i),
 keyChannels_[i]));
-  }
-
-  const auto numDependents = tableType_->size() - numKeys;
-  std::vector<facebook::velox::TypePtr> dependentTypes;
-  dependentTypes.reserve(numDependents);
-  for (int i = numKeys; i < tableType_->size(); ++i) {
-    dependentTypes.emplace_back(tableType_->childAt(i));
-  }
-  facebook::velox::exec::BaseHashTable::Options options;
-  options.minTableSizeForParallelJoinBuild = minTableRowsForParallelJoinBuild_;
-  if (isRightJoin(joinType_) || isFullJoin(joinType_) || 
isRightSemiProjectJoin(joinType_)) {
-    // Do not ignore null keys.
-    options.allowDuplicates = true;
-    options.hasProbedFlag = true;
-    options.hasCountFlag = false;
-    uniqueTable_ =
-        
facebook::velox::exec::HashTable<false>::createForJoin(std::move(keyHashers), 
dependentTypes, pool_, options);
-  } else {
-    // Right semi join needs to tag build rows that were probed.
-    options.allowDuplicates = !dropDuplicates_;
-    options.hasProbedFlag = isRightSemiFilterJoin(joinType_);
-    options.hasCountFlag = facebook::velox::core::isCountingJoin(joinType_);
-    if (facebook::velox::exec::isLeftNullAwareJoinWithFilter(joinType_, 
nullAware_, withFilter_)) {
-      // We need to check null key rows in build side in case of null-aware 
anti
-      // or left semi project join with filter set.
-      uniqueTable_ =
-          
facebook::velox::exec::HashTable<false>::createForJoin(std::move(keyHashers), 
dependentTypes, pool_, options);
-    } else {
-      // Ignore null keys
-      options.bloomFilterMaxSize = 
static_cast<uint64_t>(bloomFilterPushdownSize_);
-      uniqueTable_ =
-          
facebook::velox::exec::HashTable<true>::createForJoin(std::move(keyHashers), 
dependentTypes, pool_, options);
-    }
-  }
-  analyzeKeys_ = uniqueTable_->hashMode() != 
facebook::velox::exec::BaseHashTable::HashMode::kHash;
-
-  if (dropDuplicates_) {
-    if (!facebook::velox::core::isCountingJoin(joinType_) && 
abandonHashBuildDedupMinPct_ == 0) {
-      abandonHashBuildDedup();
-      return;
-    }
-    lookup_ = 
std::make_unique<facebook::velox::exec::HashLookup>(uniqueTable_->hashers(), 
pool_);
-  }
-}
-
-void HashTableBuilder::addInput(facebook::velox::RowVectorPtr input) {
-  activeRows_.resize(input->size());
-  activeRows_.setAll();
-
-  auto& hashers = uniqueTable_->hashers();
-
-  for (auto i = 0; i < hashers.size(); ++i) {
-    auto key = input->childAt(hashers[i]->channel())->loadedVector();
-    hashers[i]->decode(*key, activeRows_);
-  }
-
-  if (!isRightJoin(joinType_) && !isFullJoin(joinType_) && 
!isRightSemiProjectJoin(joinType_) &&
-      !facebook::velox::exec::isLeftNullAwareJoinWithFilter(joinType_, 
nullAware_, withFilter_)) {
-    deselectRowsWithNulls(hashers, activeRows_);
-    if (nullAware_ && !joinHasNullKeys_ && activeRows_.countSelected() < 
input->size()) {
-      joinHasNullKeys_ = true;
-    }
-  } else if (nullAware_ && !joinHasNullKeys_) {
-    for (auto& hasher : hashers) {
-      auto& decoded = hasher->decodedVector();
-      if (decoded.mayHaveNulls()) {
-        auto* nulls = decoded.nulls(&activeRows_);
-        if (nulls && facebook::velox::bits::countNulls(nulls, 0, 
activeRows_.end()) > 0) {
-          joinHasNullKeys_ = true;
-          break;
-        }
-      }
-    }
-  }
-
-  if (isAntiJoin(joinType_) && nullAware_ && joinHasNullKeys_ && !withFilter_) 
{
-    noMoreInput_ = true;
-    return;
-  }
-
-  if (!activeRows_.hasSelections()) {
-    return;
-  }
-
-  if (dropDuplicates_ && !abandonHashBuildDedup_) {
-    // Counting joins must not abandon dedup — accurate counts are required.
-    VELOX_CHECK_NOT_NULL(lookup_);
-    const bool abandonEarly =
-        !facebook::velox::core::isCountingJoin(joinType_) && 
abandonHashBuildDedupEarly(uniqueTable_->numDistinct());
-    if (!abandonEarly) {
-      numHashInputRows_ += activeRows_.countSelected();
-      uniqueTable_->prepareForGroupProbe(
-          *lookup_, input, activeRows_, 
facebook::velox::exec::BaseHashTable::kNoSpillInputStartPartitionBit);
-      if (lookup_->rows.empty()) {
-        return;
-      }
-      uniqueTable_->groupProbe(*lookup_, 
facebook::velox::exec::BaseHashTable::kNoSpillInputStartPartitionBit);
-
-      // For counting joins, increment the count for duplicate rows.
-      // New rows are initialized with count = 1 by initializeRow.
-      // Increment count for all rows, then decrement for new rows to
-      // correct the over-counting.
-      if (facebook::velox::core::isCountingJoin(joinType_)) {
-        auto* rows = uniqueTable_->rows();
-        for (auto row : lookup_->rows) {
-          rows->incrementCount(lookup_->hits[row]);
-        }
-        for (auto newRow : lookup_->newGroups) {
-          rows->decrementCount(lookup_->hits[newRow]);
-        }
-      }
-      return;
-    }
-    abandonHashBuildDedup();
-  }
-
-  for (auto i = 0; i < dependentChannels_.size(); ++i) {
-    
decoders_[i]->decode(*input->childAt(dependentChannels_[i])->loadedVector(), 
activeRows_);
-  }
-
-  if (isAntiJoin(joinType_) && withFilter_ && filterPropagatesNulls_) {
-    removeInputRowsForAntiJoinFilter();
-  }
-
-  if (!activeRows_.hasSelections()) {
-    return;
-  }
-
-  if (analyzeKeys_ && hashes_.size() < activeRows_.end()) {
-    hashes_.resize(activeRows_.end());
-  }
-
-  // As long as analyzeKeys is true, we keep running the keys through
-  // the Vectorhashers so that we get a possible mapping of the keys
-  // to small ints for array or normalized key. When mayUseValueIds is
-  // false for the first time we stop. We do not retain the value ids
-  // since the final ones will only be known after all data is
-  // received.
-  for (auto& hasher : hashers) {
-    // TODO: Load only for active rows, except if right/full outer join.
-    if (analyzeKeys_) {
-      hasher->computeValueIds(activeRows_, hashes_);
-      analyzeKeys_ = hasher->mayUseValueIds();
-    }
-  }
-  auto rows = uniqueTable_->rows();
-  auto nextOffset = rows->nextOffset();
-
-  activeRows_.applyToSelected([&](auto rowIndex) {
-    char* newRow = rows->newRow();
-    if (nextOffset) {
-      *reinterpret_cast<char**>(newRow + nextOffset) = nullptr;
-    }
-    // Store the columns for each row in sequence. At probe time
-    // strings of the row will probably be in consecutive places, so
-    // reading one will prime the cache for the next.
-    for (auto i = 0; i < hashers.size(); ++i) {
-      rows->store(hashers[i]->decodedVector(), rowIndex, newRow, i);
-    }
-    for (auto i = 0; i < dependentChannels_.size(); ++i) {
-      rows->store(*decoders_[i], rowIndex, newRow, i + hashers.size());
-    }
-  });
-}
-
-} // namespace gluten
diff --git a/cpp/velox/operators/hashjoin/HashTableBuilder.h 
b/cpp/velox/operators/hashjoin/HashTableBuilder.h
deleted file mode 100644
index 44769e7490..0000000000
--- a/cpp/velox/operators/hashjoin/HashTableBuilder.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * 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.
- */
-
-#pragma once
-
-#include <cstdint>
-#include <thread>
-#include "velox/exec/HashJoinBridge.h"
-#include "velox/exec/HashTable.h"
-#include "velox/exec/RowContainer.h"
-#include "velox/exec/VectorHasher.h"
-
-namespace gluten {
-using column_index_t = uint32_t;
-using vector_size_t = int32_t;
-
-class HashTableBuilder {
- public:
-  HashTableBuilder(
-      facebook::velox::core::JoinType joinType,
-      bool nullAware,
-      bool withFilter,
-      int64_t bloomFilterPushdownSize,
-      const std::vector<facebook::velox::core::FieldAccessTypedExprPtr>& 
joinKeys,
-      const std::vector<column_index_t>& filterInputChannels,
-      bool filterPropagatesNulls,
-      const facebook::velox::RowTypePtr& inputType,
-      facebook::velox::memory::MemoryPool* pool,
-      uint32_t minTableRowsForParallelJoinBuild,
-      uint32_t joinBuildVectorHasherMaxNumDistinct,
-      uint32_t abandonHashBuildDedupMinRows,
-      uint32_t abandonHashBuildDedupMinPct);
-
-  void addInput(facebook::velox::RowVectorPtr input);
-
-  void setHashTable(std::unique_ptr<facebook::velox::exec::BaseHashTable> 
uniqueHashTable) {
-    table_ = std::move(uniqueHashTable);
-  }
-
-  std::unique_ptr<facebook::velox::exec::BaseHashTable> uniqueTable() {
-    lookup_.reset();
-    return std::move(uniqueTable_);
-  }
-
-  std::shared_ptr<facebook::velox::exec::BaseHashTable> hashTable() {
-    return table_;
-  }
-  void setJoinHasNullKeys(bool joinHasNullKeys) {
-    joinHasNullKeys_ = joinHasNullKeys;
-  }
-
-  bool joinHasNullKeys() {
-    return joinHasNullKeys_;
-  }
-
-  bool dropDuplicates() {
-    return dropDuplicates_;
-  }
-
-  bool noMoreInput() const {
-    return noMoreInput_;
-  }
-
-  void setHashTableMemoryUsage(int64_t hashTableMemoryUsage) {
-    hashTableMemoryUsage_ = hashTableMemoryUsage;
-  }
-
-  int64_t hashTableMemoryUsage() const {
-    return hashTableMemoryUsage_;
-  }
-
-  uint32_t joinBuildVectorHasherMaxNumDistinct() const {
-    return joinBuildVectorHasherMaxNumDistinct_;
-  }
-
- private:
-  // Invoked to set up hash table to build.
-  void setupTable();
-
-  void setupFilterForAntiJoins(const std::vector<column_index_t>& 
filterInputChannels);
-  void removeInputRowsForAntiJoinFilter();
-
-  bool abandonHashBuildDedupEarly(int64_t numDistinct) const;
-  void abandonHashBuildDedup();
-
-  const facebook::velox::core::JoinType joinType_;
-
-  const bool nullAware_;
-  const bool withFilter_;
-
-  // The row type used for hash table build and disk spilling.
-  facebook::velox::RowTypePtr tableType_;
-
-  // Container for the rows being accumulated.
-  std::shared_ptr<facebook::velox::exec::BaseHashTable> table_;
-
-  std::unique_ptr<facebook::velox::exec::BaseHashTable> uniqueTable_;
-
-  // Key channels in 'input_'
-  std::vector<column_index_t> keyChannels_;
-
-  // Non-key channels in 'input_'.
-  std::vector<column_index_t> dependentChannels_;
-
-  // Corresponds 1:1 to 'dependentChannels_'.
-  std::vector<std::unique_ptr<facebook::velox::DecodedVector>> decoders_;
-
-  // True if we are considering use of normalized keys or array hash tables.
-  // Set to false when the dataset is no longer suitable.
-  bool analyzeKeys_;
-
-  // Temporary space for hash numbers.
-  facebook::velox::raw_vector<uint64_t> hashes_;
-
-  // Set of active rows during addInput().
-  facebook::velox::SelectivityVector activeRows_;
-
-  std::unique_ptr<facebook::velox::exec::HashLookup> lookup_;
-
-  // True if this is a build side of an anti or left semi project join and has
-  // at least one entry with null join keys.
-  bool joinHasNullKeys_{false};
-
-  // Indices of key columns used by the filter in build side table.
-  std::vector<column_index_t> keyFilterChannels_;
-  // Indices of dependent columns used by the filter in 'decoders_'.
-  std::vector<column_index_t> dependentFilterChannels_;
-
-  // Maps key channel in 'input_' to channel in key.
-  folly::F14FastMap<column_index_t, column_index_t> keyChannelMap_;
-
-  const facebook::velox::RowTypePtr& inputType_;
-
-  int64_t bloomFilterPushdownSize_;
-
-  facebook::velox::memory::MemoryPool* pool_;
-
-  bool dropDuplicates_{false};
-  bool abandonHashBuildDedup_{false};
-  bool noMoreInput_{false};
-  uint64_t numHashInputRows_{0};
-  uint32_t minTableRowsForParallelJoinBuild_{1'000};
-  uint32_t joinBuildVectorHasherMaxNumDistinct_{1'000'000};
-  uint32_t abandonHashBuildDedupMinRows_{100'000};
-  uint32_t abandonHashBuildDedupMinPct_{0};
-  bool filterPropagatesNulls_{false};
-  int64_t hashTableMemoryUsage_{0};
-};
-
-} // namespace gluten
diff --git a/cpp/velox/operators/hashjoin/HashTableTaskBuilder.cc 
b/cpp/velox/operators/hashjoin/HashTableTaskBuilder.cc
new file mode 100644
index 0000000000..5e83d9e9eb
--- /dev/null
+++ b/cpp/velox/operators/hashjoin/HashTableTaskBuilder.cc
@@ -0,0 +1,256 @@
+/*
+ * 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.
+ */
+
+#include "operators/hashjoin/HashTableTaskBuilder.h"
+
+#include <fmt/format.h>
+
+#include <atomic>
+
+#include "velox/exec/HashTableCache.h"
+#include "velox/exec/RoundRobinPartitionFunction.h"
+#include "velox/exec/Task.h"
+
+using namespace facebook::velox;
+
+namespace gluten {
+namespace {
+
+// Output type of the fake join. The probe side is empty, so the join outputs
+// nothing and needs no columns, except the match column of a semi project 
join.
+RowTypePtr fakeJoinOutputType(core::JoinType joinType) {
+  if (core::isLeftSemiProjectJoin(joinType) || 
core::isRightSemiProjectJoin(joinType)) {
+    return ROW({"__fake_match"}, {BOOLEAN()});
+  }
+  return ROW({}, {});
+}
+
+// A stand-in for the join filter with the properties HashBuild looks at, see
+// HashTableTaskBuildSpec. It is compiled by HashProbe but never evaluated.
+core::TypedExprPtr makePlaceholderFilter(const HashTableTaskBuildSpec& spec) {
+  if (!spec.withFilter) {
+    return nullptr;
+  }
+  if (!spec.filterPropagatesNulls || spec.filterBuildColumns.empty()) {
+    // References no build column, so HashBuild drops no build rows for it.
+    return std::make_shared<core::ConstantTypedExpr>(BOOLEAN(), Variant(true));
+  }
+  // Chains the build columns, cast to VARCHAR to fit any type, with equalto.
+  // Both have default null behavior, so the result is null-intolerant in each
+  // of them.
+  auto toVarchar = [&](const core::TypedExprPtr& expr) -> core::TypedExprPtr {
+    return std::make_shared<core::CastTypedExpr>(VARCHAR(), expr, false);
+  };
+  auto column = [&](const std::string& name) -> core::TypedExprPtr {
+    return 
toVarchar(std::make_shared<core::FieldAccessTypedExpr>(spec.buildType->findChild(name),
 name));
+  };
+  auto equalTo = [](const core::TypedExprPtr& left, const core::TypedExprPtr& 
right) -> core::TypedExprPtr {
+    return std::make_shared<core::CallTypedExpr>(BOOLEAN(), 
std::vector<core::TypedExprPtr>{left, right}, "equalto");
+  };
+  auto filter = equalTo(column(spec.filterBuildColumns[0]), 
column(spec.filterBuildColumns[0]));
+  for (size_t i = 1; i < spec.filterBuildColumns.size(); ++i) {
+    filter = equalTo(toVarchar(filter), column(spec.filterBuildColumns[i]));
+  }
+  return filter;
+}
+
+// An empty join table with the join keys of 'spec'.
+std::shared_ptr<exec::BaseHashTable> makeEmptyJoinTable(const 
HashTableTaskBuildSpec& spec, memory::MemoryPool* pool) {
+  std::vector<std::unique_ptr<exec::VectorHasher>> hashers;
+  for (const auto& key : spec.joinKeys) {
+    const auto channel = spec.buildType->getChildIdx(key);
+    
hashers.emplace_back(std::make_unique<exec::VectorHasher>(spec.buildType->childAt(channel),
 channel));
+  }
+  exec::BaseHashTable::Options options;
+  options.minTableSizeForParallelJoinBuild = 1'000;
+  options.allowDuplicates = true;
+  options.hasProbedFlag = false;
+  options.hasCountFlag = false;
+  auto table = exec::HashTable<false>::createForJoin(std::move(hashers), {}, 
pool, options);
+  table->prepareJoinTable({}, 
exec::BaseHashTable::kNoSpillInputStartPartitionBit, 1'000'000, false, nullptr);
+  return table;
+}
+
+std::string nextBuildId() {
+  static std::atomic<uint64_t> id{0};
+  return std::to_string(id++);
+}
+
+// A table and the pool it is allocated from. Members are destroyed in reverse
+// order, so 'table' returns its memory before 'pool' goes.
+struct TableWithPool {
+  std::shared_ptr<memory::MemoryPool> pool;
+  std::shared_ptr<exec::BaseHashTable> table;
+};
+
+} // namespace
+
+std::shared_ptr<BroadcastHashTable> buildHashTableWithTask(
+    const std::string& cacheKey,
+    const HashTableTaskBuildSpec& spec,
+    const std::vector<RowVectorPtr>& buildVectors,
+    uint32_t numDrivers,
+    folly::Executor* executor,
+    std::shared_ptr<memory::MemoryPool> queryPool,
+    memory::MemoryPool* vectorPool) {
+  VELOX_CHECK_GT(numDrivers, 0);
+  VELOX_CHECK(numDrivers == 1 || executor != nullptr, "Parallel hash table 
build requires an executor");
+  const auto buildId = nextBuildId();
+  auto queryCtx = core::QueryCtx::create(
+      numDrivers > 1 ? executor : nullptr,
+      core::QueryConfig(spec.queryConfigs),
+      {},
+      nullptr,
+      std::move(queryPool),
+      nullptr,
+      fmt::format("Gluten_HashTableBuild_{}_{}", cacheKey, buildId));
+
+  // Probe side: an empty input with one column per join key.
+  std::vector<std::string> probeNames;
+  std::vector<TypePtr> probeTypes;
+  std::vector<core::FieldAccessTypedExprPtr> leftKeys;
+  std::vector<core::FieldAccessTypedExprPtr> rightKeys;
+  for (size_t i = 0; i < spec.joinKeys.size(); ++i) {
+    const auto& type = spec.buildType->findChild(spec.joinKeys[i]);
+    probeNames.emplace_back(fmt::format("__fake_probe_k{}", i));
+    probeTypes.emplace_back(type);
+    leftKeys.emplace_back(std::make_shared<core::FieldAccessTypedExpr>(type, 
probeNames.back()));
+    rightKeys.emplace_back(std::make_shared<core::FieldAccessTypedExpr>(type, 
spec.joinKeys[i]));
+  }
+  auto probeType = ROW(std::move(probeNames), std::move(probeTypes));
+
+  int planNodeId = 0;
+  auto nextPlanNodeId = [&]() { return std::to_string(planNodeId++); };
+  core::PlanNodePtr probe = std::make_shared<core::ValuesNode>(
+      nextPlanNodeId(), 
std::vector<RowVectorPtr>{BaseVector::create<RowVector>(probeType, 0, 
vectorPool)});
+
+  // Build side: the broadcast vectors, renamed to 'buildType'.
+  std::vector<RowVectorPtr> values;
+  values.reserve(buildVectors.size());
+  for (const auto& vector : buildVectors) {
+    values.emplace_back(std::make_shared<RowVector>(
+        vector->pool(), spec.buildType, vector->nulls(), vector->size(), 
vector->children()));
+  }
+  if (values.empty()) {
+    values.emplace_back(BaseVector::create<RowVector>(spec.buildType, 0, 
vectorPool));
+  }
+  core::PlanNodePtr build = 
std::make_shared<core::ValuesNode>(nextPlanNodeId(), std::move(values));
+  if (numDrivers > 1) {
+    // Distribute the broadcast vectors across all HashBuild drivers.
+    build = std::make_shared<core::LocalPartitionNode>(
+        nextPlanNodeId(),
+        core::LocalPartitionNode::Type::kRepartition,
+        false,
+        std::make_shared<exec::RoundRobinPartitionFunctionSpec>(),
+        std::vector<core::PlanNodePtr>{build});
+  }
+
+  auto joinNode = core::HashJoinNode::Builder()
+                      .id(nextPlanNodeId())
+                      .joinType(spec.joinType)
+                      .leftKeys(std::move(leftKeys))
+                      .rightKeys(std::move(rightKeys))
+                      .filter(makePlaceholderFilter(spec))
+                      .left(probe)
+                      .right(build)
+                      .outputType(fakeJoinOutputType(spec.joinType))
+                      .nullAware(spec.nullAware)
+                      .useHashTableCache(true)
+                      .cacheKey(cacheKey)
+                      .build();
+
+  std::shared_ptr<exec::Task> task;
+  if (numDrivers == 1) {
+    task = exec::Task::create(
+        queryCtx->queryId(), core::PlanFragment{joinNode}, 0, queryCtx, 
exec::Task::ExecutionMode::kSerial);
+    while (true) {
+      ContinueFuture future = ContinueFuture::makeEmpty();
+      if (task->next(&future) == nullptr) {
+        if (!future.valid()) {
+          break;
+        }
+        future.wait();
+      }
+    }
+  } else {
+    task = exec::Task::create(
+        queryCtx->queryId(),
+        core::PlanFragment{joinNode},
+        0,
+        queryCtx,
+        exec::Task::ExecutionMode::kParallel,
+        [](RowVectorPtr, bool, ContinueFuture*) { return 
exec::BlockingReason::kNotBlocked; });
+    task->start(numDrivers);
+    task->taskCompletionFuture().wait();
+  }
+  if (task->state() != exec::TaskState::kFinished) {
+    if (auto error = task->error()) {
+      std::rethrow_exception(error);
+    }
+    VELOX_FAIL("Hash table build task {} ended in state {}", task->taskId(), 
exec::taskStateString(task->state()));
+  }
+  // Drivers can hold the task, and so the QueryCtx, briefly after it finishes.
+  // Wait for the task to go, so that releasing the returned table releases the
+  // QueryCtx and with it the cache entry.
+  const auto taskId = task->taskId();
+  auto taskDeleted = task->taskDeletionFuture();
+  task.reset();
+  taskDeleted.wait();
+
+  auto* cache = exec::HashTableCache::instance();
+  if (!cache->exist(cacheKey)) {
+    // HashBuild does not cache the table of a null-aware anti join without
+    // filter whose build side has a null key. Such a join returns nothing
+    // whatever the table holds, so cache an empty table flagged with null 
keys.
+    VELOX_CHECK(
+        core::isAntiJoin(spec.joinType) && spec.nullAware && !spec.withFilter,
+        "Hash table build task did not cache table {}",
+        cacheKey);
+    auto tablePool = 
queryCtx->pool()->addLeafChild(fmt::format("hash_table_build_empty_{}", 
buildId));
+    cache->add(cacheKey, makeEmptyJoinTable(spec, tablePool.get()), true, 
tablePool);
+    queryCtx->addReleaseCallback([cacheKey]() { 
exec::HashTableCache::instance()->drop(cacheKey); });
+  }
+  ContinueFuture future = ContinueFuture::makeEmpty();
+  auto entry = cache->get(cacheKey, taskId, queryCtx.get(), &future);
+  VELOX_CHECK(!future.valid());
+  VELOX_CHECK(entry->buildComplete);
+  // When HashBuild abandons dedup, it allows duplicates in a table whose rows
+  // have no next-row pointer. The flag no longer matters once the table is
+  // built, but HashTable::serializeTo() records it as the row layout, so make
+  // it match for the driver-side build. Nothing probes the table yet.
+  if (entry->table->rows()->nextOffset() == 0) {
+    entry->table->setAllowDuplicates(false);
+  }
+
+  // HashBuild allocated the table from 'entry->tablePool', but cached it as a
+  // plain pointer that does not keep that pool alive. Probe tasks copy that
+  // pointer out of the entry and can outlive both the entry and the returned
+  // table, e.g. when a task fails while Java releases the broadcast table.
+  // The pool would then go first and the table would free into a dead pool.
+  //
+  // So replace the cached pointer with one built by the shared_ptr aliasing
+  // constructor: it points to the table but shares ownership of a
+  // TableWithPool, so every copy keeps both the table and its pool alive. 
Velox
+  // does the same for cached Nimble tablets, see ReaderBase.cpp.
+  auto tableWithPool = 
std::make_shared<TableWithPool>(TableWithPool{entry->tablePool, entry->table});
+  entry->table = std::shared_ptr<exec::BaseHashTable>(tableWithPool, 
tableWithPool->table.get());
+
+  return std::make_shared<BroadcastHashTable>(
+      entry->table, entry->hasNullKeys, entry->tablePool->usedBytes(), 
std::move(queryCtx));
+}
+
+} // namespace gluten
diff --git a/cpp/velox/operators/hashjoin/HashTableTaskBuilder.h 
b/cpp/velox/operators/hashjoin/HashTableTaskBuilder.h
new file mode 100644
index 0000000000..30751f4ebc
--- /dev/null
+++ b/cpp/velox/operators/hashjoin/HashTableTaskBuilder.h
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <folly/Executor.h>
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include "operators/hashjoin/BroadcastHashTable.h"
+#include "velox/common/memory/Memory.h"
+#include "velox/core/PlanNode.h"
+#include "velox/vector/ComplexVector.h"
+
+namespace gluten {
+
+/// Describes the build side of a broadcast hash join.
+struct HashTableTaskBuildSpec {
+  facebook::velox::core::JoinType joinType;
+  bool nullAware{false};
+  /// HashBuild never evaluates the join filter. It only checks whether there 
is
+  /// one and, for an anti join, drops build rows with a null in the build
+  /// columns of a null-intolerant filter. So these properties are all it 
needs.
+  bool withFilter{false};
+  std::vector<std::string> filterBuildColumns;
+  bool filterPropagatesNulls{false};
+  facebook::velox::RowTypePtr buildType;
+  std::vector<std::string> joinKeys;
+  /// Velox query configs for the build, e.g. join build tuning knobs.
+  std::unordered_map<std::string, std::string> queryConfigs;
+};
+
+/// Builds a broadcast hash table by running Velox HashBuild in a dedicated 
task
+/// with its own QueryCtx. The task runs a fake HashJoinNode(useHashTableCache 
=
+/// true, cacheKey = 'cacheKey') with 'buildVectors' on the build side and an
+/// empty probe side, so HashBuild publishes the table to HashTableCache.
+/// 'numDrivers' > 1 builds in parallel on 'executor' and HashBuild merges the
+/// per-driver tables. 'vectorPool' allocates the empty inputs of the fake 
join.
+///
+/// The returned table owns the task's QueryCtx: releasing it drops the cache
+/// entry.
+std::shared_ptr<BroadcastHashTable> buildHashTableWithTask(
+    const std::string& cacheKey,
+    const HashTableTaskBuildSpec& spec,
+    const std::vector<facebook::velox::RowVectorPtr>& buildVectors,
+    uint32_t numDrivers,
+    folly::Executor* executor,
+    std::shared_ptr<facebook::velox::memory::MemoryPool> queryPool,
+    facebook::velox::memory::MemoryPool* vectorPool);
+
+} // namespace gluten
diff --git a/cpp/velox/substrait/SubstraitToVeloxPlan.cc 
b/cpp/velox/substrait/SubstraitToVeloxPlan.cc
index bb88c1df61..8d9a4faedc 100644
--- a/cpp/velox/substrait/SubstraitToVeloxPlan.cc
+++ b/cpp/velox/substrait/SubstraitToVeloxPlan.cc
@@ -24,7 +24,7 @@
 #include "compute/iceberg/IcebergPlanConverter.h"
 #include "jni/JniHashTable.h"
 #include "operators/functions/IncrementMetricFunction.h"
-#include "operators/hashjoin/HashTableBuilder.h"
+#include "operators/hashjoin/BroadcastHashTable.h"
 #include "operators/plannodes/RowVectorStream.h"
 #ifdef ENABLE_KAFKA
 #include "kafka.pb.h"
@@ -470,18 +470,19 @@ core::PlanNodePtr 
SubstraitToVeloxPlanConverter::toVeloxPlan(const ::substrait::
   } else if (
       sJoin.has_advanced_extension() &&
       SubstraitParser::configSetInOptimization(sJoin.advanced_extension(), 
"isBHJ=")) {
-    const std::string hashTableId = sJoin.hashtableid();
+    std::string cacheKey;
     bool useHashTableCache = false;
-    if (!hashTableId.empty()) {
+    if (!sJoin.hashtableid().empty()) {
       try {
-        const auto handle = getJoin(hashTableId);
+        cacheKey = getJoinCacheKey(sJoin.hashtableid());
+        const auto handle = getJoin(cacheKey);
         if (handle != 0) {
-          auto hashTableBuilder = 
ObjectStore::retrieve<gluten::HashTableBuilder>(handle);
-          useHashTableCache = (hashTableBuilder != nullptr);
+          auto hashTable = 
ObjectStore::retrieve<gluten::BroadcastHashTable>(handle);
+          useHashTableCache = (hashTable != nullptr);
         }
       } catch (const std::exception& e) {
-        LOG(WARNING) << "Failed to retrieve pre-built HashTableBuilder for 
cache key: " << hashTableId
-                     << ", error: " << e.what() << ". Disable hash table cache 
and build a new table.";
+        LOG(WARNING) << "Failed to retrieve pre-built hash table for cache 
key: " << cacheKey << ", error: " << e.what()
+                     << ". Disable hash table cache and build a new table.";
       }
     }
 
@@ -511,7 +512,7 @@ core::PlanNodePtr 
SubstraitToVeloxPlanConverter::toVeloxPlan(const ::substrait::
         getJoinOutputType(leftNode, rightNode, joinType),
         useHashTableCache,
         false,
-        sJoin.hashtableid());
+        cacheKey);
   } else {
     // Create HashJoinNode node
     return std::make_shared<core::HashJoinNode>(


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

Reply via email to