From 91f519c87f9bf2bdaced41101510b5b5de7cbf3f Mon Sep 17 00:00:00 2001 From: Nicholas Jiang Date: Tue, 1 Dec 2026 18:44:06 -0800 Subject: [PATCH] feat(append): support write-buffer spill for append-only tables Append-only writers sent every batch straight to a data file writer and reported no memory to the write memory manager, so many concurrent writers, e.g. a batch insert into many partitions, could run out of memory without any way to spill. - Add `write-buffer-for-append` and `write-max-writers-to-spill`, as in Paimon Java, defaulting to false and 10. - Add AppendWriteBuffer to keep written batches in memory, report the size of the Arrow buffers they reference to the write memory manager, spill them to temporary Arrow IPC files under memory pressure, with the threads set by SetWriteBufferSpillThreadNumber(), and replay them in write order on flush. - Let AppendOnlyWriter buffer batches with `write-buffer-for-append`, spilling only with `write-buffer-spillable` and a temporary directory, and flush data files instead when it cannot spill, its spill directory cannot be created, or its spill files reach `write-buffer-spill.max-disk-size`. - Once the active writers reach `write-max-writers-to-spill`, switch existing and future writers to spillable buffers before creating the next one, except for real-time writes, writes without a usable temporary directory, and writes with BLOBs in dedicated .blob files, which also bypass the write buffer. As in Paimon Java, a writer without a buffer closes its data files, reads their rows back into the new buffer ahead of later rows, and deletes the files, even if reading them back fails. - Count each batch read back toward the shared `write-buffer-size`, so the write memory manager spills or flushes the largest writers during the switch instead of letting every switched writer keep nearly `write-buffer-size` of rows. - Validate BLOB inline fields of buffered batches on write. - Keep the buffered rows and discard the partial data files of a failed replay, and track flushed data files before the buffer drops their rows, so a retry neither duplicates nor loses rows. - Fail a writer once rows it accepted can no longer be committed exactly once, e.g. when a spill fails or closing or reading back its data files fails during a switch, so later writes and commits return the error. - Delete spill files once their rows are flushed or the writer closes, retrying failed deletes, and on close delete the data files flushed but never returned by PrepareCommit(). - Add tests for AppendWriteBuffer, and extend the AppendOnlyWriter and AppendOnlyFileStoreWrite tests to cover spill and replay order, the shared `write-buffer-size`, the switch and its read-back, the spill disk budget, failures and cleanup. - Document the write buffer options, memory accounting, failure handling and cleanup in the append-only table user guide. --- docs/source/user_guide/append_only_table.rst | 99 +++ include/paimon/defs.h | 14 +- include/paimon/file_store_write.h | 4 + src/paimon/CMakeLists.txt | 2 + ...hared_shredding_read_plan_factory_test.cpp | 7 +- src/paimon/common/defs.cpp | 2 + .../append/append_compact_coordinator.cpp | 1 + src/paimon/core/append/append_only_writer.cpp | 297 +++++++-- src/paimon/core/append/append_only_writer.h | 66 +- .../core/append/append_only_writer_test.cpp | 617 +++++++++++++++++- .../core/append/append_write_buffer.cpp | 195 ++++++ src/paimon/core/append/append_write_buffer.h | 149 +++++ .../core/append/append_write_buffer_test.cpp | 334 ++++++++++ src/paimon/core/core_options.cpp | 16 + src/paimon/core/core_options.h | 2 + src/paimon/core/core_options_test.cpp | 6 + .../operation/abstract_file_store_write.cpp | 26 + .../operation/abstract_file_store_write.h | 24 + .../append_only_file_store_write.cpp | 102 ++- .../operation/append_only_file_store_write.h | 35 +- .../append_only_file_store_write_test.cpp | 612 ++++++++++++++++- .../table/append_only_file_store_table.cpp | 4 +- 22 files changed, 2540 insertions(+), 74 deletions(-) create mode 100644 src/paimon/core/append/append_write_buffer.cpp create mode 100644 src/paimon/core/append/append_write_buffer.h create mode 100644 src/paimon/core/append/append_write_buffer_test.cpp diff --git a/docs/source/user_guide/append_only_table.rst b/docs/source/user_guide/append_only_table.rst index 07c73a142..4252a53c8 100644 --- a/docs/source/user_guide/append_only_table.rst +++ b/docs/source/user_guide/append_only_table.rst @@ -37,3 +37,102 @@ The experimental real-time append deduplicate mode is an exception. With rows. The table still has no primary key; deduplication is scoped to each partition-bucket. See :doc:`realtime` for the required schema, options and shared context. + +Write Buffer +------------ +By default, an append writer sends each ``RecordBatch`` straight to a data file +writer and reports no memory to the write memory manager. Writing to many +partitions or buckets at once can then use a lot of memory, because every +active ``(partition, bucket)`` writer keeps an open data file writer. + +.. list-table:: + :header-rows: 1 + + * - Option + - Default + - Description + * - ``write-buffer-for-append`` + - ``false`` + - Buffer written batches in memory until the next flush and report their + size to the write memory manager. + * - ``write-max-writers-to-spill`` + - ``10`` + - Number of active writers at which creating the next one, the 11th by + default, switches every writer to a spillable write buffer. + * - ``write-buffer-spillable`` + - ``true`` + - Whether a buffer enabled by ``write-buffer-for-append`` may spill. + * - ``write-buffer-size`` + - ``256 mb`` + - Estimated in-memory threshold shared by the write buffers of one + ``FileStoreWrite``. Once reached, the largest buffer spills or flushes. + Each buffered batch counts the Arrow buffers it references up to its + last row, so columns sliced from larger columns keep more memory alive + than they count; copy them before writing. Memory held by data file + writers is not counted. + * - ``write-buffer-spill.max-disk-size`` + - unlimited + - Disk budget for the spill files of one writer, checked before each spill, + so a single spill can go past it. + +Spill files are temporary Arrow IPC files under the directory set with +``WriteContextBuilder::WithTempDirectory()``, written and read with the +threads set by ``WriteContextBuilder::SetWriteBufferSpillThreadNumber()``. +Without a temporary directory, a buffer never spills: under memory pressure it +writes data files instead. The spill directory is created under it when the +first writer that may spill is created, or when the writers switch. If that +fails, e.g. because the path is a regular file, the write logs the path and the +reason as a warning once, its buffers write data files instead of spilling and +its writers never switch; no rows are lost and no spill file is left. Failing to +write or close a spill file is an error instead, as described below. + +When ``write-buffer-for-append = true``, each writer buffers its batches. Under +memory pressure, a spillable buffer moves them to a spill file; otherwise the +writer flushes them to data files. ``PrepareCommit()`` replays the spill files +and the in-memory batches, in write order, into data files and then deletes the +spill files. + +Independently of ``write-buffer-for-append``, once a write has +``write-max-writers-to-spill`` active writers, creating the next one first +switches every active writer, and every writer created afterwards, to a +spillable write buffer. The switch requires a temporary directory whose spill +directory can be created, and overrides ``write-buffer-spillable = false``. A +writer that already has a buffer keeps its rows and starts spilling. As in +Paimon Java, a writer without one closes the data files it was writing, reads +their rows back into its new buffer ahead of later rows, so the bucket keeps its +write order, and deletes the files. The rows count toward the shared +``write-buffer-size`` as they are read back, so the largest buffers spill, or +flush data files once their spill files reach +``write-buffer-spill.max-disk-size``, before the switched writers together go +past it. If closing or reading them back fails, the files are deleted anyway and +the writer fails as described below. + +The disk budget is checked by each writer before it spills: once the spill +files of a writer reach ``write-buffer-spill.max-disk-size``, the writer +flushes its buffered rows to data files instead, which releases the spill +files. A spill file that fails to be deleted keeps counting toward the budget +and is deleted again on the next flush or close. + +The write buffer does not apply to: + +- writes whose schema has BLOB fields written to dedicated ``.blob`` files, + including a write of selected columns that contains such a field. BLOB + fields stored inline through ``blob-descriptor-field`` or + ``blob-view-field`` are buffered and can switch. +- real-time writes. See :doc:`realtime` for how real-time stores spill. + +Closing a writer deletes its spill files and the data files it flushed that +were never returned by ``PrepareCommit()``, even when syncing its compaction +fails. + +After an I/O error from ``Write()`` or ``PrepareCommit()``, close the +``FileStoreWrite`` and write the rows since the last commit again with a new +one. Within one writer: + +- a failed replay discards its partial data files and keeps the buffered rows, + so the next flush of that writer does not duplicate them. +- once a writer accepted rows it can no longer commit exactly once, e.g. when + closing or reading back its data files fails during a switch, or a spill or + flush fails after a batch was accepted, every later ``Write()`` or + ``PrepareCommit()`` that reaches it returns the error, instead of committing + without those rows or with them twice. diff --git a/include/paimon/defs.h b/include/paimon/defs.h index a39a2e128..af66fd8e7 100644 --- a/include/paimon/defs.h +++ b/include/paimon/defs.h @@ -257,7 +257,9 @@ struct PAIMON_EXPORT Options { static const char WRITE_BATCH_SIZE[]; /// "write-buffer-size" - Amount of data to build up in memory before converting to a sorted - /// on-disk file. The default value is 256 mb + /// on-disk file. For an append-only table with write buffers, the estimated memory shared by + /// the write buffers of one write before the largest one spills or flushes data files. The + /// default value is 256 mb static const char WRITE_BUFFER_SIZE[]; /// "write-buffer-spillable" - Whether the write buffer can be spillable. Default value is true. @@ -267,6 +269,16 @@ struct PAIMON_EXPORT Options { /// works when the write buffer spill is enabled. Default value is unlimited. static const char WRITE_BUFFER_SPILL_MAX_DISK_SIZE[]; + /// "write-buffer-for-append" - This option only works for append-only tables. Whether the write + /// uses a write buffer to avoid out-of-memory errors. Default value is false. + static const char WRITE_BUFFER_FOR_APPEND[]; + + /// "write-max-writers-to-spill" - When writing to an append-only table, if the number of + /// active writers is greater than this option, all writers switch to spillable write buffers + /// to avoid out-of-memory errors, even with `write-buffer-spillable` = false. This requires a + /// temporary directory for spill files. Default value is 10. + static const char WRITE_MAX_WRITERS_TO_SPILL[]; + /// "local-sort.max-num-file-handles" - The maximal fan-in for external merge sort. It limits /// the number of file handles. If it is too small, may cause intermediate merging. But if it is /// too large, it will cause too many files opened at the same time, consume memory and lead to diff --git a/include/paimon/file_store_write.h b/include/paimon/file_store_write.h index ae01dd080..225358a9a 100644 --- a/include/paimon/file_store_write.h +++ b/include/paimon/file_store_write.h @@ -66,6 +66,10 @@ class PAIMON_EXPORT FileStoreWrite { /// @note A failure while writing or flushing a real-time batch invalidates the writer and its /// `RealtimeContext`. Recreate both and let upstream replay input from the durable /// recovery offset persisted in the snapshot; retrying the failed writer is unsupported. + /// @note For an append-only table with write buffers, an I/O error from `Write()`, e.g. while + /// spilling, may leave this writer unable to commit the rows it accepted exactly once, + /// and later calls then return the error. Close it and write the rows since the last + /// commit again with a new one. virtual Status Write(std::unique_ptr&& batch) = 0; /// Slices the current in-memory real-time data into a sealed segment so it can be reclaimed diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt index e46b4b173..8e1407cc0 100644 --- a/src/paimon/CMakeLists.txt +++ b/src/paimon/CMakeLists.txt @@ -235,6 +235,7 @@ set(PAIMON_CORE_SRCS core/append/append_file_compaction.cpp core/append/append_file_compaction_planner.cpp core/append/append_only_writer.cpp + core/append/append_write_buffer.cpp core/append/bucketed_append_compact_manager.cpp core/bucket/bucket_select_converter.cpp core/append/append_compact_task.cpp @@ -868,6 +869,7 @@ if(PAIMON_BUILD_TESTS) SOURCES core/append/append_file_compaction_planner_test.cpp core/append/append_only_writer_test.cpp + core/append/append_write_buffer_test.cpp core/append/append_compact_coordinator_test.cpp core/append/append_file_index_write_test.cpp core/append/bucketed_append_compact_manager_test.cpp diff --git a/src/paimon/common/data/shredding/map_shared_shredding_read_plan_factory_test.cpp b/src/paimon/common/data/shredding/map_shared_shredding_read_plan_factory_test.cpp index fe15921cc..b63333025 100644 --- a/src/paimon/common/data/shredding/map_shared_shredding_read_plan_factory_test.cpp +++ b/src/paimon/common/data/shredding/map_shared_shredding_read_plan_factory_test.cpp @@ -218,9 +218,10 @@ class MapSharedShreddingReadPlanFactoryTest : public ::testing::Test { const std::optional>& write_cols, int64_t max_sequence_number, const std::shared_ptr& path_factory, const std::shared_ptr& compact_manager) const { - return std::make_unique(core_options, schema_id, logical_schema, - write_cols, max_sequence_number, path_factory, - compact_manager, pool_); + return std::make_unique( + core_options, schema_id, logical_schema, write_cols, max_sequence_number, path_factory, + compact_manager, /*use_write_buffer=*/false, /*io_manager=*/nullptr, + /*enable_multi_thread_spill=*/false, /*files_reader_factory=*/nullptr, pool_); } private: diff --git a/src/paimon/common/defs.cpp b/src/paimon/common/defs.cpp index 703d13bda..921640268 100644 --- a/src/paimon/common/defs.cpp +++ b/src/paimon/common/defs.cpp @@ -76,6 +76,8 @@ const char Options::WRITE_BATCH_SIZE[] = "write.batch-size"; const char Options::WRITE_BUFFER_SIZE[] = "write-buffer-size"; const char Options::WRITE_BUFFER_SPILLABLE[] = "write-buffer-spillable"; const char Options::WRITE_BUFFER_SPILL_MAX_DISK_SIZE[] = "write-buffer-spill.max-disk-size"; +const char Options::WRITE_BUFFER_FOR_APPEND[] = "write-buffer-for-append"; +const char Options::WRITE_MAX_WRITERS_TO_SPILL[] = "write-max-writers-to-spill"; const char Options::LOCAL_SORT_MAX_NUM_FILE_HANDLES[] = "local-sort.max-num-file-handles"; const char Options::SPILL_COMPRESSION[] = "spill-compression"; const char Options::SPILL_COMPRESSION_ZSTD_LEVEL[] = "spill-compression.zstd-level"; diff --git a/src/paimon/core/append/append_compact_coordinator.cpp b/src/paimon/core/append/append_compact_coordinator.cpp index b49369e2a..06b832e10 100644 --- a/src/paimon/core/append/append_compact_coordinator.cpp +++ b/src/paimon/core/append/append_compact_coordinator.cpp @@ -172,6 +172,7 @@ std::unique_ptr CreateFileStoreWrite( /*ignore_previous_files=*/true, /*is_streaming_mode=*/false, /*ignore_num_bucket_check=*/false, + /*enable_multi_thread_spill=*/false, /*realtime_context=*/nullptr, executor, pool); } diff --git a/src/paimon/core/append/append_only_writer.cpp b/src/paimon/core/append/append_only_writer.cpp index 97e7853b2..ada6bcf22 100644 --- a/src/paimon/core/append/append_only_writer.cpp +++ b/src/paimon/core/append/append_only_writer.cpp @@ -31,12 +31,16 @@ #include "arrow/util/key_value_metadata.h" #include "paimon/common/data/shredding/shredding_write_plan_factories.h" #include "paimon/common/metrics/metrics_impl.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/types/row_kind.h" +#include "paimon/common/utils/arrow/arrow_utils.h" +#include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/arrow/vector_utils.h" #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/long_counter.h" #include "paimon/common/utils/scope_guard.h" +#include "paimon/core/append/append_write_buffer.h" #include "paimon/core/append/bucketed_append_compact_manager.h" #include "paimon/core/io/append_data_file_writer_factory.h" #include "paimon/core/io/blob_data_file_writer_factory.h" @@ -53,19 +57,22 @@ #include "paimon/core/manifest/file_source.h" #include "paimon/core/operation/blob_file_context.h" #include "paimon/core/utils/commit_increment.h" +#include "paimon/logging.h" #include "paimon/macros.h" #include "paimon/metrics.h" +#include "paimon/reader/batch_reader.h" #include "paimon/record_batch.h" namespace paimon { -AppendOnlyWriter::AppendOnlyWriter(const CoreOptions& options, int64_t schema_id, - const std::shared_ptr& write_schema, - const std::optional>& write_cols, - int64_t max_sequence_number, - const std::shared_ptr& path_factory, - const std::shared_ptr& compact_manager, - const std::shared_ptr& memory_pool) +AppendOnlyWriter::AppendOnlyWriter( + const CoreOptions& options, int64_t schema_id, + const std::shared_ptr& write_schema, + const std::optional>& write_cols, int64_t max_sequence_number, + const std::shared_ptr& path_factory, + const std::shared_ptr& compact_manager, bool use_write_buffer, + const std::shared_ptr& io_manager, bool enable_multi_thread_spill, + const FilesReaderFactory& files_reader_factory, const std::shared_ptr& memory_pool) : options_(options), schema_id_(schema_id), write_schema_(write_schema), @@ -73,12 +80,157 @@ AppendOnlyWriter::AppendOnlyWriter(const CoreOptions& options, int64_t schema_id seq_num_counter_(std::make_shared(max_sequence_number + 1)), path_factory_(path_factory), compact_manager_(compact_manager), + enable_multi_thread_spill_(enable_multi_thread_spill), + files_reader_factory_(files_reader_factory), memory_pool_(memory_pool), - metrics_(std::make_shared()) {} + metrics_(std::make_shared()), + logger_(Logger::GetLogger("AppendOnlyWriter")) { + if (!options_.GetVectorFileFormat()) { + // Resolved here rather than with the data file writer, because buffered batches are + // validated when they are written, before any data file writer exists. + std::unique_ptr blob_context = + BlobFileContext::Create(write_schema_, options_); + if (blob_context) { + inline_descriptor_fields_ = blob_context->GetDescriptorFields(); + inline_view_fields_ = blob_context->GetViewFields(); + } + } + if (use_write_buffer) { + write_buffer_ = std::make_unique( + options_, write_schema_, io_manager, enable_multi_thread_spill_, memory_pool_); + } +} AppendOnlyWriter::~AppendOnlyWriter() = default; +uint64_t AppendOnlyWriter::GetMemoryUsage() const { + // Without a write buffer, rows go straight to the data file writer and nothing here can be + // released early, so report 0 to keep the memory manager from picking this writer. + return write_buffer_ ? write_buffer_->GetMemoryUsage() : 0; +} + +Status AppendOnlyWriter::FlushMemory() { + PAIMON_RETURN_NOT_OK(failure_); + // Called by the write memory manager after a batch was accepted, so a failure here must not + // look like the batch was rejected. + if (write_buffer_) { + Result spill_handled = write_buffer_->TrySpill(); + if (!spill_handled.ok()) { + return Fail(spill_handled.status()); + } + if (spill_handled.value()) { + return Status::OK(); + } + PAIMON_LOG_DEBUG(logger_, + "Write buffer in %s cannot spill (spillable: %d, spill files use %ld of " + "%ld bytes), flushing data files instead", + path_factory_->Parent().c_str(), write_buffer_->IsSpillable(), + write_buffer_->GetDiskUsage(), options_.GetWriteBufferSpillMaxDiskSize()); + } + Status status = Flush(/*wait_for_latest_compaction=*/false, /*forced_full_compaction=*/false); + return status.ok() ? status : Fail(status); +} + +Status AppendOnlyWriter::Fail(const Status& status) { + if (failure_.ok()) { + PAIMON_LOG_WARN(logger_, "Append-only writer of %s failed: %s", + path_factory_->Parent().c_str(), status.ToString().c_str()); + failure_ = status.WithMessage( + "Append-only writer failed after accepting rows it can no longer commit exactly once, " + "write the rows since the last commit again: ", + status.message()); + } + return failure_; +} + +Status AppendOnlyWriter::SwitchToSpillableBuffer(const std::shared_ptr& io_manager, + const std::function& check_memory) { + PAIMON_RETURN_NOT_OK(failure_); + if (write_buffer_) { + write_buffer_->EnableSpill(io_manager); + return Status::OK(); + } + if (!files_reader_factory_) { + // A writer that cannot read its data files back keeps writing them. + return Status::OK(); + } + Result>> closed = CloseDataFileWriter(); + if (!closed.ok()) { + // The rows written so far existed only in the discarded data files. + return Fail(closed.status()); + } + const std::vector>& closed_files = closed.value(); + write_buffer_ = std::make_unique(options_, write_schema_, io_manager, + enable_multi_thread_spill_, memory_pool_); + if (closed_files.empty()) { + return Status::OK(); + } + Status status = ReadFilesIntoWriteBuffer(closed_files, check_memory); + // Deleted even if reading them back fails: their rows are written again with the rows that + // follow, or lost with the failed writer. + for (const auto& closed_file : closed_files) { + DeleteDataFile(closed_file); + } + return status.ok() ? status : Fail(status); +} + +Status AppendOnlyWriter::ReadFilesIntoWriteBuffer( + const std::vector>& files, + const std::function& check_memory) { + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, files_reader_factory_(files)); + ScopeGuard reader_guard([&reader]() { reader->Close(); }); + std::shared_ptr data_type = arrow::struct_(write_schema_->fields()); + std::shared_ptr arrow_pool = GetArrowPool(memory_pool_); + const auto flush_threshold = static_cast(options_.GetWriteBufferSize()); + while (true) { + PAIMON_ASSIGN_OR_RAISE(BatchReader::ReadBatch batch, reader->NextBatch()); + if (BatchReader::IsEofBatch(batch)) { + break; + } + auto& [c_array, c_schema] = batch; + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr read_array, + arrow::ImportArray(c_array.get(), c_schema.get())); + if (!read_array || read_array->type_id() != arrow::Type::STRUCT) { + return Status::Invalid( + "AppendOnlyWriter: data file reader did not return a StructArray"); + } + auto struct_array = checked_pointer_cast(read_array); + PAIMON_ASSIGN_OR_RAISE(struct_array, ArrowUtils::RemoveFieldFromStructArray( + struct_array, SpecialFields::ValueKind().Name())); + // The buffer only holds batches of the write schema, which spill files and the data file + // writer expect, so every dictionary a reader may hand over is decoded. + PAIMON_ASSIGN_OR_RAISE(struct_array, + ArrowUtils::FlattenUnresolvableDictionaries( + struct_array, data_type, arrow_pool.get(), + /*preserve_layout_recoverable_dictionaries=*/false)); + // Imported with the write schema's type, as Write() does. Decoded columns keep a raw + // pointer to `arrow_pool`, so the batch keeps it alive. + ::ArrowArray typed_c_array; + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*struct_array, &typed_c_array)); + PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(&typed_c_array, /*schema=*/nullptr, arrow_pool)); + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr typed_array, + arrow::ImportArray(&typed_c_array, data_type)); + write_buffer_->Write(checked_pointer_cast(typed_array)); + if (write_buffer_->GetMemoryUsage() >= flush_threshold) { + PAIMON_RETURN_NOT_OK(FlushMemory()); + } + if (check_memory) { + PAIMON_RETURN_NOT_OK(check_memory()); + } + } + return Status::OK(); +} + +Status AppendOnlyWriter::ValidateBlobInlineFields( + const std::shared_ptr& struct_array) const { + PAIMON_RETURN_NOT_OK(BlobUtils::ValidateBlobInlineFields( + struct_array, inline_descriptor_fields_, "blob-descriptor-field")); + return BlobUtils::ValidateBlobInlineFields(struct_array, inline_view_fields_, + "blob-view-field"); +} + Status AppendOnlyWriter::Write(std::unique_ptr&& batch) { + PAIMON_RETURN_NOT_OK(failure_); for (const auto& row_kind : batch->GetRowKind()) { if (PAIMON_UNLIKELY(row_kind != RecordBatch::RowKind::INSERT)) { PAIMON_ASSIGN_OR_RAISE(const RowKind* kind, @@ -87,11 +239,8 @@ Status AppendOnlyWriter::Write(std::unique_ptr&& batch) { kind->Name()); } } - if (writer_ == nullptr) { - PAIMON_ASSIGN_OR_RAISE(writer_, CreateRollingRowWriter()); - } - - if (!inline_descriptor_fields_.empty() || !inline_view_fields_.empty()) { + bool has_inline_fields = !inline_descriptor_fields_.empty() || !inline_view_fields_.empty(); + if (write_buffer_ || has_inline_fields) { auto data_type = arrow::struct_(write_schema_->fields()); PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr arrow_array, arrow::ImportArray(batch->GetData(), data_type)); @@ -99,15 +248,22 @@ Status AppendOnlyWriter::Write(std::unique_ptr&& batch) { return Status::Invalid("AppendOnlyWriter: input is not a StructArray"); } auto struct_array = checked_pointer_cast(arrow_array); - PAIMON_RETURN_NOT_OK(BlobUtils::ValidateBlobInlineFields( - struct_array, inline_descriptor_fields_, "blob-descriptor-field")); - PAIMON_RETURN_NOT_OK(BlobUtils::ValidateBlobInlineFields(struct_array, inline_view_fields_, - "blob-view-field")); + PAIMON_RETURN_NOT_OK(ValidateBlobInlineFields(struct_array)); + if (write_buffer_) { + write_buffer_->Write(struct_array); + return Status::OK(); + } + if (writer_ == nullptr) { + PAIMON_ASSIGN_OR_RAISE(writer_, CreateRollingRowWriter()); + } ::ArrowArray c_array; PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*struct_array, &c_array)); return writer_->Write(&c_array); } + if (writer_ == nullptr) { + PAIMON_ASSIGN_OR_RAISE(writer_, CreateRollingRowWriter()); + } return writer_->Write(batch->GetData()); } @@ -168,24 +324,74 @@ Status AppendOnlyWriter::UpdateCompactDeletionFile( return Status::OK(); } +Status AppendOnlyWriter::ReplayWriteBuffer() { + if (!write_buffer_ || !write_buffer_->HasData()) { + return Status::OK(); + } + // With a write buffer, the data file writer only ever holds the output of this replay. + if (writer_ == nullptr) { + PAIMON_ASSIGN_OR_RAISE(writer_, CreateRollingRowWriter()); + } + Status status = + write_buffer_->Replay([this](const std::shared_ptr& batch) -> Status { + ::ArrowArray c_array; + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*batch, &c_array)); + ScopeGuard guard([&c_array]() { ArrowArrayRelease(&c_array); }); + PAIMON_RETURN_NOT_OK(writer_->Write(&c_array)); + guard.Release(); + return Status::OK(); + }); + if (!status.ok()) { + // The buffer keeps every row, so a retry must not see the partial output. + PAIMON_LOG_DEBUG(logger_, "Discarding data files of a failed write buffer replay in %s: %s", + path_factory_->Parent().c_str(), status.ToString().c_str()); + writer_->Abort(); + writer_.reset(); + } + return status; +} + +Result>> AppendOnlyWriter::CloseDataFileWriter() { + if (writer_ == nullptr) { + return std::vector>(); + } + Status status = writer_->Close(); + Result>> files = + status.ok() ? writer_->GetResult() + : Result>>(status); + if (!files.ok()) { + PAIMON_LOG_DEBUG(logger_, + "Discarding data files of a writer in %s that failed to close: %s", + path_factory_->Parent().c_str(), files.status().ToString().c_str()); + writer_->Abort(); + writer_.reset(); + return files.status(); + } + metrics_->Merge(writer_->GetMetrics()); + writer_.reset(); + return files; +} + Status AppendOnlyWriter::Flush(bool wait_for_latest_compaction, bool forced_full_compaction) { - std::vector> flushed_files; - if (writer_) { - PAIMON_RETURN_NOT_OK(writer_->Close()); - PAIMON_ASSIGN_OR_RAISE(flushed_files, writer_->GetResult()); + PAIMON_RETURN_NOT_OK(failure_); + PAIMON_RETURN_NOT_OK(ReplayWriteBuffer()); + Result>> closed = CloseDataFileWriter(); + if (!closed.ok()) { + // Without a write buffer, the rows existed only in the discarded data files. + return write_buffer_ ? closed.status() : Fail(closed.status()); + } + std::vector> flushed_files = std::move(closed).value(); + // Tracked before the buffer drops their rows, so a later failure cannot lose them. + new_files_.insert(new_files_.end(), flushed_files.begin(), flushed_files.end()); + if (write_buffer_) { + write_buffer_->Clear(); } // add new generated files for (const auto& flushed_file : flushed_files) { PAIMON_RETURN_NOT_OK(compact_manager_->AddNewFile(flushed_file)); } PAIMON_RETURN_NOT_OK(TrySyncLatestCompaction(wait_for_latest_compaction)); - PAIMON_RETURN_NOT_OK(compact_manager_->TriggerCompaction(forced_full_compaction)); - new_files_.insert(new_files_.end(), flushed_files.begin(), flushed_files.end()); - if (writer_) { - metrics_->Merge(writer_->GetMetrics()); - writer_.reset(); - } - return Status::OK(); + return compact_manager_->TriggerCompaction(forced_full_compaction); } AppendOnlyWriter::RollingFileWriterResult AppendOnlyWriter::CreateRollingRowWriter() { @@ -219,13 +425,6 @@ AppendOnlyWriter::RollingFileWriterResult AppendOnlyWriter::CreateRollingRowWrit vector_index); } auto blob_context = BlobFileContext::Create(write_schema_, options_); - - // Save inline descriptor and view fields for validation in Write() - if (blob_context) { - inline_descriptor_fields_ = blob_context->GetDescriptorFields(); - inline_view_fields_ = blob_context->GetViewFields(); - } - if (blob_context && blob_context->RequireBlobFileWriter()) { // Use context-aware schema separation: inline BLOB fields stay in main auto schemas = @@ -311,9 +510,22 @@ Status AppendOnlyWriter::Close() { // Request cancellation and wait for running compaction to exit. // This avoids reusing cancellation state while an old task is still running. compact_manager_->CancelAndWaitCompaction(); - PAIMON_RETURN_NOT_OK(Sync()); + Status status = Sync(); + if (status.ok()) { + status = compact_manager_->Close(); + } + // Data files flushed under memory pressure or by a switch to a spillable buffer, but never + // drained by PrepareCommit(), would otherwise be left behind uncommitted. They and the spill + // files are deleted even if the compaction could not be synced or closed. + for (const auto& file : new_files_) { + DeleteDataFile(file); + } + new_files_.clear(); + if (write_buffer_) { + write_buffer_->Clear(); + } + PAIMON_RETURN_NOT_OK(status); - PAIMON_RETURN_NOT_OK(compact_manager_->Close()); auto fs = options_.GetFileSystem(); for (const auto& file : compact_after_) { // AppendOnlyCompactManager will rewrite the file and no file upgrade will occur, so we @@ -333,4 +545,15 @@ Status AppendOnlyWriter::Close() { } return Status::OK(); } + +void AppendOnlyWriter::DeleteDataFile(const std::shared_ptr& file) const { + auto fs = options_.GetFileSystem(); + for (const std::string& path : path_factory_->CollectFiles(file)) { + Status status = fs->Delete(path); + if (!status.ok()) { + PAIMON_LOG_WARN(logger_, "Failed to delete uncommitted data file %s: %s", path.c_str(), + status.ToString().c_str()); + } + } +} } // namespace paimon diff --git a/src/paimon/core/append/append_only_writer.h b/src/paimon/core/append/append_only_writer.h index 9640f8eb9..2f947a6f5 100644 --- a/src/paimon/core/append/append_only_writer.h +++ b/src/paimon/core/append/append_only_writer.h @@ -19,6 +19,7 @@ #pragma once #include +#include #include #include #include @@ -39,29 +40,49 @@ struct ArrowArray; namespace arrow { class Schema; +class StructArray; } // namespace arrow namespace paimon { +class AppendWriteBuffer; +class BatchReader; class CommitIncrement; +class IOManager; class RecordBatch; template class RollingFileWriter; template class SingleFileWriterFactory; class LongCounter; +class Logger; class DataFilePathFactory; class MemoryPool; class Metrics; class AppendOnlyWriter : public BatchWriter { public: + /// Opens a reader over data files this writer wrote to its bucket. The reader returns their + /// rows in file order, with the fields of the write schema, possibly followed by + /// `SpecialFields::ValueKind()`. + using FilesReaderFactory = std::function>( + const std::vector>&)>; + + /// @param use_write_buffer Whether written batches are buffered until the next flush instead of + /// being sent to a data file writer directly. + /// @param io_manager Temporary storage the write buffer may spill to, or nullptr when the + /// buffer flushes data files under memory pressure. + /// @param enable_multi_thread_spill Whether spill files are written and read with threads. + /// @param files_reader_factory Reads the data files closed by `SwitchToSpillableBuffer()` back + /// into the write buffer, or nullptr. AppendOnlyWriter(const CoreOptions& options, int64_t schema_id, const std::shared_ptr& write_schema, const std::optional>& write_cols, int64_t max_sequence_number, const std::shared_ptr& path_factory, - const std::shared_ptr& compact_manager, + const std::shared_ptr& compact_manager, bool use_write_buffer, + const std::shared_ptr& io_manager, bool enable_multi_thread_spill, + const FilesReaderFactory& files_reader_factory, const std::shared_ptr& memory_pool); ~AppendOnlyWriter() override; @@ -72,13 +93,23 @@ class AppendOnlyWriter : public BatchWriter { } Status CompactFiles(const std::set& file_names); - uint64_t GetMemoryUsage() const override { - // used for spill, AppendOnlyWriter do not support spill, so return 0 to avoid triggering - // spill - return 0; - } - Status FlushMemory() override { - return Flush(/*wait_for_latest_compaction=*/false, /*forced_full_compaction=*/false); + uint64_t GetMemoryUsage() const override; + Status FlushMemory() override; + + /// Switches this writer to a write buffer that spills to `io_manager` under memory pressure. + /// Like Paimon Java, rows already sent to a data file writer are closed into data files, read + /// back into the new buffer ahead of later rows, so the bucket keeps its write order, and the + /// files are deleted. While they are read back, the buffer is flushed as by `FlushMemory()` + /// each time it reaches `write-buffer-size`, and `check_memory`, if set, is called after each + /// batch. If any of this fails, the files are deleted anyway, their rows are lost and the + /// writer fails. Without a `files_reader_factory`, the writer keeps writing data files + /// directly. + Status SwitchToSpillableBuffer(const std::shared_ptr& io_manager, + const std::function& check_memory); + + /// Returns the write buffer, or nullptr when batches go to a data file writer directly. + const AppendWriteBuffer* GetWriteBuffer() const { + return write_buffer_.get(); } Result PrepareCommit(bool wait_compaction) override; Result CompactNotCompleted() override { @@ -104,6 +135,20 @@ class AppendOnlyWriter : public BatchWriter { Result DrainIncrement(); Status Flush(bool wait_for_latest_compaction, bool forced_full_compaction); + Status ReplayWriteBuffer(); + /// Appends the rows of `files` to the write buffer, as `SwitchToSpillableBuffer()` describes. + Status ReadFilesIntoWriteBuffer(const std::vector>& files, + const std::function& check_memory); + /// Records `status` as the failure of this writer once rows it accepted can no longer be + /// committed exactly once. Only the first failure is kept, and every later `Write()`, + /// `FlushMemory()`, `SwitchToSpillableBuffer()` and `PrepareCommit()` returns it. `Close()` + /// still deletes the uncommitted data files and the spill files. + Status Fail(const Status& status); + /// Closes the data file writer and returns its files. On failure the writer and all of its + /// files are discarded, so a retry never commits a file twice or one that was aborted. + Result>> CloseDataFileWriter(); + void DeleteDataFile(const std::shared_ptr& file) const; + Status ValidateBlobInlineFields(const std::shared_ptr& struct_array) const; Result GetDataFileWriterFactory( const std::shared_ptr& schema, @@ -123,6 +168,8 @@ class AppendOnlyWriter : public BatchWriter { std::shared_ptr seq_num_counter_; std::shared_ptr path_factory_; std::shared_ptr compact_manager_; + const bool enable_multi_thread_spill_; + FilesReaderFactory files_reader_factory_; std::shared_ptr memory_pool_; std::shared_ptr metrics_; @@ -133,8 +180,11 @@ class AppendOnlyWriter : public BatchWriter { std::shared_ptr compact_deletion_file_; std::unique_ptr>> writer_; + std::unique_ptr write_buffer_; + Status failure_; std::set inline_descriptor_fields_; std::set inline_view_fields_; + std::unique_ptr logger_; }; } // namespace paimon diff --git a/src/paimon/core/append/append_only_writer_test.cpp b/src/paimon/core/append/append_only_writer_test.cpp index 14a9e4467..99690d417 100644 --- a/src/paimon/core/append/append_only_writer_test.cpp +++ b/src/paimon/core/append/append_only_writer_test.cpp @@ -41,13 +41,19 @@ #include "paimon/common/data/blob_view_struct.h" #include "paimon/common/data/shredding/map_shared_shredding_utils.h" #include "paimon/common/data/shredding/map_shredding_defs.h" +#include "paimon/common/factories/io_hook.h" #include "paimon/common/fs/external_path_provider.h" +#include "paimon/common/reader/concat_batch_reader.h" #include "paimon/common/utils/arrow/arrow_input_stream_adapter.h" +#include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/checked_cast.h" +#include "paimon/common/utils/path_util.h" +#include "paimon/core/append/append_write_buffer.h" #include "paimon/core/compact/compact_deletion_file.h" #include "paimon/core/compact/compact_result.h" #include "paimon/core/compact/noop_compact_manager.h" #include "paimon/core/core_options.h" +#include "paimon/core/disk/io_manager.h" #include "paimon/core/io/compact_increment.h" #include "paimon/core/io/data_file_path_factory.h" #include "paimon/core/io/data_increment.h" @@ -62,6 +68,8 @@ #include "paimon/fs/local/local_file_system.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/memory/memory_pool.h" +#include "paimon/reader/batch_reader.h" +#include "paimon/reader/file_batch_reader.h" #include "paimon/record_batch.h" #include "paimon/testing/utils/binary_row_generator.h" #include "paimon/testing/utils/read_result_collector.h" @@ -319,9 +327,10 @@ class AppendOnlyWriterTest : public testing::Test { const std::shared_ptr& path_factory, const std::shared_ptr& compact_manager, const std::shared_ptr& memory_pool) const { - return std::make_unique(options, schema_id, write_schema, write_cols, - max_sequence_number, path_factory, - compact_manager, memory_pool); + return std::make_unique( + options, schema_id, write_schema, write_cols, max_sequence_number, path_factory, + compact_manager, /*use_write_buffer=*/false, /*io_manager=*/nullptr, + /*enable_multi_thread_spill=*/false, /*files_reader_factory=*/nullptr, memory_pool); } protected: @@ -947,10 +956,6 @@ TEST_F(AppendOnlyWriterTest, TestWriteInvalidBlobViewFieldRejected) { auto schema = arrow::schema({arrow::field("f0", arrow::int32()), BlobUtils::ToArrowField("view", true)}); - ASSERT_OK_AND_ASSIGN( - auto writer, CreateAppendOnlyWriter( - options, /*schema_id=*/0, schema, /*write_cols=*/std::nullopt, - /*max_sequence_number=*/-1, path_factory, compact_manager_, memory_pool_)); // Build f0 column arrow::Int32Builder int_builder; @@ -962,9 +967,600 @@ TEST_F(AppendOnlyWriterTest, TestWriteInvalidBlobViewFieldRejected) { ASSERT_TRUE(view_builder.Append("not_a_valid_blob_view_or_descriptor").ok()); auto view_array = view_builder.Finish().ValueOrDie(); - ASSERT_NOK_WITH_MSG(writer->Write(CreateStructBatch(schema, {int_array, view_array})), - "BLOB inline field view require values to be set as corresponding type."); + for (bool use_write_buffer : {false, true}) { + SCOPED_TRACE(::testing::Message() << "use_write_buffer=" << use_write_buffer); + auto writer = std::make_unique( + options, /*schema_id=*/0, schema, /*write_cols=*/std::nullopt, + /*max_sequence_number=*/-1, path_factory, compact_manager_, use_write_buffer, + /*io_manager=*/nullptr, /*enable_multi_thread_spill=*/false, + /*files_reader_factory=*/nullptr, memory_pool_); + ASSERT_NOK_WITH_MSG( + writer->Write(CreateStructBatch(schema, {int_array, view_array})), + "BLOB inline field view require values to be set as corresponding type."); + ASSERT_OK(writer->Close()); + } +} + +class AppendOnlyWriterBufferTest : public AppendOnlyWriterTest { + public: + void SetUp() override { + AppendOnlyWriterTest::SetUp(); + schema_ = + arrow::schema({arrow::field("id", arrow::int32()), arrow::field("v", arrow::int64())}); + data_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(data_dir_); + tmp_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(tmp_dir_); + io_manager_ = std::make_shared(tmp_dir_->Str(), tmp_dir_->GetFileSystem()); + files_reader_factory_ = [this](const std::vector>& files) { + return ReadDataFiles(files); + }; + } + + std::unique_ptr CreateWriter(const CoreOptions& options, + bool use_write_buffer, + const std::shared_ptr& io_manager) { + path_factory_ = CreatePathFactory(data_dir_->Str(), kFormat, options); + return std::make_unique( + options, /*schema_id=*/0, schema_, /*write_cols=*/std::nullopt, + /*max_sequence_number=*/-1, path_factory_, compact_manager_, use_write_buffer, + io_manager, /*enable_multi_thread_spill=*/false, files_reader_factory_, memory_pool_); + } + + /// Opens a data file of the writer created last with its file schema. + std::unique_ptr OpenDataFile(const std::shared_ptr& file) const { + std::unique_ptr reader = + OpenFormatReader(path_factory_->ToPath(file->file_name), kFormat); + EXPECT_OK_AND_ASSIGN(std::unique_ptr c_file_schema, reader->GetFileSchema()); + EXPECT_OK(reader->SetReadSchema(c_file_schema.get(), /*predicate=*/nullptr, + /*selection_bitmap=*/std::nullopt)); + return reader; + } + + /// Reads the given data files of the writer created last, in order. + Result> ReadDataFiles( + const std::vector>& files) const { + std::vector> readers; + for (const auto& file : files) { + readers.push_back(OpenDataFile(file)); + } + return std::make_unique(std::move(readers), GetArrowPool(memory_pool_)); + } + + /// Reads the `id` column of the new data files in commit order. + std::vector ReadNewFileIds(const CommitIncrement& increment) const { + std::vector ids; + for (const auto& file : increment.GetNewFilesIncrement().NewFiles()) { + std::unique_ptr reader = OpenDataFile(file); + EXPECT_OK_AND_ASSIGN(std::shared_ptr result, + ReadResultCollector::CollectResult(std::move(reader))); + EXPECT_NE(nullptr, result); + if (!result) { + continue; + } + EXPECT_EQ(file->row_count, result->length()); + for (const auto& chunk : result->chunks()) { + auto struct_array = checked_pointer_cast(chunk); + auto id_array = checked_pointer_cast(struct_array->field(0)); + for (int64_t i = 0; i < id_array->length(); ++i) { + ids.push_back(id_array->Value(i)); + } + } + } + return ids; + } + + bool AnySpillFileExists(const std::vector& channels) const { + for (const FileIOChannel::ID& channel : channels) { + if (tmp_dir_->GetFileSystem()->Exists(channel.GetPath()).value()) { + return true; + } + } + return false; + } + + /// Returns an IOManager whose spill directory cannot be created, as a regular file is in the + /// way. + std::shared_ptr CreateUnavailableIOManager() const { + std::shared_ptr fs = tmp_dir_->GetFileSystem(); + const std::string blocker = PathUtil::JoinPath(tmp_dir_->Str(), "blocker"); + EXPECT_OK_AND_ASSIGN(auto output, fs->Create(blocker, /*overwrite=*/true)); + EXPECT_OK(output->Close()); + return std::make_shared(PathUtil::JoinPath(blocker, "tmp"), fs); + } + + /// Returns the names of the files in the data directory, sorted. + std::vector ListDataFileNames() const { + std::vector statuses; + EXPECT_OK(data_dir_->GetFileSystem()->ListDir(data_dir_->Str(), &statuses)); + std::vector names; + for (const BasicFileStatus& status : statuses) { + if (!status.IsDir()) { + names.push_back(PathUtil::GetName(status.GetPath())); + } + } + std::sort(names.begin(), names.end()); + return names; + } + + protected: + static constexpr const char* kFormat = "orc"; + + std::shared_ptr schema_; + std::unique_ptr data_dir_; + std::unique_ptr tmp_dir_; + std::shared_ptr io_manager_; + std::shared_ptr path_factory_; + AppendOnlyWriter::FilesReaderFactory files_reader_factory_; +}; + +TEST_F(AppendOnlyWriterBufferTest, TestSpillAndReplayOnPrepareCommit) { + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + /*use_write_buffer=*/true, io_manager_); + const AppendWriteBuffer* buffer = writer->GetWriteBuffer(); + ASSERT_NE(nullptr, buffer); + ASSERT_TRUE(buffer->IsSpillable()); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10], [2, 20]]"))); + ASSERT_GT(writer->GetMemoryUsage(), 0); + + // Under memory pressure the rows are spilled to a temporary file, not written as data files. + ASSERT_OK(writer->FlushMemory()); + ASSERT_EQ(0, writer->GetMemoryUsage()); + std::vector channels = buffer->GetSpillChannels(); + ASSERT_EQ(1, channels.size()); + ASSERT_TRUE(AnySpillFileExists(channels)); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[3, 30]]"))); + ASSERT_GT(writer->GetMemoryUsage(), 0); + + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + ASSERT_EQ(1, inc.GetNewFilesIncrement().NewFiles().size()); + ASSERT_EQ(std::vector({1, 2, 3}), ReadNewFileIds(inc)); + ASSERT_FALSE(buffer->HasData()); + ASSERT_EQ(0, writer->GetMemoryUsage()); + ASSERT_FALSE(AnySpillFileExists(channels)); + ASSERT_OK(writer->Close()); +} + +TEST_F(AppendOnlyWriterBufferTest, TestMemoryUsageCountsImportedBufferRanges) { + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + /*use_write_buffer=*/true, /*io_manager=*/nullptr); + constexpr int32_t kRows = 1000; + arrow::Int32Builder id_builder; + arrow::Int64Builder v_builder; + for (int32_t i = 0; i < kRows; ++i) { + ASSERT_TRUE(id_builder.Append(i).ok()); + ASSERT_TRUE(v_builder.Append(i * 10).ok()); + } + std::shared_ptr ids = id_builder.Finish().ValueOrDie(); + std::shared_ptr values = v_builder.Finish().ValueOrDie(); + // Writes a batch whose columns are one-row slices of the larger columns at `offset`. + auto write_slice = [&](int64_t offset) -> Status { + std::shared_ptr struct_array = + arrow::StructArray::Make({ids->Slice(offset, 1), values->Slice(offset, 1)}, + schema_->fields()) + .ValueOrDie(); + ::ArrowArray c_array; + if (!arrow::ExportArray(*struct_array, &c_array).ok()) { + return Status::Invalid("failed to export the batch"); + } + RecordBatchBuilder batch_builder(&c_array); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr batch, batch_builder.Finish()); + return writer->Write(std::move(batch)); + }; + const uint64_t column_bytes = kRows * (sizeof(int32_t) + sizeof(int64_t)); + + // The C data interface does not carry the allocated capacity: imported buffers end at the + // last row of the batch. Slices at the start of the columns keep both columns alive but + // count only their own row. + ASSERT_OK(write_slice(/*offset=*/0)); + uint64_t first_usage = writer->GetMemoryUsage(); + ASSERT_GT(first_usage, 0); + ASSERT_LT(first_usage, column_bytes / 10); + // Slices at the end of the columns count every row before them as well. + ASSERT_OK(write_slice(/*offset=*/kRows - 1)); + ASSERT_GE(writer->GetMemoryUsage() - first_usage, column_bytes); + + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + ASSERT_EQ(std::vector({0, kRows - 1}), ReadNewFileIds(inc)); + ASSERT_OK(writer->Close()); +} + +TEST_F(AppendOnlyWriterBufferTest, TestNonSpillableBufferFlushesDataFiles) { + for (bool spill_directory_unavailable : {false, true}) { + SCOPED_TRACE(::testing::Message() + << "spill_directory_unavailable=" << spill_directory_unavailable); + data_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(data_dir_); + auto writer = + CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + /*use_write_buffer=*/true, + spill_directory_unavailable ? CreateUnavailableIOManager() : nullptr); + ASSERT_NE(nullptr, writer->GetWriteBuffer()); + ASSERT_EQ(spill_directory_unavailable, writer->GetWriteBuffer()->IsSpillable()); + + // A buffer whose spill directory cannot be created still has every row, so it flushes + // them to a data file and stops spilling. + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10]]"))); + ASSERT_OK(writer->FlushMemory()); + ASSERT_EQ(0, writer->GetMemoryUsage()); + ASSERT_FALSE(writer->GetWriteBuffer()->HasData()); + ASSERT_FALSE(writer->GetWriteBuffer()->IsSpillable()); + ASSERT_EQ(1, ListDataFileNames().size()); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[2, 20]]"))); + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + ASSERT_EQ(2, inc.GetNewFilesIncrement().NewFiles().size()); + ASSERT_EQ(std::vector({1, 2}), ReadNewFileIds(inc)); + ASSERT_EQ(2, ListDataFileNames().size()); + ASSERT_OK(writer->Close()); + } +} + +TEST_F(AppendOnlyWriterBufferTest, TestFlushDataFilesWhenSpillBudgetExhausted) { + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}, + {Options::WRITE_BUFFER_SPILL_MAX_DISK_SIZE, "1b"}}), + /*use_write_buffer=*/true, io_manager_); + const AppendWriteBuffer* buffer = writer->GetWriteBuffer(); + ASSERT_NE(nullptr, buffer); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10]]"))); + ASSERT_OK(writer->FlushMemory()); + std::vector channels = buffer->GetSpillChannels(); + ASSERT_EQ(1, channels.size()); + + // The spill budget is used up, so the next flush writes the spilled and in-memory rows to a + // data file and releases the spill file. + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[2, 20]]"))); + ASSERT_OK(writer->FlushMemory()); + ASSERT_EQ(0, writer->GetMemoryUsage()); + ASSERT_FALSE(buffer->HasData()); + ASSERT_FALSE(AnySpillFileExists(channels)); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[3, 30]]"))); + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + ASSERT_EQ(2, inc.GetNewFilesIncrement().NewFiles().size()); + ASSERT_EQ(std::vector({1, 2, 3}), ReadNewFileIds(inc)); + ASSERT_OK(writer->Close()); +} + +TEST_F(AppendOnlyWriterBufferTest, TestSwitchToSpillableBuffer) { + for (bool use_write_buffer : {false, true}) { + SCOPED_TRACE(::testing::Message() << "use_write_buffer=" << use_write_buffer); + data_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(data_dir_); + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + use_write_buffer, /*io_manager=*/nullptr); + const AppendWriteBuffer* original_buffer = writer->GetWriteBuffer(); + ASSERT_EQ(use_write_buffer, original_buffer != nullptr); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10], [2, 20]]"))); + if (use_write_buffer) { + ASSERT_GT(writer->GetMemoryUsage(), 0); + } else { + ASSERT_EQ(0, writer->GetMemoryUsage()); + } + + ASSERT_OK(writer->SwitchToSpillableBuffer(io_manager_, /*check_memory=*/nullptr)); + const AppendWriteBuffer* buffer = writer->GetWriteBuffer(); + ASSERT_NE(nullptr, buffer); + ASSERT_TRUE(buffer->IsSpillable()); + if (use_write_buffer) { + // An existing buffer is reused and keeps its rows. + ASSERT_EQ(original_buffer, buffer); + } + // Rows written directly before the switch are read back into the buffer, and their data + // file is deleted. + ASSERT_GT(writer->GetMemoryUsage(), 0); + ASSERT_TRUE(ListDataFileNames().empty()); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[3, 30]]"))); + ASSERT_OK(writer->FlushMemory()); + ASSERT_EQ(1, buffer->GetSpillChannels().size()); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[4, 40]]"))); + + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + // Every row goes to one data file, in write order. + const auto& new_files = inc.GetNewFilesIncrement().NewFiles(); + ASSERT_EQ(1, new_files.size()); + ASSERT_EQ(std::vector({1, 2, 3, 4}), ReadNewFileIds(inc)); + ASSERT_EQ(std::vector({new_files[0]->file_name}), ListDataFileNames()); + ASSERT_OK(writer->Close()); + } +} + +TEST_F(AppendOnlyWriterBufferTest, TestSwitchFlushesRowsReadBack) { + enum class FlushBy { kSpill, kDataFile, kCheckMemory }; + for (FlushBy flush_by : {FlushBy::kSpill, FlushBy::kDataFile, FlushBy::kCheckMemory}) { + SCOPED_TRACE(::testing::Message() << "flush_by=" << static_cast(flush_by)); + data_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(data_dir_); + // Rolls a data file every two rows, so the rows come back in several batches, each + // flushed at write-buffer-size or when `check_memory` releases it: by spilling, or by + // writing data files once the first spill file uses up the disk budget. + std::map options = {{Options::FILE_FORMAT, kFormat}, + {Options::TARGET_FILE_ROW_NUM, "2"}}; + if (flush_by != FlushBy::kCheckMemory) { + options[Options::WRITE_BUFFER_SIZE] = "1b"; + } + if (flush_by == FlushBy::kDataFile) { + options[Options::WRITE_BUFFER_SPILL_MAX_DISK_SIZE] = "1b"; + } + auto writer = CreateWriter(CreateOptions(options), /*use_write_buffer=*/false, + /*io_manager=*/nullptr); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10], [2, 20]]"))); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[3, 30], [4, 40]]"))); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[5, 50]]"))); + + // Stands in for the write memory manager, which may flush this writer after each batch. + std::vector memory_usages; + auto check_memory = [&]() -> Status { + memory_usages.push_back(writer->GetMemoryUsage()); + return flush_by == FlushBy::kCheckMemory ? writer->FlushMemory() : Status::OK(); + }; + ASSERT_OK(writer->SwitchToSpillableBuffer(io_manager_, check_memory)); + // Called with each batch in the buffer, before the next one is read back. + ASSERT_GE(memory_usages.size(), 3); + for (uint64_t memory_usage : memory_usages) { + ASSERT_EQ(flush_by == FlushBy::kCheckMemory, memory_usage > 0); + } + const AppendWriteBuffer* buffer = writer->GetWriteBuffer(); + ASSERT_NE(nullptr, buffer); + ASSERT_EQ(0, writer->GetMemoryUsage()); + std::vector channels = buffer->GetSpillChannels(); + ASSERT_FALSE(channels.empty()); + // Only the data files flushed while reading back are left. + ASSERT_EQ(flush_by == FlushBy::kDataFile, !ListDataFileNames().empty()); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[6, 60]]"))); + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + ASSERT_EQ(std::vector({1, 2, 3, 4, 5, 6}), ReadNewFileIds(inc)); + // The data files read back are deleted, so only the committed ones remain. + std::vector new_file_names; + for (const auto& file : inc.GetNewFilesIncrement().NewFiles()) { + new_file_names.push_back(file->file_name); + } + std::sort(new_file_names.begin(), new_file_names.end()); + ASSERT_EQ(new_file_names, ListDataFileNames()); + ASSERT_FALSE(AnySpillFileExists(channels)); + ASSERT_OK(writer->Close()); + } +} + +TEST_F(AppendOnlyWriterBufferTest, TestSwitchWithoutReaderKeepsWritingDataFiles) { + files_reader_factory_ = nullptr; + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + /*use_write_buffer=*/false, /*io_manager=*/nullptr); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10]]"))); + + ASSERT_OK(writer->SwitchToSpillableBuffer(io_manager_, /*check_memory=*/nullptr)); + ASSERT_EQ(nullptr, writer->GetWriteBuffer()); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[2, 20]]"))); + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + ASSERT_EQ(1, inc.GetNewFilesIncrement().NewFiles().size()); + ASSERT_EQ(std::vector({1, 2}), ReadNewFileIds(inc)); + ASSERT_OK(writer->Close()); +} + +TEST_F(AppendOnlyWriterBufferTest, TestSwitchFailsAndDeletesDataFilesWhenReadBackFails) { + // Hands over every row, then fails, so the rows read so far must not be committed again. + class FailAtEofBatchReader : public BatchReader { + public: + explicit FailAtEofBatchReader(std::unique_ptr reader) + : reader_(std::move(reader)) {} + Result NextBatch() override { + PAIMON_ASSIGN_OR_RAISE(ReadBatch batch, reader_->NextBatch()); + if (IsEofBatch(batch)) { + return Status::IOError("read back failed"); + } + return batch; + } + std::shared_ptr GetReaderMetrics() const override { + return reader_->GetReaderMetrics(); + } + void Close() override { + reader_->Close(); + } + + private: + std::unique_ptr reader_; + }; + + enum class FailAt { kOpen, kRead, kCheckMemory }; + for (FailAt fail_at : {FailAt::kOpen, FailAt::kRead, FailAt::kCheckMemory}) { + SCOPED_TRACE(::testing::Message() << "fail_at=" << static_cast(fail_at)); + data_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(data_dir_); + files_reader_factory_ = [this, + fail_at](const std::vector>& files) + -> Result> { + if (fail_at == FailAt::kOpen) { + return Status::IOError("open failed"); + } + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, ReadDataFiles(files)); + if (fail_at == FailAt::kCheckMemory) { + return reader; + } + return std::make_unique(std::move(reader)); + }; + // Spills while reading back, so Close() must delete the spill files of the failed writer. + auto writer = CreateWriter( + CreateOptions({{Options::FILE_FORMAT, kFormat}, {Options::WRITE_BUFFER_SIZE, "1b"}}), + /*use_write_buffer=*/false, /*io_manager=*/nullptr); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10], [2, 20]]"))); + + // As in Paimon Java, the data file is deleted although its rows were not read back, and + // the writer fails instead of committing without them or with them twice. + const std::string expected_error = fail_at == FailAt::kOpen ? "open failed" + : fail_at == FailAt::kRead ? "read back failed" + : "check memory failed"; + auto check_memory = [fail_at]() -> Status { + return fail_at == FailAt::kCheckMemory ? Status::IOError("check memory failed") + : Status::OK(); + }; + ASSERT_NOK_WITH_MSG(writer->SwitchToSpillableBuffer(io_manager_, check_memory), + expected_error); + ASSERT_TRUE(ListDataFileNames().empty()); + ASSERT_NOK_WITH_MSG(writer->Write(CreateBatch(schema_, "[[3, 30]]")), expected_error); + ASSERT_NOK_WITH_MSG(writer->PrepareCommit(/*wait_compaction=*/true), expected_error); + std::vector channels = writer->GetWriteBuffer()->GetSpillChannels(); + ASSERT_OK(writer->Close()); + ASSERT_TRUE(ListDataFileNames().empty()); + ASSERT_FALSE(AnySpillFileExists(channels)); + } +} + +TEST_F(AppendOnlyWriterBufferTest, TestRetryFailedReplayDoesNotDuplicateRows) { + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + /*use_write_buffer=*/true, io_manager_); + const AppendWriteBuffer* buffer = writer->GetWriteBuffer(); + ASSERT_NE(nullptr, buffer); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10]]"))); + ASSERT_OK(writer->FlushMemory()); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[2, 20]]"))); + ASSERT_OK(writer->FlushMemory()); + std::vector channels = buffer->GetSpillChannels(); + ASSERT_EQ(2, channels.size()); + + // Hide the second spill file, so the replay fails after the rows of the first one were + // written to a data file. + std::shared_ptr fs = tmp_dir_->GetFileSystem(); + const std::string spill_path = channels[1].GetPath(); + const std::string hidden_path = spill_path + ".hidden"; + ASSERT_OK(fs->Rename(spill_path, hidden_path)); + ASSERT_FALSE(writer->PrepareCommit(/*wait_compaction=*/true).ok()); + // The partial data file is discarded and the buffer keeps every row for the retry. + ASSERT_TRUE(ListDataFileNames().empty()); + ASSERT_TRUE(buffer->HasData()); + ASSERT_EQ(2, buffer->GetSpillChannels().size()); + + ASSERT_OK(fs->Rename(hidden_path, spill_path)); + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + const auto& new_files = inc.GetNewFilesIncrement().NewFiles(); + ASSERT_EQ(1, new_files.size()); + ASSERT_EQ(std::vector({1, 2}), ReadNewFileIds(inc)); + ASSERT_EQ(std::vector({new_files[0]->file_name}), ListDataFileNames()); + ASSERT_FALSE(buffer->HasData()); + ASSERT_FALSE(AnySpillFileExists(channels)); + ASSERT_OK(writer->Close()); +} + +TEST_F(AppendOnlyWriterBufferTest, TestCloseDeletesSpillAndUncommittedDataFiles) { + for (bool sync_fails : {false, true}) { + SCOPED_TRACE(::testing::Message() << "sync_fails=" << sync_fails); + data_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(data_dir_); + auto compact_manager = std::make_shared(); + compact_manager_ = compact_manager; + // A buffer that cannot spill flushes the rows written so far as a data file of the + // pending commit, then the switch lets it spill. + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + /*use_write_buffer=*/true, /*io_manager=*/nullptr); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10], [2, 20]]"))); + ASSERT_OK(writer->FlushMemory()); + ASSERT_EQ(1, ListDataFileNames().size()); + ASSERT_OK(writer->SwitchToSpillableBuffer(io_manager_, /*check_memory=*/nullptr)); + + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[3, 30]]"))); + ASSERT_OK(writer->FlushMemory()); + std::vector channels = writer->GetWriteBuffer()->GetSpillChannels(); + ASSERT_EQ(1, channels.size()); + ASSERT_TRUE(AnySpillFileExists(channels)); + + // Closing without PrepareCommit() leaves neither the data file nor the spill file + // behind, even when the compaction sync fails. + if (sync_fails) { + compact_manager->queued_results.emplace_back(Status::IOError("sync failed")); + ASSERT_NOK_WITH_MSG(writer->Close(), "sync failed"); + } else { + ASSERT_OK(writer->Close()); + } + ASSERT_TRUE(ListDataFileNames().empty()); + ASSERT_FALSE(AnySpillFileExists(channels)); + } +} + +TEST_F(AppendOnlyWriterBufferTest, TestFlushTracksDataFilesWhenCompactionSyncFails) { + auto compact_manager = std::make_shared(); + compact_manager->queued_results.emplace_back(Status::IOError("sync failed")); + compact_manager_ = compact_manager; + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + /*use_write_buffer=*/true, /*io_manager=*/nullptr); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10], [2, 20]]"))); + + // The data file is closed and the buffer cleared before the compaction sync fails, so the + // retry must still commit the file. + ASSERT_NOK_WITH_MSG(writer->PrepareCommit(/*wait_compaction=*/true), "sync failed"); + ASSERT_FALSE(writer->GetWriteBuffer()->HasData()); + ASSERT_OK_AND_ASSIGN(CommitIncrement inc, writer->PrepareCommit(/*wait_compaction=*/true)); + ASSERT_EQ(std::vector({1, 2}), ReadNewFileIds(inc)); + ASSERT_OK(writer->Close()); +} + +TEST_F(AppendOnlyWriterBufferTest, TestRetryPrepareCommitAfterDataFileCloseFails) { + auto io_hook = IOHook::GetInstance(); + for (bool use_write_buffer : {false, true}) { + SCOPED_TRACE(::testing::Message() << "use_write_buffer=" << use_write_buffer); + bool close_failed = false; + bool committed = false; + for (int64_t pos = 0; pos < 200 && !committed; ++pos) { + SCOPED_TRACE(::testing::Message() << "io error position=" << pos); + data_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(data_dir_); + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + use_write_buffer, /*io_manager=*/nullptr); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10], [2, 20]]"))); + + io_hook->Reset(pos, IOHook::Mode::RETURN_ERROR); + Result inc = writer->PrepareCommit(/*wait_compaction=*/true); + io_hook->Clear(); + if (inc.ok()) { + ASSERT_EQ(std::vector({1, 2}), ReadNewFileIds(inc.value())); + committed = true; + } else if (use_write_buffer) { + // The buffer keeps every row, so the retry commits them exactly once. + ASSERT_OK_AND_ASSIGN(CommitIncrement retry, + writer->PrepareCommit(/*wait_compaction=*/true)); + ASSERT_EQ(std::vector({1, 2}), ReadNewFileIds(retry)); + close_failed = true; + } else { + // The rows existed only in the discarded data file, so the retry fails instead + // of committing without them. + ASSERT_NOK_WITH_MSG(writer->PrepareCommit(/*wait_compaction=*/true), + "Append-only writer failed after accepting rows"); + close_failed = true; + } + ASSERT_OK(writer->Close()); + } + ASSERT_TRUE(close_failed); + ASSERT_TRUE(committed); + } +} + +TEST_F(AppendOnlyWriterBufferTest, TestFailedSpillFailsWriter) { + auto writer = CreateWriter(CreateOptions({{Options::FILE_FORMAT, kFormat}}), + /*use_write_buffer=*/true, io_manager_); + ASSERT_OK(writer->Write(CreateBatch(schema_, "[[1, 10]]"))); + ASSERT_OK_AND_ASSIGN(std::string spill_dir, io_manager_->GetSpillDir()); + + // Creating the spill file fails although its directory exists. The batch was accepted + // before, so flushing again, retrying it or committing must fail rather than commit the row + // twice. + auto io_hook = IOHook::GetInstance(); + io_hook->Reset(0, IOHook::Mode::RETURN_ERROR); + Status status = writer->FlushMemory(); + io_hook->Clear(); + ASSERT_NOK_WITH_MSG(status, "io hook triggered io error"); + const std::string writer_failed = "Append-only writer failed after accepting rows"; + ASSERT_NOK_WITH_MSG(writer->FlushMemory(), writer_failed); + ASSERT_NOK_WITH_MSG(writer->Write(CreateBatch(schema_, "[[1, 10]]")), writer_failed); + ASSERT_NOK_WITH_MSG(writer->PrepareCommit(/*wait_compaction=*/true), writer_failed); ASSERT_OK(writer->Close()); + ASSERT_TRUE(ListDataFileNames().empty()); + std::vector spill_files; + ASSERT_OK(tmp_dir_->GetFileSystem()->ListDir(spill_dir, &spill_files)); + ASSERT_TRUE(spill_files.empty()); } /// Parameterized test class for shared-shredding tests, parameterized by file format. @@ -1520,7 +2116,8 @@ TEST_P(AppendOnlyWriterShreddingTest, TestSharedShreddingMapFirstFileUsesConfigu auto writer = std::make_unique( options, /*schema_id=*/0, logical_schema, /*write_cols=*/std::nullopt, - /*max_sequence_number=*/-1, path_factory, compact_manager_, memory_pool_); + /*max_sequence_number=*/-1, path_factory, compact_manager_, /*use_write_buffer=*/false, + /*io_manager=*/nullptr, /*enable_multi_thread_spill=*/false, nullptr, memory_pool_); auto batch = CreateBatch(logical_schema, R"([ [1, [["a", 10], ["b", 20], ["c", 30]]] diff --git a/src/paimon/core/append/append_write_buffer.cpp b/src/paimon/core/append/append_write_buffer.cpp new file mode 100644 index 000000000..1b9ba7211 --- /dev/null +++ b/src/paimon/core/append/append_write_buffer.cpp @@ -0,0 +1,195 @@ +/* + * 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 "paimon/core/append/append_write_buffer.h" + +#include +#include + +#include "arrow/array/array_nested.h" +#include "arrow/record_batch.h" +#include "arrow/type.h" +#include "arrow/util/byte_size.h" +#include "paimon/common/utils/arrow/mem_utils.h" +#include "paimon/common/utils/checked_cast.h" +#include "paimon/common/utils/scope_guard.h" +#include "paimon/core/core_options.h" +#include "paimon/core/disk/io_manager.h" +#include "paimon/core/io/arrow_ipc_file.h" +#include "paimon/core/mergetree/spill_channel_manager.h" +#include "paimon/core/mergetree/spill_writer.h" +#include "paimon/logging.h" + +namespace paimon { + +AppendWriteBuffer::AppendWriteBuffer(const CoreOptions& options, + const std::shared_ptr& schema, + const std::shared_ptr& io_manager, + bool enable_multi_thread_spill, + const std::shared_ptr& pool) + : fs_(options.GetFileSystem()), + max_disk_size_(options.GetWriteBufferSpillMaxDiskSize()), + spill_compress_options_(options.GetSpillCompressOptions()), + spill_schema_(arrow::schema({arrow::field("row", arrow::struct_(schema->fields()))})), + io_manager_(io_manager), + enable_multi_thread_spill_(enable_multi_thread_spill), + pool_(pool), + arrow_pool_(GetArrowPool(pool)), + spill_channel_manager_(std::make_shared(fs_, /*initial_capacity=*/0)), + logger_(Logger::GetLogger("AppendWriteBuffer")) {} + +AppendWriteBuffer::~AppendWriteBuffer() { + Clear(); +} + +void AppendWriteBuffer::Write(const std::shared_ptr& batch) { + if (batch->length() == 0) { + return; + } + memory_usage_ += static_cast(arrow::util::TotalBufferSize(*batch->data())); + in_memory_batches_.push_back(batch); +} + +void AppendWriteBuffer::EnableSpill(const std::shared_ptr& io_manager) { + if (io_manager_ == nullptr) { + io_manager_ = io_manager; + } +} + +Result AppendWriteBuffer::TrySpill() { + if (!IsSpillable() || disk_usage_ >= max_disk_size_) { + return false; + } + if (in_memory_batches_.empty()) { + return true; + } + if (channel_enumerator_ == nullptr) { + Result> enumerator = + io_manager_->CreateChannelEnumerator(); + if (!enumerator.ok()) { + // Nothing was written yet, so the buffered rows can still go to data files. + PAIMON_LOG_WARN(logger_, + "Cannot create the spill directory under %s, so the write buffer " + "stops spilling and flushes data files instead: %s", + io_manager_->GetTempDir().c_str(), + enumerator.status().ToString().c_str()); + io_manager_.reset(); + return false; + } + channel_enumerator_ = std::move(enumerator).value(); + } + PAIMON_RETURN_NOT_OK(Spill()); + return true; +} + +Status AppendWriteBuffer::Spill() { + PAIMON_ASSIGN_OR_RAISE( + std::unique_ptr spill_writer, + SpillWriter::Create(fs_, spill_schema_, channel_enumerator_, spill_channel_manager_, + spill_compress_options_.compress, spill_compress_options_.zstd_level, + enable_multi_thread_spill_, pool_)); + auto cleanup_guard = ScopeGuard([&]() { + const FileIOChannel::ID& channel_id = spill_writer->GetChannelId(); + if (!DeleteSpillFile(channel_id)) { + // Clear() deletes it again. Its size may be unknown, so it is not counted. + undeleted_spill_files_.push_back(FileChannelInfo{channel_id, /*file_size=*/0}); + } + }); + for (const std::shared_ptr& batch : in_memory_batches_) { + std::shared_ptr record_batch = + arrow::RecordBatch::Make(spill_schema_, batch->length(), {batch}); + PAIMON_RETURN_NOT_OK(spill_writer->WriteBatch(record_batch)); + } + PAIMON_RETURN_NOT_OK(spill_writer->Close()); + PAIMON_ASSIGN_OR_RAISE(int64_t file_size, spill_writer->GetFileSize()); + cleanup_guard.Release(); + + spill_files_.push_back(FileChannelInfo{spill_writer->GetChannelId(), file_size}); + disk_usage_ += file_size; + PAIMON_LOG_DEBUG(logger_, + "Spilled %zu batches (%lu bytes in memory) to %s (%ld bytes), " + "%zu spill files use %ld bytes", + in_memory_batches_.size(), memory_usage_, + spill_writer->GetChannelId().GetPath().c_str(), file_size, spill_files_.size(), + disk_usage_); + in_memory_batches_.clear(); + memory_usage_ = 0; + return Status::OK(); +} + +Status AppendWriteBuffer::Replay(const Consumer& consumer) const { + for (const FileChannelInfo& spill_file : spill_files_) { + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, + ArrowIpcFileReader::Open(fs_, spill_file.channel_id.GetPath(), + enable_multi_thread_spill_, arrow_pool_)); + for (int32_t i = 0; i < reader->GetRecordBatchCount(); ++i) { + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr record_batch, + reader->ReadRecordBatch(i)); + if (record_batch->num_columns() != 1 || + !record_batch->column(0)->type()->Equals(spill_schema_->field(0)->type())) { + return Status::Invalid("Spill file ", spill_file.channel_id.GetPath(), + " does not match the write buffer schema: ", + record_batch->schema()->ToString()); + } + PAIMON_RETURN_NOT_OK( + consumer(checked_pointer_cast(record_batch->column(0)))); + } + reader->Close(); + } + for (const std::shared_ptr& batch : in_memory_batches_) { + PAIMON_RETURN_NOT_OK(consumer(batch)); + } + return Status::OK(); +} + +void AppendWriteBuffer::Clear() { + in_memory_batches_.clear(); + memory_usage_ = 0; + undeleted_spill_files_.insert(undeleted_spill_files_.end(), spill_files_.begin(), + spill_files_.end()); + spill_files_.clear(); + std::vector remaining; + disk_usage_ = 0; + for (const FileChannelInfo& spill_file : undeleted_spill_files_) { + if (!DeleteSpillFile(spill_file.channel_id)) { + remaining.push_back(spill_file); + disk_usage_ += spill_file.file_size; + } + } + undeleted_spill_files_ = std::move(remaining); +} + +bool AppendWriteBuffer::DeleteSpillFile(const FileIOChannel::ID& channel_id) const { + Status status = spill_channel_manager_->DeleteChannel(channel_id); + if (!status.ok()) { + PAIMON_LOG_WARN(logger_, "Failed to delete spill file %s: %s", channel_id.GetPath().c_str(), + status.ToString().c_str()); + } + return status.ok(); +} + +std::vector AppendWriteBuffer::GetSpillChannels() const { + std::vector channels; + channels.reserve(spill_files_.size()); + for (const FileChannelInfo& spill_file : spill_files_) { + channels.push_back(spill_file.channel_id); + } + return channels; +} + +} // namespace paimon diff --git a/src/paimon/core/append/append_write_buffer.h b/src/paimon/core/append/append_write_buffer.h new file mode 100644 index 000000000..0ecb5c247 --- /dev/null +++ b/src/paimon/core/append/append_write_buffer.h @@ -0,0 +1,149 @@ +/* + * 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 "paimon/core/disk/file_io_channel.h" +#include "paimon/core/options/compress_options.h" +#include "paimon/result.h" +#include "paimon/status.h" + +namespace arrow { +class MemoryPool; +class Schema; +class StructArray; +} // namespace arrow + +namespace paimon { + +class CoreOptions; +class FileSystem; +class IOManager; +class Logger; +class MemoryPool; +class SpillChannelManager; + +/// Buffers the batches written to an append-only writer until they are flushed to data files. +/// +/// Batches are kept in memory and their size is reported to the write memory manager. When the +/// buffer has temporary spill storage, `TrySpill()` moves the in-memory batches to a temporary +/// Arrow IPC file instead of producing data files. `Replay()` returns every buffered batch in write +/// order: spilled batches first, then the batches still in memory. +/// @note This class is not thread-safe. +class AppendWriteBuffer { + public: + using Consumer = std::function&)>; + + /// @param schema Schema of the buffered batches. + /// @param io_manager Temporary storage for spill files, or nullptr to keep batches in memory + /// only. + /// @param enable_multi_thread_spill Whether spill files are written and read with threads. + AppendWriteBuffer(const CoreOptions& options, const std::shared_ptr& schema, + const std::shared_ptr& io_manager, bool enable_multi_thread_spill, + const std::shared_ptr& pool); + ~AppendWriteBuffer(); + + AppendWriteBuffer(const AppendWriteBuffer&) = delete; + AppendWriteBuffer& operator=(const AppendWriteBuffer&) = delete; + + /// Adds a batch whose type is a struct of the buffer schema's fields. Empty batches are + /// skipped. + void Write(const std::shared_ptr& batch); + + /// Returns the estimated in-memory size of the buffered batches in bytes, i.e. the size of the + /// Arrow buffers they reference, counting a shared buffer once per batch. + uint64_t GetMemoryUsage() const { + return memory_usage_; + } + + /// Whether `TrySpill()` may spill batches to temporary files. + bool IsSpillable() const { + return io_manager_ != nullptr; + } + + /// Enables spilling to the given temporary storage. Batches already in memory are kept. + void EnableSpill(const std::shared_ptr& io_manager); + + bool HasData() const { + return !in_memory_batches_.empty() || !spill_files_.empty(); + } + + /// Spills the in-memory batches to a temporary file. + /// + /// @return true when the in-memory batches were spilled or there were none; false, without + /// spilling, when the buffer cannot spill, the spill files have already reached + /// `write-buffer-spill.max-disk-size`, or the spill directory cannot be created, which + /// also stops later spills. The caller must then flush the buffer to data files. A + /// failure to write or close the spill file is returned as an error. + Result TrySpill(); + + /// Passes every buffered batch to `consumer` in write order. The buffer is left unchanged, so + /// the caller decides when to `Clear()` it. + Status Replay(const Consumer& consumer) const; + + /// Drops the buffered batches and deletes the spill files. A spill file that fails to be + /// deleted keeps counting toward the disk usage and is deleted again by the next `Clear()`, + /// but its rows are no longer replayed. Also retries deleting the partial file of a failed + /// spill. + void Clear(); + + /// Returns the total size of the spill files on disk in bytes, including those that failed to + /// be deleted. + int64_t GetDiskUsage() const { + return disk_usage_; + } + + /// Returns the current spill files in write order. + std::vector GetSpillChannels() const; + + private: + Status Spill(); + /// @return Whether the spill file was deleted. + bool DeleteSpillFile(const FileIOChannel::ID& channel_id) const; + + std::shared_ptr fs_; + int64_t max_disk_size_; + CompressOptions spill_compress_options_; + // Spill files hold each batch as a single struct column, so the batch keeps its own validity + // bitmap, i.e. rows that are null at the top level. + std::shared_ptr spill_schema_; + std::shared_ptr io_manager_; + const bool enable_multi_thread_spill_; + std::shared_ptr pool_; + // Batches read back from spill files keep only a raw pointer to their allocation pool, and the + // data file writer may hold them until it is closed. Keep the adapter alive with the buffer. + std::shared_ptr arrow_pool_; + std::shared_ptr channel_enumerator_; + std::shared_ptr spill_channel_manager_; + + std::vector> in_memory_batches_; + std::vector spill_files_; + // Spill files that failed to be deleted and are never replayed: files whose rows were dropped + // and partial files of failed spills. + std::vector undeleted_spill_files_; + uint64_t memory_usage_ = 0; + int64_t disk_usage_ = 0; + std::unique_ptr logger_; +}; + +} // namespace paimon diff --git a/src/paimon/core/append/append_write_buffer_test.cpp b/src/paimon/core/append/append_write_buffer_test.cpp new file mode 100644 index 000000000..f578e1935 --- /dev/null +++ b/src/paimon/core/append/append_write_buffer_test.cpp @@ -0,0 +1,334 @@ +/* + * 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 "paimon/core/append/append_write_buffer.h" + +#include +#include +#include +#include + +#include "arrow/api.h" +#include "arrow/array/concatenate.h" +#include "arrow/ipc/json_simple.h" +#include "gtest/gtest.h" +#include "paimon/common/factories/io_hook.h" +#include "paimon/common/utils/arrow/status_utils.h" +#include "paimon/common/utils/checked_cast.h" +#include "paimon/core/core_options.h" +#include "paimon/core/disk/io_manager.h" +#include "paimon/defs.h" +#include "paimon/fs/file_system.h" +#include "paimon/memory/memory_pool.h" +#include "paimon/testing/utils/testharness.h" + +namespace paimon::test { + +class AppendWriteBufferTest : public testing::Test { + public: + void SetUp() override { + pool_ = GetDefaultPool(); + schema_ = arrow::schema( + {arrow::field("id", arrow::int32()), arrow::field("name", arrow::utf8())}); + tmp_dir_ = UniqueTestDirectory::Create(); + ASSERT_TRUE(tmp_dir_); + io_manager_ = std::make_shared(tmp_dir_->Str(), tmp_dir_->GetFileSystem()); + } + + CoreOptions CreateOptions(const std::map& overrides = {}) const { + std::map raw_options = {{Options::FILE_SYSTEM, "local"}}; + for (const auto& [key, value] : overrides) { + raw_options[key] = value; + } + return CoreOptions::FromMap(raw_options).value(); + } + + std::shared_ptr MakeBatch(const std::string& json) const { + auto array = + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(schema_->fields()), json) + .ValueOrDie(); + return checked_pointer_cast(array); + } + + Result> ReplayAll(const AppendWriteBuffer& buffer) const { + arrow::ArrayVector batches; + PAIMON_RETURN_NOT_OK( + buffer.Replay([&batches](const std::shared_ptr& batch) -> Status { + batches.push_back(batch); + return Status::OK(); + })); + if (batches.empty()) { + return std::shared_ptr(); + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr result, + arrow::Concatenate(batches)); + return result; + } + + Result AllExist(const std::vector& channels) const { + for (const FileIOChannel::ID& channel : channels) { + PAIMON_ASSIGN_OR_RAISE(bool exist, + tmp_dir_->GetFileSystem()->Exists(channel.GetPath())); + if (!exist) { + return false; + } + } + return true; + } + + Result AnyExist(const std::vector& channels) const { + for (const FileIOChannel::ID& channel : channels) { + PAIMON_ASSIGN_OR_RAISE(bool exist, + tmp_dir_->GetFileSystem()->Exists(channel.GetPath())); + if (exist) { + return true; + } + } + return false; + } + + /// Returns the paths of the files in the spill directory. + Result> ListSpillFiles() const { + PAIMON_ASSIGN_OR_RAISE(std::string spill_dir, io_manager_->GetSpillDir()); + std::vector statuses; + PAIMON_RETURN_NOT_OK(tmp_dir_->GetFileSystem()->ListDir(spill_dir, &statuses)); + std::vector files; + for (const BasicFileStatus& status : statuses) { + if (!status.IsDir()) { + files.push_back(status.GetPath()); + } + } + return files; + } + + protected: + std::shared_ptr pool_; + std::shared_ptr schema_; + std::unique_ptr tmp_dir_; + std::shared_ptr io_manager_; +}; + +TEST_F(AppendWriteBufferTest, TestInMemoryBufferAndEnableSpill) { + AppendWriteBuffer buffer(CreateOptions(), schema_, /*io_manager=*/nullptr, + /*enable_multi_thread_spill=*/false, pool_); + ASSERT_FALSE(buffer.IsSpillable()); + ASSERT_FALSE(buffer.HasData()); + ASSERT_EQ(0, buffer.GetMemoryUsage()); + + // Empty batches are not buffered. + buffer.Write(MakeBatch("[]")); + ASSERT_FALSE(buffer.HasData()); + + buffer.Write(MakeBatch(R"([[1, "a"], [2, "b"]])")); + ASSERT_TRUE(buffer.HasData()); + ASSERT_GT(buffer.GetMemoryUsage(), 0); + + ASSERT_OK_AND_ASSIGN(bool spill_handled, buffer.TrySpill()); + ASSERT_FALSE(spill_handled); + ASSERT_GT(buffer.GetMemoryUsage(), 0); + ASSERT_TRUE(buffer.GetSpillChannels().empty()); + + // Enabling spill keeps the buffered rows and spills them on the next flush. + buffer.EnableSpill(io_manager_); + ASSERT_TRUE(buffer.IsSpillable()); + ASSERT_OK_AND_ASSIGN(spill_handled, buffer.TrySpill()); + ASSERT_TRUE(spill_handled); + ASSERT_EQ(0, buffer.GetMemoryUsage()); + ASSERT_EQ(1, buffer.GetSpillChannels().size()); + + buffer.Write(MakeBatch(R"([[3, "c"]])")); + ASSERT_OK_AND_ASSIGN(std::shared_ptr replayed, ReplayAll(buffer)); + ASSERT_TRUE(replayed->Equals(*MakeBatch(R"([[1, "a"], [2, "b"], [3, "c"]])"))); + + buffer.Clear(); + ASSERT_FALSE(buffer.HasData()); + ASSERT_EQ(0, buffer.GetMemoryUsage()); +} + +TEST_F(AppendWriteBufferTest, TestSpillAndReplayInWriteOrder) { + for (bool enable_multi_thread_spill : {false, true}) { + SCOPED_TRACE(::testing::Message() + << "enable_multi_thread_spill=" << enable_multi_thread_spill); + AppendWriteBuffer buffer(CreateOptions(), schema_, io_manager_, enable_multi_thread_spill, + pool_); + ASSERT_TRUE(buffer.IsSpillable()); + + buffer.Write(MakeBatch(R"([[1, "a"], [2, "b"]])")); + ASSERT_OK_AND_ASSIGN(bool spill_handled, buffer.TrySpill()); + ASSERT_TRUE(spill_handled); + ASSERT_EQ(0, buffer.GetMemoryUsage()); + ASSERT_EQ(1, buffer.GetSpillChannels().size()); + ASSERT_GT(buffer.GetDiskUsage(), 0); + + // A row that is null at the top level stays null after the spill. + buffer.Write(MakeBatch(R"([[3, "c"], null])")); + ASSERT_OK_AND_ASSIGN(spill_handled, buffer.TrySpill()); + ASSERT_TRUE(spill_handled); + ASSERT_EQ(2, buffer.GetSpillChannels().size()); + + buffer.Write(MakeBatch(R"([[4, "d"], [5, null]])")); + ASSERT_GT(buffer.GetMemoryUsage(), 0); + + std::vector channels = buffer.GetSpillChannels(); + ASSERT_OK_AND_ASSIGN(bool all_exist, AllExist(channels)); + ASSERT_TRUE(all_exist); + + // Spilled batches come first, then the batches still in memory, all in write order. + ASSERT_OK_AND_ASSIGN(std::shared_ptr replayed, ReplayAll(buffer)); + auto expected = MakeBatch(R"([[1, "a"], [2, "b"], [3, "c"], null, [4, "d"], [5, null]])"); + ASSERT_TRUE(replayed->Equals(*expected)) << replayed->ToString(); + + // Replay leaves the buffer unchanged. + ASSERT_TRUE(buffer.HasData()); + ASSERT_OK_AND_ASSIGN(all_exist, AllExist(channels)); + ASSERT_TRUE(all_exist); + + buffer.Clear(); + ASSERT_FALSE(buffer.HasData()); + ASSERT_EQ(0, buffer.GetDiskUsage()); + ASSERT_OK_AND_ASSIGN(bool any_exist, AnyExist(channels)); + ASSERT_FALSE(any_exist); + } +} + +TEST_F(AppendWriteBufferTest, TestReplayRejectsSpillFileOfAnotherSchema) { + AppendWriteBuffer buffer(CreateOptions(), schema_, io_manager_, + /*enable_multi_thread_spill=*/false, pool_); + buffer.Write(MakeBatch(R"([[1, "a"]])")); + ASSERT_OK_AND_ASSIGN(bool spill_handled, buffer.TrySpill()); + ASSERT_TRUE(spill_handled); + const std::string spill_path = buffer.GetSpillChannels()[0].GetPath(); + + // Replace the spill file with a readable Arrow IPC file of another schema. + auto other_schema = arrow::schema({arrow::field("x", arrow::int64())}); + AppendWriteBuffer other(CreateOptions(), other_schema, io_manager_, + /*enable_multi_thread_spill=*/false, pool_); + other.Write(checked_pointer_cast( + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(other_schema->fields()), "[[1]]") + .ValueOrDie())); + ASSERT_OK_AND_ASSIGN(spill_handled, other.TrySpill()); + ASSERT_TRUE(spill_handled); + std::shared_ptr fs = tmp_dir_->GetFileSystem(); + ASSERT_OK(fs->Delete(spill_path)); + ASSERT_OK(fs->Rename(other.GetSpillChannels()[0].GetPath(), spill_path)); + + ASSERT_NOK_WITH_MSG(ReplayAll(buffer).status(), "does not match the write buffer schema"); +} + +TEST_F(AppendWriteBufferTest, TestSpillDiskBudget) { + AppendWriteBuffer buffer(CreateOptions({{Options::WRITE_BUFFER_SPILL_MAX_DISK_SIZE, "1b"}}), + schema_, io_manager_, + /*enable_multi_thread_spill=*/false, pool_); + buffer.Write(MakeBatch(R"([[1, "a"]])")); + ASSERT_OK_AND_ASSIGN(bool spill_handled, buffer.TrySpill()); + ASSERT_TRUE(spill_handled); + std::vector channels = buffer.GetSpillChannels(); + ASSERT_EQ(1, channels.size()); + int64_t disk_usage = buffer.GetDiskUsage(); + ASSERT_GT(disk_usage, 0); + + // The budget is used up: the buffer refuses to spill again and keeps its rows in memory. + buffer.Write(MakeBatch(R"([[2, "b"]])")); + uint64_t memory_usage = buffer.GetMemoryUsage(); + ASSERT_GT(memory_usage, 0); + ASSERT_OK_AND_ASSIGN(spill_handled, buffer.TrySpill()); + ASSERT_FALSE(spill_handled); + ASSERT_EQ(1, buffer.GetSpillChannels().size()); + ASSERT_EQ(memory_usage, buffer.GetMemoryUsage()); + ASSERT_OK_AND_ASSIGN(std::shared_ptr replayed, ReplayAll(buffer)); + ASSERT_TRUE(replayed->Equals(*MakeBatch(R"([[1, "a"], [2, "b"]])"))); + + // A spill file that fails to be deleted is no longer replayed, but still uses up the budget. + auto io_hook = IOHook::GetInstance(); + io_hook->Reset(0, IOHook::Mode::RETURN_ERROR); + buffer.Clear(); + io_hook->Clear(); + ASSERT_FALSE(buffer.HasData()); + ASSERT_EQ(disk_usage, buffer.GetDiskUsage()); + ASSERT_OK_AND_ASSIGN(bool all_exist, AllExist(channels)); + ASSERT_TRUE(all_exist); + buffer.Write(MakeBatch(R"([[3, "c"]])")); + ASSERT_OK_AND_ASSIGN(spill_handled, buffer.TrySpill()); + ASSERT_FALSE(spill_handled); + ASSERT_OK_AND_ASSIGN(replayed, ReplayAll(buffer)); + ASSERT_TRUE(replayed->Equals(*MakeBatch(R"([[3, "c"]])"))); + + // The next Clear() deletes it again and frees the budget. + buffer.Clear(); + ASSERT_EQ(0, buffer.GetDiskUsage()); + ASSERT_OK_AND_ASSIGN(bool any_exist, AnyExist(channels)); + ASSERT_FALSE(any_exist); + buffer.Write(MakeBatch(R"([[4, "d"]])")); + ASSERT_OK_AND_ASSIGN(spill_handled, buffer.TrySpill()); + ASSERT_TRUE(spill_handled); +} + +TEST_F(AppendWriteBufferTest, TestClearDeletesFileOfFailedSpill) { + // Create the spill directory first: failing to create it only stops spilling. + ASSERT_OK(io_manager_->GetSpillDir()); + auto io_hook = IOHook::GetInstance(); + bool left_file = false; + bool spilled = false; + for (int64_t pos = 0; pos < 100 && !spilled; ++pos) { + SCOPED_TRACE(::testing::Message() << "io error position=" << pos); + AppendWriteBuffer buffer(CreateOptions(), schema_, io_manager_, + /*enable_multi_thread_spill=*/false, pool_); + buffer.Write(MakeBatch(R"([[1, "a"]])")); + + // Every IO from `pos` on fails, so a failed spill also fails to delete its own file, e.g. + // when getting the size of the written file fails. + io_hook->Reset(pos, IOHook::Mode::RETURN_ERROR); + Result spill_handled = buffer.TrySpill(); + io_hook->Clear(); + ASSERT_OK_AND_ASSIGN(std::vector files, ListSpillFiles()); + if (spill_handled.ok()) { + ASSERT_TRUE(spill_handled.value()); + ASSERT_EQ(1, files.size()); + spilled = true; + } else { + left_file = left_file || !files.empty(); + // The rows stay in memory and the partial file is never replayed. + ASSERT_TRUE(buffer.GetSpillChannels().empty()); + ASSERT_OK_AND_ASSIGN(std::shared_ptr replayed, ReplayAll(buffer)); + ASSERT_TRUE(replayed->Equals(*MakeBatch(R"([[1, "a"]])"))); + } + buffer.Clear(); + ASSERT_OK_AND_ASSIGN(files, ListSpillFiles()); + ASSERT_TRUE(files.empty()) << files[0]; + } + ASSERT_TRUE(left_file); + ASSERT_TRUE(spilled); +} + +TEST_F(AppendWriteBufferTest, TestDestructorDeletesSpillFiles) { + std::vector channels; + { + AppendWriteBuffer buffer(CreateOptions(), schema_, io_manager_, + /*enable_multi_thread_spill=*/false, pool_); + buffer.Write(MakeBatch(R"([[1, "a"]])")); + ASSERT_OK_AND_ASSIGN(bool spill_handled, buffer.TrySpill()); + ASSERT_TRUE(spill_handled); + channels = buffer.GetSpillChannels(); + ASSERT_OK_AND_ASSIGN(bool all_exist, AllExist(channels)); + ASSERT_TRUE(all_exist); + } + ASSERT_OK_AND_ASSIGN(bool any_exist, AnyExist(channels)); + ASSERT_FALSE(any_exist); +} + +} // namespace paimon::test diff --git a/src/paimon/core/core_options.cpp b/src/paimon/core/core_options.cpp index 2e92d7c98..d733aef80 100644 --- a/src/paimon/core/core_options.cpp +++ b/src/paimon/core/core_options.cpp @@ -423,6 +423,7 @@ struct CoreOptions::Impl { int32_t read_preparation_window = ConcatBatchReader::kDefaultPreparationWindow; int32_t write_batch_size = 1024; int32_t local_sort_max_num_file_handles = 128; + int32_t write_max_writers_to_spill = 10; int32_t commit_max_retries = 10; int32_t compaction_min_file_num = 5; int32_t compaction_max_size_amplification_percent = 200; @@ -463,6 +464,7 @@ struct CoreOptions::Impl { bool ignore_delete = false; bool manifest_delete_file_drop_stats = false; bool write_buffer_spillable = true; + bool write_buffer_for_append = false; bool write_only = false; bool bucket_append_ordered = true; bool deletion_vectors_enabled = false; @@ -552,6 +554,12 @@ struct CoreOptions::Impl { // Parse write-buffer-spill.max-disk-size - max disk size for spill files PAIMON_RETURN_NOT_OK(parser.ParseMemorySize(Options::WRITE_BUFFER_SPILL_MAX_DISK_SIZE, &write_buffer_spill_max_disk_size)); + // Parse write-buffer-for-append - whether append-only writers buffer rows in memory + PAIMON_RETURN_NOT_OK( + parser.Parse(Options::WRITE_BUFFER_FOR_APPEND, &write_buffer_for_append)); + // Parse write-max-writers-to-spill - writer count that forces append buffers to spill + PAIMON_RETURN_NOT_OK( + parser.Parse(Options::WRITE_MAX_WRITERS_TO_SPILL, &write_max_writers_to_spill)); // Parse local-sort.max-num-file-handles - spill file handle cap for local merge PAIMON_RETURN_NOT_OK(parser.Parse(Options::LOCAL_SORT_MAX_NUM_FILE_HANDLES, &local_sort_max_num_file_handles)); @@ -1362,6 +1370,14 @@ int64_t CoreOptions::GetWriteBufferSpillMaxDiskSize() const { return impl_->write_buffer_spill_max_disk_size; } +bool CoreOptions::GetWriteBufferForAppend() const { + return impl_->write_buffer_for_append; +} + +int32_t CoreOptions::GetWriteMaxWritersToSpill() const { + return impl_->write_max_writers_to_spill; +} + int32_t CoreOptions::GetLocalSortMaxNumFileHandles() const { return impl_->local_sort_max_num_file_handles; } diff --git a/src/paimon/core/core_options.h b/src/paimon/core/core_options.h index e513d5d93..3ed17ddd6 100644 --- a/src/paimon/core/core_options.h +++ b/src/paimon/core/core_options.h @@ -131,6 +131,8 @@ class PAIMON_EXPORT CoreOptions { int64_t GetWriteBufferSize() const; bool GetWriteBufferSpillable() const; int64_t GetWriteBufferSpillMaxDiskSize() const; + bool GetWriteBufferForAppend() const; + int32_t GetWriteMaxWritersToSpill() const; int32_t GetLocalSortMaxNumFileHandles() const; const CompressOptions& GetSpillCompressOptions() const; diff --git a/src/paimon/core/core_options_test.cpp b/src/paimon/core/core_options_test.cpp index 0a6709471..c7baf5d62 100644 --- a/src/paimon/core/core_options_test.cpp +++ b/src/paimon/core/core_options_test.cpp @@ -98,6 +98,8 @@ TEST(CoreOptionsTest, TestDefaultValue) { ASSERT_EQ(256 * 1024 * 1024, core_options.GetWriteBufferSize()); ASSERT_TRUE(core_options.GetWriteBufferSpillable()); ASSERT_EQ(std::numeric_limits::max(), core_options.GetWriteBufferSpillMaxDiskSize()); + ASSERT_FALSE(core_options.GetWriteBufferForAppend()); + ASSERT_EQ(10, core_options.GetWriteMaxWritersToSpill()); ASSERT_EQ(128, core_options.GetLocalSortMaxNumFileHandles()); ASSERT_EQ("zstd", core_options.GetSpillCompressOptions().compress); ASSERT_EQ(1, core_options.GetSpillCompressOptions().zstd_level); @@ -243,6 +245,8 @@ TEST(CoreOptionsTest, TestFromMap) { {Options::WRITE_BATCH_SIZE, "1234"}, {Options::WRITE_BUFFER_SPILLABLE, "false"}, {Options::WRITE_BUFFER_SPILL_MAX_DISK_SIZE, "7GB"}, + {Options::WRITE_BUFFER_FOR_APPEND, "true"}, + {Options::WRITE_MAX_WRITERS_TO_SPILL, "3"}, {Options::LOCAL_SORT_MAX_NUM_FILE_HANDLES, "64"}, {Options::SPILL_COMPRESSION, "lz4"}, {Options::COMMIT_FORCE_COMPACT, "true"}, @@ -399,6 +403,8 @@ TEST(CoreOptionsTest, TestFromMap) { ASSERT_EQ(16 * 1024 * 1024, core_options.GetWriteBufferSize()); ASSERT_FALSE(core_options.GetWriteBufferSpillable()); ASSERT_EQ(7L * 1024 * 1024 * 1024, core_options.GetWriteBufferSpillMaxDiskSize()); + ASSERT_TRUE(core_options.GetWriteBufferForAppend()); + ASSERT_EQ(3, core_options.GetWriteMaxWritersToSpill()); ASSERT_EQ(64, core_options.GetLocalSortMaxNumFileHandles()); ASSERT_EQ("lz4", core_options.GetSpillCompressOptions().compress); ASSERT_EQ(2, core_options.GetSpillCompressOptions().zstd_level); diff --git a/src/paimon/core/operation/abstract_file_store_write.cpp b/src/paimon/core/operation/abstract_file_store_write.cpp index 78a2ac31c..4250663c5 100644 --- a/src/paimon/core/operation/abstract_file_store_write.cpp +++ b/src/paimon/core/operation/abstract_file_store_write.cpp @@ -668,6 +668,13 @@ Result> AbstractFileStoreWrite::GetWriter(const Bin } } + if (CanForceBufferSpill()) { + int64_t active_writer_count = GetActiveWriterCountLocked(); + if (active_writer_count >= options_.GetWriteMaxWritersToSpill()) { + PAIMON_RETURN_NOT_OK(ForceBufferSpill(active_writer_count)); + } + } + std::shared_ptr restored = RestoreFiles::Empty(); if (!ignore_previous_files_) { PAIMON_ASSIGN_OR_RAISE(restored, ScanExistingFileMetas(partition, bucket)); @@ -714,4 +721,23 @@ Result> AbstractFileStoreWrite::GetWriter(const Bin return writer; } +int64_t AbstractFileStoreWrite::GetActiveWriterCountLocked() const { + int64_t active_writer_count = 0; + for (const auto& partition_writers : writers_) { + active_writer_count += static_cast(partition_writers.second.size()); + } + return active_writer_count; +} + +Status AbstractFileStoreWrite::VisitWritersLocked( + const std::function&)>& + visitor) const { + for (const auto& [partition, bucket_writers] : writers_) { + for (const auto& [bucket, writer_container] : bucket_writers) { + PAIMON_RETURN_NOT_OK(visitor(partition, bucket, writer_container.writer)); + } + } + return Status::OK(); +} + } // namespace paimon diff --git a/src/paimon/core/operation/abstract_file_store_write.h b/src/paimon/core/operation/abstract_file_store_write.h index 008d83ce1..2d93d6c0f 100644 --- a/src/paimon/core/operation/abstract_file_store_write.h +++ b/src/paimon/core/operation/abstract_file_store_write.h @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -154,6 +155,27 @@ class AbstractFileStoreWrite : public FileStoreWrite { Result> GetWriter(const BinaryRow& partition, int32_t bucket); + /// Whether `ForceBufferSpill()` may still switch the writers, checked before counting + /// them for every new writer. + virtual bool CanForceBufferSpill() const { + return false; + } + + /// Called before a writer is created once the number of active writers has reached + /// `write-max-writers-to-spill`, so that many concurrent writers do not run out of memory. + /// Runs while the writer map is locked; use `VisitWritersLocked()` to reach the writers. + /// @param active_writer_count The number of active writers, not counting the one about to be + /// created. + virtual Status ForceBufferSpill(int64_t active_writer_count) { + return Status::OK(); + } + + /// Passes every active writer with its partition and bucket to `visitor`. Only call it while + /// the writer map is locked, as it is inside `ForceBufferSpill()`. + Status VisitWritersLocked( + const std::function&)>& + visitor) const; + Result> ScanExistingFileMetas(const BinaryRow& partition, int32_t bucket) const; int32_t GetDefaultBucketNum() const; @@ -185,6 +207,8 @@ class AbstractFileStoreWrite : public FileStoreWrite { Status CheckRealtimeWriteUsable() const; void InvalidateRealtimeContext(); Status PoisonRealtimeWrite(const Status& cause); + /// Returns the number of active writers. Only call it while the writer map is locked. + int64_t GetActiveWriterCountLocked() const; Result> PrepareRealtimeCommit(); diff --git a/src/paimon/core/operation/append_only_file_store_write.cpp b/src/paimon/core/operation/append_only_file_store_write.cpp index ac7d34420..386ddef3e 100644 --- a/src/paimon/core/operation/append_only_file_store_write.cpp +++ b/src/paimon/core/operation/append_only_file_store_write.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include "arrow/c/bridge.h" @@ -48,6 +49,7 @@ #include "paimon/core/manifest/manifest_file.h" #include "paimon/core/manifest/manifest_list.h" #include "paimon/core/operation/append_only_file_store_scan.h" +#include "paimon/core/operation/blob_file_context.h" #include "paimon/core/operation/commit/realtime_commit_properties.h" #include "paimon/core/operation/file_store_scan.h" #include "paimon/core/operation/internal_read_context.h" @@ -102,7 +104,7 @@ AppendOnlyFileStoreWrite::AppendOnlyFileStoreWrite( const std::shared_ptr& dv_maintainer_factory, const std::shared_ptr& io_manager, const CoreOptions& options, bool ignore_previous_files, bool is_streaming_mode, bool ignore_num_bucket_check, - const std::shared_ptr& realtime_context, + bool enable_multi_thread_spill, const std::shared_ptr& realtime_context, const std::shared_ptr& executor, const std::shared_ptr& pool) : AbstractFileStoreWrite(file_store_path_factory, snapshot_manager, schema_manager, commit_user, root_path, table_schema, schema, write_schema, realtime_schema_layout, @@ -110,6 +112,7 @@ AppendOnlyFileStoreWrite::AppendOnlyFileStoreWrite( /*primary_key_index_maintainer_factory=*/nullptr, io_manager, options, ignore_previous_files, is_streaming_mode, ignore_num_bucket_check, executor, pool), + enable_multi_thread_spill_(enable_multi_thread_spill), realtime_context_(realtime_context), logger_(Logger::GetLogger("AppendOnlyFileStoreWrite")) { write_cols_ = write_schema->field_names(); @@ -120,6 +123,8 @@ AppendOnlyFileStoreWrite::AppendOnlyFileStoreWrite( if (schema->Equals(write_schema)) { write_cols_ = std::nullopt; } + std::unique_ptr blob_context = BlobFileContext::Create(write_schema, options); + require_blob_file_writer_ = blob_context && blob_context->RequireBlobFileWriter(); if (realtime_context_) { writer_memory_manager_ = std::make_unique(); } @@ -234,9 +239,9 @@ Result>> AppendOnlyFileStoreWrite::Com ShreddingWritePlanFactories::SelectActive(options_, write_schema_, pool_)); PAIMON_ASSIGN_OR_RAISE(std::optional veto_reason, GetDictionaryPassthroughVetoReason(plan_factory)); - PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr reader, - CreateFilesReader(partition, bucket, dv_factory, to_compact, veto_reason)); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, + CreateFilesReader(partition, bucket, dv_factory, to_compact, veto_reason, + /*read_field_names=*/std::nullopt)); PAIMON_ASSIGN_OR_RAISE(std::shared_ptr data_file_path_factory, file_store_path_factory_->CreateDataFilePathFactory(partition, bucket)); PAIMON_ASSIGN_OR_RAISE(WriterFactory writer_factory, @@ -349,9 +354,31 @@ Result> AppendOnlyFileStoreWrite::CreateWriter( /*materialize_dv_on_commit=*/!options_.GetRealtimeDeduplicateKeyFields().empty()); } + bool use_write_buffer = !realtime_context_ && !require_blob_file_writer_ && + (options_.GetWriteBufferForAppend() || force_buffer_spill_); + bool spillable = use_write_buffer && io_manager_ != nullptr && + (options_.GetWriteBufferSpillable() || force_buffer_spill_) && + IsSpillDirectoryAvailable(); + std::shared_ptr spill_io_manager = spillable ? io_manager_ : nullptr; + // Reads the files a writer closes when it switches to a spillable write buffer back into the + // buffer. The files are new, so they have no deletion vectors, and nothing forwards their + // dictionary encoding into the buffer. + // TODO(SteNicholas): With dedicated VECTOR storage, `RawFileSplitRead` reads the main file and + // the VECTOR file separately, so one logical row can come back as two partial rows with NULLs + // for the missing columns. Paimon Java's `AppendOnlyWriter.toBufferedWriter()` has the same + // issue; align this with its fix once that is merged. + AppendOnlyWriter::FilesReaderFactory files_reader_factory = + [this, partition, bucket](const std::vector>& files) + -> Result> { + return CreateFilesReader( + partition, bucket, /*dv_factory=*/nullptr, files, + std::optional("the rows are read back into a write buffer"), + write_schema_->field_names()); + }; auto writer = std::make_shared( options_, table_schema_->Id(), write_schema_, write_cols_, restore_max_seq_number, - data_file_path_factory, compact_manager, pool_); + data_file_path_factory, compact_manager, use_write_buffer, spill_io_manager, + enable_multi_thread_spill_, files_reader_factory, pool_); if (!realtime_context_) { return std::shared_ptr(std::move(writer)); } @@ -374,6 +401,63 @@ Result> AppendOnlyFileStoreWrite::CreateWriter( io_manager_ ? io_manager_->GetTempDir() : "", pool_); } +bool AppendOnlyFileStoreWrite::CanForceBufferSpill() const { + return !force_buffer_spill_ && !spill_directory_unavailable_ && io_manager_ != nullptr && + !realtime_context_ && !require_blob_file_writer_; +} + +bool AppendOnlyFileStoreWrite::IsSpillDirectoryAvailable() { + if (spill_directory_unavailable_) { + return false; + } + Result spill_dir = io_manager_->GetSpillDir(); + if (!spill_dir.ok()) { + spill_directory_unavailable_ = true; + PAIMON_LOG_WARN(logger_, + "Cannot create the spill directory under %s, so append-only writers write " + "data files instead of spilling or switching to spillable write buffers: " + "%s", + io_manager_->GetTempDir().c_str(), spill_dir.status().ToString().c_str()); + return false; + } + return true; +} + +Status AppendOnlyFileStoreWrite::ForceBufferSpill(int64_t active_writer_count) { + if (!IsSpillDirectoryAvailable()) { + return Status::OK(); + } + // Writers switched by an earlier failed attempt are left as they are. + PAIMON_RETURN_NOT_OK(VisitWritersLocked([this](const BinaryRow& partition, int32_t bucket, + const std::shared_ptr& writer) { + auto append_writer = std::dynamic_pointer_cast(writer); + if (append_writer == nullptr) { + return Status::OK(); + } + // Lets the memory manager flush the largest writers after each batch read back, so the + // rows read back by all writers stay within write-buffer-size. + BatchWriter* batch_writer = writer.get(); + Status status = + append_writer->SwitchToSpillableBuffer(io_manager_, [this, batch_writer]() -> Status { + return writer_memory_manager_->OnWriteCompleted(batch_writer); + }); + if (!status.ok()) { + return status.WithMessage("Failed to switch the writer of partition ", + partition.ToString(), ", bucket ", bucket, + " to a spillable write buffer: ", status.message()); + } + writer_memory_manager_->RefreshWriterMemory(batch_writer); + return status; + })); + force_buffer_spill_ = true; + PAIMON_LOG_INFO(logger_, + "Switched %ld active append-only writers to spillable write buffers, as they " + "reached %s = %d", + active_writer_count, Options::WRITE_MAX_WRITERS_TO_SPILL, + options_.GetWriteMaxWritersToSpill()); + return Status::OK(); +} + Result AppendOnlyFileStoreWrite::GetDataFileWriterFactory( const std::shared_ptr& data_file_path_factory, const std::shared_ptr& schema, @@ -416,8 +500,12 @@ Result> AppendOnlyFileStoreWrite::GetDictionaryPassth Result> AppendOnlyFileStoreWrite::CreateFilesReader( const BinaryRow& partition, int32_t bucket, DeletionVector::Factory dv_factory, const std::vector>& files, - const std::optional& veto_reason) const { + const std::optional& veto_reason, + const std::optional>& read_field_names) const { ReadContextBuilder context_builder(root_path_); + if (read_field_names) { + context_builder.SetReadFieldNames(read_field_names.value()); + } context_builder.SetOptions(options_.ToMap()) .WithFileSystem(options_.GetFileSystem()) .EnablePrefetch(true) @@ -438,7 +526,7 @@ Result> AppendOnlyFileStoreWrite::CreateFilesReader OptionsUtils::GetValueFromMap(options, kParquetReadEnableDictionaryPassthrough, kDefaultParquetReadEnableDictionaryPassthrough); if (requested.ok() && requested.value()) { - PAIMON_LOG_DEBUG(logger_, "Ignoring %s for this compaction rewrite: %s", + PAIMON_LOG_DEBUG(logger_, "Ignoring %s for this rewrite: %s", kParquetReadEnableDictionaryPassthrough, veto_reason->c_str()); } options[kParquetReadEnableDictionaryPassthrough] = "false"; diff --git a/src/paimon/core/operation/append_only_file_store_write.h b/src/paimon/core/operation/append_only_file_store_write.h index 93ca6cdef..49f7cd01a 100644 --- a/src/paimon/core/operation/append_only_file_store_write.h +++ b/src/paimon/core/operation/append_only_file_store_write.h @@ -86,7 +86,7 @@ class AppendOnlyFileStoreWrite : public AbstractFileStoreWrite { const std::shared_ptr& dv_maintainer_factory, const std::shared_ptr& io_manager, const CoreOptions& options, bool ignore_previous_files, bool is_streaming_mode, bool ignore_num_bucket_check, - const std::shared_ptr& realtime_context, + bool enable_multi_thread_spill, const std::shared_ptr& realtime_context, const std::shared_ptr& executor, const std::shared_ptr& pool); ~AppendOnlyFileStoreWrite() override; @@ -124,6 +124,17 @@ class AppendOnlyFileStoreWrite : public AbstractFileStoreWrite { Result> CreateFileStoreScan( const std::shared_ptr& filter) const override; + /// False once the writers have switched, without a temporary directory or once its spill + /// directory could not be created, when the schema of this write has BLOBs written to + /// dedicated .blob files, and for real-time writes. + bool CanForceBufferSpill() const override; + + /// Switches existing and future writers to write buffers that spill to temporary files, once + /// the spill directory is created. Future writers switch only once every existing writer has + /// switched. If the spill directory cannot be created, the writers keep writing data files + /// and never switch. + Status ForceBufferSpill(int64_t active_writer_count) override; + bool IsRealtimeWrite() const override { return realtime_context_ != nullptr; } @@ -142,11 +153,14 @@ class AppendOnlyFileStoreWrite : public AbstractFileStoreWrite { const std::vector>& to_compact, const std::shared_ptr& plan_factory) const; - /// @param veto_reason What GetDictionaryPassthroughVetoReason() returned. + /// @param veto_reason Why the reader must not forward dictionary encoding, e.g. what + /// GetDictionaryPassthroughVetoReason() returned, or std::nullopt. + /// @param read_field_names The fields to read, or std::nullopt for every table field. Result> CreateFilesReader( const BinaryRow& partition, int32_t bucket, DeletionVector::Factory dv_factory, const std::vector>& files, - const std::optional& veto_reason) const; + const std::optional& veto_reason, + const std::optional>& read_field_names) const; /// Why `CompactRewrite` must not forward the dictionary encoding of its input files, or /// `std::nullopt` when the table's `parquet.read.enable-dictionary-passthrough` may stand. @@ -168,8 +182,23 @@ class AppendOnlyFileStoreWrite : public AbstractFileStoreWrite { Result> GetDictionaryPassthroughVetoReason( const std::shared_ptr& plan_factory) const; + /// Creates the spill directory under the temporary directory on first use. If that fails, + /// logs a warning once and returns false from then on, so writers neither spill nor switch + /// to spillable write buffers. + bool IsSpillDirectoryAvailable(); + std::optional> write_cols_; bool custom_compaction_ = false; + // Set once every existing writer has switched to a spillable write buffer; writers created + // afterwards use one too. + bool force_buffer_spill_ = false; + // Set once the spill directory under the temporary directory could not be created, so it is + // neither created again nor reported again. + bool spill_directory_unavailable_ = false; + // Whether BLOBs of the write schema go to dedicated .blob files, which bypass the write + // buffer. + bool require_blob_file_writer_ = false; + const bool enable_multi_thread_spill_; std::shared_ptr realtime_context_; std::unique_ptr logger_; }; diff --git a/src/paimon/core/operation/append_only_file_store_write_test.cpp b/src/paimon/core/operation/append_only_file_store_write_test.cpp index d432bbadb..f89d240bb 100644 --- a/src/paimon/core/operation/append_only_file_store_write_test.cpp +++ b/src/paimon/core/operation/append_only_file_store_write_test.cpp @@ -43,10 +43,16 @@ #include "paimon/commit_context.h" #include "paimon/common/data/binary_row.h" #include "paimon/common/data/binary_row_writer.h" +#include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/blob_view_struct.h" #include "paimon/common/data/shredding/map_shared_shredding_utils.h" #include "paimon/common/data/shredding/map_shredding_defs.h" +#include "paimon/common/factories/io_hook.h" #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/path_util.h" +#include "paimon/core/append/append_only_writer.h" +#include "paimon/core/append/append_write_buffer.h" +#include "paimon/core/disk/io_manager.h" #include "paimon/core/io/data_file_meta.h" #include "paimon/core/operation/restore_files.h" #include "paimon/core/realtime/realtime_schema_layout.h" @@ -64,7 +70,9 @@ #include "paimon/realtime/realtime_context.h" #include "paimon/record_batch.h" #include "paimon/status.h" +#include "paimon/table/source/startup_mode.h" #include "paimon/testing/utils/read_result_collector.h" +#include "paimon/testing/utils/test_helper.h" #include "paimon/testing/utils/testharness.h" #include "paimon/write_context.h" @@ -91,13 +99,14 @@ class AppendOnlyFileStoreWriteTest : public testing::Test { } void CreateTable(const std::string& warehouse, const std::shared_ptr& schema, - const std::map& options) const { + const std::map& options, + const std::vector& partition_keys = {}) const { ::ArrowSchema c_schema; ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); ASSERT_OK_AND_ASSIGN(auto catalog, Catalog::Create(warehouse, options)); ASSERT_OK(catalog->CreateDatabase("foo", {}, /*ignore_if_exists=*/false)); - ASSERT_OK(catalog->CreateTable(Identifier("foo", "bar"), &c_schema, - /*partition_keys=*/{}, /*primary_keys=*/{}, options, + ASSERT_OK(catalog->CreateTable(Identifier("foo", "bar"), &c_schema, partition_keys, + /*primary_keys=*/{}, options, /*ignore_if_exists=*/false)); } @@ -883,4 +892,601 @@ TEST_F(AppendOnlyFileStoreWriteTest, TestSharedShreddingPartialWriteSkipsMissing } } +namespace { + +std::vector> AppendWriters(AppendOnlyFileStoreWrite* write) { + std::vector> writers; + for (const auto& [_, bucket_writers] : write->writers_) { + for (const auto& [__, container] : bucket_writers) { + writers.push_back(std::dynamic_pointer_cast(container.writer)); + } + } + return writers; +} + +size_t CountSpillFiles(AppendOnlyFileStoreWrite* write) { + EXPECT_OK_AND_ASSIGN(std::string spill_dir, write->io_manager_->GetSpillDir()); + std::vector spill_files; + EXPECT_OK(write->options_.GetFileSystem()->ListDir(spill_dir, &spill_files)); + return spill_files.size(); +} + +/// Returns the files in the bucket directories of an unpartitioned table, sorted. +std::vector ListBucketFiles(const std::string& table_path) { + auto fs = std::make_shared(); + std::vector entries; + EXPECT_OK(fs->ListDir(table_path, &entries)); + std::vector files; + for (const BasicFileStatus& entry : entries) { + std::string dir_name = PathUtil::GetName(entry.GetPath()); + if (!entry.IsDir() || dir_name.rfind("bucket-", 0) != 0) { + continue; + } + std::vector bucket_files; + EXPECT_OK(fs->ListDir(entry.GetPath(), &bucket_files)); + for (const BasicFileStatus& file : bucket_files) { + if (!file.IsDir()) { + files.push_back(PathUtil::JoinPath(dir_name, PathUtil::GetName(file.GetPath()))); + } + } + } + std::sort(files.begin(), files.end()); + return files; +} + +} // namespace + +TEST_F(AppendOnlyFileStoreWriteTest, TestForceBufferSpillWhenWritersReachThreshold) { + auto schema = arrow::schema({arrow::field("id", arrow::int32()), + arrow::field("tags", arrow::map(arrow::utf8(), arrow::int64()))}); + struct TestCase { + std::string file_format; + bool shared_shredding; + bool non_spillable_buffer; + }; + for (const auto& test_case : std::vector{{"orc", false, false}, + {"parquet", true, false}, + {"orc", true, false}, + {"orc", false, true}}) { + SCOPED_TRACE(::testing::Message() + << "file_format=" << test_case.file_format + << ", shared_shredding=" << test_case.shared_shredding + << ", non_spillable_buffer=" << test_case.non_spillable_buffer); + std::map options = {{Options::FILE_FORMAT, test_case.file_format}, + {Options::WRITE_ONLY, "true"}, + {Options::BUCKET, "2"}, + {Options::BUCKET_KEY, "id"}, + {Options::WRITE_MAX_WRITERS_TO_SPILL, "1"}, + {Options::WRITE_BUFFER_SIZE, "1b"}}; + if (test_case.non_spillable_buffer) { + options[Options::WRITE_BUFFER_FOR_APPEND] = "true"; + options[Options::WRITE_BUFFER_SPILLABLE] = "false"; + } + if (test_case.shared_shredding) { + options["fields.tags.map.storage-layout"] = "shared-shredding"; + options["fields.tags.map.shared-shredding.max-columns"] = "10"; + options["fields.tags.map.shared-shredding.column-placement-policy"] = "plain"; + } + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto tmp_dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(tmp_dir); + CreateTable(dir->Str(), schema, options); + const std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + + WriteContextBuilder builder(table_path, commit_user_); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr write_context, + builder.SetOptions(options).WithTempDirectory(tmp_dir->Str()).Finish()); + ASSERT_OK_AND_ASSIGN(auto file_store_write, + FileStoreWrite::Create(std::move(write_context))); + auto* write = dynamic_cast(file_store_write.get()); + ASSERT_NE(nullptr, write); + + auto write_to_bucket = [&](const std::string& json, int32_t bucket) { + auto batch = MakeBatch(schema, json); + batch->SetBucket(bucket); + return file_store_write->Write(std::move(batch)); + }; + + // Below the threshold, rows go to a data file, directly or through a buffer that cannot + // spill. + ASSERT_OK(write_to_bucket(R"([[1, [["a", 10]]], [2, [["b", 20]]]])", /*bucket=*/0)); + ASSERT_FALSE(write->force_buffer_spill_); + for (const auto& writer : AppendWriters(write)) { + ASSERT_NE(nullptr, writer); + if (test_case.non_spillable_buffer) { + ASSERT_NE(nullptr, writer->GetWriteBuffer()); + ASSERT_FALSE(writer->GetWriteBuffer()->IsSpillable()); + } else { + ASSERT_EQ(nullptr, writer->GetWriteBuffer()); + } + } + + // Opening a second writer switches existing and new writers to spillable buffers, even + // with write-buffer-spillable = false; the tiny write buffer then spills. The rows bucket + // 0 wrote to a data file are read back into its buffer and spilled; a buffer that could + // not spill has already flushed them to a data file instead. + ASSERT_OK(write_to_bucket(R"([[3, [["c", 30]]]])", /*bucket=*/1)); + ASSERT_TRUE(write->force_buffer_spill_); + std::vector> writers = AppendWriters(write); + ASSERT_EQ(2, writers.size()); + for (const auto& writer : writers) { + ASSERT_NE(nullptr, writer); + ASSERT_NE(nullptr, writer->GetWriteBuffer()); + ASSERT_TRUE(writer->GetWriteBuffer()->IsSpillable()); + } + const int64_t spilled_before_switch = test_case.non_spillable_buffer ? 0 : 1; + ASSERT_EQ(spilled_before_switch + 1, CountSpillFiles(write)); + + ASSERT_OK(write_to_bucket(R"([[4, [["d", 40]]], [5, [["e", 50]]]])", /*bucket=*/0)); + ASSERT_EQ(spilled_before_switch + 2, CountSpillFiles(write)); + + ASSERT_OK_AND_ASSIGN(auto commit_msgs, + file_store_write->PrepareCommit( + /*wait_compaction=*/false, /*commit_identifier=*/0)); + ASSERT_EQ(0, CountSpillFiles(write)); + // Data files read back into a buffer are deleted, so only committed files remain. + ASSERT_EQ(test_case.non_spillable_buffer ? 3 : 2, ListBucketFiles(table_path).size()); + ASSERT_EQ(2, commit_msgs.size()); + for (const auto& commit_msg : commit_msgs) { + auto msg = std::dynamic_pointer_cast(commit_msg); + ASSERT_NE(nullptr, msg); + const auto& files = msg->GetNewFilesIncrement().NewFiles(); + if (msg->Bucket() == 1) { + ASSERT_EQ(1, files.size()); + ASSERT_EQ(1, files[0]->row_count); + continue; + } + ASSERT_EQ(0, msg->Bucket()); + // Rows written before the switch are replayed with the later rows into one data + // file, unless a buffer that could not spill flushed them to their own data file + // first. Either way the bucket keeps its write order. + ASSERT_EQ(test_case.non_spillable_buffer ? 2 : 1, files.size()); + std::vector ids; + for (const auto& file : files) { + if (test_case.shared_shredding) { + std::shared_ptr file_schema = + ReadDataFileSchema(table_path, file, options); + ASSERT_EQ(1, ShreddingMeta(file_schema, /*field_index=*/1).max_row_width); + } + std::shared_ptr array = + ReadDataFileArray(table_path, file, options); + ASSERT_NE(nullptr, array); + auto id_array = checked_pointer_cast(array->field(0)); + for (int64_t i = 0; i < id_array->length(); ++i) { + ids.push_back(id_array->Value(i)); + } + } + ASSERT_EQ(std::vector({1, 2, 4, 5}), ids); + } + ASSERT_OK(file_store_write->Close()); + ASSERT_EQ(0, CountSpillFiles(write)); + + // Every committed row is read back exactly once. + Commit(table_path, options, commit_msgs); + ASSERT_OK_AND_ASSIGN(auto helper, + TestHelper::Create(table_path, options, /*is_streaming_mode=*/false)); + ASSERT_OK_AND_ASSIGN(auto splits, helper->NewScan(StartupMode::LatestFull(), + /*snapshot_id=*/std::nullopt, + /*is_streaming=*/false)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr result, + helper->ReadResult(splits)); + std::vector ids; + for (const auto& chunk : result->chunks()) { + // The first column is the row kind. + auto row_array = checked_pointer_cast(chunk); + auto id_array = checked_pointer_cast(row_array->field(1)); + auto tags_array = checked_pointer_cast(row_array->field(2)); + auto keys = checked_pointer_cast(tags_array->keys()); + auto items = checked_pointer_cast(tags_array->items()); + for (int64_t i = 0; i < id_array->length(); ++i) { + int32_t id = id_array->Value(i); + ids.push_back(id); + // Row i holds the single tag {"a" + (id - 1): id * 10}. + ASSERT_EQ(1, tags_array->value_length(i)); + int64_t offset = tags_array->value_offset(i); + ASSERT_EQ(std::string(1, static_cast('a' + id - 1)), keys->GetString(offset)); + ASSERT_EQ(id * 10, items->Value(offset)); + } + } + std::sort(ids.begin(), ids.end()); + ASSERT_EQ(std::vector({1, 2, 3, 4, 5}), ids); + ASSERT_OK(helper->write_->Close()); + } +} + +TEST_F(AppendOnlyFileStoreWriteTest, TestWriteBufferSizeIsSharedAcrossBuckets) { + struct TestCase { + int32_t spill_thread_number; + bool switch_to_buffer; + }; + // Spill files are written and read back with and without spill threads. Rows that switched + // writers read back into their buffers share the limit as well. + for (const auto& test_case : std::vector{{0, false}, {2, false}, {0, true}}) { + SCOPED_TRACE(::testing::Message() << "spill_thread_number=" << test_case.spill_thread_number + << ", switch_to_buffer=" << test_case.switch_to_buffer); + auto schema = + arrow::schema({arrow::field("id", arrow::int32()), arrow::field("v", arrow::int64())}); + // A 1000-row batch buffers about 12 KB, so one bucket stays below the shared 20 KB limit + // while two buckets together exceed it. + std::map options = { + {Options::FILE_FORMAT, "orc"}, + {Options::WRITE_ONLY, "true"}, + {Options::BUCKET, "2"}, + {Options::BUCKET_KEY, "id"}, + {Options::WRITE_BUFFER_FOR_APPEND, test_case.switch_to_buffer ? "false" : "true"}, + {Options::WRITE_BUFFER_SIZE, "20kb"}}; + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto tmp_dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(tmp_dir); + CreateTable(dir->Str(), schema, options); + const std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + + WriteContextBuilder builder(table_path, commit_user_); + ASSERT_OK_AND_ASSIGN(std::unique_ptr write_context, + builder.SetOptions(options) + .WithTempDirectory(tmp_dir->Str()) + .SetWriteBufferSpillThreadNumber(test_case.spill_thread_number) + .Finish()); + ASSERT_OK_AND_ASSIGN(auto file_store_write, + FileStoreWrite::Create(std::move(write_context))); + auto* write = dynamic_cast(file_store_write.get()); + ASSERT_NE(nullptr, write); + ASSERT_EQ(test_case.spill_thread_number > 0, write->enable_multi_thread_spill_); + auto write_to_bucket = [&](int32_t bucket) { + std::string json = "["; + for (int32_t i = 0; i < 1000; ++i) { + json += (i == 0 ? "[" : ", [") + std::to_string(i) + ", 10]"; + } + json += "]"; + auto batch = MakeBatch(schema, json); + batch->SetBucket(bucket); + return file_store_write->Write(std::move(batch)); + }; + + ASSERT_OK(write_to_bucket(/*bucket=*/0)); + ASSERT_EQ(0, CountSpillFiles(write)); + ASSERT_OK(write_to_bucket(/*bucket=*/1)); + if (test_case.switch_to_buffer) { + // Both buckets wrote data files. The switch reads them back one bucket after the + // other, and spills before the rows read back by both stay in memory together. + ASSERT_EQ(0, CountSpillFiles(write)); + ASSERT_OK(write->ForceBufferSpill(write->GetActiveWriterCountLocked())); + uint64_t memory_usage = 0; + for (const auto& writer : AppendWriters(write)) { + ASSERT_NE(nullptr, writer); + memory_usage += writer->GetMemoryUsage(); + } + ASSERT_LT(memory_usage, static_cast(write->options_.GetWriteBufferSize())); + } + ASSERT_EQ(1, CountSpillFiles(write)); + + ASSERT_OK_AND_ASSIGN(auto commit_msgs, + file_store_write->PrepareCommit( + /*wait_compaction=*/false, /*commit_identifier=*/0)); + int64_t row_count = 0; + for (const auto& commit_msg : commit_msgs) { + auto msg = std::dynamic_pointer_cast(commit_msg); + ASSERT_NE(nullptr, msg); + for (const auto& file : msg->GetNewFilesIncrement().NewFiles()) { + row_count += file->row_count; + } + } + ASSERT_EQ(2000, row_count); + ASSERT_EQ(2, ListBucketFiles(table_path).size()); + ASSERT_EQ(0, CountSpillFiles(write)); + ASSERT_OK(file_store_write->Close()); + } +} + +TEST_F(AppendOnlyFileStoreWriteTest, TestForceBufferSpillAtDefaultThreshold) { + auto schema = + arrow::schema({arrow::field("id", arrow::int32()), arrow::field("v", arrow::int64())}); + enum class TempDir { kAvailable, kMissing, kUnavailable }; + for (bool write_buffer_for_append : {false, true}) { + for (TempDir temp_dir : {TempDir::kAvailable, TempDir::kMissing, TempDir::kUnavailable}) { + SCOPED_TRACE(::testing::Message() + << "write_buffer_for_append=" << write_buffer_for_append + << ", temp_dir=" << static_cast(temp_dir)); + std::map options = { + {Options::FILE_FORMAT, "orc"}, + {Options::WRITE_ONLY, "true"}, + {Options::BUCKET, "12"}, + {Options::BUCKET_KEY, "id"}, + {Options::WRITE_BUFFER_FOR_APPEND, write_buffer_for_append ? "true" : "false"}}; + const bool with_temp_dir = temp_dir == TempDir::kAvailable; + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto tmp_dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(tmp_dir); + CreateTable(dir->Str(), schema, options); + const std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + + WriteContextBuilder builder(table_path, commit_user_); + builder.SetOptions(options); + if (temp_dir == TempDir::kAvailable) { + builder.WithTempDirectory(tmp_dir->Str()); + } else if (temp_dir == TempDir::kUnavailable) { + // A regular file where the spill directory should be created. + const std::string blocker = PathUtil::JoinPath(tmp_dir->Str(), "blocker"); + ASSERT_OK_AND_ASSIGN(auto output, + tmp_dir->GetFileSystem()->Create(blocker, /*overwrite=*/true)); + ASSERT_OK(output->Close()); + builder.WithTempDirectory(PathUtil::JoinPath(blocker, "tmp")); + } + ASSERT_OK_AND_ASSIGN(std::unique_ptr write_context, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto file_store_write, + FileStoreWrite::Create(std::move(write_context))); + auto* write = dynamic_cast(file_store_write.get()); + ASSERT_NE(nullptr, write); + for (int32_t bucket = 0; bucket < 12; ++bucket) { + SCOPED_TRACE(::testing::Message() << "bucket=" << bucket); + auto batch = MakeBatch(schema, "[[" + std::to_string(bucket) + ", 10]]"); + batch->SetBucket(bucket); + ASSERT_OK(file_store_write->Write(std::move(batch))); + ASSERT_EQ(bucket + 1, write->GetActiveWriterCountLocked()); + // With the default write-max-writers-to-spill of 10, creating the 11th writer + // switches, unless there is no temporary directory to spill to. The spill + // directory is first created by the first spillable writer or by the switch; + // if that fails, the writers write data files instead. + ASSERT_EQ(with_temp_dir && bucket >= 10, write->force_buffer_spill_); + ASSERT_EQ( + temp_dir == TempDir::kUnavailable && (write_buffer_for_append || bucket >= 10), + write->spill_directory_unavailable_); + } + std::vector> writers = AppendWriters(write); + ASSERT_EQ(12, writers.size()); + for (const auto& writer : writers) { + ASSERT_NE(nullptr, writer); + if (with_temp_dir || write_buffer_for_append) { + ASSERT_NE(nullptr, writer->GetWriteBuffer()); + ASSERT_EQ(with_temp_dir, writer->GetWriteBuffer()->IsSpillable()); + } else { + ASSERT_EQ(nullptr, writer->GetWriteBuffer()); + } + } + ASSERT_OK_AND_ASSIGN(auto commit_msgs, + file_store_write->PrepareCommit( + /*wait_compaction=*/false, /*commit_identifier=*/0)); + ASSERT_EQ(12, commit_msgs.size()); + ASSERT_EQ(12, ListBucketFiles(table_path).size()); + ASSERT_OK(file_store_write->Close()); + ASSERT_EQ(0, write->GetActiveWriterCountLocked()); + } + } +} + +TEST_F(AppendOnlyFileStoreWriteTest, TestForceBufferSpillWithBlobFields) { + auto schema = + arrow::schema({arrow::field("pt", arrow::utf8()), arrow::field("id", arrow::int32()), + BlobUtils::ToArrowField("blob", /*nullable=*/true)}); + for (bool inline_blob : {true, false}) { + SCOPED_TRACE(::testing::Message() << "inline_blob=" << inline_blob); + std::map options = {{Options::FILE_FORMAT, "orc"}, + {Options::BUCKET, "-1"}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {Options::WRITE_MAX_WRITERS_TO_SPILL, "1"}, + {Options::WRITE_BUFFER_SIZE, "1b"}}; + if (inline_blob) { + options[Options::BLOB_VIEW_FIELD] = "blob"; + } else { + options[Options::WRITE_BUFFER_FOR_APPEND] = "true"; + } + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto tmp_dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(tmp_dir); + CreateTable(dir->Str(), schema, options, /*partition_keys=*/{"pt"}); + const std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + + WriteContextBuilder builder(table_path, commit_user_); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr write_context, + builder.SetOptions(options).WithTempDirectory(tmp_dir->Str()).Finish()); + ASSERT_OK_AND_ASSIGN(auto file_store_write, + FileStoreWrite::Create(std::move(write_context))); + auto* write = dynamic_cast(file_store_write.get()); + ASSERT_NE(nullptr, write); + + auto pool = GetDefaultPool(); + auto write_to_partition = [&](const std::string& partition, int32_t id) -> Status { + arrow::StringBuilder pt_builder; + PAIMON_RETURN_NOT_OK_FROM_ARROW(pt_builder.Append(partition)); + arrow::Int32Builder id_builder; + PAIMON_RETURN_NOT_OK_FROM_ARROW(id_builder.Append(id)); + arrow::LargeBinaryBuilder blob_builder; + if (inline_blob) { + BlobViewStruct view(Identifier("db", "tbl"), /*field_id=*/1, /*row_id=*/id); + PAIMON_ASSIGN_OR_RAISE(PAIMON_UNIQUE_PTR view_bytes, view.Serialize(pool)); + PAIMON_RETURN_NOT_OK_FROM_ARROW( + blob_builder.Append(view_bytes->data(), view_bytes->size())); + } else { + PAIMON_RETURN_NOT_OK_FROM_ARROW(blob_builder.Append("blob-" + std::to_string(id))); + } + std::vector> children(3); + PAIMON_RETURN_NOT_OK_FROM_ARROW(pt_builder.Finish(&children[0])); + PAIMON_RETURN_NOT_OK_FROM_ARROW(id_builder.Finish(&children[1])); + PAIMON_RETURN_NOT_OK_FROM_ARROW(blob_builder.Finish(&children[2])); + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr array, + arrow::StructArray::Make(children, schema->fields())); + ::ArrowArray c_array; + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*array, &c_array)); + RecordBatchBuilder batch_builder(&c_array); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr batch, + batch_builder.SetPartition({{"pt", partition}}).Finish()); + return file_store_write->Write(std::move(batch)); + }; + + ASSERT_OK(write_to_partition("a", 1)); + ASSERT_OK(write_to_partition("b", 2)); + // Inline BLOB fields are buffered like other fields, while BLOBs written to dedicated + // .blob files bypass the write buffer, even with write-buffer-for-append. + ASSERT_EQ(inline_blob, write->force_buffer_spill_); + std::vector> writers = AppendWriters(write); + ASSERT_EQ(2, writers.size()); + for (const auto& writer : writers) { + ASSERT_NE(nullptr, writer); + if (inline_blob) { + ASSERT_NE(nullptr, writer->GetWriteBuffer()); + ASSERT_TRUE(writer->GetWriteBuffer()->IsSpillable()); + } else { + ASSERT_EQ(nullptr, writer->GetWriteBuffer()); + ASSERT_EQ(0, writer->GetMemoryUsage()); + } + } + // The rows partition "a" wrote to a data file are read back into its buffer and spilled, + // and the tiny write buffer of partition "b" spills its rows. + ASSERT_EQ(inline_blob ? 2 : 0, CountSpillFiles(write)); + + ASSERT_OK_AND_ASSIGN(auto commit_msgs, + file_store_write->PrepareCommit( + /*wait_compaction=*/false, /*commit_identifier=*/0)); + ASSERT_EQ(0, CountSpillFiles(write)); + ASSERT_EQ(2, commit_msgs.size()); + ASSERT_OK(file_store_write->Close()); + } +} + +TEST_F(AppendOnlyFileStoreWriteTest, TestForceBufferSpillSkipsRealtimeWrite) { + std::map options = {{Options::FILE_FORMAT, "parquet"}, + {Options::WRITE_ONLY, "true"}, + {Options::BUCKET, "1"}, + {Options::BUCKET_KEY, "id"}, + {Options::REALTIME_ENABLED, "true"}, + {Options::WRITE_BUFFER_FOR_APPEND, "true"}, + {Options::WRITE_MAX_WRITERS_TO_SPILL, "0"}}; + auto logical_schema = + arrow::schema({arrow::field("id", arrow::int32()), arrow::field("name", arrow::utf8())}); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr schema_layout, + RealtimeSchemaLayout::Create(RealtimeStoreMode::APPEND_ONLY, logical_schema)); + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto tmp_dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(tmp_dir); + CreateTable(dir->Str(), logical_schema, options); + const std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + + ASSERT_OK_AND_ASSIGN(std::shared_ptr realtime_context, + RealtimeContext::Create()); + WriteContextBuilder builder(table_path, commit_user_); + ASSERT_OK_AND_ASSIGN(std::unique_ptr write_context, + builder.SetOptions(options) + .WithStreamingMode(true) + .WithRealtimeContext(realtime_context) + .WithTempDirectory(tmp_dir->Str()) + .Finish()); + ASSERT_OK_AND_ASSIGN(auto file_store_write, FileStoreWrite::Create(std::move(write_context))); + auto* write = dynamic_cast(file_store_write.get()); + ASSERT_NE(nullptr, write); + + // The first writer already reaches write-max-writers-to-spill = 0, but real-time writes never + // switch to spillable write buffers. + ASSERT_OK(file_store_write->Write( + MakeBatch(schema_layout->InputSchema(), R"([[10, 1, "a"], [20, 2, "b"]])"))); + ASSERT_FALSE(write->force_buffer_spill_); + ASSERT_OK_AND_ASSIGN(auto prepared, + file_store_write->PrepareCommitWithProgress(/*commit_identifier=*/0)); + ASSERT_EQ(1, prepared.size()); + ASSERT_EQ(2, OnlyNewFile({prepared[0].commit_message})->row_count); + ASSERT_OK(file_store_write->Close()); +} + +TEST_F(AppendOnlyFileStoreWriteTest, TestForceBufferSpillWithFailedSwitch) { + auto schema = + arrow::schema({arrow::field("id", arrow::int32()), arrow::field("v", arrow::int64())}); + std::map options = {{Options::FILE_FORMAT, "orc"}, + {Options::WRITE_ONLY, "true"}, + {Options::BUCKET, "2"}, + {Options::BUCKET_KEY, "id"}, + {Options::WRITE_MAX_WRITERS_TO_SPILL, "1"}}; + auto io_hook = IOHook::GetInstance(); + bool switch_failed = false; + bool run_complete = false; + for (int64_t pos = 0; pos < 200 && !run_complete; ++pos) { + SCOPED_TRACE(::testing::Message() << "io error position=" << pos); + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto tmp_dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(tmp_dir); + CreateTable(dir->Str(), schema, options); + const std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + + WriteContextBuilder builder(table_path, commit_user_); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr write_context, + builder.SetOptions(options).WithTempDirectory(tmp_dir->Str()).Finish()); + ASSERT_OK_AND_ASSIGN(auto file_store_write, + FileStoreWrite::Create(std::move(write_context))); + auto* write = dynamic_cast(file_store_write.get()); + ASSERT_NE(nullptr, write); + auto write_to_bucket = [&](const std::string& json, int32_t bucket) { + auto batch = MakeBatch(schema, json); + batch->SetBucket(bucket); + return file_store_write->Write(std::move(batch)); + }; + ASSERT_OK(write_to_bucket("[[1, 10], [2, 20]]", /*bucket=*/0)); + // Create the spill directory first: failing to create it only skips the switch. + ASSERT_OK(write->io_manager_->GetSpillDir()); + + // Opening the second writer switches the first one, which closes its data file and reads + // it back. + io_hook->Reset(pos, IOHook::Mode::RETURN_ERROR); + Status status = write_to_bucket("[[3, 30]]", /*bucket=*/1); + io_hook->Clear(); + if (status.ok()) { + run_complete = true; + } else { + ASSERT_NOK_WITH_MSG(status, "io hook triggered io error"); + Status retry = write_to_bucket("[[3, 30]]", /*bucket=*/1); + if (!retry.ok()) { + // Bucket 0 lost the rows of its discarded or deleted data file, so the write keeps + // failing instead of committing without them. + ASSERT_NOK_WITH_MSG(retry, "Failed to switch the writer of partition"); + ASSERT_FALSE(write->force_buffer_spill_); + ASSERT_NOK_WITH_MSG(file_store_write->PrepareCommit(/*wait_compaction=*/false, + /*commit_identifier=*/0), + "Append-only writer failed after accepting rows"); + ASSERT_OK(file_store_write->Close()); + switch_failed = true; + continue; + } + } + ASSERT_TRUE(write->force_buffer_spill_); + std::vector> writers = AppendWriters(write); + ASSERT_EQ(2, writers.size()); + for (const auto& writer : writers) { + ASSERT_NE(nullptr, writer); + ASSERT_NE(nullptr, writer->GetWriteBuffer()); + ASSERT_TRUE(writer->GetWriteBuffer()->IsSpillable()); + } + + ASSERT_OK_AND_ASSIGN(auto commit_msgs, + file_store_write->PrepareCommit( + /*wait_compaction=*/false, /*commit_identifier=*/0)); + // Both buckets commit every row exactly once. + auto fs = std::make_shared(); + std::map bucket_rows; + for (const auto& commit_msg : commit_msgs) { + auto msg = std::dynamic_pointer_cast(commit_msg); + ASSERT_NE(nullptr, msg); + for (const auto& file : msg->GetNewFilesIncrement().NewFiles()) { + std::string file_path = PathUtil::JoinPath( + PathUtil::JoinPath(table_path, "bucket-" + std::to_string(msg->Bucket())), + file->file_name); + ASSERT_OK_AND_ASSIGN(bool exists, fs->Exists(file_path)); + ASSERT_TRUE(exists) << file_path; + bucket_rows[msg->Bucket()] += file->row_count; + } + } + ASSERT_EQ((std::map{{0, 2}, {1, 1}}), bucket_rows); + ASSERT_OK(file_store_write->Close()); + } + ASSERT_TRUE(switch_failed); + ASSERT_TRUE(run_complete); +} + } // namespace paimon::test diff --git a/src/paimon/core/table/append_only_file_store_table.cpp b/src/paimon/core/table/append_only_file_store_table.cpp index b8e3906f6..3cc61c6df 100644 --- a/src/paimon/core/table/append_only_file_store_table.cpp +++ b/src/paimon/core/table/append_only_file_store_table.cpp @@ -138,8 +138,8 @@ Result> AppendOnlyFileStoreTable::CreateWrite( file_store_path_factory, snapshot_manager, schema_manager, ctx.GetCommitUser(), root_path_, schema, arrow_schema, write_schema, realtime_schema_layout, partition_schema, dv_maintainer_factory, io_manager, options, ignore_previous_files, ctx.IsStreamingMode(), - ctx.IgnoreNumBucketCheck(), ctx.GetRealtimeContext(), ctx.GetExecutor(), - ctx.GetMemoryPool()); + ctx.IgnoreNumBucketCheck(), ctx.EnableMultiThreadSpill(), ctx.GetRealtimeContext(), + ctx.GetExecutor(), ctx.GetMemoryPool()); if (ctx.GetRealtimeContext() && realtime_deduplicate) { PAIMON_ASSIGN_OR_RAISE(std::optional latest_snapshot, snapshot_manager->LatestSnapshot());