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

Gabriel39 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 74d92ecdbb1 [fix](iceberg) Record only executed data file sort orders 
(#70615)
74d92ecdbb1 is described below

commit 74d92ecdbb134597c18faf12f5c654f601e6576c
Author: daidai <[email protected]>
AuthorDate: Tue Nov 24 15:33:32 2026 +0800

    [fix](iceberg) Record only executed data file sort orders (#70615)
    
    ### Background
    
    Iceberg tables can declare a default sort order, while each data file
    records the order that its writer actually executed. Doris builds
    write-sort expressions in FE and sends them to the BE data writer, then
    converts the reported files into Iceberg manifest entries.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #60540 (introduced the original sort support)
    PR Type: Bugfix
    
    Problem Summary:
    
    Doris skipped transform and nested sort fields when building write keys
    but still recorded the complete table sort order on the resulting data
    files. UPDATE/MERGE data writers also do not execute the transmitted
    sort_fields. This change records an order only when the actual data sink
    executes the complete supported order; other writes are recorded as
    unsorted without changing the table's default order.
    
    ### Details
    
    - **Change map:** 189 changed production lines and 556 changed test
    lines; no generated files or documentation changes. The production
    change adds a shared sort-order resolver, binds the actual file order
    once per transaction, and passes that decision through every data-file
    commit path. Most of the diff adds plan, resolver, helper, and
    manifest-commit regression coverage.
    - **Frequency:** Writes to tables with transform/nested sort keys, and
    UPDATE/MERGE writes to sorted tables, could create misleading file-order
    metadata.
    - **Root cause:** Planning silently dropped unsupported fields, while
    commit inferred a file's order from the table default. The row-level
    sink's sort_fields are not consumed by its data writer.
    - **Why existing tests missed it:** Plan-parity tests explicitly
    accepted an empty bucket-sort key list. Metadata tests checked
    table-order pinning separately from the actual sink plan.
    - **Fix:** Resolve the entire order before sorting; require complete
    sort_info including matching direction and NULL ordering before
    preserving a nonzero ID. Pin the effective order for shared REWRITE
    groups, reject inconsistent group decisions, and explicitly pass the
    pinned order to INSERT/OVERWRITE, REWRITE, and row-level data-file
    conversion. Keep the original table order for metadata fences.
    - **Other paths and branches:** CTAS shares the INSERT path. DELETE and
    delete-only MERGE retain their independent delete-file handling.
    branch-4.2 is affected, but its legacy FE layout requires an adapted
    backport rather than a direct cherry-pick of this connector patch.
    - **Behavior change:** Unsupported complete orders use the existing
    unsorted writer and record order 0. UPDATE/MERGE data files record order
    0 until their data writer executes a complete sort. Supported identity
    orders remain available for INSERT/OVERWRITE/REWRITE.
    
    ### Testing
    
    - Before the planner fix,
    `IcebergWritePlanProviderTest#getWriteSortColumnsNullForBucketSortOrder`
    failed with `expected: <null> but was: <[]>` using the original planner
    source.
    - After the fix, the project preset `./run-fe-ut.sh --run
    
'org.apache.doris.connector.iceberg.IcebergWriteSortOrderTest,org.apache.doris.connector.iceberg.IcebergWritePlanProviderTest,org.apache.doris.connector.iceberg.IcebergWriterHelperTest,org.apache.doris.connector.iceberg.IcebergConnectorTransactionTest'`
    passed all 275 selected tests locally.
    - The plan-to-transaction tests inspect the actual committed manifest
    metadata across 14 INSERT/OVERWRITE/REWRITE/UPDATE/MERGE cases,
    including identity, bucket, truncate, and nested orders.
    - Module Checkstyle passed with 0 violations. `git diff --check` passed.
    
    Validation covers plans and committed manifest metadata. Physical
    data-file row-order and cluster regression tests were not run.
    
    ### Release note
    
    New Iceberg data files are recorded as unsorted when Doris does not
    execute the complete table sort order, including unsupported
    transform/nested orders and current UPDATE/MERGE data writers. Supported
    complete identity sorting remains available. Table sort definitions and
    historical file metadata are preserved.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details).
    - Does this need documentation: No.
    - Pre-submission status: Partially verified: local FE tests and
    Checkstyle; cluster regression tests pending.
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6).
    - Generated: Production changes, tests, and this description.
    - Human review: Pending maintainer review.
---
 .../iceberg/IcebergConnectorTransaction.java       |  27 ++-
 .../iceberg/IcebergWritePlanProvider.java          |  86 ++++----
 .../connector/iceberg/IcebergWriteSortOrder.java   |  62 ++++++
 .../connector/iceberg/IcebergWriterHelper.java     |  14 +-
 .../iceberg/IcebergConnectorTransactionTest.java   | 130 ++++++++++++
 .../iceberg/IcebergWritePlanProviderTest.java      | 229 +++++++++++++++++++--
 .../iceberg/IcebergWriteSortOrderTest.java         | 144 +++++++++++++
 .../connector/iceberg/IcebergWriterHelperTest.java |  53 ++++-
 8 files changed, 667 insertions(+), 78 deletions(-)

diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorTransaction.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorTransaction.java
index b3068188fad..933897cfbe5 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorTransaction.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorTransaction.java
@@ -51,6 +51,7 @@ import org.apache.iceberg.RowDelta;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.Snapshot;
 import org.apache.iceberg.SnapshotRef;
+import org.apache.iceberg.SortOrder;
 import org.apache.iceberg.StaticTableOperations;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.TableMetadata;
@@ -179,6 +180,10 @@ public class IcebergConnectorTransaction implements 
ConnectorTransaction, Rewrit
     private Map<String, String> staticPartitionValues = Collections.emptyMap();
     private String branchName;
     private IcebergWriteSchemaContext writeSchemaContext;
+    // The default is deliberately unsorted until sink planning proves that it 
executes a complete order.
+    private volatile SortOrder fileSortOrder = SortOrder.unsorted();
+    // Protected by beginLock: all groups of a shared rewrite transaction must 
use the same file order.
+    private boolean fileSortOrderBound;
     // The snapshot pinned at begin time for DELETE/MERGE and OVERWRITE (null 
for INSERT). Consumed by the
     // commit validation suite (validateFromSnapshot).
     private Long baseSnapshotId;
@@ -660,6 +665,18 @@ public class IcebergConnectorTransaction implements 
ConnectorTransaction, Rewrit
         }
     }
 
+    void bindFileSortOrder(SortOrder order) {
+        synchronized (beginLock) {
+            if (fileSortOrderBound) {
+                Preconditions.checkState(fileSortOrder.orderId() == 
order.orderId() && fileSortOrder.sameOrder(order),
+                        "Iceberg transaction %s file sort order changed 
between write groups", transactionId);
+            } else {
+                fileSortOrder = order;
+                fileSortOrderBound = true;
+            }
+        }
+    }
+
     /**
      * Rejects a fragment whose file is not recorded under a location a sink 
of this write carries. BE writes
      * through the normalized location (s3://b/db/t/data for an oss:// table) 
and must report the table's own
@@ -846,8 +863,8 @@ public class IcebergConnectorTransaction implements 
ConnectorTransaction, Rewrit
             return Collections.emptyList();
         }
         WriteResult writeResult = writeSchemaContext == null
-                ? 
IcebergWriterHelper.convertToWriterResult(transaction.table(), commitDataList, 
zone)
-                : 
IcebergWriterHelper.convertToWriterResult(writeSchemaContext, commitDataList, 
zone);
+                ? 
IcebergWriterHelper.convertToWriterResult(transaction.table(), fileSortOrder, 
commitDataList, zone)
+                : 
IcebergWriterHelper.convertToWriterResult(writeSchemaContext, fileSortOrder, 
commitDataList, zone);
         List<WriteResult> results = new ArrayList<>(1);
         results.add(writeResult);
         return results;
@@ -893,7 +910,7 @@ public class IcebergConnectorTransaction implements 
ConnectorTransaction, Rewrit
             return;
         }
         WriteResult writeResult =
-                IcebergWriterHelper.convertToWriterResult(transaction.table(), 
commitDataList, zone);
+                IcebergWriterHelper.convertToWriterResult(transaction.table(), 
fileSortOrder, commitDataList, zone);
         synchronized (filesToAdd) {
             filesToAdd.addAll(Arrays.asList(writeResult.dataFiles()));
         }
@@ -1153,9 +1170,9 @@ public class IcebergConnectorTransaction implements 
ConnectorTransaction, Rewrit
         if (!dataCommitData.isEmpty()) {
             WriteResult writeResult = writeSchemaContext == null
                     ? IcebergWriterHelper.convertToWriterResult(
-                            transaction.table(), dataCommitData, zone)
+                            transaction.table(), fileSortOrder, 
dataCommitData, zone)
                     : IcebergWriterHelper.convertToWriterResult(
-                            writeSchemaContext, dataCommitData, zone);
+                            writeSchemaContext, fileSortOrder, dataCommitData, 
zone);
             dataFiles.addAll(Arrays.asList(writeResult.dataFiles()));
         }
 
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWritePlanProvider.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWritePlanProvider.java
index 011ea5deff7..1a050c55fdb 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWritePlanProvider.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWritePlanProvider.java
@@ -236,8 +236,21 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
         Map<String, List<TIcebergDeleteFileDesc>> rewritableDeletes =
                 IcebergStatementScope.rewritableDeleteSupply(session);
 
+        if (writeOp == WriteOperation.REWRITE) {
+            schemaContext = IcebergWriteSchemaContext.create(table, 
tableHandle.getTableName(), Optional.empty(),
+                    mappingVarbinaryEnabled(), mappingTimestampTzEnabled());
+            validateVariantWrite(handle, schemaContext);
+            validateNestedPartitionWriteCompatibility(handle, schemaContext);
+        }
         TDataSink dataSink = buildDataSink(writeContext.getWriteOperation(), 
table, tableHandle, handle,
                 rewritableDeletes, schemaContext);
+        SortOrder fileSortOrder = SortOrder.unsorted();
+        if (dataSink.getType() == TDataSinkType.ICEBERG_TABLE_SINK) {
+            fileSortOrder = 
IcebergWriteSortOrder.fileSortOrder(schemaContext.getSchema(),
+                    schemaContext.getSortOrder(), 
dataSink.getIcebergTableSink().getSortInfo());
+        }
+        // Row-level sinks do not execute sort_info, so their replacement data 
files remain unsorted.
+        transaction.bindFileSortOrder(fileSortOrder);
         // BE reports every file of the sink under the raw location the sink 
carries, whichever writer
         // produced it; the transaction rejects a reported file anywhere else.
         commitLocationsOf(dataSink).forEach(transaction::addCommitLocation);
@@ -279,7 +292,7 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
                 // rewritableDeletes supply does not apply to rewrite (it 
deals with no position deletes), and
                 // is already evicted above.
                 TDataSink dataSink = new 
TDataSink(TDataSinkType.ICEBERG_TABLE_SINK);
-                dataSink.setIcebergTableSink(buildRewriteSink(table, 
tableHandle, handle));
+                dataSink.setIcebergTableSink(buildRewriteSink(table, 
tableHandle, handle, schemaContext));
                 return dataSink;
             }
             default:
@@ -495,9 +508,7 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
         IcebergTableHandle tableHandle = (IcebergTableHandle) 
handle.getTableHandle();
         output.append(prefix).append("  ICEBERG TABLE: ")
                 
.append(tableHandle.getDbName()).append(".").append(tableHandle.getTableName()).append("\n");
-        // Legacy IcebergTableSink also rendered the table's write sort order 
(getSortOrderSql) when sorted;
-        // reuse the SHOW CREATE TABLE renderer so EXPLAIN INSERT surfaces the 
same "ORDER BY (...)" the BE
-        // write applies (getWriteSortColumns), keeping EXPLAIN and SHOW 
CREATE TABLE consistent.
+        // Display the table's declared default order, which is preserved even 
when this write is unsorted.
         String sortClause = 
IcebergConnectorMetadata.buildShowSortClause(resolveTable(session, 
tableHandle));
         if (!sortClause.isEmpty()) {
             output.append(prefix).append("  ").append(sortClause).append("\n");
@@ -506,10 +517,8 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
 
     /**
      * Declares the table's write-side sort columns (a {@code WRITE ORDERED 
BY} sort order) so the engine
-     * can build the {@code TSortInfo} from the bound sink output. Ports legacy
-     * {@code IcebergTableSink.bindDataSink}'s sort-order loop: only identity 
sort fields contribute, each
-     * mapped from its iceberg field id to the column's position in the table 
schema (1:1 with the sink
-     * output). An unsorted table yields an empty list (no sort).
+     * can build the {@code TSortInfo} from the bound sink output. Only 
complete orders consisting of
+     * top-level identity fields are executable. Other orders return null to 
select an unsorted writer.
      */
     @Override
     public List<ConnectorWriteSortColumn> getWriteSortColumns(ConnectorSession 
session,
@@ -525,18 +534,15 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
                 IcebergStatementScope.activeWriteSchema(
                         session, handle.getDbName(), handle.getTableName());
         Table table = active.isPresent() ? null : resolveTable(session, 
handle);
-        SortOrder sortOrder = active.isPresent()
-                ? active.get().getSortOrder() : table.sortOrder();
+        Schema schema = active.isPresent() ? active.get().getSchema() : 
table.schema();
+        SortOrder sortOrder = IcebergWriteSortOrder.supportedOrder(schema,
+                active.isPresent() ? active.get().getSortOrder() : 
table.sortOrder());
         if (!sortOrder.isSorted()) {
-            // null == "no write sort order" (legacy gates setSortInfo on 
isSorted()). A sorted table
-            // returns a (possibly empty) list so the engine still emits a 
TSortInfo, matching legacy's
-            // unconditional setSortInfo inside the isSorted() branch even 
when no identity column resolves.
             return null;
         }
         Map<Integer, Integer> positionsByFieldId = new HashMap<>();
         if (boundTargetColumns.isEmpty()) {
-            List<NestedField> currentColumns = active.isPresent()
-                    ? active.get().getSchema().columns() : 
table.schema().columns();
+            List<NestedField> currentColumns = schema.columns();
             for (int i = 0; i < currentColumns.size(); i++) {
                 positionsByFieldId.put(currentColumns.get(i).fieldId(), i);
             }
@@ -547,17 +553,16 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
         }
         List<ConnectorWriteSortColumn> result = new ArrayList<>();
         for (SortField sortField : sortOrder.fields()) {
-            if (!sortField.transform().isIdentity()) {
-                continue;
-            }
             Integer position = positionsByFieldId.get(sortField.sourceId());
-            if (position != null) {
-                // Resolve against the bound field id, never a newly refreshed 
live ordinal; otherwise
-                // schema reorder can sort one output expression using another 
column's ordering contract.
-                result.add(new ConnectorWriteSortColumn(position,
-                        sortField.direction() == SortDirection.ASC,
-                        sortField.nullOrder() == NullOrder.NULLS_FIRST));
+            if (position == null) {
+                throw new DorisConnectorException("Iceberg sort field " + 
sortField.sourceId()
+                        + " is missing from the bound write columns for " + 
handle.getDbName()
+                        + "." + handle.getTableName());
             }
+            // Resolve against the bound field ID so a schema reorder cannot 
change the sorting expression.
+            result.add(new ConnectorWriteSortColumn(position,
+                    sortField.direction() == SortDirection.ASC,
+                    sortField.nullOrder() == NullOrder.NULLS_FIRST));
         }
         return result;
     }
@@ -900,7 +905,8 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
 
         // Sort info: the engine builds the TSortInfo from the 
connector-declared write-sort columns
         // (getWriteSortColumns) and threads it back on the handle; the 
connector stamps it verbatim.
-        if (handle.getSortInfo() != null) {
+        if (IcebergWriteSortOrder.fileSortOrder(schemaContext.getSchema(), 
schemaContext.getSortOrder(),
+                handle.getSortInfo()).isSorted()) {
             tSink.setSortInfo(handle.getSortInfo());
         }
 
@@ -950,19 +956,12 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
      * All other fields are inherited unchanged from the INSERT path.
      */
     private TIcebergTableSink buildRewriteSink(Table table, IcebergTableHandle 
tableHandle,
-            ConnectorWriteHandle handle) {
+            ConnectorWriteHandle handle, IcebergWriteSchemaContext 
rewriteSchemaContext) {
         // A compaction REWRITE atomically replaces a file set; it is never a 
user INSERT OVERWRITE, and the
         // BE writer does not accept the REWRITE write-type together with the 
overwrite flag.
         if (handle.isOverwrite()) {
             throw new DorisConnectorException("REWRITE writes cannot be 
overwrite operations");
         }
-        IcebergWriteSchemaContext rewriteSchemaContext = 
IcebergWriteSchemaContext.create(
-                table, tableHandle.getTableName(), Optional.empty(),
-                mappingVarbinaryEnabled(), mappingTimestampTzEnabled());
-        // REWRITE resolves its schema after beginWrite, so its Variant check 
and rolling-upgrade fence must run
-        // here against the same schema and partition spec that the compaction 
sink will actually use.
-        validateVariantWrite(handle, rewriteSchemaContext);
-        validateNestedPartitionWriteCompatibility(handle, 
rewriteSchemaContext);
         TIcebergTableSink tSink = buildSink(table, tableHandle, handle, 
rewriteSchemaContext);
         tSink.setWriteType(TIcebergWriteType.REWRITE);
         if (IcebergWriterHelper.getFormatVersion(table) >= 3) {
@@ -1058,13 +1057,10 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
             tSink.setPartitionSpecId(partitionSpec.specId());
         }
 
-        // Sort fields: identity sort-order fields whose source id is a base 
column, carrying the iceberg
-        // source field id directly (BE merge writer field 6) — distinct from 
the INSERT path's sort_info(16).
-        // A sorted table with no resolving identity column still emits an 
(empty) sort_fields list (legacy
-        // sets it unconditionally inside the isSorted() branch).
-        SortOrder sortOrder = schemaContext.getSortOrder();
+        SortOrder sortOrder = IcebergWriteSortOrder.supportedOrder(
+                schemaContext.getSchema(), schemaContext.getSortOrder());
         if (sortOrder.isSorted()) {
-            
tSink.setSortFields(buildMergeSortFields(schemaContext.getSchema(), sortOrder));
+            tSink.setSortFields(buildMergeSortFields(sortOrder));
         }
 
         tSink.setFileFormat(toTFileFormatType(schemaContext.getFileFormat()));
@@ -1114,19 +1110,9 @@ public class IcebergWritePlanProvider implements 
ConnectorWritePlanProvider {
         return sets;
     }
 
-    private static List<TSortField> buildMergeSortFields(Schema schema, 
SortOrder sortOrder) {
-        Set<Integer> baseColumnFieldIds = new HashSet<>();
-        for (NestedField column : schema.columns()) {
-            baseColumnFieldIds.add(column.fieldId());
-        }
+    private static List<TSortField> buildMergeSortFields(SortOrder sortOrder) {
         List<TSortField> sortFields = new ArrayList<>();
         for (SortField sortField : sortOrder.fields()) {
-            if (!sortField.transform().isIdentity()) {
-                continue;
-            }
-            if (!baseColumnFieldIds.contains(sortField.sourceId())) {
-                continue;
-            }
             TSortField tSortField = new TSortField();
             tSortField.setSourceColumnId(sortField.sourceId());
             tSortField.setAscending(sortField.direction() == 
SortDirection.ASC);
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWriteSortOrder.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWriteSortOrder.java
new file mode 100644
index 00000000000..627d32a8b76
--- /dev/null
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWriteSortOrder.java
@@ -0,0 +1,62 @@
+// 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.doris.connector.iceberg;
+
+import org.apache.doris.thrift.TSortInfo;
+
+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;
+
+/** Resolves the complete sort order that the data writer can actually 
execute. */
+final class IcebergWriteSortOrder {
+    private IcebergWriteSortOrder() {
+    }
+
+    static SortOrder supportedOrder(Schema schema, SortOrder order) {
+        for (SortField field : order.fields()) {
+            if (!field.transform().isIdentity() || 
schema.asStruct().field(field.sourceId()) == null) {
+                // Sorting a subset of the fields does not satisfy the 
declared lexicographic order.
+                return SortOrder.unsorted();
+            }
+        }
+        return order;
+    }
+
+    static SortOrder fileSortOrder(Schema schema, SortOrder order, TSortInfo 
sortInfo) {
+        SortOrder supported = supportedOrder(schema, order);
+        if (!supported.isSorted() || sortInfo == null) {
+            return SortOrder.unsorted();
+        }
+        int fieldCount = supported.fields().size();
+        if (sortInfo.getOrderingExprsSize() != fieldCount
+                || sortInfo.getIsAscOrderSize() != fieldCount || 
sortInfo.getNullsFirstSize() != fieldCount) {
+            return SortOrder.unsorted();
+        }
+        for (int i = 0; i < fieldCount; i++) {
+            SortField field = supported.fields().get(i);
+            if (sortInfo.getIsAscOrder().get(i) != (field.direction() == 
SortDirection.ASC)
+                    || sortInfo.getNullsFirst().get(i) != (field.nullOrder() 
== NullOrder.NULLS_FIRST)) {
+                return SortOrder.unsorted();
+            }
+        }
+        return supported;
+    }
+}
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWriterHelper.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWriterHelper.java
index ecd1f957c05..4a68f124e6b 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWriterHelper.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergWriterHelper.java
@@ -142,6 +142,11 @@ final class IcebergWriterHelper {
      * file; {@code "null"} partition tokens map to a real {@code null}.
      */
     static WriteResult convertToWriterResult(Table table, 
List<TIcebergCommitData> commitDataList, ZoneId zone) {
+        return convertToWriterResult(table, SortOrder.unsorted(), 
commitDataList, zone);
+    }
+
+    static WriteResult convertToWriterResult(Table table, SortOrder 
fileSortOrder,
+            List<TIcebergCommitData> commitDataList, ZoneId zone) {
         PartitionSpec spec = table.spec();
         FileFormat fileFormat = getFileFormat(table);
         MetricsConfig metricsConfig = MetricsConfig.forTable(table);
@@ -151,14 +156,19 @@ final class IcebergWriterHelper {
             schema = appendRowLineageFieldsForV3(schema);
         }
         return convertToWriterResult(
-                spec, fileFormat, metricsConfig, schema, table.sortOrder(), 
commitDataList, zone);
+                spec, fileFormat, metricsConfig, schema, fileSortOrder, 
commitDataList, zone);
     }
 
     static WriteResult convertToWriterResult(
             IcebergWriteSchemaContext context, List<TIcebergCommitData> 
commitDataList, ZoneId zone) {
+        return convertToWriterResult(context, SortOrder.unsorted(), 
commitDataList, zone);
+    }
+
+    static WriteResult convertToWriterResult(IcebergWriteSchemaContext 
context, SortOrder fileSortOrder,
+            List<TIcebergCommitData> commitDataList, ZoneId zone) {
         return convertToWriterResult(
                 context.getPartitionSpec(), context.getFileFormat(), 
context.getMetricsConfig(),
-                context.getMergeSchema(), context.getSortOrder(), 
commitDataList, zone);
+                context.getMergeSchema(), fileSortOrder, commitDataList, zone);
     }
 
     private static WriteResult convertToWriterResult(
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergConnectorTransactionTest.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergConnectorTransactionTest.java
index dbf2f0df886..77f5b1ba4ee 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergConnectorTransactionTest.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergConnectorTransactionTest.java
@@ -48,6 +48,7 @@ import org.apache.iceberg.PartitionData;
 import org.apache.iceberg.PartitionSpec;
 import org.apache.iceberg.Schema;
 import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.SortOrder;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.TableOperations;
 import org.apache.iceberg.TableProperties;
@@ -225,6 +226,13 @@ public class IcebergConnectorTransactionTest {
         return files;
     }
 
+    private static DataFile onlyAddedDataFile(Table table) {
+        List<DataFile> files = new ArrayList<>();
+        table.currentSnapshot().addedDataFiles(table.io()).forEach(files::add);
+        Assertions.assertEquals(1, files.size());
+        return files.get(0);
+    }
+
     private static DataFile dataFile(PartitionSpec spec, String path, long 
records) {
         return DataFiles.builder(spec)
                 .withPath(path)
@@ -764,6 +772,88 @@ public class IcebergConnectorTransactionTest {
         Assertions.assertEquals("1", snap.summary().get("added-data-files"));
     }
 
+    @Test
+    public void dataFilesDefaultToUnsortedWithoutABoundFileSortOrder() {
+        for (WriteOperation operation : Arrays.asList(
+                WriteOperation.INSERT, WriteOperation.OVERWRITE, 
WriteOperation.REWRITE)) {
+            InMemoryCatalog catalog = freshCatalog();
+            TableIdentifier id = TableIdentifier.of("db1", "t1");
+            Table table = catalog.createTable(id, SCHEMA, 
PartitionSpec.unpartitioned(),
+                    props("format-version", "2", "write.format.default", 
"parquet"));
+            table.replaceSortOrder().asc("id").commit();
+            table.newAppend().appendFile(dataFile(table.spec(), 
"s3://b/db1/t1/seed.parquet", 1L)).commit();
+            IcebergConnectorTransaction txn = txnFor(opsReturning(table), new 
RecordingConnectorContext());
+
+            txn.beginWrite(SESSION, "db1", "t1",
+                    operation == WriteOperation.REWRITE ? rewriteCtx() : 
pinnedCtx(operation, table));
+            if (operation == WriteOperation.REWRITE) {
+                txn.updateRewriteFiles(currentDataFiles(table));
+            }
+            
txn.addCommitData(commitBytes(dataFileItem("s3://b/db1/t1/new.parquet", 1L, 
1024L)));
+            txn.commit();
+
+            Table committed = catalog.loadTable(id);
+            Assertions.assertTrue(committed.sortOrder().isSorted());
+            Assertions.assertEquals(Integer.valueOf(0), 
onlyAddedDataFile(committed).sortOrderId(),
+                    operation + " must not claim the table order without a 
complete bound sorting plan");
+        }
+    }
+
+    @Test
+    public void dataFilesUseBoundFileSortOrderAfterDefaultOrderEvolution() {
+        for (WriteOperation operation : Arrays.asList(
+                WriteOperation.INSERT, WriteOperation.OVERWRITE, 
WriteOperation.REWRITE)) {
+            InMemoryCatalog catalog = freshCatalog();
+            TableIdentifier id = TableIdentifier.of("db1", "t1");
+            Table table = catalog.createTable(id, SCHEMA, 
PartitionSpec.unpartitioned(),
+                    props("format-version", "2", "write.format.default", 
"parquet"));
+            table.replaceSortOrder().asc("id").commit();
+            SortOrder fileSortOrder = table.sortOrder();
+            table.newAppend().appendFile(dataFile(table.spec(), 
"s3://b/db1/t1/seed.parquet", 1L)).commit();
+            IcebergConnectorTransaction txn = txnFor(opsReturning(table), new 
RecordingConnectorContext());
+
+            txn.beginWrite(SESSION, "db1", "t1",
+                    operation == WriteOperation.REWRITE ? rewriteCtx() : 
pinnedCtx(operation, table));
+            // Model the complete sorting plan recorded before the sink starts 
writing files.
+            txn.bindFileSortOrder(fileSortOrder);
+            if (operation == WriteOperation.REWRITE) {
+                txn.updateRewriteFiles(currentDataFiles(table));
+            }
+            catalog.loadTable(id).replaceSortOrder().desc("name").commit();
+            
txn.addCommitData(commitBytes(dataFileItem("s3://b/db1/t1/new.parquet", 1L, 
1024L)));
+            txn.commit();
+
+            Table committed = catalog.loadTable(id);
+            Assertions.assertNotEquals(fileSortOrder.orderId(), 
committed.sortOrder().orderId());
+            Assertions.assertEquals(Integer.valueOf(fileSortOrder.orderId()),
+                    onlyAddedDataFile(committed).sortOrderId(),
+                    operation + " must describe the executed order instead of 
the new table default");
+        }
+    }
+
+    @Test
+    public void rowLevelDataFilesUseBoundUnsortedOrderOnSortedTables() {
+        for (WriteOperation operation : Arrays.asList(WriteOperation.UPDATE, 
WriteOperation.MERGE)) {
+            InMemoryCatalog catalog = freshCatalog();
+            TableIdentifier id = TableIdentifier.of("db1", "t1");
+            Table table = catalog.createTable(id, SCHEMA, 
PartitionSpec.unpartitioned(),
+                    props("format-version", "2", "write.format.default", 
"parquet"));
+            table.replaceSortOrder().asc("id").commit();
+            table.newAppend().appendFile(dataFile(table.spec(), 
"s3://b/db1/t1/seed.parquet", 1L)).commit();
+            IcebergConnectorTransaction txn = txnFor(opsReturning(table), new 
RecordingConnectorContext());
+
+            txn.beginWrite(SESSION, "db1", "t1", pinnedCtx(operation, table));
+            txn.bindFileSortOrder(SortOrder.unsorted());
+            
txn.addCommitData(commitBytes(dataFileItem("s3://b/db1/t1/new.parquet", 1L, 
1024L)));
+            txn.commit();
+
+            Table committed = catalog.loadTable(id);
+            Assertions.assertTrue(committed.sortOrder().isSorted());
+            Assertions.assertEquals(Integer.valueOf(0), 
onlyAddedDataFile(committed).sortOrderId(),
+                    operation + " must not claim a table order that its data 
writer did not execute");
+        }
+    }
+
     @Test
     public void insertToBranchCommitsOnBranch() {
         InMemoryCatalog catalog = freshCatalog();
@@ -806,6 +896,7 @@ public class IcebergConnectorTransactionTest {
         IcebergConnectorTransaction txn = txnFor(opsReturning(table), new 
RecordingConnectorContext());
 
         txn.beginWrite(SESSION, "db1", "t1", ctx);
+        txn.bindFileSortOrder(ctx.getWriteSchemaContext().getSortOrder());
         txn.addCommitData(commitBytes(
                 dataFileItem("s3://b/db1/t1/id=7/f1.orc", 1L, 1024L, 
Collections.singletonList("7"))));
         txn.commit();
@@ -2579,6 +2670,45 @@ public class IcebergConnectorTransactionTest {
         Assertions.assertEquals(expected, txn.getStartingSnapshotId(), "OCC 
anchor must stay pinned to S1");
     }
 
+    @Test
+    public void sharedRewriteGroupsCannotReplaceTheBoundFileSortOrder() {
+        InMemoryCatalog catalog = freshCatalog();
+        TableIdentifier id = TableIdentifier.of("db1", "t1");
+        Table table = catalog.createTable(id, SCHEMA, 
PartitionSpec.unpartitioned(),
+                props("format-version", "2", "write.format.default", 
"parquet"));
+        table.replaceSortOrder().asc("id").commit();
+        SortOrder fileSortOrder = table.sortOrder();
+        table.newAppend().appendFile(dataFile(table.spec(), 
"s3://b/db1/t1/seed.parquet", 2L)).commit();
+        IcebergConnectorTransaction txn = txnFor(opsReturning(table), new 
RecordingConnectorContext());
+
+        txn.beginWrite(SESSION, "db1", "t1", rewriteCtx());
+        txn.bindFileSortOrder(fileSortOrder);
+        txn.updateRewriteFiles(currentDataFiles(table));
+        
txn.addCommitData(commitBytes(dataFileItem("s3://b/db1/t1/group1.parquet", 1L, 
1024L)));
+
+        txn.beginWrite(SESSION, "db1", "t1", rewriteCtx());
+        SortOrder sameOrder = SortOrder.builderFor(SCHEMA)
+                .withOrderId(fileSortOrder.orderId()).asc("id").build();
+        Assertions.assertDoesNotThrow(() -> txn.bindFileSortOrder(sameOrder));
+        
txn.addCommitData(commitBytes(dataFileItem("s3://b/db1/t1/group2.parquet", 1L, 
1024L)));
+
+        SortOrder differentId = SortOrder.builderFor(SCHEMA)
+                .withOrderId(fileSortOrder.orderId() + 1).asc("id").build();
+        SortOrder differentDefinition = SortOrder.builderFor(SCHEMA)
+                .withOrderId(fileSortOrder.orderId()).desc("id").build();
+        Assertions.assertThrows(IllegalStateException.class, () -> 
txn.bindFileSortOrder(differentId));
+        Assertions.assertThrows(IllegalStateException.class, () -> 
txn.bindFileSortOrder(differentDefinition));
+        Assertions.assertDoesNotThrow(() -> 
txn.bindFileSortOrder(fileSortOrder),
+                "a rejected group must not replace the order already bound for 
earlier fragments");
+        txn.commit();
+
+        List<DataFile> files = currentDataFiles(catalog.loadTable(id));
+        Assertions.assertEquals(2, files.size());
+        for (DataFile file : files) {
+            Assertions.assertEquals(Integer.valueOf(fileSortOrder.orderId()), 
file.sortOrderId());
+        }
+    }
+
     @Test
     public void registerRewriteSourceFilesBeforeBeginFailsLoud() {
         // registerRewriteSourceFiles re-derives the source files from the 
table at the pinned snapshot, both
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWritePlanProviderTest.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWritePlanProviderTest.java
index 94e935ee6ba..07a996e6066 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWritePlanProviderTest.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWritePlanProviderTest.java
@@ -41,6 +41,9 @@ import 
org.apache.doris.filesystem.properties.BackendStorageProperties;
 import org.apache.doris.filesystem.properties.StorageKind;
 import org.apache.doris.filesystem.properties.StorageProperties;
 import org.apache.doris.thrift.TDataSinkType;
+import org.apache.doris.thrift.TExpr;
+import org.apache.doris.thrift.TExprNode;
+import org.apache.doris.thrift.TExprNodeType;
 import org.apache.doris.thrift.TFileCompressType;
 import org.apache.doris.thrift.TFileContent;
 import org.apache.doris.thrift.TFileFormatType;
@@ -53,13 +56,20 @@ import 
org.apache.doris.thrift.TIcebergRewritableDeleteFileSet;
 import org.apache.doris.thrift.TIcebergTableSink;
 import org.apache.doris.thrift.TIcebergWriteType;
 import org.apache.doris.thrift.TNetworkAddress;
+import org.apache.doris.thrift.TPrimitiveType;
+import org.apache.doris.thrift.TScalarType;
+import org.apache.doris.thrift.TSlotRef;
 import org.apache.doris.thrift.TSortField;
 import org.apache.doris.thrift.TSortInfo;
+import org.apache.doris.thrift.TTypeDesc;
+import org.apache.doris.thrift.TTypeNode;
+import org.apache.doris.thrift.TTypeNodeType;
 
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Maps;
 import org.apache.commons.lang3.exception.ExceptionUtils;
 import org.apache.iceberg.BaseTable;
+import org.apache.iceberg.DataFile;
 import org.apache.iceberg.DataFiles;
 import org.apache.iceberg.FileFormat;
 import org.apache.iceberg.HasTableOperations;
@@ -295,6 +305,17 @@ public class IcebergWritePlanProviderTest {
                 PartitionSpec.unpartitioned(), tableProps);
     }
 
+    private static Table nestedSortedTable(InMemoryCatalog catalog) {
+        Schema schema = new Schema(Types.NestedField.required(1, "id", 
Types.IntegerType.get()),
+                Types.NestedField.optional(2, "s", Types.StructType.of(
+                        Types.NestedField.optional(3, "k", 
Types.IntegerType.get()))));
+        Table table = catalog.createTable(TableIdentifier.of("db1", "t2"), 
schema,
+                PartitionSpec.unpartitioned(), 
ImmutableMap.of("write.format.default", "parquet",
+                        "write.data.path", "oss://bucket/wh/db1/t2/data"));
+        table.replaceSortOrder().asc("s.k", NullOrder.NULLS_FIRST).commit();
+        return catalog.loadTable(TableIdentifier.of("db1", "t2"));
+    }
+
     /** A format-version 3 table (exercises the merge sink's row-lineage 
schema append + v3 delete path). */
     private static Table formatVersionThreeTable(InMemoryCatalog catalog) {
         Map<String, String> tableProps = new HashMap<>();
@@ -1581,12 +1602,71 @@ public class IcebergWritePlanProviderTest {
 
     // ───────────────────────────── sort info (engine-built, stamped) 
─────────────────────────────
 
+    @Test
+    public void plannedIdentitySortOrderReachesCommittedManifest() throws 
TException {
+        for (WriteOperation operation : Arrays.asList(WriteOperation.INSERT, 
WriteOperation.OVERWRITE,
+                WriteOperation.REWRITE, WriteOperation.UPDATE, 
WriteOperation.MERGE)) {
+            Table table = unpartitionedUnsortedTable(freshCatalog());
+            table.replaceSortOrder().asc("id", NullOrder.NULLS_FIRST).commit();
+            int expectedOrderId = operation == WriteOperation.UPDATE || 
operation == WriteOperation.MERGE
+                    ? 0 : table.sortOrder().orderId();
+            assertPlannedFileSortOrder(table, operation, 
identitySortInfo(true, true), expectedOrderId);
+        }
+    }
+
+    @Test
+    public void plannedUnsupportedSortOrdersReachManifestAsUnsorted() throws 
TException {
+        for (WriteOperation operation : Arrays.asList(
+                WriteOperation.INSERT, WriteOperation.OVERWRITE, 
WriteOperation.REWRITE)) {
+            Table bucket = unpartitionedUnsortedTable(freshCatalog());
+            bucket.replaceSortOrder().asc(Expressions.bucket("id", 
4)).commit();
+            Table truncate = unpartitionedUnsortedTable(freshCatalog());
+            truncate.replaceSortOrder().asc(Expressions.truncate("id", 
10)).commit();
+            for (Table table : Arrays.asList(bucket, truncate, 
nestedSortedTable(freshCatalog()))) {
+                assertPlannedFileSortOrder(table, operation, 
identitySortInfo(true, true), 0);
+            }
+        }
+    }
+
+    private static void assertPlannedFileSortOrder(Table table, WriteOperation 
operation,
+            TSortInfo sortInfo, int expectedOrderId) throws TException {
+        String location = table.properties().get("write.data.path");
+        DataFile original = DataFiles.builder(table.spec()).withPath(location 
+ "/original.parquet")
+                
.withFormat(FileFormat.PARQUET).withRecordCount(1L).withFileSizeInBytes(128L).build();
+        table.newAppend().appendFile(original).commit();
+        int tableOrderId = table.sortOrder().orderId();
+        RecordingConnectorContext context = contextWithStorage();
+        WriteSession session = sessionFor(table, context);
+        IcebergConnectorTransaction transaction = (IcebergConnectorTransaction)
+                
session.getCurrentTransaction().orElseThrow(AssertionError::new);
+        providerFor(table, context).planWrite(session,
+                new WriteHandle(new IcebergTableHandle("db1", 
"t2")).writeOperation(operation)
+                        .overwrite(operation == 
WriteOperation.OVERWRITE).sortInfo(sortInfo));
+        if (operation == WriteOperation.REWRITE) {
+            
transaction.updateRewriteFiles(Collections.singletonList(original));
+        }
+        TIcebergCommitData fragment = new TIcebergCommitData();
+        fragment.setFilePath(location + "/planned.parquet");
+        fragment.setFileSize(128L);
+        fragment.setRowCount(1L);
+        fragment.setFileContent(TFileContent.DATA);
+        transaction.addCommitData(new TSerializer(new 
TBinaryProtocol.Factory()).serialize(fragment));
+        transaction.commit();
+
+        table.refresh();
+        List<DataFile> added = new ArrayList<>();
+        table.currentSnapshot().addedDataFiles(table.io()).forEach(added::add);
+        Assertions.assertEquals(1, added.size(), operation + " must commit one 
planned data file");
+        Assertions.assertEquals(Integer.valueOf(expectedOrderId), 
added.get(0).sortOrderId(),
+                operation + " must commit the order bound by its actual sink 
plan");
+        Assertions.assertEquals(tableOrderId, table.sortOrder().orderId(),
+                "the effective file order must not change the table's default 
sort order");
+    }
+
     @Test
     public void planWriteStampsHandleSortInfoOntoSink() {
         Table table = partitionedSortedTable(freshCatalog());
-        TSortInfo engineBuilt = new TSortInfo();
-        engineBuilt.setIsAscOrder(Collections.singletonList(true));
-        engineBuilt.setNullsFirst(Collections.singletonList(true));
+        TSortInfo engineBuilt = identitySortInfo(true, true);
         TIcebergTableSink sink = planSink(table, contextWithStorage(),
                 new WriteHandle(new IcebergTableHandle("db1", 
"t1")).sortInfo(engineBuilt));
 
@@ -1595,6 +1675,47 @@ public class IcebergWritePlanProviderTest {
                         + "stamped onto the sink verbatim");
     }
 
+    private static TSortInfo identitySortInfo(boolean ascending, boolean 
nullsFirst) {
+        TTypeNode typeNode = new TTypeNode();
+        typeNode.setType(TTypeNodeType.SCALAR);
+        typeNode.setScalarType(new TScalarType(TPrimitiveType.INT));
+        TTypeDesc type = new TTypeDesc();
+        type.setTypes(Collections.singletonList(typeNode));
+        TExprNode slot = new TExprNode();
+        slot.setNodeType(TExprNodeType.SLOT_REF);
+        slot.setType(type);
+        slot.setNumChildren(0);
+        slot.setOutputScale(0);
+        slot.setSlotRef(new TSlotRef(0, 0));
+        TExpr expression = new TExpr();
+        expression.setNodes(Collections.singletonList(slot));
+        TSortInfo sortInfo = new TSortInfo();
+        sortInfo.setOrderingExprs(Collections.singletonList(expression));
+        sortInfo.setIsAscOrder(Collections.singletonList(ascending));
+        sortInfo.setNullsFirst(Collections.singletonList(nullsFirst));
+        return sortInfo;
+    }
+
+    @Test
+    public void planWriteEmptyOrPartialSortInfoLeavesSinkUnsorted() {
+        Table table = unpartitionedUnsortedTable(freshCatalog());
+        table.replaceSortOrder().asc("id", NullOrder.NULLS_FIRST).desc("name", 
NullOrder.NULLS_LAST).commit();
+        for (TSortInfo sortInfo : Arrays.asList(new TSortInfo(), 
identitySortInfo(true, true))) {
+            TIcebergTableSink sink = planSink(table, contextWithStorage(),
+                    new WriteHandle(new IcebergTableHandle("db1", 
"t2")).sortInfo(sortInfo));
+            Assertions.assertFalse(sink.isSetSortInfo(), "an incomplete key 
list must not enable the sort writer");
+        }
+    }
+
+    @Test
+    public void planWriteUnsupportedSortOrderOmitsHandleSortInfo() {
+        Table table = unpartitionedUnsortedTable(freshCatalog());
+        table.replaceSortOrder().asc(Expressions.truncate("id", 10)).commit();
+        TIcebergTableSink sink = planSink(table, contextWithStorage(),
+                new WriteHandle(new IcebergTableHandle("db1", 
"t2")).sortInfo(identitySortInfo(true, true)));
+        Assertions.assertFalse(sink.isSetSortInfo(), "sorting the source 
column is not the declared transform sort");
+    }
+
     @Test
     public void planWriteWithoutHandleSortInfoLeavesSinkUnsorted() {
         Table table = partitionedSortedTable(freshCatalog());
@@ -1650,25 +1771,68 @@ public class IcebergWritePlanProviderTest {
     }
 
     @Test
-    public void 
getWriteSortColumnsNonNullEmptyForSortOrderWithoutIdentityColumns() {
-        // A table sorted ONLY by a non-identity transform (e.g. bucket) still 
HAS a write sort order, so
-        // legacy unconditionally sets an (empty) sort_info inside the 
isSorted() branch -> BE uses the
-        // sort writer. The connector must signal this as a non-null EMPTY 
list (not null), so the engine
-        // emits an empty TSortInfo. MUTATION: returning null here -> BE uses 
the plain writer -> red.
-        InMemoryCatalog catalog = freshCatalog();
-        Map<String, String> tableProps = new HashMap<>();
-        tableProps.put("write.format.default", "parquet");
-        tableProps.put("write.data.path", "oss://bucket/wh/db1/t3/data");
-        Table table = catalog.createTable(TableIdentifier.of("db1", "t3"), 
SCHEMA,
-                PartitionSpec.unpartitioned(), tableProps);
+    public void getWriteSortColumnsNullForBucketSortOrder() {
+        Table table = unpartitionedUnsortedTable(freshCatalog());
         table.replaceSortOrder().asc(Expressions.bucket("id", 4)).commit();
-        Table reloaded = catalog.loadTable(TableIdentifier.of("db1", "t3"));
+        Assertions.assertNull(providerFor(table, contextWithStorage())
+                .getWriteSortColumns(sessionFor(table, contextWithStorage()),
+                        new IcebergTableHandle("db1", "t2")),
+                "an unsupported sort order must not produce an empty-key sort 
writer");
+    }
+
+    @Test
+    public void getWriteSortColumnsNullForTruncateSortOrder() {
+        Table table = unpartitionedUnsortedTable(freshCatalog());
+        table.replaceSortOrder().asc(Expressions.truncate("id", 10)).commit();
+        Assertions.assertNull(providerFor(table, contextWithStorage())
+                .getWriteSortColumns(sessionFor(table, contextWithStorage()),
+                        new IcebergTableHandle("db1", "t2")));
+    }
+
+    @Test
+    public void getWriteSortColumnsNullForMixedSortOrder() {
+        Table table = unpartitionedUnsortedTable(freshCatalog());
+        table.replaceSortOrder().asc(Expressions.truncate("id", 
10)).desc("name", NullOrder.NULLS_LAST).commit();
+        Assertions.assertNull(providerFor(table, contextWithStorage())
+                .getWriteSortColumns(sessionFor(table, contextWithStorage()),
+                        new IcebergTableHandle("db1", "t2")),
+                "the identity suffix cannot stand in for the full 
lexicographic order");
+    }
+
+    @Test
+    public void getWriteSortColumnsNullForNestedSortOrder() {
+        Table table = nestedSortedTable(freshCatalog());
+        Assertions.assertNull(providerFor(table, contextWithStorage())
+                .getWriteSortColumns(sessionFor(table, contextWithStorage()),
+                        new IcebergTableHandle("db1", "t2")));
+    }
+
+    @Test
+    public void 
getWriteSortColumnsKeepsIdentityFieldOrderDirectionAndNullOrder() {
+        Table table = unpartitionedUnsortedTable(freshCatalog());
+        table.replaceSortOrder().desc("name", NullOrder.NULLS_LAST).asc("id", 
NullOrder.NULLS_FIRST).commit();
+        List<ConnectorWriteSortColumn> columns = providerFor(table, 
contextWithStorage())
+                .getWriteSortColumns(sessionFor(table, contextWithStorage()),
+                        new IcebergTableHandle("db1", "t2"));
+        Assertions.assertEquals(2, columns.size());
+        Assertions.assertEquals(1, columns.get(0).getColumnIndex());
+        Assertions.assertFalse(columns.get(0).isAsc());
+        Assertions.assertFalse(columns.get(0).isNullsFirst());
+        Assertions.assertEquals(0, columns.get(1).getColumnIndex());
+        Assertions.assertTrue(columns.get(1).isAsc());
+        Assertions.assertTrue(columns.get(1).isNullsFirst());
+    }
 
-        List<ConnectorWriteSortColumn> cols = providerFor(reloaded, 
contextWithStorage())
-                .getWriteSortColumns(sessionFor(reloaded, 
contextWithStorage()),
-                        new IcebergTableHandle("db1", "t3"));
-        Assertions.assertNotNull(cols, "a sorted table (even by a non-identity 
transform) has a write sort order");
-        Assertions.assertTrue(cols.isEmpty(), "no identity column resolves -> 
empty list -> empty TSortInfo");
+    @Test
+    public void getWriteSortColumnsRejectsMissingBoundIdentityField() {
+        Table table = partitionedSortedTable(freshCatalog());
+        List<ConnectorColumn> boundColumns = Collections.singletonList(
+                new ConnectorColumn("name", ConnectorType.of("STRING"), "", 
true, null)
+                        
.withUniqueId(table.schema().findField("name").fieldId()));
+        Assertions.assertThrows(DorisConnectorException.class,
+                () -> providerFor(table, contextWithStorage())
+                        .getWriteSortColumns(sessionFor(table, 
contextWithStorage()),
+                                new IcebergTableHandle("db1", "t1"), 
boundColumns));
     }
 
     @Test
@@ -2772,6 +2936,31 @@ public class IcebergWritePlanProviderTest {
         Assertions.assertTrue(sf.isNullFirst());
     }
 
+    @Test
+    public void planWriteMergeSinkUnsupportedSortOrderOmitsSortFields() {
+        Table transformed = unpartitionedUnsortedTable(freshCatalog());
+        transformed.replaceSortOrder().asc(Expressions.truncate("id", 
10)).asc("name").commit();
+        for (Table table : Arrays.asList(transformed, 
nestedSortedTable(freshCatalog()))) {
+            TIcebergMergeSink sink = planMergeSink(table, contextWithStorage(),
+                    new WriteHandle(new IcebergTableHandle("db1", 
"t2")).writeOperation(WriteOperation.UPDATE));
+            Assertions.assertFalse(sink.isSetSortFields(),
+                    "unsupported sort fields must not be reduced to an 
identity subset");
+        }
+    }
+
+    @Test
+    public void unsupportedDataSortOrderDoesNotPreventDeleteOnlyWrites() {
+        Table table = nestedSortedTable(freshCatalog());
+        TIcebergDeleteSink deleteSink = planDeleteSink(table, 
contextWithStorage(),
+                new WriteHandle(new IcebergTableHandle("db1", "t2"))
+                        
.writeOperation(WriteOperation.DELETE).writesDataFiles(false));
+        Assertions.assertNotNull(deleteSink);
+        TIcebergMergeSink mergeSink = planMergeSink(table, 
contextWithStorage(),
+                new WriteHandle(new IcebergTableHandle("db1", "t2"))
+                        
.writeOperation(WriteOperation.MERGE).writesDataFiles(false));
+        Assertions.assertFalse(mergeSink.isWritesDataFiles());
+    }
+
     @Test
     public void planWriteMergeSinkUnsortedOmitsSortFields() {
         InMemoryCatalog catalog = freshCatalog();
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWriteSortOrderTest.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWriteSortOrderTest.java
new file mode 100644
index 00000000000..2ee83fa1058
--- /dev/null
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWriteSortOrderTest.java
@@ -0,0 +1,144 @@
+// 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.doris.connector.iceberg;
+
+import org.apache.doris.thrift.TExpr;
+import org.apache.doris.thrift.TSortInfo;
+
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortOrder;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class IcebergWriteSortOrderTest {
+    private final Schema schema = new Schema(
+            Types.NestedField.required(1, "id", Types.IntegerType.get()),
+            Types.NestedField.optional(2, "name", Types.StringType.get()),
+            Types.NestedField.optional(3, "s", Types.StructType.of(
+                    Types.NestedField.optional(4, "k", 
Types.IntegerType.get()))));
+
+    @Test
+    public void completeIdentityOrderKeepsDirectionAndNullOrdering() {
+        SortOrder order = identityOrder();
+        TSortInfo sortInfo = sortInfo(Arrays.asList(true, false), 
Arrays.asList(false, true));
+
+        SortOrder supported = IcebergWriteSortOrder.supportedOrder(schema, 
order);
+        SortOrder fileOrder = IcebergWriteSortOrder.fileSortOrder(schema, 
order, sortInfo);
+        Assertions.assertEquals(order.orderId(), supported.orderId());
+        Assertions.assertTrue(order.sameOrder(supported));
+        Assertions.assertEquals(order.orderId(), fileOrder.orderId());
+        Assertions.assertTrue(order.sameOrder(fileOrder));
+    }
+
+    @Test
+    public void unsupportedTransformsUseUnsortedOrder() {
+        for (SortOrder order : Arrays.asList(
+                SortOrder.builderFor(schema).asc(Expressions.truncate("id", 
10)).build(),
+                SortOrder.builderFor(schema).asc(Expressions.bucket("id", 
4)).build())) {
+            Assertions.assertTrue(IcebergWriteSortOrder.supportedOrder(schema, 
order).isUnsorted());
+            Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order,
+                    sortInfo(Collections.singletonList(true), 
Collections.singletonList(true))).isUnsorted());
+        }
+    }
+
+    @Test
+    public void nestedIdentityUsesUnsortedOrder() {
+        SortOrder order = SortOrder.builderFor(schema).asc("s.k").build();
+
+        Assertions.assertTrue(IcebergWriteSortOrder.supportedOrder(schema, 
order).isUnsorted());
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order,
+                sortInfo(Collections.singletonList(true), 
Collections.singletonList(true))).isUnsorted());
+    }
+
+    @Test
+    public void mixedOrdersDoNotClaimAnIdentitySubset() {
+        for (SortOrder order : Arrays.asList(
+                SortOrder.builderFor(schema).asc(Expressions.bucket("id", 
4)).desc("name").build(),
+                
SortOrder.builderFor(schema).asc("name").asc(Expressions.truncate("id", 
10)).build(),
+                SortOrder.builderFor(schema).asc("s.k").desc("name").build(),
+                SortOrder.builderFor(schema).asc("name").desc("s.k").build())) 
{
+            Assertions.assertTrue(IcebergWriteSortOrder.supportedOrder(schema, 
order).isUnsorted());
+            Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order,
+                    sortInfo(Arrays.asList(true, false), Arrays.asList(true, 
false))).isUnsorted());
+        }
+    }
+
+    @Test
+    public void absentAndPartialSortInfoUseUnsortedOrder() {
+        SortOrder order = identityOrder();
+
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order, null).isUnsorted());
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order, new TSortInfo()).isUnsorted());
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order,
+                sortInfo(Collections.singletonList(true), 
Collections.singletonList(false))).isUnsorted());
+        TSortInfo noExpressions = sortInfo(Arrays.asList(true, false), 
Arrays.asList(false, true));
+        noExpressions.setOrderingExprs(Collections.emptyList());
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order, noExpressions).isUnsorted());
+    }
+
+    @Test
+    public void directionAndNullOrderMustMatchEveryField() {
+        SortOrder order = identityOrder();
+
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order,
+                sortInfo(Arrays.asList(true, true), Arrays.asList(false, 
true))).isUnsorted());
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order,
+                sortInfo(Arrays.asList(true, false), Arrays.asList(true, 
true))).isUnsorted());
+        TSortInfo missingDirection = sortInfo(Arrays.asList(true, false), 
Arrays.asList(false, true));
+        missingDirection.setIsAscOrder(Collections.singletonList(true));
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order, missingDirection).isUnsorted());
+        TSortInfo missingNullOrder = sortInfo(Arrays.asList(true, false), 
Arrays.asList(false, true));
+        missingNullOrder.setNullsFirst(Collections.singletonList(false));
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order, missingNullOrder).isUnsorted());
+    }
+
+    @Test
+    public void unsortedTableDoesNotClaimAnOrder() {
+        SortOrder order = SortOrder.unsorted();
+
+        Assertions.assertTrue(IcebergWriteSortOrder.supportedOrder(schema, 
order).isUnsorted());
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order, null).isUnsorted());
+        Assertions.assertTrue(IcebergWriteSortOrder.fileSortOrder(schema, 
order,
+                sortInfo(Collections.singletonList(true), 
Collections.singletonList(true))).isUnsorted());
+    }
+
+    private SortOrder identityOrder() {
+        return SortOrder.builderFor(schema).asc("id", NullOrder.NULLS_LAST)
+                .desc("name", NullOrder.NULLS_FIRST).build();
+    }
+
+    private TSortInfo sortInfo(List<Boolean> ascending, List<Boolean> 
nullsFirst) {
+        List<TExpr> expressions = new ArrayList<>();
+        for (int i = 0; i < ascending.size(); i++) {
+            expressions.add(new TExpr());
+        }
+        TSortInfo sortInfo = new TSortInfo();
+        sortInfo.setOrderingExprs(expressions);
+        sortInfo.setIsAscOrder(ascending);
+        sortInfo.setNullsFirst(nullsFirst);
+        return sortInfo;
+    }
+}
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWriterHelperTest.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWriterHelperTest.java
index 9cf897e24c3..3c46a1c9a33 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWriterHelperTest.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergWriterHelperTest.java
@@ -30,6 +30,7 @@ import org.apache.iceberg.FileScanTask;
 import org.apache.iceberg.MetadataColumns;
 import org.apache.iceberg.PartitionSpec;
 import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortOrder;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.catalog.Namespace;
 import org.apache.iceberg.catalog.TableIdentifier;
@@ -217,6 +218,56 @@ public class IcebergWriterHelperTest {
         Assertions.assertEquals(FileFormat.PARQUET, df.format());
     }
 
+    @Test
+    public void convertToWriterResultDoesNotInferFileOrderFromTableMetadata() {
+        Table table = tableWith("write.format.default", "parquet");
+        table.replaceSortOrder().desc("age").commit();
+        IcebergWriteSchemaContext context = IcebergWriteSchemaContext.create(
+                table, "db1.t", Optional.empty(), false, false);
+        TIcebergCommitData commit = dataCommit();
+
+        DataFile fromTable = IcebergWriterHelper.convertToWriterResult(
+                table, Collections.singletonList(commit), 
ZoneOffset.UTC).dataFiles()[0];
+        DataFile fromContext = IcebergWriterHelper.convertToWriterResult(
+                context, Collections.singletonList(commit), 
ZoneOffset.UTC).dataFiles()[0];
+
+        Assertions.assertTrue(table.sortOrder().isSorted());
+        Assertions.assertTrue(context.getSortOrder().isSorted());
+        Assertions.assertEquals(Integer.valueOf(0), fromTable.sortOrderId());
+        Assertions.assertEquals(Integer.valueOf(0), fromContext.sortOrderId());
+    }
+
+    @Test
+    public void 
convertToWriterResultUsesExplicitFileOrderAcrossBothEntrypoints() {
+        Table table = tableWith("write.format.default", "parquet");
+        table.replaceSortOrder().desc("age").commit();
+        IcebergWriteSchemaContext context = IcebergWriteSchemaContext.create(
+                table, "db1.t", Optional.empty(), false, false);
+        SortOrder fileOrder = context.getSortOrder();
+        table.replaceSortOrder().asc("name").commit();
+        TIcebergCommitData commit = dataCommit();
+
+        for (SortOrder order : Arrays.asList(SortOrder.unsorted(), fileOrder)) 
{
+            DataFile fromTable = IcebergWriterHelper.convertToWriterResult(
+                    table, order, Collections.singletonList(commit), 
ZoneOffset.UTC).dataFiles()[0];
+            DataFile fromContext = IcebergWriterHelper.convertToWriterResult(
+                    context, order, Collections.singletonList(commit), 
ZoneOffset.UTC).dataFiles()[0];
+
+            Assertions.assertEquals(Integer.valueOf(order.orderId()), 
fromTable.sortOrderId());
+            Assertions.assertEquals(Integer.valueOf(order.orderId()), 
fromContext.sortOrderId());
+        }
+        Assertions.assertNotEquals(fileOrder.orderId(), 
table.sortOrder().orderId());
+    }
+
+    private TIcebergCommitData dataCommit() {
+        TIcebergCommitData commit = new TIcebergCommitData();
+        commit.setFilePath("s3://b/db1/t/data.parquet");
+        commit.setRowCount(3L);
+        commit.setFileSize(128L);
+        commit.setFileContent(TFileContent.DATA);
+        return commit;
+    }
+
     @Test
     public void convertToWriterResultCarriesSplitOffsetsFromCommitProtocol() 
throws Exception {
         Table table = tableWith("write.format.default", "parquet", 
"write.metadata.metrics.default", "none");
@@ -300,7 +351,7 @@ public class IcebergWriterHelperTest {
         commitData.setColumnStats(stats);
 
         DataFile dataFile = IcebergWriterHelper.convertToWriterResult(
-                context, Collections.singletonList(commitData), 
ZoneOffset.UTC).dataFiles()[0];
+                context, context.getSortOrder(), 
Collections.singletonList(commitData), ZoneOffset.UTC).dataFiles()[0];
 
         Assertions.assertNotEquals(table.spec().specId(), dataFile.specId(), 
"the live spec must have moved on");
         Assertions.assertEquals(context.getPartitionSpec().specId(), 
dataFile.specId());


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

Reply via email to