Coverage Report

Created: 2026-07-29 15:21

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