Coverage Report

Created: 2026-08-14 10:14

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