From 5980c3731ef1033dd734b1ff4ffbfda74e01426d Mon Sep 17 00:00:00 2001 From: wirybeaver Date: Thu, 26 Nov 2026 13:27:08 -0800 Subject: [PATCH 1/2] feat(data): write position deletes from the original scan tasks --- src/iceberg/CMakeLists.txt | 3 + src/iceberg/action/CMakeLists.txt | 18 ++ src/iceberg/action/position_delete_action.cc | 55 ++++ .../action/position_delete_action_internal.h | 37 +++ src/iceberg/arrow/arrow_io.cc | 8 +- .../data/output_file_cleanup_internal.h | 56 ++++ src/iceberg/data/position_deletes.cc | 170 +++++++++++ src/iceberg/data/position_deletes_internal.h | 46 +++ src/iceberg/file_io.h | 3 + src/iceberg/row/partition_values.cc | 51 +--- src/iceberg/test/CMakeLists.txt | 1 + src/iceberg/test/arrow_io_test.cc | 10 +- .../test/position_delete_update_test.cc | 287 ++++++++++++++++++ src/iceberg/test/std_io.h | 8 +- src/iceberg/test/struct_like_test.cc | 5 +- 15 files changed, 697 insertions(+), 61 deletions(-) create mode 100644 src/iceberg/action/CMakeLists.txt create mode 100644 src/iceberg/action/position_delete_action.cc create mode 100644 src/iceberg/action/position_delete_action_internal.h create mode 100644 src/iceberg/data/output_file_cleanup_internal.h create mode 100644 src/iceberg/data/position_deletes.cc create mode 100644 src/iceberg/data/position_deletes_internal.h create mode 100644 src/iceberg/test/position_delete_update_test.cc diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index f9604e2575..c4dce273f2 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -257,6 +257,7 @@ if(MSVC_TOOLCHAIN) endif() set(ICEBERG_DATA_SOURCES + action/position_delete_action.cc data/arrow_batch_sizer.cc data/data_writer.cc data/delete_filter.cc @@ -264,6 +265,7 @@ set(ICEBERG_DATA_SOURCES data/equality_delete_writer.cc data/file_scan_task_reader.cc data/parallel_scan_reader.cc + data/position_deletes.cc data/position_delete_writer.cc data/writer.cc) @@ -306,6 +308,7 @@ iceberg_install_all_headers(iceberg) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/version.h" DESTINATION "${ICEBERG_INSTALL_INCLUDEDIR}/iceberg") +add_subdirectory(action) add_subdirectory(catalog) add_subdirectory(compat) add_subdirectory(data) diff --git a/src/iceberg/action/CMakeLists.txt b/src/iceberg/action/CMakeLists.txt new file mode 100644 index 0000000000..1ac6ab7245 --- /dev/null +++ b/src/iceberg/action/CMakeLists.txt @@ -0,0 +1,18 @@ +# 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. + +iceberg_install_all_headers(iceberg/action) diff --git a/src/iceberg/action/position_delete_action.cc b/src/iceberg/action/position_delete_action.cc new file mode 100644 index 0000000000..d9ffaaaa5a --- /dev/null +++ b/src/iceberg/action/position_delete_action.cc @@ -0,0 +1,55 @@ +/* + * 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 +#include +#include + +#include "iceberg/action/position_delete_action_internal.h" +#include "iceberg/data/output_file_cleanup_internal.h" +#include "iceberg/table.h" +#include "iceberg/update/row_delta.h" + +namespace iceberg::internal { + +Status CommitPositionDeletes(const Table& table, RowDelta& delta, + int64_t scan_snapshot_id, + const std::shared_ptr& scan_io, + std::vector files) { + std::set outputs; + auto written = WritePositionDeletes(table, scan_io, std::move(files), outputs); + if (!written) { + return FailWithOutputCleanup(std::move(written.error()), *table.io(), outputs); + } + if (written->data_files.empty()) return {}; + + delta.ValidateFromSnapshot(scan_snapshot_id) + .ValidateDataFilesExist(written->referenced_data_files) + .ValidateDeletedFiles(); + for (const auto& file : written->data_files) delta.AddDeletes(file); + for (const auto& file : written->rewritten_delete_files) delta.RemoveDeletes(file); + + auto status = delta.Commit(); + if (!status && status.error().kind != ErrorKind::kCommitStateUnknown) { + return FailWithOutputCleanup(std::move(status.error()), *table.io(), outputs); + } + return status; +} + +} // namespace iceberg::internal diff --git a/src/iceberg/action/position_delete_action_internal.h b/src/iceberg/action/position_delete_action_internal.h new file mode 100644 index 0000000000..281009e8d6 --- /dev/null +++ b/src/iceberg/action/position_delete_action_internal.h @@ -0,0 +1,37 @@ +/* + * 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 +#include +#include + +#include "iceberg/data/position_deletes_internal.h" + +namespace iceberg::internal { + +// Write positions from the original scan and commit them through a fresh RowDelta. +// The caller may configure conflict detection on the delta before invoking the action. +ICEBERG_DATA_EXPORT Status CommitPositionDeletes(const Table& table, RowDelta& delta, + int64_t scan_snapshot_id, + const std::shared_ptr& scan_io, + std::vector files); + +} // namespace iceberg::internal diff --git a/src/iceberg/arrow/arrow_io.cc b/src/iceberg/arrow/arrow_io.cc index 998f8c5ce8..7393ed88c0 100644 --- a/src/iceberg/arrow/arrow_io.cc +++ b/src/iceberg/arrow/arrow_io.cc @@ -18,6 +18,7 @@ */ #include +#include #include #include #include @@ -30,6 +31,7 @@ #include #include #include +#include #include #include "iceberg/arrow/arrow_io_internal.h" @@ -591,7 +593,11 @@ Result> ArrowFileSystemFileIO::NewOutputFile( /// \brief Delete a file at the given location. Status ArrowFileSystemFileIO::DeleteFile(const std::string& file_location) { ICEBERG_ASSIGN_OR_RAISE(auto path, ResolvePath(file_location)); - ICEBERG_ARROW_RETURN_NOT_OK(arrow_fs_->DeleteFile(path)); + auto status = arrow_fs_->DeleteFile(path); + if (::arrow::internal::ErrnoFromStatus(status) == ENOENT) { + return {}; + } + ICEBERG_ARROW_RETURN_NOT_OK(status); return {}; } diff --git a/src/iceberg/data/output_file_cleanup_internal.h b/src/iceberg/data/output_file_cleanup_internal.h new file mode 100644 index 0000000000..e1c0db16f0 --- /dev/null +++ b/src/iceberg/data/output_file_cleanup_internal.h @@ -0,0 +1,56 @@ +/* + * 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 +#include +#include + +#include "iceberg/file_io.h" +#include "iceberg/result.h" + +namespace iceberg::internal { + +// Try every owned output, keeping failed paths for a subsequent cleanup attempt. +inline Status CleanupOutputFiles(FileIO& io, std::set& paths) { + Status first_error; + for (auto it = paths.begin(); it != paths.end();) { + auto status = io.DeleteFile(*it); + if (status.has_value()) { + it = paths.erase(it); + } else { + if (first_error.has_value()) first_error = std::move(status); + ++it; + } + } + return first_error; +} + +// Preserve the operation's error kind while reporting a cleanup failure, if any. +inline Status FailWithOutputCleanup(Error error, FileIO& io, + std::set& paths) { + auto cleanup = CleanupOutputFiles(io, paths); + if (!cleanup.has_value()) { + error.message += "; output cleanup failed: " + cleanup.error().message; + } + return iceberg::unexpected(std::move(error)); +} + +} // namespace iceberg::internal diff --git a/src/iceberg/data/position_deletes.cc b/src/iceberg/data/position_deletes.cc new file mode 100644 index 0000000000..0b6945e4d2 --- /dev/null +++ b/src/iceberg/data/position_deletes.cc @@ -0,0 +1,170 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iceberg/data/delete_loader.h" +#include "iceberg/data/position_delete_writer.h" +#include "iceberg/data/position_deletes_internal.h" +#include "iceberg/deletes/dv_writer.h" +#include "iceberg/file_format.h" +#include "iceberg/file_io.h" +#include "iceberg/location_provider.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/table.h" +#include "iceberg/table_metadata.h" +#include "iceberg/table_properties.h" +#include "iceberg/table_scan.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/uuid.h" + +namespace iceberg::internal { +namespace { + +Result WriteParquetDeletes(const Table& table, + std::vector& files, + std::set& output_paths) { + ICEBERG_ASSIGN_OR_RAISE(auto location_provider, table.location_provider()); + ICEBERG_ASSIGN_OR_RAISE(auto schema, table.schema()); + + DeleteWriteResult result; + result.data_files.reserve(files.size()); + result.referenced_data_files.reserve(files.size()); + auto properties = table.properties().configs(); + properties[TableProperties::kParquetCompression.key()] = + table.properties().Get(TableProperties::kDeleteParquetCompression); + properties[TableProperties::kParquetCompressionLevel.key()] = + table.properties().Get(TableProperties::kDeleteParquetCompressionLevel); + const auto write_uuid = Uuid::GenerateV7().ToString(); + size_t file_number = 0; + + for (auto& [task, positions] : files) { + const auto& data_file = *task->data_file(); + const auto& path = data_file.file_path; + std::ranges::sort(positions); + + ICEBERG_ASSIGN_OR_RAISE(auto spec, table.metadata()->PartitionSpecById( + data_file.partition_spec_id.value())); + const auto filename = + std::format("position-deletes-{}-{}.parquet", write_uuid, file_number++); + auto output_path = location_provider->NewDataLocation(filename); + output_paths.insert(output_path); + + ICEBERG_ASSIGN_OR_RAISE(auto writer, + PositionDeleteWriter::Make(PositionDeleteWriterOptions{ + .path = output_path, + .schema = schema, + .spec = spec, + .partition = data_file.partition, + .format = FileFormatType::kParquet, + .io = table.io(), + .properties = properties, + })); + for (int64_t pos : positions) { + ICEBERG_RETURN_UNEXPECTED(writer->WriteDelete(path, pos)); + } + ICEBERG_RETURN_UNEXPECTED(writer->Close()); + ICEBERG_ASSIGN_OR_RAISE(auto metadata, writer->Metadata()); + result.data_files.insert(result.data_files.end(), + std::make_move_iterator(metadata.data_files.begin()), + std::make_move_iterator(metadata.data_files.end())); + result.referenced_data_files.push_back(path); + } + return result; +} + +Result WriteDeletionVectors( + const Table& table, const std::shared_ptr& scan_io, + const std::vector& files, std::set& output_paths) { + ICEBERG_ASSIGN_OR_RAISE(auto locations, table.location_provider()); + auto path = locations->NewDataLocation( + std::format("position-deletes-{}.puffin", Uuid::GenerateV7().ToString())); + output_paths.insert(path); + std::unordered_map>> previous; + for (const auto& file : files) { + for (const auto& entry : file.task->delete_files()) { + if (entry->content == DataFile::Content::kPositionDeletes) { + previous[file.task->data_file()->file_path].push_back(entry); + } + } + } + DeleteLoader loader(scan_io); + ICEBERG_ASSIGN_OR_RAISE( + auto writer, + DVWriter::Make({.path = path, + .io = table.io(), + .load_previous_deletes = [&](std::string_view target) + -> Result> { + auto it = previous.find(target); + if (it == previous.end()) return std::nullopt; + ICEBERG_ASSIGN_OR_RAISE( + auto index, loader.LoadPositionDeletes(it->second, target)); + return std::optional(std::move(index)); + }})); + for (const auto& [task, positions] : files) { + const auto& file = *task->data_file(); + ICEBERG_ASSIGN_OR_RAISE( + auto spec, table.metadata()->PartitionSpecById(file.partition_spec_id.value())); + for (int64_t pos : positions) { + ICEBERG_RETURN_UNEXPECTED( + writer->Delete(file.file_path, pos, spec, file.partition)); + } + } + ICEBERG_RETURN_UNEXPECTED(writer->Close()); + return writer->Metadata(); +} + +} // namespace + +Result WritePositionDeletes(const Table& table, + const std::shared_ptr& scan_io, + std::vector files, + std::set& output_paths) { + const auto version = table.metadata()->format_version; + ICEBERG_PRECHECK(version >= 2, + "Position deletes require table format version 2 or later"); + std::erase_if(files, [](const auto& file) { return file.positions.empty(); }); + if (files.empty()) return DeleteWriteResult{}; + for (const auto& [task, positions] : files) { + const auto& file = *task->data_file(); + ICEBERG_PRECHECK(file.partition_spec_id.has_value(), + "Missing partition spec ID for {}", file.file_path); + for (int64_t pos : positions) { + ICEBERG_PRECHECK(pos >= 0 && pos < file.record_count, + "Invalid position {} for {} ({} rows)", pos, file.file_path, + file.record_count); + } + } + return version >= 3 ? WriteDeletionVectors(table, scan_io, files, output_paths) + : WriteParquetDeletes(table, files, output_paths); +} + +} // namespace iceberg::internal diff --git a/src/iceberg/data/position_deletes_internal.h b/src/iceberg/data/position_deletes_internal.h new file mode 100644 index 0000000000..d11dd2fa5d --- /dev/null +++ b/src/iceberg/data/position_deletes_internal.h @@ -0,0 +1,46 @@ +/* + * 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 +#include +#include +#include +#include + +#include "iceberg/deletes/dv_writer.h" +#include "iceberg/iceberg_data_export.h" + +namespace iceberg::internal { + +// Group absolute row positions by data file using a task from the original scan. +struct FilePositionDeletes { + std::shared_ptr task; + std::vector positions; +}; + +// Write one group per target file. Read previous deletes with the planned scan's +// FileIO and write new outputs with the table's FileIO. The caller owns output_paths +// until commit and validates its RowDelta against the snapshot used for planning. +ICEBERG_DATA_EXPORT Result WritePositionDeletes( + const Table& table, const std::shared_ptr& scan_io, + std::vector files, std::set& output_paths); + +} // namespace iceberg::internal diff --git a/src/iceberg/file_io.h b/src/iceberg/file_io.h index 79faaacbb8..b7caa4c1d6 100644 --- a/src/iceberg/file_io.h +++ b/src/iceberg/file_io.h @@ -164,6 +164,9 @@ class ICEBERG_EXPORT FileIO { /// \brief Delete a file at the given location. /// + /// Deletion is idempotent: implementations must return success when the file does + /// not exist. + /// /// \param file_location The location of the file to delete. /// \return Status indicating success, or an error if the delete failed. virtual Status DeleteFile(const std::string& /*file_location*/) { diff --git a/src/iceberg/row/partition_values.cc b/src/iceberg/row/partition_values.cc index edf55a7725..63d47af766 100644 --- a/src/iceberg/row/partition_values.cc +++ b/src/iceberg/row/partition_values.cc @@ -19,10 +19,6 @@ #include "iceberg/row/partition_values.h" -#include - -#include "iceberg/util/uuid.h" - namespace iceberg { PartitionValues& PartitionValues::operator=(const PartitionValues& other) { @@ -43,52 +39,7 @@ Result PartitionValues::GetField(size_t pos) const { values_.size()); } - const auto& literal = values_[pos]; - - // Handle null values - if (literal.IsNull()) { - return Scalar{std::monostate{}}; - } - - // Convert Literal to Scalar based on type - switch (literal.type()->type_id()) { - case TypeId::kBoolean: - return Scalar{std::get(literal.value())}; - case TypeId::kInt: - case TypeId::kDate: - return Scalar{std::get(literal.value())}; - case TypeId::kLong: - case TypeId::kTime: - case TypeId::kTimestamp: - case TypeId::kTimestampTz: - case TypeId::kTimestampNs: - case TypeId::kTimestampTzNs: - return Scalar{std::get(literal.value())}; - case TypeId::kFloat: - return Scalar{std::get(literal.value())}; - case TypeId::kDouble: - return Scalar{std::get(literal.value())}; - case TypeId::kString: { - const auto& str = std::get(literal.value()); - return Scalar{std::string_view(str)}; - } - case TypeId::kBinary: - case TypeId::kFixed: { - const auto& bytes = std::get>(literal.value()); - return Scalar{ - std::string_view(reinterpret_cast(bytes.data()), bytes.size())}; - } - case TypeId::kUuid: { - const auto bytes = std::get(literal.value()).bytes(); - return Scalar{ - std::string_view(reinterpret_cast(bytes.data()), bytes.size())}; - } - case TypeId::kDecimal: - return Scalar{std::get(literal.value())}; - default: - return NotSupported("Cannot convert literal of type {} to Scalar", - literal.type()->ToString()); - } + return LiteralToScalar(values_[pos]); } Result> PartitionValues::ValueAt(size_t pos) const { diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 125ba128a3..7dbee50721 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -345,6 +345,7 @@ if(ICEBERG_BUILD_BUNDLE) delete_loader_test.cc dv_writer_test.cc file_scan_task_reader_test.cc + position_delete_update_test.cc literal_util_test.cc) endif() diff --git a/src/iceberg/test/arrow_io_test.cc b/src/iceberg/test/arrow_io_test.cc index 7bc9ebba53..6b3f6e4dd4 100644 --- a/src/iceberg/test/arrow_io_test.cc +++ b/src/iceberg/test/arrow_io_test.cc @@ -364,8 +364,7 @@ TEST_F(LocalFileIOTest, DeleteFile) { EXPECT_THAT(del_res, IsOk()); del_res = file_io_->DeleteFile(temp_filepath_); - EXPECT_THAT(del_res, IsError(ErrorKind::kIOError)); - EXPECT_THAT(del_res, HasErrorMessage("Cannot delete file")); + EXPECT_THAT(del_res, IsOk()); } TEST_F(LocalFileIOTest, DeleteFiles) { @@ -414,6 +413,13 @@ TEST_F(LocalFileIOTest, StdReadFullyReadsFromAbsolutePosition) { VerifyReadFullyReadsFromAbsolutePosition(file_io, temp_filepath_)); } +TEST_F(LocalFileIOTest, StdDeleteFileIsIdempotent) { + auto file_io = std::make_shared(); + ASSERT_THAT(file_io->WriteFile(temp_filepath_, "abc"), IsOk()); + EXPECT_THAT(file_io->DeleteFile(temp_filepath_), IsOk()); + EXPECT_THAT(file_io->DeleteFile(temp_filepath_), IsOk()); +} + TEST_F(LocalFileIOTest, StdReadKeepsPositionAvailableAtEof) { auto file_io = std::make_shared(); ASSERT_THAT(file_io->WriteFile(temp_filepath_, "abc"), IsOk()); diff --git a/src/iceberg/test/position_delete_update_test.cc b/src/iceberg/test/position_delete_update_test.cc new file mode 100644 index 0000000000..32d0727b36 --- /dev/null +++ b/src/iceberg/test/position_delete_update_test.cc @@ -0,0 +1,287 @@ +/* + * 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 +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "iceberg/action/position_delete_action_internal.h" +#include "iceberg/arrow/arrow_io_internal.h" +#include "iceberg/avro/avro_register.h" +#include "iceberg/data/data_writer.h" +#include "iceberg/data/file_scan_task_reader.h" +#include "iceberg/data_table_scan.h" +#include "iceberg/file_reader.h" +#include "iceberg/metadata_columns.h" +#include "iceberg/parquet/parquet_register.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/schema_internal.h" +#include "iceberg/table.h" +#include "iceberg/table_metadata.h" +#include "iceberg/table_properties.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/mock_catalog.h" +#include "iceberg/test/update_test_base.h" +#include "iceberg/update/delete_files.h" +#include "iceberg/update/fast_append.h" +#include "iceberg/update/row_delta.h" +#include "iceberg/update/update_partition_spec.h" +#include "iceberg/update/update_properties.h" + +namespace iceberg { +namespace { + +class ScanFileIO : public FileIO { + public: + MOCK_METHOD(Result>, NewInputFile, (std::string), + (override)); +}; + +class PositionDeleteV3Test : public MinimalUpdateTestBase { + protected: + static void SetUpTestSuite() { + avro::RegisterAll(); + parquet::RegisterAll(); + } + + int8_t format_version() const override { return 3; } + virtual bool unpartitioned() const { return false; } + + void SetUp() override { + MinimalUpdateTestBase::SetUp(); + ICEBERG_UNWRAP_OR_FAIL(auto properties, table_->NewUpdateProperties()); + properties->Set(TableProperties::kDeleteParquetCompression.key(), "uncompressed"); + ASSERT_THAT(properties->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + if (unpartitioned()) { + ICEBERG_UNWRAP_OR_FAIL(auto evolution, table_->NewUpdatePartitionSpec()); + evolution->RemoveField("x"); + ASSERT_THAT(evolution->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + } + ICEBERG_UNWRAP_OR_FAIL(auto schema, table_->schema()); + ICEBERG_UNWRAP_OR_FAIL(auto spec, table_->spec()); + ICEBERG_UNWRAP_OR_FAIL( + auto writer, + DataWriter::Make({ + .path = table_location_ + "/data/file.parquet", + .schema = schema, + .spec = spec, + .partition = + unpartitioned() ? PartitionValues{} : PartitionValues(Literal::Long(10)), + .format = FileFormatType::kParquet, + .io = file_io_, + .properties = {{"write.parquet.compression-codec", "uncompressed"}}, + })); + ArrowSchema c_schema{}; + ASSERT_THAT(ToArrowSchema(*schema, &c_schema), IsOk()); + auto type = ::arrow::ImportType(&c_schema).ValueOrDie(); + auto array = ::arrow::json::ArrayFromJSONString( + type, "[[10,0,0],[10,1,10],[10,2,20],[10,3,30],[10,4,40]]") + .ValueOrDie(); + ArrowArray c_array{}; + ASSERT_TRUE(::arrow::ExportArray(*array, &c_array).ok()); + ASSERT_THAT(writer->Write(&c_array), IsOk()); + ASSERT_THAT(writer->Close(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto result, writer->Metadata()); + data_file_ = result.data_files.front(); + ICEBERG_UNWRAP_OR_FAIL(auto append, table_->NewFastAppend()); + append->AppendFile(data_file_); + ASSERT_THAT(append->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + } + + Status DeletePositions(std::vector positions, + std::shared_ptr scan_io = nullptr) { + const auto snapshot_id = table_->metadata()->current_snapshot_id; + ICEBERG_ASSIGN_OR_RAISE(auto builder, table_->NewScan()); + builder->UseSnapshot(snapshot_id); + ICEBERG_ASSIGN_OR_RAISE(auto scan, builder->Build()); + ICEBERG_ASSIGN_OR_RAISE(auto tasks, scan->PlanFiles()); + ICEBERG_ASSIGN_OR_RAISE(auto delta, table_->NewRowDelta()); + return internal::CommitPositionDeletes(*table_, *delta, snapshot_id, + scan_io ? scan_io : scan->io(), + {{tasks.at(0), std::move(positions)}}); + } + + std::vector> Tasks() { + ICEBERG_THROW_NOT_OK(table_->Refresh()); + auto builder = table_->NewScan().value(); + return builder->Build().value()->PlanFiles().value(); + } + + std::vector ReadRows() { + table_ = catalog_->LoadTable(table_ident_).value(); + auto tasks = Tasks(); + auto schema = table_->schema().value(); + auto reader = FileScanTaskReader::Make({ + .io = file_io_, + .table_schema = schema, + .schemas = table_->metadata()->schemas, + .projected_schema = schema, + }) + .value(); + auto stream = reader->Open(*tasks.at(0)).value(); + auto batches = ::arrow::ImportRecordBatchReader(&stream).ValueOrDie(); + std::vector rows; + while (auto batch = batches->Next().ValueOrDie()) { + const auto& values = static_cast(*batch->column(1)); + for (int64_t i = 0; i < values.length(); ++i) rows.push_back(values.Value(i)); + } + return rows; + } + + std::shared_ptr data_file_; +}; + +class PositionDeleteUpdateTest : public PositionDeleteV3Test { + protected: + int8_t format_version() const override { return 2; } +}; + +TEST_F(PositionDeleteUpdateTest, WritesSortedParquetDeletes) { + ASSERT_THAT(DeletePositions({3, 1}), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 2, 4)); + const auto old_delete = Tasks().at(0)->delete_files().at(0); + ASSERT_EQ(old_delete->file_format, FileFormatType::kParquet); + auto projection = std::make_shared(std::vector{ + MetadataColumns::kDeleteFilePath, MetadataColumns::kDeleteFilePos}); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, + ReaderFactoryRegistry::Open( + FileFormatType::kParquet, + {.path = old_delete->file_path, .io = file_io_, .projection = projection})); + ICEBERG_UNWRAP_OR_FAIL(auto batch, reader->Next()); + ASSERT_TRUE(batch.has_value()); + ArrowSchema schema{}; + ASSERT_THAT(ToArrowSchema(*projection, &schema), IsOk()); + auto rows = ::arrow::ImportArray(&*batch, ::arrow::ImportType(&schema).ValueOrDie()) + .ValueOrDie(); + const auto& positions = static_cast( + *static_cast(*rows).field(1)); + ASSERT_EQ(positions.length(), 2); + EXPECT_EQ(positions.Value(0), 1); + EXPECT_EQ(positions.Value(1), 3); +} + +TEST_F(PositionDeleteUpdateTest, UpgradeMergesPreviousParquetDeletes) { + ASSERT_THAT(DeletePositions({3, 1}), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto properties, table_->NewUpdateProperties()); + properties->Set(TableProperties::kFormatVersion.key(), "3"); + ASSERT_THAT(properties->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ASSERT_THAT(DeletePositions({2}), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 4)); + auto task = Tasks().at(0); + ASSERT_EQ(task->delete_files().size(), 1); + EXPECT_TRUE(task->delete_files().front()->IsDeletionVector()); +} + +TEST_F(PositionDeleteV3Test, MergesPreviousVectorAfterPartitionEvolution) { + ASSERT_THAT(DeletePositions({3, 1}), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 2, 4)); + const auto old_delete = Tasks().at(0)->delete_files().at(0); + ICEBERG_UNWRAP_OR_FAIL(auto evolution, table_->NewUpdatePartitionSpec()); + evolution->RemoveField("x"); + ASSERT_THAT(evolution->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ASSERT_NE(table_->metadata()->default_spec_id, data_file_->partition_spec_id); + auto scan_io = std::make_shared(); + EXPECT_CALL(*scan_io, NewInputFile(old_delete->file_path)) + .WillOnce( + [this](std::string path) { return file_io_->NewInputFile(std::move(path)); }); + ASSERT_THAT(DeletePositions({2}, scan_io), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 4)); + auto task = Tasks().at(0); + ASSERT_EQ(task->delete_files().size(), 1); + const auto& dv = task->delete_files().front(); + EXPECT_EQ(dv->file_format, FileFormatType::kPuffin); + EXPECT_NE(dv->file_path, old_delete->file_path); + EXPECT_EQ(dv->partition_spec_id, data_file_->partition_spec_id); + EXPECT_EQ(dv->partition, data_file_->partition); +} + +class UnpartitionedPositionDeleteV3Test : public PositionDeleteV3Test { + protected: + bool unpartitioned() const override { return true; } +}; + +TEST_F(UnpartitionedPositionDeleteV3Test, ReloadsCommittedDeletes) { + ASSERT_THAT(DeletePositions({1, 2}), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 3, 4)); +} + +TEST_F(PositionDeleteV3Test, RejectsPositionPastEndOfFile) { + EXPECT_THAT(DeletePositions({data_file_->record_count}), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST_F(PositionDeleteV3Test, LostCommitResponsePreservesPublishedVector) { + auto task = Tasks().at(0); + auto mock = std::make_shared<::testing::NiceMock>(); + EXPECT_CALL(*mock, UpdateTable(::testing::_, ::testing::_, ::testing::_)) + .WillOnce([this](const auto& name, const auto& requirements, + const auto& updates) -> Result> { + ICEBERG_RETURN_UNEXPECTED(catalog_->UpdateTable(name, requirements, updates)); + return CommitStateUnknown("lost commit response"); + }); + ICEBERG_UNWRAP_OR_FAIL( + auto uncertain, + Table::Make(table_->name(), table_->metadata(), + std::string(table_->metadata_file_location()), file_io_, mock)); + ICEBERG_UNWRAP_OR_FAIL(auto delta, uncertain->NewRowDelta()); + EXPECT_THAT(internal::CommitPositionDeletes(*uncertain, *delta, + table_->metadata()->current_snapshot_id, + file_io_, {{task, {2}}}), + IsError(ErrorKind::kCommitStateUnknown)); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 1, 3, 4)); +} + +TEST_F(PositionDeleteV3Test, ConcurrentRemovalRejectsPreparedDeletes) { + auto snapshot_id = table_->metadata()->current_snapshot_id; + auto task = Tasks().at(0); + + ICEBERG_UNWRAP_OR_FAIL(auto removal, table_->NewDeleteFiles()); + removal->DeleteFile(data_file_); + ASSERT_THAT(removal->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + ICEBERG_UNWRAP_OR_FAIL(auto delta, table_->NewRowDelta()); + EXPECT_THAT(internal::CommitPositionDeletes(*table_, *delta, snapshot_id, file_io_, + {{task, {1}}}), + IsError(ErrorKind::kValidationFailed)); + auto io = std::static_pointer_cast(file_io_); + ::arrow::fs::FileSelector selector; + selector.base_dir = table_location_ + "/data"; + const auto files = io->fs()->GetFileInfo(selector).ValueOrDie(); + ASSERT_EQ(files.size(), 1); + EXPECT_EQ(files.front().path(), data_file_->file_path); + EXPECT_TRUE(Tasks().empty()); +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/test/std_io.h b/src/iceberg/test/std_io.h index b5b2a617c0..2ddd115283 100644 --- a/src/iceberg/test/std_io.h +++ b/src/iceberg/test/std_io.h @@ -319,11 +319,9 @@ class StdFileIO : public FileIO { Status DeleteFile(const std::string& file_location) override { std::error_code ec; - if (!std::filesystem::remove(file_location, ec)) { - if (ec) { - return IOError("Failed to delete file {}: {}", file_location, ec.message()); - } - return IOError("File does not exist: {}", file_location); + std::filesystem::remove(file_location, ec); + if (ec) { + return IOError("Failed to delete file {}: {}", file_location, ec.message()); } return {}; } diff --git a/src/iceberg/test/struct_like_test.cc b/src/iceberg/test/struct_like_test.cc index e04d2c089b..458b507a0d 100644 --- a/src/iceberg/test/struct_like_test.cc +++ b/src/iceberg/test/struct_like_test.cc @@ -40,6 +40,7 @@ #include "iceberg/manifest/manifest_reader_internal.h" #include "iceberg/row/arrow_array_wrapper.h" #include "iceberg/row/manifest_wrapper.h" +#include "iceberg/row/partition_values.h" #include "iceberg/schema.h" #include "iceberg/schema_internal.h" #include "iceberg/test/matchers.h" @@ -181,9 +182,7 @@ TEST(LiteralToScalarTest, Uuid) { TEST(StructLikeAccessorTest, GetLiteralUuid) { ICEBERG_UNWRAP_OR_FAIL(auto uuid, Uuid::FromString("123e4567-e89b-12d3-a456-426614174000")); - const auto& bytes = uuid.bytes(); - std::string_view uuid_data(reinterpret_cast(bytes.data()), bytes.size()); - SingleFieldStructLike row(Scalar{uuid_data}); + PartitionValues row(Literal::UUID(uuid)); std::array path = {0}; StructLikeAccessor accessor(iceberg::uuid(), path, {false}); From 3ad71180f35d77bb254e66b69dcac666f6f48a61 Mon Sep 17 00:00:00 2001 From: wirybeaver Date: Sat, 5 Dec 2026 15:19:53 -0800 Subject: [PATCH 2/2] feat(data): delete matching rows with a snapshot-bound merge-on-read scan --- src/iceberg/CMakeLists.txt | 1 + src/iceberg/action/delete_rows.cc | 161 ++++++++++++++++++ src/iceberg/action/delete_rows.h | 36 ++++ src/iceberg/cpp20_compatibility_internal.h | 1 + src/iceberg/table_scan.cc | 8 +- src/iceberg/table_scan.h | 4 + .../test/position_delete_update_test.cc | 42 ++++- 7 files changed, 251 insertions(+), 2 deletions(-) create mode 100644 src/iceberg/action/delete_rows.cc create mode 100644 src/iceberg/action/delete_rows.h diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index c4dce273f2..eb383a576d 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -257,6 +257,7 @@ if(MSVC_TOOLCHAIN) endif() set(ICEBERG_DATA_SOURCES + action/delete_rows.cc action/position_delete_action.cc data/arrow_batch_sizer.cc data/data_writer.cc diff --git a/src/iceberg/action/delete_rows.cc b/src/iceberg/action/delete_rows.cc new file mode 100644 index 0000000000..e77f832391 --- /dev/null +++ b/src/iceberg/action/delete_rows.cc @@ -0,0 +1,161 @@ +/* + * 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 "iceberg/action/delete_rows.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "iceberg/action/position_delete_action_internal.h" +#include "iceberg/data/file_scan_task_reader.h" +#include "iceberg/data_table_scan.h" +#include "iceberg/expression/binder.h" +#include "iceberg/json_serde_internal.h" +#include "iceberg/metadata_columns.h" +#include "iceberg/name_mapping.h" +#include "iceberg/schema.h" +#include "iceberg/table.h" +#include "iceberg/table_metadata.h" +#include "iceberg/table_properties.h" +#include "iceberg/update/row_delta.h" + +namespace iceberg { +namespace { + +// Record the original references before binding can fold a predicate to a constant. +// The task reader needs these columns when it binds residuals to the read schema. +class FilterColumns : public Binder { + public: + explicit FilterColumns(const Schema& schema) + : Binder(schema, /*case_sensitive=*/true) {} + using Binder::Predicate; + Result> Predicate( + const std::shared_ptr& pred) override { + names.emplace_back(pred->reference()->name()); + return Binder::Predicate(pred); + } + std::vector names; +}; + +Result> MatchingPositions(FileScanTaskReader& reader, + const FileScanTask& task) { + ICEBERG_ASSIGN_OR_RAISE(auto opened, reader.Open(task)); + nanoarrow::UniqueArrayStream stream(&opened); + std::vector positions; + while (true) { + nanoarrow::UniqueArray batch; + ArrowError error{}; + if (ArrowArrayStreamGetNext(stream.get(), batch.get(), &error) != NANOARROW_OK) { + return IOError("Reading rows for deletion: {}", error.message); + } + if (!batch->release) break; + if (batch->length == 0) continue; + // _pos is the first projected field, a required int64 absolute file position. + const auto& column = *batch->children[0]; + const auto* begin = + static_cast(column.buffers[1]) + column.offset + batch->offset; + positions.insert(positions.end(), begin, begin + batch->length); + } + return positions; +} + +Result> CollectDeletes( + FileScanTaskReader& reader, FileScanTaskStream& tasks) { + std::vector groups; + std::unordered_map by_file; + while (true) { + ICEBERG_ASSIGN_OR_RAISE(auto task, tasks.Next()); + if (!task) break; + ICEBERG_ASSIGN_OR_RAISE(auto positions, MatchingPositions(reader, **task)); + if (positions.empty()) continue; + auto [it, inserted] = + by_file.try_emplace((*task)->data_file()->file_path, groups.size()); + if (inserted) { + groups.push_back({std::move(*task), std::move(positions)}); + } else { + auto& group = groups[it->second].positions; + group.insert(group.end(), positions.begin(), positions.end()); + } + } + return groups; +} + +} // namespace + +Status MergeOnReadDelete(Table& table, std::shared_ptr filter) { + ICEBERG_PRECHECK(filter != nullptr, "Delete filter cannot be null"); + auto metadata = table.metadata(); + ICEBERG_PRECHECK(metadata->format_version >= 2, + "Merge-on-read deletes require v2 or later"); + auto isolation = table.properties().Get(TableProperties::kDeleteIsolationLevel); + ICEBERG_PRECHECK(isolation == "serializable" || isolation == "snapshot", + "Unsupported delete isolation level: {}", isolation); + ICEBERG_ASSIGN_OR_RAISE(auto schema, metadata->Schema()); + FilterColumns columns(*schema); + ICEBERG_RETURN_UNEXPECTED( + (Visit, Binder>(filter, columns))); + const auto snapshot_id = metadata->current_snapshot_id; + if (snapshot_id == kInvalidSnapshotId) return {}; + + ICEBERG_ASSIGN_OR_RAISE(auto selected, schema->Select(columns.names)); + std::vector fields{MetadataColumns::kRowPosition}; + fields.insert(fields.end(), selected->fields().begin(), selected->fields().end()); + ICEBERG_ASSIGN_OR_RAISE(auto builder, table.NewScan()); + builder->UseSnapshot(snapshot_id, /*use_snapshot_schema=*/false) + .Filter(filter) + .Project(std::move(selected)); + ICEBERG_ASSIGN_OR_RAISE(auto scan, builder->Build()); + ICEBERG_ASSIGN_OR_RAISE(auto tasks, scan->PlanFilesStream()); + + const auto& properties = table.properties().configs(); + std::shared_ptr mapping; + auto mapping_it = properties.find(std::string(TableProperties::kDefaultNameMapping)); + if (mapping_it != properties.end()) { + ICEBERG_ASSIGN_OR_RAISE(auto json, FromJsonString(mapping_it->second)); + ICEBERG_ASSIGN_OR_RAISE(mapping, NameMappingFromJson(json)); + } + ICEBERG_ASSIGN_OR_RAISE( + auto reader, FileScanTaskReader::Make({ + .io = scan->io(), + .table_schema = schema, + .schemas = metadata->schemas, + .projected_schema = std::make_shared(std::move(fields)), + .name_mapping = std::move(mapping), + .properties = properties, + .apply_residuals = true, + })); + ICEBERG_ASSIGN_OR_RAISE(auto groups, CollectDeletes(*reader, *tasks)); + if (groups.empty()) return {}; + + ICEBERG_ASSIGN_OR_RAISE(auto delta, table.NewRowDelta()); + delta->ConflictDetectionFilter(std::move(filter)); + if (isolation == "serializable") delta->ValidateNoConflictingDataFiles(); + + return internal::CommitPositionDeletes(table, *delta, snapshot_id, scan->io(), + std::move(groups)); +} + +} // namespace iceberg diff --git a/src/iceberg/action/delete_rows.h b/src/iceberg/action/delete_rows.h new file mode 100644 index 0000000000..6b8da51951 --- /dev/null +++ b/src/iceberg/action/delete_rows.h @@ -0,0 +1,36 @@ +/* + * 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 + +#include "iceberg/iceberg_data_export.h" +#include "iceberg/result.h" +#include "iceberg/type_fwd.h" + +namespace iceberg { + +/// Delete live rows matching an unbound, case-sensitive predicate on the current +/// snapshot. Uses merge-on-read on v2 and v3 tables and honors +/// write.delete.isolation-level. An empty match succeeds without creating a snapshot. +ICEBERG_DATA_EXPORT Status MergeOnReadDelete(Table& table, + std::shared_ptr filter); + +} // namespace iceberg diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index 93d716e950..10725685b4 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -24,6 +24,7 @@ #pragma once +#include "iceberg/action/delete_rows.h" #include "iceberg/arrow_c_data.h" #include "iceberg/catalog.h" #include "iceberg/catalog/catalog_util.h" diff --git a/src/iceberg/table_scan.cc b/src/iceberg/table_scan.cc index 847ddfd6e0..0682f72483 100644 --- a/src/iceberg/table_scan.cc +++ b/src/iceberg/table_scan.cc @@ -423,12 +423,18 @@ TableScanBuilder& TableScanBuilder::PlanWith(Executor& execu template TableScanBuilder& TableScanBuilder::UseSnapshot(int64_t snapshot_id) { + return UseSnapshot(snapshot_id, /*use_snapshot_schema=*/true); +} + +template +TableScanBuilder& TableScanBuilder::UseSnapshot( + int64_t snapshot_id, bool use_snapshot_schema) { ICEBERG_BUILDER_CHECK(!context_.snapshot_id.has_value(), "Cannot override snapshot, already set snapshot id={}", context_.snapshot_id.value()); ICEBERG_BUILDER_ASSIGN_OR_RETURN(std::ignore, metadata_->SnapshotById(snapshot_id)); context_.snapshot_id = snapshot_id; - context_.use_snapshot_schema = true; + context_.use_snapshot_schema = use_snapshot_schema; return *this; } diff --git a/src/iceberg/table_scan.h b/src/iceberg/table_scan.h index 31998c182c..538ebc8bd1 100644 --- a/src/iceberg/table_scan.h +++ b/src/iceberg/table_scan.h @@ -414,6 +414,10 @@ class ICEBERG_TEMPLATE_CLASS_EXPORT TableScanBuilder : public ErrorCollector { /// \note InvalidArgument will be returned if the snapshot cannot be found TableScanBuilder& UseSnapshot(int64_t snapshot_id); + /// Pin the snapshot while choosing whether its historical schema or the current + /// table schema is used to resolve the scan. + TableScanBuilder& UseSnapshot(int64_t snapshot_id, bool use_snapshot_schema); + /// \brief Request this scan to use the given reference. /// \param ref reference /// \note InvalidArgument will be returned if a reference with the given name diff --git a/src/iceberg/test/position_delete_update_test.cc b/src/iceberg/test/position_delete_update_test.cc index 32d0727b36..a61a1ff984 100644 --- a/src/iceberg/test/position_delete_update_test.cc +++ b/src/iceberg/test/position_delete_update_test.cc @@ -28,12 +28,14 @@ #include #include +#include "iceberg/action/delete_rows.h" #include "iceberg/action/position_delete_action_internal.h" #include "iceberg/arrow/arrow_io_internal.h" #include "iceberg/avro/avro_register.h" #include "iceberg/data/data_writer.h" #include "iceberg/data/file_scan_task_reader.h" #include "iceberg/data_table_scan.h" +#include "iceberg/expression/expressions.h" #include "iceberg/file_reader.h" #include "iceberg/metadata_columns.h" #include "iceberg/parquet/parquet_register.h" @@ -51,6 +53,7 @@ #include "iceberg/update/row_delta.h" #include "iceberg/update/update_partition_spec.h" #include "iceberg/update/update_properties.h" +#include "iceberg/update/update_schema.h" namespace iceberg { namespace { @@ -189,7 +192,10 @@ TEST_F(PositionDeleteUpdateTest, WritesSortedParquetDeletes) { } TEST_F(PositionDeleteUpdateTest, UpgradeMergesPreviousParquetDeletes) { - ASSERT_THAT(DeletePositions({3, 1}), IsOk()); + ASSERT_THAT(MergeOnReadDelete( + *table_, Expressions::Or(Expressions::Equal("y", Literal::Long(3)), + Expressions::Equal("y", Literal::Long(1)))), + IsOk()); ICEBERG_UNWRAP_OR_FAIL(auto properties, table_->NewUpdateProperties()); properties->Set(TableProperties::kFormatVersion.key(), "3"); ASSERT_THAT(properties->Commit(), IsOk()); @@ -235,6 +241,40 @@ TEST_F(UnpartitionedPositionDeleteV3Test, ReloadsCommittedDeletes) { EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 3, 4)); } +TEST_F(PositionDeleteV3Test, FilterDeleteUsesCurrentSchemaAndAbsolutePositions) { + ASSERT_THAT(DeletePositions({1}), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto rename, table_->NewUpdateSchema()); + rename->RenameColumn("y", "value"); + ASSERT_THAT(rename->Commit(), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + + auto predicate = Expressions::Equal("value", Literal::Long(3)); + ASSERT_THAT(MergeOnReadDelete(*table_, predicate), IsOk()); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 2, 4)); + auto snapshot = table_->metadata()->current_snapshot_id; + ASSERT_THAT(MergeOnReadDelete(*table_, predicate), IsOk()); + ASSERT_THAT(table_->Refresh(), IsOk()); + EXPECT_EQ(table_->metadata()->current_snapshot_id, snapshot); +} + +TEST_F(PositionDeleteV3Test, FilterDeletePreservesOutputWhenCommitOutcomeIsUnknown) { + auto mock = std::make_shared<::testing::NiceMock>(); + EXPECT_CALL(*mock, UpdateTable(::testing::_, ::testing::_, ::testing::_)) + .WillOnce([this](const auto& name, const auto& requirements, + const auto& updates) -> Result> { + ICEBERG_RETURN_UNEXPECTED(catalog_->UpdateTable(name, requirements, updates)); + return CommitStateUnknown("lost commit response"); + }); + ICEBERG_UNWRAP_OR_FAIL( + auto uncertain, + Table::Make(table_->name(), table_->metadata(), + std::string(table_->metadata_file_location()), file_io_, mock)); + EXPECT_THAT(MergeOnReadDelete(*uncertain, Expressions::Equal("y", Literal::Long(2))), + IsError(ErrorKind::kCommitStateUnknown)); + EXPECT_THAT(ReadRows(), ::testing::ElementsAre(0, 1, 3, 4)); +} + TEST_F(PositionDeleteV3Test, RejectsPositionPastEndOfFile) { EXPECT_THAT(DeletePositions({data_file_->record_count}), IsError(ErrorKind::kInvalidArgument));