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

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


The following commit(s) were added to refs/heads/main by this push:
     new 80a37645930 GH-55650: [C++][ORC] Preserve offsets when normalizing 
structs (#55662)
80a37645930 is described below

commit 80a37645930200ac20889b91173e6547c53c1d8a
Author: Sabyasachi Panda <[email protected]>
AuthorDate: Sun Nov 22 21:08:34 2026 +0530

    GH-55650: [C++][ORC] Preserve offsets when normalizing structs (#55662)
    
    ### Rationale for this change
    
    The ORC writer serializes a sliced `struct` column with struct-level nulls 
incorrectly: it writes the struct's validity and the child values starting at 
physical row 0 instead of at the array's offset (`NormalizeArray()` in 
`cpp/src/arrow/adapters/orc/util.cc`, STRUCT branch). No error is raised — the 
file itself is wrong, and the struct column ends up misaligned with the other 
columns in the same file. This affects everyday operations such as 
`Table.slice()` / `table[a:b]`, or writin [...]
    
    Example (pyarrow): writing `t.slice(1, 4)` of `[{a:0}, None, {a:2}, {a:3}, 
None, {a:5}]` produces `[{'a': 0}, None, {'a': 2}, {'a': 3}]` instead of 
`[None, {'a': 2}, {'a': 3}, None]`, while the `id` column is written correctly. 
The Apache ORC C++ reader returns the same wrong values, confirming the file is 
corrupt, not just the Arrow reader.
    
    The root cause: `NormalizeArray()` (STRUCT branch, runs when `null_count() 
!= 0`) rebuilds each child to AND in the struct's validity, dropping every 
offset in the process:
    
    1. `StructArray::field(i)` returns the child already re-sliced to the 
struct's range (child offset = child offset + struct offset), but
    2. `BitmapAnd()` reads both validity buffers from bit 0 instead of from the 
parent's and child's offsets,
    3. `ArrayData::Make(child->type(), child->length(), ...)` rebuilds the 
child without passing `child->offset()`, so it defaults to 0 over the original, 
unsliced buffers, and
    4. `std::make_shared<StructArray>(...)` drops the struct's own offset while 
reusing the unsliced validity buffer.
    
    Additionally, when a child has no validity bitmap, the parent's raw, 
unoffset bitmap buffer was assigned directly as the child's validity buffer, 
which only aligns by coincidence.
    
    GH-15212 / PR #15213 fixed the same class of bug for the 
LIST/LARGE_LIST/FIXED_SIZE_LIST/MAP branches by passing offsets through; the 
STRUCT branch was left as it was. The existing `writeSlicedBatch` regression 
test does not reach this branch because it generates its table with 
`probability=0` (no nulls), so `NormalizeArray` takes the `null_count() == 0` 
early return.
    
    Closes #55650.
    
    ### What changes are included in this PR?
    
    Use the existing `StructArray::GetFlattenedField()` abstraction in the 
STRUCT branch of `NormalizeArray()` — the same one the SPARSE_UNION branch of 
the same function already uses. It pushes the parent slice down to each child 
(child offset = child offset + parent offset) and merges parent and child 
validity at the correct bit positions, including the case where the child has 
no validity bitmap. Each flattened child is normalized recursively. The 
struct's own validity bitmap is then r [...]
    
    This PR addresses GH-55650 only. GH-55618 (a struct-normalization bug on 
the `null_count() == 0` early-return path of the same function) is related but 
distinct and is intentionally not addressed here.
    
    ### Are these changes tested?
    
    Yes — deterministic regression tests added to 
`cpp/src/arrow/adapters/orc/adapter_test.cc`:
    
    - `writeSlicedBatchWithStructNulls`: a struct column with struct-level 
nulls, sliced with a non-zero offset (`table->Slice(1, 4)`), round-tripped 
through the ORC writer/reader.
    - `writeStructWithOffsetChild`: struct at offset 0 with a child that has 
its own offset (logical values `[13, 14, 15]` over physical `[10, 11, 12, 13, 
14, 15]`) and a struct-level null at row 1, round-tripped.
    - `writeSlicedStructWithOffsetChild`: combines a non-zero struct offset 
with an independently offset child.
    
    Results against the unpatched implementation (built locally at the same 
revision): all three tests **fail**, and the failure diffs reproduce the 
corruption reported in the issue exactly (e.g. child values `[10, null, 12]` 
written instead of `[13, 14, 15]`, validity shifted from `[false, true, true, 
false]` to `[true, false, true, true]`). With this patch, all three pass, and 
the full ORC adapter suite passes (`ctest -R arrow-orc-adapter-test`: 100% 
passed, 0 failed — 44/44). Without t [...]
    
    `git diff --check` is clean; no unrelated tests were modified.
    
    ### Are there any user-facing changes?
    
    No API changes. Users who write sliced struct columns containing 
struct-level nulls (or structs whose children carry their own offsets) to ORC 
now get correct files instead of silently corrupted ones.
    
    **This PR contains a "Critical Fix".** The bug caused incorrect or invalid 
data to be produced: the ORC writer silently wrote rows from the wrong offset 
for sliced struct columns with nulls, producing files that are wrong in every 
reader (verified with the Apache ORC C++ reader).
    
    ### Was AI used for this PR?
    
    In accordance to the [AI generation 
guidelines](https://arrow.apache.org/docs/dev/developers/overview.html#ai-generated-code),
 please disclose below whether and how AI was used in this PR.
    
    AI assistance (an AI coding agent) was used to prepare the analysis, the 
code change, and this description. The complete diff was reviewed by the 
author, who verified the root-cause analysis against the checked-out sources, 
and the build and regression tests were run locally with the results reported 
above.
    
    **PR code and description written by:**
    
    - [ ] Human
    - [x] AI
    
    **Reviewed before submission by:**
    
    - [x] Human
    - [ ] AI
    - [ ] Not reviewed
    
    Authored-by: SabyaXSachi <[email protected]>
    Signed-off-by: Gang Wu <[email protected]>
---
 cpp/src/arrow/adapters/orc/adapter_test.cc | 41 ++++++++++++++++++++++++++++
 cpp/src/arrow/adapters/orc/util.cc         | 44 ++++++++++++------------------
 2 files changed, 59 insertions(+), 26 deletions(-)

diff --git a/cpp/src/arrow/adapters/orc/adapter_test.cc 
b/cpp/src/arrow/adapters/orc/adapter_test.cc
index 3cbb6d7828f..a6f4686402f 100644
--- a/cpp/src/arrow/adapters/orc/adapter_test.cc
+++ b/cpp/src/arrow/adapters/orc/adapter_test.cc
@@ -746,6 +746,47 @@ TEST_F(TestORCWriterTrivialNoConversion, writeSlicedBatch) 
{
   AssertTableWriteReadEqual(table, table, kDefaultSmallMemStreamSize / 16);
 }
 
+TEST_F(TestORCWriterTrivialNoConversion, writeSlicedBatchWithStructNulls) {
+  std::shared_ptr<Schema> local_schema =
+      schema({field("id", int32()), field("s", struct_({field("a", 
int64())}))});
+  std::shared_ptr<Table> table = TableFromJSON(local_schema, {R"([
+    {"id": 0, "s": {"a": 0}}, {"id": 1, "s": null}, {"id": 2, "s": {"a": 2}},
+    {"id": 3, "s": {"a": 3}}, {"id": 4, "s": null}, {"id": 5, "s": {"a": 
5}}])"});
+  table = table->Slice(1, 4);
+
+  AssertTableWriteReadEqual(table, table, kDefaultSmallMemStreamSize / 16);
+}
+
+TEST_F(TestORCWriterTrivialNoConversion, writeStructWithOffsetChild) {
+  // The child array carries its own offset (logical values are [13, 14, 15]),
+  // while the struct itself starts at offset 0 and has a struct-level null at
+  // row 1.
+  std::shared_ptr<Array> values =
+      ArrayFromJSON(int64(), "[10, 11, 12, 13, 14, 15]")->Slice(3, 3);
+  ASSERT_OK_AND_ASSIGN(auto null_bitmap, AllocateBuffer(1, 
default_memory_pool()));
+  // Bit i is set when row i is valid: rows 0 and 2 are valid, row 1 is null.
+  null_bitmap->mutable_data()[0] = 0b101;
+  ASSERT_OK_AND_ASSIGN(
+      auto struct_array,
+      StructArray::Make({values}, {"a"}, std::move(null_bitmap), 
/*null_count=*/1));
+
+  AssertArrayWriteReadEqual(struct_array, struct_array, 
kDefaultSmallMemStreamSize / 16);
+}
+
+TEST_F(TestORCWriterTrivialNoConversion, writeSlicedStructWithOffsetChild) {
+  // Combine a non-zero struct offset with an independently offset child.
+  std::shared_ptr<Array> values =
+      ArrayFromJSON(int64(), "[10, 11, 12, 13, 14, 15]")->Slice(3, 3);
+  ASSERT_OK_AND_ASSIGN(auto null_bitmap, AllocateBuffer(1, 
default_memory_pool()));
+  null_bitmap->mutable_data()[0] = 0b101;
+  ASSERT_OK_AND_ASSIGN(
+      auto struct_array,
+      StructArray::Make({values}, {"a"}, std::move(null_bitmap), 
/*null_count=*/1));
+  std::shared_ptr<Array> sliced = struct_array->Slice(1, 2);
+
+  AssertArrayWriteReadEqual(sliced, sliced, kDefaultSmallMemStreamSize / 16);
+}
+
 class TestORCWriterTrivialWithConversion : public ::testing::Test {
  public:
   TestORCWriterTrivialWithConversion() {
diff --git a/cpp/src/arrow/adapters/orc/util.cc 
b/cpp/src/arrow/adapters/orc/util.cc
index 91260302abd..c5d30fad920 100644
--- a/cpp/src/arrow/adapters/orc/util.cc
+++ b/cpp/src/arrow/adapters/orc/util.cc
@@ -24,6 +24,7 @@
 #include <vector>
 
 #include "arrow/array/builder_base.h"
+#include "arrow/buffer.h"
 #include "arrow/builder.h"
 #include "arrow/chunked_array.h"
 #include "arrow/scalar.h"
@@ -397,33 +398,24 @@ Result<std::shared_ptr<Array>> NormalizeArray(const 
std::shared_ptr<Array>& arra
         return array;
       } else {
         auto struct_array = checked_pointer_cast<StructArray>(array);
-        const std::shared_ptr<Buffer> bitmap = struct_array->null_bitmap();
-        std::shared_ptr<DataType> struct_type = struct_array->type();
-        std::size_t size = struct_type->fields().size();
-        std::vector<std::shared_ptr<Array>> new_children(size, nullptr);
-        for (std::size_t i = 0; i < size; i++) {
-          std::shared_ptr<Array> child = 
struct_array->field(static_cast<int>(i));
-          const std::shared_ptr<Buffer> child_bitmap = child->null_bitmap();
-          std::shared_ptr<Buffer> final_child_bitmap;
-          if (child_bitmap == nullptr) {
-            final_child_bitmap = bitmap;
-          } else {
-            ARROW_ASSIGN_OR_RAISE(
-                final_child_bitmap,
-                internal::BitmapAnd(default_memory_pool(), bitmap->data(), 0,
-                                    child_bitmap->data(), 0, 
struct_array->length(), 0));
-          }
-          std::shared_ptr<ArrayData> child_array_data = child->data();
-          std::vector<std::shared_ptr<Buffer>> child_buffers = 
child_array_data->buffers;
-          child_buffers[0] = final_child_bitmap;
-          std::shared_ptr<ArrayData> new_child_array_data =
-              ArrayData::Make(child->type(), child->length(), child_buffers,
-                              child_array_data->child_data, 
child_array_data->dictionary);
-          ARROW_ASSIGN_OR_RAISE(new_children[i],
-                                
NormalizeArray(MakeArray(new_child_array_data)));
+        std::vector<std::shared_ptr<Array>> new_children(
+            struct_array->type()->num_fields());
+        for (int i = 0; i < static_cast<int>(new_children.size()); ++i) {
+          // Push the struct's offset down and merge the struct's validity into
+          // the child's, so each child is valid only on rows valid in both.
+          ARROW_ASSIGN_OR_RAISE(auto child, 
struct_array->GetFlattenedField(i));
+          ARROW_ASSIGN_OR_RAISE(new_children[i], NormalizeArray(child));
         }
-        return std::make_shared<StructArray>(struct_type, 
struct_array->length(),
-                                             new_children, bitmap);
+        // The children have been rebased to offset 0, so rebase the struct's
+        // own validity bitmap to offset 0 as well.
+        std::shared_ptr<Buffer> new_bitmap;
+        ARROW_ASSIGN_OR_RAISE(new_bitmap, 
AllocateEmptyBitmap(struct_array->length(),
+                                                              
default_memory_pool()));
+        internal::CopyBitmap(struct_array->null_bitmap_data(), 
struct_array->offset(),
+                             struct_array->length(), 
new_bitmap->mutable_data(), 0);
+        return std::make_shared<StructArray>(struct_array->type(), 
struct_array->length(),
+                                             new_children, 
std::move(new_bitmap),
+                                             struct_array->null_count());
       }
     }
     case Type::type::LIST: {

Reply via email to