Coverage Report

Created: 2026-07-16 19:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/sink/viceberg_delete_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_delete_sink.h"
19
20
#include <fmt/format.h>
21
#include <rapidjson/stringbuffer.h>
22
#include <rapidjson/writer.h>
23
#include <zlib.h>
24
25
#include "common/logging.h"
26
#include "core/block/column_with_type_and_name.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_factory.hpp"
32
#include "core/data_type/data_type_nullable.h"
33
#include "core/data_type/data_type_number.h"
34
#include "core/data_type/data_type_string.h"
35
#include "core/data_type/data_type_struct.h"
36
#include "exec/common/endian.h"
37
#include "exprs/vexpr.h"
38
#include "format/table/deletion_vector.h"
39
#include "format/table/iceberg_delete_file_reader_helper.h"
40
#include "format/transformer/vfile_format_transformer.h"
41
#include "io/file_factory.h"
42
#include "runtime/runtime_state.h"
43
#include "util/slice.h"
44
#include "util/string_util.h"
45
#include "util/uid_util.h"
46
47
namespace doris {
48
49
namespace {
50
51
class RewriteBitmapVisitor final : public IcebergPositionDeleteVisitor {
52
public:
53
    RewriteBitmapVisitor(const std::string& referenced_data_file_path,
54
                         roaring::Roaring64Map* rows_to_delete)
55
0
            : _referenced_data_file_path(referenced_data_file_path),
56
0
              _rows_to_delete(rows_to_delete) {}
57
58
0
    Status visit(const std::string& file_path, int64_t pos) override {
59
0
        if (_rows_to_delete == nullptr) {
60
0
            return Status::InvalidArgument("rows_to_delete is null");
61
0
        }
62
0
        if (file_path == _referenced_data_file_path) {
63
0
            _rows_to_delete->add(static_cast<uint64_t>(pos));
64
0
        }
65
0
        return Status::OK();
66
0
    }
67
68
private:
69
    const std::string& _referenced_data_file_path;
70
    roaring::Roaring64Map* _rows_to_delete;
71
};
72
73
Status load_rewritable_delete_rows(RuntimeState* state, RuntimeProfile* profile,
74
                                   const std::string& referenced_data_file_path,
75
                                   const std::vector<TIcebergDeleteFileDesc>& delete_files,
76
                                   const std::map<std::string, std::string>& hadoop_conf,
77
                                   TFileType::type file_type,
78
                                   const std::vector<TNetworkAddress>& broker_addresses,
79
0
                                   roaring::Roaring64Map* rows_to_delete) {
80
0
    if (rows_to_delete == nullptr) {
81
0
        return Status::InvalidArgument("rows_to_delete is null");
82
0
    }
83
0
    if (state == nullptr || profile == nullptr || delete_files.empty()) {
84
0
        return Status::OK();
85
0
    }
86
87
0
    TFileScanRangeParams params =
88
0
            build_iceberg_delete_scan_range_params(hadoop_conf, file_type, broker_addresses);
89
0
    IcebergDeleteFileIOContext delete_file_io_ctx(state);
90
0
    IcebergDeleteFileReaderOptions options;
91
0
    options.state = state;
92
0
    options.profile = profile;
93
0
    options.scan_params = &params;
94
0
    options.io_ctx = &delete_file_io_ctx.io_ctx;
95
0
    options.batch_size = 102400;
96
97
0
    for (const auto& delete_file : delete_files) {
98
0
        if (is_iceberg_deletion_vector(delete_file)) {
99
0
            RETURN_IF_ERROR(read_iceberg_deletion_vector(delete_file, options, rows_to_delete));
100
0
            continue;
101
0
        }
102
0
        RewriteBitmapVisitor visitor(referenced_data_file_path, rows_to_delete);
103
0
        RETURN_IF_ERROR(read_iceberg_position_delete_file(delete_file, options, &visitor));
104
0
    }
105
0
    return Status::OK();
106
0
}
107
108
} // namespace
109
110
32
Status calculate_iceberg_deletion_vector_content_size(size_t bitmap_size, int64_t* content_size) {
111
32
    DORIS_CHECK(content_size != nullptr);
112
32
    constexpr size_t max_bitmap_size = static_cast<size_t>(MAX_ICEBERG_DELETION_VECTOR_BYTES) -
113
32
                                       ICEBERG_DELETION_VECTOR_BLOB_OVERHEAD_BYTES;
114
32
    if (bitmap_size > max_bitmap_size) {
115
1
        return Status::NotSupported(
116
1
                "Iceberg deletion vector bitmap size exceeds Doris supported limit: {}, "
117
1
                "maximum bitmap size: {}, content size limit: {}",
118
1
                bitmap_size, max_bitmap_size, MAX_ICEBERG_DELETION_VECTOR_BYTES);
119
1
    }
120
31
    *content_size = static_cast<int64_t>(bitmap_size + ICEBERG_DELETION_VECTOR_BLOB_OVERHEAD_BYTES);
121
31
    return Status::OK();
122
32
}
123
124
VIcebergDeleteSink::VIcebergDeleteSink(const TDataSink& t_sink,
125
                                       const VExprContextSPtrs& output_exprs,
126
                                       std::shared_ptr<Dependency> dep,
127
                                       std::shared_ptr<Dependency> fin_dep)
128
850
        : AsyncResultWriter(output_exprs, dep, fin_dep), _t_sink(t_sink) {
129
850
    DCHECK(_t_sink.__isset.iceberg_delete_sink);
130
850
}
131
132
843
Status VIcebergDeleteSink::init_properties(ObjectPool* pool) {
133
843
    const auto& delete_sink = _t_sink.iceberg_delete_sink;
134
135
843
    _delete_type = delete_sink.delete_type;
136
843
    if (_delete_type != TFileContent::POSITION_DELETES) {
137
1
        return Status::NotSupported("Iceberg delete only supports position delete files");
138
1
    }
139
140
    // Get file format settings
141
842
    if (delete_sink.__isset.file_format) {
142
842
        _file_format_type = delete_sink.file_format;
143
842
    }
144
145
842
    if (delete_sink.__isset.compress_type) {
146
842
        _compress_type = delete_sink.compress_type;
147
842
    }
148
149
    // Get output path and table location
150
842
    if (delete_sink.__isset.output_path) {
151
842
        _output_path = delete_sink.output_path;
152
842
    }
153
154
842
    if (delete_sink.__isset.table_location) {
155
842
        _table_location = delete_sink.table_location;
156
842
    }
157
158
    // Get Hadoop configuration
159
842
    if (delete_sink.__isset.hadoop_config) {
160
834
        _hadoop_conf.insert(delete_sink.hadoop_config.begin(), delete_sink.hadoop_config.end());
161
834
    }
162
163
842
    if (delete_sink.__isset.file_type) {
164
839
        _file_type = delete_sink.file_type;
165
839
    }
166
167
842
    if (delete_sink.__isset.broker_addresses) {
168
0
        _broker_addresses.assign(delete_sink.broker_addresses.begin(),
169
0
                                 delete_sink.broker_addresses.end());
170
0
    }
171
172
    // Get partition information
173
842
    if (delete_sink.__isset.partition_spec_id) {
174
247
        _partition_spec_id = delete_sink.partition_spec_id;
175
247
    }
176
177
842
    if (delete_sink.__isset.partition_data_json) {
178
1
        _partition_data_json = delete_sink.partition_data_json;
179
1
    }
180
181
842
    if (delete_sink.__isset.format_version) {
182
833
        _format_version = delete_sink.format_version;
183
833
    }
184
185
    // for merge old deletion vector and old position delete to a new deletion vector.
186
842
    if (_format_version >= 3 && delete_sink.__isset.rewritable_delete_file_sets) {
187
256
        for (const auto& delete_file_set : delete_sink.rewritable_delete_file_sets) {
188
256
            if (!delete_file_set.__isset.referenced_data_file_path ||
189
256
                !delete_file_set.__isset.delete_files ||
190
256
                delete_file_set.referenced_data_file_path.empty() ||
191
256
                delete_file_set.delete_files.empty()) {
192
224
                continue;
193
224
            }
194
32
            _rewritable_delete_files.emplace(delete_file_set.referenced_data_file_path,
195
32
                                             delete_file_set.delete_files);
196
32
        }
197
192
    }
198
199
842
    return Status::OK();
200
843
}
201
202
835
Status VIcebergDeleteSink::open(RuntimeState* state, RuntimeProfile* profile) {
203
835
    _state = state;
204
205
    // Initialize counters
206
835
    _written_rows_counter = ADD_COUNTER(profile, "RowsWritten", TUnit::UNIT);
207
835
    _send_data_timer = ADD_TIMER(profile, "SendDataTime");
208
835
    _write_delete_files_timer = ADD_TIMER(profile, "WriteDeleteFilesTime");
209
835
    _delete_file_count_counter = ADD_COUNTER(profile, "DeleteFileCount", TUnit::UNIT);
210
835
    _open_timer = ADD_TIMER(profile, "OpenTime");
211
835
    _close_timer = ADD_TIMER(profile, "CloseTime");
212
213
835
    SCOPED_TIMER(_open_timer);
214
215
835
    if (_format_version < 3) {
216
643
        RETURN_IF_ERROR(_init_position_delete_output_exprs());
217
643
    }
218
219
835
    LOG(INFO) << fmt::format(
220
835
            "VIcebergDeleteSink opened: delete_type={}, output_path={}, format_version={}",
221
835
            to_string(_delete_type), _output_path, _format_version);
222
223
835
    return Status::OK();
224
835
}
225
226
108
Status VIcebergDeleteSink::write(RuntimeState* state, Block& block) {
227
108
    SCOPED_TIMER(_send_data_timer);
228
229
108
    if (block.rows() == 0) {
230
0
        return Status::OK();
231
0
    }
232
233
108
    _row_count += block.rows();
234
235
108
    if (_delete_type != TFileContent::POSITION_DELETES) {
236
0
        return Status::NotSupported("Iceberg delete only supports position delete files");
237
0
    }
238
239
    // Extract $row_id column and group by file_path
240
108
    RETURN_IF_ERROR(_collect_position_deletes(block, _file_deletions));
241
242
108
    if (_written_rows_counter) {
243
108
        COUNTER_UPDATE(_written_rows_counter, block.rows());
244
108
    }
245
246
108
    return Status::OK();
247
108
}
248
249
834
Status VIcebergDeleteSink::close(Status close_status) {
250
834
    SCOPED_TIMER(_close_timer);
251
252
834
    if (!close_status.ok()) {
253
0
        LOG(WARNING) << fmt::format("VIcebergDeleteSink close with error: {}",
254
0
                                    close_status.to_string());
255
0
        return close_status;
256
0
    }
257
258
834
    if (_delete_type == TFileContent::POSITION_DELETES && !_file_deletions.empty()) {
259
108
        SCOPED_TIMER(_write_delete_files_timer);
260
108
        if (_format_version >= 3) {
261
28
            RETURN_IF_ERROR(_write_deletion_vector_files(_file_deletions));
262
80
        } else {
263
80
            RETURN_IF_ERROR(_write_position_delete_files(_file_deletions));
264
80
        }
265
108
    }
266
267
    // Update counters
268
834
    if (_delete_file_count_counter) {
269
834
        COUNTER_UPDATE(_delete_file_count_counter, _delete_file_count);
270
834
    }
271
272
834
    LOG(INFO) << fmt::format("VIcebergDeleteSink closed: rows={}, delete_files={}", _row_count,
273
834
                             _delete_file_count);
274
275
834
    if (_state != nullptr) {
276
834
        for (const auto& commit_data : _commit_data_list) {
277
108
            _state->add_iceberg_commit_datas(commit_data);
278
108
        }
279
834
    }
280
281
834
    return Status::OK();
282
834
}
283
284
115
int VIcebergDeleteSink::_get_row_id_column_index(const Block& block) {
285
    // Find __DORIS_ICEBERG_ROWID_COL__ column in block
286
140
    for (size_t i = 0; i < block.columns(); ++i) {
287
140
        const auto& col_name = block.get_by_position(i).name;
288
140
        if (col_name == doris::BeConsts::ICEBERG_ROWID_COL) {
289
115
            return static_cast<int>(i);
290
115
        }
291
140
    }
292
0
    return -1;
293
115
}
294
295
Status VIcebergDeleteSink::_collect_position_deletes(
296
113
        const Block& block, std::map<std::string, IcebergFileDeletion>& file_deletions) {
297
    // Find row id column
298
113
    int row_id_col_idx = _get_row_id_column_index(block);
299
113
    if (row_id_col_idx < 0) {
300
0
        return Status::InternalError(
301
0
                "__DORIS_ICEBERG_ROWID_COL__ column not found in block for position delete");
302
0
    }
303
304
113
    const auto& row_id_col = block.get_by_position(row_id_col_idx);
305
113
    const IColumn* row_id_data = row_id_col.column.get();
306
113
    const IDataType* row_id_type = row_id_col.type.get();
307
113
    const auto* nullable_col = check_and_get_column<ColumnNullable>(row_id_data);
308
113
    if (nullable_col != nullptr) {
309
48
        row_id_data = nullable_col->get_nested_column_ptr().get();
310
48
    }
311
113
    const auto* nullable_type = check_and_get_data_type<DataTypeNullable>(row_id_type);
312
113
    if (nullable_type != nullptr) {
313
48
        row_id_type = nullable_type->get_nested_type().get();
314
48
    }
315
113
    const auto* struct_col = check_and_get_column<ColumnStruct>(row_id_data);
316
113
    const auto* struct_type = check_and_get_data_type<DataTypeStruct>(row_id_type);
317
113
    if (!struct_col || !struct_type) {
318
0
        return Status::InternalError("__DORIS_ICEBERG_ROWID_COL__ column is not a struct column");
319
0
    }
320
321
    // __DORIS_ICEBERG_ROWID_COL__ struct:
322
    // (file_path: STRING, row_position: BIGINT, partition_spec_id: INT, partition_data: STRING)
323
113
    size_t field_count = struct_col->tuple_size();
324
113
    if (field_count < 2) {
325
0
        return Status::InternalError(
326
0
                "__DORIS_ICEBERG_ROWID_COL__ struct must have at least 2 fields "
327
0
                "(file_path, row_position)");
328
0
    }
329
330
448
    auto normalize = [](const std::string& name) { return doris::to_lower(name); };
331
332
113
    int file_path_idx = -1;
333
113
    int row_position_idx = -1;
334
113
    int spec_id_idx = -1;
335
113
    int partition_data_idx = -1;
336
113
    const auto& field_names = struct_type->get_element_names();
337
561
    for (size_t i = 0; i < field_names.size(); ++i) {
338
448
        std::string name = normalize(field_names[i]);
339
448
        if (file_path_idx < 0 && name == "file_path") {
340
113
            file_path_idx = static_cast<int>(i);
341
335
        } else if (row_position_idx < 0 && name == "row_position") {
342
112
            row_position_idx = static_cast<int>(i);
343
223
        } else if (spec_id_idx < 0 && name == "partition_spec_id") {
344
110
            spec_id_idx = static_cast<int>(i);
345
113
        } else if (partition_data_idx < 0 && name == "partition_data") {
346
110
            partition_data_idx = static_cast<int>(i);
347
110
        }
348
448
    }
349
350
113
    if (file_path_idx < 0 || row_position_idx < 0) {
351
1
        return Status::InternalError(
352
1
                "__DORIS_ICEBERG_ROWID_COL__ must contain standard fields file_path and "
353
1
                "row_position");
354
1
    }
355
112
    if (field_count >= 3 && spec_id_idx < 0) {
356
0
        return Status::InternalError(
357
0
                "__DORIS_ICEBERG_ROWID_COL__ must use standard field name partition_spec_id");
358
0
    }
359
112
    if (field_count >= 4 && partition_data_idx < 0) {
360
0
        return Status::InternalError(
361
0
                "__DORIS_ICEBERG_ROWID_COL__ must use standard field name partition_data");
362
0
    }
363
364
112
    const auto* file_path_col = check_and_get_column<ColumnString>(
365
112
            remove_nullable(struct_col->get_column_ptr(file_path_idx)).get());
366
112
    const auto* row_position_col = check_and_get_column<ColumnVector<TYPE_BIGINT>>(
367
112
            remove_nullable(struct_col->get_column_ptr(row_position_idx)).get());
368
369
112
    if (!file_path_col || !row_position_col) {
370
0
        return Status::InternalError(
371
0
                "__DORIS_ICEBERG_ROWID_COL__ struct fields have incorrect types");
372
0
    }
373
374
112
    const ColumnVector<TYPE_INT>* spec_id_col = nullptr;
375
112
    const ColumnString* partition_data_col = nullptr;
376
112
    if (spec_id_idx >= 0 && spec_id_idx < static_cast<int>(field_count)) {
377
110
        spec_id_col = check_and_get_column<ColumnVector<TYPE_INT>>(
378
110
                remove_nullable(struct_col->get_column_ptr(spec_id_idx)).get());
379
110
        if (!spec_id_col) {
380
0
            return Status::InternalError(
381
0
                    "__DORIS_ICEBERG_ROWID_COL__ partition_spec_id has incorrect type");
382
0
        }
383
110
    }
384
112
    if (partition_data_idx >= 0 && partition_data_idx < static_cast<int>(field_count)) {
385
110
        partition_data_col = check_and_get_column<ColumnString>(
386
110
                remove_nullable(struct_col->get_column_ptr(partition_data_idx)).get());
387
110
        if (!partition_data_col) {
388
0
            return Status::InternalError(
389
0
                    "__DORIS_ICEBERG_ROWID_COL__ partition_data has incorrect type");
390
0
        }
391
110
    }
392
393
    // Group by file_path using roaring bitmap
394
233
    for (size_t i = 0; i < block.rows(); ++i) {
395
122
        std::string file_path = file_path_col->get_data_at(i).to_string();
396
122
        int64_t row_position = row_position_col->get_element(i);
397
122
        if (row_position < 0) {
398
1
            return Status::InternalError("Invalid row_position {} in row_id column", row_position);
399
1
        }
400
401
121
        int32_t partition_spec_id = _partition_spec_id;
402
121
        std::string partition_data_json = _partition_data_json;
403
121
        if (spec_id_col != nullptr) {
404
120
            partition_spec_id = spec_id_col->get_element(i);
405
120
        }
406
121
        if (partition_data_col != nullptr) {
407
120
            partition_data_json = partition_data_col->get_data_at(i).to_string();
408
120
        }
409
410
121
        auto [iter, inserted] = file_deletions.emplace(
411
121
                file_path, IcebergFileDeletion(partition_spec_id, partition_data_json));
412
121
        if (!inserted) {
413
9
            if (iter->second.partition_spec_id != partition_spec_id ||
414
9
                iter->second.partition_data_json != partition_data_json) {
415
0
                LOG(WARNING) << fmt::format(
416
0
                        "Mismatched partition info for file {}, existing spec_id={}, data={}, "
417
0
                        "new spec_id={}, data={}",
418
0
                        file_path, iter->second.partition_spec_id, iter->second.partition_data_json,
419
0
                        partition_spec_id, partition_data_json);
420
0
            }
421
9
        }
422
121
        iter->second.rows_to_delete.add(static_cast<uint64_t>(row_position));
423
121
    }
424
425
111
    return Status::OK();
426
112
}
427
428
Status VIcebergDeleteSink::_write_position_delete_files(
429
80
        const std::map<std::string, IcebergFileDeletion>& file_deletions) {
430
80
    constexpr size_t kBatchSize = 4096;
431
80
    for (const auto& [data_file_path, deletion] : file_deletions) {
432
80
        if (deletion.rows_to_delete.isEmpty()) {
433
0
            continue;
434
0
        }
435
        // Generate unique delete file path
436
80
        std::string delete_file_path = _generate_delete_file_path(data_file_path);
437
438
        // Create delete file writer
439
80
        auto writer = VIcebergDeleteFileWriterFactory::create_writer(
440
80
                TFileContent::POSITION_DELETES, delete_file_path, _file_format_type,
441
80
                _compress_type);
442
443
        // Build column names for position delete
444
80
        std::vector<std::string> column_names = {"file_path", "pos"};
445
446
80
        if (_position_delete_output_expr_ctxs.empty()) {
447
0
            RETURN_IF_ERROR(_init_position_delete_output_exprs());
448
0
        }
449
450
        // Open writer
451
80
        RETURN_IF_ERROR(writer->open(_state, _state->runtime_profile(),
452
80
                                     _position_delete_output_expr_ctxs, column_names, _hadoop_conf,
453
80
                                     _file_type, _broker_addresses));
454
455
        // Build block with (file_path, pos) columns
456
80
        std::vector<int64_t> positions;
457
80
        positions.reserve(kBatchSize);
458
168
        for (auto it = deletion.rows_to_delete.begin(); it != deletion.rows_to_delete.end(); ++it) {
459
88
            positions.push_back(static_cast<int64_t>(*it));
460
88
            if (positions.size() >= kBatchSize) {
461
0
                Block delete_block;
462
0
                RETURN_IF_ERROR(
463
0
                        _build_position_delete_block(data_file_path, positions, delete_block));
464
0
                RETURN_IF_ERROR(writer->write(delete_block));
465
0
                positions.clear();
466
0
            }
467
88
        }
468
80
        if (!positions.empty()) {
469
80
            Block delete_block;
470
80
            RETURN_IF_ERROR(_build_position_delete_block(data_file_path, positions, delete_block));
471
80
            RETURN_IF_ERROR(writer->write(delete_block));
472
80
        }
473
474
        // Set partition info on writer before close
475
80
        writer->set_partition_info(deletion.partition_spec_id, deletion.partition_data_json);
476
477
        // Close writer and collect commit data
478
80
        TIcebergCommitData commit_data;
479
80
        RETURN_IF_ERROR(writer->close(commit_data));
480
481
        // Set referenced data file path
482
80
        commit_data.__set_referenced_data_file_path(data_file_path);
483
484
80
        _commit_data_list.push_back(commit_data);
485
80
        _delete_file_count++;
486
487
80
        VLOG(1) << fmt::format("Written position delete file: path={}, rows={}, referenced_file={}",
488
0
                               delete_file_path, commit_data.row_count, data_file_path);
489
80
    }
490
491
80
    return Status::OK();
492
80
}
493
494
643
Status VIcebergDeleteSink::_init_position_delete_output_exprs() {
495
643
    if (!_position_delete_output_expr_ctxs.empty()) {
496
0
        return Status::OK();
497
0
    }
498
499
643
    std::vector<TExpr> texprs;
500
643
    texprs.reserve(2);
501
502
643
    std::string empty_string;
503
643
    TExprNode file_path_node =
504
643
            create_texpr_node_from(&empty_string, PrimitiveType::TYPE_STRING, 0, 0);
505
643
    file_path_node.__set_num_children(0);
506
643
    file_path_node.__set_output_scale(0);
507
643
    file_path_node.__set_is_nullable(false);
508
643
    TExpr file_path_expr;
509
643
    file_path_expr.nodes.emplace_back(std::move(file_path_node));
510
643
    texprs.emplace_back(std::move(file_path_expr));
511
512
643
    int64_t zero = 0;
513
643
    TExprNode pos_node = create_texpr_node_from(&zero, PrimitiveType::TYPE_BIGINT, 0, 0);
514
643
    pos_node.__set_num_children(0);
515
643
    pos_node.__set_output_scale(0);
516
643
    pos_node.__set_is_nullable(false);
517
643
    TExpr pos_expr;
518
643
    pos_expr.nodes.emplace_back(std::move(pos_node));
519
643
    texprs.emplace_back(std::move(pos_expr));
520
521
643
    RETURN_IF_ERROR(VExpr::create_expr_trees(texprs, _position_delete_output_expr_ctxs));
522
643
    return Status::OK();
523
643
}
524
525
Status VIcebergDeleteSink::_build_position_delete_block(const std::string& file_path,
526
                                                        const std::vector<int64_t>& positions,
527
81
                                                        Block& output_block) {
528
    // Create file_path column (repeated for each position)
529
81
    auto file_path_col = ColumnString::create();
530
173
    for (size_t i = 0; i < positions.size(); ++i) {
531
92
        file_path_col->insert_data(file_path.data(), file_path.size());
532
92
    }
533
534
    // Create pos column
535
81
    auto pos_col = ColumnVector<TYPE_BIGINT>::create();
536
81
    pos_col->get_data().assign(positions.begin(), positions.end());
537
538
    // Build block
539
81
    output_block.insert(ColumnWithTypeAndName(std::move(file_path_col),
540
81
                                              std::make_shared<DataTypeString>(), "file_path"));
541
81
    output_block.insert(
542
81
            ColumnWithTypeAndName(std::move(pos_col), std::make_shared<DataTypeInt64>(), "pos"));
543
544
81
    return Status::OK();
545
81
}
546
547
81
std::string VIcebergDeleteSink::_get_file_extension() const {
548
81
    std::string compress_name;
549
81
    switch (_compress_type) {
550
1
    case TFileCompressType::SNAPPYBLOCK: {
551
1
        compress_name = ".snappy";
552
1
        break;
553
0
    }
554
38
    case TFileCompressType::ZLIB: {
555
38
        compress_name = ".zlib";
556
38
        break;
557
0
    }
558
40
    case TFileCompressType::ZSTD: {
559
40
        compress_name = ".zstd";
560
40
        break;
561
0
    }
562
2
    default: {
563
2
        compress_name = "";
564
2
        break;
565
0
    }
566
81
    }
567
568
81
    std::string file_format_name;
569
81
    switch (_file_format_type) {
570
43
    case TFileFormatType::FORMAT_PARQUET: {
571
43
        file_format_name = ".parquet";
572
43
        break;
573
0
    }
574
38
    case TFileFormatType::FORMAT_ORC: {
575
38
        file_format_name = ".orc";
576
38
        break;
577
0
    }
578
0
    default: {
579
0
        file_format_name = "";
580
0
        break;
581
0
    }
582
81
    }
583
81
    return fmt::format("{}{}", compress_name, file_format_name);
584
81
}
585
586
Status VIcebergDeleteSink::_write_deletion_vector_files(
587
29
        const std::map<std::string, IcebergFileDeletion>& file_deletions) {
588
29
    std::vector<DeletionVectorBlob> blobs;
589
30
    for (const auto& [data_file_path, deletion] : file_deletions) {
590
30
        if (deletion.rows_to_delete.isEmpty()) {
591
0
            continue;
592
0
        }
593
30
        roaring::Roaring64Map merged_rows = deletion.rows_to_delete;
594
30
        DeletionVectorBlob blob;
595
30
        blob.delete_count = static_cast<int64_t>(merged_rows.cardinality());
596
30
        auto previous_delete_it = _rewritable_delete_files.find(data_file_path);
597
30
        if (previous_delete_it != _rewritable_delete_files.end()) {
598
0
            roaring::Roaring64Map previous_rows;
599
0
            RETURN_IF_ERROR(load_rewritable_delete_rows(
600
0
                    _state, _state->runtime_profile(), data_file_path, previous_delete_it->second,
601
0
                    _hadoop_conf, _file_type, _broker_addresses, &previous_rows));
602
0
            merged_rows |= previous_rows;
603
0
        }
604
605
30
        size_t bitmap_size = merged_rows.getSizeInBytes();
606
30
        blob.referenced_data_file = data_file_path;
607
30
        blob.partition_spec_id = deletion.partition_spec_id;
608
30
        blob.partition_data_json = deletion.partition_data_json;
609
30
        blob.merged_count = static_cast<int64_t>(merged_rows.cardinality());
610
30
        RETURN_IF_ERROR(calculate_iceberg_deletion_vector_content_size(
611
30
                bitmap_size, &blob.content_size_in_bytes));
612
30
        blob.blob_data.resize(static_cast<size_t>(blob.content_size_in_bytes));
613
30
        merged_rows.write(blob.blob_data.data() + 8);
614
615
30
        uint32_t total_length = static_cast<uint32_t>(4 + bitmap_size);
616
30
        BigEndian::Store32(blob.blob_data.data(), total_length);
617
618
30
        constexpr char DV_MAGIC[] = {'\xD1', '\xD3', '\x39', '\x64'};
619
30
        memcpy(blob.blob_data.data() + 4, DV_MAGIC, 4);
620
621
30
        uint32_t crc = static_cast<uint32_t>(
622
30
                ::crc32(0, reinterpret_cast<const Bytef*>(blob.blob_data.data() + 4),
623
30
                        static_cast<uInt>(4 + bitmap_size)));
624
30
        BigEndian::Store32(blob.blob_data.data() + 8 + bitmap_size, crc);
625
30
        blobs.emplace_back(std::move(blob));
626
30
    }
627
628
29
    if (blobs.empty()) {
629
0
        return Status::OK();
630
0
    }
631
632
29
    std::string puffin_path = _generate_puffin_file_path();
633
29
    int64_t puffin_file_size = 0;
634
29
    RETURN_IF_ERROR(_write_puffin_file(puffin_path, &blobs, &puffin_file_size));
635
636
30
    for (const auto& blob : blobs) {
637
30
        TIcebergCommitData commit_data;
638
30
        commit_data.__set_file_path(puffin_path);
639
30
        commit_data.__set_row_count(blob.merged_count);
640
30
        commit_data.__set_affected_rows(blob.delete_count);
641
30
        commit_data.__set_file_size(puffin_file_size);
642
30
        commit_data.__set_file_content(TFileContent::DELETION_VECTOR);
643
30
        commit_data.__set_content_offset(blob.content_offset);
644
30
        commit_data.__set_content_size_in_bytes(blob.content_size_in_bytes);
645
30
        commit_data.__set_referenced_data_file_path(blob.referenced_data_file);
646
30
        if (blob.partition_spec_id != 0 || !blob.partition_data_json.empty()) {
647
22
            commit_data.__set_partition_spec_id(blob.partition_spec_id);
648
22
            commit_data.__set_partition_data_json(blob.partition_data_json);
649
22
        }
650
651
30
        _commit_data_list.push_back(commit_data);
652
30
        _delete_file_count++;
653
30
    }
654
29
    return Status::OK();
655
29
}
656
657
Status VIcebergDeleteSink::_write_puffin_file(const std::string& puffin_path,
658
                                              std::vector<DeletionVectorBlob>* blobs,
659
29
                                              int64_t* out_file_size) {
660
29
    DCHECK(blobs != nullptr);
661
29
    DCHECK(!blobs->empty());
662
663
29
    io::FSPropertiesRef fs_properties(_file_type);
664
29
    fs_properties.properties = &_hadoop_conf;
665
29
    if (!_broker_addresses.empty()) {
666
0
        fs_properties.broker_addresses = &_broker_addresses;
667
0
    }
668
29
    io::FileDescription file_description = {.path = puffin_path, .fs_name {}};
669
29
    auto fs = DORIS_TRY(FileFactory::create_fs(fs_properties, file_description));
670
29
    io::FileWriterOptions file_writer_options = {.used_by_s3_committer = false};
671
29
    io::FileWriterPtr file_writer;
672
29
    RETURN_IF_ERROR(fs->create_file(file_description.path, &file_writer, &file_writer_options));
673
674
29
    constexpr char PUFFIN_MAGIC[] = {'\x50', '\x46', '\x41', '\x31'};
675
29
    RETURN_IF_ERROR(file_writer->append(Slice(reinterpret_cast<const uint8_t*>(PUFFIN_MAGIC), 4)));
676
29
    int64_t current_offset = 4;
677
30
    for (auto& blob : *blobs) {
678
30
        blob.content_offset = current_offset;
679
30
        RETURN_IF_ERROR(file_writer->append(Slice(
680
30
                reinterpret_cast<const uint8_t*>(blob.blob_data.data()), blob.blob_data.size())));
681
30
        current_offset += static_cast<int64_t>(blob.blob_data.size());
682
30
    }
683
29
    RETURN_IF_ERROR(file_writer->append(Slice(reinterpret_cast<const uint8_t*>(PUFFIN_MAGIC), 4)));
684
685
29
    std::string footer_json = _build_puffin_footer_json(*blobs);
686
29
    RETURN_IF_ERROR(file_writer->append(
687
29
            Slice(reinterpret_cast<const uint8_t*>(footer_json.data()), footer_json.size())));
688
689
29
    char footer_size_buf[4];
690
29
    LittleEndian::Store32(footer_size_buf, static_cast<uint32_t>(footer_json.size()));
691
29
    RETURN_IF_ERROR(file_writer->append(
692
29
            Slice(reinterpret_cast<const uint8_t*>(footer_size_buf), sizeof(footer_size_buf))));
693
694
29
    char flags[4] = {0, 0, 0, 0};
695
29
    RETURN_IF_ERROR(
696
29
            file_writer->append(Slice(reinterpret_cast<const uint8_t*>(flags), sizeof(flags))));
697
29
    RETURN_IF_ERROR(file_writer->append(Slice(reinterpret_cast<const uint8_t*>(PUFFIN_MAGIC), 4)));
698
29
    RETURN_IF_ERROR(file_writer->close());
699
700
29
    *out_file_size = current_offset + 4 + static_cast<int64_t>(footer_json.size()) + 4 + 4 + 4;
701
29
    return Status::OK();
702
29
}
703
704
std::string VIcebergDeleteSink::_build_puffin_footer_json(
705
29
        const std::vector<DeletionVectorBlob>& blobs) {
706
29
    rapidjson::StringBuffer buffer;
707
29
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
708
29
    writer.StartObject();
709
29
    writer.Key("blobs");
710
29
    writer.StartArray();
711
30
    for (const auto& blob : blobs) {
712
30
        writer.StartObject();
713
30
        writer.Key("type");
714
30
        writer.String("deletion-vector-v1");
715
30
        writer.Key("fields");
716
30
        writer.StartArray();
717
30
        writer.EndArray();
718
30
        writer.Key("snapshot-id");
719
30
        writer.Int64(-1);
720
30
        writer.Key("sequence-number");
721
30
        writer.Int64(-1);
722
30
        writer.Key("offset");
723
30
        writer.Int64(blob.content_offset);
724
30
        writer.Key("length");
725
30
        writer.Int64(blob.content_size_in_bytes);
726
30
        writer.Key("properties");
727
30
        writer.StartObject();
728
30
        writer.Key("referenced-data-file");
729
30
        writer.String(blob.referenced_data_file.c_str(),
730
30
                      static_cast<rapidjson::SizeType>(blob.referenced_data_file.size()));
731
30
        std::string cardinality = std::to_string(blob.merged_count);
732
30
        writer.Key("cardinality");
733
30
        writer.String(cardinality.c_str(), static_cast<rapidjson::SizeType>(cardinality.size()));
734
30
        writer.EndObject();
735
30
        writer.EndObject();
736
30
    }
737
29
    writer.EndArray();
738
29
    writer.Key("properties");
739
29
    writer.StartObject();
740
29
    writer.Key("created-by");
741
29
    writer.String("doris-puffin-v1");
742
29
    writer.EndObject();
743
29
    writer.EndObject();
744
29
    return {buffer.GetString(), buffer.GetSize()};
745
29
}
746
747
std::string VIcebergDeleteSink::_generate_delete_file_path(
748
81
        const std::string& referenced_data_file) {
749
    // Generate unique delete file name using UUID
750
81
    std::string uuid = generate_uuid_string();
751
81
    std::string file_name;
752
753
81
    std::string file_extension = _get_file_extension();
754
81
    file_name =
755
81
            fmt::format("delete_pos_{}_{}{}", uuid,
756
81
                        std::hash<std::string> {}(referenced_data_file) % 10000000, file_extension);
757
758
    // Combine with output path or table location
759
81
    std::string base_path = _output_path.empty() ? _table_location : _output_path;
760
761
    // Ensure base path ends with /
762
81
    if (!base_path.empty() && base_path.back() != '/') {
763
81
        base_path += '/';
764
81
    }
765
766
    // Delete files are data files in Iceberg, write under data location
767
81
    return fmt::format("{}{}", base_path, file_name);
768
81
}
769
770
29
std::string VIcebergDeleteSink::_generate_puffin_file_path() {
771
29
    std::string uuid = generate_uuid_string();
772
29
    std::string file_name = fmt::format("delete_dv_{}.puffin", uuid);
773
29
    std::string base_path = _output_path.empty() ? _table_location : _output_path;
774
29
    if (!base_path.empty() && base_path.back() != '/') {
775
29
        base_path += '/';
776
29
    }
777
29
    return fmt::format("{}{}", base_path, file_name);
778
29
}
779
780
} // namespace doris