Coverage Report

Created: 2026-07-30 00:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/sink/viceberg_merge_sink.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exec/sink/viceberg_merge_sink.h"
19
20
#include <fmt/format.h>
21
22
#include "agent/be_exec_version_manager.h"
23
#include "common/consts.h"
24
#include "common/exception.h"
25
#include "common/logging.h"
26
#include "core/block/block.h"
27
#include "core/column/column_nullable.h"
28
#include "core/column/column_string.h"
29
#include "core/column/column_struct.h"
30
#include "core/column/column_vector.h"
31
#include "core/data_type/data_type_nullable.h"
32
#include "core/data_type/data_type_struct.h"
33
#include "exec/sink/sink_common.h"
34
#include "exec/sink/viceberg_delete_sink.h"
35
#include "exec/sink/writer/iceberg/viceberg_table_writer.h"
36
#include "exprs/vexpr_context.h"
37
#include "format/table/iceberg/schema.h"
38
#include "format/table/iceberg/schema_parser.h"
39
#include "runtime/runtime_state.h"
40
#include "util/string_util.h"
41
42
namespace doris {
43
44
namespace {} // namespace
45
46
VIcebergMergeSink::VIcebergMergeSink(const TDataSink& t_sink, const VExprContextSPtrs& output_exprs,
47
                                     std::shared_ptr<Dependency> dep,
48
                                     std::shared_ptr<Dependency> fin_dep)
49
14
        : AsyncResultWriter(output_exprs, dep, fin_dep), _t_sink(t_sink) {
50
14
    DCHECK(_t_sink.__isset.iceberg_merge_sink);
51
14
}
52
53
14
VIcebergMergeSink::~VIcebergMergeSink() = default;
54
55
14
Status VIcebergMergeSink::init_properties(ObjectPool* pool, const RowDescriptor& row_desc) {
56
14
    RETURN_IF_ERROR(_build_inner_sinks());
57
58
14
    _table_writer = std::make_unique<VIcebergTableWriter>(_table_sink, _table_output_expr_ctxs,
59
14
                                                          nullptr, nullptr);
60
14
    _table_writer->defer_file_cleanup_until_outer_close();
61
14
    _delete_writer = std::make_unique<VIcebergDeleteSink>(_delete_sink, _delete_output_expr_ctxs,
62
14
                                                          nullptr, nullptr);
63
14
    _delete_writer->defer_file_cleanup_until_outer_close();
64
14
    RETURN_IF_ERROR(_table_writer->init_properties(pool, row_desc));
65
14
    RETURN_IF_ERROR(_delete_writer->init_properties(pool));
66
14
    return Status::OK();
67
14
}
68
69
14
Status VIcebergMergeSink::open(RuntimeState* state, RuntimeProfile* profile) {
70
14
    _state = state;
71
72
14
    _written_rows_counter = ADD_COUNTER(profile, "RowsWritten", TUnit::UNIT);
73
14
    _insert_rows_counter = ADD_COUNTER(profile, "InsertRows", TUnit::UNIT);
74
14
    _delete_rows_counter = ADD_COUNTER(profile, "DeleteRows", TUnit::UNIT);
75
    // The query-wide version keeps validation all-or-nothing during a rolling BE upgrade.
76
14
    _require_merge_cardinality_check =
77
14
            _require_merge_cardinality_check &&
78
14
            state->be_exec_version() >= SUPPORT_ICEBERG_MERGE_CARDINALITY_VERSION;
79
14
    if (_require_merge_cardinality_check) {
80
11
        _matched_row_id_state_bytes_counter =
81
11
                ADD_COUNTER(profile, "MatchedRowIdStateBytes", TUnit::BYTES);
82
11
    }
83
14
    _send_data_timer = ADD_TIMER(profile, "SendDataTime");
84
14
    _open_timer = ADD_TIMER(profile, "OpenTime");
85
14
    _close_timer = ADD_TIMER(profile, "CloseTime");
86
87
14
    SCOPED_TIMER(_open_timer);
88
89
14
    RETURN_IF_ERROR(_prepare_output_layout());
90
91
12
    RuntimeProfile* table_profile = profile->create_child("IcebergMergeTableWriter", true, true);
92
12
    RuntimeProfile* delete_profile = profile->create_child("IcebergMergeDeleteWriter", true, true);
93
94
12
    RETURN_IF_ERROR(_table_writer->open(state, table_profile));
95
11
    RETURN_IF_ERROR(_delete_writer->open(state, delete_profile));
96
97
11
    return Status::OK();
98
11
}
99
100
74
Status VIcebergMergeSink::write(RuntimeState* state, Block& block) {
101
74
    SCOPED_TIMER(_send_data_timer);
102
74
    if (block.rows() == 0) {
103
0
        return Status::OK();
104
0
    }
105
106
74
    Block output_block;
107
74
    RETURN_IF_ERROR(_projection_block(block, &output_block));
108
74
    if (output_block.rows() == 0) {
109
0
        return Status::OK();
110
0
    }
111
112
74
    if (_operation_idx < 0 || _row_id_idx < 0) {
113
0
        return Status::InternalError("Iceberg merge sink missing operation/row_id columns");
114
0
    }
115
116
74
    const auto& op_column = output_block.get_by_position(_operation_idx).column;
117
74
    const auto* op_data = remove_nullable(op_column).get();
118
119
74
    IColumn::Filter delete_filter(output_block.rows(), 0);
120
74
    IColumn::Filter insert_filter(output_block.rows(), 0);
121
74
    bool has_delete = false;
122
74
    bool has_insert = false;
123
74
    size_t delete_rows = 0;
124
74
    size_t insert_rows = 0;
125
126
102k
    for (size_t i = 0; i < output_block.rows(); ++i) {
127
102k
        int8_t op = static_cast<int8_t>(op_data->get_int(i));
128
102k
        bool delete_op = is_delete_op(op);
129
102k
        bool insert_op = is_insert_op(op);
130
102k
        if (!delete_op && !insert_op) {
131
1
            return Status::InternalError("Unknown Iceberg merge operation {}", op);
132
1
        }
133
102k
        if (delete_op) {
134
102k
            delete_filter[i] = 1;
135
102k
            has_delete = true;
136
102k
            ++delete_rows;
137
102k
        }
138
102k
        if (insert_op) {
139
102k
            insert_filter[i] = 1;
140
102k
            has_insert = true;
141
102k
            ++insert_rows;
142
102k
        }
143
102k
    }
144
145
73
    if (_require_merge_cardinality_check) {
146
        // The physical sink hashes matched rows by row_id, so exact state retained across blocks
147
        // enforces SQL MERGE cardinality for the whole query without changing UPDATE semantics.
148
69
        RETURN_IF_ERROR(_validate_matched_row_ids(output_block, delete_filter.data()));
149
68
        COUNTER_SET(_matched_row_id_state_bytes_counter,
150
68
                    static_cast<int64_t>(_matched_row_id_state_size));
151
68
    }
152
72
    _row_count += output_block.rows();
153
72
    _delete_row_count += delete_rows;
154
72
    _insert_row_count += insert_rows;
155
156
72
    bool skip_io = false;
157
72
#ifdef BE_TEST
158
72
    skip_io = _skip_io;
159
72
#endif
160
161
72
    if (has_delete && !skip_io) {
162
0
        Block delete_block = output_block;
163
0
        std::vector<int> delete_indices {_row_id_idx};
164
0
        delete_block.erase_not_in(delete_indices);
165
0
        Block::filter_block_internal(&delete_block, delete_filter);
166
0
        RETURN_IF_ERROR(_delete_writer->write(state, delete_block));
167
0
    }
168
169
72
    if (has_insert && !skip_io) {
170
0
        if (_data_column_indices.empty()) {
171
0
            return Status::InternalError("Iceberg merge sink has no data columns for insert");
172
0
        }
173
0
        Block insert_block = output_block;
174
0
        insert_block.erase_not_in(_data_column_indices);
175
0
        Block::filter_block_internal(&insert_block, insert_filter);
176
0
        RETURN_IF_ERROR(_table_writer->write_prepared_block(insert_block));
177
0
    }
178
179
72
    if (_written_rows_counter != nullptr) {
180
72
        COUNTER_UPDATE(_written_rows_counter, output_block.rows());
181
72
    }
182
72
    if (_insert_rows_counter != nullptr) {
183
72
        COUNTER_UPDATE(_insert_rows_counter, insert_rows);
184
72
    }
185
72
    if (_delete_rows_counter != nullptr) {
186
72
        COUNTER_UPDATE(_delete_rows_counter, delete_rows);
187
72
    }
188
189
72
    return Status::OK();
190
72
}
191
192
Status VIcebergMergeSink::_validate_matched_row_ids(const Block& block,
193
69
                                                    const uint8_t* delete_filter) {
194
69
    const auto& row_id = block.get_by_position(_row_id_idx);
195
69
    const IColumn* row_id_data = row_id.column.get();
196
69
    const IDataType* row_id_type = row_id.type.get();
197
69
    const auto* nullable_row_id = check_and_get_column<ColumnNullable>(row_id_data);
198
69
    if (nullable_row_id != nullptr) {
199
0
        row_id_data = nullable_row_id->get_nested_column_ptr().get();
200
0
    }
201
69
    if (const auto* nullable_type = check_and_get_data_type<DataTypeNullable>(row_id_type)) {
202
0
        row_id_type = nullable_type->get_nested_type().get();
203
0
    }
204
205
69
    const auto* struct_column = check_and_get_column<ColumnStruct>(row_id_data);
206
69
    const auto* struct_type = check_and_get_data_type<DataTypeStruct>(row_id_type);
207
69
    if (struct_column == nullptr || struct_type == nullptr) {
208
0
        return Status::InternalError("Iceberg merge row_id column is not a struct");
209
0
    }
210
211
69
    int file_path_idx = -1;
212
69
    int row_position_idx = -1;
213
69
    const auto& field_names = struct_type->get_element_names();
214
207
    for (size_t i = 0; i < field_names.size(); ++i) {
215
138
        std::string field_name = doris::to_lower(field_names[i]);
216
138
        if (field_name == "file_path") {
217
69
            file_path_idx = static_cast<int>(i);
218
69
        } else if (field_name == "row_position") {
219
69
            row_position_idx = static_cast<int>(i);
220
69
        }
221
138
    }
222
69
    if (file_path_idx < 0 || row_position_idx < 0) {
223
0
        return Status::InternalError(
224
0
                "Iceberg merge row_id must contain file_path and row_position fields");
225
0
    }
226
227
69
    const auto& file_path_column = struct_column->get_column_ptr(file_path_idx);
228
69
    const auto& row_position_column = struct_column->get_column_ptr(row_position_idx);
229
69
    const auto* nullable_file_path = check_and_get_column<ColumnNullable>(file_path_column.get());
230
69
    const auto* nullable_row_position =
231
69
            check_and_get_column<ColumnNullable>(row_position_column.get());
232
69
    const auto* file_paths =
233
69
            check_and_get_column<ColumnString>(remove_nullable(file_path_column).get());
234
69
    const auto* row_positions = check_and_get_column<ColumnVector<TYPE_BIGINT>>(
235
69
            remove_nullable(row_position_column).get());
236
69
    if (file_paths == nullptr || row_positions == nullptr) {
237
0
        return Status::InternalError("Iceberg merge row_id fields have incorrect types");
238
0
    }
239
240
69
    std::map<roaring::Roaring64Map*, size_t> touched_bitmap_sizes;
241
102k
    for (size_t i = 0; i < block.rows(); ++i) {
242
102k
        if (delete_filter[i] == 0) {
243
2
            continue;
244
2
        }
245
102k
        if ((nullable_row_id != nullptr && nullable_row_id->is_null_at(i)) ||
246
102k
            (nullable_file_path != nullptr && nullable_file_path->is_null_at(i)) ||
247
102k
            (nullable_row_position != nullptr && nullable_row_position->is_null_at(i))) {
248
0
            return Status::InternalError("Iceberg merge matched row_id cannot be null");
249
0
        }
250
251
102k
        int64_t row_position = row_positions->get_element(i);
252
102k
        if (row_position < 0) {
253
0
            return Status::InternalError("Invalid row_position {} in Iceberg merge row_id",
254
0
                                         row_position);
255
0
        }
256
        // Intern each file path once and keep exact positions in a compressed bitmap; retaining a
257
        // full path string per matched row makes MERGE memory grow with path_length * row_count.
258
102k
        auto [file_it, inserted] =
259
102k
                _matched_row_positions.try_emplace(file_paths->get_data_at(i).to_string());
260
102k
        auto* positions = &file_it->second;
261
102k
        auto touched_it = touched_bitmap_sizes.find(positions);
262
102k
        if (touched_it == touched_bitmap_sizes.end()) {
263
2.05k
            touched_it = touched_bitmap_sizes.emplace(positions, positions->getSizeInBytes()).first;
264
2.05k
        }
265
102k
        if (inserted) {
266
2.05k
            _matched_row_id_state_size +=
267
2.05k
                    sizeof(std::pair<const std::string, roaring::Roaring64Map>);
268
2.05k
            _matched_row_id_state_size += file_it->first.capacity();
269
2.05k
            _matched_row_id_state_size += touched_it->second;
270
2.05k
        }
271
102k
        if (!positions->addChecked(static_cast<uint64_t>(row_position))) {
272
1
            return Status::InvalidArgument(
273
1
                    "Iceberg MERGE failed because multiple source rows matched the same target "
274
1
                    "row");
275
1
        }
276
102k
    }
277
278
    // Measure only bitmaps touched by this block; rescanning all retained files on every write
279
    // makes a many-file MERGE quadratic in the number of input blocks.
280
2.05k
    for (const auto& [positions, previous_size] : touched_bitmap_sizes) {
281
2.05k
        size_t current_size = positions->getSizeInBytes();
282
2.05k
        if (current_size >= previous_size) {
283
2.05k
            _matched_row_id_state_size += current_size - previous_size;
284
2.05k
        } else {
285
0
            _matched_row_id_state_size -= previous_size - current_size;
286
0
        }
287
2.05k
    }
288
68
    return Status::OK();
289
69
}
290
291
4
Status VIcebergMergeSink::close(Status close_status) {
292
4
    SCOPED_TIMER(_close_timer);
293
294
4
    if (!close_status.ok()) {
295
1
        LOG(WARNING) << fmt::format("VIcebergMergeSink close with error: {}",
296
1
                                    close_status.to_string());
297
1
        if (_table_writer) {
298
1
            static_cast<void>(_table_writer->close(close_status));
299
1
        }
300
1
        if (_delete_writer) {
301
1
            static_cast<void>(_delete_writer->close(close_status));
302
1
        }
303
1
        return close_status;
304
1
    }
305
306
3
    Status table_status = Status::OK();
307
3
    Status delete_status = Status::OK();
308
3
    if (_table_writer) {
309
3
        table_status = _table_writer->close(close_status);
310
3
    }
311
3
    if (_delete_writer) {
312
3
        delete_status = _delete_writer->close(close_status);
313
3
    }
314
315
3
    if (_written_rows_counter != nullptr) {
316
3
        COUNTER_SET(_written_rows_counter, static_cast<int64_t>(_row_count));
317
3
    }
318
3
    if (_insert_rows_counter != nullptr) {
319
3
        COUNTER_SET(_insert_rows_counter, static_cast<int64_t>(_insert_row_count));
320
3
    }
321
3
    if (_delete_rows_counter != nullptr) {
322
3
        COUNTER_SET(_delete_rows_counter, static_cast<int64_t>(_delete_row_count));
323
3
    }
324
325
3
    Status result_status = table_status.ok() ? delete_status : table_status;
326
3
    if (_table_writer) {
327
3
        _table_writer->finish_deferred_file_cleanup(result_status);
328
3
    }
329
3
    if (_delete_writer) {
330
3
        _delete_writer->finish_deferred_file_cleanup(result_status);
331
3
    }
332
3
    return result_status;
333
4
}
334
335
14
Status VIcebergMergeSink::_build_inner_sinks() {
336
14
    if (!_t_sink.__isset.iceberg_merge_sink) {
337
0
        return Status::InternalError("Missing iceberg merge sink config");
338
0
    }
339
340
14
    const auto& merge_sink = _t_sink.iceberg_merge_sink;
341
    // Missing means an old FE plan, which predates SQL MERGE cardinality validation.
342
14
    _require_merge_cardinality_check = merge_sink.__isset.require_merge_cardinality_check &&
343
14
                                       merge_sink.require_merge_cardinality_check;
344
345
14
    TIcebergTableSink table_sink;
346
14
    if (merge_sink.__isset.db_name) {
347
14
        table_sink.__set_db_name(merge_sink.db_name);
348
14
    }
349
14
    if (merge_sink.__isset.tb_name) {
350
14
        table_sink.__set_tb_name(merge_sink.tb_name);
351
14
    }
352
14
    if (merge_sink.__isset.schema_json) {
353
14
        table_sink.__set_schema_json(merge_sink.schema_json);
354
14
    }
355
14
    if (merge_sink.__isset.partition_specs_json) {
356
0
        table_sink.__set_partition_specs_json(merge_sink.partition_specs_json);
357
0
    }
358
14
    if (merge_sink.__isset.partition_spec_id) {
359
14
        table_sink.__set_partition_spec_id(merge_sink.partition_spec_id);
360
14
    }
361
14
    if (merge_sink.__isset.sort_fields) {
362
0
        table_sink.__set_sort_fields(merge_sink.sort_fields);
363
0
    }
364
14
    if (merge_sink.__isset.file_format) {
365
14
        table_sink.__set_file_format(merge_sink.file_format);
366
14
    }
367
14
    if (merge_sink.__isset.compression_type) {
368
14
        table_sink.__set_compression_type(merge_sink.compression_type);
369
14
    }
370
14
    if (merge_sink.__isset.output_path) {
371
14
        table_sink.__set_output_path(merge_sink.output_path);
372
14
    }
373
14
    if (merge_sink.__isset.original_output_path) {
374
14
        table_sink.__set_original_output_path(merge_sink.original_output_path);
375
14
    }
376
14
    if (merge_sink.__isset.hadoop_config) {
377
0
        table_sink.__set_hadoop_config(merge_sink.hadoop_config);
378
0
    }
379
14
    if (merge_sink.__isset.file_type) {
380
14
        table_sink.__set_file_type(merge_sink.file_type);
381
14
    }
382
14
    if (merge_sink.__isset.broker_addresses) {
383
0
        table_sink.__set_broker_addresses(merge_sink.broker_addresses);
384
0
    }
385
14
    if (merge_sink.__isset.collect_column_stats) {
386
0
        table_sink.__set_collect_column_stats(merge_sink.collect_column_stats);
387
0
    }
388
14
    _table_sink.__set_type(TDataSinkType::ICEBERG_TABLE_SINK);
389
14
    _table_sink.__set_iceberg_table_sink(table_sink);
390
391
14
    TIcebergDeleteSink delete_sink;
392
14
    if (merge_sink.__isset.db_name) {
393
14
        delete_sink.__set_db_name(merge_sink.db_name);
394
14
    }
395
14
    if (merge_sink.__isset.tb_name) {
396
14
        delete_sink.__set_tb_name(merge_sink.tb_name);
397
14
    }
398
14
    if (merge_sink.__isset.delete_type) {
399
14
        delete_sink.__set_delete_type(merge_sink.delete_type);
400
14
    }
401
14
    if (merge_sink.__isset.file_format) {
402
14
        delete_sink.__set_file_format(merge_sink.file_format);
403
14
    }
404
14
    if (merge_sink.__isset.compression_type) {
405
14
        delete_sink.__set_compress_type(merge_sink.compression_type);
406
14
    }
407
14
    if (merge_sink.__isset.output_path) {
408
14
        delete_sink.__set_output_path(merge_sink.output_path);
409
14
    }
410
14
    if (merge_sink.__isset.table_location) {
411
14
        delete_sink.__set_table_location(merge_sink.table_location);
412
14
    }
413
14
    if (merge_sink.__isset.hadoop_config) {
414
0
        delete_sink.__set_hadoop_config(merge_sink.hadoop_config);
415
0
    }
416
14
    if (merge_sink.__isset.file_type) {
417
14
        delete_sink.__set_file_type(merge_sink.file_type);
418
14
    }
419
14
    if (merge_sink.__isset.partition_spec_id_for_delete) {
420
14
        delete_sink.__set_partition_spec_id(merge_sink.partition_spec_id_for_delete);
421
14
    }
422
14
    if (merge_sink.__isset.partition_data_json_for_delete) {
423
0
        delete_sink.__set_partition_data_json(merge_sink.partition_data_json_for_delete);
424
0
    }
425
14
    if (merge_sink.__isset.broker_addresses) {
426
0
        delete_sink.__set_broker_addresses(merge_sink.broker_addresses);
427
0
    }
428
14
    if (merge_sink.__isset.format_version) {
429
0
        delete_sink.__set_format_version(merge_sink.format_version);
430
0
    }
431
14
    if (merge_sink.__isset.rewritable_delete_file_sets) {
432
0
        delete_sink.__set_rewritable_delete_file_sets(merge_sink.rewritable_delete_file_sets);
433
0
    }
434
14
    _delete_sink.__set_type(TDataSinkType::ICEBERG_DELETE_SINK);
435
14
    _delete_sink.__set_iceberg_delete_sink(delete_sink);
436
437
14
    return Status::OK();
438
14
}
439
440
14
Status VIcebergMergeSink::_prepare_output_layout() {
441
14
    if (_vec_output_expr_ctxs.empty()) {
442
0
        return Status::InternalError("Iceberg merge sink has empty output expressions");
443
0
    }
444
445
14
    std::string row_id_name = doris::to_lower(BeConsts::ICEBERG_ROWID_COL);
446
14
    std::string op_name = doris::to_lower(kOperationColumnName);
447
448
14
    _operation_idx = -1;
449
14
    _row_id_idx = -1;
450
68
    for (size_t i = 0; i < _vec_output_expr_ctxs.size(); ++i) {
451
54
        std::string expr_name = doris::to_lower(_vec_output_expr_ctxs[i]->expr_name());
452
54
        if (_operation_idx < 0 && expr_name == op_name) {
453
13
            _operation_idx = static_cast<int>(i);
454
41
        } else if (_row_id_idx < 0 && expr_name == row_id_name) {
455
13
            _row_id_idx = static_cast<int>(i);
456
13
        }
457
54
    }
458
459
14
    if (_operation_idx < 0) {
460
1
        return Status::InternalError("Iceberg merge sink missing operation column");
461
1
    }
462
13
    if (_row_id_idx < 0) {
463
1
        return Status::InternalError("Iceberg merge sink missing row_id column");
464
1
    }
465
466
12
    _data_column_indices.clear();
467
12
    _table_output_expr_ctxs.clear();
468
60
    for (size_t i = 0; i < _vec_output_expr_ctxs.size(); ++i) {
469
48
        if (static_cast<int>(i) == _operation_idx || static_cast<int>(i) == _row_id_idx) {
470
24
            continue;
471
24
        }
472
24
        _data_column_indices.push_back(static_cast<int>(i));
473
24
        _table_output_expr_ctxs.emplace_back(_vec_output_expr_ctxs[i]);
474
24
    }
475
476
12
    return Status::OK();
477
13
}
478
479
} // namespace doris