This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new d657e381c2f branch-4.2: [fix](iceberg) Validate required NULLs before
file creation (#69327) (#69842)
d657e381c2f is described below
commit d657e381c2f9e08357c0900a475f83beb435d9ae
Author: daidai <[email protected]>
AuthorDate: Tue Nov 24 15:30:20 2026 +0800
branch-4.2: [fix](iceberg) Validate required NULLs before file creation
(#69327) (#69842)
pick #69327
---
.../writer/iceberg/iceberg_write_validator.cpp | 374 ++++++++++++++++++
.../sink/writer/iceberg/iceberg_write_validator.h | 35 ++
.../writer/iceberg/viceberg_partition_writer.cpp | 39 +-
.../writer/iceberg/viceberg_partition_writer.h | 8 +-
.../sink/writer/iceberg/viceberg_sort_writer.cpp | 109 ++----
.../sink/writer/iceberg/viceberg_table_writer.cpp | 2 +
.../sink/writer/iceberg/viceberg_table_writer.h | 2 +
.../iceberg/iceberg_partition_writer_test.cpp | 183 ++++++++-
.../iceberg/iceberg_write_validator_test.cpp | 427 +++++++++++++++++++++
.../writer/iceberg/viceberg_table_writer_test.cpp | 69 ++++
.../datasource/iceberg/IcebergTransaction.java | 56 ++-
.../insert/BaseExternalTableInsertExecutor.java | 4 +-
.../datasource/iceberg/IcebergTransactionTest.java | 194 ++++++++++
.../iceberg/test_iceberg_show_nullable.groovy | 4 +-
...berg_write_required_null_select_negative.groovy | 74 ++--
...berg_write_required_null_values_negative.groovy | 173 +++++++--
16 files changed, 1593 insertions(+), 160 deletions(-)
diff --git a/be/src/exec/sink/writer/iceberg/iceberg_write_validator.cpp
b/be/src/exec/sink/writer/iceberg/iceberg_write_validator.cpp
new file mode 100644
index 00000000000..c07ae65aad3
--- /dev/null
+++ b/be/src/exec/sink/writer/iceberg/iceberg_write_validator.cpp
@@ -0,0 +1,374 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "exec/sink/writer/iceberg/iceberg_write_validator.h"
+
+#include <fmt/format.h>
+
+#include <algorithm>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "core/assert_cast.h"
+#include "core/block/block.h"
+#include "core/column/column_array.h"
+#include "core/column/column_map.h"
+#include "core/column/column_nullable.h"
+#include "core/column/column_struct.h"
+#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_map.h"
+#include "core/data_type/data_type_nullable.h"
+#include "core/data_type/data_type_struct.h"
+#include "format/table/iceberg/schema.h"
+#include "format/table/iceberg/types.h"
+
+namespace doris::iceberg {
+namespace {
+
+using Path = std::vector<std::string_view>;
+
+struct ValidationLocation {
+ size_t row = 0;
+ std::optional<size_t> ordinal;
+ std::string_view ordinal_kind;
+};
+
+enum class NonNullReason {
+ SCHEMA_REQUIRED,
+ MAP_KEY,
+};
+
+std::string path_to_string(const Path& path) {
+ std::string result;
+ for (size_t i = 0; i < path.size(); ++i) {
+ if (i > 0) {
+ result.push_back('.');
+ }
+ result.append(path[i]);
+ }
+ return result;
+}
+
+Status null_violation(const Path& path, const ValidationLocation& location,
NonNullReason reason) {
+ std::string position = fmt::format("row {}", location.row);
+ if (location.ordinal.has_value()) {
+ position += fmt::format(", {} {}", location.ordinal_kind,
*location.ordinal);
+ }
+ return Status::DataQualityError("Iceberg {} '{}' contains NULL at {}",
+ reason == NonNullReason::MAP_KEY ? "map
key" : "required field",
+ path_to_string(path), position);
+}
+
+bool requires_validation(const NestedField& field) {
+ if (field.is_required()) {
+ return true;
+ }
+ switch (field.field_type()->type_id()) {
+ case TypeID::STRUCT: {
+ const auto& fields = field.field_type()->as_struct_type()->fields();
+ return std::ranges::any_of(
+ fields, [](const NestedField& child) { return
requires_validation(child); });
+ }
+ case TypeID::LIST:
+ return
requires_validation(field.field_type()->as_list_type()->element_field());
+ case TypeID::MAP:
+ // Iceberg map keys are required independently of the map field's
nullability.
+ return true;
+ default:
+ return false;
+ }
+}
+
+template <typename Offsets>
+Status validate_collection_offsets(const Offsets& offsets, size_t position,
size_t row,
+ std::string_view container_name, const
Path& path, size_t* start,
+ size_t* end) {
+ if (position >= offsets.size()) {
+ return Status::InternalError(
+ "Iceberg {} field '{}' has {} offsets, but position {} is
required", container_name,
+ path_to_string(path), offsets.size(), position);
+ }
+ *start = offsets[position - 1];
+ *end = offsets[position];
+ if (*start > *end) {
+ return Status::InternalError(
+ "Iceberg {} field '{}' has invalid offsets at row {}: [{},
{}]", container_name,
+ path_to_string(path), row, *start, *end);
+ }
+ return Status::OK();
+}
+
+Status validate_value(const NestedField& field, const IColumn& column, const
DataTypePtr& type,
+ size_t position, const ValidationLocation& location,
Path& path,
+ NonNullReason reason);
+
+Status validate_struct(const NestedField& field, const IColumn& column, const
DataTypePtr& type,
+ size_t position, const ValidationLocation& location,
Path& path) {
+ const IColumn* data_column = &column;
+ const auto primitive_type = remove_nullable(type)->get_primitive_type();
+ if (primitive_type != TYPE_STRUCT) {
+ return Status::InternalError("Iceberg STRUCT field '{}' does not match
Doris type {}",
+ path_to_string(path), type->get_name());
+ }
+ const auto* struct_column =
check_and_get_column<ColumnStruct>(*data_column);
+ const auto* struct_type = assert_cast<const
DataTypeStruct*>(remove_nullable(type).get());
+ if (struct_column == nullptr) {
+ return Status::InternalError("Iceberg STRUCT field '{}' is not stored
as a STRUCT",
+ path_to_string(path));
+ }
+ const auto& fields = field.field_type()->as_struct_type()->fields();
+ if (struct_column->tuple_size() != fields.size() ||
+ struct_type->get_elements().size() != fields.size()) {
+ return Status::InternalError(
+ "Iceberg STRUCT field '{}' has {} schema fields, {} Doris type
fields, and "
+ "{} column fields",
+ path_to_string(path), fields.size(),
struct_type->get_elements().size(),
+ struct_column->tuple_size());
+ }
+ for (size_t i = 0; i < fields.size(); ++i) {
+ if (!requires_validation(fields[i])) {
+ continue;
+ }
+ path.emplace_back(fields[i].field_name());
+ Status status =
+ validate_value(fields[i], struct_column->get_column(i),
struct_type->get_element(i),
+ position, location, path,
NonNullReason::SCHEMA_REQUIRED);
+ path.pop_back();
+ RETURN_IF_ERROR(status);
+ }
+ return Status::OK();
+}
+
+Status validate_list(const NestedField& field, const IColumn& column, const
DataTypePtr& type,
+ size_t position, const ValidationLocation& location,
Path& path) {
+ const IColumn* data_column = &column;
+ const auto primitive_type = remove_nullable(type)->get_primitive_type();
+ if (primitive_type != TYPE_ARRAY) {
+ return Status::InternalError("Iceberg LIST field '{}' does not match
Doris type {}",
+ path_to_string(path), type->get_name());
+ }
+ const auto* array_column = check_and_get_column<ColumnArray>(*data_column);
+ const auto* array_type = assert_cast<const
DataTypeArray*>(remove_nullable(type).get());
+ if (array_column == nullptr) {
+ return Status::InternalError("Iceberg LIST field '{}' is not stored as
an ARRAY",
+ path_to_string(path));
+ }
+ const auto& offsets = array_column->get_offsets();
+ size_t start = 0;
+ size_t end = 0;
+ RETURN_IF_ERROR(validate_collection_offsets(offsets, position,
location.row, "LIST", path,
+ &start, &end));
+ if (end > array_column->get_data().size()) {
+ return Status::InternalError(
+ "Iceberg LIST field '{}' has invalid offsets at row {}: [{},
{}], "
+ "element count {}",
+ path_to_string(path), location.row, start, end,
array_column->get_data().size());
+ }
+ const auto& element = field.field_type()->as_list_type()->element_field();
+ if (!requires_validation(element)) {
+ return Status::OK();
+ }
+ path.emplace_back(element.field_name());
+ for (size_t i = start; i < end; ++i) {
+ ValidationLocation element_location {
+ .row = location.row,
+ .ordinal = i - start,
+ .ordinal_kind = "element",
+ };
+ Status status =
+ validate_value(element, array_column->get_data(),
array_type->get_nested_type(), i,
+ element_location, path,
NonNullReason::SCHEMA_REQUIRED);
+ if (!status.ok()) {
+ path.pop_back();
+ return status;
+ }
+ }
+ path.pop_back();
+ return Status::OK();
+}
+
+Status validate_map(const NestedField& field, const IColumn& column, const
DataTypePtr& type,
+ size_t position, const ValidationLocation& location, Path&
path) {
+ const IColumn* data_column = &column;
+ const auto primitive_type = remove_nullable(type)->get_primitive_type();
+ if (primitive_type != TYPE_MAP) {
+ return Status::InternalError("Iceberg MAP field '{}' does not match
Doris type {}",
+ path_to_string(path), type->get_name());
+ }
+ const auto* map_column = check_and_get_column<ColumnMap>(*data_column);
+ const auto* map_type = assert_cast<const
DataTypeMap*>(remove_nullable(type).get());
+ if (map_column == nullptr) {
+ return Status::InternalError("Iceberg MAP field '{}' is not stored as
a MAP",
+ path_to_string(path));
+ }
+ const auto& offsets = map_column->get_offsets();
+ size_t start = 0;
+ size_t end = 0;
+ RETURN_IF_ERROR(validate_collection_offsets(offsets, position,
location.row, "MAP", path,
+ &start, &end));
+ if (end > map_column->get_keys().size() || end >
map_column->get_values().size()) {
+ return Status::InternalError(
+ "Iceberg MAP field '{}' has invalid offsets at row {}: [{},
{}], "
+ "key count {}, value count {}",
+ path_to_string(path), location.row, start, end,
map_column->get_keys().size(),
+ map_column->get_values().size());
+ }
+
+ const auto& map_type_desc = field.field_type()->as_map_type();
+ path.emplace_back(map_type_desc->key_field().field_name());
+ for (size_t i = start; i < end; ++i) {
+ ValidationLocation entry_location {
+ .row = location.row,
+ .ordinal = i - start,
+ .ordinal_kind = "map entry",
+ };
+ Status status = validate_value(map_type_desc->key_field(),
map_column->get_keys(),
+ map_type->get_key_type(), i,
entry_location, path,
+ NonNullReason::MAP_KEY);
+ if (!status.ok()) {
+ path.pop_back();
+ return status;
+ }
+ }
+ path.pop_back();
+
+ const auto& value = map_type_desc->value_field();
+ if (!requires_validation(value)) {
+ return Status::OK();
+ }
+ path.emplace_back(value.field_name());
+ for (size_t i = start; i < end; ++i) {
+ ValidationLocation entry_location {
+ .row = location.row,
+ .ordinal = i - start,
+ .ordinal_kind = "map entry",
+ };
+ Status status = validate_value(value, map_column->get_values(),
map_type->get_value_type(),
+ i, entry_location, path,
NonNullReason::SCHEMA_REQUIRED);
+ if (!status.ok()) {
+ path.pop_back();
+ return status;
+ }
+ }
+ path.pop_back();
+ return Status::OK();
+}
+
+Status validate_value(const NestedField& field, const IColumn& column, const
DataTypePtr& type,
+ size_t position, const ValidationLocation& location,
Path& path,
+ NonNullReason reason) {
+ if (position >= column.size()) {
+ return Status::InternalError(
+ "Iceberg write column '{}' has {} values, but position {} "
+ "is required",
+ path_to_string(path), column.size(), position);
+ }
+
+ if (column.is_null_at(position)) {
+ if (reason == NonNullReason::MAP_KEY || field.is_required()) {
+ return null_violation(path, location, reason);
+ }
+ // An optional STRUCT/LIST/MAP is a NULL value in its own right. Its
children and
+ // elements are masked by the parent NULL and must not be inspected.
+ return Status::OK();
+ }
+
+ const IColumn* data_column = &column;
+ if (const auto* nullable = check_and_get_column<ColumnNullable>(column)) {
+ data_column = &nullable->get_nested_column();
+ }
+
+ switch (field.field_type()->type_id()) {
+ case TypeID::STRUCT:
+ return validate_struct(field, *data_column, type, position, location,
path);
+ case TypeID::LIST:
+ return validate_list(field, *data_column, type, position, location,
path);
+ case TypeID::MAP:
+ return validate_map(field, *data_column, type, position, location,
path);
+ default:
+ return Status::OK();
+ }
+}
+
+} // namespace
+
+Status validate_write_block(const Schema& schema, const Block& block) {
+ if (block.columns() != schema.columns().size()) {
+ return Status::InternalError(
+ "Iceberg write block has {} columns, but pinned schema has {}
fields",
+ block.columns(), schema.columns().size());
+ }
+
+ Path path;
+ path.reserve(8);
+ for (size_t field_index = 0; field_index < schema.columns().size();
++field_index) {
+ const auto& field = schema.columns()[field_index];
+ if (!requires_validation(field)) {
+ continue;
+ }
+ const auto& column_with_name = block.get_by_position(field_index);
+ ColumnPtr column =
column_with_name.column->convert_to_full_column_if_const();
+ if (!column) {
+ return Status::InternalError("Iceberg write block column {} is
null", field_index);
+ }
+ if (column->size() < block.rows()) {
+ return Status::InternalError(
+ "Iceberg write block column '{}' has {} values, but block
has {} rows",
+ field.field_name(), column->size(), block.rows());
+ }
+
+ path.emplace_back(field.field_name());
+ if (field.field_type()->is_primitive_type() && field.is_required()) {
+ if (column->has_null()) {
+ for (size_t row = 0; row < block.rows(); ++row) {
+ if (!column->is_null_at(row)) {
+ continue;
+ }
+ ValidationLocation location {
+ .row = row,
+ .ordinal = std::nullopt,
+ .ordinal_kind = {},
+ };
+ Status status = null_violation(path, location,
NonNullReason::SCHEMA_REQUIRED);
+ path.pop_back();
+ return status;
+ }
+ }
+ path.pop_back();
+ continue;
+ }
+ for (size_t row = 0; row < block.rows(); ++row) {
+ ValidationLocation location {
+ .row = row,
+ .ordinal = std::nullopt,
+ .ordinal_kind = {},
+ };
+ Status status = validate_value(field, *column,
column_with_name.type, row, location,
+ path,
NonNullReason::SCHEMA_REQUIRED);
+ if (!status.ok()) {
+ path.pop_back();
+ return status;
+ }
+ }
+ path.pop_back();
+ }
+ return Status::OK();
+}
+
+} // namespace doris::iceberg
diff --git a/be/src/exec/sink/writer/iceberg/iceberg_write_validator.h
b/be/src/exec/sink/writer/iceberg/iceberg_write_validator.h
new file mode 100644
index 00000000000..30d55e1f52a
--- /dev/null
+++ b/be/src/exec/sink/writer/iceberg/iceberg_write_validator.h
@@ -0,0 +1,35 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include "common/status.h"
+
+namespace doris {
+
+class Block;
+
+namespace iceberg {
+
+class Schema;
+
+// Validates the data-dependent Iceberg write contract for one materialized
Block.
+// Schema identity, field IDs, partition specs, and sort orders are pinned and
checked in FE.
+Status validate_write_block(const Schema& schema, const Block& block);
+
+} // namespace iceberg
+} // namespace doris
diff --git a/be/src/exec/sink/writer/iceberg/viceberg_partition_writer.cpp
b/be/src/exec/sink/writer/iceberg/viceberg_partition_writer.cpp
index be14b1ef48c..02106907a39 100644
--- a/be/src/exec/sink/writer/iceberg/viceberg_partition_writer.cpp
+++ b/be/src/exec/sink/writer/iceberg/viceberg_partition_writer.cpp
@@ -132,13 +132,33 @@ Status VIcebergPartitionWriter::open(RuntimeState* state,
RuntimeProfile* profil
}
}
if (!open_status.ok()) {
- // A transformer failure happens after object creation, so remove any
published file.
- WARN_IF_ERROR(_fs->delete_file(_path), "failed to delete Iceberg file
after open error");
+ // Defer deletion until the output stream has finished closing so an
asynchronous upload
+ // cannot publish the failed file later.
+ _defer_file_cleanup();
}
return open_status;
}
+void VIcebergPartitionWriter::_defer_file_cleanup() {
+ if (_fs == nullptr || _file_cleanup_deferred) {
+ return;
+ }
+ _file_cleanup_deferred = true;
+ // The output stream may still own an asynchronous upload after a failed
close. Destroy it
+ // before the outer writer deletes the physical object.
+ _file_format_transformer.reset();
+ _file_writer.reset();
+ if (_closed_file_callback) {
+ _closed_file_callback(_fs, _path);
+ } else {
+ WARN_IF_ERROR(_fs->delete_file(_path), "failed to delete Iceberg
file");
+ }
+}
+
Status VIcebergPartitionWriter::close(const Status& status) {
+ if (_file_cleanup_deferred) {
+ return _terminal_close_status;
+ }
Status result_status;
if (_file_format_transformer != nullptr) {
result_status = _file_format_transformer->close();
@@ -149,22 +169,15 @@ Status VIcebergPartitionWriter::close(const Status&
status) {
}
bool status_ok = result_status.ok() && status.ok();
if (!status_ok && _fs != nullptr) {
- // delete the actual created file, otherwise an orphan file is left
behind
- Status st = _fs->delete_file(_path);
- if (!st.ok()) {
- LOG(WARNING) << fmt::format("Delete file {} failed, reason: {}",
_path, st.to_string());
- }
+ _terminal_close_status = result_status;
+ _defer_file_cleanup();
}
if (status_ok) {
TIcebergCommitData commit_data;
Status commit_status = _build_iceberg_commit_data(&commit_data);
if (!commit_status.ok()) {
- // A closed object without commit data can never be published, so
remove it immediately.
- Status delete_status = _fs->delete_file(_path);
- if (!delete_status.ok()) {
- LOG(WARNING) << fmt::format("Delete file {} failed, reason:
{}", _path,
- delete_status.to_string());
- }
+ _terminal_close_status = commit_status;
+ _defer_file_cleanup();
return commit_status;
}
_state->add_iceberg_commit_datas(commit_data);
diff --git a/be/src/exec/sink/writer/iceberg/viceberg_partition_writer.h
b/be/src/exec/sink/writer/iceberg/viceberg_partition_writer.h
index f3a7a6002f8..2a06f8776f9 100644
--- a/be/src/exec/sink/writer/iceberg/viceberg_partition_writer.h
+++ b/be/src/exec/sink/writer/iceberg/viceberg_partition_writer.h
@@ -70,7 +70,9 @@ public:
inline int file_name_index() const override { return _file_name_index; }
- inline size_t written_len() const override { return
_file_format_transformer->written_len(); }
+ inline size_t written_len() const override {
+ return _file_format_transformer == nullptr ? 0 :
_file_format_transformer->written_len();
+ }
private:
friend class VIcebergPartitionWriterTest;
@@ -79,6 +81,8 @@ private:
Status _build_iceberg_commit_data(TIcebergCommitData* commit_data);
+ void _defer_file_cleanup();
+
std::string _get_file_extension(TFileFormatType::type file_format_type,
TFileCompressType::type
write_compress_type);
@@ -100,6 +104,8 @@ private:
TFileCompressType::type _compress_type;
const std::map<std::string, std::string>& _hadoop_conf;
ClosedFileCallback _closed_file_callback;
+ bool _file_cleanup_deferred = false;
+ Status _terminal_close_status = Status::OK();
bool _collect_column_stats = true;
std::shared_ptr<io::FileSystem> _fs = nullptr;
diff --git a/be/src/exec/sink/writer/iceberg/viceberg_sort_writer.cpp
b/be/src/exec/sink/writer/iceberg/viceberg_sort_writer.cpp
index b296fa9c504..c29525e5256 100644
--- a/be/src/exec/sink/writer/iceberg/viceberg_sort_writer.cpp
+++ b/be/src/exec/sink/writer/iceberg/viceberg_sort_writer.cpp
@@ -17,6 +17,7 @@
#include "exec/sink/writer/iceberg/viceberg_sort_writer.h"
+#include "common/exception.h"
#include "exec/spill/spill_file_manager.h"
#include "exec/spill/spill_file_reader.h"
#include "exec/spill/spill_file_writer.h"
@@ -118,80 +119,42 @@ Status VIcebergSortWriter::close(const Status& status) {
}
Status VIcebergSortWriter::_close_locked(const Status& status) {
- // Track the actual internal status of operations performed during close.
- // This is important because if intermediate operations (like do_sort())
fail,
- // we need to propagate the actual error status to the underlying
partition writer's
- // close() call, rather than the original status parameter which could be
OK.
- Status internal_status = Status::OK();
- // Track the close status of the underlying partition writer.
- // If _iceberg_partition_writer->close() fails (e.g., Parquet file flush
error),
- // we must propagate this error to the caller to avoid silent data loss.
- Status close_status = Status::OK();
-
- // Defer ensures the underlying partition writer is always closed and
- // spill streams are cleaned up, regardless of whether intermediate
operations succeed.
- // Uses internal_status to propagate any errors that occurred during close
operations.
- Defer defer {[&]() {
- // If any intermediate operation failed, pass that error to the
partition writer;
- // otherwise, pass the original status from the caller.
- close_status =
- _iceberg_partition_writer->close(internal_status.ok() ? status
: internal_status);
- if (!close_status.ok()) {
- LOG(WARNING) << fmt::format("_iceberg_partition_writer close
failed, reason: {}",
- close_status.to_string());
- }
- _cleanup_spill_streams();
- }};
-
- // If the original status is already an error or the query is cancelled,
- // skip all close operations and propagate the original error
- if (!status.ok() || _runtime_state->is_cancelled()) {
- return status;
- }
-
- // If sorter was never initialized (e.g., no data was written), nothing to
do
- if (_sorter == nullptr) {
- return Status::OK();
- }
-
- // Check if there is any remaining data in the sorter (either unsorted or
already sorted blocks)
- if (!_sorter->merge_sort_state()->unsorted_block()->empty() ||
- !_sorter->merge_sort_state()->get_sorted_block().empty()) {
- if (_sorted_spill_files.empty()) {
- // No spill has occurred, all data is in memory.
- // Sort the remaining data, prepare for reading, and write to file.
- internal_status = _sorter->do_sort();
- if (!internal_status.ok()) {
- return internal_status;
- }
- internal_status = _sorter->prepare_for_read(false);
- if (!internal_status.ok()) {
- return internal_status;
- }
- internal_status = _write_sorted_data();
- return internal_status;
- }
-
- // Some data has already been spilled to disk.
- // Spill the remaining in-memory data to a new spill stream.
- internal_status = _do_spill();
- if (!internal_status.ok()) {
- return internal_status;
- }
+ Status internal_status = status;
+ // Sort/merge/permute allocations can throw. Convert them before
finalizing the partition so
+ // outer close still learns about the file even though close() marks this
sorted writer closed.
+ ASSIGN_STATUS_IF_CATCH_EXCEPTION(
+ {
+ if (status.ok() && !_runtime_state->is_cancelled()) {
+ internal_status = Status::OK();
+ if (_sorter != nullptr &&
+
(!_sorter->merge_sort_state()->unsorted_block()->empty() ||
+
!_sorter->merge_sort_state()->get_sorted_block().empty())) {
+ if (_sorted_spill_files.empty()) {
+ internal_status = _sorter->do_sort();
+ if (internal_status.ok()) {
+ internal_status =
_sorter->prepare_for_read(false);
+ }
+ if (internal_status.ok()) {
+ internal_status = _write_sorted_data();
+ }
+ } else {
+ internal_status = _do_spill();
+ }
+ }
+ if (internal_status.ok() && !_sorted_spill_files.empty()) {
+ internal_status = _combine_files_output();
+ }
+ }
+ },
+ internal_status);
+
+ // Form the return value only after the underlying close runs; a deferred
assignment is too late.
+ Status close_status =
+ _iceberg_partition_writer->close(internal_status.ok() ? status :
internal_status);
+ _cleanup_spill_streams();
+ if (!internal_status.ok()) {
+ return internal_status;
}
-
- // Merge all spilled streams using multi-way merge sort and output final
sorted data to files
- if (!_sorted_spill_files.empty()) {
- internal_status = _combine_files_output();
- if (!internal_status.ok()) {
- return internal_status;
- }
- }
-
- // Return close_status if internal operations succeeded but the underlying
- // partition writer's close() failed (e.g., file flush error).
- // This prevents silent data loss where the caller thinks the write
succeeded
- // but the file was not properly closed.
return close_status;
}
diff --git a/be/src/exec/sink/writer/iceberg/viceberg_table_writer.cpp
b/be/src/exec/sink/writer/iceberg/viceberg_table_writer.cpp
index 23d7e9b30a0..02454e94512 100644
--- a/be/src/exec/sink/writer/iceberg/viceberg_table_writer.cpp
+++ b/be/src/exec/sink/writer/iceberg/viceberg_table_writer.cpp
@@ -32,6 +32,7 @@
#include "core/data_type/data_type_struct.h"
#include "core/data_type_serde/data_type_serde.h"
#include "exec/sink/writer/iceberg/iceberg_partition_path.h"
+#include "exec/sink/writer/iceberg/iceberg_write_validator.h"
#include "exec/sink/writer/iceberg/partition_transformers.h"
#include "exec/sink/writer/iceberg/viceberg_partition_writer.h"
#include "exec/sink/writer/iceberg/viceberg_sort_writer.h"
@@ -448,6 +449,7 @@ Status
VIcebergTableWriter::_process_row_lineage_columns(Block& block) {
Status VIcebergTableWriter::_write_prepared_block(Block& output_block) {
RETURN_IF_ERROR(_process_row_lineage_columns(output_block));
+ RETURN_IF_ERROR(iceberg::validate_write_block(*_schema, output_block));
std::unordered_map<std::shared_ptr<IPartitionWriterBase>, IColumn::Filter>
writer_positions;
_row_count += output_block.rows();
diff --git a/be/src/exec/sink/writer/iceberg/viceberg_table_writer.h
b/be/src/exec/sink/writer/iceberg/viceberg_table_writer.h
index 5baf351c72c..953b2116e3b 100644
--- a/be/src/exec/sink/writer/iceberg/viceberg_table_writer.h
+++ b/be/src/exec/sink/writer/iceberg/viceberg_table_writer.h
@@ -92,6 +92,8 @@ private:
friend class IcebergTableSinkOperatorTest;
FRIEND_TEST(VIcebergTableWriterTest, RejectMissingPartitionSource);
FRIEND_TEST(VIcebergTableWriterTest, ResolvesNestedPartitionSource);
+ FRIEND_TEST(VIcebergTableWriterTest,
RejectsRequiredNullBeforeWriterCreation);
+ FRIEND_TEST(VIcebergTableWriterTest,
RejectsNestedRequiredNullBeforeWriterCreation);
// The currently active partition writer (may be VIcebergPartitionWriter
or VIcebergSortWriter).
// Updated during write() to track which writer received the most recent
data.
diff --git a/be/test/exec/sink/writer/iceberg/iceberg_partition_writer_test.cpp
b/be/test/exec/sink/writer/iceberg/iceberg_partition_writer_test.cpp
index 4ea11154098..adfbd11bdd5 100644
--- a/be/test/exec/sink/writer/iceberg/iceberg_partition_writer_test.cpp
+++ b/be/test/exec/sink/writer/iceberg/iceberg_partition_writer_test.cpp
@@ -20,9 +20,11 @@
#include <optional>
+#include "core/column/column_dummy.h"
#include "core/data_type/data_type_number.h"
#include "exec/sink/writer/iceberg/viceberg_partition_writer.h"
#include "exec/sink/writer/iceberg/viceberg_sort_writer.h"
+#include "exec/sink/writer/iceberg/viceberg_table_writer.h"
#include "format/table/iceberg/schema_parser.h"
#include "format/transformer/viceberg_parquet_writer.h"
#include "io/fs/file_system.h"
@@ -40,15 +42,45 @@ namespace doris {
namespace {
+class ThrowOnSortCloneColumn final : public COWHelper<IColumnDummy,
ThrowOnSortCloneColumn> {
+private:
+ friend class COWHelper<IColumnDummy, ThrowOnSortCloneColumn>;
+ explicit ThrowOnSortCloneColumn(size_t rows) { s = rows; }
+ ThrowOnSortCloneColumn(const ThrowOnSortCloneColumn&) = default;
+
+public:
+ std::string get_name() const override { return "ThrowOnSortClone"; }
+ MutableColumnPtr clone_dummy(size_t) const override {
+ throw Exception(ErrorCode::MEM_ALLOC_FAILED, "injected sorted EOS
allocation failure");
+ }
+ bool structure_equals(const IColumn& rhs) const override {
+ return typeid(rhs) == typeid(ThrowOnSortCloneColumn);
+ }
+};
+
class FakeFileFormatTransformer final : public VFileFormatTransformer {
public:
- explicit FakeFileFormatTransformer(const VExprContextSPtrs& output_exprs)
- : VFileFormatTransformer(nullptr, output_exprs, false) {}
+ explicit FakeFileFormatTransformer(const VExprContextSPtrs& output_exprs,
+ Status close_status = Status::OK(),
+ bool* destroyed = nullptr)
+ : VFileFormatTransformer(nullptr, output_exprs, false),
+ _close_status(std::move(close_status)),
+ _destroyed(destroyed) {}
+
+ ~FakeFileFormatTransformer() override {
+ if (_destroyed != nullptr) {
+ *_destroyed = true;
+ }
+ }
Status open() override { return Status::OK(); }
Status write(const Block&) override { return Status::OK(); }
- Status close() override { return Status::OK(); }
+ Status close() override { return _close_status; }
int64_t written_len() override { return 64; }
+
+private:
+ Status _close_status;
+ bool* _destroyed;
};
TDataSink make_table_sink(std::optional<bool> collect_column_stats) {
@@ -80,9 +112,11 @@ protected:
}
static void install_fake_transformer(VIcebergPartitionWriter* writer,
- const VExprContextSPtrs&
output_exprs) {
- writer->_file_format_transformer =
- std::make_unique<FakeFileFormatTransformer>(output_exprs);
+ const VExprContextSPtrs& output_exprs,
+ Status close_status = Status::OK(),
+ bool* destroyed = nullptr) {
+ writer->_file_format_transformer =
std::make_unique<FakeFileFormatTransformer>(
+ output_exprs, std::move(close_status), destroyed);
}
static void install_parquet_transformer(VIcebergPartitionWriter* writer,
@@ -98,6 +132,19 @@ protected:
static bool collect_column_stats(const VIcebergPartitionWriter& writer) {
return writer._collect_column_stats;
}
+
+ static Status persist_file(VIcebergPartitionWriter* writer) {
+ RETURN_IF_ERROR(writer->_fs->create_file(writer->_path,
&writer->_file_writer));
+ RETURN_IF_ERROR(writer->_file_writer->append(Slice("persisted data")));
+ return writer->_file_writer->close();
+ }
+
+ static void expect_file_presence(const std::shared_ptr<io::FileSystem>& fs,
+ const std::string& path, bool expected) {
+ bool exists = false;
+ ASSERT_TRUE(fs->exists(path, &exists).ok());
+ EXPECT_EQ(expected, exists);
+ }
};
TEST_F(VIcebergPartitionWriterTest,
OrcSkipsFooterCollectionWhenMetricsAreDisabled) {
@@ -195,4 +242,128 @@ TEST_F(VIcebergPartitionWriterTest,
UnsupportedParquetCodecDoesNotCreateFile) {
EXPECT_FALSE(exists);
}
+TEST_F(VIcebergPartitionWriterTest,
SortWriterPropagatesUnderlyingCloseFailure) {
+ VExprContextSPtrs output_exprs;
+ iceberg::Schema schema(std::vector<iceberg::NestedField> {});
+ std::string schema_json;
+ std::map<std::string, std::string> hadoop_conf;
+ auto partition_writer = std::shared_ptr<VIcebergPartitionWriter>(
+ make_writer(make_table_sink(false), output_exprs, schema,
&schema_json, hadoop_conf));
+ install_fake_transformer(partition_writer.get(), output_exprs,
+ Status::IOError("injected close failure"));
+ VIcebergSortWriter sort_writer(partition_writer, TSortInfo(), 1024);
+ RuntimeState state;
+ sort_writer._runtime_state = &state;
+
+ Status status = sort_writer.close(Status::OK());
+
+ EXPECT_FALSE(status.ok());
+ EXPECT_NE(status.to_string().find("injected close failure"),
std::string::npos);
+}
+
+TEST_F(VIcebergPartitionWriterTest,
SortedEosAllocationFailureRemovesPersistedFile) {
+ VExprContextSPtrs output_exprs;
+ iceberg::Schema schema(std::vector<iceberg::NestedField> {});
+ std::string schema_json;
+ std::map<std::string, std::string> hadoop_conf;
+ auto sink = make_table_sink(false);
+ bool transformer_destroyed = false;
+ auto partition_writer = std::shared_ptr<VIcebergPartitionWriter>(
+ make_writer(sink, output_exprs, schema, &schema_json,
hadoop_conf));
+ auto fs = io::global_local_filesystem();
+ std::string path = "./iceberg_sorted_eos_failure_" +
UniqueId::gen_uid().to_string() + ".orc";
+ Defer cleanup_file {
+ [&]() { WARN_IF_ERROR(fs->delete_file(path), "test file cleanup
failed"); }};
+ partition_writer->_fs = fs;
+ partition_writer->_path = path;
+ ASSERT_TRUE(persist_file(partition_writer.get()).ok());
+ install_fake_transformer(partition_writer.get(), output_exprs,
Status::OK(),
+ &transformer_destroyed);
+ VIcebergTableWriter table_writer(sink, output_exprs);
+ partition_writer->_closed_file_callback =
[&](std::shared_ptr<io::FileSystem> file_fs,
+ const std::string&
file_path) {
+ EXPECT_TRUE(transformer_destroyed);
+ table_writer._closed_files.emplace_back(std::move(file_fs), file_path);
+ };
+ MockRuntimeState state;
+ RuntimeProfile profile("sorted-eos-failure");
+ MockRowDescriptor row_desc;
+ partition_writer->_state = &state;
+ VIcebergSortWriter sort_writer(partition_writer, TSortInfo(), 1024);
+ sort_writer._runtime_state = &state;
+ sort_writer._sorter = FullSorter::create_unique(
+ sort_writer._ordering_expr_ctxs, -1, 0, &sort_writer._pool,
+ sort_writer._sort_info.is_asc_order,
sort_writer._sort_info.nulls_first, row_desc,
+ &state, &profile);
+ sort_writer._sorter->init_profile(&profile);
+ sort_writer._sorter->set_enable_spill();
+ *sort_writer._sorter->merge_sort_state()->unsorted_block() =
Block({ColumnWithTypeAndName(
+ ThrowOnSortCloneColumn::create(1),
std::make_shared<DataTypeInt32>(), "id")});
+
+ Status status = sort_writer.close(Status::OK());
+
+ EXPECT_FALSE(status.ok());
+ EXPECT_NE(status.to_string().find("injected sorted EOS allocation
failure"), std::string::npos);
+ ASSERT_EQ(1, table_writer._closed_files.size());
+ expect_file_presence(fs, path, true);
+ EXPECT_TRUE(state.iceberg_commit_datas().empty());
+ table_writer.finish_deferred_file_cleanup(status);
+ expect_file_presence(fs, path, false);
+ EXPECT_TRUE(table_writer._closed_files.empty());
+ EXPECT_TRUE(sort_writer.close(status).ok());
+}
+
+TEST_F(VIcebergPartitionWriterTest,
FailedCloseDefersFileCleanupToOuterCallback) {
+ VExprContextSPtrs output_exprs;
+ iceberg::Schema schema(std::vector<iceberg::NestedField> {});
+ std::string schema_json;
+ std::map<std::string, std::string> hadoop_conf;
+ auto writer = std::shared_ptr<VIcebergPartitionWriter>(
+ make_writer(make_table_sink(false), output_exprs, schema,
&schema_json, hadoop_conf));
+ bool transformer_destroyed = false;
+ install_fake_transformer(writer.get(), output_exprs, Status::OK(),
&transformer_destroyed);
+ writer->_fs = io::global_local_filesystem();
+ writer->_path = "./doris-iceberg-failed-close.orc";
+ int cleanup_calls = 0;
+ writer->_closed_file_callback = [&](std::shared_ptr<io::FileSystem> fs,
+ const std::string& path) {
+ EXPECT_EQ(writer->_fs, fs);
+ EXPECT_EQ(writer->_path, path);
+ EXPECT_TRUE(transformer_destroyed);
+ ++cleanup_calls;
+ };
+
+ EXPECT_TRUE(writer->close(Status::Cancelled("injected write
failure")).ok());
+ EXPECT_EQ(1, cleanup_calls);
+ EXPECT_EQ(0, writer->written_len());
+
+ EXPECT_TRUE(writer->close(Status::Cancelled("injected write
failure")).ok());
+ EXPECT_EQ(1, cleanup_calls);
+}
+
+TEST_F(VIcebergPartitionWriterTest, RepeatedClosePreservesTerminalError) {
+ VExprContextSPtrs output_exprs;
+ iceberg::Schema schema(std::vector<iceberg::NestedField> {});
+ std::string schema_json;
+ std::map<std::string, std::string> hadoop_conf;
+ auto writer = std::shared_ptr<VIcebergPartitionWriter>(
+ make_writer(make_table_sink(false), output_exprs, schema,
&schema_json, hadoop_conf));
+ install_fake_transformer(writer.get(), output_exprs,
Status::IOError("injected close failure"));
+ writer->_fs = io::global_local_filesystem();
+ writer->_path = "./doris-iceberg-close-failure.orc";
+ int cleanup_calls = 0;
+ writer->_closed_file_callback = [&](std::shared_ptr<io::FileSystem>, const
std::string&) {
+ ++cleanup_calls;
+ };
+
+ Status first_status = writer->close(Status::OK());
+ Status second_status = writer->close(Status::OK());
+
+ EXPECT_FALSE(first_status.ok());
+ EXPECT_FALSE(second_status.ok());
+ EXPECT_NE(first_status.to_string().find("injected close failure"),
std::string::npos);
+ EXPECT_EQ(first_status, second_status);
+ EXPECT_EQ(1, cleanup_calls);
+}
+
} // namespace doris
diff --git a/be/test/exec/sink/writer/iceberg/iceberg_write_validator_test.cpp
b/be/test/exec/sink/writer/iceberg/iceberg_write_validator_test.cpp
new file mode 100644
index 00000000000..435a3c9600f
--- /dev/null
+++ b/be/test/exec/sink/writer/iceberg/iceberg_write_validator_test.cpp
@@ -0,0 +1,427 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "exec/sink/writer/iceberg/iceberg_write_validator.h"
+
+#include <gtest/gtest.h>
+
+#include <memory>
+#include <optional>
+#include <vector>
+
+#include "core/block/block.h"
+#include "core/column/column_array.h"
+#include "core/column/column_const.h"
+#include "core/column/column_map.h"
+#include "core/column/column_nullable.h"
+#include "core/column/column_struct.h"
+#include "core/column/column_vector.h"
+#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_map.h"
+#include "core/data_type/data_type_nullable.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "core/data_type/data_type_struct.h"
+#include "format/table/iceberg/schema.h"
+#include "format/table/iceberg/types.h"
+
+namespace doris::iceberg {
+namespace {
+
+DataTypePtr nullable_int() {
+ return make_nullable(std::make_shared<DataTypeInt32>());
+}
+
+ColumnPtr nullable_int_column(std::vector<int32_t> values,
std::vector<uint8_t> nulls) {
+ auto data = ColumnInt32::create();
+ data->get_data().assign(values.begin(), values.end());
+ auto null_map = ColumnUInt8::create();
+ null_map->get_data().assign(nulls.begin(), nulls.end());
+ return ColumnNullable::create(std::move(data), std::move(null_map));
+}
+
+void expect_data_quality_error(const Status& status, std::string_view path,
+ std::string_view location) {
+ EXPECT_FALSE(status.ok());
+ EXPECT_NE(status.to_string().find(path), std::string::npos);
+ EXPECT_NE(status.to_string().find(location), std::string::npos);
+}
+
+Schema field_schema(std::unique_ptr<Type> type, bool optional = false) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(optional, 1, "payload", std::move(type), std::nullopt);
+ return {std::move(fields)};
+}
+
+std::vector<std::unique_ptr<Type>> required_container_types() {
+ std::vector<std::unique_ptr<Type>> types;
+ std::vector<NestedField> children;
+ children.emplace_back(false, 2, "id", std::make_unique<IntegerType>(),
std::nullopt);
+ types.push_back(std::make_unique<StructType>(std::move(children)));
+ types.push_back(ListType::of_required(2, std::make_unique<IntegerType>()));
+ types.push_back(MapType::of_required(2, 3, std::make_unique<IntegerType>(),
+ std::make_unique<IntegerType>()));
+ return types;
+}
+
+void expect_invalid_block(const Schema& schema, const Block& block,
std::string_view message) {
+ Status status = validate_write_block(schema, block);
+ EXPECT_TRUE(status.is<ErrorCode::INTERNAL_ERROR>()) << status.to_string();
+ EXPECT_NE(status.to_string().find(message), std::string::npos) <<
status.to_string();
+}
+
+} // namespace
+
+TEST(IcebergWriteValidatorTest, RejectsTopLevelRequiredNullWithLocation) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(false, 1, "payload", std::make_unique<StringType>(),
std::nullopt);
+ Schema schema(std::move(fields));
+ auto type = make_nullable(std::make_shared<DataTypeString>());
+ auto data = ColumnString::create();
+ data->insert_data("A", 1);
+ data->insert_default();
+ auto null_map = ColumnUInt8::create();
+ null_map->get_data().assign({0, 1});
+ Block block({ColumnWithTypeAndName(ColumnNullable::create(std::move(data),
std::move(null_map)),
+ type, "payload")});
+
+ expect_data_quality_error(validate_write_block(schema, block), "payload",
"row 1");
+}
+
+TEST(IcebergWriteValidatorTest, RejectsRequiredConstantNull) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(false, 1, "id", std::make_unique<IntegerType>(),
std::nullopt);
+ Schema schema(std::move(fields));
+ auto type = nullable_int();
+ Block
block({ColumnWithTypeAndName(ColumnConst::create(nullable_int_column({0}, {1}),
3), type,
+ "id")});
+
+ expect_data_quality_error(validate_write_block(schema, block), "id", "row
0");
+}
+
+TEST(IcebergWriteValidatorTest, SkipsRequiredChildWhenOptionalParentIsNull) {
+ std::vector<NestedField> child_fields;
+ child_fields.emplace_back(false, 2, "id", std::make_unique<IntegerType>(),
std::nullopt);
+ std::vector<NestedField> fields;
+ fields.emplace_back(true, 1, "payload",
std::make_unique<StructType>(std::move(child_fields)),
+ std::nullopt);
+ Schema schema(std::move(fields));
+ auto child_type = nullable_int();
+ auto struct_type = std::make_shared<DataTypeStruct>(DataTypes
{child_type}, Strings {"id"});
+ auto parent_type = make_nullable(struct_type);
+ Columns children {nullable_int_column({7}, {1})};
+ auto parent_null_map = ColumnUInt8::create();
+ parent_null_map->get_data().push_back(1);
+ Block block(
+
{ColumnWithTypeAndName(ColumnNullable::create(ColumnStruct::create(std::move(children)),
+
std::move(parent_null_map)),
+ parent_type, "payload")});
+
+ EXPECT_TRUE(validate_write_block(schema, block).ok());
+}
+
+TEST(IcebergWriteValidatorTest, RejectsRequiredStructChildNull) {
+ std::vector<NestedField> child_fields;
+ child_fields.emplace_back(false, 2, "id", std::make_unique<IntegerType>(),
std::nullopt);
+ std::vector<NestedField> fields;
+ fields.emplace_back(false, 1, "payload",
std::make_unique<StructType>(std::move(child_fields)),
+ std::nullopt);
+ Schema schema(std::move(fields));
+ auto child_type = nullable_int();
+ auto struct_type = std::make_shared<DataTypeStruct>(DataTypes
{child_type}, Strings {"id"});
+ auto parent_type = make_nullable(struct_type);
+ Columns children {nullable_int_column({7, 8}, {0, 1})};
+ auto parent_null_map = ColumnUInt8::create();
+ parent_null_map->get_data().assign({0, 0});
+ Block block(
+
{ColumnWithTypeAndName(ColumnNullable::create(ColumnStruct::create(std::move(children)),
+
std::move(parent_null_map)),
+ parent_type, "payload")});
+
+ expect_data_quality_error(validate_write_block(schema, block),
"payload.id", "row 1");
+}
+
+TEST(IcebergWriteValidatorTest, RejectsRequiredListElementNull) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(true, 1, "items", ListType::of_required(2,
std::make_unique<IntegerType>()),
+ std::nullopt);
+ Schema schema(std::move(fields));
+ auto element_type = nullable_int();
+ auto array_type = std::make_shared<DataTypeArray>(element_type);
+ auto offsets = ColumnArray::ColumnOffsets::create();
+ offsets->get_data().push_back(3);
+ auto array = ColumnArray::create(nullable_int_column({1, 2, 3}, {0, 1,
0}), std::move(offsets));
+ auto null_map = ColumnUInt8::create();
+ null_map->get_data().push_back(0);
+ Block block(
+ {ColumnWithTypeAndName(ColumnNullable::create(std::move(array),
std::move(null_map)),
+ make_nullable(array_type), "items")});
+
+ expect_data_quality_error(validate_write_block(schema, block),
"items.element", "element 1");
+}
+
+TEST(IcebergWriteValidatorTest, RejectsNullMapKey) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(true, 1, "attrs",
+ MapType::of_required(2, 3,
std::make_unique<IntegerType>(),
+ std::make_unique<IntegerType>()),
+ std::nullopt);
+ Schema schema(std::move(fields));
+ auto key_type = std::make_shared<DataTypeInt32>();
+ auto value_type = nullable_int();
+ auto map_type = std::make_shared<DataTypeMap>(key_type, value_type);
+ auto offsets = ColumnMap::COffsets::create();
+ offsets->get_data().push_back(2);
+ auto map = ColumnMap::create(nullable_int_column({1, 2}, {0, 1}),
+ nullable_int_column({10, 20}, {0, 0}),
std::move(offsets));
+ auto null_map = ColumnUInt8::create();
+ null_map->get_data().push_back(0);
+ Block block({ColumnWithTypeAndName(ColumnNullable::create(std::move(map),
std::move(null_map)),
+ make_nullable(map_type), "attrs")});
+
+ expect_data_quality_error(validate_write_block(schema, block),
"attrs.key", "map entry 1");
+}
+
+TEST(IcebergWriteValidatorTest, SkipsMapKeyWhenOptionalMapIsNull) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(true, 1, "attrs",
+ MapType::of_required(2, 3,
std::make_unique<IntegerType>(),
+ std::make_unique<IntegerType>()),
+ std::nullopt);
+ Schema schema(std::move(fields));
+ auto key_type = std::make_shared<DataTypeInt32>();
+ auto value_type = nullable_int();
+ auto map_type = std::make_shared<DataTypeMap>(key_type, value_type);
+ auto offsets = ColumnMap::COffsets::create();
+ offsets->get_data().push_back(1);
+ // Keep a physically materialized NULL key under the NULL parent to prove
that the parent mask,
+ // rather than an empty map, is what suppresses the map-key check.
+ auto map = ColumnMap::create(nullable_int_column({1}, {1}),
nullable_int_column({10}, {0}),
+ std::move(offsets));
+ auto null_map = ColumnUInt8::create();
+ null_map->get_data().push_back(1);
+ Block block({ColumnWithTypeAndName(ColumnNullable::create(std::move(map),
std::move(null_map)),
+ make_nullable(map_type), "attrs")});
+
+ EXPECT_TRUE(validate_write_block(schema, block).ok());
+}
+
+TEST(IcebergWriteValidatorTest, RejectsRequiredMapValueNull) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(true, 1, "attrs",
+ MapType::of_required(2, 3,
std::make_unique<IntegerType>(),
+ std::make_unique<IntegerType>()),
+ std::nullopt);
+ Schema schema(std::move(fields));
+ auto key_type = std::make_shared<DataTypeInt32>();
+ auto value_type = nullable_int();
+ auto map_type = std::make_shared<DataTypeMap>(key_type, value_type);
+ auto offsets = ColumnMap::COffsets::create();
+ offsets->get_data().push_back(2);
+ auto map = ColumnMap::create(nullable_int_column({1, 2}, {0, 0}),
+ nullable_int_column({10, 20}, {0, 1}),
std::move(offsets));
+ auto null_map = ColumnUInt8::create();
+ null_map->get_data().push_back(0);
+ Block block({ColumnWithTypeAndName(ColumnNullable::create(std::move(map),
std::move(null_map)),
+ make_nullable(map_type), "attrs")});
+
+ expect_data_quality_error(validate_write_block(schema, block),
"attrs.value", "map entry 1");
+}
+
+TEST(IcebergWriteValidatorTest, AcceptsValidRequiredNestedValues) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(false, 1, "id", std::make_unique<IntegerType>(),
std::nullopt);
+ fields.emplace_back(true, 2, "items", ListType::of_required(3,
std::make_unique<IntegerType>()),
+ std::nullopt);
+ Schema schema(std::move(fields));
+ auto id_type = nullable_int();
+ auto id_column = nullable_int_column({1, 2}, {0, 0});
+ auto element_type = nullable_int();
+ auto array_type =
make_nullable(std::make_shared<DataTypeArray>(element_type));
+ auto offsets = ColumnArray::ColumnOffsets::create();
+ offsets->get_data().assign({2, 3});
+ auto array =
+ ColumnArray::create(nullable_int_column({10, 20, 30}, {0, 0, 0}),
std::move(offsets));
+ auto array_nulls = ColumnUInt8::create();
+ array_nulls->get_data().assign({0, 0});
+ Block block({
+ ColumnWithTypeAndName(std::move(id_column), id_type, "id"),
+ ColumnWithTypeAndName(ColumnNullable::create(std::move(array),
std::move(array_nulls)),
+ array_type, "items"),
+ });
+
+ EXPECT_TRUE(validate_write_block(schema, block).ok());
+}
+
+TEST(IcebergWriteValidatorTest, RejectsSchemaColumnCountMismatch) {
+ auto schema = field_schema(std::make_unique<IntegerType>());
+ auto type = nullable_int();
+ Block block({ColumnWithTypeAndName(nullable_int_column({1}, {0}), type,
"payload"),
+ ColumnWithTypeAndName(nullable_int_column({2}, {0}), type,
"extra")});
+
+ expect_invalid_block(schema, block, "pinned schema has 1 fields");
+}
+
+TEST(IcebergWriteValidatorTest, RejectsShortTopLevelColumn) {
+ std::vector<NestedField> fields;
+ fields.emplace_back(false, 1, "id", std::make_unique<IntegerType>(),
std::nullopt);
+ fields.emplace_back(false, 2, "payload", std::make_unique<IntegerType>(),
std::nullopt);
+ Schema schema(std::move(fields));
+ auto type = nullable_int();
+ Block block({ColumnWithTypeAndName(nullable_int_column({1, 2}, {0, 0}),
type, "id"),
+ ColumnWithTypeAndName(nullable_int_column({3}, {0}), type,
"payload")});
+
+ expect_invalid_block(schema, block, "column 'payload' has 1 values, but
block has 2 rows");
+}
+
+TEST(IcebergWriteValidatorTest, RejectsContainerTypeMismatches) {
+ for (auto& container : required_container_types()) {
+ SCOPED_TRACE(container->to_string());
+ auto schema = field_schema(std::move(container));
+ Block block(
+ {ColumnWithTypeAndName(nullable_int_column({1}, {0}),
nullable_int(), "payload")});
+
+ expect_invalid_block(schema, block, "does not match Doris type");
+ }
+}
+
+TEST(IcebergWriteValidatorTest, RejectsPhysicalContainerColumnMismatches) {
+ auto containers = required_container_types();
+ DataTypes types {std::make_shared<DataTypeStruct>(DataTypes
{nullable_int()}, Strings {"id"}),
+ std::make_shared<DataTypeArray>(nullable_int()),
+ std::make_shared<DataTypeMap>(nullable_int(),
nullable_int())};
+ for (size_t i = 0; i < containers.size(); ++i) {
+ SCOPED_TRACE(containers[i]->to_string());
+ auto schema = field_schema(std::move(containers[i]));
+ auto data = ColumnInt32::create();
+ data->insert_value(1);
+ Block block({ColumnWithTypeAndName(std::move(data), types[i],
"payload")});
+
+ expect_invalid_block(schema, block, "is not stored as");
+ }
+}
+
+TEST(IcebergWriteValidatorTest, RejectsStructArityMismatches) {
+ for (bool extra_type_field : {false, true}) {
+ auto containers = required_container_types();
+ auto schema = field_schema(std::move(containers[0]));
+ Columns children {nullable_int_column({1}, {0})};
+ DataTypes child_types {nullable_int()};
+ Strings child_names {"id"};
+ if (extra_type_field) {
+ child_types.push_back(nullable_int());
+ child_names.emplace_back("extra");
+ } else {
+ children.push_back(nullable_int_column({2}, {0}));
+ }
+ auto type = std::make_shared<DataTypeStruct>(child_types, child_names);
+ Block
block({ColumnWithTypeAndName(ColumnStruct::create(std::move(children)), type,
+ "payload")});
+
+ expect_invalid_block(schema, block, "has 1 schema fields");
+ }
+}
+
+TEST(IcebergWriteValidatorTest,
AcceptsOptionalStructChildrenUnderRequiredParent) {
+ std::vector<NestedField> children;
+ children.emplace_back(true, 2, "id", std::make_unique<IntegerType>(),
std::nullopt);
+ auto schema =
field_schema(std::make_unique<StructType>(std::move(children)));
+ auto type = std::make_shared<DataTypeStruct>(DataTypes {nullable_int()},
Strings {"id"});
+ Columns data {nullable_int_column({0}, {1})};
+ Block block({ColumnWithTypeAndName(ColumnStruct::create(std::move(data)),
type, "payload")});
+
+ EXPECT_TRUE(validate_write_block(schema, block).ok());
+}
+
+TEST(IcebergWriteValidatorTest, RejectsListOffsetsBeyondElements) {
+ auto schema = field_schema(ListType::of_required(2,
std::make_unique<IntegerType>()));
+ auto offsets = ColumnArray::ColumnOffsets::create();
+ offsets->get_data().push_back(1);
+ auto array = ColumnArray::create(nullable_int_column({1}, {0}),
std::move(offsets));
+ array->get_offsets()[0] = 2;
+ auto type = std::make_shared<DataTypeArray>(nullable_int());
+ Block block({ColumnWithTypeAndName(std::move(array), type, "payload")});
+
+ expect_invalid_block(schema, block, "element count 1");
+}
+
+TEST(IcebergWriteValidatorTest, RejectsDecreasingCollectionOffsets) {
+ auto schema = field_schema(ListType::of_required(2,
std::make_unique<IntegerType>()));
+ auto offsets = ColumnArray::ColumnOffsets::create();
+ offsets->get_data().assign({1, 1});
+ auto array = ColumnArray::create(nullable_int_column({1}, {0}),
std::move(offsets));
+ array->get_offsets()[1] = 0;
+ auto type = std::make_shared<DataTypeArray>(nullable_int());
+ Block block({ColumnWithTypeAndName(std::move(array), type, "payload")});
+
+ expect_invalid_block(schema, block, "invalid offsets at row 1: [1, 0]");
+}
+
+TEST(IcebergWriteValidatorTest, AcceptsNullOptionalListElements) {
+ auto schema = field_schema(ListType::of_optional(2,
std::make_unique<IntegerType>()));
+ auto offsets = ColumnArray::ColumnOffsets::create();
+ offsets->get_data().push_back(2);
+ auto array = ColumnArray::create(nullable_int_column({1, 0}, {0, 1}),
std::move(offsets));
+ auto type = std::make_shared<DataTypeArray>(nullable_int());
+ Block block({ColumnWithTypeAndName(std::move(array), type, "payload")});
+
+ EXPECT_TRUE(validate_write_block(schema, block).ok());
+}
+
+TEST(IcebergWriteValidatorTest, RejectsMapOffsetsBeyondEntries) {
+ auto schema = field_schema(MapType::of_required(2, 3,
std::make_unique<IntegerType>(),
+
std::make_unique<IntegerType>()));
+ auto offsets = ColumnMap::COffsets::create();
+ // MAP materialization reconstructs the column and checks its final
offset. Keep that
+ // invariant while an intermediate offset still exceeds the available
entries.
+ offsets->get_data().assign({1, 1});
+ auto map = ColumnMap::create(nullable_int_column({1}, {0}),
nullable_int_column({2}, {0}),
+ std::move(offsets));
+ map->get_offsets()[0] = 2;
+ auto type = std::make_shared<DataTypeMap>(nullable_int(), nullable_int());
+ Block block({ColumnWithTypeAndName(std::move(map), type, "payload")});
+
+ expect_invalid_block(schema, block, "key count 1, value count 1");
+}
+
+TEST(IcebergWriteValidatorTest, AcceptsNullOptionalMapValues) {
+ auto schema = field_schema(MapType::of_optional(2, 3,
std::make_unique<IntegerType>(),
+
std::make_unique<IntegerType>()));
+ auto offsets = ColumnMap::COffsets::create();
+ offsets->get_data().push_back(1);
+ auto map = ColumnMap::create(nullable_int_column({1}, {0}),
nullable_int_column({0}, {1}),
+ std::move(offsets));
+ auto type = std::make_shared<DataTypeMap>(nullable_int(), nullable_int());
+ Block block({ColumnWithTypeAndName(std::move(map), type, "payload")});
+
+ EXPECT_TRUE(validate_write_block(schema, block).ok());
+}
+
+TEST(IcebergWriteValidatorTest, AcceptsValidRequiredMapEntries) {
+ auto schema = field_schema(MapType::of_required(2, 3,
std::make_unique<IntegerType>(),
+
std::make_unique<IntegerType>()));
+ auto offsets = ColumnMap::COffsets::create();
+ offsets->get_data().assign({1, 2});
+ auto map = ColumnMap::create(nullable_int_column({1, 2}, {0, 0}),
+ nullable_int_column({10, 20}, {0, 0}),
std::move(offsets));
+ auto type = std::make_shared<DataTypeMap>(nullable_int(), nullable_int());
+ Block block({ColumnWithTypeAndName(std::move(map), type, "payload")});
+
+ EXPECT_TRUE(validate_write_block(schema, block).ok());
+}
+
+} // namespace doris::iceberg
diff --git a/be/test/exec/sink/writer/iceberg/viceberg_table_writer_test.cpp
b/be/test/exec/sink/writer/iceberg/viceberg_table_writer_test.cpp
index 0d70c865c7e..08822c97630 100644
--- a/be/test/exec/sink/writer/iceberg/viceberg_table_writer_test.cpp
+++ b/be/test/exec/sink/writer/iceberg/viceberg_table_writer_test.cpp
@@ -64,6 +64,75 @@ public:
};
} // namespace
+TEST(VIcebergTableWriterTest, RejectsRequiredNullBeforeWriterCreation) {
+ std::vector<iceberg::NestedField> fields;
+ fields.emplace_back(false, 1, "id",
std::make_unique<iceberg::IntegerType>(), std::nullopt);
+ auto schema = std::make_shared<iceberg::Schema>(std::move(fields));
+ TIcebergTableSink sink;
+ TDataSink data_sink;
+ data_sink.__set_iceberg_table_sink(sink);
+ VExprContextSPtrs output_exprs;
+ VIcebergTableWriter writer(data_sink, output_exprs);
+ writer._schema = schema;
+
+ auto type = make_nullable(std::make_shared<DataTypeInt32>());
+ auto data = ColumnInt32::create();
+ data->insert_value(1);
+ auto null_map = ColumnUInt8::create();
+ null_map->get_data().push_back(1);
+ Block block({ColumnWithTypeAndName(ColumnNullable::create(std::move(data),
std::move(null_map)),
+ type, "id")});
+
+ Status status = writer._write_prepared_block(block);
+
+ EXPECT_FALSE(status.ok());
+ EXPECT_NE(status.to_string().find("required field 'id'"),
std::string::npos);
+ EXPECT_TRUE(writer._partitions_to_writers.empty());
+ EXPECT_EQ(0, writer._row_count);
+}
+
+TEST(VIcebergTableWriterTest, RejectsNestedRequiredNullBeforeWriterCreation) {
+ std::vector<iceberg::NestedField> child_fields;
+ child_fields.emplace_back(false, 2, "required_metric",
std::make_unique<iceberg::IntegerType>(),
+ std::nullopt);
+ std::vector<iceberg::NestedField> fields;
+ fields.emplace_back(true, 1, "info",
+
std::make_unique<iceberg::StructType>(std::move(child_fields)),
+ std::nullopt);
+ auto schema = std::make_shared<iceberg::Schema>(std::move(fields));
+ TIcebergTableSink sink;
+ TDataSink data_sink;
+ data_sink.__set_iceberg_table_sink(sink);
+ VExprContextSPtrs output_exprs;
+ VIcebergTableWriter writer(data_sink, output_exprs);
+ writer._schema = schema;
+
+ auto child_type = make_nullable(std::make_shared<DataTypeInt32>());
+ auto child_data = ColumnInt32::create();
+ child_data->insert_value(7);
+ auto child_nulls = ColumnUInt8::create();
+ child_nulls->get_data().push_back(1);
+ Columns children {
+ ColumnNullable::create(std::move(child_data),
std::move(child_nulls)),
+ };
+ auto struct_type =
+ std::make_shared<DataTypeStruct>(DataTypes {child_type}, Strings
{"required_metric"});
+ auto parent_nulls = ColumnUInt8::create();
+ parent_nulls->get_data().push_back(0);
+ Block block({
+
ColumnWithTypeAndName(ColumnNullable::create(ColumnStruct::create(std::move(children)),
+
std::move(parent_nulls)),
+ make_nullable(struct_type), "info"),
+ });
+
+ Status status = writer._write_prepared_block(block);
+
+ EXPECT_FALSE(status.ok());
+ EXPECT_NE(status.to_string().find("required field
'info.required_metric'"), std::string::npos);
+ EXPECT_TRUE(writer._partitions_to_writers.empty());
+ EXPECT_EQ(0, writer._row_count);
+}
+
TEST(VIcebergTableWriterTest, TimestampIdentityPreservesUtcCommitAndNull) {
std::vector<iceberg::NestedField> fields;
fields.emplace_back(false, 1, "event_time",
std::make_unique<iceberg::TimestampTzType>(),
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergTransaction.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergTransaction.java
index e2291105ef2..596c5e4cb24 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergTransaction.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergTransaction.java
@@ -58,6 +58,7 @@ import org.apache.iceberg.TableMetadataParser;
import org.apache.iceberg.TableOperations;
import org.apache.iceberg.TableScan;
import org.apache.iceberg.encryption.EncryptionManager;
+import org.apache.iceberg.exceptions.CleanableFailure;
import org.apache.iceberg.expressions.Expression;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.io.CloseableIterable;
@@ -102,6 +103,7 @@ public class IcebergTransaction implements Transaction {
private String branchName;
private Long baseSnapshotId;
private boolean hasStagedUpdates;
+ private boolean commitMayHaveSucceeded;
private Map<String, List<DeleteFile>>
rewrittenDeleteFilesByReferencedDataFile = Collections.emptyMap();
// Rewrite operation support
@@ -701,11 +703,19 @@ public class IcebergTransaction implements Transaction {
if (!hasStagedUpdates) {
validatePinnedWriterMetadata();
}
+ // A REST catalog may publish metadata before its response is
lost or malformed.
+ // From this point, only an SDK CleanableFailure proves that
deletion is safe.
+ commitMayHaveSucceeded = true;
transaction.commitTransaction();
});
} catch (RuntimeException e) {
+ if (e instanceof CleanableFailure) {
+ commitMayHaveSucceeded = false;
+ }
+ cleanupReportedFiles();
throw e;
} catch (Exception e) {
+ cleanupReportedFiles();
throw new UserException("Failed to commit Iceberg transaction: " +
e.getMessage(), e);
} finally {
releaseWritableTableLease();
@@ -842,6 +852,7 @@ public class IcebergTransaction implements Transaction {
@Override
public void rollback() {
try {
+ cleanupReportedFiles();
if (isRewriteMode) {
// Clear the collected files for rewrite mode
synchronized (filesToDelete) {
@@ -852,12 +863,55 @@ public class IcebergTransaction implements Transaction {
}
LOG.info("Rewrite transaction rolled back");
}
- // For insert mode, do nothing as original implementation
} finally {
releaseWritableTableLease();
}
}
+ private void cleanupReportedFiles() {
+ List<TIcebergCommitData> pending;
+ synchronized (this) {
+ pending = new ArrayList<>(commitDataList);
+ commitDataList.clear();
+ }
+ Table rollbackTable = table;
+ if (commitMayHaveSucceeded) {
+ LOG.warn("Preserving {} reported Iceberg files because the commit
may have succeeded", pending.size());
+ return;
+ }
+ if (rollbackTable == null || pending.isEmpty()) {
+ return;
+ }
+ Set<String> paths = new HashSet<>();
+ for (TIcebergCommitData data : pending) {
+ if (data != null && data.isSetFilePath() && data.getFilePath() !=
null
+ && !data.getFilePath().isEmpty()) {
+ paths.add(data.getFilePath());
+ }
+ }
+ if (paths.isEmpty()) {
+ return;
+ }
+ try {
+ // Cleanup must finish before releasing the lease and its
generation's FileIO.
+ // If begin failed before acquiring a lease, use the retained
metadata ops' credentials.
+ ExecutionAuthenticator authenticator = writableTableLease == null
+ ? ops.getExecutionAuthenticator() :
writableAuthenticator();
+ authenticator.execute(() -> {
+ for (String path : paths) {
+ try {
+ rollbackTable.io().deleteFile(path);
+ } catch (Exception e) {
+ // Keep the original query failure; log cleanup
failures for orphan maintenance.
+ LOG.warn("Failed to delete uncommitted Iceberg file
{}: {}", path, e.getMessage());
+ }
+ }
+ });
+ } catch (Exception e) {
+ LOG.warn("Failed to clean reported Iceberg files: {}",
e.getMessage());
+ }
+ }
+
public long getUpdateCnt() {
long dataRows = 0;
long deleteRows = 0;
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/BaseExternalTableInsertExecutor.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/BaseExternalTableInsertExecutor.java
index 288bcb32f5f..b0aaadf3cbc 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/BaseExternalTableInsertExecutor.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/insert/BaseExternalTableInsertExecutor.java
@@ -172,8 +172,8 @@ public abstract class BaseExternalTableInsertExecutor
extends AbstractInsertExec
ctx.getState().setError(ErrorCode.ERR_UNKNOWN_ERROR, finalErrorMsg);
if (transactionType() == TransactionType.ICEBERG) {
- // Iceberg rollback only clears transaction-local state and
releases the generation
- // lease retained by IcebergTransaction. It must remain possible
after catalog reset,
+ // Iceberg rollback cleans reported files and releases the
generation lease using
+ // the context retained by IcebergTransaction. It must remain
possible after catalog reset,
// when the mutable catalog authenticator is intentionally
unavailable.
try {
transactionManager.rollback(txnId);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergTransactionTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergTransactionTest.java
index 0bf0ce98424..d9d8fefc93f 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergTransactionTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergTransactionTest.java
@@ -50,12 +50,16 @@ import org.apache.iceberg.TableScan;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.exceptions.CommitFailedException;
+import org.apache.iceberg.exceptions.CommitStateUnknownException;
+import org.apache.iceberg.exceptions.RESTException;
import org.apache.iceberg.expressions.Binder;
import org.apache.iceberg.expressions.Expression;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.expressions.UnboundPredicate;
import org.apache.iceberg.hadoop.HadoopCatalog;
import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.PositionOutputStream;
import org.apache.iceberg.io.WriteResult;
import org.apache.iceberg.transforms.Transform;
import org.apache.iceberg.transforms.Transforms;
@@ -64,6 +68,7 @@ import org.apache.iceberg.util.DateTimeUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.AdditionalAnswers;
import org.mockito.ArgumentMatchers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
@@ -1327,6 +1332,195 @@ public class IcebergTransactionTest {
}
}
+ @Test
+ public void testRollbackDeletesReportedFilesAndClearsCommitData() throws
Exception {
+ Table table = ops.getCatalog().loadTable(TableIdentifier.of(dbName,
tbWithoutPartition));
+ String path = table.location() + "/data/uncommitted.parquet";
+ try (PositionOutputStream stream =
table.io().newOutputFile(path).create()) {
+ stream.write(1);
+ }
+ IcebergExternalTable dorisTable =
Mockito.mock(IcebergExternalTable.class);
+ Mockito.when(dorisTable.getName()).thenReturn(tbWithoutPartition);
+ try (MockedStatic<IcebergUtils> mockedUtils =
Mockito.mockStatic(IcebergUtils.class)) {
+ mockWritableTable(mockedUtils, table);
+ IcebergTransaction txn = getTxn();
+ txn.beginInsert(dorisTable, table, Optional.empty());
+ TIcebergCommitData data = new TIcebergCommitData();
+ data.setFilePath(path);
+ txn.updateIcebergCommitData(Arrays.asList(data, data));
+
+ txn.rollback();
+
+ Assert.assertFalse(table.io().newInputFile(path).exists());
+ Assert.assertTrue(txn.getCommitDataList().isEmpty());
+ Assert.assertNull("rollback must not publish a snapshot",
table.currentSnapshot());
+ txn.rollback();
+ }
+ }
+
+ @Test
+ public void
testRollbackContinuesCleanupAfterDeleteFailureBeforeReleasingLease() throws
Exception {
+ Table table = Mockito.mock(Table.class);
+ FileIO fileIO = Mockito.mock(FileIO.class);
+ Mockito.when(table.io()).thenReturn(fileIO);
+
Mockito.when(table.newTransaction()).thenReturn(Mockito.mock(org.apache.iceberg.Transaction.class));
+ Mockito.doThrow(new RuntimeException("injected delete
failure")).when(fileIO).deleteFile("failed.parquet");
+ AtomicBoolean released = new AtomicBoolean();
+ try (MockedStatic<IcebergUtils> mockedUtils =
Mockito.mockStatic(IcebergUtils.class)) {
+ mockedUtils.when(() -> IcebergUtils.acquireWritableIcebergTable(
+ ArgumentMatchers.any(ExternalTable.class),
ArgumentMatchers.eq(ops)))
+ .thenReturn(new
IcebergExternalMetaCache.WritableTableLease(
+ table, ops, testRuntimeContext(), false, false, ()
-> {
+
Mockito.verify(fileIO).deleteFile("failed.parquet");
+ Mockito.verify(fileIO).deleteFile("other.orc");
+ released.set(true);
+ }));
+ IcebergTransaction txn = getTxn();
+ txn.beginInsert(Mockito.mock(IcebergExternalTable.class), table,
Optional.empty());
+ TIcebergCommitData failed = new TIcebergCommitData();
+ failed.setFilePath("failed.parquet");
+ TIcebergCommitData other = new TIcebergCommitData();
+ other.setFilePath("other.orc");
+ txn.updateIcebergCommitData(Arrays.asList(failed, failed, other));
+
+ txn.rollback();
+
+ Assert.assertTrue(released.get());
+ Assert.assertTrue(txn.getCommitDataList().isEmpty());
+ }
+ }
+
+ @Test
+ public void testFailedCommitCleansReportedFilesBeforeReleasingLease()
throws Exception {
+ Table table = Mockito.mock(Table.class);
+ FileIO fileIO = Mockito.mock(FileIO.class);
+ org.apache.iceberg.Transaction icebergTxn =
Mockito.mock(org.apache.iceberg.Transaction.class);
+ Mockito.when(table.io()).thenReturn(fileIO);
+ Mockito.when(table.newTransaction()).thenReturn(icebergTxn);
+ Mockito.doThrow(new CommitFailedException("injected commit
failure")).when(icebergTxn).commitTransaction();
+ AtomicBoolean released = new AtomicBoolean();
+ try (MockedStatic<IcebergUtils> mockedUtils =
Mockito.mockStatic(IcebergUtils.class)) {
+ mockedUtils.when(() -> IcebergUtils.acquireWritableIcebergTable(
+ ArgumentMatchers.any(ExternalTable.class),
ArgumentMatchers.eq(ops)))
+ .thenReturn(new
IcebergExternalMetaCache.WritableTableLease(
+ table, ops, testRuntimeContext(), false, false, ()
-> {
+
Mockito.verify(fileIO).deleteFile("uncommitted.parquet");
+ released.set(true);
+ }));
+ IcebergTransaction txn = getTxn();
+ txn.beginInsert(Mockito.mock(IcebergExternalTable.class), table,
Optional.empty());
+ TIcebergCommitData data = new TIcebergCommitData();
+ data.setFilePath("uncommitted.parquet");
+ txn.updateIcebergCommitData(Collections.singletonList(data));
+
+ Assert.assertThrows(CommitFailedException.class, txn::commit);
+
+ Assert.assertTrue(released.get());
+ Assert.assertTrue(txn.getCommitDataList().isEmpty());
+ txn.rollback();
+ Mockito.verify(fileIO).deleteFile("uncommitted.parquet");
+ }
+ }
+
+ @Test
+ public void testUnknownCommitStatePreservesPotentiallyCommittedFiles()
throws Exception {
+ Table table = Mockito.mock(Table.class);
+ FileIO fileIO = Mockito.mock(FileIO.class);
+ org.apache.iceberg.Transaction icebergTxn =
Mockito.mock(org.apache.iceberg.Transaction.class);
+ Mockito.when(table.io()).thenReturn(fileIO);
+ Mockito.when(table.newTransaction()).thenReturn(icebergTxn);
+ Mockito.doThrow(new CommitStateUnknownException(new
IOException("injected unknown commit state")))
+ .when(icebergTxn).commitTransaction();
+ try (MockedStatic<IcebergUtils> mockedUtils =
Mockito.mockStatic(IcebergUtils.class)) {
+ mockWritableTable(mockedUtils, table);
+ IcebergTransaction txn = getTxn();
+ txn.beginInsert(Mockito.mock(IcebergExternalTable.class), table,
Optional.empty());
+ TIcebergCommitData data = new TIcebergCommitData();
+ data.setFilePath("possibly-committed.parquet");
+ txn.updateIcebergCommitData(Collections.singletonList(data));
+
+ Assert.assertThrows(CommitStateUnknownException.class,
txn::commit);
+ txn.rollback();
+
+ Mockito.verify(fileIO,
Mockito.never()).deleteFile(ArgumentMatchers.anyString());
+ }
+ }
+
+ @Test
+ public void testRestResponseLossPreservesPublishedFileThroughRollback()
throws Exception {
+ assertPublishedFileSurvivesCommitFailure(new RESTException(
+ new IOException("truncated commit response"), "Failed to parse
REST commit response"));
+ }
+
+ @Test
+ public void
testOtherIndeterminateFailurePreservesPublishedFileThroughRollback() throws
Exception {
+ assertPublishedFileSurvivesCommitFailure(new
IllegalStateException("response lost after publication"));
+ }
+
+ private void assertPublishedFileSurvivesCommitFailure(RuntimeException
failure) throws Exception {
+ Table actualTable =
ops.getCatalog().loadTable(TableIdentifier.of(dbName, tbWithoutPartition));
+ String path = actualTable.location() + "/data/published.parquet";
+ try (PositionOutputStream stream =
actualTable.io().newOutputFile(path).create()) {
+ stream.write(1);
+ }
+ org.apache.iceberg.Transaction actualTransaction =
actualTable.newTransaction();
+
actualTransaction.newAppend().appendFile(DataFiles.builder(actualTable.spec())
+ .withPath(path).withFormat(FileFormat.PARQUET)
+ .withRecordCount(1).withFileSizeInBytes(1).build()).commit();
+ org.apache.iceberg.Transaction sdkTransaction =
Mockito.mock(org.apache.iceberg.Transaction.class,
+ AdditionalAnswers.delegatesTo(actualTransaction));
+ Mockito.doAnswer(invocation -> {
+ actualTransaction.commitTransaction();
+ throw failure;
+ }).when(sdkTransaction).commitTransaction();
+ Table table = Mockito.mock(Table.class,
AdditionalAnswers.delegatesTo(actualTable));
+ Mockito.when(table.newTransaction()).thenReturn(sdkTransaction);
+
+ try (MockedStatic<IcebergUtils> mockedUtils =
Mockito.mockStatic(IcebergUtils.class)) {
+ mockWritableTable(mockedUtils, table);
+ IcebergTransaction txn = getTxn();
+ txn.beginInsert(Mockito.mock(IcebergExternalTable.class), table,
Optional.empty());
+ TIcebergCommitData data = new TIcebergCommitData();
+ data.setFilePath(path);
+ txn.updateIcebergCommitData(Collections.singletonList(data));
+
+ Assert.assertSame(failure, Assert.assertThrows(failure.getClass(),
txn::commit));
+ actualTable.refresh();
+ Assert.assertNotNull("the server-side metadata commit succeeded",
actualTable.currentSnapshot());
+ Assert.assertTrue(actualTable.io().newInputFile(path).exists());
+
+ // Retain another fragment report to verify rollback consults the
publication state,
+ // rather than relying only on commit() clearing its first
pending-file inventory.
+ txn.updateIcebergCommitData(Collections.singletonList(data));
+ txn.rollback();
+
+ Assert.assertTrue("rollback must preserve files referenced by the
published snapshot",
+ actualTable.io().newInputFile(path).exists());
+ Assert.assertTrue(txn.getCommitDataList().isEmpty());
+ }
+ }
+
+ @Test
+ public void testRollbackAfterSuccessfulCommitPreservesReportedFiles()
throws Exception {
+ Table table = Mockito.mock(Table.class);
+ FileIO fileIO = Mockito.mock(FileIO.class);
+ Mockito.when(table.io()).thenReturn(fileIO);
+
Mockito.when(table.newTransaction()).thenReturn(Mockito.mock(org.apache.iceberg.Transaction.class));
+ try (MockedStatic<IcebergUtils> mockedUtils =
Mockito.mockStatic(IcebergUtils.class)) {
+ mockWritableTable(mockedUtils, table);
+ IcebergTransaction txn = getTxn();
+ txn.beginInsert(Mockito.mock(IcebergExternalTable.class), table,
Optional.empty());
+ TIcebergCommitData data = new TIcebergCommitData();
+ data.setFilePath("committed.parquet");
+ txn.updateIcebergCommitData(Collections.singletonList(data));
+
+ txn.commit();
+ txn.rollback();
+
+ Mockito.verify(fileIO,
Mockito.never()).deleteFile(ArgumentMatchers.anyString());
+ }
+ }
+
@Test
public void testRewriteAdoptsEnclosingWritableTableLease() throws
UserException {
IcebergExternalTable dorisTable =
Mockito.mock(IcebergExternalTable.class);
diff --git
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_show_nullable.groovy
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_show_nullable.groovy
index c92787a4d98..8e3164a6ce2 100644
---
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_show_nullable.groovy
+++
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_show_nullable.groovy
@@ -92,11 +92,11 @@ suite("test_iceberg_show_nullable",
"p0,external,doris,external_docker,external_
test {
sql """insert into ${tableName} values (null, 'bad', '2026-01-02
00:00:00')"""
- exception "Column 'id' is declared non-nullable but contains nulls"
+ exception "required field 'id' contains NULL"
}
test {
sql """insert into ${tableName} values (3, null, '2026-01-02
00:00:00')"""
- exception "Column 'value' is declared non-nullable but contains
nulls"
+ exception "required field 'value' contains NULL"
}
assertEquals(2L, sql("select count(*) from ${tableName}")[0][0])
diff --git
a/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_required_null_select_negative.groovy
b/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_required_null_select_negative.groovy
index 765e5c58345..cf1441369f0 100644
---
a/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_required_null_select_negative.groovy
+++
b/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_required_null_select_negative.groovy
@@ -23,13 +23,6 @@ suite("test_iceberg_write_required_null_select_negative",
return
}
- // This opt-in switch isolates a write that can publish an unreadable
Iceberg data file.
- String knownBugTestEnabled =
context.config.otherConfigs.get("enableIcebergKnownBugTest")
- if (knownBugTestEnabled == null ||
!knownBugTestEnabled.equalsIgnoreCase("true")) {
- logger.info("skip isolated Iceberg known-bug regression")
- return
- }
-
String restPort = context.config.otherConfigs.get("iceberg_rest_uri_port")
String minioPort = context.config.otherConfigs.get("iceberg_minio_port")
String externalEnvIp = context.config.otherConfigs.get("externalEnvIp")
@@ -71,33 +64,48 @@ suite("test_iceberg_write_required_null_select_negative",
sql """create database ${dbName}"""
sql """use ${dbName}"""
- sql """
- create table required_select (
- id int not null,
- required_text string not null
- )
- partition by list (bucket(8, id)) ()
- properties ("format-version" = "2")
- """
-
- long snapshotsBefore = (sql """select count(*) from
required_select\$snapshots""")[0][0] as long
- long filesBefore = (sql """select count(*) from
required_select\$files""")[0][0] as long
- long rowsBefore = (sql """select count(*) from required_select""")[0][0]
as long
-
- // W07-S02: The metadata and row baselines distinguish an early rejection
- // from a late failure that has already published a snapshot or data file.
- test {
+ for (String fileFormat : ["orc", "parquet"]) {
+ String tableName = "required_select_${fileFormat}"
sql """
- insert into required_select
- select id, required_text
- from internal.${internalDb}.nullable_source
+ create table ${tableName} (
+ id int not null,
+ required_text string not null
+ )
+ partition by list (bucket(8, id)) ()
+ properties (
+ "format-version" = "2",
+ "write.format.default" = "${fileFormat}"
+ )
"""
- exception "null"
+
+ long snapshotsBefore = (sql """
+ select count(*) from ${tableName}\$snapshots
+ """)[0][0] as long
+ long filesBefore = (sql """
+ select count(*) from ${tableName}\$files
+ """)[0][0] as long
+ long rowsBefore = (sql """
+ select count(*) from ${tableName}
+ """)[0][0] as long
+
+ // W07-S02: The metadata and row baselines distinguish an early
rejection
+ // from a late failure that has already published a snapshot or data
file.
+ test {
+ sql """
+ insert into ${tableName}
+ select id, required_text
+ from internal.${internalDb}.nullable_source
+ """
+ exception "required field 'required_text' contains NULL"
+ }
+ assertEquals(snapshotsBefore, (sql """
+ select count(*) from ${tableName}\$snapshots
+ """)[0][0] as long)
+ assertEquals(filesBefore, (sql """
+ select count(*) from ${tableName}\$files
+ """)[0][0] as long)
+ assertEquals(rowsBefore, (sql """
+ select count(*) from ${tableName}
+ """)[0][0] as long)
}
- assertEquals(snapshotsBefore,
- (sql """select count(*) from required_select\$snapshots""")[0][0]
as long)
- assertEquals(filesBefore,
- (sql """select count(*) from required_select\$files""")[0][0] as
long)
- assertEquals(rowsBefore,
- (sql """select count(*) from required_select""")[0][0] as long)
}
diff --git
a/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_required_null_values_negative.groovy
b/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_required_null_values_negative.groovy
index 86c433dc634..2842e3d8f63 100644
---
a/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_required_null_values_negative.groovy
+++
b/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_required_null_values_negative.groovy
@@ -23,13 +23,6 @@ suite("test_iceberg_write_required_null_values_negative",
return
}
- // This opt-in switch isolates a write that can publish an unreadable
Iceberg data file.
- String knownBugTestEnabled =
context.config.otherConfigs.get("enableIcebergKnownBugTest")
- if (knownBugTestEnabled == null ||
!knownBugTestEnabled.equalsIgnoreCase("true")) {
- logger.info("skip isolated Iceberg known-bug regression")
- return
- }
-
String restPort = context.config.otherConfigs.get("iceberg_rest_uri_port")
String minioPort = context.config.otherConfigs.get("iceberg_minio_port")
String externalEnvIp = context.config.otherConfigs.get("externalEnvIp")
@@ -53,29 +46,151 @@ suite("test_iceberg_write_required_null_values_negative",
sql """create database ${dbName}"""
sql """use ${dbName}"""
- sql """
- create table required_values (
- id int not null,
- required_text string not null
- )
- partition by list (bucket(8, id)) ()
- properties ("format-version" = "2")
- """
+ for (String fileFormat : ["orc", "parquet"]) {
+ String tableName = "required_values_${fileFormat}"
+ sql """
+ create table ${tableName} (
+ id int not null,
+ required_text string not null
+ )
+ partition by list (bucket(8, id)) ()
+ properties (
+ "format-version" = "2",
+ "write.format.default" = "${fileFormat}"
+ )
+ """
+
+ long snapshotsBefore = (sql """
+ select count(*) from ${tableName}\$snapshots
+ """)[0][0] as long
+ long filesBefore = (sql """
+ select count(*) from ${tableName}\$files
+ """)[0][0] as long
+ long rowsBefore = (sql """
+ select count(*) from ${tableName}
+ """)[0][0] as long
+
+ // W07-S01: A thrown NULL error is insufficient proof of atomicity; all
+ // visible and metadata state must remain at the pre-statement
baseline.
+ test {
+ sql """insert into ${tableName} values (1, null)"""
+ exception "required field 'required_text' contains NULL"
+ }
+ assertEquals(snapshotsBefore, (sql """
+ select count(*) from ${tableName}\$snapshots
+ """)[0][0] as long)
+ assertEquals(filesBefore, (sql """
+ select count(*) from ${tableName}\$files
+ """)[0][0] as long)
+ assertEquals(rowsBefore, (sql """
+ select count(*) from ${tableName}
+ """)[0][0] as long)
+ }
+
+ // Spark can express required nested fields that Doris DDL cannot declare
directly.
+ for (String fileFormat : ["orc", "parquet"]) {
+ String tableName = "required_nested_${fileFormat}"
+ spark_iceberg """
+ drop table if exists demo.${dbName}.${tableName}
+ """
+ spark_iceberg """
+ create table demo.${dbName}.${tableName} (
+ id int,
+ info struct<required_metric: int not null, required_label:
string not null>
+ )
+ using iceberg
+ tblproperties (
+ 'format-version' = '2',
+ 'write.format.default' = '${fileFormat}'
+ )
+ """
+ spark_iceberg """
+ insert into demo.${dbName}.${tableName}
+ values (1, named_struct('required_metric', 10, 'required_label',
'old-label'))
+ """
+ sql """refresh table ${tableName}"""
+
+ // The STRUCT itself is optional. A NULL parent masks its required
children and is a valid row.
+ sql """insert into ${tableName} values (2, null)"""
+ sql """refresh table ${tableName}"""
+
+ long snapshotsBefore = (sql """
+ select count(*) from ${tableName}\$snapshots
+ """)[0][0] as long
+ long filesBefore = (sql """
+ select count(*) from ${tableName}\$files
+ """)[0][0] as long
+ long rowsBefore = (sql """
+ select count(*) from ${tableName}
+ """)[0][0] as long
+
+ test {
+ sql """
+ insert into ${tableName}
+ values (
+ 3,
+ named_struct(
+ 'required_metric', cast(null as int),
+ 'required_label', 'new-label'
+ )
+ )
+ """
+ // Current FE versions may reject the nullable-to-required cast
during planning; later
+ // versions may let the block reach BE. Both paths must identify
the required child.
+ exception "required_metric"
+ }
+ assertEquals(snapshotsBefore, (sql """
+ select count(*) from ${tableName}\$snapshots
+ """)[0][0] as long)
+ assertEquals(filesBefore, (sql """
+ select count(*) from ${tableName}\$files
+ """)[0][0] as long)
+ assertEquals(rowsBefore, (sql """
+ select count(*) from ${tableName}
+ """)[0][0] as long)
+ }
+
+ // Iceberg MAP keys are always required, including when the MAP parent is
optional.
+ for (String fileFormat : ["orc", "parquet"]) {
+ String tableName = "required_map_key_${fileFormat}"
+ sql """
+ create table ${tableName} (
+ id int not null,
+ attrs map<int, int>
+ )
+ partition by list (bucket(8, id)) ()
+ properties (
+ "format-version" = "2",
+ "write.format.default" = "${fileFormat}"
+ )
+ """
+
+ // A NULL MAP parent masks all entries, so it must remain writable.
+ sql """insert into ${tableName} values (1, null)"""
+ sql """refresh table ${tableName}"""
- long snapshotsBefore = (sql """select count(*) from
required_values\$snapshots""")[0][0] as long
- long filesBefore = (sql """select count(*) from
required_values\$files""")[0][0] as long
- long rowsBefore = (sql """select count(*) from required_values""")[0][0]
as long
+ long snapshotsBefore = (sql """
+ select count(*) from ${tableName}\$snapshots
+ """)[0][0] as long
+ long filesBefore = (sql """
+ select count(*) from ${tableName}\$files
+ """)[0][0] as long
+ long rowsBefore = (sql """
+ select count(*) from ${tableName}
+ """)[0][0] as long
- // W07-S01: A thrown NULL error is insufficient proof of atomicity; all
- // visible and metadata state must remain at the pre-statement baseline.
- test {
- sql """insert into required_values values (1, null)"""
- exception "null"
+ test {
+ sql """insert into ${tableName} values (2, map(cast(null as int),
2))"""
+ exception "map key 'attrs.key' contains NULL"
+ }
+ assertEquals(snapshotsBefore, (sql """
+ select count(*) from ${tableName}\$snapshots
+ """)[0][0] as long)
+ assertEquals(filesBefore, (sql """
+ select count(*) from ${tableName}\$files
+ """)[0][0] as long)
+ assertEquals(rowsBefore, (sql """
+ select count(*) from ${tableName}
+ """)[0][0] as long)
}
- assertEquals(snapshotsBefore,
- (sql """select count(*) from required_values\$snapshots""")[0][0]
as long)
- assertEquals(filesBefore,
- (sql """select count(*) from required_values\$files""")[0][0] as
long)
- assertEquals(rowsBefore,
- (sql """select count(*) from required_values""")[0][0] as long)
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]