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

zhouyuan 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 aece57488f [VL] Fix zero-size aligned memory reallocation (#13668)
aece57488f is described below

commit aece57488f3ae82a1ffe520326b8d4b2881b8ee6
Author: Mingliang Zhu <[email protected]>
AuthorDate: Sun Nov 22 18:58:48 2026 +0800

    [VL] Fix zero-size aligned memory reallocation (#13668)
    
    * [CORE] Fix zero-size aligned memory reallocation
    
    Allow aligned allocations to shrink to zero while preserving a non-null,
    aligned pointer that can be freed or grown again. Keep logical memory
    accounting correct and preserve the original allocation on failure.
    
    Add allocator and Arrow regression tests, plus a native Parquet write
    regression in VeloxParquetWriteSuite using the existing checkNativeWrite
    helper.
---
 .../sql/execution/VeloxParquetWriteSuite.scala     |  25 ++++
 cpp/core/memory/MemoryAllocator.cc                 |  14 +-
 cpp/core/memory/MemoryAllocator.h                  |   3 +
 cpp/core/tests/MemoryAllocatorTest.cc              | 150 +++++++++++++++++++++
 4 files changed, 191 insertions(+), 1 deletion(-)

diff --git 
a/backends-velox/src/test/scala/org/apache/spark/sql/execution/VeloxParquetWriteSuite.scala
 
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/VeloxParquetWriteSuite.scala
index ef7ff5d23c..86058e122b 100644
--- 
a/backends-velox/src/test/scala/org/apache/spark/sql/execution/VeloxParquetWriteSuite.scala
+++ 
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/VeloxParquetWriteSuite.scala
@@ -65,6 +65,31 @@ class VeloxParquetWriteSuite extends 
VeloxWholeStageTransformerSuite with WriteU
     super.sparkConf.set(GlutenConfig.NATIVE_WRITER_ENABLED.key, "true")
   }
 
+  test("native Parquet write of filtered dictionary containing only empty 
strings") {
+    import testImplicits._
+
+    withTempPath {
+      dir =>
+        val inputPath = s"${dir.getCanonicalPath}/input"
+        val outputPath = s"${dir.getCanonicalPath}/output"
+        val values = Seq((0, ""), (1, "unreferenced-a"), (2, "unreferenced-b"))
+        withSQLConf(GlutenConfig.NATIVE_WRITER_ENABLED.key -> "false") {
+          Seq.fill(128)(values).flatten.toDF("id", "value").coalesce(1).write
+            .option("parquet.enable.dictionary", "true")
+            .parquet(inputPath)
+        }
+
+        // Keep unused, non-empty values in the source dictionary while 
selecting only empty
+        // strings. Dictionary statistics may then shrink Arrow Take's value 
buffer to zero.
+        checkNativeWrite(
+          s"""INSERT OVERWRITE DIRECTORY '$outputPath'
+             |USING PARQUET OPTIONS ('parquet.enable.dictionary' 'true')
+             |SELECT value FROM parquet.`$inputPath` WHERE id % 3 = 0
+             |""".stripMargin)
+        checkAnswer(spark.read.parquet(outputPath), Seq.fill(128)(Row("")))
+    }
+  }
+
   test("test Array(Struct) fallback") {
     withTempPath {
       f =>
diff --git a/cpp/core/memory/MemoryAllocator.cc 
b/cpp/core/memory/MemoryAllocator.cc
index ef35847085..8f74553ee3 100644
--- a/cpp/core/memory/MemoryAllocator.cc
+++ b/cpp/core/memory/MemoryAllocator.cc
@@ -166,9 +166,21 @@ bool StdMemoryAllocator::reallocate(void* p, int64_t size, 
int64_t newSize, void
 
 bool StdMemoryAllocator::reallocateAligned(void* p, uint64_t alignment, 
int64_t size, int64_t newSize, void** out) {
   GLUTEN_CHECK(p != nullptr, "reallocate with nullptr");
-  if (newSize <= 0) {
+  if (newSize < 0) {
     return false;
   }
+  if (newSize == 0) {
+    // Keep a freeable, aligned pointer without relying on realloc(p, 0) or 
aligned_alloc(alignment, 0).
+    // The allocation has zero logical size, so only the old size is removed 
from accounting.
+    void* empty = std::aligned_alloc(alignment, alignment);
+    if (empty == nullptr) {
+      return false;
+    }
+    std::free(p);
+    *out = empty;
+    bytes_ -= size;
+    return true;
+  }
   if (newSize <= size) {
     auto aligned = ROUND_TO_LINE(static_cast<uint64_t>(newSize), alignment);
     if (aligned <= size) {
diff --git a/cpp/core/memory/MemoryAllocator.h 
b/cpp/core/memory/MemoryAllocator.h
index 01271cc946..6ffdf953be 100644
--- a/cpp/core/memory/MemoryAllocator.h
+++ b/cpp/core/memory/MemoryAllocator.h
@@ -36,6 +36,9 @@ class MemoryAllocator {
   virtual bool allocateAligned(uint64_t alignment, int64_t size, void** out) = 
0;
 
   virtual bool reallocate(void* p, int64_t size, int64_t newSize, void** out) 
= 0;
+
+  // On success, *out is non-null and aligned even when newSize is zero, and 
can be freed or reallocated again.
+  // A zero-size allocation does not contribute to getBytes().
   virtual bool reallocateAligned(void* p, uint64_t alignment, int64_t size, 
int64_t newSize, void** out) = 0;
 
   virtual bool free(void* p, int64_t size) = 0;
diff --git a/cpp/core/tests/MemoryAllocatorTest.cc 
b/cpp/core/tests/MemoryAllocatorTest.cc
index bd023544bf..52209d9e31 100644
--- a/cpp/core/tests/MemoryAllocatorTest.cc
+++ b/cpp/core/tests/MemoryAllocatorTest.cc
@@ -16,7 +16,12 @@
  */
 
 #include "memory/MemoryAllocator.h"
+#include <arrow/array/builder_binary.h>
+#include <arrow/array/builder_primitive.h>
+#include <arrow/buffer_builder.h>
+#include <arrow/compute/api.h>
 #include <gtest/gtest.h>
+#include "memory/ArrowMemoryPool.h"
 
 #include <cstdint>
 
@@ -62,3 +67,148 @@ TEST(StdMemoryAllocator, shrinkKeepsAlignment) {
     ASSERT_EQ(allocator.getBytes(), 0);
   }
 }
+
+TEST(StdMemoryAllocator, reallocateAlignedToZeroAndGrow) {
+  StdMemoryAllocator allocator;
+  constexpr uint64_t kAlignment = 64;
+  constexpr int64_t kSize = 1024;
+  void* buf = nullptr;
+  ASSERT_TRUE(allocator.allocateAligned(kAlignment, kSize, &buf));
+
+  ASSERT_TRUE(allocator.reallocateAligned(buf, kAlignment, kSize, 0, &buf));
+  ASSERT_NE(buf, nullptr);
+  ASSERT_EQ(reinterpret_cast<uintptr_t>(buf) % kAlignment, 0);
+  ASSERT_EQ(allocator.getBytes(), 0);
+
+  ASSERT_TRUE(allocator.reallocateAligned(buf, kAlignment, 0, 0, &buf));
+  ASSERT_NE(buf, nullptr);
+  ASSERT_EQ(allocator.getBytes(), 0);
+
+  ASSERT_TRUE(allocator.reallocateAligned(buf, kAlignment, 0, kSize, &buf));
+  ASSERT_NE(buf, nullptr);
+  ASSERT_EQ(reinterpret_cast<uintptr_t>(buf) % kAlignment, 0);
+  ASSERT_EQ(allocator.getBytes(), kSize);
+  std::memset(buf, 0x5a, kSize);
+  ASSERT_EQ(static_cast<uint8_t*>(buf)[kSize - 1], 0x5a);
+
+  ASSERT_TRUE(allocator.free(buf, kSize));
+  ASSERT_EQ(allocator.getBytes(), 0);
+}
+
+TEST(ListenableMemoryAllocator, reallocateAlignedToZeroAccounting) {
+  class TrackingListener final : public AllocationListener {
+   public:
+    void allocationChanged(int64_t diff) override {
+      bytes += diff;
+    }
+    int64_t bytes = 0;
+  } listener;
+  StdMemoryAllocator delegated;
+  ListenableMemoryAllocator allocator(&delegated, &listener);
+  constexpr uint64_t kAlignment = 64;
+  constexpr int64_t kSize = 1024;
+  void* buf = nullptr;
+  ASSERT_TRUE(allocator.allocateAligned(kAlignment, kSize, &buf));
+  ASSERT_EQ(listener.bytes, kSize);
+
+  ASSERT_TRUE(allocator.reallocateAligned(buf, kAlignment, kSize, 0, &buf));
+  ASSERT_NE(buf, nullptr);
+  ASSERT_EQ(allocator.getBytes(), 0);
+  ASSERT_EQ(delegated.getBytes(), 0);
+  ASSERT_EQ(listener.bytes, 0);
+  ASSERT_EQ(allocator.peakBytes(), kSize);
+
+  ASSERT_TRUE(allocator.free(buf, 0));
+  ASSERT_EQ(allocator.getBytes(), 0);
+  ASSERT_EQ(delegated.getBytes(), 0);
+  ASSERT_EQ(listener.bytes, 0);
+}
+
+TEST(ArrowMemoryPool, finishEmptyBufferWithReservedCapacity) {
+  auto listener = AllocationListener::noop();
+  ArrowMemoryPool pool(listener.get());
+  {
+    arrow::BufferBuilder builder(&pool);
+    ASSERT_TRUE(builder.Reserve(1024).ok());
+    ASSERT_GT(pool.bytes_allocated(), 0);
+
+    std::shared_ptr<arrow::Buffer> buffer;
+    const auto status = builder.Finish(&buffer);
+    ASSERT_TRUE(status.ok()) << status.ToString();
+    ASSERT_EQ(buffer->size(), 0);
+    ASSERT_EQ(pool.bytes_allocated(), 0);
+  }
+  ASSERT_EQ(pool.bytes_allocated(), 0);
+}
+
+TEST(ArrowMemoryPool, resizeBufferToZeroAndGrow) {
+  auto listener = AllocationListener::noop();
+  ArrowMemoryPool pool(listener.get());
+  {
+    auto result = arrow::AllocateResizableBuffer(1024, &pool);
+    ASSERT_TRUE(result.ok()) << result.status().ToString();
+    auto buffer = std::move(result).ValueOrDie();
+    const auto status = buffer->Resize(0);
+    ASSERT_TRUE(status.ok()) << status.ToString();
+    ASSERT_EQ(buffer->size(), 0);
+    ASSERT_EQ(pool.bytes_allocated(), 0);
+
+    ASSERT_TRUE(buffer->Resize(1024).ok());
+    ASSERT_EQ(buffer->size(), 1024);
+    ASSERT_EQ(pool.bytes_allocated(), 1024);
+    std::memset(buffer->mutable_data(), 0x5a, buffer->size());
+    ASSERT_EQ(buffer->data()[1023], 0x5a);
+  }
+  ASSERT_EQ(pool.bytes_allocated(), 0);
+}
+
+TEST(StdMemoryAllocator, negativeReallocationPreservesAllocation) {
+  StdMemoryAllocator allocator;
+  constexpr int64_t kSize = 64;
+  void* buf = nullptr;
+  ASSERT_TRUE(allocator.allocateAligned(kSize, kSize, &buf));
+  std::memset(buf, 0x5a, kSize);
+  void* original = buf;
+
+  ASSERT_FALSE(allocator.reallocateAligned(buf, kSize, kSize, -1, &buf));
+  ASSERT_EQ(buf, original);
+  ASSERT_EQ(allocator.getBytes(), kSize);
+  ASSERT_EQ(static_cast<uint8_t*>(buf)[kSize - 1], 0x5a);
+  ASSERT_TRUE(allocator.free(buf, kSize));
+  ASSERT_EQ(allocator.getBytes(), 0);
+}
+
+TEST(ArrowMemoryPool, takeStringsWithNoValueBytes) {
+  auto listener = AllocationListener::noop();
+  ArrowMemoryPool pool(listener.get());
+
+  // The Parquet dictionary writer uses Take to compute statistics for the 
referenced dictionary values.
+  // Selecting only nulls or empty strings can shrink the output value buffer 
to zero bytes.
+  for (bool takeNull : {false, true}) {
+    SCOPED_TRACE(takeNull);
+    {
+      arrow::StringBuilder valuesBuilder;
+      ASSERT_TRUE(valuesBuilder.Append("").ok());
+      ASSERT_TRUE(valuesBuilder.Append("unreferenced dictionary value").ok());
+      auto values = valuesBuilder.Finish();
+      ASSERT_TRUE(values.ok()) << values.status().ToString();
+
+      arrow::Int32Builder indicesBuilder;
+      ASSERT_TRUE((takeNull ? indicesBuilder.AppendNull() : 
indicesBuilder.Append(0)).ok());
+      auto indices = indicesBuilder.Finish();
+      ASSERT_TRUE(indices.ok()) << indices.status().ToString();
+
+      arrow::compute::ExecContext context(&pool);
+      auto result = arrow::compute::Take(
+          *values.ValueOrDie(), *indices.ValueOrDie(), 
arrow::compute::TakeOptions::Defaults(), &context);
+      ASSERT_TRUE(result.ok()) << result.status().ToString();
+      const auto& strings = static_cast<const 
arrow::StringArray&>(*result.ValueOrDie());
+      ASSERT_EQ(strings.length(), 1);
+      ASSERT_EQ(strings.IsNull(0), takeNull);
+      if (!takeNull) {
+        ASSERT_EQ(strings.GetView(0), "");
+      }
+    }
+    ASSERT_EQ(pool.bytes_allocated(), 0);
+  }
+}


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

Reply via email to