Coverage Report

Created: 2026-07-30 18:53

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