Coverage Report

Created: 2026-07-20 18:23

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
4
Status calculate_iceberg_deletion_vector_content_size(size_t bitmap_size, int64_t* content_size) {
111
4
    DORIS_CHECK(content_size != nullptr);
112
4
    constexpr size_t max_bitmap_size = static_cast<size_t>(MAX_ICEBERG_DELETION_VECTOR_BYTES) -
113
4
                                       ICEBERG_DELETION_VECTOR_BLOB_OVERHEAD_BYTES;
114
4
    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
3
    *content_size = static_cast<int64_t>(bitmap_size + ICEBERG_DELETION_VECTOR_BLOB_OVERHEAD_BYTES);
121
3
    return Status::OK();
122
4
}
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
18
        : AsyncResultWriter(output_exprs, dep, fin_dep), _t_sink(t_sink) {
129
18
    DCHECK(_t_sink.__isset.iceberg_delete_sink);
130
18
}
131
132
11
Status VIcebergDeleteSink::init_properties(ObjectPool* pool) {
133
11
    const auto& delete_sink = _t_sink.iceberg_delete_sink;
134
135
11
    _delete_type = delete_sink.delete_type;
136
11
    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
10
    if (delete_sink.__isset.file_format) {
142
10
        _file_format_type = delete_sink.file_format;
143
10
    }
144
145
10
    if (delete_sink.__isset.compress_type) {
146
10
        _compress_type = delete_sink.compress_type;
147
10
    }
148
149
    // Get output path and table location
150
10
    if (delete_sink.__isset.output_path) {
151
10
        _output_path = delete_sink.output_path;
152
10
    }
153
154
10
    if (delete_sink.__isset.table_location) {
155
10
        _table_location = delete_sink.table_location;
156
10
    }
157
158
    // Get Hadoop configuration
159
10
    if (delete_sink.__isset.hadoop_config) {
160
2
        _hadoop_conf.insert(delete_sink.hadoop_config.begin(), delete_sink.hadoop_config.end());
161
2
    }
162
163
10
    if (delete_sink.__isset.file_type) {
164
7
        _file_type = delete_sink.file_type;
165
7
    }
166
167
10
    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
10
    if (delete_sink.__isset.partition_spec_id) {
174
7
        _partition_spec_id = delete_sink.partition_spec_id;
175
7
    }
176
177
10
    if (delete_sink.__isset.partition_data_json) {
178
1
        _partition_data_json = delete_sink.partition_data_json;
179
1
    }
180
181
10
    if (delete_sink.__isset.format_version) {
182
1
        _format_version = delete_sink.format_version;
183
1
    }
184
185
    // for merge old deletion vector and old position delete to a new deletion vector.
186
10
    if (_format_version >= 3 && delete_sink.__isset.rewritable_delete_file_sets) {
187
0
        for (const auto& delete_file_set : delete_sink.rewritable_delete_file_sets) {
188
0
            if (!delete_file_set.__isset.referenced_data_file_path ||
189
0
                !delete_file_set.__isset.delete_files ||
190
0
                delete_file_set.referenced_data_file_path.empty() ||
191
0
                delete_file_set.delete_files.empty()) {
192
0
                continue;
193
0
            }
194
0
            _rewritable_delete_files.emplace(delete_file_set.referenced_data_file_path,
195
0
                                             delete_file_set.delete_files);
196
0
        }
197
0
    }
198
199
10
    return Status::OK();
200
11
}
201
202
3
Status VIcebergDeleteSink::open(RuntimeState* state, RuntimeProfile* profile) {
203
3
    _state = state;
204
205
    // Initialize counters
206
3
    _written_rows_counter = ADD_COUNTER(profile, "RowsWritten", TUnit::UNIT);
207
3
    _send_data_timer = ADD_TIMER(profile, "SendDataTime");
208
3
    _write_delete_files_timer = ADD_TIMER(profile, "WriteDeleteFilesTime");
209
3
    _delete_file_count_counter = ADD_COUNTER(profile, "DeleteFileCount", TUnit::UNIT);
210
3
    _open_timer = ADD_TIMER(profile, "OpenTime");
211
3
    _close_timer = ADD_TIMER(profile, "CloseTime");
212
213
3
    SCOPED_TIMER(_open_timer);
214
215
3
    if (_format_version < 3) {
216
3
        RETURN_IF_ERROR(_init_position_delete_output_exprs());
217
3
    }
218
219
3
    LOG(INFO) << fmt::format(
220
3
            "VIcebergDeleteSink opened: delete_type={}, output_path={}, format_version={}",
221
3
            to_string(_delete_type), _output_path, _format_version);
222
223
3
    return Status::OK();
224
3
}
225
226
0
Status VIcebergDeleteSink::write(RuntimeState* state, Block& block) {
227
0
    SCOPED_TIMER(_send_data_timer);
228
229
0
    if (block.rows() == 0) {
230
0
        return Status::OK();
231
0
    }
232
233
0
    _row_count += block.rows();
234
235
0
    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
0
    RETURN_IF_ERROR(_collect_position_deletes(block, _file_deletions));
241
242
0
    if (_written_rows_counter) {
243
0
        COUNTER_UPDATE(_written_rows_counter, block.rows());
244
0
    }
245
246
0
    return Status::OK();
247
0
}
248
249
2
Status VIcebergDeleteSink::close(Status close_status) {
250
2
    SCOPED_TIMER(_close_timer);
251
252
2
    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
2
    if (_delete_type == TFileContent::POSITION_DELETES && !_file_deletions.empty()) {
259
0
        SCOPED_TIMER(_write_delete_files_timer);
260
0
        if (_format_version >= 3) {
261
0
            RETURN_IF_ERROR(_write_deletion_vector_files(_file_deletions));
262
0
        } else {
263
0
            RETURN_IF_ERROR(_write_position_delete_files(_file_deletions));
264
0
        }
265
0
    }
266
267
    // Update counters
268
2
    if (_delete_file_count_counter) {
269
2
        COUNTER_UPDATE(_delete_file_count_counter, _delete_file_count);
270
2
    }
271
272
2
    LOG(INFO) << fmt::format("VIcebergDeleteSink closed: rows={}, delete_files={}", _row_count,
273
2
                             _delete_file_count);
274
275
2
    if (_state != nullptr) {
276
2
        for (const auto& commit_data : _commit_data_list) {
277
0
            _state->add_iceberg_commit_datas(commit_data);
278
0
        }
279
2
    }
280
281
2
    return Status::OK();
282
2
}
283
284
7
int VIcebergDeleteSink::_get_row_id_column_index(const Block& block) {
285
    // Find __DORIS_ICEBERG_ROWID_COL__ column in block
286
8
    for (size_t i = 0; i < block.columns(); ++i) {
287
8
        const auto& col_name = block.get_by_position(i).name;
288
8
        if (col_name == doris::BeConsts::ICEBERG_ROWID_COL) {
289
7
            return static_cast<int>(i);
290
7
        }
291
8
    }
292
0
    return -1;
293
7
}
294
295
Status VIcebergDeleteSink::_collect_position_deletes(
296
5
        const Block& block, std::map<std::string, IcebergFileDeletion>& file_deletions) {
297
    // Find row id column
298
5
    int row_id_col_idx = _get_row_id_column_index(block);
299
5
    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
5
    const auto& row_id_col = block.get_by_position(row_id_col_idx);
305
5
    const IColumn* row_id_data = row_id_col.column.get();
306
5
    const IDataType* row_id_type = row_id_col.type.get();
307
5
    const auto* nullable_col = check_and_get_column<ColumnNullable>(row_id_data);
308
5
    if (nullable_col != nullptr) {
309
0
        row_id_data = nullable_col->get_nested_column_ptr().get();
310
0
    }
311
5
    const auto* nullable_type = check_and_get_data_type<DataTypeNullable>(row_id_type);
312
5
    if (nullable_type != nullptr) {
313
0
        row_id_type = nullable_type->get_nested_type().get();
314
0
    }
315
5
    const auto* struct_col = check_and_get_column<ColumnStruct>(row_id_data);
316
5
    const auto* struct_type = check_and_get_data_type<DataTypeStruct>(row_id_type);
317
5
    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
5
    size_t field_count = struct_col->tuple_size();
324
5
    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
16
    auto normalize = [](const std::string& name) { return doris::to_lower(name); };
331
332
5
    int file_path_idx = -1;
333
5
    int row_position_idx = -1;
334
5
    int spec_id_idx = -1;
335
5
    int partition_data_idx = -1;
336
5
    const auto& field_names = struct_type->get_element_names();
337
21
    for (size_t i = 0; i < field_names.size(); ++i) {
338
16
        std::string name = normalize(field_names[i]);
339
16
        if (file_path_idx < 0 && name == "file_path") {
340
5
            file_path_idx = static_cast<int>(i);
341
11
        } else if (row_position_idx < 0 && name == "row_position") {
342
4
            row_position_idx = static_cast<int>(i);
343
7
        } else if (spec_id_idx < 0 && name == "partition_spec_id") {
344
2
            spec_id_idx = static_cast<int>(i);
345
5
        } else if (partition_data_idx < 0 && name == "partition_data") {
346
2
            partition_data_idx = static_cast<int>(i);
347
2
        }
348
16
    }
349
350
5
    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
4
    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
4
    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
4
    const auto* file_path_col = check_and_get_column<ColumnString>(
365
4
            remove_nullable(struct_col->get_column_ptr(file_path_idx)).get());
366
4
    const auto* row_position_col = check_and_get_column<ColumnVector<TYPE_BIGINT>>(
367
4
            remove_nullable(struct_col->get_column_ptr(row_position_idx)).get());
368
369
4
    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
4
    const ColumnVector<TYPE_INT>* spec_id_col = nullptr;
375
4
    const ColumnString* partition_data_col = nullptr;
376
4
    if (spec_id_idx >= 0 && spec_id_idx < static_cast<int>(field_count)) {
377
2
        spec_id_col = check_and_get_column<ColumnVector<TYPE_INT>>(
378
2
                remove_nullable(struct_col->get_column_ptr(spec_id_idx)).get());
379
2
        if (!spec_id_col) {
380
0
            return Status::InternalError(
381
0
                    "__DORIS_ICEBERG_ROWID_COL__ partition_spec_id has incorrect type");
382
0
        }
383
2
    }
384
4
    if (partition_data_idx >= 0 && partition_data_idx < static_cast<int>(field_count)) {
385
2
        partition_data_col = check_and_get_column<ColumnString>(
386
2
                remove_nullable(struct_col->get_column_ptr(partition_data_idx)).get());
387
2
        if (!partition_data_col) {
388
0
            return Status::InternalError(
389
0
                    "__DORIS_ICEBERG_ROWID_COL__ partition_data has incorrect type");
390
0
        }
391
2
    }
392
393
    // Group by file_path using roaring bitmap
394
9
    for (size_t i = 0; i < block.rows(); ++i) {
395
6
        std::string file_path = file_path_col->get_data_at(i).to_string();
396
6
        int64_t row_position = row_position_col->get_element(i);
397
6
        if (row_position < 0) {
398
1
            return Status::InternalError("Invalid row_position {} in row_id column", row_position);
399
1
        }
400
401
5
        int32_t partition_spec_id = _partition_spec_id;
402
5
        std::string partition_data_json = _partition_data_json;
403
5
        if (spec_id_col != nullptr) {
404
4
            partition_spec_id = spec_id_col->get_element(i);
405
4
        }
406
5
        if (partition_data_col != nullptr) {
407
4
            partition_data_json = partition_data_col->get_data_at(i).to_string();
408
4
        }
409
410
5
        auto [iter, inserted] = file_deletions.emplace(
411
5
                file_path, IcebergFileDeletion(partition_spec_id, partition_data_json));
412
5
        if (!inserted) {
413
1
            if (iter->second.partition_spec_id != partition_spec_id ||
414
1
                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
1
        }
422
5
        iter->second.rows_to_delete.add(static_cast<uint64_t>(row_position));
423
5
    }
424
425
3
    return Status::OK();
426
4
}
427
428
Status VIcebergDeleteSink::_write_position_delete_files(
429
0
        const std::map<std::string, IcebergFileDeletion>& file_deletions) {
430
0
    constexpr size_t kBatchSize = 4096;
431
0
    for (const auto& [data_file_path, deletion] : file_deletions) {
432
0
        if (deletion.rows_to_delete.isEmpty()) {
433
0
            continue;
434
0
        }
435
        // Generate unique delete file path
436
0
        std::string delete_file_path = _generate_delete_file_path(data_file_path);
437
438
        // Create delete file writer
439
0
        auto writer = VIcebergDeleteFileWriterFactory::create_writer(
440
0
                TFileContent::POSITION_DELETES, delete_file_path, _file_format_type,
441
0
                _compress_type);
442
443
        // Build column names for position delete
444
0
        std::vector<std::string> column_names = {"file_path", "pos"};
445
446
0
        if (_position_delete_output_expr_ctxs.empty()) {
447
0
            RETURN_IF_ERROR(_init_position_delete_output_exprs());
448
0
        }
449
450
        // Open writer
451
0
        RETURN_IF_ERROR(writer->open(_state, _state->runtime_profile(),
452
0
                                     _position_delete_output_expr_ctxs, column_names, _hadoop_conf,
453
0
                                     _file_type, _broker_addresses));
454
455
        // Build block with (file_path, pos) columns
456
0
        std::vector<int64_t> positions;
457
0
        positions.reserve(kBatchSize);
458
0
        for (auto it = deletion.rows_to_delete.begin(); it != deletion.rows_to_delete.end(); ++it) {
459
0
            positions.push_back(static_cast<int64_t>(*it));
460
0
            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
0
        }
468
0
        if (!positions.empty()) {
469
0
            Block delete_block;
470
0
            RETURN_IF_ERROR(_build_position_delete_block(data_file_path, positions, delete_block));
471
0
            RETURN_IF_ERROR(writer->write(delete_block));
472
0
        }
473
474
        // Set partition info on writer before close
475
0
        writer->set_partition_info(deletion.partition_spec_id, deletion.partition_data_json);
476
477
        // Close writer and collect commit data
478
0
        TIcebergCommitData commit_data;
479
0
        RETURN_IF_ERROR(writer->close(commit_data));
480
481
        // Set referenced data file path
482
0
        commit_data.__set_referenced_data_file_path(data_file_path);
483
484
0
        _commit_data_list.push_back(commit_data);
485
0
        _delete_file_count++;
486
487
0
        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
0
    }
490
491
0
    return Status::OK();
492
0
}
493
494
3
Status VIcebergDeleteSink::_init_position_delete_output_exprs() {
495
3
    if (!_position_delete_output_expr_ctxs.empty()) {
496
0
        return Status::OK();
497
0
    }
498
499
3
    std::vector<TExpr> texprs;
500
3
    texprs.reserve(2);
501
502
3
    std::string empty_string;
503
3
    TExprNode file_path_node =
504
3
            create_texpr_node_from(&empty_string, PrimitiveType::TYPE_STRING, 0, 0);
505
3
    file_path_node.__set_num_children(0);
506
3
    file_path_node.__set_output_scale(0);
507
3
    file_path_node.__set_is_nullable(false);
508
3
    TExpr file_path_expr;
509
3
    file_path_expr.nodes.emplace_back(std::move(file_path_node));
510
3
    texprs.emplace_back(std::move(file_path_expr));
511
512
3
    int64_t zero = 0;
513
3
    TExprNode pos_node = create_texpr_node_from(&zero, PrimitiveType::TYPE_BIGINT, 0, 0);
514
3
    pos_node.__set_num_children(0);
515
3
    pos_node.__set_output_scale(0);
516
3
    pos_node.__set_is_nullable(false);
517
3
    TExpr pos_expr;
518
3
    pos_expr.nodes.emplace_back(std::move(pos_node));
519
3
    texprs.emplace_back(std::move(pos_expr));
520
521
3
    RETURN_IF_ERROR(VExpr::create_expr_trees(texprs, _position_delete_output_expr_ctxs));
522
3
    return Status::OK();
523
3
}
524
525
Status VIcebergDeleteSink::_build_position_delete_block(const std::string& file_path,
526
                                                        const std::vector<int64_t>& positions,
527
1
                                                        Block& output_block) {
528
    // Create file_path column (repeated for each position)
529
1
    auto file_path_col = ColumnString::create();
530
5
    for (size_t i = 0; i < positions.size(); ++i) {
531
4
        file_path_col->insert_data(file_path.data(), file_path.size());
532
4
    }
533
534
    // Create pos column
535
1
    auto pos_col = ColumnVector<TYPE_BIGINT>::create();
536
1
    pos_col->get_data().assign(positions.begin(), positions.end());
537
538
    // Build block
539
1
    output_block.insert(ColumnWithTypeAndName(std::move(file_path_col),
540
1
                                              std::make_shared<DataTypeString>(), "file_path"));
541
1
    output_block.insert(
542
1
            ColumnWithTypeAndName(std::move(pos_col), std::make_shared<DataTypeInt64>(), "pos"));
543
544
1
    return Status::OK();
545
1
}
546
547
1
std::string VIcebergDeleteSink::_get_file_extension() const {
548
1
    std::string compress_name;
549
1
    switch (_compress_type) {
550
1
    case TFileCompressType::SNAPPYBLOCK: {
551
1
        compress_name = ".snappy";
552
1
        break;
553
0
    }
554
0
    case TFileCompressType::ZLIB: {
555
0
        compress_name = ".zlib";
556
0
        break;
557
0
    }
558
0
    case TFileCompressType::ZSTD: {
559
0
        compress_name = ".zstd";
560
0
        break;
561
0
    }
562
0
    default: {
563
0
        compress_name = "";
564
0
        break;
565
0
    }
566
1
    }
567
568
1
    std::string file_format_name;
569
1
    switch (_file_format_type) {
570
1
    case TFileFormatType::FORMAT_PARQUET: {
571
1
        file_format_name = ".parquet";
572
1
        break;
573
0
    }
574
0
    case TFileFormatType::FORMAT_ORC: {
575
0
        file_format_name = ".orc";
576
0
        break;
577
0
    }
578
0
    default: {
579
0
        file_format_name = "";
580
0
        break;
581
0
    }
582
1
    }
583
1
    return fmt::format("{}{}", compress_name, file_format_name);
584
1
}
585
586
Status VIcebergDeleteSink::_write_deletion_vector_files(
587
1
        const std::map<std::string, IcebergFileDeletion>& file_deletions) {
588
1
    std::vector<DeletionVectorBlob> blobs;
589
2
    for (const auto& [data_file_path, deletion] : file_deletions) {
590
2
        if (deletion.rows_to_delete.isEmpty()) {
591
0
            continue;
592
0
        }
593
2
        roaring::Roaring64Map merged_rows = deletion.rows_to_delete;
594
2
        DeletionVectorBlob blob;
595
2
        blob.delete_count = static_cast<int64_t>(merged_rows.cardinality());
596
2
        auto previous_delete_it = _rewritable_delete_files.find(data_file_path);
597
2
        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
2
        size_t bitmap_size = merged_rows.getSizeInBytes();
606
2
        blob.referenced_data_file = data_file_path;
607
2
        blob.partition_spec_id = deletion.partition_spec_id;
608
2
        blob.partition_data_json = deletion.partition_data_json;
609
2
        blob.merged_count = static_cast<int64_t>(merged_rows.cardinality());
610
2
        RETURN_IF_ERROR(calculate_iceberg_deletion_vector_content_size(
611
2
                bitmap_size, &blob.content_size_in_bytes));
612
2
        blob.blob_data.resize(static_cast<size_t>(blob.content_size_in_bytes));
613
2
        merged_rows.write(blob.blob_data.data() + 8);
614
615
2
        uint32_t total_length = static_cast<uint32_t>(4 + bitmap_size);
616
2
        BigEndian::Store32(blob.blob_data.data(), total_length);
617
618
2
        constexpr char DV_MAGIC[] = {'\xD1', '\xD3', '\x39', '\x64'};
619
2
        memcpy(blob.blob_data.data() + 4, DV_MAGIC, 4);
620
621
2
        uint32_t crc = static_cast<uint32_t>(
622
2
                ::crc32(0, reinterpret_cast<const Bytef*>(blob.blob_data.data() + 4),
623
2
                        static_cast<uInt>(4 + bitmap_size)));
624
2
        BigEndian::Store32(blob.blob_data.data() + 8 + bitmap_size, crc);
625
2
        blobs.emplace_back(std::move(blob));
626
2
    }
627
628
1
    if (blobs.empty()) {
629
0
        return Status::OK();
630
0
    }
631
632
1
    std::string puffin_path = _generate_puffin_file_path();
633
1
    int64_t puffin_file_size = 0;
634
1
    RETURN_IF_ERROR(_write_puffin_file(puffin_path, &blobs, &puffin_file_size));
635
636
2
    for (const auto& blob : blobs) {
637
2
        TIcebergCommitData commit_data;
638
2
        commit_data.__set_file_path(puffin_path);
639
2
        commit_data.__set_row_count(blob.merged_count);
640
2
        commit_data.__set_affected_rows(blob.delete_count);
641
2
        commit_data.__set_file_size(puffin_file_size);
642
2
        commit_data.__set_file_content(TFileContent::DELETION_VECTOR);
643
2
        commit_data.__set_content_offset(blob.content_offset);
644
2
        commit_data.__set_content_size_in_bytes(blob.content_size_in_bytes);
645
2
        commit_data.__set_referenced_data_file_path(blob.referenced_data_file);
646
2
        if (blob.partition_spec_id != 0 || !blob.partition_data_json.empty()) {
647
2
            commit_data.__set_partition_spec_id(blob.partition_spec_id);
648
2
            commit_data.__set_partition_data_json(blob.partition_data_json);
649
2
        }
650
651
2
        _commit_data_list.push_back(commit_data);
652
2
        _delete_file_count++;
653
2
    }
654
1
    return Status::OK();
655
1
}
656
657
Status VIcebergDeleteSink::_write_puffin_file(const std::string& puffin_path,
658
                                              std::vector<DeletionVectorBlob>* blobs,
659
1
                                              int64_t* out_file_size) {
660
1
    DCHECK(blobs != nullptr);
661
1
    DCHECK(!blobs->empty());
662
663
1
    io::FSPropertiesRef fs_properties(_file_type);
664
1
    fs_properties.properties = &_hadoop_conf;
665
1
    if (!_broker_addresses.empty()) {
666
0
        fs_properties.broker_addresses = &_broker_addresses;
667
0
    }
668
1
    io::FileDescription file_description = {.path = puffin_path, .fs_name {}};
669
1
    auto fs = DORIS_TRY(FileFactory::create_fs(fs_properties, file_description));
670
1
    io::FileWriterOptions file_writer_options = {.used_by_s3_committer = false};
671
1
    io::FileWriterPtr file_writer;
672
1
    RETURN_IF_ERROR(fs->create_file(file_description.path, &file_writer, &file_writer_options));
673
674
1
    constexpr char PUFFIN_MAGIC[] = {'\x50', '\x46', '\x41', '\x31'};
675
1
    RETURN_IF_ERROR(file_writer->append(Slice(reinterpret_cast<const uint8_t*>(PUFFIN_MAGIC), 4)));
676
1
    int64_t current_offset = 4;
677
2
    for (auto& blob : *blobs) {
678
2
        blob.content_offset = current_offset;
679
2
        RETURN_IF_ERROR(file_writer->append(Slice(
680
2
                reinterpret_cast<const uint8_t*>(blob.blob_data.data()), blob.blob_data.size())));
681
2
        current_offset += static_cast<int64_t>(blob.blob_data.size());
682
2
    }
683
1
    RETURN_IF_ERROR(file_writer->append(Slice(reinterpret_cast<const uint8_t*>(PUFFIN_MAGIC), 4)));
684
685
1
    std::string footer_json = _build_puffin_footer_json(*blobs);
686
1
    RETURN_IF_ERROR(file_writer->append(
687
1
            Slice(reinterpret_cast<const uint8_t*>(footer_json.data()), footer_json.size())));
688
689
1
    char footer_size_buf[4];
690
1
    LittleEndian::Store32(footer_size_buf, static_cast<uint32_t>(footer_json.size()));
691
1
    RETURN_IF_ERROR(file_writer->append(
692
1
            Slice(reinterpret_cast<const uint8_t*>(footer_size_buf), sizeof(footer_size_buf))));
693
694
1
    char flags[4] = {0, 0, 0, 0};
695
1
    RETURN_IF_ERROR(
696
1
            file_writer->append(Slice(reinterpret_cast<const uint8_t*>(flags), sizeof(flags))));
697
1
    RETURN_IF_ERROR(file_writer->append(Slice(reinterpret_cast<const uint8_t*>(PUFFIN_MAGIC), 4)));
698
1
    RETURN_IF_ERROR(file_writer->close());
699
700
1
    *out_file_size = current_offset + 4 + static_cast<int64_t>(footer_json.size()) + 4 + 4 + 4;
701
1
    return Status::OK();
702
1
}
703
704
std::string VIcebergDeleteSink::_build_puffin_footer_json(
705
1
        const std::vector<DeletionVectorBlob>& blobs) {
706
1
    rapidjson::StringBuffer buffer;
707
1
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
708
1
    writer.StartObject();
709
1
    writer.Key("blobs");
710
1
    writer.StartArray();
711
2
    for (const auto& blob : blobs) {
712
2
        writer.StartObject();
713
2
        writer.Key("type");
714
2
        writer.String("deletion-vector-v1");
715
2
        writer.Key("fields");
716
2
        writer.StartArray();
717
2
        writer.EndArray();
718
2
        writer.Key("snapshot-id");
719
2
        writer.Int64(-1);
720
2
        writer.Key("sequence-number");
721
2
        writer.Int64(-1);
722
2
        writer.Key("offset");
723
2
        writer.Int64(blob.content_offset);
724
2
        writer.Key("length");
725
2
        writer.Int64(blob.content_size_in_bytes);
726
2
        writer.Key("properties");
727
2
        writer.StartObject();
728
2
        writer.Key("referenced-data-file");
729
2
        writer.String(blob.referenced_data_file.c_str(),
730
2
                      static_cast<rapidjson::SizeType>(blob.referenced_data_file.size()));
731
2
        std::string cardinality = std::to_string(blob.merged_count);
732
2
        writer.Key("cardinality");
733
2
        writer.String(cardinality.c_str(), static_cast<rapidjson::SizeType>(cardinality.size()));
734
2
        writer.EndObject();
735
2
        writer.EndObject();
736
2
    }
737
1
    writer.EndArray();
738
1
    writer.Key("properties");
739
1
    writer.StartObject();
740
1
    writer.Key("created-by");
741
1
    writer.String("doris-puffin-v1");
742
1
    writer.EndObject();
743
1
    writer.EndObject();
744
1
    return {buffer.GetString(), buffer.GetSize()};
745
1
}
746
747
std::string VIcebergDeleteSink::_generate_delete_file_path(
748
1
        const std::string& referenced_data_file) {
749
    // Generate unique delete file name using UUID
750
1
    std::string uuid = generate_uuid_string();
751
1
    std::string file_name;
752
753
1
    std::string file_extension = _get_file_extension();
754
1
    file_name =
755
1
            fmt::format("delete_pos_{}_{}{}", uuid,
756
1
                        std::hash<std::string> {}(referenced_data_file) % 10000000, file_extension);
757
758
    // Combine with output path or table location
759
1
    std::string base_path = _output_path.empty() ? _table_location : _output_path;
760
761
    // Ensure base path ends with /
762
1
    if (!base_path.empty() && base_path.back() != '/') {
763
1
        base_path += '/';
764
1
    }
765
766
    // Delete files are data files in Iceberg, write under data location
767
1
    return fmt::format("{}{}", base_path, file_name);
768
1
}
769
770
1
std::string VIcebergDeleteSink::_generate_puffin_file_path() {
771
1
    std::string uuid = generate_uuid_string();
772
1
    std::string file_name = fmt::format("delete_dv_{}.puffin", uuid);
773
1
    std::string base_path = _output_path.empty() ? _table_location : _output_path;
774
1
    if (!base_path.empty() && base_path.back() != '/') {
775
1
        base_path += '/';
776
1
    }
777
1
    return fmt::format("{}{}", base_path, file_name);
778
1
}
779
780
} // namespace doris