Copilot commented on code in PR #45001:
URL: https://github.com/apache/arrow/pull/45001#discussion_r3644358945


##########
cpp/src/arrow/compute/kernels/scalar_hash.cc:
##########
@@ -0,0 +1,364 @@
+// 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 <algorithm>
+#include <utility>
+
+#include "arrow/array/array_base.h"
+#include "arrow/array/builder_primitive.h"
+#include "arrow/compute/kernels/common_internal.h"
+#include "arrow/compute/key_hash_internal.h"
+#include "arrow/compute/light_array_internal.h"
+#include "arrow/compute/registry_internal.h"
+#include "arrow/compute/util.h"
+#include "arrow/result.h"
+
+namespace arrow {
+namespace compute {
+namespace internal {
+
+// Define symbols visible within `arrow::compute::internal` in this file;
+// these symbols are not visible outside of this file.
+namespace {
+
+// ------------------------------
+// Kernel implementations
+// It is expected that HashArrowType is either UInt32Type or UInt64Type 
(default)
+
+// Not dependent on the ArrowType/Hasher template arguments below, so defined
+// as a free function to avoid unnecessary code generation per instantiation.
+// Never called with a nested (list-like or struct) array: HashArray handles 
those
+// itself, either via HashChild (which reduces them to a plain UInt32/UInt64 
array
+// before it ever reaches here) or the is_list_like branch directly.
+Result<KeyColumnArray> ToColumnArray(const ArraySpan& array) {
+  KeyColumnMetadata metadata;
+  const uint8_t* validity_buffer = nullptr;
+  const uint8_t* fixed_length_buffer = nullptr;
+  const uint8_t* var_length_buffer = nullptr;
+
+  if (array.GetBuffer(0) != nullptr) {
+    validity_buffer = array.GetBuffer(0)->data();
+  }
+  if (array.GetBuffer(1) != nullptr) {
+    fixed_length_buffer = array.GetBuffer(1)->data();
+  }
+
+  auto type = array.type;
+  auto type_id = type->id();
+  if (type_id == Type::NA) {
+    metadata = KeyColumnMetadata(true, 0, true);
+  } else if (type_id == Type::BOOL) {
+    metadata = KeyColumnMetadata(true, 0);
+  } else if (is_fixed_width(type_id)) {
+    metadata = KeyColumnMetadata(true, type->bit_width() / 8);
+  } else if (is_binary_like(type_id)) {
+    metadata = KeyColumnMetadata(false, sizeof(uint32_t));
+    if (array.GetBuffer(2) != nullptr) {
+      var_length_buffer = array.GetBuffer(2)->data();
+    }
+  } else if (is_large_binary_like(type_id)) {
+    metadata = KeyColumnMetadata(false, sizeof(uint64_t));
+    if (array.GetBuffer(2) != nullptr) {
+      var_length_buffer = array.GetBuffer(2)->data();
+    }
+  } else {
+    return Status::TypeError("Unsupported column data type ", type->name(),
+                             " used with hash32/hash64 compute kernel");
+  }
+
+  return KeyColumnArray(metadata, array.length, validity_buffer, 
fixed_length_buffer,
+                        var_length_buffer);
+}
+
+// Zeroes out[i] wherever array is null.
+template <typename c_type>
+void ZeroNulls(const ArraySpan& array, c_type* out) {
+  if (array.GetBuffer(0) == nullptr) {
+    return;
+  }
+  for (int64_t i = 0; i < array.length; i++) {
+    if (array.IsNull(i)) {
+      out[i] = 0;
+    }
+  }
+}
+
+// Folds one row's child hashes into a single hash. Seeded with 
CombineHashes(0, 0),
+// not 0, so an empty list doesn't collide with a null list (zeroed separately 
below).
+// Free function since it only depends on c_type/Hasher, not ArrowType.
+template <typename c_type, typename Hasher>
+c_type CombineRange(const c_type* value_hashes, int64_t start, int64_t end) {
+  c_type combined = Hasher::CombineHashes(0, 0);
+  for (int64_t j = start; j < end; j++) {
+    combined = Hasher::CombineHashes(combined, value_hashes[j]);
+  }
+  return combined;
+}
+
+// Combines rows for LIST/LARGE_LIST/MAP, whose offsets buffers differ only in 
width.
+// `bias` is values.offset + rel_start, so offsets[i] - bias locates row i.
+template <typename c_type, typename Hasher, typename OffsetT>
+void CombineOffsetRows(int64_t length, const OffsetT* offsets, int64_t bias,
+                       const c_type* value_hash_data, c_type* out) {
+  for (int64_t i = 0; i < length; i++) {
+    out[i] = CombineRange<c_type, Hasher>(value_hash_data, offsets[i] - bias,
+                                          offsets[i + 1] - bias);
+  }
+}
+
+template <typename ArrowType, typename Hasher>
+struct FastHashScalar {
+  using c_type = typename ArrowType::c_type;
+
+  // Hashes the [offset, offset + length) slice of `child`.
+  static Result<std::shared_ptr<ArrayData>> HashChild(const ArraySpan& child,
+                                                      int64_t offset, int64_t 
length,
+                                                      LightContext* hash_ctx,
+                                                      MemoryPool* memory_pool) 
{
+    auto sliced = child;
+    sliced.SetSlice(offset, length);
+    auto arrow_type = TypeTraits<ArrowType>::type_singleton();
+    auto buffer_size = sliced.length * sizeof(c_type);
+    ARROW_ASSIGN_OR_RAISE(auto buffer, AllocateBuffer(buffer_size, 
memory_pool));
+    ARROW_RETURN_NOT_OK(
+        HashArray(sliced, hash_ctx, memory_pool, 
buffer->mutable_data_as<c_type>()));
+    return ArrayData::Make(arrow_type, sliced.length,
+                           {sliced.GetBuffer(0), std::move(buffer)}, 
sliced.null_count);
+  }
+
+  static Status HashStructArray(const ArraySpan& array, LightContext* hash_ctx,
+                                MemoryPool* memory_pool, c_type* out) {
+    if (array.child_data.empty()) {
+      // No fields to combine (e.g. struct<>): HashMultiColumn requires at 
least one
+      // column (it reads cols[0] unconditionally), so give every row the same 
defined
+      // hash here instead, then let ZeroNulls below zero out the 
actually-null rows.
+      c_type empty_struct_hash = Hasher::CombineHashes(0, 0);
+      for (int64_t i = 0; i < array.length; i++) {
+        out[i] = empty_struct_hash;
+      }
+      ZeroNulls(array, out);
+      return Status::OK();
+    }
+    std::vector<std::shared_ptr<ArrayData>> 
child_hashes(array.child_data.size());
+    std::vector<KeyColumnArray> columns(array.child_data.size());
+    KeyColumnArray column;
+    for (size_t i = 0; i < array.child_data.size(); i++) {
+      auto child = array.child_data[i];
+      int64_t slice_offset = array.offset;
+      if (is_nested(child.type->id())) {
+        ARROW_ASSIGN_OR_RAISE(
+            child_hashes[i],
+            HashChild(child, child.offset, child.length, hash_ctx, 
memory_pool));
+        ARROW_ASSIGN_OR_RAISE(column, ToColumnArray(*child_hashes[i]));
+        // child_hashes[i] starts at offset 0; only the struct's own offset 
applies.
+      } else {
+        ARROW_ASSIGN_OR_RAISE(column, ToColumnArray(child));
+        // `child` may have its own offset independent of the struct's (a 
struct field
+        // can itself be a slice; see StructArray::GetFlattenedField), so add 
both.
+        slice_offset += child.offset;
+      }
+      columns[i] = column.Slice(slice_offset, array.length);
+    }
+    Hasher::HashMultiColumn(columns, hash_ctx, out);
+    // A null struct row's children may still look valid, so force 0 
explicitly.
+    ZeroNulls(array, out);
+    return Status::OK();
+  }
+
+  // Handles FIXED_SIZE_LIST, LARGE_LIST, LIST, and MAP. `offsets` is null for
+  // FIXED_SIZE_LIST, which uses `list_size` as a constant stride instead. 
HashArray
+  // computes rel_start/rel_end (the range of `values` actually referenced, 
since
+  // ArrayData::Slice() doesn't slice child_data) since it already branches on 
type_id.
+  template <typename OffsetT>
+  static Status HashListArray(const ArraySpan& array, int64_t list_size,
+                              const OffsetT* offsets, int64_t rel_start, 
int64_t rel_end,
+                              LightContext* hash_ctx, MemoryPool* memory_pool,
+                              c_type* out) {
+    auto values = array.child_data[0];
+    ARROW_ASSIGN_OR_RAISE(auto value_hashes,
+                          HashChild(values, values.offset + rel_start,
+                                    rel_end - rel_start, hash_ctx, 
memory_pool));
+    const c_type* value_hash_data = 
value_hashes->buffers[1]->data_as<c_type>();
+    // value_hash_data[k] corresponds to original row (values.offset + 
rel_start + k).
+
+    // Fold every row, then zero nulls separately below; benchmarking showed 
this beats
+    // branchless masking (masking costs every row; branch prediction handles 
nulls free).
+    if (offsets != nullptr) {
+      CombineOffsetRows<c_type, Hasher>(array.length, offsets, values.offset + 
rel_start,
+                                        value_hash_data, out);
+    } else {
+      for (int64_t i = 0; i < array.length; i++) {
+        int64_t start = (array.offset + i) * list_size - values.offset - 
rel_start;
+        out[i] = CombineRange<c_type, Hasher>(value_hash_data, start, start + 
list_size);
+      }
+    }
+    // Required: a null row's offset range isn't guaranteed empty, and even an 
empty
+    // one would collide with CombineRange's seed for a real empty list.
+    ZeroNulls(array, out);
+    return Status::OK();
+  }
+
+  // Routes to the per-shape hashing routine for `array`'s type.
+  static Status HashArray(const ArraySpan& array, LightContext* hash_ctx,
+                          MemoryPool* memory_pool, c_type* out) {
+    auto type_id = array.type->id();
+    if (type_id == Type::EXTENSION) {
+      auto extension_type = checked_cast<const ExtensionType*>(array.type);
+      auto storage_array = array;
+      storage_array.type = extension_type->storage_type().get();
+      return HashArray(storage_array, hash_ctx, memory_pool, out);
+    } else if (type_id == Type::STRUCT) {
+      return HashStructArray(array, hash_ctx, memory_pool, out);
+    } else if (type_id == Type::FIXED_SIZE_LIST) {
+      auto list_size = checked_cast<const 
FixedSizeListType*>(array.type)->list_size();
+      auto values = array.child_data[0];
+      int64_t rel_start = 0, rel_end = 0;
+      if (array.length > 0) {
+        rel_start = array.offset * list_size - values.offset;
+        rel_end = (array.offset + array.length) * list_size - values.offset;
+      }
+      return HashListArray<int32_t>(array, list_size, nullptr, rel_start, 
rel_end,
+                                    hash_ctx, memory_pool, out);
+    } else if (type_id == Type::LARGE_LIST) {
+      auto offsets = array.GetValues<int64_t>(1);
+      auto values = array.child_data[0];
+      int64_t rel_start = 0, rel_end = 0;
+      if (array.length > 0) {
+        rel_start = offsets[0] - values.offset;
+        rel_end = offsets[array.length] - values.offset;
+      }
+      return HashListArray<int64_t>(array, 0, offsets, rel_start, rel_end, 
hash_ctx,
+                                    memory_pool, out);
+    } else if (is_list_like(type_id)) {
+      // LIST and MAP both use 32-bit offsets.
+      auto offsets = array.GetValues<int32_t>(1);
+      auto values = array.child_data[0];
+      int64_t rel_start = 0, rel_end = 0;
+      if (array.length > 0) {
+        rel_start = offsets[0] - values.offset;
+        rel_end = offsets[array.length] - values.offset;
+      }
+      return HashListArray<int32_t>(array, 0, offsets, rel_start, rel_end, 
hash_ctx,
+                                    memory_pool, out);
+    } else {
+      KeyColumnArray column;
+      ARROW_ASSIGN_OR_RAISE(column, ToColumnArray(array));
+      std::vector<KeyColumnArray> columns{column.Slice(array.offset, 
array.length)};
+      Hasher::HashMultiColumn(columns, hash_ctx, out);
+      // HashIntImp (used for fixed-width types up to 8 bytes) doesn't 
special-case an
+      // all-zero-bits key (e.g. integer 0, float 0.0), so it can legitimately 
produce
+      // the same 0 that HashMultiColumn uses as the null sentinel for 
actually-null
+      // rows. Remap valid rows that collide with 0 here, scoped to this 
kernel's
+      // output, rather than changing the shared hashing engine used by 
hash-join and
+      // group-by too.
+      for (int64_t i = 0; i < array.length; i++) {
+        if (out[i] == 0 && array.IsValid(i)) {
+          out[i] = Hasher::CombineHashes(0, 0);
+        }
+      }
+      return Status::OK();
+    }
+  }
+
+  static Status Exec(KernelContext* ctx, const ExecSpan& input_arg, 
ExecResult* out) {
+    ARROW_DCHECK_EQ(input_arg.num_values(), 1);
+    ARROW_DCHECK(input_arg[0].is_array());
+    ArraySpan hash_input = input_arg[0].array;
+
+    auto exec_ctx = default_exec_context();
+    if (ctx && ctx->exec_context()) {
+      exec_ctx = ctx->exec_context();
+    }
+
+    // Initialize stack-based memory allocator used by Hashing32 and Hashing64
+    util::TempVectorStack stack_memallocator;
+    ARROW_RETURN_NOT_OK(stack_memallocator.Init(exec_ctx->memory_pool(),
+                                                
Hasher::kHashBatchTempStackUsage));
+
+    // Prepare context used by Hashing32 and Hashing64
+    LightContext hash_ctx;
+    hash_ctx.hardware_flags = exec_ctx->cpu_info()->hardware_flags();
+    hash_ctx.stack = &stack_memallocator;
+
+    // Call the hashing function, overloaded based on OutputCType
+    ArraySpan* result_span = out->array_span_mutable();
+    c_type* result_ptr = result_span->GetValues<c_type>(1);
+    ARROW_RETURN_NOT_OK(
+        HashArray(hash_input, &hash_ctx, exec_ctx->memory_pool(), result_ptr));
+
+    return Status::OK();
+  }
+};
+
+class HashableMatcher : public TypeMatcher {
+ public:
+  HashableMatcher() {}
+
+  bool Matches(const DataType& type) const override {
+    return !(is_union(type) || is_binary_view_like(type) || is_list_view(type) 
||
+             type.id() == Type::RUN_END_ENCODED);
+  }

Review Comment:
   HashableMatcher::Matches() only rejects unsupported physical types at the 
top-level. For EXTENSION types, Matches() will return true even if the storage 
type is a union/view/run-end-encoded type, leading to runtime TypeError from 
HashArray/ToColumnArray rather than a clean NotImplemented kernel dispatch. 
Unwrapping extension types inside the matcher keeps the dispatch behavior 
consistent with the documented unsupported-type handling.



-- 
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]

Reply via email to