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


##########
cpp/src/arrow/compute/api_scalar.h:
##########
@@ -1807,5 +1807,42 @@ ARROW_EXPORT Result<Datum> NanosecondsBetween(const 
Datum& left, const Datum& ri
 /// \note API not yet finalized
 ARROW_EXPORT Result<Datum> MapLookup(const Datum& map, MapLookupOptions 
options,
                                      ExecContext* ctx = NULLPTR);
+
+/// \brief Construct a hash value for each row of the input.
+///
+/// The result is an Array of length equal to the length of the input; 
however, the output
+/// shall be a UInt32Array, with each element being a hash constructed from 
each row of
+/// the input. If the input Array is a NestedArray, this means that each 
"attribute" or
+/// "field" of the input NestedArray corresponding to the same "row" will 
collectively
+/// produce a single uint32_t hash. At the moment, this function does not take 
options,
+/// though these may be added in the future.

Review Comment:
   The Hash32/Hash64 API docstrings state the result is always an Array and 
refer to a "NestedArray" type; however these functions take a Datum and (like 
other compute APIs) may return a Scalar/Array/ChunkedArray depending on the 
input kind, and for nested *types* (struct/list/map) the semantics are “combine 
child hashes per top-level element”. It would also help to mention the NULL 
sentinel behavior (OUTPUT_NOT_NULL) and that hash values are not stable across 
Arrow versions. Please update the Hash32 docs accordingly (and mirror the same 
edits for Hash64).



##########
cpp/src/arrow/compute/kernels/scalar_hash.cc:
##########
@@ -0,0 +1,387 @@
+// 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"
+#include "arrow/util/bitmap_ops.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>()));
+
+    std::shared_ptr<Buffer> validity;
+    if (sliced.GetBuffer(0) != nullptr) {
+      // sliced.GetBuffer(0) is unshifted: reading logical row i requires bit
+      // `sliced.offset + i`. But the returned ArrayData has offset 0, and 
callers
+      // build a KeyColumnArray directly from its buffers without applying that
+      // offset themselves (see ToColumnArray, which always treats bit/byte 0 
of a
+      // buffer as row 0). Repack into a fresh, 0-based bitmap so it's 
self-consistent
+      // with the hash values buffer, which is already 0-based.
+      ARROW_ASSIGN_OR_RAISE(validity, ::arrow::internal::CopyBitmap(
+                                          memory_pool, 
sliced.GetBuffer(0)->data(),
+                                          sliced.offset, sliced.length));
+    }
+    return ArrayData::Make(arrow_type, sliced.length,
+                           {std::move(validity), 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);

Review Comment:
   In HashStructArray, nested child fields are hashed for the entire child 
array (`HashChild(child, child.offset, child.length, ...)`) and only then 
sliced. Since StructArray::Slice() doesn’t reslice child_data, hashing 
`child.length` makes hashing a small struct slice O(size of the original 
struct) whenever a field is nested (e.g. struct<list<...>>). Consider hashing 
only the struct slice’s referenced range (and then slicing from 0) to keep 
sliced structs proportional to the slice size, similar to the list/map paths.



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