You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "atognolag (via GitHub)" <gi...@apache.org> on 2026/05/07 15:33:15 UTC

[PR] Implement high-performance sorted writing support in IcebergIO [beam]

atognolag opened a new pull request, #38406:
URL: https://github.com/apache/beam/pull/38406

   # Pull Request: High-Performance Sorted Writing Support in Native IcebergIO
   
   ## Description
   This pull request implements robust, high-performance sorted writing support in native `IcebergIO` (`sdks/java/io/iceberg`).
   
   When writing to sorted Iceberg tables, writing unsorted data causes massive performance degradation, high memory overhead, and "file thrashing" due to too many concurrent file writers being kept open on workers. By dynamically pre-sorting incoming `PCollection<Row>` elements based on the active Iceberg table `SortOrder` inside the write transform, we produce perfectly ordered Parquet files, optimize worker resources, and reduce the number of concurrent file handles.
   
   ---
   
   ## Core Technical Implementation
   
   ### 1. Memory-Safe Spill-to-Disk Sorter (`IcebergRowSorter.java`)
   - Integrates Beam's native `:sdks:java:extensions:sorter` (via `BufferedExternalSorter`).
   - Processes row sorting per-partition dynamically. If memory buffers are exceeded, the sorter automatically spills elements to the worker's local disk, ensuring strict memory guardrails against out-of-memory (`OOM`) crashes.
   
   ### 2. Dynamic Unsigned Lexicographical Byte Encoding
   - Generates a sorting key dynamically by converting composite sort columns into a lexicographically comparable byte array (`byte[]`):
     - **Direction (ASC vs DESC)**: ASC columns are encoded in their natural comparable format. DESC columns are inverted bitwise (`~byte`) to reverse the unsigned byte comparison order naturally.
     - **Null Constraints (`NULLS_FIRST` & `NULLS_LAST`)**: Prefix headers are mapped statically to direct standard unsigned comparators correctly:
       - ASC NULLS_FIRST -> `0x00` / ASC NULLS_LAST -> `0xFF`
       - DESC NULLS_FIRST -> `0xFF` / DESC NULLS_LAST -> `0x00`
     - **Escape Boundary Protocol**: Strings and byte arrays are mapped to a deterministic, collision-free escaping sequence (`0x00 -> [0x01, 0x01]`, `0x01 -> [0x01, 0x02]`) terminated by a safe `0x00` byte. This prevents column boundary bleeding on composite keys (e.g. `"abc"+"def"` vs `"abcdef"+null`).
     - **Algebraic Numbers**: Transforms signed integers, longs, doubles, and floats into big-endian byte structures with flipped sign bits to preserve algebraic scale order.
     - **Flexible Timeframes**: Supports `ReadableInstant`, `java.time.Instant`, and `java.util.Date` conversions, preventing runner-specific casting crashes.
   
   ### 3. Shard-Routing and Write-Path Bypasses
   - **Dynamic Schema Extraction**: Extracts schemas dynamically from active row elements at runtime, avoiding null schema references caused by transient serialization on worker nodes.
   - **Direct-Write Bypass**: Dynamically inspects target table metadata inside `WriteUngroupedRowsToFiles`. If the table has an active `SortOrder`, it skips direct ungrouped writing and spills elements to the grouped, shuffled path where they are properly partitioned and pre-sorted before writing.
   
   ---
   
   ## Verification and Test Coverage
   
   ### 1. Expanded Unit Tests (`IcebergRowSorterTest.java`)
   - **String Collision Proofing**: Asserts that boundary-safe byte escaping correctly distinguishes and orders complex composite strings.
   - **Null Quadrant Matrix**: Validates all 4 null-ordering combinations under unsigned comparison.
   - **Scale and Disk Spill**: Asserts sorting safety and data integrity with 5,000 randomized records under extremely tight memory bounds (1MB buffer), forcing disk spilling.
   
   ### 2. End-to-End Pipeline Integration Tests (`IcebergIOWriteTest.java`)
   - Appends scrambled datasets to a sorted Iceberg table in a Beam pipeline.
   - Implements a sharding-friendly `assertFilesAreInternallySorted` verification helper which parses individual Parquet files committed to the table directly using Iceberg scan APIs, ensuring that *each written file* is perfectly sorted internally, regardless of the runner's sharding factor.
   - Tested and validated successfully across `NONE`, `HASH`, and `HASH_WITH_AUTOSHARDING` distribution modes.
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3203048872


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+    for (SortField field : sortOrder.fields()) {
+      String colName = icebergSchema.findColumnName(field.sourceId());
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        Object icebergVal =
+            IcebergUtils.beamRowToIcebergRecord(icebergSchema, row).getField(colName);
+        if (icebergVal != null) {
+          val = field.transform().apply(icebergVal);
+        } else {
+          val = null;
+        }
+      }
+
+      boolean isNull = (val == null);
+      boolean isDesc = (field.direction() == SortDirection.DESC);
+      boolean nullsFirst = (field.nullOrder() == NullOrder.NULLS_FIRST);
+
+      // Determine correct header prefix to fulfill the NullOrder contracts
+      byte prefixByte;
+      if (isNull) {
+        if (isDesc) {
+          // Descending: High byte keys sort first.
+          // If Nulls First -> Null gets highest byte (0xFF)
+          // If Nulls Last -> Null gets lowest byte (0x00)
+          prefixByte = nullsFirst ? (byte) 0xFF : (byte) 0x00;
+        } else {
+          // Ascending: Low byte keys sort first.
+          // If Nulls First -> Null gets lowest byte (0x00)
+          // If Nulls Last -> Null gets highest byte (0xFF)
+          prefixByte = nullsFirst ? (byte) 0x00 : (byte) 0xFF;
+        }
+      } else {
+        if (isDesc) {
+          // If non-null and Descending, use a neutral value that sits opposite to the null byte
+          prefixByte = nullsFirst ? (byte) 0xFE : (byte) 0x01;
+        } else {
+          prefixByte = nullsFirst ? (byte) 0x01 : (byte) 0x00;
+        }
+      }
+
+      baos.write(prefixByte);
+
+      if (!isNull) {
+        byte[] valBytes = encodeValue(val);
+        // Bitwise invert non-null bytes to sort descending lexicographically
+        if (isDesc) {
+          for (int i = 0; i < valBytes.length; i++) {
+            valBytes[i] = (byte) ~valBytes[i];
+          }
+        }
+        baos.write(valBytes);
+      }
+    }
+
+    return baos.toByteArray();
+  }
+
+  @SuppressWarnings("JavaUtilDate")
+  private static byte[] encodeValue(@Nullable Object val) throws IOException {
+    if (val == null) {
+      return new byte[0];
+    }
+    if (val instanceof String) {
+      return encodeString((String) val);
+    } else if (val instanceof Integer) {
+      int v = (Integer) val;
+      return ByteBuffer.allocate(4).putInt(v ^ Integer.MIN_VALUE).array();
+    } else if (val instanceof Long) {
+      long v = (Long) val;
+      return ByteBuffer.allocate(8).putLong(v ^ Long.MIN_VALUE).array();
+    } else if (val instanceof Float) {
+      int bits = Float.floatToIntBits((Float) val);
+      bits = (bits >= 0) ? (bits ^ Integer.MIN_VALUE) : ~bits;
+      return ByteBuffer.allocate(4).putInt(bits).array();
+    } else if (val instanceof Double) {
+      long bits = Double.doubleToLongBits((Double) val);
+      bits = (bits >= 0) ? (bits ^ Long.MIN_VALUE) : ~bits;
+      return ByteBuffer.allocate(8).putLong(bits).array();

Review Comment:
   The IcebergRowSorter.java now uses bit manipulation directly into the destination ByteArrayOutputStream, supporting inline byte inversion without allocating any heap objects.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on PR #38406:
URL: https://github.com/apache/beam/pull/38406#issuecomment-4406233033

   I have updated this PR to address your (Ahmed) feedback and optimize the sorting implementation. Below is a summary of the changes:
   
   **1. Configurable Distribution Modes**
   Introduced configurable Distribution Modes in IcebergIO.WriteRows to manage sharding and sorting behaviors before writing:
   
   1. HASH (Default): Shuffles and groups data by partition key ({destination, partition}) to consolidate files per partition and prevent cross-worker file overlaps. Supports optional dynamic auto-sharding (withAutosharding()) to split hot partitions (but losing the non-overlapping files condition).
   
   2. RANGE: Shuffles data based on a user-supplied SerializableFunction<Row, Integer> (shard function) to distribute hot partitions across parallel sharded workers, keeping file min/max key ranges non-overlapping (provided the user logic does not randomize shard IDs).
   
   3. NONE: No network shuffle. Best for lightweight pipelines that rely on post-fact compaction or read-time sort merges.
   
   **2. Performance Optimizations (GC & CPU Overhead Reductions)**
   Optimized the sorting pipeline in IcebergRowSorter to reduce CPU cycles and GC memory pressure:
   
   1. Field-Level Value Conversion: Added beamValueToIcebergValue to IcebergUtils. This converts only the specific fields requiring a sort transform, completely bypassing the expensive row-to-record conversion (beamRowToIcebergRecord) inside the sorting loop.
   2. Stream Reuse: Reuses and resets (.reset()) the ByteArrayOutputStream in the sorting loops to eliminate short-lived output stream allocations.
   3. Primitive Serialization: Encodes numeric fields using bitwise shifts directly into the output stream, eliminating intermediate ByteBuffer and byte[] allocations.
   
   **3. Sorter Correctness & Safety**
   1. Null-Ordering Correctness: Corrected the null-ordering prefix byte logic for descending sort orders. Prefix bytes now remain consistent regardless of sorting direction (which is already handled by bitwise inverting values), resolving the descending null order bugs.
   2. Sorting Type Safety: Throws UnsupportedOperationException when attempting to sort on complex types (maps, lists, structs) to prevent non Iceberg compliant sorts.
   3. Deprecated API Removal: Removed the unused, deprecated encodeSortKey overload from IcebergRowSorter since it is a package-private utility class and not used elsewhere.
   
   **4. Verification & Test Coverage**
   1. Checkstyle & Linter Warnings: Documented all exposed configurations and resolved Google Error Prone warnings.
   2. New Test Cases: Added testRangeDistribution to IcebergIOWriteTest to verify range-based writes with custom sharding. Added a test verifying ValidationException is thrown when trying to construct a sort order with complex types.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38406:
URL: https://github.com/apache/beam/pull/38406#issuecomment-4916028266

   Hi @atognolag, can you fix the conflicts and any other errors? Then @ahmedabu98 can review again. Thanks!


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #38406: Implement high-performance sorted writing support in IcebergIO
URL: https://github.com/apache/beam/pull/38406


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3203023168


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+    for (SortField field : sortOrder.fields()) {
+      String colName = icebergSchema.findColumnName(field.sourceId());
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        Object icebergVal =
+            IcebergUtils.beamRowToIcebergRecord(icebergSchema, row).getField(colName);

Review Comment:
   Now exactly one conversion occurs per row when one or more transformed columns are sorted, regardless of the number of sort fields.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [IcebergIO] Support sorted writes and RANGE distribution mode (#38406) [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on PR #38406:
URL: https://github.com/apache/beam/pull/38406#issuecomment-6264484134

   Superseded by #40653 (rebased on `master` with all review comments addressed, zero-shuffle `NONE` bundle sorting, and dynamic quantile sharding for `RANGE`). cc @ahmedabu98


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3203011770


##########
sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorterTest.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.types.Types;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class IcebergRowSorterTest {
+
+  private static final Schema BEAM_SCHEMA =
+      Schema.builder()
+          .addInt32Field("id")
+          .addNullableField("name", Schema.FieldType.STRING)
+          .addNullableField("value", Schema.FieldType.DOUBLE)
+          .addNullableField("active", Schema.FieldType.BOOLEAN)
+          .build();
+
+  private static final org.apache.iceberg.Schema ICEBERG_SCHEMA =
+      new org.apache.iceberg.Schema(
+          Types.NestedField.required(1, "id", Types.IntegerType.get()),
+          Types.NestedField.optional(2, "name", Types.StringType.get()),
+          Types.NestedField.optional(3, "value", Types.DoubleType.get()),
+          Types.NestedField.optional(4, "active", Types.BooleanType.get()));
+
+  private static final Comparator<byte[]> BYTE_ARR_COMPARATOR =
+      org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.primitives.UnsignedBytes
+          .lexicographicalComparator();
+
+  @Test
+  public void testStringKeyEncodingOrder() throws Exception {
+    SortOrder sortOrder = SortOrder.builderFor(ICEBERG_SCHEMA).asc("name").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(1, "apple", 1.5, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(2, "banana", 2.0, true).build();
+    Row r3 = Row.withSchema(BEAM_SCHEMA).addValues(3, "apricot", 3.0, false).build();
+
+    byte[] k1 = IcebergRowSorter.encodeSortKey(r1, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2 = IcebergRowSorter.encodeSortKey(r2, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k3 = IcebergRowSorter.encodeSortKey(r3, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k2) < 0); // apple < banana
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k3) < 0); // apple < apricot
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k3, k2) < 0); // apricot < banana
+  }
+
+  @Test
+  public void testStringCollisionProofing() throws Exception {
+    // Tests that secondary columns don't bleed into primary columns.
+    // Row 1: Primary="abc", Secondary="def"
+    // Row 2: Primary="abcdef", Secondary=null
+    // In raw byte concatenation, both could equal "abcdef\0" if delimiters or escaping fail.
+    SortOrder sortOrder = SortOrder.builderFor(ICEBERG_SCHEMA).asc("name").asc("value").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(1, "abc", 1.0, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(2, "abcdef", null, true).build();
+
+    byte[] k1 = IcebergRowSorter.encodeSortKey(r1, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2 = IcebergRowSorter.encodeSortKey(r2, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    // "abc" must sort lexicographically before "abcdef"
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k2) < 0);
+  }
+
+  @Test
+  public void testDescInversion() throws Exception {
+    SortOrder sortOrderAsc = SortOrder.builderFor(ICEBERG_SCHEMA).asc("id").build();
+    SortOrder sortOrderDesc = SortOrder.builderFor(ICEBERG_SCHEMA).desc("id").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(10, "test", 1.5, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(20, "test", 2.0, true).build();
+
+    byte[] k1Asc = IcebergRowSorter.encodeSortKey(r1, sortOrderAsc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2Asc = IcebergRowSorter.encodeSortKey(r2, sortOrderAsc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    byte[] k1Desc = IcebergRowSorter.encodeSortKey(r1, sortOrderDesc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2Desc = IcebergRowSorter.encodeSortKey(r2, sortOrderDesc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    // Ascending: 10 < 20
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1Asc, k2Asc) < 0);
+
+    // Descending: 10 > 20 (inverted bytes)
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1Desc, k2Desc) > 0);
+  }
+
+  @Test
+  public void testNullOrderingMatrix() throws Exception {
+    Row rNonNull = Row.withSchema(BEAM_SCHEMA).addValues(1, "apple", 1.5, true).build();
+    Row rNull = Row.withSchema(BEAM_SCHEMA).addValues(2, null, 2.0, true).build();
+
+    // 1. ASC, NULLS_FIRST
+    SortOrder ascFirst =
+        SortOrder.builderFor(ICEBERG_SCHEMA).asc("name", NullOrder.NULLS_FIRST).build();
+    byte[] kNonNullAscFirst =
+        IcebergRowSorter.encodeSortKey(rNonNull, ascFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullAscFirst =
+        IcebergRowSorter.encodeSortKey(rNull, ascFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "ASC NULLS_FIRST failed: null should sort before non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullAscFirst, kNonNullAscFirst) < 0);
+
+    // 2. ASC, NULLS_LAST
+    SortOrder ascLast =
+        SortOrder.builderFor(ICEBERG_SCHEMA).asc("name", NullOrder.NULLS_LAST).build();
+    byte[] kNonNullAscLast =
+        IcebergRowSorter.encodeSortKey(rNonNull, ascLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullAscLast =
+        IcebergRowSorter.encodeSortKey(rNull, ascLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "ASC NULLS_LAST failed: null should sort after non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullAscLast, kNonNullAscLast) > 0);
+
+    // 3. DESC, NULLS_FIRST
+    SortOrder descFirst =
+        SortOrder.builderFor(ICEBERG_SCHEMA).desc("name", NullOrder.NULLS_FIRST).build();
+    byte[] kNonNullDescFirst =
+        IcebergRowSorter.encodeSortKey(rNonNull, descFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullDescFirst =
+        IcebergRowSorter.encodeSortKey(rNull, descFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "DESC NULLS_FIRST failed: null should sort before non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullDescFirst, kNonNullDescFirst) > 0);
+
+    // 4. DESC, NULLS_LAST
+    SortOrder descLast =
+        SortOrder.builderFor(ICEBERG_SCHEMA).desc("name", NullOrder.NULLS_LAST).build();
+    byte[] kNonNullDescLast =
+        IcebergRowSorter.encodeSortKey(rNonNull, descLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullDescLast =
+        IcebergRowSorter.encodeSortKey(rNull, descLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "DESC NULLS_LAST failed: null should sort after non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullDescLast, kNonNullDescLast) < 0);
+  }

Review Comment:
   Fix adopted



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38406:
URL: https://github.com/apache/beam/pull/38406#issuecomment-5570845085

   This pull request has been marked as stale due to 60 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the dev@beam.apache.org list. Thank you for your contributions.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3209272524


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    List<SortField> fields = sortOrder.fields();
+    String[] columnNames = new String[fields.size()];
+    for (int i = 0; i < fields.size(); i++) {
+      columnNames[i] = icebergSchema.findColumnName(fields.get(i).sourceId());
+    }
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, columnNames, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      String[] columnNames,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+    List<SortField> fields = sortOrder.fields();
+    org.apache.iceberg.data.Record icebergRecord = null;
+
+    for (int i = 0; i < fields.size(); i++) {
+      SortField field = fields.get(i);
+      String colName = columnNames[i];
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        if (icebergRecord == null) {
+          icebergRecord = IcebergUtils.beamRowToIcebergRecord(icebergSchema, row);
+        }
+        Object icebergVal = icebergRecord.getField(colName);
+        if (icebergVal != null) {
+          val = field.transform().apply(icebergVal);
+        } else {
+          val = null;
+        }
+      }
+
+      boolean isNull = (val == null);
+      boolean isDesc = (field.direction() == SortDirection.DESC);
+      boolean nullsFirst = (field.nullOrder() == NullOrder.NULLS_FIRST);
+
+      // Determine correct header prefix to fulfill the NullOrder contracts
+      byte prefixByte;
+      if (isNull) {
+        prefixByte = nullsFirst ? (byte) 0x00 : (byte) 0xFF;
+      } else {
+        prefixByte = nullsFirst ? (byte) 0x01 : (byte) 0x00;
+      }
+
+      baos.write(prefixByte);
+
+      if (!isNull) {
+        writeValue(val, baos, isDesc);
+      }
+    }
+
+    return baos.toByteArray();
+  }
+
+  private static void writeInt(int v, ByteArrayOutputStream baos, boolean invert) {
+    byte b3 = (byte) (v >>> 24);
+    byte b2 = (byte) (v >>> 16);
+    byte b1 = (byte) (v >>> 8);
+    byte b0 = (byte) v;
+    if (invert) {
+      baos.write(~b3);
+      baos.write(~b2);
+      baos.write(~b1);
+      baos.write(~b0);
+    } else {
+      baos.write(b3);
+      baos.write(b2);
+      baos.write(b1);
+      baos.write(b0);
+    }
+  }
+
+  private static void writeLong(long v, ByteArrayOutputStream baos, boolean invert) {
+    byte b7 = (byte) (v >>> 56);
+    byte b6 = (byte) (v >>> 48);
+    byte b5 = (byte) (v >>> 40);
+    byte b4 = (byte) (v >>> 32);
+    byte b3 = (byte) (v >>> 24);
+    byte b2 = (byte) (v >>> 16);
+    byte b1 = (byte) (v >>> 8);
+    byte b0 = (byte) v;
+    if (invert) {
+      baos.write(~b7);
+      baos.write(~b6);
+      baos.write(~b5);
+      baos.write(~b4);
+      baos.write(~b3);
+      baos.write(~b2);
+      baos.write(~b1);
+      baos.write(~b0);
+    } else {
+      baos.write(b7);
+      baos.write(b6);
+      baos.write(b5);
+      baos.write(b4);
+      baos.write(b3);
+      baos.write(b2);
+      baos.write(b1);
+      baos.write(b0);
+    }
+  }
+
+  @SuppressWarnings("JavaUtilDate")
+  private static void writeValue(Object val, ByteArrayOutputStream baos, boolean invert)
+      throws IOException {
+    if (val instanceof String) {
+      writeString((String) val, baos, invert);
+    } else if (val instanceof Integer) {
+      int v = (Integer) val;
+      writeInt(v ^ Integer.MIN_VALUE, baos, invert);
+    } else if (val instanceof Long) {
+      long v = (Long) val;
+      writeLong(v ^ Long.MIN_VALUE, baos, invert);
+    } else if (val instanceof Float) {
+      int bits = Float.floatToIntBits((Float) val);
+      bits = (bits >= 0) ? (bits ^ Integer.MIN_VALUE) : ~bits;
+      writeInt(bits, baos, invert);
+    } else if (val instanceof Double) {
+      long bits = Double.doubleToLongBits((Double) val);
+      bits = (bits >= 0) ? (bits ^ Long.MIN_VALUE) : ~bits;
+      writeLong(bits, baos, invert);
+    } else if (val instanceof Boolean) {
+      byte b = ((Boolean) val) ? (byte) 0x01 : (byte) 0x00;
+      baos.write(invert ? ~b : b);
+    } else if (val instanceof byte[]) {
+      writeByteArray((byte[]) val, baos, invert);
+    } else if (val instanceof ByteBuffer) {
+      writeByteArray(((ByteBuffer) val).array(), baos, invert);
+    } else if (val instanceof ReadableInstant) {
+      long enc = ((ReadableInstant) val).getMillis() ^ Long.MIN_VALUE;
+      writeLong(enc, baos, invert);
+    } else if (val instanceof Instant) {
+      long enc = ((Instant) val).toEpochMilli() ^ Long.MIN_VALUE;
+      writeLong(enc, baos, invert);
+    } else if (val instanceof Date) {
+      long enc = ((Date) val).getTime() ^ Long.MIN_VALUE;
+      writeLong(enc, baos, invert);
+    } else {
+      writeString(val.toString(), baos, invert);
+    }

Review Comment:
   It is not supported. It now raises an `UnsupportedOperationException`



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on PR #38406:
URL: https://github.com/apache/beam/pull/38406#issuecomment-4399053531

   @ahmedabu98 mind taking a look? Thanks!


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3202710866


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+    for (SortField field : sortOrder.fields()) {
+      String colName = icebergSchema.findColumnName(field.sourceId());
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        Object icebergVal =
+            IcebergUtils.beamRowToIcebergRecord(icebergSchema, row).getField(colName);
+        if (icebergVal != null) {
+          val = field.transform().apply(icebergVal);
+        } else {
+          val = null;
+        }
+      }
+
+      boolean isNull = (val == null);
+      boolean isDesc = (field.direction() == SortDirection.DESC);
+      boolean nullsFirst = (field.nullOrder() == NullOrder.NULLS_FIRST);
+
+      // Determine correct header prefix to fulfill the NullOrder contracts
+      byte prefixByte;
+      if (isNull) {
+        if (isDesc) {
+          // Descending: High byte keys sort first.
+          // If Nulls First -> Null gets highest byte (0xFF)
+          // If Nulls Last -> Null gets lowest byte (0x00)
+          prefixByte = nullsFirst ? (byte) 0xFF : (byte) 0x00;
+        } else {
+          // Ascending: Low byte keys sort first.
+          // If Nulls First -> Null gets lowest byte (0x00)
+          // If Nulls Last -> Null gets highest byte (0xFF)
+          prefixByte = nullsFirst ? (byte) 0x00 : (byte) 0xFF;
+        }
+      } else {
+        if (isDesc) {
+          // If non-null and Descending, use a neutral value that sits opposite to the null byte
+          prefixByte = nullsFirst ? (byte) 0xFE : (byte) 0x01;
+        } else {
+          prefixByte = nullsFirst ? (byte) 0x01 : (byte) 0x00;
+        }
+      }

Review Comment:
   ![critical](https://www.gstatic.com/codereviewagent/critical.svg)
   
   The logic for `prefixByte` when `isDesc` is true is incorrect. `BufferedExternalSorter` performs an ascending lexicographical comparison of the byte keys. To achieve `NULLS_FIRST`, the null prefix must always be smaller than the non-null prefix, regardless of whether the column values are inverted for descending order. Currently, for `isDesc=true`, `NULLS_FIRST` uses `0xFF` for null and `0xFE` for non-null, which will cause nulls to sort **last** in the resulting iterable.
   
   Additionally, the prefix logic can be simplified as it does not depend on the sort direction; the direction is already handled by inverting the value bytes.
   
   ```java
         // Determine correct header prefix to fulfill the NullOrder contracts
         byte prefixByte;
         if (isNull) {
           prefixByte = nullsFirst ? (byte) 0x00 : (byte) 0xFF;
         } else {
           prefixByte = nullsFirst ? (byte) 0x01 : (byte) 0x00;
         }
   ```



##########
sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorterTest.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.types.Types;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class IcebergRowSorterTest {
+
+  private static final Schema BEAM_SCHEMA =
+      Schema.builder()
+          .addInt32Field("id")
+          .addNullableField("name", Schema.FieldType.STRING)
+          .addNullableField("value", Schema.FieldType.DOUBLE)
+          .addNullableField("active", Schema.FieldType.BOOLEAN)
+          .build();
+
+  private static final org.apache.iceberg.Schema ICEBERG_SCHEMA =
+      new org.apache.iceberg.Schema(
+          Types.NestedField.required(1, "id", Types.IntegerType.get()),
+          Types.NestedField.optional(2, "name", Types.StringType.get()),
+          Types.NestedField.optional(3, "value", Types.DoubleType.get()),
+          Types.NestedField.optional(4, "active", Types.BooleanType.get()));
+
+  private static final Comparator<byte[]> BYTE_ARR_COMPARATOR =
+      org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.primitives.UnsignedBytes
+          .lexicographicalComparator();
+
+  @Test
+  public void testStringKeyEncodingOrder() throws Exception {
+    SortOrder sortOrder = SortOrder.builderFor(ICEBERG_SCHEMA).asc("name").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(1, "apple", 1.5, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(2, "banana", 2.0, true).build();
+    Row r3 = Row.withSchema(BEAM_SCHEMA).addValues(3, "apricot", 3.0, false).build();
+
+    byte[] k1 = IcebergRowSorter.encodeSortKey(r1, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2 = IcebergRowSorter.encodeSortKey(r2, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k3 = IcebergRowSorter.encodeSortKey(r3, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k2) < 0); // apple < banana
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k3) < 0); // apple < apricot
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k3, k2) < 0); // apricot < banana
+  }
+
+  @Test
+  public void testStringCollisionProofing() throws Exception {
+    // Tests that secondary columns don't bleed into primary columns.
+    // Row 1: Primary="abc", Secondary="def"
+    // Row 2: Primary="abcdef", Secondary=null
+    // In raw byte concatenation, both could equal "abcdef\0" if delimiters or escaping fail.
+    SortOrder sortOrder = SortOrder.builderFor(ICEBERG_SCHEMA).asc("name").asc("value").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(1, "abc", 1.0, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(2, "abcdef", null, true).build();
+
+    byte[] k1 = IcebergRowSorter.encodeSortKey(r1, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2 = IcebergRowSorter.encodeSortKey(r2, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    // "abc" must sort lexicographically before "abcdef"
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k2) < 0);
+  }
+
+  @Test
+  public void testDescInversion() throws Exception {
+    SortOrder sortOrderAsc = SortOrder.builderFor(ICEBERG_SCHEMA).asc("id").build();
+    SortOrder sortOrderDesc = SortOrder.builderFor(ICEBERG_SCHEMA).desc("id").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(10, "test", 1.5, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(20, "test", 2.0, true).build();
+
+    byte[] k1Asc = IcebergRowSorter.encodeSortKey(r1, sortOrderAsc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2Asc = IcebergRowSorter.encodeSortKey(r2, sortOrderAsc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    byte[] k1Desc = IcebergRowSorter.encodeSortKey(r1, sortOrderDesc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2Desc = IcebergRowSorter.encodeSortKey(r2, sortOrderDesc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    // Ascending: 10 < 20
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1Asc, k2Asc) < 0);
+
+    // Descending: 10 > 20 (inverted bytes)
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1Desc, k2Desc) > 0);
+  }
+
+  @Test
+  public void testNullOrderingMatrix() throws Exception {
+    Row rNonNull = Row.withSchema(BEAM_SCHEMA).addValues(1, "apple", 1.5, true).build();
+    Row rNull = Row.withSchema(BEAM_SCHEMA).addValues(2, null, 2.0, true).build();
+
+    // 1. ASC, NULLS_FIRST
+    SortOrder ascFirst =
+        SortOrder.builderFor(ICEBERG_SCHEMA).asc("name", NullOrder.NULLS_FIRST).build();
+    byte[] kNonNullAscFirst =
+        IcebergRowSorter.encodeSortKey(rNonNull, ascFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullAscFirst =
+        IcebergRowSorter.encodeSortKey(rNull, ascFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "ASC NULLS_FIRST failed: null should sort before non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullAscFirst, kNonNullAscFirst) < 0);
+
+    // 2. ASC, NULLS_LAST
+    SortOrder ascLast =
+        SortOrder.builderFor(ICEBERG_SCHEMA).asc("name", NullOrder.NULLS_LAST).build();
+    byte[] kNonNullAscLast =
+        IcebergRowSorter.encodeSortKey(rNonNull, ascLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullAscLast =
+        IcebergRowSorter.encodeSortKey(rNull, ascLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "ASC NULLS_LAST failed: null should sort after non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullAscLast, kNonNullAscLast) > 0);
+
+    // 3. DESC, NULLS_FIRST
+    SortOrder descFirst =
+        SortOrder.builderFor(ICEBERG_SCHEMA).desc("name", NullOrder.NULLS_FIRST).build();
+    byte[] kNonNullDescFirst =
+        IcebergRowSorter.encodeSortKey(rNonNull, descFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullDescFirst =
+        IcebergRowSorter.encodeSortKey(rNull, descFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "DESC NULLS_FIRST failed: null should sort before non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullDescFirst, kNonNullDescFirst) > 0);
+
+    // 4. DESC, NULLS_LAST
+    SortOrder descLast =
+        SortOrder.builderFor(ICEBERG_SCHEMA).desc("name", NullOrder.NULLS_LAST).build();
+    byte[] kNonNullDescLast =
+        IcebergRowSorter.encodeSortKey(rNonNull, descLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullDescLast =
+        IcebergRowSorter.encodeSortKey(rNull, descLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "DESC NULLS_LAST failed: null should sort after non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullDescLast, kNonNullDescLast) < 0);
+  }

Review Comment:
   ![critical](https://www.gstatic.com/codereviewagent/critical.svg)
   
   This assertion is incorrect. For `NULLS_LAST`, the null key should be **larger** than the non-null key so that it appears last in an ascending sort. The current test asserts `< 0`, which validates that nulls appear first.
   
   ```java
       assertTrue(
           "DESC NULLS_LAST failed: null should sort after non-null",
           BYTE_ARR_COMPARATOR.compare(kNullDescLast, kNonNullDescLast) > 0);
   ```



##########
sdks/java/io/iceberg/src/test/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorterTest.java:
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.types.Types;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class IcebergRowSorterTest {
+
+  private static final Schema BEAM_SCHEMA =
+      Schema.builder()
+          .addInt32Field("id")
+          .addNullableField("name", Schema.FieldType.STRING)
+          .addNullableField("value", Schema.FieldType.DOUBLE)
+          .addNullableField("active", Schema.FieldType.BOOLEAN)
+          .build();
+
+  private static final org.apache.iceberg.Schema ICEBERG_SCHEMA =
+      new org.apache.iceberg.Schema(
+          Types.NestedField.required(1, "id", Types.IntegerType.get()),
+          Types.NestedField.optional(2, "name", Types.StringType.get()),
+          Types.NestedField.optional(3, "value", Types.DoubleType.get()),
+          Types.NestedField.optional(4, "active", Types.BooleanType.get()));
+
+  private static final Comparator<byte[]> BYTE_ARR_COMPARATOR =
+      org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.primitives.UnsignedBytes
+          .lexicographicalComparator();
+
+  @Test
+  public void testStringKeyEncodingOrder() throws Exception {
+    SortOrder sortOrder = SortOrder.builderFor(ICEBERG_SCHEMA).asc("name").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(1, "apple", 1.5, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(2, "banana", 2.0, true).build();
+    Row r3 = Row.withSchema(BEAM_SCHEMA).addValues(3, "apricot", 3.0, false).build();
+
+    byte[] k1 = IcebergRowSorter.encodeSortKey(r1, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2 = IcebergRowSorter.encodeSortKey(r2, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k3 = IcebergRowSorter.encodeSortKey(r3, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k2) < 0); // apple < banana
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k3) < 0); // apple < apricot
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k3, k2) < 0); // apricot < banana
+  }
+
+  @Test
+  public void testStringCollisionProofing() throws Exception {
+    // Tests that secondary columns don't bleed into primary columns.
+    // Row 1: Primary="abc", Secondary="def"
+    // Row 2: Primary="abcdef", Secondary=null
+    // In raw byte concatenation, both could equal "abcdef\0" if delimiters or escaping fail.
+    SortOrder sortOrder = SortOrder.builderFor(ICEBERG_SCHEMA).asc("name").asc("value").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(1, "abc", 1.0, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(2, "abcdef", null, true).build();
+
+    byte[] k1 = IcebergRowSorter.encodeSortKey(r1, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2 = IcebergRowSorter.encodeSortKey(r2, sortOrder, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    // "abc" must sort lexicographically before "abcdef"
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1, k2) < 0);
+  }
+
+  @Test
+  public void testDescInversion() throws Exception {
+    SortOrder sortOrderAsc = SortOrder.builderFor(ICEBERG_SCHEMA).asc("id").build();
+    SortOrder sortOrderDesc = SortOrder.builderFor(ICEBERG_SCHEMA).desc("id").build();
+
+    Row r1 = Row.withSchema(BEAM_SCHEMA).addValues(10, "test", 1.5, true).build();
+    Row r2 = Row.withSchema(BEAM_SCHEMA).addValues(20, "test", 2.0, true).build();
+
+    byte[] k1Asc = IcebergRowSorter.encodeSortKey(r1, sortOrderAsc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2Asc = IcebergRowSorter.encodeSortKey(r2, sortOrderAsc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    byte[] k1Desc = IcebergRowSorter.encodeSortKey(r1, sortOrderDesc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] k2Desc = IcebergRowSorter.encodeSortKey(r2, sortOrderDesc, ICEBERG_SCHEMA, BEAM_SCHEMA);
+
+    // Ascending: 10 < 20
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1Asc, k2Asc) < 0);
+
+    // Descending: 10 > 20 (inverted bytes)
+    assertTrue(BYTE_ARR_COMPARATOR.compare(k1Desc, k2Desc) > 0);
+  }
+
+  @Test
+  public void testNullOrderingMatrix() throws Exception {
+    Row rNonNull = Row.withSchema(BEAM_SCHEMA).addValues(1, "apple", 1.5, true).build();
+    Row rNull = Row.withSchema(BEAM_SCHEMA).addValues(2, null, 2.0, true).build();
+
+    // 1. ASC, NULLS_FIRST
+    SortOrder ascFirst =
+        SortOrder.builderFor(ICEBERG_SCHEMA).asc("name", NullOrder.NULLS_FIRST).build();
+    byte[] kNonNullAscFirst =
+        IcebergRowSorter.encodeSortKey(rNonNull, ascFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullAscFirst =
+        IcebergRowSorter.encodeSortKey(rNull, ascFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "ASC NULLS_FIRST failed: null should sort before non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullAscFirst, kNonNullAscFirst) < 0);
+
+    // 2. ASC, NULLS_LAST
+    SortOrder ascLast =
+        SortOrder.builderFor(ICEBERG_SCHEMA).asc("name", NullOrder.NULLS_LAST).build();
+    byte[] kNonNullAscLast =
+        IcebergRowSorter.encodeSortKey(rNonNull, ascLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullAscLast =
+        IcebergRowSorter.encodeSortKey(rNull, ascLast, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "ASC NULLS_LAST failed: null should sort after non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullAscLast, kNonNullAscLast) > 0);
+
+    // 3. DESC, NULLS_FIRST
+    SortOrder descFirst =
+        SortOrder.builderFor(ICEBERG_SCHEMA).desc("name", NullOrder.NULLS_FIRST).build();
+    byte[] kNonNullDescFirst =
+        IcebergRowSorter.encodeSortKey(rNonNull, descFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    byte[] kNullDescFirst =
+        IcebergRowSorter.encodeSortKey(rNull, descFirst, ICEBERG_SCHEMA, BEAM_SCHEMA);
+    assertTrue(
+        "DESC NULLS_FIRST failed: null should sort before non-null",
+        BYTE_ARR_COMPARATOR.compare(kNullDescFirst, kNonNullDescFirst) > 0);
+

Review Comment:
   ![critical](https://www.gstatic.com/codereviewagent/critical.svg)
   
   This assertion is incorrect. For `NULLS_FIRST`, the null key should be **smaller** than the non-null key so that it appears first in an ascending sort. The current test asserts `> 0`, which validates that nulls appear last. This matches the bug in the implementation.
   
   ```java
       assertTrue(
           "DESC NULLS_FIRST failed: null should sort before non-null",
           BYTE_ARR_COMPARATOR.compare(kNullDescFirst, kNonNullDescFirst) < 0);
   ```



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+    for (SortField field : sortOrder.fields()) {
+      String colName = icebergSchema.findColumnName(field.sourceId());
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        Object icebergVal =
+            IcebergUtils.beamRowToIcebergRecord(icebergSchema, row).getField(colName);

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   `IcebergUtils.beamRowToIcebergRecord` is a computationally expensive operation as it creates a new `GenericRecord` and copies all fields from the Beam `Row`. Calling this inside a loop for every transformed sort field for every row will cause severe performance degradation. You should convert the row at most once per row, or ideally, only extract and convert the specific fields required for sorting.



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+    for (SortField field : sortOrder.fields()) {
+      String colName = icebergSchema.findColumnName(field.sourceId());

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Looking up the column name by `sourceId` for every field in every row is redundant. These mappings should be pre-calculated once before iterating over the rows to improve performance.



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+    for (SortField field : sortOrder.fields()) {
+      String colName = icebergSchema.findColumnName(field.sourceId());
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        Object icebergVal =
+            IcebergUtils.beamRowToIcebergRecord(icebergSchema, row).getField(colName);
+        if (icebergVal != null) {
+          val = field.transform().apply(icebergVal);
+        } else {
+          val = null;
+        }
+      }
+
+      boolean isNull = (val == null);
+      boolean isDesc = (field.direction() == SortDirection.DESC);
+      boolean nullsFirst = (field.nullOrder() == NullOrder.NULLS_FIRST);
+
+      // Determine correct header prefix to fulfill the NullOrder contracts
+      byte prefixByte;
+      if (isNull) {
+        if (isDesc) {
+          // Descending: High byte keys sort first.
+          // If Nulls First -> Null gets highest byte (0xFF)
+          // If Nulls Last -> Null gets lowest byte (0x00)
+          prefixByte = nullsFirst ? (byte) 0xFF : (byte) 0x00;
+        } else {
+          // Ascending: Low byte keys sort first.
+          // If Nulls First -> Null gets lowest byte (0x00)
+          // If Nulls Last -> Null gets highest byte (0xFF)
+          prefixByte = nullsFirst ? (byte) 0x00 : (byte) 0xFF;
+        }
+      } else {
+        if (isDesc) {
+          // If non-null and Descending, use a neutral value that sits opposite to the null byte
+          prefixByte = nullsFirst ? (byte) 0xFE : (byte) 0x01;
+        } else {
+          prefixByte = nullsFirst ? (byte) 0x01 : (byte) 0x00;
+        }
+      }
+
+      baos.write(prefixByte);
+
+      if (!isNull) {
+        byte[] valBytes = encodeValue(val);
+        // Bitwise invert non-null bytes to sort descending lexicographically
+        if (isDesc) {
+          for (int i = 0; i < valBytes.length; i++) {
+            valBytes[i] = (byte) ~valBytes[i];
+          }
+        }
+        baos.write(valBytes);
+      }
+    }
+
+    return baos.toByteArray();
+  }
+
+  @SuppressWarnings("JavaUtilDate")
+  private static byte[] encodeValue(@Nullable Object val) throws IOException {
+    if (val == null) {
+      return new byte[0];
+    }
+    if (val instanceof String) {
+      return encodeString((String) val);
+    } else if (val instanceof Integer) {
+      int v = (Integer) val;
+      return ByteBuffer.allocate(4).putInt(v ^ Integer.MIN_VALUE).array();
+    } else if (val instanceof Long) {
+      long v = (Long) val;
+      return ByteBuffer.allocate(8).putLong(v ^ Long.MIN_VALUE).array();
+    } else if (val instanceof Float) {
+      int bits = Float.floatToIntBits((Float) val);
+      bits = (bits >= 0) ? (bits ^ Integer.MIN_VALUE) : ~bits;
+      return ByteBuffer.allocate(4).putInt(bits).array();
+    } else if (val instanceof Double) {
+      long bits = Double.doubleToLongBits((Double) val);
+      bits = (bits >= 0) ? (bits ^ Long.MIN_VALUE) : ~bits;
+      return ByteBuffer.allocate(8).putLong(bits).array();

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Allocating a new `ByteBuffer` and a new `byte[]` for every numeric value in every row creates significant GC pressure. Consider using bit manipulation directly into a reusable buffer or the main `ByteArrayOutputStream` to improve throughput.



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/WriteGroupedRowsToFiles.java:
##########
@@ -101,11 +104,22 @@ public void processElement(
       IcebergDestination destination = dynamicDestinations.instantiateDestination(tableIdentifier);
       WindowedValue<IcebergDestination> windowedDestination =
           WindowedValues.of(destination, window.maxTimestamp(), window, paneInfo);
+      Iterator<Row> rowIt = element.getValue().iterator();
+      if (!rowIt.hasNext()) {
+        return;
+      }
+      Row firstRow = rowIt.next();
+      Schema dataSchema = firstRow.getSchema();

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Consuming the first element of the `Iterable` to extract the schema is risky. If the `Iterable` is not re-iterable (which can happen with certain Beam runner implementations), the first row will be lost for the subsequent sorting and writing steps. It is safer to pass the schema into the `DoFn` or use a method that doesn't consume the iterator.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38406:
URL: https://github.com/apache/beam/pull/38406#issuecomment-5664183704

   This pull request has been closed due to lack of activity. If you think that is incorrect, or the pull request requires review, you can revive the PR at any time.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3203010493


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+    for (SortField field : sortOrder.fields()) {
+      String colName = icebergSchema.findColumnName(field.sourceId());
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        Object icebergVal =
+            IcebergUtils.beamRowToIcebergRecord(icebergSchema, row).getField(colName);
+        if (icebergVal != null) {
+          val = field.transform().apply(icebergVal);
+        } else {
+          val = null;
+        }
+      }
+
+      boolean isNull = (val == null);
+      boolean isDesc = (field.direction() == SortDirection.DESC);
+      boolean nullsFirst = (field.nullOrder() == NullOrder.NULLS_FIRST);
+
+      // Determine correct header prefix to fulfill the NullOrder contracts
+      byte prefixByte;
+      if (isNull) {
+        if (isDesc) {
+          // Descending: High byte keys sort first.
+          // If Nulls First -> Null gets highest byte (0xFF)
+          // If Nulls Last -> Null gets lowest byte (0x00)
+          prefixByte = nullsFirst ? (byte) 0xFF : (byte) 0x00;
+        } else {
+          // Ascending: Low byte keys sort first.
+          // If Nulls First -> Null gets lowest byte (0x00)
+          // If Nulls Last -> Null gets highest byte (0xFF)
+          prefixByte = nullsFirst ? (byte) 0x00 : (byte) 0xFF;
+        }
+      } else {
+        if (isDesc) {
+          // If non-null and Descending, use a neutral value that sits opposite to the null byte
+          prefixByte = nullsFirst ? (byte) 0xFE : (byte) 0x01;
+        } else {
+          prefixByte = nullsFirst ? (byte) 0x01 : (byte) 0x00;
+        }
+      }

Review Comment:
   Fix adopted



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "ahmedabu98 (via GitHub)" <gi...@apache.org>.
ahmedabu98 commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3203659945


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    List<SortField> fields = sortOrder.fields();
+    String[] columnNames = new String[fields.size()];
+    for (int i = 0; i < fields.size(); i++) {
+      columnNames[i] = icebergSchema.findColumnName(fields.get(i).sourceId());
+    }
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, columnNames, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();

Review Comment:
   Let's to clear and reuse the output stream object instead of creating a new one each iteration



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    List<SortField> fields = sortOrder.fields();
+    String[] columnNames = new String[fields.size()];
+    for (int i = 0; i < fields.size(); i++) {
+      columnNames[i] = icebergSchema.findColumnName(fields.get(i).sourceId());
+    }
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, columnNames, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      String[] columnNames,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();

Review Comment:
   Same thing here, let's create `ByteArrayOutputStream` it in the caller function and pass it in here. Each call should reset and use the same one for efficiency



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    List<SortField> fields = sortOrder.fields();
+    String[] columnNames = new String[fields.size()];
+    for (int i = 0; i < fields.size(); i++) {
+      columnNames[i] = icebergSchema.findColumnName(fields.get(i).sourceId());
+    }
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, columnNames, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      String[] columnNames,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+    List<SortField> fields = sortOrder.fields();
+    org.apache.iceberg.data.Record icebergRecord = null;
+
+    for (int i = 0; i < fields.size(); i++) {
+      SortField field = fields.get(i);
+      String colName = columnNames[i];
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        if (icebergRecord == null) {
+          icebergRecord = IcebergUtils.beamRowToIcebergRecord(icebergSchema, row);
+        }
+        Object icebergVal = icebergRecord.getField(colName);
+        if (icebergVal != null) {
+          val = field.transform().apply(icebergVal);
+        } else {
+          val = null;
+        }
+      }
+
+      boolean isNull = (val == null);
+      boolean isDesc = (field.direction() == SortDirection.DESC);
+      boolean nullsFirst = (field.nullOrder() == NullOrder.NULLS_FIRST);
+
+      // Determine correct header prefix to fulfill the NullOrder contracts
+      byte prefixByte;
+      if (isNull) {
+        prefixByte = nullsFirst ? (byte) 0x00 : (byte) 0xFF;
+      } else {
+        prefixByte = nullsFirst ? (byte) 0x01 : (byte) 0x00;
+      }
+
+      baos.write(prefixByte);
+
+      if (!isNull) {
+        writeValue(val, baos, isDesc);
+      }
+    }
+
+    return baos.toByteArray();
+  }
+
+  private static void writeInt(int v, ByteArrayOutputStream baos, boolean invert) {
+    byte b3 = (byte) (v >>> 24);
+    byte b2 = (byte) (v >>> 16);
+    byte b1 = (byte) (v >>> 8);
+    byte b0 = (byte) v;
+    if (invert) {
+      baos.write(~b3);
+      baos.write(~b2);
+      baos.write(~b1);
+      baos.write(~b0);
+    } else {
+      baos.write(b3);
+      baos.write(b2);
+      baos.write(b1);
+      baos.write(b0);
+    }
+  }
+
+  private static void writeLong(long v, ByteArrayOutputStream baos, boolean invert) {
+    byte b7 = (byte) (v >>> 56);
+    byte b6 = (byte) (v >>> 48);
+    byte b5 = (byte) (v >>> 40);
+    byte b4 = (byte) (v >>> 32);
+    byte b3 = (byte) (v >>> 24);
+    byte b2 = (byte) (v >>> 16);
+    byte b1 = (byte) (v >>> 8);
+    byte b0 = (byte) v;
+    if (invert) {
+      baos.write(~b7);
+      baos.write(~b6);
+      baos.write(~b5);
+      baos.write(~b4);
+      baos.write(~b3);
+      baos.write(~b2);
+      baos.write(~b1);
+      baos.write(~b0);
+    } else {
+      baos.write(b7);
+      baos.write(b6);
+      baos.write(b5);
+      baos.write(b4);
+      baos.write(b3);
+      baos.write(b2);
+      baos.write(b1);
+      baos.write(b0);
+    }
+  }
+
+  @SuppressWarnings("JavaUtilDate")
+  private static void writeValue(Object val, ByteArrayOutputStream baos, boolean invert)
+      throws IOException {
+    if (val instanceof String) {
+      writeString((String) val, baos, invert);
+    } else if (val instanceof Integer) {
+      int v = (Integer) val;
+      writeInt(v ^ Integer.MIN_VALUE, baos, invert);
+    } else if (val instanceof Long) {
+      long v = (Long) val;
+      writeLong(v ^ Long.MIN_VALUE, baos, invert);
+    } else if (val instanceof Float) {
+      int bits = Float.floatToIntBits((Float) val);
+      bits = (bits >= 0) ? (bits ^ Integer.MIN_VALUE) : ~bits;
+      writeInt(bits, baos, invert);
+    } else if (val instanceof Double) {
+      long bits = Double.doubleToLongBits((Double) val);
+      bits = (bits >= 0) ? (bits ^ Long.MIN_VALUE) : ~bits;
+      writeLong(bits, baos, invert);
+    } else if (val instanceof Boolean) {
+      byte b = ((Boolean) val) ? (byte) 0x01 : (byte) 0x00;
+      baos.write(invert ? ~b : b);
+    } else if (val instanceof byte[]) {
+      writeByteArray((byte[]) val, baos, invert);
+    } else if (val instanceof ByteBuffer) {
+      writeByteArray(((ByteBuffer) val).array(), baos, invert);
+    } else if (val instanceof ReadableInstant) {
+      long enc = ((ReadableInstant) val).getMillis() ^ Long.MIN_VALUE;
+      writeLong(enc, baos, invert);
+    } else if (val instanceof Instant) {
+      long enc = ((Instant) val).toEpochMilli() ^ Long.MIN_VALUE;
+      writeLong(enc, baos, invert);
+    } else if (val instanceof Date) {
+      long enc = ((Date) val).getTime() ^ Long.MIN_VALUE;
+      writeLong(enc, baos, invert);
+    } else {
+      writeString(val.toString(), baos, invert);
+    }

Review Comment:
   Does Iceberg support sorting on complex types (lists, maps, structs) ?
   
   We should either 1) add support for that or 2) throw an Unsupported Exception early on.
   
   I'd rather throw an error than fall back on String because it may lead to unexpected sorting behavior for some types.



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    List<SortField> fields = sortOrder.fields();
+    String[] columnNames = new String[fields.size()];
+    for (int i = 0; i < fields.size(); i++) {
+      columnNames[i] = icebergSchema.findColumnName(fields.get(i).sourceId());
+    }
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, columnNames, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      String[] columnNames,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+    List<SortField> fields = sortOrder.fields();
+    org.apache.iceberg.data.Record icebergRecord = null;
+
+    for (int i = 0; i < fields.size(); i++) {
+      SortField field = fields.get(i);
+      String colName = columnNames[i];
+      Object val = row.getValue(colName);
+
+      if (!field.transform().isIdentity()) {
+        if (icebergRecord == null) {
+          icebergRecord = IcebergUtils.beamRowToIcebergRecord(icebergSchema, row);
+        }
+        Object icebergVal = icebergRecord.getField(colName);
+        if (icebergVal != null) {
+          val = field.transform().apply(icebergVal);

Review Comment:
   This is pretty heavy to extract the transformed value. Will make writes pretty slow
   
   Can we apply the transform to the Beam field object directly? If not, maybe we need a "beam object to iceberg object" conversion. IcebergUtils.copyFieldIntoRecord does something similar, but we may need to refactor it a little to fit this use case.



##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/WritePartitionedRowsToFiles.java:
##########
@@ -130,7 +130,10 @@ public void processElement(
       RecordWriter writer =
           new RecordWriter(table, destination.getFileFormat(), fileName, partitionData);
       try {
-        for (Row row : element.getValue()) {
+        Iterable<Row> sortedOrUnsortedRows =
+            IcebergRowSorter.sortRows(
+                element.getValue(), table.sortOrder(), table.schema(), dataSchema);
+        for (Row row : sortedOrUnsortedRows) {

Review Comment:
   We should only be sorting if the user asked us to. 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #38406:
URL: https://github.com/apache/beam/pull/38406#issuecomment-4398534076

   ## Summary of Changes
   
   Hello, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
   
   This pull request introduces native support for sorted writes in IcebergIO. By integrating a memory-safe, disk-spilling sorter, the implementation ensures that data written to sorted Iceberg tables is perfectly ordered, which significantly improves performance and reduces resource contention by minimizing concurrent file writers. The changes include a comprehensive byte-encoding protocol for lexicographical sorting and updated write-path logic to handle sorted tables efficiently.
   
   ### Highlights
   
   * **Sorted Writing Support**: Implemented high-performance sorted writing in IcebergIO by dynamically pre-sorting incoming rows based on the target table's SortOrder.
   * **Memory-Safe Sorter**: Introduced IcebergRowSorter, which leverages Beam's BufferedExternalSorter to spill data to disk when memory limits are exceeded, preventing OOM errors.
   * **Lexicographical Encoding**: Added a robust byte-encoding mechanism that supports complex composite keys, null-ordering contracts, and type-specific sorting (including algebraic number handling).
   * **Write Path Optimization**: Updated WriteUngroupedRowsToFiles and WriteGroupedRowsToFiles to automatically detect table sort requirements and route data through the sorting path.
   
   <details>
   <summary><b>New Features</b></summary>
   
   🧠 You can now enable **Memory** (public preview) to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
   </details>
   
   <details>
   <summary><b>Using Gemini Code Assist</b></summary>
   <br>
   
   The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
   
   <b>Invoking Gemini</b>
   
   You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
   
   Feature | Command | Description
   --- | --- | ---
   Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
   Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
   Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
   Help | `/gemini help` | Displays a list of available commands.
   
   <b>Customization</b>
   
   To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
   
   <b>Limitations & Feedback</b>
   
   Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
   </details>
   
   
   [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3208811128


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/WritePartitionedRowsToFiles.java:
##########
@@ -130,7 +130,10 @@ public void processElement(
       RecordWriter writer =
           new RecordWriter(table, destination.getFileFormat(), fileName, partitionData);
       try {
-        for (Row row : element.getValue()) {
+        Iterable<Row> sortedOrUnsortedRows =
+            IcebergRowSorter.sortRows(
+                element.getValue(), table.sortOrder(), table.schema(), dataSchema);
+        for (Row row : sortedOrUnsortedRows) {

Review Comment:
   IcebergRowSorter.sortRows() will only sort if the table schema defines any sort configuration or else, it does nothing.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3203061634


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/IcebergRowSorter.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+package org.apache.beam.sdk.io.iceberg;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import java.util.Iterator;
+import org.apache.beam.sdk.coders.RowCoder;
+import org.apache.beam.sdk.extensions.sorter.BufferedExternalSorter;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.Row;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.SortOrder;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.ReadableInstant;
+
+/**
+ * A utility class to sort Beam {@link Row}s based on an Iceberg {@link SortOrder}. Leverages {@link
+ * BufferedExternalSorter} to spill to local disk when elements exceed memory limit.
+ */
+class IcebergRowSorter implements Serializable {
+
+  public static Iterable<Row> sortRows(
+      Iterable<Row> rows,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema) {
+
+    if (sortOrder == null || !sortOrder.isSorted()) {
+      return rows;
+    }
+
+    BufferedExternalSorter.Options sorterOptions = BufferedExternalSorter.options();
+    BufferedExternalSorter sorter = BufferedExternalSorter.create(sorterOptions);
+    RowCoder rowCoder = RowCoder.of(beamSchema);
+
+    try {
+      for (Row row : rows) {
+        byte[] keyBytes = encodeSortKey(row, sortOrder, icebergSchema, beamSchema);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        rowCoder.encode(row, baos);
+        byte[] valBytes = baos.toByteArray();
+        sorter.add(KV.of(keyBytes, valBytes));
+      }
+
+      Iterable<KV<byte[], byte[]>> sortedKVs = sorter.sort();
+      return new Iterable<Row>() {
+        @Override
+        public Iterator<Row> iterator() {
+          final Iterator<KV<byte[], byte[]>> it = sortedKVs.iterator();
+          return new Iterator<Row>() {
+            @Override
+            public boolean hasNext() {
+              return it.hasNext();
+            }
+
+            @Override
+            public Row next() {
+              KV<byte[], byte[]> next = it.next();
+              try {
+                ByteArrayInputStream bais = new ByteArrayInputStream(next.getValue());
+                return rowCoder.decode(bais);
+              } catch (IOException e) {
+                throw new RuntimeException("Failed to decode Row during sorting", e);
+              }
+            }
+          };
+        }
+      };
+
+    } catch (IOException e) {
+      throw new RuntimeException("Failed to sort rows with external sorter", e);
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  public static byte[] encodeSortKey(
+      Row row,
+      SortOrder sortOrder,
+      Schema icebergSchema,
+      org.apache.beam.sdk.schemas.Schema beamSchema)
+      throws IOException {
+
+    ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+    for (SortField field : sortOrder.fields()) {
+      String colName = icebergSchema.findColumnName(field.sourceId());

Review Comment:
   This has been fixed by pre-calculating the column names array exactly once per sorting operation, completely eliminating redundant schema metadata lookups in the row-level loops.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Implement high-performance sorted writing support in IcebergIO [beam]

Posted by "atognolag (via GitHub)" <gi...@apache.org>.
atognolag commented on code in PR #38406:
URL: https://github.com/apache/beam/pull/38406#discussion_r3203056222


##########
sdks/java/io/iceberg/src/main/java/org/apache/beam/sdk/io/iceberg/WriteGroupedRowsToFiles.java:
##########
@@ -101,11 +104,22 @@ public void processElement(
       IcebergDestination destination = dynamicDestinations.instantiateDestination(tableIdentifier);
       WindowedValue<IcebergDestination> windowedDestination =
           WindowedValues.of(destination, window.maxTimestamp(), window, paneInfo);
+      Iterator<Row> rowIt = element.getValue().iterator();
+      if (!rowIt.hasNext()) {
+        return;
+      }
+      Row firstRow = rowIt.next();
+      Schema dataSchema = firstRow.getSchema();

Review Comment:
   This issue was resolved by statically extracting the schema from the PCollection's Coder during the pipeline construct/expansion phase, rather than dynamically inside the DoFn process loop.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org