You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by "morningman (via GitHub)" <gi...@apache.org> on 2026/03/03 08:41:09 UTC

[PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

morningman opened a new pull request, #60978:
URL: https://github.com/apache/doris/pull/60978

   ### What problem does this PR solve?
   
   Based on PR #60540 review suggestions:
   
   1: Encapsulate _current_writer in VIcebergTableWriter
     - Move _current_writer from public to private
     - Add const getter method current_writer()
     - Update SpillIcebergTableSinkLocalState to use getter
   
   2: Split VIcebergSortWriter header-only into .h + .cpp
     - Move all method implementations to viceberg_sort_writer.cpp
     - Replace heavy includes (spill_stream.h, spill_stream_manager.h) with forward declarations in header to reduce compilation dependencies
     - Add comprehensive documentation comments to all methods and members
   
   4: Fix error handling in VIcebergSortWriter::close()
     - Track internal_status for intermediate operations
     - Pass actual error status to underlying partition writer's close() instead of the original caller status (which could be OK)
   
   5: Add explicit do_sort() in _do_spill()
     - Call _sorter->do_sort() before prepare_for_read() for clarity
     - Add detailed comments explaining the relationship with FullSorter::prepare_for_read() internal sorting
   
   6: Fix typo 'SpillReadDerializeBlockTime' -> 'SpillReadDeserializeBlockTime'
     - Fix counter name string in spill_iceberg_table_sink_operator.cpp
     - Fix counter name string in operator.h (PipelineXSpillLocalState)
     - Fix counter lookup string in spill_reader.h
     - Fix member variable name _spill_read_derialize_block_timer
   
   ### Release note
   
   None
   
   ### Check List (For Author)
   
   - Test <!-- At least one of them must be included. -->
       - [ ] Regression test
       - [ ] Unit Test
       - [ ] Manual test (add detailed scripts or steps below)
       - [ ] No need to test or manual test. Explain why:
           - [ ] This is a refactor/code format and no logic has been changed.
           - [ ] Previous test can cover this change.
           - [ ] No code files have been changed.
           - [ ] Other reason <!-- Add your reason?  -->
   
   - Behavior changed:
       - [ ] No.
       - [ ] Yes. <!-- Explain the behavior change -->
   
   - Does this need documentation?
       - [ ] No.
       - [ ] Yes. <!-- Add document PR link here. eg: https://github.com/apache/doris-website/pull/1214 -->
   
   ### Check List (For Reviewer who merge this PR)
   
   - [ ] Confirm the release note
   - [ ] Confirm test cases
   - [ ] Confirm document
   - [ ] Add branch pick label <!-- Add branch pick label that this PR should merge into -->
   
   


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

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

   PR approved by anyone and no changes requested.


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "morningman (via GitHub)" <gi...@apache.org>.
morningman commented on PR #60978:
URL: https://github.com/apache/doris/pull/60978#issuecomment-3989795308

   run buildall


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "hello-stephen (via GitHub)" <gi...@apache.org>.
hello-stephen commented on PR #60978:
URL: https://github.com/apache/doris/pull/60978#issuecomment-3991039585

   # BE Regression && UT Coverage Report
   Increment line coverage `1.32% (3/228)` :tada:
   
   [Increment coverage report](http://coverage.selectdb-in.cc/coverage/60978_557fdd355f6849f6e5ef5eaf82a00e4c7479e210_merge/increment_report/index.html)
   [Complete coverage report](http://coverage.selectdb-in.cc/coverage/60978_557fdd355f6849f6e5ef5eaf82a00e4c7479e210_merge/report/index.html)
   | Category          | Coverage           |
   |-------------------|--------------------|
   | Function Coverage | 71.57% (26179/36576) |
   | Line Coverage     | 54.36% (274520/505014) |
   | Region Coverage   | 51.78% (228810/441872) |
   | Branch Coverage   | 53.07% (98176/185000) |


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "hello-stephen (via GitHub)" <gi...@apache.org>.
hello-stephen commented on PR #60978:
URL: https://github.com/apache/doris/pull/60978#issuecomment-3990350716

   # BE UT Coverage Report
   Increment line coverage `1.32% (3/228)` :tada:
   
   [Increment coverage report](http://coverage.selectdb-in.cc/coverage/557fdd355f6849f6e5ef5eaf82a00e4c7479e210_557fdd355f6849f6e5ef5eaf82a00e4c7479e210/increment_report/index.html)
   [Complete coverage report](http://coverage.selectdb-in.cc/coverage/557fdd355f6849f6e5ef5eaf82a00e4c7479e210_557fdd355f6849f6e5ef5eaf82a00e4c7479e210/report/index.html)
   | Category          | Coverage           |
   |-------------------|--------------------|
   | Function Coverage | 52.58% (19642/37354) |
   | Line Coverage     | 36.22% (183463/506567) |
   | Region Coverage   | 32.49% (142232/437735) |
   | Branch Coverage   | 33.45% (61694/184436) |


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "morningman (via GitHub)" <gi...@apache.org>.
morningman commented on PR #60978:
URL: https://github.com/apache/doris/pull/60978#issuecomment-3989539516

   /review


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "doris-robot (via GitHub)" <gi...@apache.org>.
doris-robot commented on PR #60978:
URL: https://github.com/apache/doris/pull/60978#issuecomment-3990197033

   
   <details>
   <summary>TPC-DS: <b>Total hot run time: 184376 ms</b></summary>
   
   ```
   machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
   scripts: https://github.com/apache/doris/tree/master/tools/tpcds-tools
   TPC-DS sf100 test result on commit 557fdd355f6849f6e5ef5eaf82a00e4c7479e210, data reload: false
   
   query5	4344	641	517	517
   query6	331	231	198	198
   query7	4209	469	282	282
   query8	333	245	240	240
   query9	8727	2760	2766	2760
   query10	543	386	352	352
   query11	17082	17548	17211	17211
   query12	204	129	130	129
   query13	1369	508	370	370
   query14	6626	3424	3157	3157
   query14_1	2932	2927	2862	2862
   query15	211	207	188	188
   query16	2114	449	453	449
   query17	1075	816	648	648
   query18	2556	471	350	350
   query19	220	230	195	195
   query20	139	135	131	131
   query21	220	139	117	117
   query22	5573	5252	4751	4751
   query23	17249	16795	16519	16519
   query23_1	16588	16734	16706	16706
   query24	7171	1624	1226	1226
   query24_1	1229	1241	1230	1230
   query25	561	455	394	394
   query26	1257	259	150	150
   query27	2776	468	310	310
   query28	4481	1881	1888	1881
   query29	824	587	512	512
   query30	305	245	209	209
   query31	881	714	689	689
   query32	81	71	73	71
   query33	513	341	272	272
   query34	908	909	574	574
   query35	625	683	612	612
   query36	1122	1126	962	962
   query37	130	112	86	86
   query38	2994	2916	2904	2904
   query39	893	863	849	849
   query39_1	828	814	841	814
   query40	226	153	135	135
   query41	62	60	56	56
   query42	104	100	108	100
   query43	375	374	346	346
   query44	
   query45	195	184	187	184
   query46	887	987	623	623
   query47	2177	2139	2045	2045
   query48	312	309	231	231
   query49	625	462	379	379
   query50	685	274	215	215
   query51	4093	4137	4107	4107
   query52	107	106	95	95
   query53	288	338	272	272
   query54	292	262	260	260
   query55	89	80	84	80
   query56	331	314	317	314
   query57	1335	1335	1272	1272
   query58	315	271	268	268
   query59	2517	2674	2524	2524
   query60	349	335	323	323
   query61	151	146	146	146
   query62	626	547	557	547
   query63	320	276	275	275
   query64	4925	1267	1006	1006
   query65	
   query66	1455	449	359	359
   query67	16456	16497	16262	16262
   query68	
   query69	409	306	310	306
   query70	1007	977	900	900
   query71	340	299	296	296
   query72	2799	2680	2614	2614
   query73	539	551	333	333
   query74	10003	9961	9791	9791
   query75	2876	2750	2495	2495
   query76	2315	1032	667	667
   query77	390	391	312	312
   query78	11199	11436	10726	10726
   query79	1162	800	603	603
   query80	1555	666	570	570
   query81	569	301	256	256
   query82	1044	154	117	117
   query83	364	273	260	260
   query84	261	125	114	114
   query85	1239	547	425	425
   query86	422	317	305	305
   query87	3108	3132	3003	3003
   query88	3580	2691	2664	2664
   query89	433	368	353	353
   query90	1861	174	169	169
   query91	164	155	135	135
   query92	81	78	68	68
   query93	988	897	507	507
   query94	624	327	278	278
   query95	582	358	382	358
   query96	644	532	229	229
   query97	2488	2494	2425	2425
   query98	232	223	226	223
   query99	993	998	896	896
   Total cold run time: 255576 ms
   Total hot run time: 184376 ms
   ```
   </details>
   


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "morningman (via GitHub)" <gi...@apache.org>.
morningman merged PR #60978:
URL: https://github.com/apache/doris/pull/60978


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "Thearas (via GitHub)" <gi...@apache.org>.
Thearas commented on PR #60978:
URL: https://github.com/apache/doris/pull/60978#issuecomment-3989528850

   
   Thank you for your contribution to Apache Doris.
   Don't know what should be done next? See [How to process your PR](https://cwiki.apache.org/confluence/display/DORIS/How+to+process+your+PR).
   
   Please clearly describe your PR:
   1. What problem was fixed (it's best to include specific error reporting information). How it was fixed.
   2. Which behaviors were modified. What was the previous behavior, what is it now, why was it modified, and what possible impacts might there be.
   3. What features were added. Why was this function added?
   4. Which code was refactored and why was this part of the code refactored?
   5. Which functions were optimized and what is the difference before and after the optimization?
       


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on code in PR #60978:
URL: https://github.com/apache/doris/pull/60978#discussion_r2876960788


##########
be/src/vec/sink/writer/iceberg/viceberg_sort_writer.cpp:
##########
@@ -0,0 +1,362 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "vec/sink/writer/iceberg/viceberg_sort_writer.h"
+
+#include "runtime/exec_env.h"
+#include "runtime/runtime_state.h"
+#include "vec/spill/spill_stream.h"
+#include "vec/spill/spill_stream_manager.h"
+
+namespace doris::vectorized {
+
+Status VIcebergSortWriter::open(RuntimeState* state, RuntimeProfile* profile,
+                                const RowDescriptor* row_desc) {
+    // row_desc is required for initializing sort expressions
+    DCHECK(row_desc != nullptr);
+    _runtime_state = state;
+    _profile = profile;
+    _row_desc = row_desc;
+
+    // Initialize sort expressions from sort_info (contains ordering columns, asc/desc, nulls first/last)
+    RETURN_IF_ERROR(_vsort_exec_exprs.init(_sort_info, &_pool));
+    RETURN_IF_ERROR(_vsort_exec_exprs.prepare(state, *row_desc, *row_desc));
+    RETURN_IF_ERROR(_vsort_exec_exprs.open(state));
+
+    // Create FullSorter for in-memory sorting with spill support enabled.
+    // Parameters: limit=-1 (no limit), offset=0 (no offset)
+    _sorter = vectorized::FullSorter::create_unique(_vsort_exec_exprs, -1, 0, &_pool,
+                                                    _sort_info.is_asc_order, _sort_info.nulls_first,
+                                                    *row_desc, state, _profile);
+    _sorter->init_profile(_profile);
+    // Enable spill support so the sorter can be used with the spill framework
+    _sorter->set_enable_spill();
+    _do_spill_count_counter = ADD_COUNTER(_profile, "IcebergDoSpillCount", TUnit::UNIT);
+
+    // Open the underlying partition writer that handles actual file I/O
+    RETURN_IF_ERROR(_iceberg_partition_writer->open(state, profile, row_desc));
+    return Status::OK();
+}
+
+Status VIcebergSortWriter::write(vectorized::Block& block) {
+    // Append incoming block data to the sorter's internal buffer
+    RETURN_IF_ERROR(_sorter->append_block(&block));
+    _update_spill_block_batch_row_count(block);
+
+    // When accumulated data size reaches the target file size threshold,
+    // sort the data in memory and flush it directly to a Parquet/ORC file.
+    // This avoids holding too much data in memory before writing.
+    if (_sorter->data_size() >= _target_file_size_bytes) {
+        return _flush_to_file();
+    }
+
+    // If data size is below threshold, wait for more data.
+    // Note: trigger_spill() may be called externally by the memory management
+    // system if memory pressure is high.
+    return Status::OK();
+}
+
+Status VIcebergSortWriter::close(const Status& status) {
+    // Track the actual internal status of operations performed during close.
+    // This is important because if intermediate operations (like do_sort()) fail,
+    // we need to propagate the actual error status to the underlying partition writer's
+    // close() call, rather than the original status parameter which could be OK.
+    Status internal_status = Status::OK();
+
+    // Defer ensures the underlying partition writer is always closed and
+    // spill streams are cleaned up, regardless of whether intermediate operations succeed.
+    // Uses internal_status to propagate any errors that occurred during close operations.
+    Defer defer {[&]() {
+        // If any intermediate operation failed, pass that error to the partition writer;
+        // otherwise, pass the original status from the caller.
+        Status st =
+                _iceberg_partition_writer->close(internal_status.ok() ? status : internal_status);
+        if (!st.ok()) {
+            LOG(WARNING) << fmt::format("_iceberg_partition_writer close failed, reason: {}",
+                                        st.to_string());

Review Comment:
   **[Medium]** The Defer lambda catches the return status of `_iceberg_partition_writer->close()` but only logs a warning and discards it. If the underlying writer's close fails (e.g., a Parquet file flush error), the caller of `VIcebergSortWriter::close()` will receive `Status::OK()` (from line 140) while the actual file close error is silently lost.
   
   This could mask data loss—the caller thinks the write succeeded but the file was not properly closed. Consider propagating this error, e.g., by capturing it in a local variable and returning it from `close()`.
   
   Note: This was the same behavior in the original code before this PR, but since this PR explicitly aims to fix error handling in `close()` (item 4 in the PR description), it would be good to address this too.



##########
be/src/vec/sink/writer/iceberg/viceberg_sort_writer.cpp:
##########
@@ -0,0 +1,362 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "vec/sink/writer/iceberg/viceberg_sort_writer.h"
+
+#include "runtime/exec_env.h"
+#include "runtime/runtime_state.h"
+#include "vec/spill/spill_stream.h"
+#include "vec/spill/spill_stream_manager.h"
+
+namespace doris::vectorized {
+
+Status VIcebergSortWriter::open(RuntimeState* state, RuntimeProfile* profile,
+                                const RowDescriptor* row_desc) {
+    // row_desc is required for initializing sort expressions
+    DCHECK(row_desc != nullptr);
+    _runtime_state = state;
+    _profile = profile;
+    _row_desc = row_desc;
+
+    // Initialize sort expressions from sort_info (contains ordering columns, asc/desc, nulls first/last)
+    RETURN_IF_ERROR(_vsort_exec_exprs.init(_sort_info, &_pool));
+    RETURN_IF_ERROR(_vsort_exec_exprs.prepare(state, *row_desc, *row_desc));
+    RETURN_IF_ERROR(_vsort_exec_exprs.open(state));
+
+    // Create FullSorter for in-memory sorting with spill support enabled.
+    // Parameters: limit=-1 (no limit), offset=0 (no offset)
+    _sorter = vectorized::FullSorter::create_unique(_vsort_exec_exprs, -1, 0, &_pool,
+                                                    _sort_info.is_asc_order, _sort_info.nulls_first,
+                                                    *row_desc, state, _profile);
+    _sorter->init_profile(_profile);
+    // Enable spill support so the sorter can be used with the spill framework
+    _sorter->set_enable_spill();
+    _do_spill_count_counter = ADD_COUNTER(_profile, "IcebergDoSpillCount", TUnit::UNIT);
+
+    // Open the underlying partition writer that handles actual file I/O
+    RETURN_IF_ERROR(_iceberg_partition_writer->open(state, profile, row_desc));
+    return Status::OK();
+}
+
+Status VIcebergSortWriter::write(vectorized::Block& block) {
+    // Append incoming block data to the sorter's internal buffer
+    RETURN_IF_ERROR(_sorter->append_block(&block));
+    _update_spill_block_batch_row_count(block);
+
+    // When accumulated data size reaches the target file size threshold,
+    // sort the data in memory and flush it directly to a Parquet/ORC file.
+    // This avoids holding too much data in memory before writing.
+    if (_sorter->data_size() >= _target_file_size_bytes) {
+        return _flush_to_file();
+    }
+
+    // If data size is below threshold, wait for more data.
+    // Note: trigger_spill() may be called externally by the memory management
+    // system if memory pressure is high.
+    return Status::OK();
+}
+
+Status VIcebergSortWriter::close(const Status& status) {
+    // Track the actual internal status of operations performed during close.
+    // This is important because if intermediate operations (like do_sort()) fail,
+    // we need to propagate the actual error status to the underlying partition writer's
+    // close() call, rather than the original status parameter which could be OK.
+    Status internal_status = Status::OK();
+
+    // Defer ensures the underlying partition writer is always closed and
+    // spill streams are cleaned up, regardless of whether intermediate operations succeed.
+    // Uses internal_status to propagate any errors that occurred during close operations.
+    Defer defer {[&]() {
+        // If any intermediate operation failed, pass that error to the partition writer;
+        // otherwise, pass the original status from the caller.
+        Status st =
+                _iceberg_partition_writer->close(internal_status.ok() ? status : internal_status);
+        if (!st.ok()) {
+            LOG(WARNING) << fmt::format("_iceberg_partition_writer close failed, reason: {}",
+                                        st.to_string());
+        }
+        _cleanup_spill_streams();
+    }};
+
+    // If the original status is already an error or the query is cancelled,
+    // skip all close operations and propagate the original error
+    if (!status.ok() || _runtime_state->is_cancelled()) {
+        return status;
+    }
+
+    // If sorter was never initialized (e.g., no data was written), nothing to do
+    if (_sorter == nullptr) {
+        return Status::OK();
+    }
+
+    // Check if there is any remaining data in the sorter (either unsorted or already sorted blocks)
+    if (!_sorter->merge_sort_state()->unsorted_block()->empty() ||
+        !_sorter->merge_sort_state()->get_sorted_block().empty()) {
+        if (_sorted_streams.empty()) {
+            // No spill has occurred, all data is in memory.
+            // Sort the remaining data, prepare for reading, and write to file.
+            internal_status = _sorter->do_sort();
+            if (!internal_status.ok()) {
+                return internal_status;
+            }
+            internal_status = _sorter->prepare_for_read(false);
+            if (!internal_status.ok()) {
+                return internal_status;
+            }
+            internal_status = _write_sorted_data();
+            return internal_status;
+        }
+
+        // Some data has already been spilled to disk.
+        // Spill the remaining in-memory data to a new spill stream.
+        internal_status = _do_spill();
+        if (!internal_status.ok()) {
+            return internal_status;
+        }
+    }
+
+    // Merge all spilled streams using multi-way merge sort and output final sorted data to files
+    if (!_sorted_streams.empty()) {
+        internal_status = _combine_files_output();
+        if (!internal_status.ok()) {
+            return internal_status;
+        }
+    }
+
+    return Status::OK();
+}
+
+void VIcebergSortWriter::_update_spill_block_batch_row_count(const vectorized::Block& block) {
+    auto rows = block.rows();
+    // Calculate average row size from the first non-empty block to determine
+    // the optimal batch size for spill operations
+    if (rows > 0 && 0 == _avg_row_bytes) {
+        _avg_row_bytes = std::max(1UL, block.bytes() / rows);
+        int64_t spill_batch_bytes = _runtime_state->spill_sort_batch_bytes(); // default 8MB
+        // Calculate how many rows fit in one spill batch (ceiling division)
+        _spill_block_batch_row_count = (spill_batch_bytes + _avg_row_bytes - 1) / _avg_row_bytes;
+    }
+}
+
+Status VIcebergSortWriter::_flush_to_file() {
+    // Sort the accumulated data in memory
+    RETURN_IF_ERROR(_sorter->do_sort());
+    // Prepare the sorted data for sequential reading (builds merge tree if needed)
+    RETURN_IF_ERROR(_sorter->prepare_for_read(false));
+    // Write the sorted data to the current Parquet/ORC file
+    RETURN_IF_ERROR(_write_sorted_data());
+    // Close the current file (it has reached the target size) and open a new writer
+    RETURN_IF_ERROR(_close_current_writer_and_open_next());
+    // Reset the sorter state to accept new data for the next file
+    _sorter->reset();
+    return Status::OK();
+}
+
+Status VIcebergSortWriter::_write_sorted_data() {
+    // Read sorted blocks from the sorter one by one and write them
+    // to the underlying partition writer (Parquet/ORC file)
+    bool eos = false;
+    Block block;
+    while (!eos && !_runtime_state->is_cancelled()) {
+        RETURN_IF_ERROR(_sorter->get_next(_runtime_state, &block, &eos));
+        RETURN_IF_ERROR(_iceberg_partition_writer->write(block));
+        block.clear_column_data();
+    }
+    return Status::OK();
+}
+
+Status VIcebergSortWriter::_close_current_writer_and_open_next() {
+    // Save the current file name and index before closing, so the next file
+    // can use an incremented index (e.g., file_0, file_1, file_2, ...)
+    std::string current_file_name = _iceberg_partition_writer->file_name();
+    int current_file_index = _iceberg_partition_writer->file_name_index();
+    RETURN_IF_ERROR(_iceberg_partition_writer->close(Status::OK()));
+
+    // Use the lambda to create a new partition writer with the next file index
+    _iceberg_partition_writer = _create_writer_lambda(&current_file_name, current_file_index + 1);
+    if (!_iceberg_partition_writer) {
+        return Status::InternalError("Failed to create new partition writer");
+    }
+
+    RETURN_IF_ERROR(_iceberg_partition_writer->open(_runtime_state, _profile, _row_desc));
+    return Status::OK();
+}
+
+int32_t VIcebergSortWriter::_get_spill_batch_size() const {
+    // Clamp the batch row count to int32_t max to prevent overflow
+    if (_spill_block_batch_row_count > std::numeric_limits<int32_t>::max()) {
+        return std::numeric_limits<int32_t>::max();
+    }
+    return static_cast<int32_t>(_spill_block_batch_row_count);
+}
+
+Status VIcebergSortWriter::_do_spill() {
+    COUNTER_UPDATE(_do_spill_count_counter, 1);
+
+    // Explicitly sort the data before preparing for spill read.
+    // Although FullSorter::prepare_for_read(is_spill=true) internally calls do_sort()
+    // when there is unsorted data (see sorter.cpp), we call do_sort() explicitly here
+    // for clarity and to guarantee that the data written to the spill stream is sorted.
+    // This ensures correctness of the subsequent multi-way merge phase.
+    RETURN_IF_ERROR(_sorter->do_sort());
+
+    // prepare_for_read(is_spill=true) adjusts limit/offset for spill mode
+    // and builds the merge tree for reading sorted data
+    RETURN_IF_ERROR(_sorter->prepare_for_read(true));
+    int32_t batch_size = _get_spill_batch_size();
+
+    // Register a new spill stream to store the sorted data on disk
+    SpillStreamSPtr spilling_stream;
+    RETURN_IF_ERROR(ExecEnv::GetInstance()->spill_stream_mgr()->register_spill_stream(
+            _runtime_state, spilling_stream, print_id(_runtime_state->query_id()), "iceberg-sort",
+            1 /* node_id */, batch_size, _runtime_state->spill_sort_batch_bytes(), _profile));
+    _sorted_streams.emplace_back(spilling_stream);
+
+    // Read sorted data from the sorter in batches and write to the spill stream
+    bool eos = false;
+    Block block;
+    while (!eos && !_runtime_state->is_cancelled()) {
+        RETURN_IF_ERROR(_sorter->merge_sort_read_for_spill(
+                _runtime_state, &block, (int)_spill_block_batch_row_count, &eos));
+        RETURN_IF_ERROR(spilling_stream->spill_block(_runtime_state, block, eos));

Review Comment:
   **[Medium]** This uses a C-style cast `(int)_spill_block_batch_row_count` which is a narrowing conversion from `size_t` to `int`. The `_get_spill_batch_size()` method was specifically created (a few lines above) to handle this conversion safely with bounds checking. This line should use it:
   ```cpp
   RETURN_IF_ERROR(_sorter->merge_sort_read_for_spill(
           _runtime_state, &block, _get_spill_batch_size(), &eos));
   ```
   Using the C-style cast defeats the purpose of having the safe helper method.



##########
be/src/vec/sink/writer/iceberg/viceberg_sort_writer.cpp:
##########
@@ -0,0 +1,362 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "vec/sink/writer/iceberg/viceberg_sort_writer.h"
+
+#include "runtime/exec_env.h"
+#include "runtime/runtime_state.h"
+#include "vec/spill/spill_stream.h"
+#include "vec/spill/spill_stream_manager.h"

Review Comment:
   **[Low]** This new `.cpp` file is missing `compile_check_begin.h` / `compile_check_end.h` includes. The codebase convention (and the code-review checklist) requires new files to include these paired headers to enable `-Wconversion` as an error, which would have caught the narrowing cast issue on line 234. Consider adding:
   ```cpp
   #include "common/compile_check_begin.h"
   ```
   after the last include, and:
   ```cpp
   #include "common/compile_check_end.h"
   ```
   at the end of the file after the namespace closing brace.



##########
be/src/pipeline/exec/spill_iceberg_table_sink_operator.cpp:
##########
@@ -182,7 +182,7 @@ void SpillIcebergTableSinkLocalState::_init_spill_counters() {
     ADD_COUNTER_WITH_LEVEL(profile, "SpillReadTaskCount", TUnit::UNIT, 1);
     ADD_TIMER_WITH_LEVEL(profile, "SpillReadTaskWaitInQueueTime", 1);
     ADD_TIMER_WITH_LEVEL(profile, "SpillReadFileTime", 1);
-    ADD_TIMER_WITH_LEVEL(profile, "SpillReadDerializeBlockTime", 1);
+    ADD_TIMER_WITH_LEVEL(profile, "SpillReadDeserializeBlockTime", 1);
     ADD_COUNTER_WITH_LEVEL(profile, "SpillReadBlockCount", TUnit::UNIT, 1);

Review Comment:
   **[Medium]** The typo fix from `SpillReadDerializeBlockTime` to `SpillReadDeserializeBlockTime` is correct, but it's **incomplete across the codebase**. Two test files still use the old misspelled name and need to be updated as well:
   
   1. `be/test/pipeline/operator/spillable_operator_test_helper.cpp` line 56: `"SpillReadDerializeBlockTime"`
   2. `be/test/pipeline/exec/multi_cast_data_streamer_test.cpp` lines 59 and 103: `"SpillReadDerializeBlockTime"`
   
   After this PR, the production code registers the counter as `SpillReadDeserializeBlockTime`, but these tests will still register counters with the old name `SpillReadDerializeBlockTime`. This will cause `get_counter()` lookups to return `nullptr` when the spill reader tries to find its counter by the new name, potentially causing test failures or null dereferences.



-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

Posted by "doris-robot (via GitHub)" <gi...@apache.org>.
doris-robot commented on PR #60978:
URL: https://github.com/apache/doris/pull/60978#issuecomment-3990141095

   
   <details>
   <summary>TPC-H: <b>Total hot run time: 28975 ms</b></summary>
   
   ```
   machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
   scripts: https://github.com/apache/doris/tree/master/tools/tpch-tools
   Tpch sf100 test result on commit 557fdd355f6849f6e5ef5eaf82a00e4c7479e210, data reload: false
   
   ------ Round 1 ----------------------------------
   ============================================
   q1	17687	4513	4324	4324
   q2	q3	10633	752	520	520
   q4	4689	355	251	251
   q5	7587	1190	1024	1024
   q6	172	172	145	145
   q7	805	838	665	665
   q8	9825	1453	1314	1314
   q9	5610	4763	4701	4701
   q10	6846	1895	1651	1651
   q11	486	250	236	236
   q12	759	571	468	468
   q13	17774	4234	3438	3438
   q14	232	239	212	212
   q15	940	810	787	787
   q16	761	715	686	686
   q17	745	859	457	457
   q18	5907	5312	5285	5285
   q19	1485	993	614	614
   q20	531	494	387	387
   q21	4699	1956	1554	1554
   q22	389	327	256	256
   Total cold run time: 98562 ms
   Total hot run time: 28975 ms
   
   ----- Round 2, with runtime_filter_mode=off -----
   ============================================
   q1	4783	4697	4590	4590
   q2	q3	2030	2250	1746	1746
   q4	882	1174	763	763
   q5	4060	4366	4362	4362
   q6	188	175	144	144
   q7	1778	1665	1520	1520
   q8	2491	2730	2616	2616
   q9	7496	7422	7429	7422
   q10	2675	2839	2456	2456
   q11	550	423	410	410
   q12	525	594	460	460
   q13	4184	4779	3598	3598
   q14	283	298	278	278
   q15	868	826	811	811
   q16	723	796	709	709
   q17	1180	1660	1365	1365
   q18	7331	6752	6690	6690
   q19	891	868	889	868
   q20	2103	2134	1984	1984
   q21	3941	3497	3357	3357
   q22	473	414	368	368
   Total cold run time: 49435 ms
   Total hot run time: 46517 ms
   ```
   </details>
   


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


Re: [PR] [improvement](iceberg) Improve VIcebergSortWriter code quality [doris]

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

   PR approved by at least one committer and no changes requested.


-- 
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: commits-unsubscribe@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org