From e215adb0d8ec3383cb1f2eedb57544cd8b038e0c Mon Sep 17 00:00:00 2001 From: XiaoHongbo <27951066+XiaoHongbo-Hope@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:44:16 -0800 Subject: [PATCH 01/19] feat(blob): read Paimon video files Generated-by: OpenAI Codex CLI 0.172.0 (GPT-6.2 Sol) --- docs/source/user_guide/read.rst | 11 + include/paimon/data/blob.h | 14 + include/paimon/data/blob_descriptor.h | 32 ++ src/paimon/common/data/blob.cpp | 16 + src/paimon/common/data/blob_descriptor.cpp | 59 +++- src/paimon/common/data/blob_utils.cpp | 2 +- .../reader/data_file_reader_factory.cpp | 6 +- .../core/operation/abstract_split_read.cpp | 5 +- src/paimon/format/blob/CMakeLists.txt | 9 +- .../format/blob/blob_file_format_factory.cpp | 78 +++++ .../format/blob/video_file_batch_reader.cpp | 282 ++++++++++++++++++ .../format/blob/video_file_batch_reader.h | 100 +++++++ .../blob/video_file_batch_reader_test.cpp | 219 ++++++++++++++ 13 files changed, 820 insertions(+), 13 deletions(-) create mode 100644 src/paimon/format/blob/video_file_batch_reader.cpp create mode 100644 src/paimon/format/blob/video_file_batch_reader.h create mode 100644 src/paimon/format/blob/video_file_batch_reader_test.cpp diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index d55a141c1..0cd00d4e9 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -331,6 +331,17 @@ Implementation Guidance - Do not assume identical overflow semantics across C++ and Java; tests should validate acceptable ranges and nullability. - For timestamp handling, consider precision/range constraints in C++ when interoperating with Java-produced data splits. +Reading Video Columns +--------------------- + +Paimon C++ can read scalar BLOB columns stored in Paimon v1 ``.video`` files. +Each non-null row returns a serialized frame descriptor. Open it with +``Blob::FromDescriptor()``, then use ``Blob::FrameIndex()`` to get the frame's +zero-based position. ``Blob::NewInputStream()`` opens the encoded video payload. +``Blob::MoovOffset()`` and ``Blob::MoovLength()`` locate the optional MP4 +``moov`` box within that payload. Applications decode the video payload with their +own video decoder. + .. _data-evolution-deletion-vectors: Deletion Vectors on Data-Evolution Tables diff --git a/include/paimon/data/blob.h b/include/paimon/data/blob.h index 0b66ce7b6..bfdeac967 100644 --- a/include/paimon/data/blob.h +++ b/include/paimon/data/blob.h @@ -75,8 +75,22 @@ class PAIMON_EXPORT Blob { /// Gets the URI of the blob. const std::string& Uri() const; + /// Whether this blob refers to one logical frame in an encoded video payload. + bool IsVideoFrame() const; + + /// Zero-based frame ordinal, or -1 for a regular blob. + int64_t FrameIndex() const; + + /// Offset and length of the MP4 moov box relative to the encoded video payload. + /// Both values are 0 if absent. + int64_t MoovOffset() const; + int64_t MoovLength() const; + /// Creates an input stream for reading the blob data. /// + /// For a video frame descriptor, the stream contains the encoded video payload. + /// Use `FrameIndex()` to locate the logical frame when decoding the payload. + /// /// @param fs The file system to use for reading. /// @return A result containing the input stream or an error. Result> NewInputStream( diff --git a/include/paimon/data/blob_descriptor.h b/include/paimon/data/blob_descriptor.h index ce53ea2d5..80059479d 100644 --- a/include/paimon/data/blob_descriptor.h +++ b/include/paimon/data/blob_descriptor.h @@ -41,6 +41,10 @@ namespace paimon { /// | 13 | uri_bytes | byte[N] | N | /// | 13 + N | offset | long | 8 | /// | 21 + N | length | long | 8 | +/// +/// A video frame descriptor uses its own magic and version, followed by the same URI, +/// offset and length fields. Three long values follow: the frame ordinal, the MP4 moov +/// box offset and length relative to the video payload. class PAIMON_EXPORT BlobDescriptor { public: @@ -50,6 +54,14 @@ class PAIMON_EXPORT BlobDescriptor { static Result> Create(int8_t version, const std::string& uri, int64_t offset, int64_t length); + /// Create a reference to one logical frame in an encoded video payload. + /// An absent MP4 moov box has offset and length 0. + static Result> CreateVideoFrame(const std::string& uri, + int64_t offset, int64_t length, + int64_t frame_index, + int64_t moov_offset, + int64_t moov_length); + static Result> Deserialize(const char* buffer, uint64_t size); static Result IsBlobDescriptor(const char* buffer, uint64_t size); @@ -74,6 +86,23 @@ class PAIMON_EXPORT BlobDescriptor { return length_; } + bool IsVideoFrame() const { + return frame_index_ >= 0; + } + + /// Zero-based frame ordinal, or -1 for a regular blob. + int64_t FrameIndex() const { + return frame_index_; + } + + int64_t MoovOffset() const { + return moov_offset_; + } + + int64_t MoovLength() const { + return moov_length_; + } + private: BlobDescriptor(int8_t version, const std::string& uri, int64_t offset, int64_t length) : version_(version), uri_(uri), offset_(offset), length_(length) {} @@ -85,6 +114,9 @@ class PAIMON_EXPORT BlobDescriptor { std::string uri_; int64_t offset_ = 0; int64_t length_ = -1; + int64_t frame_index_ = -1; + int64_t moov_offset_ = 0; + int64_t moov_length_ = 0; }; } // namespace paimon diff --git a/src/paimon/common/data/blob.cpp b/src/paimon/common/data/blob.cpp index 707dd475d..653dda9c6 100644 --- a/src/paimon/common/data/blob.cpp +++ b/src/paimon/common/data/blob.cpp @@ -89,6 +89,22 @@ const std::string& Blob::Uri() const { return impl_->Uri(); } +bool Blob::IsVideoFrame() const { + return impl_->GetDescriptor()->IsVideoFrame(); +} + +int64_t Blob::FrameIndex() const { + return impl_->GetDescriptor()->FrameIndex(); +} + +int64_t Blob::MoovOffset() const { + return impl_->GetDescriptor()->MoovOffset(); +} + +int64_t Blob::MoovLength() const { + return impl_->GetDescriptor()->MoovLength(); +} + Result> Blob::NewInputStream( const std::shared_ptr& fs) const { if (fs == nullptr) { diff --git a/src/paimon/common/data/blob_descriptor.cpp b/src/paimon/common/data/blob_descriptor.cpp index 5a020c9fc..9cb3b6be4 100644 --- a/src/paimon/common/data/blob_descriptor.cpp +++ b/src/paimon/common/data/blob_descriptor.cpp @@ -19,6 +19,7 @@ #include "paimon/data/blob_descriptor.h" +#include #include #include "fmt/format.h" @@ -34,6 +35,8 @@ namespace paimon { namespace { constexpr int64_t kMagic = 0x424C4F4244455343l; +constexpr int64_t kVideoFrameMagic = 0x564944454F46524D; +constexpr int8_t kVideoFrameVersion = 1; // One byte for version, eight bytes for magic number. constexpr uint64_t kMinDescriptorLength = 9; @@ -57,22 +60,47 @@ Result> BlobDescriptor::Create(int8_t version, return std::unique_ptr(new BlobDescriptor(version, uri, offset, length)); } +Result> BlobDescriptor::CreateVideoFrame( + const std::string& uri, int64_t offset, int64_t length, int64_t frame_index, + int64_t moov_offset, int64_t moov_length) { + if (frame_index < 0 || moov_offset < 0 || moov_length < 0 || + uri.size() > std::numeric_limits::max() || + (moov_length == 0 ? moov_offset != 0 + : moov_offset > length || moov_length > length - moov_offset)) { + return Status::Invalid("invalid video frame descriptor range"); + } + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr descriptor, + Create(kVideoFrameVersion, uri, offset, length)); + descriptor->frame_index_ = frame_index; + descriptor->moov_offset_ = moov_offset; + descriptor->moov_length_ = moov_length; + return descriptor; +} + PAIMON_UNIQUE_PTR BlobDescriptor::Serialize(const std::shared_ptr& pool) const { MemorySegmentOutputStream out(MemorySegmentOutputStream::DEFAULT_SEGMENT_SIZE, pool); out.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); - out.WriteValue(kCurrentVersion); - out.WriteValue(kMagic); + out.WriteValue(IsVideoFrame() ? kVideoFrameVersion : kCurrentVersion); + out.WriteValue(IsVideoFrame() ? kVideoFrameMagic : kMagic); out.WriteValue(static_cast(uri_.size())); auto uri_bytes = std::make_shared(uri_, pool.get()); out.WriteBytes(uri_bytes); out.WriteValue(offset_); out.WriteValue(length_); + if (IsVideoFrame()) { + out.WriteValue(frame_index_); + out.WriteValue(moov_offset_); + out.WriteValue(moov_length_); + } return MemorySegmentUtils::CopyToBytes(out.Segments(), 0, out.CurrentSize(), pool.get()); } Result> BlobDescriptor::Deserialize(const char* buffer, uint64_t size) { + if (buffer == nullptr || size == 0) { + return Status::Invalid("empty blob descriptor"); + } auto input_stream = std::make_shared(buffer, size); DataInputStream in(std::move(input_stream)); in.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); @@ -82,7 +110,14 @@ Result> BlobDescriptor::Deserialize(const char* "Expecting BlobDescriptor version to be less than or equal to {}, but found {}.", kCurrentVersion, version)); } - if (version > 1) { + bool video_frame = false; + if (version == kVideoFrameVersion && size >= kMinDescriptorLength) { + PAIMON_ASSIGN_OR_RAISE(int64_t magic, in.ReadValue()); + video_frame = magic == kVideoFrameMagic; + if (!video_frame) { + PAIMON_RETURN_NOT_OK(in.Seek(1)); + } + } else if (version > 1) { PAIMON_ASSIGN_OR_RAISE(int64_t magic, in.ReadValue()); if (kMagic != magic) { return Status::Invalid(fmt::format( @@ -91,15 +126,29 @@ Result> BlobDescriptor::Deserialize(const char* } } PAIMON_ASSIGN_OR_RAISE(int32_t uri_length, in.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t uri_start, in.GetPos()); + const uint64_t fixed_tail_size = (video_frame ? 5 : 2) * sizeof(int64_t); + const uint64_t remaining_size = size - uri_start; + if (uri_length < 0 || remaining_size < fixed_tail_size || + static_cast(uri_length) > remaining_size - fixed_tail_size || + (video_frame && static_cast(uri_length) != remaining_size - fixed_tail_size)) { + return Status::Invalid("invalid blob descriptor length"); + } std::string uri(uri_length, '\0'); PAIMON_RETURN_NOT_OK(in.Read(uri.data(), uri.size())); PAIMON_ASSIGN_OR_RAISE(int64_t offset, in.ReadValue()); PAIMON_ASSIGN_OR_RAISE(int64_t length, in.ReadValue()); + if (video_frame) { + PAIMON_ASSIGN_OR_RAISE(int64_t frame_index, in.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t moov_offset, in.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t moov_length, in.ReadValue()); + return CreateVideoFrame(uri, offset, length, frame_index, moov_offset, moov_length); + } return BlobDescriptor::Create(version, uri, offset, length); } Result BlobDescriptor::IsBlobDescriptor(const char* buffer, uint64_t size) { - if (size < kMinDescriptorLength) { + if (buffer == nullptr || size < kMinDescriptorLength) { return false; } auto input_stream = std::make_shared(buffer, size); @@ -110,7 +159,7 @@ Result BlobDescriptor::IsBlobDescriptor(const char* buffer, uint64_t size) return false; } PAIMON_ASSIGN_OR_RAISE(int64_t magic, in.ReadValue()); - return kMagic == magic; + return kMagic == magic || (version == kVideoFrameVersion && kVideoFrameMagic == magic); } std::string BlobDescriptor::ToString() const { diff --git a/src/paimon/common/data/blob_utils.cpp b/src/paimon/common/data/blob_utils.cpp index fd12cbcd9..1afd2d5b2 100644 --- a/src/paimon/common/data/blob_utils.cpp +++ b/src/paimon/common/data/blob_utils.cpp @@ -195,7 +195,7 @@ bool BlobUtils::IsBlobMetadata(const std::shared_ptr BlobUtils::ToArrowField( diff --git a/src/paimon/common/reader/data_file_reader_factory.cpp b/src/paimon/common/reader/data_file_reader_factory.cpp index edaac8301..b481d64c3 100644 --- a/src/paimon/common/reader/data_file_reader_factory.cpp +++ b/src/paimon/common/reader/data_file_reader_factory.cpp @@ -41,9 +41,9 @@ namespace { // files (FormatTable::ParseFormat accepts only parquet/orc), so this only concerns the managed // table path. bool FormatSupportsPrefetch(const std::string& format_identifier) { - return format_identifier != "blob" && format_identifier != "avro" && - format_identifier != "lance" && format_identifier != "mosaic" && - format_identifier != "vortex"; + return format_identifier != "blob" && format_identifier != "video" && + format_identifier != "avro" && format_identifier != "lance" && + format_identifier != "mosaic" && format_identifier != "vortex"; } } // namespace diff --git a/src/paimon/core/operation/abstract_split_read.cpp b/src/paimon/core/operation/abstract_split_read.cpp index f14e2cede..6c2043d55 100644 --- a/src/paimon/core/operation/abstract_split_read.cpp +++ b/src/paimon/core/operation/abstract_split_read.cpp @@ -463,7 +463,8 @@ Result> AbstractSplitRead::CreateFieldMappingRe file_reader = std::make_unique(std::move(file_reader), arrow_pool_); } std::set skip_map_selected_keys_filter_field_ids; - if (file_format_identifier != "blob") { + const bool is_blob_file = BlobUtils::IsBlobFile(file_meta->file_name); + if (!is_blob_file) { std::pair, std::set> shredding_result; PAIMON_ASSIGN_OR_RAISE(shredding_result, ApplyShreddingReaderIfNeeded(std::move(file_reader), read_schema)); @@ -474,7 +475,7 @@ Result> AbstractSplitRead::CreateFieldMappingRe // A blob file has no self-describing schema: its physical fields are declared by the // file meta's write cols instead of queried from the format reader. std::optional> file_field_names; - if (file_format_identifier == "blob") { + if (is_blob_file) { file_field_names = file_meta->write_cols; } file_reader = std::make_unique( diff --git a/src/paimon/format/blob/CMakeLists.txt b/src/paimon/format/blob/CMakeLists.txt index 239a936a9..8a4a9f1c6 100644 --- a/src/paimon/format/blob/CMakeLists.txt +++ b/src/paimon/format/blob/CMakeLists.txt @@ -14,8 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -set(PAIMON_BLOB_FILE_FORMAT blob_file_batch_reader.cpp blob_file_format_factory.cpp - blob_format_writer.cpp blob_stats_extractor.cpp) +set(PAIMON_BLOB_FILE_FORMAT + blob_file_batch_reader.cpp + blob_file_format_factory.cpp + blob_format_writer.cpp + blob_stats_extractor.cpp + video_file_batch_reader.cpp) add_paimon_lib(paimon_blob_file_format SOURCES @@ -41,6 +45,7 @@ if(PAIMON_BUILD_TESTS) blob_stats_extractor_test.cpp blob_writer_builder_test.cpp blob_file_format_factory_test.cpp + video_file_batch_reader_test.cpp EXTRA_INCLUDES ${BLOB_INCLUDE_DIR} STATIC_LINK_LIBS diff --git a/src/paimon/format/blob/blob_file_format_factory.cpp b/src/paimon/format/blob/blob_file_format_factory.cpp index 8d0f858df..058a61d84 100644 --- a/src/paimon/format/blob/blob_file_format_factory.cpp +++ b/src/paimon/format/blob/blob_file_format_factory.cpp @@ -20,10 +20,87 @@ #include +#include "paimon/common/data/blob_defs.h" +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/common/utils/options_utils.h" #include "paimon/factories/factory.h" #include "paimon/format/blob/blob_file_format.h" +#include "paimon/format/blob/video_file_batch_reader.h" namespace paimon::blob { +namespace { + +class VideoReaderBuilder : public ReaderBuilder, public BlobReadContextAwareBuilder { + public: + VideoReaderBuilder(int32_t batch_size, bool emit_placeholder_sentinel) + : batch_size_(batch_size), emit_placeholder_sentinel_(emit_placeholder_sentinel) {} + + ReaderBuilder* WithMemoryPool(const std::shared_ptr& pool) override { + pool_ = pool; + return this; + } + + void SetBlobReadContext(const std::shared_ptr& context) override { + blob_context_ = context; + } + + Result> Build( + const std::shared_ptr& input) const override { + return VideoFileBatchReader::Create(input, batch_size_, pool_, emit_placeholder_sentinel_, + blob_context_); + } + + private: + int32_t batch_size_; + bool emit_placeholder_sentinel_; + std::shared_ptr pool_ = GetDefaultPool(); + std::shared_ptr blob_context_; +}; + +class VideoFileFormat : public FileFormat { + public: + explicit VideoFileFormat(bool emit_placeholder_sentinel) + : emit_placeholder_sentinel_(emit_placeholder_sentinel) {} + + const std::string& Identifier() const override { + static const std::string identifier = "video"; + return identifier; + } + + Result> CreateReaderBuilder(int32_t batch_size) const override { + return std::make_unique(batch_size, emit_placeholder_sentinel_); + } + + Result> CreateWriterBuilder(::ArrowSchema*, + int32_t) const override { + return Status::NotImplemented("video writing is not supported"); + } + + Result> CreateStatsExtractor( + ::ArrowSchema*) const override { + return Status::NotImplemented("video stats extraction is not supported"); + } + + private: + bool emit_placeholder_sentinel_; +}; + +class VideoFileFormatFactory : public FileFormatFactory { + public: + const char* Identifier() const override { + return "video"; + } + + Result> Create( + const std::map& options) const override { + PAIMON_ASSIGN_OR_RAISE(bool emit_placeholder_sentinel, + OptionsUtils::GetValueFromMap( + options, BlobDefs::kEmitPlaceholderSentinelKey, false)); + return std::make_unique(emit_placeholder_sentinel); + } +}; + +} // namespace const char BlobFileFormatFactory::IDENTIFIER[] = "blob"; @@ -33,5 +110,6 @@ Result> BlobFileFormatFactory::Create( } REGISTER_PAIMON_FACTORY(BlobFileFormatFactory); +REGISTER_PAIMON_FACTORY(VideoFileFormatFactory); } // namespace paimon::blob diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp new file mode 100644 index 000000000..5b859906f --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -0,0 +1,282 @@ +/* + * 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/format/blob/video_file_batch_reader.h" + +#include +#include +#include + +#include "arrow/api.h" +#include "arrow/c/bridge.h" +#include "paimon/common/data/blob_defs.h" +#include "paimon/common/data/blob_utils.h" +#include "paimon/common/metrics/metrics_impl.h" +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/common/utils/arrow/mem_utils.h" +#include "paimon/common/utils/arrow/status_utils.h" +#include "paimon/common/utils/delta_varint_compressor.h" +#include "paimon/data/blob_descriptor.h" +#include "paimon/fs/file_system.h" +#include "paimon/io/byte_array_input_stream.h" +#include "paimon/io/data_input_stream.h" + +namespace paimon::blob { +namespace { + +// Encoded video payloads, six delta varint indexes, then the footer. +// The footer stores six little endian int32 index lengths followed by the magic and version. +constexpr int64_t kFooterSize = 29; +constexpr int32_t kMagic = 0x4F454449; +constexpr int8_t kVersion = 1; +constexpr int64_t kNullReference = -1; +constexpr int64_t kPlaceholderReference = -2; + +Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) { + for (int64_t read = 0; read < size;) { + PAIMON_ASSIGN_OR_RAISE(int64_t n, input->Read(data + read, size - read, offset + read)); + if (n <= 0) { + return Status::Invalid("truncated video file"); + } + read += n; + } + return Status::OK(); +} + +} // namespace + +VideoFileBatchReader::VideoFileBatchReader(std::string uri, int32_t batch_size, + std::shared_ptr pool, + bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context) + : uri_(std::move(uri)), + batch_size_(batch_size), + pool_(std::move(pool)), + arrow_pool_(GetArrowPool(pool_)), + metrics_(std::make_shared()), + emit_placeholder_sentinel_(emit_placeholder_sentinel), + blob_context_(blob_context) {} + +Result> VideoFileBatchReader::Create( + const std::shared_ptr& input, int32_t batch_size, + const std::shared_ptr& pool, bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context) { + if (!input || !pool || batch_size <= 0) { + return Status::Invalid("invalid video reader input, pool, or batch size"); + } + PAIMON_ASSIGN_OR_RAISE(int64_t size, input->Length()); + if (size < kFooterSize) { + return Status::Invalid("video file is smaller than its footer"); + } + char footer[kFooterSize]; + PAIMON_RETURN_NOT_OK(ReadAtFully(input.get(), size - kFooterSize, footer, sizeof(footer))); + DataInputStream footer_input(std::make_shared(footer, sizeof(footer))); + footer_input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); + std::array index_lengths; + int64_t index_start = size - kFooterSize; + for (int32_t& index_length : index_lengths) { + PAIMON_ASSIGN_OR_RAISE(index_length, footer_input.ReadValue()); + if (index_length < 0 || index_length > index_start) { + return Status::Invalid("video indexes exceed the file size"); + } + index_start -= index_length; + } + PAIMON_ASSIGN_OR_RAISE(int32_t magic, footer_input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int8_t version, footer_input.ReadValue()); + if (magic != kMagic || version != kVersion) { + return Status::Invalid("invalid or unsupported video file footer"); + } + std::array, 6> indexes; + int64_t index_offset = index_start; + for (size_t i = 0; i < indexes.size(); ++i) { + std::vector bytes(index_lengths[i]); + PAIMON_RETURN_NOT_OK(ReadAtFully(input.get(), index_offset, bytes.data(), bytes.size())); + PAIMON_ASSIGN_OR_RAISE(indexes[i], DeltaVarintCompressor::Decompress(bytes)); + index_offset += index_lengths[i]; + } + + const auto& video_lengths = indexes[0]; + const auto& moov_offsets = indexes[1]; + const auto& moov_lengths = indexes[2]; + const auto& run_lengths = indexes[3]; + const auto& references = indexes[4]; + const auto& first_frames = indexes[5]; + if (video_lengths.size() != moov_offsets.size() || + video_lengths.size() != moov_lengths.size() || run_lengths.size() != references.size() || + run_lengths.size() != first_frames.size()) { + return Status::Invalid("video indexes have inconsistent entry counts"); + } + + PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); + auto reader = std::unique_ptr(new VideoFileBatchReader( + std::move(uri), batch_size, pool, emit_placeholder_sentinel, blob_context)); + int64_t payload_offset = 0; + reader->videos_.reserve(video_lengths.size()); + for (size_t i = 0; i < video_lengths.size(); ++i) { + const int64_t length = video_lengths[i]; + if (length <= 0 || length > index_start - payload_offset) { + return Status::Invalid("invalid video payload length"); + } + const int64_t moov_offset = moov_offsets[i]; + const int64_t moov_length = moov_lengths[i]; + if (moov_offset < 0 || moov_length < 0 || moov_offset > length || + moov_length > length - moov_offset || (moov_length == 0 && moov_offset != 0)) { + return Status::Invalid("invalid moov range in video payload"); + } + reader->videos_.push_back({payload_offset, length, moov_offset, moov_length}); + payload_offset += length; + } + if (payload_offset != index_start) { + return Status::Invalid("video payload length does not match its index"); + } + + int64_t rows = 0; + reader->runs_.reserve(run_lengths.size()); + for (size_t i = 0; i < run_lengths.size(); ++i) { + const int64_t length = run_lengths[i]; + const int64_t ref = references[i]; + const int64_t first = first_frames[i]; + if (length <= 0 || length > std::numeric_limits::max() - rows || + (ref != kNullReference && ref != kPlaceholderReference && + (ref < 0 || static_cast(ref) >= video_lengths.size())) || + (ref >= 0 && + (first < 0 || first > std::numeric_limits::max() - (length - 1)))) { + return Status::Invalid("invalid video frame run"); + } + rows += length; + reader->runs_.push_back({static_cast(rows), ref, first}); + } + reader->row_count_ = rows; + return reader; +} + +Result> VideoFileBatchReader::GetFileSchema() const { + return Status::NotImplemented("video files have no self-describing schema"); +} + +Status VideoFileBatchReader::SetReadSchema(::ArrowSchema* schema, const std::shared_ptr&, + const std::optional& selection) { + if (!schema) { + return Status::Invalid("video read schema is null"); + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr arrow_schema, + arrow::ImportSchema(schema)); + if (arrow_schema->num_fields() != 1 || !BlobUtils::IsBlobField(arrow_schema->field(0))) { + return Status::Invalid("video reader requires one scalar BLOB field"); + } + std::optional> selected_rows; + if (selection) { + selected_rows.emplace(); + for (auto it = selection->Begin(); it != selection->End(); ++it) { + const uint64_t row = *it; + if (row >= row_count_) { + return Status::Invalid("video selection row exceeds row count"); + } + selected_rows->push_back(row); + } + } + + selected_rows_ = std::move(selected_rows); + field_ = arrow_schema->field(0); + current_ = 0; + previous_batch_size_ = 0; + return Status::OK(); +} + +uint64_t VideoFileBatchReader::FileRowAt(uint64_t position) const { + return selected_rows_ ? (*selected_rows_)[position] : position; +} + +Result VideoFileBatchReader::GetPreviousBatchFileRowId(uint64_t batch_row_id) const { + if (batch_row_id >= previous_batch_size_) { + return Status::Invalid("video batch row ID is out of range"); + } + return FileRowAt(current_ - previous_batch_size_ + batch_row_id); +} + +Result VideoFileBatchReader::GetNumberOfRows() const { + return row_count_; +} + +std::shared_ptr VideoFileBatchReader::GetReaderMetrics() const { + return metrics_; +} + +void VideoFileBatchReader::Close() { + closed_ = true; +} + +Result VideoFileBatchReader::NextBatch() { + if (closed_ || !field_) { + return Status::Invalid("video reader is closed or read schema is unset"); + } + const uint64_t total = selected_rows_ ? selected_rows_->size() : row_count_; + if (current_ >= total) { + previous_batch_size_ = 0; + return BatchReader::MakeEofBatch(); + } + const auto request = blob_context_ ? blob_context_->request : std::nullopt; + if (request && request->max_rows <= 0) { + return Status::Invalid("video read batch row limit must be positive"); + } + const uint64_t batch_limit = request ? std::min(batch_size_, request->max_rows) : batch_size_; + const uint64_t count = std::min(batch_limit, total - current_); + arrow::LargeBinaryBuilder builder(arrow_pool_.get()); + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Reserve(count)); + for (uint64_t i = 0; i < count; ++i) { + if (request && !request->read_payload) { + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); + continue; + } + const uint64_t row = FileRowAt(current_ + i); + const auto run = + std::upper_bound(runs_.begin(), runs_.end(), row, + [](uint64_t row, const FrameRun& run) { return row < run.end; }); + if (run->reference == kNullReference) { + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); + } else if (run->reference == kPlaceholderReference) { + if (!emit_placeholder_sentinel_) { + return Status::Invalid("video placeholder requires the blob fallback read path"); + } + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Append(BlobDefs::PlaceholderSentinelView())); + } else { + const auto& video = videos_[run->reference]; + const uint64_t run_start = run == runs_.begin() ? 0 : (run - 1)->end; + const int64_t frame = run->first_frame + static_cast(row - run_start); + PAIMON_ASSIGN_OR_RAISE( + std::unique_ptr descriptor, + BlobDescriptor::CreateVideoFrame(uri_, video.offset, video.length, frame, + video.moov_offset, video.moov_length)); + auto bytes = descriptor->Serialize(pool_); + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Append(bytes->data(), bytes->size())); + } + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr values, builder.Finish()); + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr array, + arrow::StructArray::Make({values}, {field_})); + auto c_array = std::make_unique<::ArrowArray>(); + auto c_schema = std::make_unique<::ArrowSchema>(); + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*array, c_array.get(), c_schema.get())); + PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(c_array.get(), c_schema.get(), arrow_pool_)); + current_ += count; + previous_batch_size_ = count; + return std::make_pair(std::move(c_array), std::move(c_schema)); +} + +} // namespace paimon::blob diff --git a/src/paimon/format/blob/video_file_batch_reader.h b/src/paimon/format/blob/video_file_batch_reader.h new file mode 100644 index 000000000..cde62018e --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include "paimon/reader/file_batch_reader.h" + +namespace arrow { +class Field; +class MemoryPool; +} // namespace arrow + +namespace paimon { +class InputStream; +class MemoryPool; +struct BlobReadContext; +} // namespace paimon + +namespace paimon::blob { + +/// Reads the row index of a Paimon v1 .video file and emits lazy frame descriptors. +class VideoFileBatchReader : public FileBatchReader { + public: + static Result> Create( + const std::shared_ptr& input, int32_t batch_size, + const std::shared_ptr& pool, bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context); + + Result> GetFileSchema() const override; + Status SetReadSchema(::ArrowSchema* schema, const std::shared_ptr& predicate, + const std::optional& selection) override; + Result NextBatch() override; + Result GetPreviousBatchFileRowId(uint64_t batch_row_id) const override; + Result GetNumberOfRows() const override; + std::shared_ptr GetReaderMetrics() const override; + void Close() override; + bool SupportPreciseBitmapSelection() const override { + return true; + } + + private: + struct VideoRange { + int64_t offset; + int64_t length; + int64_t moov_offset; + int64_t moov_length; + }; + + struct FrameRun { + uint64_t end; + int64_t reference; + int64_t first_frame; + }; + + VideoFileBatchReader(std::string uri, int32_t batch_size, std::shared_ptr pool, + bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context); + + uint64_t FileRowAt(uint64_t position) const; + + std::string uri_; + int32_t batch_size_; + std::shared_ptr pool_; + std::shared_ptr arrow_pool_; + std::shared_ptr field_; + std::shared_ptr metrics_; + bool emit_placeholder_sentinel_; + std::shared_ptr blob_context_; + std::vector videos_; + std::vector runs_; + std::optional> selected_rows_; + uint64_t row_count_ = 0; + uint64_t current_ = 0; + uint64_t previous_batch_size_ = 0; + bool closed_ = false; +}; + +} // namespace paimon::blob diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp new file mode 100644 index 000000000..f26227078 --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -0,0 +1,219 @@ +/* + * 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/format/blob/video_file_batch_reader.h" + +#include "arrow/api.h" +#include "arrow/c/bridge.h" +#include "gtest/gtest.h" +#include "paimon/common/data/blob_defs.h" +#include "paimon/common/data/blob_utils.h" +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/common/utils/delta_varint_compressor.h" +#include "paimon/data/blob.h" +#include "paimon/data/blob_descriptor.h" +#include "paimon/format/file_format.h" +#include "paimon/format/file_format_factory.h" +#include "paimon/fs/local/local_file_system.h" +#include "paimon/testing/utils/testharness.h" + +namespace paimon::test { +namespace { + +using blob::VideoFileBatchReader; + +void Append32(std::string* data, uint32_t value) { + for (int32_t i = 0; i < 4; ++i) { + data->push_back(static_cast(value >> (8 * i))); + } +} + +std::string MakeVideoFile(bool placeholder = false, int64_t first_moov_length = 3) { + std::string data = "VIDEOfilm"; + const std::vector> indexes = { + {5, 4}, {2, 0}, {first_moov_length, 0}, {2, 1, 1}, {0, placeholder ? -2 : -1, 1}, + {4, 0, 9}}; + std::vector sizes; + for (const auto& values : indexes) { + const auto bytes = DeltaVarintCompressor::Compress(values); + sizes.push_back(bytes.size()); + data.append(bytes.data(), bytes.size()); + } + for (auto size : sizes) { + Append32(&data, size); + } + Append32(&data, 0x4f454449); + data.push_back(1); + return data; +} + +TEST(VideoFileBatchReaderTest, ReadsJavaCompatibleRunsAndSelection) { + auto dir = paimon::test::UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto fs = std::make_shared(); + const std::string path = dir->Str() + "/part.video"; + ASSERT_OK(fs->WriteFile(path, MakeVideoFile(), true)); + ASSERT_OK_AND_ASSIGN(auto input, fs->Open(path)); + std::shared_ptr shared_input(std::move(input)); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(shared_input)); + ASSERT_OK_AND_ASSIGN(uint64_t row_count, reader->GetNumberOfRows()); + ASSERT_EQ(row_count, 4); + + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, std::nullopt)); + + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_OK_AND_ASSIGN(uint64_t row_id, reader->GetPreviousBatchFileRowId(0)); + ASSERT_EQ(row_id, 0); + auto imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status(); + auto array = imported.ValueOrDie(); + auto rows = std::dynamic_pointer_cast(array); + auto blobs = std::dynamic_pointer_cast(rows->field(0)); + ASSERT_EQ(blobs->length(), 2); + for (int32_t i = 0; i < 2; ++i) { + auto bytes = blobs->GetView(i); + ASSERT_OK_AND_ASSIGN(auto blob, Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(blob->IsVideoFrame()); + ASSERT_EQ(blob->FrameIndex(), 4 + i); + ASSERT_EQ(blob->MoovOffset(), 2); + ASSERT_EQ(blob->MoovLength(), 3); + ASSERT_OK_AND_ASSIGN(bool recognized, + BlobDescriptor::IsBlobDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(recognized); + auto serialized = blob->ToDescriptor(GetDefaultPool()); + ASSERT_EQ(std::string_view(serialized->data(), serialized->size()), bytes); + ASSERT_OK_AND_ASSIGN(auto payload, blob->ToData(fs, GetDefaultPool())); + ASSERT_EQ(std::string_view(payload->data(), payload->size()), "VIDEO"); + } + + ASSERT_OK_AND_ASSIGN(batch, reader->NextBatch()); + imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status(); + array = imported.ValueOrDie(); + rows = std::dynamic_pointer_cast(array); + blobs = std::dynamic_pointer_cast(rows->field(0)); + ASSERT_TRUE(blobs->IsNull(0)); + auto bytes = blobs->GetView(1); + ASSERT_OK_AND_ASSIGN(auto blob, Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_EQ(blob->FrameIndex(), 9); + ASSERT_EQ(blob->MoovOffset(), 0); + ASSERT_EQ(blob->MoovLength(), 0); + ASSERT_OK_AND_ASSIGN(auto second_payload, blob->ToData(fs, GetDefaultPool())); + ASSERT_EQ(std::string_view(second_payload->data(), second_payload->size()), "film"); + + ::ArrowSchema selected_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &selected_schema).ok()); + RoaringBitmap32 bitmap; + bitmap.Add(0); + bitmap.Add(3); + ASSERT_OK(reader->SetReadSchema(&selected_schema, nullptr, bitmap)); + ASSERT_OK_AND_ASSIGN(batch, reader->NextBatch()); + ASSERT_OK_AND_ASSIGN(row_id, reader->GetPreviousBatchFileRowId(0)); + ASSERT_EQ(row_id, 0); + ASSERT_OK_AND_ASSIGN(row_id, reader->GetPreviousBatchFileRowId(1)); + ASSERT_EQ(row_id, 3); + + ::ArrowSchema empty_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &empty_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&empty_schema, nullptr, RoaringBitmap32())); + ASSERT_OK_AND_ASSIGN(auto empty_batch, reader->NextBatch()); + ASSERT_TRUE(BatchReader::IsEofBatch(empty_batch)); + ASSERT_NOK(reader->GetPreviousBatchFileRowId(0)); + reader.reset(); + // The exported array keeps its Arrow allocator alive after the reader is destroyed. + imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status(); + ASSERT_EQ(imported.ValueOrDie()->length(), 2); +} + +TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { + auto dir = paimon::test::UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto fs = std::make_shared(); + const std::string path = dir->Str() + "/bad.video"; + auto bytes = MakeVideoFile(); + bytes.back() = 2; + ASSERT_OK(fs->WriteFile(path, bytes, true)); + ASSERT_OK_AND_ASSIGN(auto input, fs->Open(path)); + std::shared_ptr shared_input(std::move(input)); + ASSERT_NOK(VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr)); +} + +TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto fs = std::make_shared(); + const std::string path = dir->Str() + "/bad.video"; + ASSERT_OK( + fs->WriteFile(path, MakeVideoFile(/*placeholder=*/false, /*first_moov_length=*/4), true)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs->Open(path)); + ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), + "invalid moov range"); +} + +TEST(VideoFileBatchReaderTest, ExposesPlaceholdersOnlyForBlobFallback) { + auto dir = paimon::test::UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto fs = std::make_shared(); + const std::string path = dir->Str() + "/part.video"; + ASSERT_OK(fs->WriteFile(path, MakeVideoFile(/*placeholder=*/true), true)); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + for (bool fallback : {false, true}) { + std::map options; + if (fallback) { + options[BlobDefs::kEmitPlaceholderSentinelKey] = "true"; + } + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", options)); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(4)); + auto* context_builder = dynamic_cast(builder.get()); + ASSERT_TRUE(context_builder); + auto context = std::make_shared(); + context_builder->SetBlobReadContext(context); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs->Open(path)); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(input)); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, std::nullopt)); + if (!fallback) { + ASSERT_NOK(reader->NextBatch()); + continue; + } + context->request = BlobBatchRequest{2, /*read_payload=*/false}; + ASSERT_OK_AND_ASSIGN(auto skipped_batch, reader->NextBatch()); + auto skipped = arrow::ImportArray(skipped_batch.first.get(), skipped_batch.second.get()); + ASSERT_TRUE(skipped.ok()) << skipped.status(); + ASSERT_EQ(skipped.ValueOrDie()->length(), 2); + context->request = BlobBatchRequest{1, /*read_payload=*/true}; + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + auto imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status(); + auto rows = std::static_pointer_cast(imported.ValueOrDie()); + auto blobs = std::static_pointer_cast(rows->field(0)); + ASSERT_EQ(blobs->length(), 1); + ASSERT_EQ(blobs->GetView(0), BlobDefs::PlaceholderSentinelView()); + } +} + +} // namespace +} // namespace paimon::test From b4bbe8da9b6bee126fa5bb0705625dbce58d9217 Mon Sep 17 00:00:00 2001 From: XiaoHongbo <27951066+XiaoHongbo-Hope@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:55:47 -0800 Subject: [PATCH 02/19] fix(blob): avoid copying optional video read requests Generated-by: OpenAI Codex CLI 0.172.0 (GPT-6.2 Sol) --- src/paimon/format/blob/video_file_batch_reader.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 5b859906f..35cb1b2af 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -231,7 +231,8 @@ Result VideoFileBatchReader::NextBatch() { previous_batch_size_ = 0; return BatchReader::MakeEofBatch(); } - const auto request = blob_context_ ? blob_context_->request : std::nullopt; + const BlobBatchRequest* request = + blob_context_ && blob_context_->request ? &blob_context_->request.value() : nullptr; if (request && request->max_rows <= 0) { return Status::Invalid("video read batch row limit must be positive"); } From d90c80bc7f04c98eda73e2ef07e315da06d463e0 Mon Sep 17 00:00:00 2001 From: XiaoHongbo <27951066+XiaoHongbo-Hope@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:00:41 -0800 Subject: [PATCH 03/19] fix(blob): preserve video frame identity and descriptor ABI Generated-by: OpenAI Codex CLI 0.172.0 (GPT-6.2 Sol) --- docs/source/user_guide/read.rst | 13 +- include/paimon/data/blob_descriptor.h | 32 ----- src/paimon/CMakeLists.txt | 1 + src/paimon/common/data/blob.cpp | 27 +++-- src/paimon/common/data/blob_defs.h | 3 + src/paimon/common/data/blob_descriptor.cpp | 59 ++-------- .../common/data/video_frame_descriptor.cpp | 111 ++++++++++++++++++ .../common/data/video_frame_descriptor.h | 72 ++++++++++++ src/paimon/core/append/append_only_writer.cpp | 13 ++ src/paimon/format/blob/blob_format_writer.cpp | 4 + .../format/blob/blob_format_writer_test.cpp | 17 +++ .../format/blob/video_file_batch_reader.cpp | 8 +- .../blob/video_file_batch_reader_test.cpp | 26 +++- src/paimon/testing/utils/video_test_utils.h | 62 ++++++++++ test/inte/blob_table_inte_test.cpp | 94 +++++++++++++++ .../video-frame-descriptor-v1.hex | 20 ++++ .../video_format.data/video-v1-moov.hex | 20 ++++ 17 files changed, 489 insertions(+), 93 deletions(-) create mode 100644 src/paimon/common/data/video_frame_descriptor.cpp create mode 100644 src/paimon/common/data/video_frame_descriptor.h create mode 100644 src/paimon/testing/utils/video_test_utils.h create mode 100644 test/test_data/video_format.data/video-frame-descriptor-v1.hex create mode 100644 test/test_data/video_format.data/video-v1-moov.hex diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index 0cd00d4e9..adbe2d468 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -334,14 +334,23 @@ Implementation Guidance Reading Video Columns --------------------- -Paimon C++ can read scalar BLOB columns stored in Paimon v1 ``.video`` files. -Each non-null row returns a serialized frame descriptor. Open it with +Paimon C++ reads scalar BLOB columns stored in Paimon v1 ``.video`` files with +a 29-byte footer and six indexes. Earlier files with a five-index footer also +use version 1. Reimport those files with a current Java Paimon writer before +reading them with Paimon C++. + +Each non-null row returns a serialized frame descriptor, including when +``blob-as-descriptor=false``. Open the descriptor with ``Blob::FromDescriptor()``, then use ``Blob::FrameIndex()`` to get the frame's zero-based position. ``Blob::NewInputStream()`` opens the encoded video payload. ``Blob::MoovOffset()`` and ``Blob::MoovLength()`` locate the optional MP4 ``moov`` box within that payload. Applications decode the video payload with their own video decoder. +Write video columns with a Java Paimon writer. Paimon C++ rejects writes to +columns configured in ``video-frame-field`` and rejects frame descriptors +passed to the ordinary BLOB writer. + .. _data-evolution-deletion-vectors: Deletion Vectors on Data-Evolution Tables diff --git a/include/paimon/data/blob_descriptor.h b/include/paimon/data/blob_descriptor.h index 80059479d..ce53ea2d5 100644 --- a/include/paimon/data/blob_descriptor.h +++ b/include/paimon/data/blob_descriptor.h @@ -41,10 +41,6 @@ namespace paimon { /// | 13 | uri_bytes | byte[N] | N | /// | 13 + N | offset | long | 8 | /// | 21 + N | length | long | 8 | -/// -/// A video frame descriptor uses its own magic and version, followed by the same URI, -/// offset and length fields. Three long values follow: the frame ordinal, the MP4 moov -/// box offset and length relative to the video payload. class PAIMON_EXPORT BlobDescriptor { public: @@ -54,14 +50,6 @@ class PAIMON_EXPORT BlobDescriptor { static Result> Create(int8_t version, const std::string& uri, int64_t offset, int64_t length); - /// Create a reference to one logical frame in an encoded video payload. - /// An absent MP4 moov box has offset and length 0. - static Result> CreateVideoFrame(const std::string& uri, - int64_t offset, int64_t length, - int64_t frame_index, - int64_t moov_offset, - int64_t moov_length); - static Result> Deserialize(const char* buffer, uint64_t size); static Result IsBlobDescriptor(const char* buffer, uint64_t size); @@ -86,23 +74,6 @@ class PAIMON_EXPORT BlobDescriptor { return length_; } - bool IsVideoFrame() const { - return frame_index_ >= 0; - } - - /// Zero-based frame ordinal, or -1 for a regular blob. - int64_t FrameIndex() const { - return frame_index_; - } - - int64_t MoovOffset() const { - return moov_offset_; - } - - int64_t MoovLength() const { - return moov_length_; - } - private: BlobDescriptor(int8_t version, const std::string& uri, int64_t offset, int64_t length) : version_(version), uri_(uri), offset_(offset), length_(length) {} @@ -114,9 +85,6 @@ class PAIMON_EXPORT BlobDescriptor { std::string uri_; int64_t offset_ = 0; int64_t length_ = -1; - int64_t frame_index_ = -1; - int64_t moov_offset_ = 0; - int64_t moov_length_ = 0; }; } // namespace paimon diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt index 4ab30167d..87a1fa09e 100644 --- a/src/paimon/CMakeLists.txt +++ b/src/paimon/CMakeLists.txt @@ -30,6 +30,7 @@ set(PAIMON_COMMON_SRCS common/data/blob_descriptor.cpp common/data/blob_view.cpp common/data/blob_view_struct.cpp + common/data/video_frame_descriptor.cpp common/data/blob_utils.cpp common/data/columnar/columnar_array.cpp common/data/columnar/columnar_map.cpp diff --git a/src/paimon/common/data/blob.cpp b/src/paimon/common/data/blob.cpp index 653dda9c6..adfb268b0 100644 --- a/src/paimon/common/data/blob.cpp +++ b/src/paimon/common/data/blob.cpp @@ -24,6 +24,7 @@ #include "arrow/c/bridge.h" #include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/path_util.h" @@ -40,21 +41,28 @@ class Blob::Impl { public: explicit Impl(std::unique_ptr&& descriptor) : descriptor_(std::move(descriptor)) {} + explicit Impl(std::unique_ptr&& video_frame) + : video_frame_(std::move(video_frame)) {} PAIMON_UNIQUE_PTR SerializeDescriptor(const std::shared_ptr& pool) const { - return descriptor_->Serialize(pool); + return video_frame_ ? video_frame_->Serialize(pool) : descriptor_->Serialize(pool); } const BlobDescriptor* GetDescriptor() const { - return descriptor_.get(); + return video_frame_ ? &video_frame_->Payload() : descriptor_.get(); } const std::string& Uri() const { - return descriptor_->Uri(); + return GetDescriptor()->Uri(); + } + + const VideoFrameDescriptor* VideoFrame() const { + return video_frame_.get(); } private: std::unique_ptr descriptor_; + std::unique_ptr video_frame_; }; Result> Blob::FromPath(const std::string& path) { @@ -74,6 +82,11 @@ Blob::Blob(std::unique_ptr&& impl) : impl_(std::move(impl)) {} Blob::~Blob() = default; Result> Blob::FromDescriptor(const char* buffer, uint64_t length) { + if (VideoFrameDescriptor::HasMagic(buffer, length)) { + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr video_frame, + VideoFrameDescriptor::Deserialize(buffer, length)); + return std::unique_ptr(new Blob(std::make_unique(std::move(video_frame)))); + } PAIMON_ASSIGN_OR_RAISE(std::unique_ptr descriptor, BlobDescriptor::Deserialize(buffer, length)); @@ -90,19 +103,19 @@ const std::string& Blob::Uri() const { } bool Blob::IsVideoFrame() const { - return impl_->GetDescriptor()->IsVideoFrame(); + return impl_->VideoFrame() != nullptr; } int64_t Blob::FrameIndex() const { - return impl_->GetDescriptor()->FrameIndex(); + return impl_->VideoFrame() ? impl_->VideoFrame()->FrameIndex() : -1; } int64_t Blob::MoovOffset() const { - return impl_->GetDescriptor()->MoovOffset(); + return impl_->VideoFrame() ? impl_->VideoFrame()->MoovOffset() : 0; } int64_t Blob::MoovLength() const { - return impl_->GetDescriptor()->MoovLength(); + return impl_->VideoFrame() ? impl_->VideoFrame()->MoovLength() : 0; } Result> Blob::NewInputStream( diff --git a/src/paimon/common/data/blob_defs.h b/src/paimon/common/data/blob_defs.h index 8dbb681b1..51c076d73 100644 --- a/src/paimon/common/data/blob_defs.h +++ b/src/paimon/common/data/blob_defs.h @@ -50,6 +50,9 @@ class BlobDefs { /// Metadata value identifying a Paimon Blob extension type field. static constexpr char kExtensionTypeValue[] = "paimon.type.blob"; + /// Java Paimon table option naming scalar BLOB fields stored as video frames. + static constexpr char kVideoFrameFieldOption[] = "video-frame-field"; + /// A bin_length value of -1 in the index indicates a null blob entry. static constexpr int64_t kNullBinLength = -1; /// A bin_length value of -2 in the index indicates a placeholder blob entry, written by diff --git a/src/paimon/common/data/blob_descriptor.cpp b/src/paimon/common/data/blob_descriptor.cpp index 9cb3b6be4..947575ede 100644 --- a/src/paimon/common/data/blob_descriptor.cpp +++ b/src/paimon/common/data/blob_descriptor.cpp @@ -19,10 +19,10 @@ #include "paimon/data/blob_descriptor.h" -#include #include #include "fmt/format.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/io/memory_segment_output_stream.h" #include "paimon/common/memory/memory_segment_utils.h" #include "paimon/io/byte_array_input_stream.h" @@ -35,8 +35,6 @@ namespace paimon { namespace { constexpr int64_t kMagic = 0x424C4F4244455343l; -constexpr int64_t kVideoFrameMagic = 0x564944454F46524D; -constexpr int8_t kVideoFrameVersion = 1; // One byte for version, eight bytes for magic number. constexpr uint64_t kMinDescriptorLength = 9; @@ -60,39 +58,17 @@ Result> BlobDescriptor::Create(int8_t version, return std::unique_ptr(new BlobDescriptor(version, uri, offset, length)); } -Result> BlobDescriptor::CreateVideoFrame( - const std::string& uri, int64_t offset, int64_t length, int64_t frame_index, - int64_t moov_offset, int64_t moov_length) { - if (frame_index < 0 || moov_offset < 0 || moov_length < 0 || - uri.size() > std::numeric_limits::max() || - (moov_length == 0 ? moov_offset != 0 - : moov_offset > length || moov_length > length - moov_offset)) { - return Status::Invalid("invalid video frame descriptor range"); - } - PAIMON_ASSIGN_OR_RAISE(std::unique_ptr descriptor, - Create(kVideoFrameVersion, uri, offset, length)); - descriptor->frame_index_ = frame_index; - descriptor->moov_offset_ = moov_offset; - descriptor->moov_length_ = moov_length; - return descriptor; -} - PAIMON_UNIQUE_PTR BlobDescriptor::Serialize(const std::shared_ptr& pool) const { MemorySegmentOutputStream out(MemorySegmentOutputStream::DEFAULT_SEGMENT_SIZE, pool); out.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); - out.WriteValue(IsVideoFrame() ? kVideoFrameVersion : kCurrentVersion); - out.WriteValue(IsVideoFrame() ? kVideoFrameMagic : kMagic); + out.WriteValue(kCurrentVersion); + out.WriteValue(kMagic); out.WriteValue(static_cast(uri_.size())); auto uri_bytes = std::make_shared(uri_, pool.get()); out.WriteBytes(uri_bytes); out.WriteValue(offset_); out.WriteValue(length_); - if (IsVideoFrame()) { - out.WriteValue(frame_index_); - out.WriteValue(moov_offset_); - out.WriteValue(moov_length_); - } return MemorySegmentUtils::CopyToBytes(out.Segments(), 0, out.CurrentSize(), pool.get()); } @@ -101,6 +77,9 @@ Result> BlobDescriptor::Deserialize(const char* if (buffer == nullptr || size == 0) { return Status::Invalid("empty blob descriptor"); } + if (VideoFrameDescriptor::HasMagic(buffer, size)) { + return Status::Invalid("video frame descriptors must be opened with Blob::FromDescriptor"); + } auto input_stream = std::make_shared(buffer, size); DataInputStream in(std::move(input_stream)); in.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); @@ -110,14 +89,7 @@ Result> BlobDescriptor::Deserialize(const char* "Expecting BlobDescriptor version to be less than or equal to {}, but found {}.", kCurrentVersion, version)); } - bool video_frame = false; - if (version == kVideoFrameVersion && size >= kMinDescriptorLength) { - PAIMON_ASSIGN_OR_RAISE(int64_t magic, in.ReadValue()); - video_frame = magic == kVideoFrameMagic; - if (!video_frame) { - PAIMON_RETURN_NOT_OK(in.Seek(1)); - } - } else if (version > 1) { + if (version > 1) { PAIMON_ASSIGN_OR_RAISE(int64_t magic, in.ReadValue()); if (kMagic != magic) { return Status::Invalid(fmt::format( @@ -127,23 +99,16 @@ Result> BlobDescriptor::Deserialize(const char* } PAIMON_ASSIGN_OR_RAISE(int32_t uri_length, in.ReadValue()); PAIMON_ASSIGN_OR_RAISE(int64_t uri_start, in.GetPos()); - const uint64_t fixed_tail_size = (video_frame ? 5 : 2) * sizeof(int64_t); - const uint64_t remaining_size = size - uri_start; - if (uri_length < 0 || remaining_size < fixed_tail_size || - static_cast(uri_length) > remaining_size - fixed_tail_size || - (video_frame && static_cast(uri_length) != remaining_size - fixed_tail_size)) { + constexpr uint64_t kTailSize = 2 * sizeof(int64_t); + const uint64_t remaining = size - uri_start; + if (uri_length < 0 || remaining < kTailSize || + static_cast(uri_length) > remaining - kTailSize) { return Status::Invalid("invalid blob descriptor length"); } std::string uri(uri_length, '\0'); PAIMON_RETURN_NOT_OK(in.Read(uri.data(), uri.size())); PAIMON_ASSIGN_OR_RAISE(int64_t offset, in.ReadValue()); PAIMON_ASSIGN_OR_RAISE(int64_t length, in.ReadValue()); - if (video_frame) { - PAIMON_ASSIGN_OR_RAISE(int64_t frame_index, in.ReadValue()); - PAIMON_ASSIGN_OR_RAISE(int64_t moov_offset, in.ReadValue()); - PAIMON_ASSIGN_OR_RAISE(int64_t moov_length, in.ReadValue()); - return CreateVideoFrame(uri, offset, length, frame_index, moov_offset, moov_length); - } return BlobDescriptor::Create(version, uri, offset, length); } @@ -159,7 +124,7 @@ Result BlobDescriptor::IsBlobDescriptor(const char* buffer, uint64_t size) return false; } PAIMON_ASSIGN_OR_RAISE(int64_t magic, in.ReadValue()); - return kMagic == magic || (version == kVideoFrameVersion && kVideoFrameMagic == magic); + return kMagic == magic; } std::string BlobDescriptor::ToString() const { diff --git a/src/paimon/common/data/video_frame_descriptor.cpp b/src/paimon/common/data/video_frame_descriptor.cpp new file mode 100644 index 000000000..c213054e3 --- /dev/null +++ b/src/paimon/common/data/video_frame_descriptor.cpp @@ -0,0 +1,111 @@ +/* + * 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/common/data/video_frame_descriptor.h" + +#include +#include +#include +#include + +#include "paimon/common/io/memory_segment_output_stream.h" +#include "paimon/common/memory/memory_segment_utils.h" +#include "paimon/io/byte_array_input_stream.h" +#include "paimon/io/data_input_stream.h" + +namespace paimon { +namespace { + +constexpr int8_t kVersion = 1; +constexpr std::string_view kMagic = "MRFOEDIV"; // 0x564944454F46524D in little endian +constexpr uint64_t kHeaderSize = sizeof(kVersion) + kMagic.size(); +constexpr uint64_t kFixedSize = kHeaderSize + sizeof(int32_t) + 5 * sizeof(int64_t); + +} // namespace + +VideoFrameDescriptor::VideoFrameDescriptor(std::unique_ptr payload, + int64_t frame_index, int64_t moov_offset, + int64_t moov_length) + : payload_(std::move(payload)), + frame_index_(frame_index), + moov_offset_(moov_offset), + moov_length_(moov_length) {} + +Result> VideoFrameDescriptor::Create( + const std::string& uri, int64_t offset, int64_t length, int64_t frame_index, + int64_t moov_offset, int64_t moov_length) { + if (frame_index < 0 || moov_offset < 0 || moov_length < 0 || + uri.size() > std::numeric_limits::max() || + (moov_length == 0 ? moov_offset != 0 + : moov_offset > length || moov_length > length - moov_offset)) { + return Status::Invalid("invalid video frame descriptor range"); + } + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr payload, + BlobDescriptor::Create(uri, offset, length)); + return std::unique_ptr( + new VideoFrameDescriptor(std::move(payload), frame_index, moov_offset, moov_length)); +} + +bool VideoFrameDescriptor::HasMagic(const char* buffer, uint64_t size) { + return buffer != nullptr && size >= kHeaderSize && + std::string_view(buffer + sizeof(kVersion), kMagic.size()) == kMagic; +} + +Result> VideoFrameDescriptor::Deserialize(const char* buffer, + uint64_t size) { + if (size < kFixedSize || !HasMagic(buffer, size) || buffer[0] != kVersion) { + return Status::Invalid("invalid or unsupported video frame descriptor header"); + } + DataInputStream input(std::make_shared(buffer, size)); + input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); + PAIMON_RETURN_NOT_OK(input.Seek(kHeaderSize)); + PAIMON_ASSIGN_OR_RAISE(int32_t uri_length, input.ReadValue()); + if (uri_length < 0 || static_cast(uri_length) != size - kFixedSize) { + return Status::Invalid("invalid video frame descriptor length"); + } + std::string uri(uri_length, '\0'); + PAIMON_RETURN_NOT_OK(input.Read(uri.data(), uri_length)); + PAIMON_ASSIGN_OR_RAISE(int64_t offset, input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t length, input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t frame_index, input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t moov_offset, input.ReadValue()); + PAIMON_ASSIGN_OR_RAISE(int64_t moov_length, input.ReadValue()); + return Create(uri, offset, length, frame_index, moov_offset, moov_length); +} + +PAIMON_UNIQUE_PTR VideoFrameDescriptor::Serialize( + const std::shared_ptr& pool) const { + const std::string& uri = payload_->Uri(); + const int32_t segment_size = std::min( + kFixedSize + uri.size(), MemorySegmentOutputStream::DEFAULT_SEGMENT_SIZE); + MemorySegmentOutputStream output(segment_size, pool); + output.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); + output.WriteValue(kVersion); + output.Write(kMagic.data(), kMagic.size()); + output.WriteValue(uri.size()); + output.Write(uri.data(), uri.size()); + output.WriteValue(payload_->Offset()); + output.WriteValue(payload_->Length()); + output.WriteValue(frame_index_); + output.WriteValue(moov_offset_); + output.WriteValue(moov_length_); + return MemorySegmentUtils::CopyToBytes(output.Segments(), 0, output.CurrentSize(), pool.get()); +} + +} // namespace paimon diff --git a/src/paimon/common/data/video_frame_descriptor.h b/src/paimon/common/data/video_frame_descriptor.h new file mode 100644 index 000000000..00873734a --- /dev/null +++ b/src/paimon/common/data/video_frame_descriptor.h @@ -0,0 +1,72 @@ +/* + * 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 "paimon/data/blob_descriptor.h" +#include "paimon/visibility.h" + +namespace paimon { + +/// Wire representation of a frame in an encoded video. The moov range is relative to its payload. +class PAIMON_EXPORT VideoFrameDescriptor { + public: + static Result> Create(const std::string& uri, + int64_t offset, int64_t length, + int64_t frame_index, + int64_t moov_offset, + int64_t moov_length); + + static bool HasMagic(const char* buffer, uint64_t size); + static Result> Deserialize(const char* buffer, + uint64_t size); + + PAIMON_UNIQUE_PTR Serialize(const std::shared_ptr& pool) const; + + const BlobDescriptor& Payload() const { + return *payload_; + } + + int64_t FrameIndex() const { + return frame_index_; + } + + int64_t MoovOffset() const { + return moov_offset_; + } + + int64_t MoovLength() const { + return moov_length_; + } + + private: + VideoFrameDescriptor(std::unique_ptr payload, int64_t frame_index, + int64_t moov_offset, int64_t moov_length); + + std::unique_ptr payload_; + int64_t frame_index_; + int64_t moov_offset_; + int64_t moov_length_; +}; + +} // namespace paimon diff --git a/src/paimon/core/append/append_only_writer.cpp b/src/paimon/core/append/append_only_writer.cpp index 97e7853b2..3550f4426 100644 --- a/src/paimon/core/append/append_only_writer.cpp +++ b/src/paimon/core/append/append_only_writer.cpp @@ -29,6 +29,7 @@ #include "arrow/c/helpers.h" #include "arrow/type.h" #include "arrow/util/key_value_metadata.h" +#include "paimon/common/data/blob_defs.h" #include "paimon/common/data/shredding/shredding_write_plan_factories.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/types/row_kind.h" @@ -37,6 +38,7 @@ #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/long_counter.h" #include "paimon/common/utils/scope_guard.h" +#include "paimon/common/utils/string_utils.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" @@ -189,6 +191,17 @@ Status AppendOnlyWriter::Flush(bool wait_for_latest_compaction, bool forced_full } AppendOnlyWriter::RollingFileWriterResult AppendOnlyWriter::CreateRollingRowWriter() { + const auto& table_options = options_.ToMap(); + const auto video_fields = table_options.find(BlobDefs::kVideoFrameFieldOption); + if (video_fields != table_options.end()) { + for (std::string field : StringUtils::Split(video_fields->second, ",")) { + StringUtils::Trim(&field); + if (write_schema_->GetFieldIndex(field) >= 0) { + return Status::NotImplemented( + fmt::format("writing video-frame-field '{}' is not supported", field)); + } + } + } if (options_.GetVectorFileFormat()) { arrow::FieldVector main_fields; arrow::FieldVector vector_fields; diff --git a/src/paimon/format/blob/blob_format_writer.cpp b/src/paimon/format/blob/blob_format_writer.cpp index 1838849e7..33f8c2d39 100644 --- a/src/paimon/format/blob/blob_format_writer.cpp +++ b/src/paimon/format/blob/blob_format_writer.cpp @@ -32,6 +32,7 @@ #include "arrow/util/utf8.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/memory/memory_segment_utils.h" #include "paimon/common/metrics/metrics_impl.h" @@ -419,6 +420,9 @@ Result> BlobFormatWriter::WriteBlobElements( Result BlobFormatWriter::OpenBlobInputStream( std::string_view blob_data, std::optional element_index) { + if (VideoFrameDescriptor::HasMagic(blob_data.data(), blob_data.size())) { + return Status::NotImplemented("video frame descriptors cannot be written to .blob files"); + } // Whether blob_data is a serialized BlobDescriptor is detected by its magic header rather // than taken from a blob_as_descriptor option, so each value may hold either form. PAIMON_ASSIGN_OR_RAISE(bool is_descriptor, diff --git a/src/paimon/format/blob/blob_format_writer_test.cpp b/src/paimon/format/blob/blob_format_writer_test.cpp index 866411363..3e3ca507c 100644 --- a/src/paimon/format/blob/blob_format_writer_test.cpp +++ b/src/paimon/format/blob/blob_format_writer_test.cpp @@ -32,6 +32,7 @@ #include "gtest/gtest.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" @@ -714,6 +715,22 @@ TEST_P(BlobFormatWriterTest, TestAddBatchWithNullValues) { ArrowArrayRelease(null_c_array.get()); } +TEST_F(BlobFormatWriterWriteNullTest, TestRejectVideoFrameDescriptor) { + const std::string path = dir_->Str() + "/payload.mp4"; + ASSERT_OK(file_system_->WriteFile(path, "encoded", true)); + ASSERT_OK_AND_ASSIGN(std::unique_ptr frame, + VideoFrameDescriptor::Create(path, 0, 7, 42, 0, 0)); + auto bytes = frame->Serialize(pool_); + ASSERT_OK_AND_ASSIGN(std::shared_ptr array, + MakeBlobArrayFromBytes(std::string(bytes->data(), bytes->size()))); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr writer, + BlobFormatWriter::Create(output_stream_, struct_type_, /*write_null_on_missing_file=*/true, + /*write_null_on_fetch_failure=*/true, file_system_, pool_)); + ASSERT_NOK_WITH_MSG(AddBatchOnce(writer, array), + "video frame descriptors cannot be written to .blob files"); +} + TEST_F(BlobFormatWriterWriteNullTest, TestWriteNullOnMissingFile) { ASSERT_OK_AND_ASSIGN( std::shared_ptr writer, diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 35cb1b2af..2234f1316 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -27,12 +27,12 @@ #include "arrow/c/bridge.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/reader/blob_read_context.h" #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/delta_varint_compressor.h" -#include "paimon/data/blob_descriptor.h" #include "paimon/fs/file_system.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/io/data_input_stream.h" @@ -261,9 +261,9 @@ Result VideoFileBatchReader::NextBatch() { const uint64_t run_start = run == runs_.begin() ? 0 : (run - 1)->end; const int64_t frame = run->first_frame + static_cast(row - run_start); PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr descriptor, - BlobDescriptor::CreateVideoFrame(uri_, video.offset, video.length, frame, - video.moov_offset, video.moov_length)); + std::unique_ptr descriptor, + VideoFrameDescriptor::Create(uri_, video.offset, video.length, frame, + video.moov_offset, video.moov_length)); auto bytes = descriptor->Serialize(pool_); PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Append(bytes->data(), bytes->size())); } diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index f26227078..28e2f8bff 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -24,6 +24,7 @@ #include "gtest/gtest.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/reader/blob_read_context.h" #include "paimon/common/utils/delta_varint_compressor.h" #include "paimon/data/blob.h" @@ -32,6 +33,7 @@ #include "paimon/format/file_format_factory.h" #include "paimon/fs/local/local_file_system.h" #include "paimon/testing/utils/testharness.h" +#include "paimon/testing/utils/video_test_utils.h" namespace paimon::test { namespace { @@ -100,7 +102,7 @@ TEST(VideoFileBatchReaderTest, ReadsJavaCompatibleRunsAndSelection) { ASSERT_EQ(blob->MoovLength(), 3); ASSERT_OK_AND_ASSIGN(bool recognized, BlobDescriptor::IsBlobDescriptor(bytes.data(), bytes.size())); - ASSERT_TRUE(recognized); + ASSERT_FALSE(recognized); auto serialized = blob->ToDescriptor(GetDefaultPool()); ASSERT_EQ(std::string_view(serialized->data(), serialized->size()), bytes); ASSERT_OK_AND_ASSIGN(auto payload, blob->ToData(fs, GetDefaultPool())); @@ -147,6 +149,28 @@ TEST(VideoFileBatchReaderTest, ReadsJavaCompatibleRunsAndSelection) { ASSERT_EQ(imported.ValueOrDie()->length(), 2); } +TEST(VideoFileBatchReaderTest, RoundTripsJavaFrameDescriptor) { + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-frame-descriptor-v1.hex")); + ASSERT_OK_AND_ASSIGN(std::unique_ptr blob, + Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(blob->IsVideoFrame()); + ASSERT_EQ(blob->Uri(), "s3://bucket/视频.mp4"); + ASSERT_EQ(blob->FrameIndex(), 42); + ASSERT_EQ(blob->MoovOffset(), 0); + ASSERT_EQ(blob->MoovLength(), 0); + auto serialized = blob->ToDescriptor(GetDefaultPool()); + ASSERT_EQ(std::string_view(serialized->data(), serialized->size()), bytes); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr frame, + VideoFrameDescriptor::Create("s3://bucket/视频.mp4", /*offset=*/7, /*length=*/99, + /*frame_index=*/42, /*moov_offset=*/0, /*moov_length=*/0)); + auto encoded = frame->Serialize(GetDefaultPool()); + ASSERT_EQ(std::string_view(encoded->data(), encoded->size()), bytes); + ASSERT_NOK(BlobDescriptor::Deserialize(bytes.data(), bytes.size())); + ASSERT_NOK(Blob::FromDescriptor(bytes.data(), 5)); + ASSERT_NOK(Blob::FromDescriptor(bytes.data(), bytes.size() - 1)); +} + TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { auto dir = paimon::test::UniqueTestDirectory::Create(); ASSERT_TRUE(dir); diff --git a/src/paimon/testing/utils/video_test_utils.h b/src/paimon/testing/utils/video_test_utils.h new file mode 100644 index 000000000..f767d5f06 --- /dev/null +++ b/src/paimon/testing/utils/video_test_utils.h @@ -0,0 +1,62 @@ +/* + * 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 "paimon/result.h" +#include "paimon/status.h" +#include "paimon/testing/utils/testharness.h" + +namespace paimon::test { + +// Apache Paimon's Java fixtures from apache/paimon#10905 (5faef60f6fee). +inline Result ReadJavaVideoFixture(const std::string& name) { + std::ifstream input(GetDataDir() + "/video_format.data/" + name); + if (!input) { + return Status::IOError("cannot open Java video fixture ", name); + } + std::string bytes; + for (std::string line; std::getline(input, line);) { + if (line.empty() || line.front() == '#') { + continue; + } + if (line.size() % 2 != 0) { + return Status::Invalid("odd length in Java video fixture ", name); + } + for (size_t i = 0; i < line.size(); i += 2) { + unsigned char byte = 0; + const char* end = line.data() + i + 2; + const auto parsed = std::from_chars(line.data() + i, end, byte, 16); + if (parsed.ec != std::errc() || parsed.ptr != end) { + return Status::Invalid("invalid hex in Java video fixture ", name); + } + bytes.push_back(static_cast(byte)); + } + } + if (bytes.empty() || !input.eof()) { + return Status::Invalid("empty or unreadable Java video fixture ", name); + } + return bytes; +} + +} // namespace paimon::test diff --git a/test/inte/blob_table_inte_test.cpp b/test/inte/blob_table_inte_test.cpp index 1bd320e49..66280843a 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -84,6 +84,7 @@ #include "paimon/testing/utils/io_exception_helper.h" #include "paimon/testing/utils/test_helper.h" #include "paimon/testing/utils/testharness.h" +#include "paimon/testing/utils/video_test_utils.h" #include "paimon/write_context.h" namespace paimon { @@ -1328,6 +1329,99 @@ std::shared_ptr MakeBlobUpdateArray( return std::dynamic_pointer_cast(array); } +TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { + const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + BlobUtils::ToArrowField("video", /*nullable=*/true)}; + const std::map options = { + {Options::FILE_FORMAT, GetParam()}, {Options::FILE_SYSTEM, "local"}, + {Options::ROW_TRACKING_ENABLED, "true"}, {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, "video"}, + }; + CreateTable(fields, /*partition_keys=*/{}, options); + const std::string table_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + auto id_array = + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({fields[0]}), "[[10], [20]]") + .ValueOrDie(); + // The table option is present, but a projection that excludes video can still write. + ASSERT_OK_AND_ASSIGN(auto commit_messages, WriteArray(table_path, {}, {"id"}, {id_array})); + ASSERT_OK(Commit(table_path, commit_messages)); + auto video_array = MakeBlobUpdateArray(fields[1], {"payload"}); + ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"video"}, {video_array}), + "writing video-frame-field 'video' is not supported"); + + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, ScanTable(table_path)); + ASSERT_EQ(plan->Splits().size(), 1); + auto main_split = std::dynamic_pointer_cast(plan->Splits()[0]); + ASSERT_TRUE(main_split); + auto files = main_split->DataFiles(); + ASSERT_EQ(files.size(), 1); + const auto& data_file = files[0]; + ASSERT_TRUE(data_file->first_row_id); + const int64_t first_row_id = data_file->first_row_id.value(); + const int64_t sequence = data_file->max_sequence_number; + auto fs = dir_->GetFileSystem(); + + ASSERT_OK_AND_ASSIGN(std::string base, ReadJavaVideoFixture("video-v1-moov.hex")); + // Two runs with no physical payloads: the first falls back, the second overwrites with NULL. + constexpr char overlay[] = + "\x02\x00\x03\x02\x00\x00" // Run lengths, references, first frames. + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00" + "IDEO\x01"; + ASSERT_OK( + fs->WriteFile(PathUtil::JoinPath(main_split->BucketPath(), "base.video"), base, true)); + ASSERT_OK(fs->WriteFile(PathUtil::JoinPath(main_split->BucketPath(), "overlay.video"), + std::string(overlay, sizeof(overlay) - 1), true)); + auto make_video_meta = [&](const std::string& name, int64_t file_size, int64_t seq) { + return DataFileMeta::ForAppend(name, file_size, /*row_count=*/2, SimpleStats::EmptyStats(), + seq, seq, /*schema_id=*/0, FileSource::Append(), + std::nullopt, std::nullopt, first_row_id, + std::vector{"video"}); + }; + ASSERT_OK_AND_ASSIGN(std::shared_ptr older, + make_video_meta("base.video", base.size(), sequence + 1)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr newer, + make_video_meta("overlay.video", sizeof(overlay) - 1, sequence + 2)); + files.push_back(older); + files.push_back(newer); + ASSERT_OK_AND_ASSIGN(std::shared_ptr split, + DataSplitImpl::Builder(main_split->Partition(), main_split->Bucket(), + main_split->BucketPath(), std::move(files)) + .WithSnapshot(main_split->SnapshotId()) + .WithTotalBuckets(main_split->TotalBuckets()) + .RawConvertible(false) + .Build()); + auto video_plan = + std::make_shared(plan->SnapshotId(), std::vector>{split}); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr result, + ReadTable(table_path, {"id", "video", "_ROW_ID"}, video_plan, + /*predicate=*/nullptr, {{Options::BLOB_AS_DESCRIPTOR, "false"}})); + ASSERT_TRUE(result); + auto rows = + checked_pointer_cast(arrow::Concatenate(result->chunks()).ValueOrDie()); + ASSERT_EQ(rows->length(), 2); + auto ids = checked_pointer_cast(rows->GetFieldByName("id")); + auto row_ids = checked_pointer_cast(rows->GetFieldByName("_ROW_ID")); + auto video = checked_pointer_cast(rows->GetFieldByName("video")); + ASSERT_EQ(ids->Value(0), 10); + ASSERT_EQ(ids->Value(1), 20); + ASSERT_EQ(row_ids->Value(0), first_row_id); + ASSERT_EQ(row_ids->Value(1), first_row_id + 1); + ASSERT_TRUE(video->IsNull(1)); + ASSERT_FALSE(video->IsNull(0)); + const std::string_view bytes = video->GetView(0); + ASSERT_OK_AND_ASSIGN(std::unique_ptr frame, + Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(frame->IsVideoFrame()); + ASSERT_EQ(frame->FrameIndex(), 7); + ASSERT_EQ(frame->MoovOffset(), 16); + ASSERT_EQ(frame->MoovLength(), 8); + ASSERT_OK_AND_ASSIGN(auto payload, frame->ToData(fs, pool_)); + ASSERT_EQ(std::string_view(payload->data(), payload->size()), + std::string_view(base).substr(0, 24)); +} + TEST_P(BlobTableInteTest, TestDataEvolutionBlobPartialUpdateFallback) { // the blob column is updated to null below, so it must be nullable arrow::FieldVector fields = {arrow::field("f0", arrow::int32()), diff --git a/test/test_data/video_format.data/video-frame-descriptor-v1.hex b/test/test_data/video_format.data/video-frame-descriptor-v1.hex new file mode 100644 index 000000000..a1db5dfc9 --- /dev/null +++ b/test/test_data/video_format.data/video-frame-descriptor-v1.hex @@ -0,0 +1,20 @@ +# 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. + + +# Video frame descriptor v1 with optional moov range. +014d52464f454449561600000073333a2f2f6275636b65742fe8a786e9a2912e6d7034070000000000000063000000000000002a0000000000000000000000000000000000000000000000 diff --git a/test/test_data/video_format.data/video-v1-moov.hex b/test/test_data/video_format.data/video-v1-moov.hex new file mode 100644 index 000000000..c69fbfa96 --- /dev/null +++ b/test/test_data/video_format.data/video-v1-moov.hex @@ -0,0 +1,20 @@ +# 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. + + +# Single video, moov at offset 16, two frames starting at 7. +0000000866747970000000086d646174000000086d6f6f7630201004000e0100000001000000010000000100000001000000010000004944454f01 From a231733f988312761491a171694f949a53d83cda Mon Sep 17 00:00:00 2001 From: XiaoHongbo <27951066+XiaoHongbo-Hope@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:28:23 -0800 Subject: [PATCH 04/19] fix(blob): bound video index memory before decoding Generated-by: OpenAI Codex CLI 0.172.0 (GPT-6.2 Sol) --- docs/source/user_guide/read.rst | 4 ++ .../format/blob/video_file_batch_reader.cpp | 17 +++++ .../blob/video_file_batch_reader_test.cpp | 72 +++++++++++++++++-- 3 files changed, 88 insertions(+), 5 deletions(-) diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index adbe2d468..d428ae2ee 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -339,6 +339,10 @@ a 29-byte footer and six indexes. Earlier files with a five-index footer also use version 1. Reimport those files with a current Java Paimon writer before reading them with Paimon C++. +The reader estimates peak index memory from the footer and rejects files whose +indexes could use more than 64 MiB during decoding or construction of the +in-memory index. + Each non-null row returns a serialized frame descriptor, including when ``blob-as-descriptor=false``. Open the descriptor with ``Blob::FromDescriptor()``, then use ``Blob::FrameIndex()`` to get the frame's diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 2234f1316..5596d976d 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -45,6 +45,7 @@ namespace { constexpr int64_t kFooterSize = 29; constexpr int32_t kMagic = 0x4F454449; constexpr int8_t kVersion = 1; +constexpr uint64_t kMaxIndexMemoryBytes = 64 * 1024 * 1024; constexpr int64_t kNullReference = -1; constexpr int64_t kPlaceholderReference = -2; @@ -90,18 +91,34 @@ Result> VideoFileBatchReader::Create( footer_input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); std::array index_lengths; int64_t index_start = size - kFooterSize; + uint64_t decoded_index_bytes = 0; + uint64_t decode_peak_bytes = 0; for (int32_t& index_length : index_lengths) { PAIMON_ASSIGN_OR_RAISE(index_length, footer_input.ReadValue()); if (index_length < 0 || index_length > index_start) { return Status::Invalid("video indexes exceed the file size"); } index_start -= index_length; + // A varint can be one byte. The decoder holds both deltas and decoded values. + const uint64_t decoded_bytes = static_cast(index_length) * sizeof(int64_t); + decode_peak_bytes = + std::max(decode_peak_bytes, decoded_index_bytes + index_length + 2 * decoded_bytes); + decoded_index_bytes += decoded_bytes; } PAIMON_ASSIGN_OR_RAISE(int32_t magic, footer_input.ReadValue()); PAIMON_ASSIGN_OR_RAISE(int8_t version, footer_input.ReadValue()); if (magic != kMagic || version != kVersion) { return Status::Invalid("invalid or unsupported video file footer"); } + // Each group has equal entry counts, bounded by its shortest encoded index. + const uint64_t video_count = std::min({index_lengths[0], index_lengths[1], index_lengths[2]}); + const uint64_t run_count = std::min({index_lengths[3], index_lengths[4], index_lengths[5]}); + const uint64_t build_peak_bytes = + decoded_index_bytes + video_count * sizeof(VideoRange) + run_count * sizeof(FrameRun); + if (std::max(decode_peak_bytes, build_peak_bytes) > kMaxIndexMemoryBytes) { + return Status::CapacityError("video indexes exceed the memory budget of ", + kMaxIndexMemoryBytes, " bytes"); + } std::array, 6> indexes; int64_t index_offset = index_start; for (size_t i = 0; i < indexes.size(); ++i) { diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index 28e2f8bff..fa8e57b55 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -19,6 +19,9 @@ #include "paimon/format/blob/video_file_batch_reader.h" +#include +#include + #include "arrow/api.h" #include "arrow/c/bridge.h" #include "gtest/gtest.h" @@ -32,6 +35,8 @@ #include "paimon/format/file_format.h" #include "paimon/format/file_format_factory.h" #include "paimon/fs/local/local_file_system.h" +#include "paimon/io/byte_array_input_stream.h" +#include "paimon/testing/mock/mock_file_system.h" #include "paimon/testing/utils/testharness.h" #include "paimon/testing/utils/video_test_utils.h" @@ -46,6 +51,14 @@ void Append32(std::string* data, uint32_t value) { } } +void AppendVideoFooter(std::string* data, const std::vector& index_lengths) { + for (uint32_t length : index_lengths) { + Append32(data, length); + } + Append32(data, 0x4f454449); + data->push_back(1); +} + std::string MakeVideoFile(bool placeholder = false, int64_t first_moov_length = 3) { std::string data = "VIDEOfilm"; const std::vector> indexes = { @@ -57,11 +70,7 @@ std::string MakeVideoFile(bool placeholder = false, int64_t first_moov_length = sizes.push_back(bytes.size()); data.append(bytes.data(), bytes.size()); } - for (auto size : sizes) { - Append32(&data, size); - } - Append32(&data, 0x4f454449); - data.push_back(1); + AppendVideoFooter(&data, sizes); return data; } @@ -184,6 +193,59 @@ TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { ASSERT_NOK(VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr)); } +TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { + class FooterOnlyStream : public MockInputStream { + public: + explicit FooterOnlyStream(const std::vector& index_lengths) + : footer_offset_( + std::accumulate(index_lengths.begin(), index_lengths.end(), int64_t{0})) { + AppendVideoFooter(&footer_, index_lengths); + } + + Result Length() const override { + return footer_offset_ + footer_.size(); + } + + Result Read(char* buffer, int64_t size, int64_t offset) override { + if (offset != footer_offset_ || size != static_cast(footer_.size())) { + return Status::IOError("unexpected index read"); + } + std::memcpy(buffer, footer_.data(), footer_.size()); + return size; + } + + private: + int64_t footer_offset_; + std::string footer_; + }; + + constexpr uint32_t kMiB = 1024 * 1024; + // A single 64 MiB index exceeds the decode budget. Three 1.5 MiB run indexes fit + // during decoding but exceed the budget once the runs and decoded indexes coexist. + constexpr uint32_t kRunIndexBytes = 3 * kMiB / 2; + for (const std::vector& lengths : + {std::vector{64 * kMiB, 0, 0, 0, 0, 0}, + std::vector{0, 0, 0, kRunIndexBytes, kRunIndexBytes, kRunIndexBytes}}) { + auto result = VideoFileBatchReader::Create(std::make_shared(lengths), 2, + GetDefaultPool(), false, nullptr); + ASSERT_TRUE(result.status().IsCapacityError()) << result.status(); + } +} + +TEST(VideoFileBatchReaderTest, ReadsLargeIndexWithinMemoryBudget) { + constexpr uint32_t kRuns = 1024 * 1024; + // Each run contains one NULL row. The indexes encode deltas as single-byte varints. + std::string bytes(3 * kRuns, '\0'); + bytes[0] = 2; // Run length 1. + bytes[kRuns] = 1; // Video reference -1. + AppendVideoFooter(&bytes, {0, 0, 0, kRuns, kRuns, kRuns}); + auto input = std::make_shared(bytes.data(), bytes.size()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); + ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); + ASSERT_EQ(rows, kRuns); +} + TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { auto dir = UniqueTestDirectory::Create(); ASSERT_TRUE(dir); From c722c4c75fcbf948053ece342072f070c8568791 Mon Sep 17 00:00:00 2001 From: XiaoHongbo <27951066+XiaoHongbo-Hope@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:06:03 -0800 Subject: [PATCH 05/19] fix(blob): bound video row selection and clarify legacy layout errors Generated-by: OpenAI Codex CLI 0.172.0 (GPT-6.2 Sol) --- .../format/blob/video_file_batch_reader.cpp | 61 ++++++++++------- .../format/blob/video_file_batch_reader.h | 6 +- .../blob/video_file_batch_reader_test.cpp | 68 +++++++++++++++++++ src/paimon/testing/utils/video_test_utils.h | 2 +- .../video_format.data/video-v1-five-index.hex | 18 +++++ 5 files changed, 125 insertions(+), 30 deletions(-) create mode 100644 test/test_data/video_format.data/video-v1-five-index.hex diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 5596d976d..7c03afa22 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -48,6 +48,7 @@ constexpr int8_t kVersion = 1; constexpr uint64_t kMaxIndexMemoryBytes = 64 * 1024 * 1024; constexpr int64_t kNullReference = -1; constexpr int64_t kPlaceholderReference = -2; +constexpr char kLegacyVideoHint[] = ". Legacy five-index .video files require reimport"; Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) { for (int64_t read = 0; read < size;) { @@ -83,7 +84,7 @@ Result> VideoFileBatchReader::Create( } PAIMON_ASSIGN_OR_RAISE(int64_t size, input->Length()); if (size < kFooterSize) { - return Status::Invalid("video file is smaller than its footer"); + return Status::Invalid("video file is smaller than its footer", kLegacyVideoHint); } char footer[kFooterSize]; PAIMON_RETURN_NOT_OK(ReadAtFully(input.get(), size - kFooterSize, footer, sizeof(footer))); @@ -96,7 +97,7 @@ Result> VideoFileBatchReader::Create( for (int32_t& index_length : index_lengths) { PAIMON_ASSIGN_OR_RAISE(index_length, footer_input.ReadValue()); if (index_length < 0 || index_length > index_start) { - return Status::Invalid("video indexes exceed the file size"); + return Status::Invalid("video indexes exceed the file size", kLegacyVideoHint); } index_start -= index_length; // A varint can be one byte. The decoder holds both deltas and decoded values. @@ -137,30 +138,34 @@ Result> VideoFileBatchReader::Create( if (video_lengths.size() != moov_offsets.size() || video_lengths.size() != moov_lengths.size() || run_lengths.size() != references.size() || run_lengths.size() != first_frames.size()) { - return Status::Invalid("video indexes have inconsistent entry counts"); + return Status::Invalid("video indexes have inconsistent entry counts", kLegacyVideoHint); } PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); auto reader = std::unique_ptr(new VideoFileBatchReader( std::move(uri), batch_size, pool, emit_placeholder_sentinel, blob_context)); int64_t payload_offset = 0; + // Both layouts use v1. For a five-index file, the moov indexes below would actually + // contain the old video and keyframe lengths. Their sum covers the old payload region, + // which ends at least four bytes after index_start. The range and exact coverage checks + // together therefore reject the old layout even if its footer parses. reader->videos_.reserve(video_lengths.size()); for (size_t i = 0; i < video_lengths.size(); ++i) { const int64_t length = video_lengths[i]; if (length <= 0 || length > index_start - payload_offset) { - return Status::Invalid("invalid video payload length"); + return Status::Invalid("invalid video payload length", kLegacyVideoHint); } const int64_t moov_offset = moov_offsets[i]; const int64_t moov_length = moov_lengths[i]; if (moov_offset < 0 || moov_length < 0 || moov_offset > length || moov_length > length - moov_offset || (moov_length == 0 && moov_offset != 0)) { - return Status::Invalid("invalid moov range in video payload"); + return Status::Invalid("invalid moov range in video payload", kLegacyVideoHint); } reader->videos_.push_back({payload_offset, length, moov_offset, moov_length}); payload_offset += length; } if (payload_offset != index_start) { - return Status::Invalid("video payload length does not match its index"); + return Status::Invalid("video payload length does not match its index", kLegacyVideoHint); } int64_t rows = 0; @@ -197,34 +202,28 @@ Status VideoFileBatchReader::SetReadSchema(::ArrowSchema* schema, const std::sha if (arrow_schema->num_fields() != 1 || !BlobUtils::IsBlobField(arrow_schema->field(0))) { return Status::Invalid("video reader requires one scalar BLOB field"); } - std::optional> selected_rows; - if (selection) { - selected_rows.emplace(); - for (auto it = selection->Begin(); it != selection->End(); ++it) { - const uint64_t row = *it; - if (row >= row_count_) { - return Status::Invalid("video selection row exceeds row count"); - } - selected_rows->push_back(row); - } + // Create() bounds row_count_ by INT32_MAX. Seek once to check the entire upper range, + // including bitmap entries above INT32_MAX, which appear negative when dereferenced. + if (selection && + selection->EqualOrLarger(static_cast(row_count_)) != selection->End()) { + return Status::Invalid("video selection row exceeds row count"); } - selected_rows_ = std::move(selected_rows); + selection_ = selection; + read_row_count_ = selection ? selection->Cardinality() : row_count_; + previous_selected_rows_.clear(); field_ = arrow_schema->field(0); current_ = 0; previous_batch_size_ = 0; return Status::OK(); } -uint64_t VideoFileBatchReader::FileRowAt(uint64_t position) const { - return selected_rows_ ? (*selected_rows_)[position] : position; -} - Result VideoFileBatchReader::GetPreviousBatchFileRowId(uint64_t batch_row_id) const { if (batch_row_id >= previous_batch_size_) { return Status::Invalid("video batch row ID is out of range"); } - return FileRowAt(current_ - previous_batch_size_ + batch_row_id); + return selection_ ? previous_selected_rows_[batch_row_id] + : current_ - previous_batch_size_ + batch_row_id; } Result VideoFileBatchReader::GetNumberOfRows() const { @@ -243,8 +242,7 @@ Result VideoFileBatchReader::NextBatch() { if (closed_ || !field_) { return Status::Invalid("video reader is closed or read schema is unset"); } - const uint64_t total = selected_rows_ ? selected_rows_->size() : row_count_; - if (current_ >= total) { + if (current_ >= read_row_count_) { previous_batch_size_ = 0; return BatchReader::MakeEofBatch(); } @@ -254,7 +252,17 @@ Result VideoFileBatchReader::NextBatch() { return Status::Invalid("video read batch row limit must be positive"); } const uint64_t batch_limit = request ? std::min(batch_size_, request->max_rows) : batch_size_; - const uint64_t count = std::min(batch_limit, total - current_); + const uint64_t count = std::min(batch_limit, read_row_count_ - current_); + std::vector selected_rows; + if (selection_) { + const int32_t start = + previous_selected_rows_.empty() ? 0 : previous_selected_rows_.back() + 1; + auto selected = selection_->EqualOrLarger(start); + selected_rows.reserve(count); + for (uint64_t i = 0; i < count; ++i, ++selected) { + selected_rows.push_back(*selected); + } + } arrow::LargeBinaryBuilder builder(arrow_pool_.get()); PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Reserve(count)); for (uint64_t i = 0; i < count; ++i) { @@ -262,7 +270,7 @@ Result VideoFileBatchReader::NextBatch() { PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); continue; } - const uint64_t row = FileRowAt(current_ + i); + const uint64_t row = selection_ ? selected_rows[i] : current_ + i; const auto run = std::upper_bound(runs_.begin(), runs_.end(), row, [](uint64_t row, const FrameRun& run) { return row < run.end; }); @@ -294,6 +302,7 @@ Result VideoFileBatchReader::NextBatch() { PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(c_array.get(), c_schema.get(), arrow_pool_)); current_ += count; previous_batch_size_ = count; + previous_selected_rows_ = std::move(selected_rows); return std::make_pair(std::move(c_array), std::move(c_schema)); } diff --git a/src/paimon/format/blob/video_file_batch_reader.h b/src/paimon/format/blob/video_file_batch_reader.h index cde62018e..36409764e 100644 --- a/src/paimon/format/blob/video_file_batch_reader.h +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -78,8 +78,6 @@ class VideoFileBatchReader : public FileBatchReader { bool emit_placeholder_sentinel, const std::shared_ptr& blob_context); - uint64_t FileRowAt(uint64_t position) const; - std::string uri_; int32_t batch_size_; std::shared_ptr pool_; @@ -90,8 +88,10 @@ class VideoFileBatchReader : public FileBatchReader { std::shared_ptr blob_context_; std::vector videos_; std::vector runs_; - std::optional> selected_rows_; + std::optional selection_; + std::vector previous_selected_rows_; uint64_t row_count_ = 0; + uint64_t read_row_count_ = 0; uint64_t current_ = 0; uint64_t previous_batch_size_ = 0; bool closed_ = false; diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index fa8e57b55..c1020686c 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -24,6 +24,7 @@ #include "arrow/api.h" #include "arrow/c/bridge.h" +#include "arrow/c/helpers.h" #include "gtest/gtest.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" @@ -193,6 +194,73 @@ TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { ASSERT_NOK(VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr)); } +TEST(VideoFileBatchReaderTest, RejectsLegacyFiveIndexLayout) { + ASSERT_OK_AND_ASSIGN(std::string fixture, ReadJavaVideoFixture("video-v1-five-index.hex")); + auto input = std::make_shared(fixture.data(), fixture.size()); + ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), + "Legacy five-index .video files require reimport"); + + // The old payload is nine bytes. Its trailing index bytes look like a valid first index + // length of one in a six-index footer. At the guessed index start, 0x08 decodes to a + // four-byte video that exactly covers the guessed payload. The moov range must reject it. + constexpr char old_file[] = + "abcd\x08" + "efgh" + "\x12\x00" // Video length 9, no keyframe index. + "\x02\x00\x00\x00\x00" // Five runs of one row. + "\x00\x01\x02\x01\x02" // References 0, NULL, 0, NULL, 0. + "\x02\x01\x00\x00\x00"; // First frames 1, 0, 0, 0, 0. + std::string bytes(old_file, sizeof(old_file) - 1); + AppendVideoFooter(&bytes, {1, 1, 5, 5, 5}); + input = std::make_shared(bytes.data(), bytes.size()); + ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), + "invalid moov range in video payload"); +} + +TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { + constexpr int32_t kRows = 512 * 1024 * 1024; + const auto runs = DeltaVarintCompressor::Compress({kRows}); + std::string bytes(runs.data(), runs.size()); + bytes.append("\x01\x00", 2); // One NULL reference and first frame 0. + AppendVideoFooter(&bytes, {0, 0, 0, static_cast(runs.size()), 1, 1}); + auto input = std::make_shared(bytes.data(), bytes.size()); + auto context = std::make_shared(); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + VideoFileBatchReader::Create(input, 4, GetDefaultPool(), false, context)); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + std::optional bitmap(std::in_place); + bitmap->AddRange(1, kRows); + bitmap->RemoveRange(2, 5); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, bitmap)); + bitmap.reset(); + + context->request = BlobBatchRequest{2, /*read_payload=*/false}; + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_EQ(batch.first->length, 2); + ASSERT_EQ(reader->GetPreviousBatchFileRowId(0).value(), 1); + ASSERT_EQ(reader->GetPreviousBatchFileRowId(1).value(), 5); + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); + + context->request = BlobBatchRequest{3, /*read_payload=*/true}; + ASSERT_OK_AND_ASSIGN(batch, reader->NextBatch()); + ASSERT_EQ(batch.first->length, 3); + ASSERT_EQ(reader->GetPreviousBatchFileRowId(2).value(), 8); + ASSERT_EQ(reader->GetPreviousBatchFileRowId(0).value(), 6); + ASSERT_NOK(reader->GetPreviousBatchFileRowId(3)); + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); + + for (int32_t invalid : {kRows, -1}) { + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_NOK_WITH_MSG( + reader->SetReadSchema(&c_schema, nullptr, RoaringBitmap32::From({1, invalid})), + "video selection row exceeds row count"); + } +} + TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { class FooterOnlyStream : public MockInputStream { public: diff --git a/src/paimon/testing/utils/video_test_utils.h b/src/paimon/testing/utils/video_test_utils.h index f767d5f06..720497bf4 100644 --- a/src/paimon/testing/utils/video_test_utils.h +++ b/src/paimon/testing/utils/video_test_utils.h @@ -29,7 +29,7 @@ namespace paimon::test { -// Apache Paimon's Java fixtures from apache/paimon#10905 (5faef60f6fee). +// Apache Paimon's Java fixtures before (ff63bf8a6c24) and after (5faef60f6fee) #10905. inline Result ReadJavaVideoFixture(const std::string& name) { std::ifstream input(GetDataDir() + "/video_format.data/" + name); if (!input) { diff --git a/test/test_data/video_format.data/video-v1-five-index.hex b/test/test_data/video_format.data/video-v1-five-index.hex new file mode 100644 index 000000000..257cddbd1 --- /dev/null +++ b/test/test_data/video_format.data/video-v1-five-index.hex @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +6162635758595a0149464b4f45444956010000000200000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000c00000000000000a08c0000000000000200000000000000dfd9164b0602b201b101040100020100010106010403000e0602000000040000000500000005000000050000004944454f01 From 2d701f3fe6be372e9455c64a380309a8c195d987 Mon Sep 17 00:00:00 2001 From: XiaoHongbo <27951066+XiaoHongbo-Hope@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:50:26 -0800 Subject: [PATCH 06/19] fix(blob): reject ambiguous v1 video layouts Generated-by: OpenAI Codex CLI 0.172.0 (GPT-6.2 Sol) --- docs/source/user_guide/read.rst | 11 +- .../format/blob/video_file_batch_reader.cpp | 234 +++++++++++++----- .../format/blob/video_file_batch_reader.h | 4 + .../blob/video_file_batch_reader_test.cpp | 28 ++- 4 files changed, 213 insertions(+), 64 deletions(-) diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index d428ae2ee..7d903287b 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -336,8 +336,15 @@ Reading Video Columns Paimon C++ reads scalar BLOB columns stored in Paimon v1 ``.video`` files with a 29-byte footer and six indexes. Earlier files with a five-index footer also -use version 1. Reimport those files with a current Java Paimon writer before -reading them with Paimon C++. +use version 1. Paimon C++ validates both layouts and reads a file only when +the six-index layout is the sole match. If both layouts match, the reader +reports an ambiguous layout. + +To migrate older files, read the encoded video payloads and row-to-frame +mappings with a Java Paimon release that supports the five-index layout, +then rewrite them with a current Java Paimon writer. Read the rewritten +files with Paimon C++ and verify row counts, frame ordinals and row alignment +before switching to the rewritten data. The reader estimates peak index memory from the footer and rejects files whose indexes could use more than 64 MiB during decoding or construction of the diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 7c03afa22..1563cc5e2 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -43,20 +43,114 @@ namespace { // Encoded video payloads, six delta varint indexes, then the footer. // The footer stores six little endian int32 index lengths followed by the magic and version. constexpr int64_t kFooterSize = 29; +constexpr int64_t kLegacyFooterSize = 25; constexpr int32_t kMagic = 0x4F454449; constexpr int8_t kVersion = 1; constexpr uint64_t kMaxIndexMemoryBytes = 64 * 1024 * 1024; constexpr int64_t kNullReference = -1; constexpr int64_t kPlaceholderReference = -2; -constexpr char kLegacyVideoHint[] = ". Legacy five-index .video files require reimport"; + +using IndexLengths = std::array; + +struct IndexLayout { + int64_t start; + uint64_t decoded_bytes = 0; + uint64_t decode_peak_bytes = 0; +}; Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) { for (int64_t read = 0; read < size;) { - PAIMON_ASSIGN_OR_RAISE(int64_t n, input->Read(data + read, size - read, offset + read)); - if (n <= 0) { - return Status::Invalid("truncated video file"); + const Result n = input->Read(data + read, size - read, offset + read); + // An I/O failure leaves the layout undetermined. + if (!n.ok()) { + return n.status().IsInvalid() + ? Status::IOError("failed to read video file. ", n.status().ToString()) + : n.status(); + } + if (n.value() <= 0) { + return Status::IOError("truncated video file"); + } + read += n.value(); + } + return Status::OK(); +} + +Result PlanIndexes(const IndexLengths& lengths, int64_t footer_start) { + if (footer_start < 0) { + return Status::Invalid("video file is smaller than its footer"); + } + IndexLayout layout{footer_start}; + for (int32_t length : lengths) { + if (length < 0 || length > layout.start) { + return Status::Invalid("video indexes exceed the file size"); + } + layout.start -= length; + // A varint can be one byte. The decoder holds both deltas and decoded values. + const uint64_t decoded_bytes = static_cast(length) * sizeof(int64_t); + layout.decode_peak_bytes = + std::max(layout.decode_peak_bytes, layout.decoded_bytes + length + 2 * decoded_bytes); + layout.decoded_bytes += decoded_bytes; + } + return layout; +} + +Status CheckIndexBudget(const IndexLayout& layout, uint64_t materialized_bytes) { + if (std::max(layout.decode_peak_bytes, layout.decoded_bytes + materialized_bytes) > + kMaxIndexMemoryBytes) { + return Status::CapacityError("video indexes exceed the memory budget of ", + kMaxIndexMemoryBytes, " bytes"); + } + return Status::OK(); +} + +Result> ReadIndex(InputStream* input, int64_t* offset, int32_t length) { + std::vector bytes(length); + PAIMON_RETURN_NOT_OK(ReadAtFully(input, *offset, bytes.data(), length)); + *offset += length; + return DeltaVarintCompressor::Decompress(bytes); +} + +bool IsValidFrameRun(int64_t length, int64_t reference, int64_t first, size_t video_count, + int64_t rows) { + return length > 0 && length <= std::numeric_limits::max() - rows && + (reference == kNullReference || reference == kPlaceholderReference || + (reference >= 0 && static_cast(reference) < video_count && first >= 0)); +} + +Status ValidateLegacyLayout(InputStream* input, const IndexLengths& lengths, int64_t index_start) { + // Before apache/paimon#10905, the payload area contained videos followed by keyframe + // indexes. The footer had two physical indexes and three run indexes. + int64_t offset = index_start; + PAIMON_ASSIGN_OR_RAISE(std::vector videos, ReadIndex(input, &offset, lengths[1])); + PAIMON_ASSIGN_OR_RAISE(std::vector keyframes, ReadIndex(input, &offset, lengths[2])); + if (videos.size() != keyframes.size()) { + return Status::Invalid("legacy video and keyframe indexes have different counts"); + } + int64_t remaining = index_start; + for (size_t i = 0; i < videos.size(); ++i) { + if (videos[i] <= 0 || videos[i] > remaining || keyframes[i] < 0 || + keyframes[i] > remaining - videos[i]) { + return Status::Invalid("invalid legacy video or keyframe length"); } - read += n; + remaining -= videos[i] + keyframes[i]; + } + if (remaining != 0) { + return Status::Invalid("legacy payload length does not match its indexes"); + } + + PAIMON_ASSIGN_OR_RAISE(std::vector runs, ReadIndex(input, &offset, lengths[3])); + PAIMON_ASSIGN_OR_RAISE(std::vector references, ReadIndex(input, &offset, lengths[4])); + PAIMON_ASSIGN_OR_RAISE(std::vector first_frames, + ReadIndex(input, &offset, lengths[5])); + if (runs.size() != references.size() || runs.size() != first_frames.size()) { + return Status::Invalid("legacy video run indexes have different counts"); + } + int64_t rows = 0; + for (size_t i = 0; i < runs.size(); ++i) { + if (!IsValidFrameRun(runs[i], references[i], first_frames[i], videos.size(), rows)) { + return Status::Invalid("invalid legacy video frame run"); + } + rows += runs[i]; } return Status::OK(); } @@ -83,50 +177,84 @@ Result> VideoFileBatchReader::Create( return Status::Invalid("invalid video reader input, pool, or batch size"); } PAIMON_ASSIGN_OR_RAISE(int64_t size, input->Length()); - if (size < kFooterSize) { - return Status::Invalid("video file is smaller than its footer", kLegacyVideoHint); + if (size < kLegacyFooterSize) { + return Status::Invalid( + "corrupt or unsupported .video layout. File is smaller than its footer"); } - char footer[kFooterSize]; - PAIMON_RETURN_NOT_OK(ReadAtFully(input.get(), size - kFooterSize, footer, sizeof(footer))); + // Both layouts end with the same five lengths, magic and version. The index data + // for those lengths starts four bytes earlier in the six-index interpretation. + char footer[kFooterSize] = {}; + const int64_t footer_size = std::min(size, kFooterSize); + PAIMON_RETURN_NOT_OK(ReadAtFully(input.get(), size - footer_size, + footer + kFooterSize - footer_size, footer_size)); DataInputStream footer_input(std::make_shared(footer, sizeof(footer))); footer_input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); - std::array index_lengths; - int64_t index_start = size - kFooterSize; - uint64_t decoded_index_bytes = 0; - uint64_t decode_peak_bytes = 0; + IndexLengths index_lengths; for (int32_t& index_length : index_lengths) { PAIMON_ASSIGN_OR_RAISE(index_length, footer_input.ReadValue()); - if (index_length < 0 || index_length > index_start) { - return Status::Invalid("video indexes exceed the file size", kLegacyVideoHint); - } - index_start -= index_length; - // A varint can be one byte. The decoder holds both deltas and decoded values. - const uint64_t decoded_bytes = static_cast(index_length) * sizeof(int64_t); - decode_peak_bytes = - std::max(decode_peak_bytes, decoded_index_bytes + index_length + 2 * decoded_bytes); - decoded_index_bytes += decoded_bytes; } PAIMON_ASSIGN_OR_RAISE(int32_t magic, footer_input.ReadValue()); PAIMON_ASSIGN_OR_RAISE(int8_t version, footer_input.ReadValue()); if (magic != kMagic || version != kVersion) { - return Status::Invalid("invalid or unsupported video file footer"); - } - // Each group has equal entry counts, bounded by its shortest encoded index. - const uint64_t video_count = std::min({index_lengths[0], index_lengths[1], index_lengths[2]}); - const uint64_t run_count = std::min({index_lengths[3], index_lengths[4], index_lengths[5]}); - const uint64_t build_peak_bytes = - decoded_index_bytes + video_count * sizeof(VideoRange) + run_count * sizeof(FrameRun); - if (std::max(decode_peak_bytes, build_peak_bytes) > kMaxIndexMemoryBytes) { - return Status::CapacityError("video indexes exceed the memory budget of ", - kMaxIndexMemoryBytes, " bytes"); + return Status::Invalid("corrupt or unsupported .video footer"); + } + + // Check both budgets before reading index data. The legacy probe frees its decoded + // indexes before the six-index reader allocates its own. + const Result modern_layout = PlanIndexes(index_lengths, size - kFooterSize); + if (modern_layout.ok()) { + // Each group has equal entry counts, bounded by its shortest encoded index. + const uint64_t videos = std::min({index_lengths[0], index_lengths[1], index_lengths[2]}); + const uint64_t runs = std::min({index_lengths[3], index_lengths[4], index_lengths[5]}); + PAIMON_RETURN_NOT_OK(CheckIndexBudget( + modern_layout.value(), videos * sizeof(VideoRange) + runs * sizeof(FrameRun))); } + IndexLengths legacy_lengths = index_lengths; + legacy_lengths[0] = 0; + const Result legacy_layout = PlanIndexes(legacy_lengths, size - kLegacyFooterSize); + Status legacy_status = legacy_layout.status(); + if (legacy_layout.ok()) { + PAIMON_RETURN_NOT_OK(CheckIndexBudget(legacy_layout.value(), 0)); + legacy_status = + ValidateLegacyLayout(input.get(), legacy_lengths, legacy_layout.value().start); + if (!legacy_status.ok() && !legacy_status.IsInvalid()) { + return legacy_status; + } + } + + std::unique_ptr reader; + Status modern_status = modern_layout.status(); + if (modern_layout.ok()) { + PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); + reader.reset(new VideoFileBatchReader(std::move(uri), batch_size, pool, + emit_placeholder_sentinel, blob_context)); + modern_status = + reader->ReadSixIndexLayout(input.get(), index_lengths, modern_layout.value().start); + if (!modern_status.ok() && !modern_status.IsInvalid()) { + return modern_status; + } + } + if (legacy_status.ok()) { + if (modern_status.ok()) { + return Status::Invalid( + "ambiguous v1 .video layout. Both five-index and six-index " + "validation passed. Reimport the file"); + } + return Status::Invalid("Legacy five-index .video files require reimport"); + } + if (!modern_status.ok()) { + return Status::Invalid("corrupt or unsupported .video layout. ", modern_status.ToString()); + } + return reader; +} + +Status VideoFileBatchReader::ReadSixIndexLayout(InputStream* input, + const IndexLengths& index_lengths, + int64_t index_start) { std::array, 6> indexes; int64_t index_offset = index_start; for (size_t i = 0; i < indexes.size(); ++i) { - std::vector bytes(index_lengths[i]); - PAIMON_RETURN_NOT_OK(ReadAtFully(input.get(), index_offset, bytes.data(), bytes.size())); - PAIMON_ASSIGN_OR_RAISE(indexes[i], DeltaVarintCompressor::Decompress(bytes)); - index_offset += index_lengths[i]; + PAIMON_ASSIGN_OR_RAISE(indexes[i], ReadIndex(input, &index_offset, index_lengths[i])); } const auto& video_lengths = indexes[0]; @@ -138,54 +266,44 @@ Result> VideoFileBatchReader::Create( if (video_lengths.size() != moov_offsets.size() || video_lengths.size() != moov_lengths.size() || run_lengths.size() != references.size() || run_lengths.size() != first_frames.size()) { - return Status::Invalid("video indexes have inconsistent entry counts", kLegacyVideoHint); + return Status::Invalid("video indexes have inconsistent entry counts"); } - PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); - auto reader = std::unique_ptr(new VideoFileBatchReader( - std::move(uri), batch_size, pool, emit_placeholder_sentinel, blob_context)); int64_t payload_offset = 0; - // Both layouts use v1. For a five-index file, the moov indexes below would actually - // contain the old video and keyframe lengths. Their sum covers the old payload region, - // which ends at least four bytes after index_start. The range and exact coverage checks - // together therefore reject the old layout even if its footer parses. - reader->videos_.reserve(video_lengths.size()); + videos_.reserve(video_lengths.size()); for (size_t i = 0; i < video_lengths.size(); ++i) { const int64_t length = video_lengths[i]; if (length <= 0 || length > index_start - payload_offset) { - return Status::Invalid("invalid video payload length", kLegacyVideoHint); + return Status::Invalid("invalid video payload length"); } const int64_t moov_offset = moov_offsets[i]; const int64_t moov_length = moov_lengths[i]; if (moov_offset < 0 || moov_length < 0 || moov_offset > length || moov_length > length - moov_offset || (moov_length == 0 && moov_offset != 0)) { - return Status::Invalid("invalid moov range in video payload", kLegacyVideoHint); + return Status::Invalid("invalid moov range in video payload"); } - reader->videos_.push_back({payload_offset, length, moov_offset, moov_length}); + videos_.push_back({payload_offset, length, moov_offset, moov_length}); payload_offset += length; } if (payload_offset != index_start) { - return Status::Invalid("video payload length does not match its index", kLegacyVideoHint); + return Status::Invalid("video payload length does not match its index"); } int64_t rows = 0; - reader->runs_.reserve(run_lengths.size()); + runs_.reserve(run_lengths.size()); for (size_t i = 0; i < run_lengths.size(); ++i) { const int64_t length = run_lengths[i]; const int64_t ref = references[i]; const int64_t first = first_frames[i]; - if (length <= 0 || length > std::numeric_limits::max() - rows || - (ref != kNullReference && ref != kPlaceholderReference && - (ref < 0 || static_cast(ref) >= video_lengths.size())) || - (ref >= 0 && - (first < 0 || first > std::numeric_limits::max() - (length - 1)))) { + if (!IsValidFrameRun(length, ref, first, video_lengths.size(), rows) || + (ref >= 0 && first > std::numeric_limits::max() - (length - 1))) { return Status::Invalid("invalid video frame run"); } rows += length; - reader->runs_.push_back({static_cast(rows), ref, first}); + runs_.push_back({static_cast(rows), ref, first}); } - reader->row_count_ = rows; - return reader; + row_count_ = rows; + return Status::OK(); } Result> VideoFileBatchReader::GetFileSchema() const { diff --git a/src/paimon/format/blob/video_file_batch_reader.h b/src/paimon/format/blob/video_file_batch_reader.h index 36409764e..b50f3c823 100644 --- a/src/paimon/format/blob/video_file_batch_reader.h +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -19,6 +19,7 @@ #pragma once +#include #include #include #include @@ -78,6 +79,9 @@ class VideoFileBatchReader : public FileBatchReader { bool emit_placeholder_sentinel, const std::shared_ptr& blob_context); + Status ReadSixIndexLayout(InputStream* input, const std::array& index_lengths, + int64_t index_start); + std::string uri_; int32_t batch_size_; std::shared_ptr pool_; diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index c1020686c..afc53cc38 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -202,7 +202,7 @@ TEST(VideoFileBatchReaderTest, RejectsLegacyFiveIndexLayout) { // The old payload is nine bytes. Its trailing index bytes look like a valid first index // length of one in a six-index footer. At the guessed index start, 0x08 decodes to a - // four-byte video that exactly covers the guessed payload. The moov range must reject it. + // four-byte video that exactly covers the guessed payload. Only the old layout is valid. constexpr char old_file[] = "abcd\x08" "efgh" @@ -214,7 +214,26 @@ TEST(VideoFileBatchReaderTest, RejectsLegacyFiveIndexLayout) { AppendVideoFooter(&bytes, {1, 1, 5, 5, 5}); input = std::make_shared(bytes.data(), bytes.size()); ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), - "invalid moov range in video payload"); + "Legacy five-index .video files require reimport"); +} + +TEST(VideoFileBatchReaderTest, RejectsAmbiguousVideoLayout) { + // Five indexes describe two 25-byte videos, no keyframe indexes and four + // one-row runs. The same bytes also encode two 22-byte videos with no moov + // ranges and four 25-row runs when read using the six-index footer. + std::string bytes(50, '\0'); + bytes[44] = 44; // Six-index video lengths: 22, 22. + constexpr char indexes[] = + "\x32\x00" // Legacy video lengths: 25, 25. + "\x00\x00" // Legacy keyframe lengths: 0, 0. + "\x02\x00\x00\x00" // Legacy run lengths: 1, 1, 1, 1. + "\x00\x02\x01\x02" // Legacy references: 0, 1, 0, 1. + "\x02\x00\x00\x00"; // Legacy first frames: 1, 1, 1, 1. + bytes.append(indexes, sizeof(indexes) - 1); + AppendVideoFooter(&bytes, {2, 2, 4, 4, 4}); + auto input = std::make_shared(bytes.data(), bytes.size()); + ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), + "ambiguous v1 .video layout"); } TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { @@ -322,8 +341,9 @@ TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { ASSERT_OK( fs->WriteFile(path, MakeVideoFile(/*placeholder=*/false, /*first_moov_length=*/4), true)); ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs->Open(path)); - ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), - "invalid moov range"); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "corrupt or unsupported .video layout"); + ASSERT_NOK_WITH_MSG(result, "invalid moov range"); } TEST(VideoFileBatchReaderTest, ExposesPlaceholdersOnlyForBlobFallback) { From 2a7792dd5b260efd69115f90af1397966a7d045d Mon Sep 17 00:00:00 2001 From: XiaoHongbo <27951066+XiaoHongbo-Hope@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:31:11 -0800 Subject: [PATCH 07/19] docs(blob): shorten video read guidance Generated-by: OpenAI Codex CLI 0.172.0 (GPT-6.2 Sol) --- docs/source/user_guide/read.rst | 43 ++++++++++++--------------------- 1 file changed, 16 insertions(+), 27 deletions(-) diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index 7d903287b..1b036e034 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -334,33 +334,22 @@ Implementation Guidance Reading Video Columns --------------------- -Paimon C++ reads scalar BLOB columns stored in Paimon v1 ``.video`` files with -a 29-byte footer and six indexes. Earlier files with a five-index footer also -use version 1. Paimon C++ validates both layouts and reads a file only when -the six-index layout is the sole match. If both layouts match, the reader -reports an ambiguous layout. - -To migrate older files, read the encoded video payloads and row-to-frame -mappings with a Java Paimon release that supports the five-index layout, -then rewrite them with a current Java Paimon writer. Read the rewritten -files with Paimon C++ and verify row counts, frame ordinals and row alignment -before switching to the rewritten data. - -The reader estimates peak index memory from the footer and rejects files whose -indexes could use more than 64 MiB during decoding or construction of the -in-memory index. - -Each non-null row returns a serialized frame descriptor, including when -``blob-as-descriptor=false``. Open the descriptor with -``Blob::FromDescriptor()``, then use ``Blob::FrameIndex()`` to get the frame's -zero-based position. ``Blob::NewInputStream()`` opens the encoded video payload. -``Blob::MoovOffset()`` and ``Blob::MoovLength()`` locate the optional MP4 -``moov`` box within that payload. Applications decode the video payload with their -own video decoder. - -Write video columns with a Java Paimon writer. Paimon C++ rejects writes to -columns configured in ``video-frame-field`` and rejects frame descriptors -passed to the ordinary BLOB writer. +Paimon C++ reads scalar BLOB columns from v1 ``.video`` files that match only +the six-index layout (29-byte footer). It rejects files whose estimated peak +index memory exceeds 64 MiB. + +Reimport five-index or ambiguous files with a Java reader for the source +layout and a current Java writer. Verify row counts, frame ordinals and row +alignment in C++ before switching. + +Non-null rows return frame descriptors even with ``blob-as-descriptor=false``. +Open them with ``Blob::FromDescriptor()``. Use ``FrameIndex()`` for the zero-based +frame ordinal, ``NewInputStream()`` for the encoded payload, and ``MoovOffset()`` +and ``MoovLength()`` for the optional MP4 ``moov`` range. + +Use Java Paimon to write video columns. C++ rejects writes to +``video-frame-field`` columns and rejects frame descriptors in ordinary BLOB +writes. .. _data-evolution-deletion-vectors: From 7b5f393d04c69e45ca3c1ae1c04b4a1496609fba Mon Sep 17 00:00:00 2001 From: XiaoHongbo <27951066+XiaoHongbo-Hope@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:49:07 -0800 Subject: [PATCH 08/19] test(blob): simplify legacy video layout coverage Generated-by: OpenAI Codex CLI 0.172.0 (GPT-6.2 Sol) --- .../blob/video_file_batch_reader_test.cpp | 31 +++++-------------- src/paimon/testing/utils/video_test_utils.h | 2 +- .../video_format.data/video-v1-five-index.hex | 18 ----------- 3 files changed, 8 insertions(+), 43 deletions(-) delete mode 100644 test/test_data/video_format.data/video-v1-five-index.hex diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index afc53cc38..e4d0d8e32 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -194,30 +194,7 @@ TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { ASSERT_NOK(VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr)); } -TEST(VideoFileBatchReaderTest, RejectsLegacyFiveIndexLayout) { - ASSERT_OK_AND_ASSIGN(std::string fixture, ReadJavaVideoFixture("video-v1-five-index.hex")); - auto input = std::make_shared(fixture.data(), fixture.size()); - ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), - "Legacy five-index .video files require reimport"); - - // The old payload is nine bytes. Its trailing index bytes look like a valid first index - // length of one in a six-index footer. At the guessed index start, 0x08 decodes to a - // four-byte video that exactly covers the guessed payload. Only the old layout is valid. - constexpr char old_file[] = - "abcd\x08" - "efgh" - "\x12\x00" // Video length 9, no keyframe index. - "\x02\x00\x00\x00\x00" // Five runs of one row. - "\x00\x01\x02\x01\x02" // References 0, NULL, 0, NULL, 0. - "\x02\x01\x00\x00\x00"; // First frames 1, 0, 0, 0, 0. - std::string bytes(old_file, sizeof(old_file) - 1); - AppendVideoFooter(&bytes, {1, 1, 5, 5, 5}); - input = std::make_shared(bytes.data(), bytes.size()); - ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), - "Legacy five-index .video files require reimport"); -} - -TEST(VideoFileBatchReaderTest, RejectsAmbiguousVideoLayout) { +TEST(VideoFileBatchReaderTest, RejectsLegacyAndAmbiguousVideoLayouts) { // Five indexes describe two 25-byte videos, no keyframe indexes and four // one-row runs. The same bytes also encode two 22-byte videos with no moov // ranges and four 25-row runs when read using the six-index footer. @@ -234,6 +211,12 @@ TEST(VideoFileBatchReaderTest, RejectsAmbiguousVideoLayout) { auto input = std::make_shared(bytes.data(), bytes.size()); ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), "ambiguous v1 .video layout"); + + // This byte belongs to the five-index payload and the six-index video lengths. + // Zero video lengths invalidate only the six-index interpretation. + bytes[44] = 0; + ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), + "Legacy five-index .video files require reimport"); } TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { diff --git a/src/paimon/testing/utils/video_test_utils.h b/src/paimon/testing/utils/video_test_utils.h index 720497bf4..f767d5f06 100644 --- a/src/paimon/testing/utils/video_test_utils.h +++ b/src/paimon/testing/utils/video_test_utils.h @@ -29,7 +29,7 @@ namespace paimon::test { -// Apache Paimon's Java fixtures before (ff63bf8a6c24) and after (5faef60f6fee) #10905. +// Apache Paimon's Java fixtures from apache/paimon#10905 (5faef60f6fee). inline Result ReadJavaVideoFixture(const std::string& name) { std::ifstream input(GetDataDir() + "/video_format.data/" + name); if (!input) { diff --git a/test/test_data/video_format.data/video-v1-five-index.hex b/test/test_data/video_format.data/video-v1-five-index.hex deleted file mode 100644 index 257cddbd1..000000000 --- a/test/test_data/video_format.data/video-v1-five-index.hex +++ /dev/null @@ -1,18 +0,0 @@ -# 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. - -6162635758595a0149464b4f45444956010000000200000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000c00000000000000a08c0000000000000200000000000000dfd9164b0602b201b101040100020100010106010403000e0602000000040000000500000005000000050000004944454f01 From 7bd6898f1ff8b5172fcdc4a40b16632b656ba358 Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Sat, 28 Nov 2026 23:20:33 -0800 Subject: [PATCH 09/19] fix(blob): preserve video frame descriptors in blob views --- src/paimon/core/utils/blob_view_lookup.cpp | 7 +- test/inte/blob_table_inte_test.cpp | 86 ++++++++++++++++++++++ 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/src/paimon/core/utils/blob_view_lookup.cpp b/src/paimon/core/utils/blob_view_lookup.cpp index 30999fe62..d6dfba625 100644 --- a/src/paimon/core/utils/blob_view_lookup.cpp +++ b/src/paimon/core/utils/blob_view_lookup.cpp @@ -28,6 +28,7 @@ #include "arrow/c/bridge.h" #include "fmt/format.h" #include "paimon/catalog/catalog.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/executor/future.h" #include "paimon/common/table/special_fields.h" #include "paimon/common/utils/arrow/status_utils.h" @@ -252,10 +253,10 @@ Status BlobViewLookup::ExtractBlobDescriptors(const Identifier& identifier, std::string_view bytes = binary_array->GetView(row); PAIMON_ASSIGN_OR_RAISE(bool is_descriptor, BlobDescriptor::IsBlobDescriptor( bytes.data(), bytes.size())); - if (!is_descriptor) { + if (!is_descriptor && !VideoFrameDescriptor::HasMagic(bytes.data(), bytes.size())) { return Status::Invalid( - "requires blob field value to be a serialized BlobDescriptor in source " - "table."); + "requires a serialized BlobDescriptor or VideoFrameDescriptor in the " + "source table."); } auto descriptor_bytes = std::make_shared(bytes.size(), pool.get()); std::memcpy(descriptor_bytes->data(), bytes.data(), bytes.size()); diff --git a/test/inte/blob_table_inte_test.cpp b/test/inte/blob_table_inte_test.cpp index 66280843a..9d03b8fb1 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -4644,6 +4644,92 @@ TEST_P(BlobTableInteTest, TestBlobViewFieldWithUpstreamDescriptorBlob) { << "expected:" << expected_with_rk->ToString(); } +TEST_P(BlobTableInteTest, TestBlobViewFieldWithUpstreamVideo) { + if (GetParam() == "mosaic") { + GTEST_SKIP() << "Mosaic does not support inline BLOB view fields"; + } + const auto downstream_fields = CreateBlobViewTable(/*deletion_vectors_enabled=*/false); + const std::string downstream_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + const Identifier upstream_identifier("foo", "video_source"); + const arrow::FieldVector upstream_fields = {downstream_fields[0], + BlobUtils::ToArrowField("video", true)}; + const std::map upstream_options = { + {Options::FILE_FORMAT, GetParam()}, + {Options::FILE_SYSTEM, "local"}, + {Options::BUCKET, "-1"}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, "video"}}; + ASSERT_OK_AND_ASSIGN(std::shared_ptr catalog, Catalog::Create(dir_->Str(), {})); + ArrowSchema upstream_schema; + ASSERT_TRUE(arrow::ExportSchema(*arrow::schema(upstream_fields), &upstream_schema).ok()); + ASSERT_OK(catalog->CreateTable(upstream_identifier, &upstream_schema, {}, {}, upstream_options, + /*ignore_if_exists=*/false)); + ASSERT_OK_AND_ASSIGN(std::string upstream_path, catalog->GetTableLocation(upstream_identifier)); + + auto id_rows = checked_pointer_cast( + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({upstream_fields[0]}), + "[[10], [20]]") + .ValueOrDie()); + ASSERT_OK_AND_ASSIGN(auto upstream_messages, WriteArray(upstream_path, {}, {"f0"}, {id_rows})); + ASSERT_EQ(upstream_messages.size(), 1); + auto upstream_message = std::dynamic_pointer_cast(upstream_messages[0]); + ASSERT_TRUE(upstream_message); + auto& new_files = upstream_message->data_increment_.new_files_; + ASSERT_EQ(new_files.size(), 1); + + // Attach a Java-written video alongside the data file so the upstream catalog scan sees it. + ASSERT_OK_AND_ASSIGN(std::string video, ReadJavaVideoFixture("video-v1-moov.hex")); + const std::string video_name = "frames.video"; + auto fs = dir_->GetFileSystem(); + ASSERT_OK(fs->WriteFile(PathUtil::JoinPath(upstream_path, "bucket-0/" + video_name), video, + /*overwrite=*/false)); + const auto& data_file = new_files[0]; + ASSERT_OK_AND_ASSIGN(std::shared_ptr video_file, + DataFileMeta::ForAppend( + video_name, video.size(), /*row_count=*/2, SimpleStats::EmptyStats(), + data_file->min_sequence_number, data_file->max_sequence_number, + data_file->schema_id, FileSource::Append(), std::nullopt, std::nullopt, + std::nullopt, std::vector{"video"})); + new_files.push_back(std::move(video_file)); + ASSERT_OK(Commit(upstream_path, upstream_messages)); + + arrow::LargeBinaryBuilder view_builder; + for (const int64_t row_id : {1, 0}) { + BlobViewStruct view(upstream_identifier, /*field_id=*/1, row_id); + ASSERT_OK_AND_ASSIGN(PAIMON_UNIQUE_PTR bytes, view.Serialize(pool_)); + ASSERT_TRUE(view_builder.Append(bytes->data(), bytes->size()).ok()); + } + std::shared_ptr view_array; + ASSERT_TRUE(view_builder.Finish(&view_array).ok()); + auto downstream_rows = + arrow::StructArray::Make({id_rows->field(0), view_array}, downstream_fields).ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto downstream_messages, + WriteArray(downstream_path, {}, {"f0", "view"}, {downstream_rows})); + ASSERT_OK(Commit(downstream_path, downstream_messages)); + + ASSERT_OK_AND_ASSIGN(auto result, ScanAndReadResult(downstream_path, {"view"})); + ASSERT_TRUE(result); + auto rows = + checked_pointer_cast(arrow::Concatenate(result->chunks()).ValueOrDie()); + ASSERT_EQ(rows->length(), 2); + auto views = checked_pointer_cast(rows->GetFieldByName("view")); + ASSERT_TRUE(views); + for (int64_t row = 0; row < views->length(); ++row) { + ASSERT_FALSE(views->IsNull(row)); + const std::string_view bytes = views->GetView(row); + ASSERT_OK_AND_ASSIGN(std::unique_ptr frame, + Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_TRUE(frame->IsVideoFrame()); + ASSERT_EQ(frame->FrameIndex(), 8 - row); + ASSERT_EQ(frame->MoovOffset(), 16); + ASSERT_EQ(frame->MoovLength(), 8); + ASSERT_OK_AND_ASSIGN(auto payload, frame->ToData(fs, pool_)); + ASSERT_EQ(std::string_view(payload->data(), payload->size()), + std::string_view(video).substr(0, 24)); + } +} + TEST_P(BlobTableInteTest, TestBlobViewFieldWithMultipleUpstreamTables) { auto file_format = GetParam(); if (file_format == "avro" || file_format == "mosaic") { From 697f1cdd0a193ce52ac3b71a15ccc468d72cac54 Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 01:50:35 -0800 Subject: [PATCH 10/19] fix(blob): validate video layouts with one bounded index read --- src/paimon/CMakeLists.txt | 3 + .../fs/object_store_file_system_test.cpp | 25 +++ .../common/utils/delta_varint_compressor.cpp | 18 +- .../common/utils/delta_varint_compressor.h | 3 +- .../format/blob/video_file_batch_reader.cpp | 157 ++++++++-------- .../format/blob/video_file_batch_reader.h | 4 +- .../blob/video_file_batch_reader_test.cpp | 171 +++++++++++++----- 7 files changed, 253 insertions(+), 128 deletions(-) diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt index 87a1fa09e..e0c645051 100644 --- a/src/paimon/CMakeLists.txt +++ b/src/paimon/CMakeLists.txt @@ -1145,6 +1145,8 @@ if(PAIMON_BUILD_TESTS) if(PAIMON_ENABLE_OSS OR PAIMON_ENABLE_S3) list(APPEND PAIMON_OBJECT_STORE_FS_TEST_SOURCES common/fs/object_store_file_system_test.cpp) + set(PAIMON_OBJECT_STORE_FS_TEST_LINK_LIBS + ${PAIMON_BLOB_FILE_FORMAT_STATIC_LINK_LIBS}) endif() add_paimon_test(fs_test @@ -1159,6 +1161,7 @@ if(PAIMON_BUILD_TESTS) paimon_shared ${PAIMON_LOCAL_FILE_SYSTEM_STATIC_LINK_LIBS} ${PAIMON_JINDO_FS_TEST_LINK_LIBS} + ${PAIMON_OBJECT_STORE_FS_TEST_LINK_LIBS} test_utils_static ${GTEST_LINK_TOOLCHAIN} EXTRA_INCLUDES diff --git a/src/paimon/common/fs/object_store_file_system_test.cpp b/src/paimon/common/fs/object_store_file_system_test.cpp index 880d02bd2..6f3970a8e 100644 --- a/src/paimon/common/fs/object_store_file_system_test.cpp +++ b/src/paimon/common/fs/object_store_file_system_test.cpp @@ -30,7 +30,10 @@ #include #include +#include "paimon/format/file_format.h" +#include "paimon/format/file_format_factory.h" #include "paimon/testing/utils/testharness.h" +#include "paimon/testing/utils/video_test_utils.h" namespace paimon::test { namespace { @@ -276,6 +279,28 @@ TEST(ObjectStoreInputStreamTest, TestShortReadFails) { "range read for s3://bucket/file returned"); } +TEST(ObjectStoreInputStreamTest, VideoReaderOpensWithTwoRangeRequests) { + auto client = std::make_shared(); + ASSERT_OK_AND_ASSIGN(client->objects_["part.video"], ReadJavaVideoFixture("video-v1-moov.hex")); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + + ObjectStoreFileSystem default_fs("s3", client); + ObjectStoreFileSystem no_read_ahead_fs("s3", client, 0); + for (auto* fs : {&default_fs, &no_read_ahead_fs}) { + SCOPED_TRACE(fs == &default_fs ? "default read-ahead" : "no read-ahead budget"); + client->ranges_.clear(); + ASSERT_OK_AND_ASSIGN(auto input, fs->Open("s3://bucket/part.video")); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(std::move(input))); + ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); + ASSERT_EQ(rows, 2u); + // The Java fixture has 24 bytes of payload, six bytes of indexes and a 29-byte footer. + ASSERT_EQ(client->ranges_.size(), 2u); + ASSERT_EQ(client->ranges_[0], Range(30, 29)); + ASSERT_EQ(client->ranges_[1].first, 24); + } +} + TEST(ObjectStoreInputStreamTest, TestSequentialReadAheadGrows) { auto client = std::make_shared(); client->objects_["file"] = std::string(1024 * 1024, 'x'); diff --git a/src/paimon/common/utils/delta_varint_compressor.cpp b/src/paimon/common/utils/delta_varint_compressor.cpp index 89f908da9..0c7e098a8 100644 --- a/src/paimon/common/utils/delta_varint_compressor.cpp +++ b/src/paimon/common/utils/delta_varint_compressor.cpp @@ -52,16 +52,20 @@ std::vector DeltaVarintCompressor::Compress(const std::vector& da } Result> DeltaVarintCompressor::Decompress(const std::vector& bytes) { - if (bytes.empty()) { + return Decompress(bytes.data(), bytes.size()); +} + +Result> DeltaVarintCompressor::Decompress(const char* data, size_t size) { + if (size == 0) { return std::vector(); } // 1. Decode ZigZag + Varint → delta std::vector deltas; - deltas.reserve(bytes.size()); + deltas.reserve(size); size_t pos = 0; - while (pos < bytes.size()) { - PAIMON_ASSIGN_OR_RAISE(int64_t delta, DecodeVarint(bytes, &pos)); + while (pos < size) { + PAIMON_ASSIGN_OR_RAISE(int64_t delta, DecodeVarint(data, size, &pos)); deltas.push_back(delta); } @@ -89,14 +93,14 @@ void DeltaVarintCompressor::EncodeVarint(int64_t value, std::vector* out) out->push_back(static_cast(tmp)); } -Result DeltaVarintCompressor::DecodeVarint(const std::vector& in, size_t* pos) { +Result DeltaVarintCompressor::DecodeVarint(const char* data, size_t size, size_t* pos) { uint64_t result = 0; int32_t shift = 0; while (true) { - if (*pos >= in.size()) { + if (*pos >= size) { return Status::Invalid("Unexpected end of input"); } - char byte = in[(*pos)++]; + char byte = data[(*pos)++]; // Extract 7 bits result |= (static_cast(byte & 0x7F) << shift); // MSB is 0, end of encoding diff --git a/src/paimon/common/utils/delta_varint_compressor.h b/src/paimon/common/utils/delta_varint_compressor.h index a66cbcf31..268ace63b 100644 --- a/src/paimon/common/utils/delta_varint_compressor.h +++ b/src/paimon/common/utils/delta_varint_compressor.h @@ -34,12 +34,13 @@ class PAIMON_EXPORT DeltaVarintCompressor { static std::vector Compress(const std::vector& data); // Decompresses a byte array back to the original long array static Result> Decompress(const std::vector& bytes); + static Result> Decompress(const char* data, size_t size); private: // Encodes a long value using ZigZag and Varints static void EncodeVarint(int64_t value, std::vector* out); // Decodes a Varints-encoded value and reverses ZigZag transformation - static Result DecodeVarint(const std::vector& in, size_t* pos); + static Result DecodeVarint(const char* data, size_t size, size_t* pos); inline static uint64_t ZigZag(int64_t value) { return ((static_cast(value) << 1) ^ (value >> 63)); diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 1563cc5e2..0d152698c 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -36,6 +36,7 @@ #include "paimon/fs/file_system.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/io/data_input_stream.h" +#include "paimon/memory/bytes.h" namespace paimon::blob { namespace { @@ -52,12 +53,6 @@ constexpr int64_t kPlaceholderReference = -2; using IndexLengths = std::array; -struct IndexLayout { - int64_t start; - uint64_t decoded_bytes = 0; - uint64_t decode_peak_bytes = 0; -}; - Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) { for (int64_t read = 0; read < size;) { const Result n = input->Read(data + read, size - read, offset + read); @@ -75,39 +70,39 @@ Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) return Status::OK(); } -Result PlanIndexes(const IndexLengths& lengths, int64_t footer_start) { +Result PlanIndexStart(const IndexLengths& lengths, int64_t footer_start, int64_t tail_end, + uint64_t video_entry_size, uint64_t run_entry_size) { if (footer_start < 0) { return Status::Invalid("video file is smaller than its footer"); } - IndexLayout layout{footer_start}; + int64_t start = footer_start; + uint64_t decoded_bytes = 0; + uint64_t peak = 0; for (int32_t length : lengths) { - if (length < 0 || length > layout.start) { + if (length < 0 || length > start) { return Status::Invalid("video indexes exceed the file size"); } - layout.start -= length; + start -= length; // A varint can be one byte. The decoder holds both deltas and decoded values. - const uint64_t decoded_bytes = static_cast(length) * sizeof(int64_t); - layout.decode_peak_bytes = - std::max(layout.decode_peak_bytes, layout.decoded_bytes + length + 2 * decoded_bytes); - layout.decoded_bytes += decoded_bytes; - } - return layout; -} - -Status CheckIndexBudget(const IndexLayout& layout, uint64_t materialized_bytes) { - if (std::max(layout.decode_peak_bytes, layout.decoded_bytes + materialized_bytes) > - kMaxIndexMemoryBytes) { + const uint64_t index_bytes = static_cast(length) * sizeof(int64_t); + peak = std::max(peak, decoded_bytes + 2 * index_bytes); + decoded_bytes += index_bytes; + } + // Each materialized group has equal entry counts, bounded by its shortest index. + const uint64_t videos = std::min({lengths[0], lengths[1], lengths[2]}); + const uint64_t runs = std::min({lengths[3], lengths[4], lengths[5]}); + peak = std::max(peak, decoded_bytes + videos * video_entry_size + runs * run_entry_size); + if (peak + (tail_end - start) > kMaxIndexMemoryBytes) { return Status::CapacityError("video indexes exceed the memory budget of ", kMaxIndexMemoryBytes, " bytes"); } - return Status::OK(); + return start; } -Result> ReadIndex(InputStream* input, int64_t* offset, int32_t length) { - std::vector bytes(length); - PAIMON_RETURN_NOT_OK(ReadAtFully(input, *offset, bytes.data(), length)); - *offset += length; - return DeltaVarintCompressor::Decompress(bytes); +Result> DecodeIndex(std::string_view* tail, int32_t length) { + const char* data = tail->data(); + tail->remove_prefix(length); + return DeltaVarintCompressor::Decompress(data, length); } bool IsValidFrameRun(int64_t length, int64_t reference, int64_t first, size_t video_count, @@ -117,12 +112,12 @@ bool IsValidFrameRun(int64_t length, int64_t reference, int64_t first, size_t vi (reference >= 0 && static_cast(reference) < video_count && first >= 0)); } -Status ValidateLegacyLayout(InputStream* input, const IndexLengths& lengths, int64_t index_start) { +Status ValidateLegacyLayout(std::string_view tail, const IndexLengths& lengths, + int64_t index_start) { // Before apache/paimon#10905, the payload area contained videos followed by keyframe // indexes. The footer had two physical indexes and three run indexes. - int64_t offset = index_start; - PAIMON_ASSIGN_OR_RAISE(std::vector videos, ReadIndex(input, &offset, lengths[1])); - PAIMON_ASSIGN_OR_RAISE(std::vector keyframes, ReadIndex(input, &offset, lengths[2])); + PAIMON_ASSIGN_OR_RAISE(std::vector videos, DecodeIndex(&tail, lengths[1])); + PAIMON_ASSIGN_OR_RAISE(std::vector keyframes, DecodeIndex(&tail, lengths[2])); if (videos.size() != keyframes.size()) { return Status::Invalid("legacy video and keyframe indexes have different counts"); } @@ -138,10 +133,9 @@ Status ValidateLegacyLayout(InputStream* input, const IndexLengths& lengths, int return Status::Invalid("legacy payload length does not match its indexes"); } - PAIMON_ASSIGN_OR_RAISE(std::vector runs, ReadIndex(input, &offset, lengths[3])); - PAIMON_ASSIGN_OR_RAISE(std::vector references, ReadIndex(input, &offset, lengths[4])); - PAIMON_ASSIGN_OR_RAISE(std::vector first_frames, - ReadIndex(input, &offset, lengths[5])); + PAIMON_ASSIGN_OR_RAISE(std::vector runs, DecodeIndex(&tail, lengths[3])); + PAIMON_ASSIGN_OR_RAISE(std::vector references, DecodeIndex(&tail, lengths[4])); + PAIMON_ASSIGN_OR_RAISE(std::vector first_frames, DecodeIndex(&tail, lengths[5])); if (runs.size() != references.size() || runs.size() != first_frames.size()) { return Status::Invalid("legacy video run indexes have different counts"); } @@ -176,6 +170,18 @@ Result> VideoFileBatchReader::Create( if (!input || !pool || batch_size <= 0) { return Status::Invalid("invalid video reader input, pool, or batch size"); } + PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); + auto reader = std::unique_ptr(new VideoFileBatchReader( + std::move(uri), batch_size, pool, emit_placeholder_sentinel, blob_context)); + const Status status = reader->ReadIndexes(input.get()); + if (!status.ok()) { + return reader->uri_.empty() ? status + : status.WithMessage(status.message(), " (", reader->uri_, ")"); + } + return reader; +} + +Status VideoFileBatchReader::ReadIndexes(InputStream* input) { PAIMON_ASSIGN_OR_RAISE(int64_t size, input->Length()); if (size < kLegacyFooterSize) { return Status::Invalid( @@ -185,8 +191,8 @@ Result> VideoFileBatchReader::Create( // for those lengths starts four bytes earlier in the six-index interpretation. char footer[kFooterSize] = {}; const int64_t footer_size = std::min(size, kFooterSize); - PAIMON_RETURN_NOT_OK(ReadAtFully(input.get(), size - footer_size, - footer + kFooterSize - footer_size, footer_size)); + PAIMON_RETURN_NOT_OK( + ReadAtFully(input, size - footer_size, footer + kFooterSize - footer_size, footer_size)); DataInputStream footer_input(std::make_shared(footer, sizeof(footer))); footer_input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); IndexLengths index_lengths; @@ -199,40 +205,39 @@ Result> VideoFileBatchReader::Create( return Status::Invalid("corrupt or unsupported .video footer"); } - // Check both budgets before reading index data. The legacy probe frees its decoded - // indexes before the six-index reader allocates its own. - const Result modern_layout = PlanIndexes(index_lengths, size - kFooterSize); - if (modern_layout.ok()) { - // Each group has equal entry counts, bounded by its shortest encoded index. - const uint64_t videos = std::min({index_lengths[0], index_lengths[1], index_lengths[2]}); - const uint64_t runs = std::min({index_lengths[3], index_lengths[4], index_lengths[5]}); - PAIMON_RETURN_NOT_OK(CheckIndexBudget( - modern_layout.value(), videos * sizeof(VideoRange) + runs * sizeof(FrameRun))); - } + const int64_t tail_end = size - kLegacyFooterSize; IndexLengths legacy_lengths = index_lengths; legacy_lengths[0] = 0; - const Result legacy_layout = PlanIndexes(legacy_lengths, size - kLegacyFooterSize); - Status legacy_status = legacy_layout.status(); - if (legacy_layout.ok()) { - PAIMON_RETURN_NOT_OK(CheckIndexBudget(legacy_layout.value(), 0)); - legacy_status = - ValidateLegacyLayout(input.get(), legacy_lengths, legacy_layout.value().start); - if (!legacy_status.ok() && !legacy_status.IsInvalid()) { - return legacy_status; - } - } - - std::unique_ptr reader; - Status modern_status = modern_layout.status(); - if (modern_layout.ok()) { - PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); - reader.reset(new VideoFileBatchReader(std::move(uri), batch_size, pool, - emit_placeholder_sentinel, blob_context)); - modern_status = - reader->ReadSixIndexLayout(input.get(), index_lengths, modern_layout.value().start); - if (!modern_status.ok() && !modern_status.IsInvalid()) { - return modern_status; - } + const Result legacy = PlanIndexStart(legacy_lengths, tail_end, tail_end, 0, 0); + // Every six-index candidate contains all five legacy lengths and needs at least + // as much memory. If the legacy range cannot be probed, neither layout can be read. + if (!legacy.ok()) { + return legacy.status().IsInvalid() + ? Status::Invalid("corrupt or unsupported .video layout. ", + legacy.status().message()) + : legacy.status(); + } + const Result modern = PlanIndexStart(index_lengths, size - kFooterSize, tail_end, + sizeof(VideoRange), sizeof(FrameRun)); + + // The six-index range starts first and its budget covers both probes. If it does + // not fit, read only the five-index range to check whether the file needs reimport. + const int64_t start = modern.ok() ? modern.value() : legacy.value(); + Bytes buffer(tail_end - start, pool_.get()); + constexpr int64_t kFooterOverlap = kFooterSize - kLegacyFooterSize; + const int64_t overlap = std::min(buffer.size(), kFooterOverlap); + const int64_t read_size = buffer.size() - overlap; + PAIMON_RETURN_NOT_OK(ReadAtFully(input, start, buffer.data(), read_size)); + if (overlap > 0) { + std::copy_n(footer + kFooterOverlap - overlap, overlap, buffer.data() + read_size); + } + const std::string_view tail(buffer.data(), buffer.size()); + + const Status legacy_status = + ValidateLegacyLayout(tail.substr(legacy.value() - start), legacy_lengths, legacy.value()); + Status modern_status = modern.status(); + if (modern.ok()) { + modern_status = ReadSixIndexLayout(tail, index_lengths, modern.value()); } if (legacy_status.ok()) { if (modern_status.ok()) { @@ -242,19 +247,21 @@ Result> VideoFileBatchReader::Create( } return Status::Invalid("Legacy five-index .video files require reimport"); } - if (!modern_status.ok()) { - return Status::Invalid("corrupt or unsupported .video layout. ", modern_status.ToString()); + if (!legacy_status.IsInvalid()) { + return legacy_status; } - return reader; + if (modern_status.IsInvalid()) { + return Status::Invalid("corrupt or unsupported .video layout. ", modern_status.message()); + } + return modern_status; } -Status VideoFileBatchReader::ReadSixIndexLayout(InputStream* input, +Status VideoFileBatchReader::ReadSixIndexLayout(std::string_view tail, const IndexLengths& index_lengths, int64_t index_start) { std::array, 6> indexes; - int64_t index_offset = index_start; for (size_t i = 0; i < indexes.size(); ++i) { - PAIMON_ASSIGN_OR_RAISE(indexes[i], ReadIndex(input, &index_offset, index_lengths[i])); + PAIMON_ASSIGN_OR_RAISE(indexes[i], DecodeIndex(&tail, index_lengths[i])); } const auto& video_lengths = indexes[0]; diff --git a/src/paimon/format/blob/video_file_batch_reader.h b/src/paimon/format/blob/video_file_batch_reader.h index b50f3c823..76e60b8cf 100644 --- a/src/paimon/format/blob/video_file_batch_reader.h +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include "paimon/reader/file_batch_reader.h" @@ -79,7 +80,8 @@ class VideoFileBatchReader : public FileBatchReader { bool emit_placeholder_sentinel, const std::shared_ptr& blob_context); - Status ReadSixIndexLayout(InputStream* input, const std::array& index_lengths, + Status ReadIndexes(InputStream* input); + Status ReadSixIndexLayout(std::string_view tail, const std::array& index_lengths, int64_t index_start); std::string uri_; diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index e4d0d8e32..e1794253a 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -20,7 +20,7 @@ #include "paimon/format/blob/video_file_batch_reader.h" #include -#include +#include #include "arrow/api.h" #include "arrow/c/bridge.h" @@ -46,6 +46,38 @@ namespace { using blob::VideoFileBatchReader; +constexpr char kVideoUri[] = "s3://bucket/part-2.video"; + +// Serves only the stored suffix, so a read into an omitted payload fails the test. +class VideoTailStream : public MockInputStream { + public: + VideoTailStream(int64_t offset, std::string tail) : offset_(offset), tail_(std::move(tail)) {} + + Result Length() const override { + return offset_ + tail_.size(); + } + + Result GetUri() const override { + return std::string(kVideoUri); + } + + Result Read(char* buffer, int64_t size, int64_t offset) override { + reads.emplace_back(offset, size); + const int64_t end = offset_ + tail_.size(); + if (offset < offset_ || offset > end || size > end - offset) { + return Status::IOError("unexpected read outside the stored video tail"); + } + std::memcpy(buffer, tail_.data() + (offset - offset_), size); + return size; + } + + std::vector> reads; + + private: + int64_t offset_; + std::string tail_; +}; + void Append32(std::string* data, uint32_t value) { for (int32_t i = 0; i < 4; ++i) { data->push_back(static_cast(value >> (8 * i))); @@ -60,18 +92,22 @@ void AppendVideoFooter(std::string* data, const std::vector& index_len data->push_back(1); } -std::string MakeVideoFile(bool placeholder = false, int64_t first_moov_length = 3) { - std::string data = "VIDEOfilm"; - const std::vector> indexes = { - {5, 4}, {2, 0}, {first_moov_length, 0}, {2, 1, 1}, {0, placeholder ? -2 : -1, 1}, - {4, 0, 9}}; +void AppendVideoIndexes(std::string* data, const std::vector>& indexes) { std::vector sizes; for (const auto& values : indexes) { const auto bytes = DeltaVarintCompressor::Compress(values); sizes.push_back(bytes.size()); - data.append(bytes.data(), bytes.size()); + data->append(bytes.data(), bytes.size()); } - AppendVideoFooter(&data, sizes); + AppendVideoFooter(data, sizes); +} + +std::string MakeVideoFile(bool placeholder = false, int64_t first_moov_length = 3) { + std::string data = "VIDEOfilm"; + const std::vector> indexes = { + {5, 4}, {2, 0}, {first_moov_length, 0}, {2, 1, 1}, {0, placeholder ? -2 : -1, 1}, + {4, 0, 9}}; + AppendVideoIndexes(&data, indexes); return data; } @@ -191,7 +227,9 @@ TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { ASSERT_OK(fs->WriteFile(path, bytes, true)); ASSERT_OK_AND_ASSIGN(auto input, fs->Open(path)); std::shared_ptr shared_input(std::move(input)); - ASSERT_NOK(VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr)); + auto result = VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "corrupt or unsupported .video footer"); + ASSERT_NOK_WITH_MSG(result, path); } TEST(VideoFileBatchReaderTest, RejectsLegacyAndAmbiguousVideoLayouts) { @@ -208,15 +246,18 @@ TEST(VideoFileBatchReaderTest, RejectsLegacyAndAmbiguousVideoLayouts) { "\x02\x00\x00\x00"; // Legacy first frames: 1, 1, 1, 1. bytes.append(indexes, sizeof(indexes) - 1); AppendVideoFooter(&bytes, {2, 2, 4, 4, 4}); - auto input = std::make_shared(bytes.data(), bytes.size()); - ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), - "ambiguous v1 .video layout"); + auto input = std::make_shared(0, bytes); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "ambiguous v1 .video layout"); + ASSERT_NOK_WITH_MSG(result, kVideoUri); // This byte belongs to the five-index payload and the six-index video lengths. // Zero video lengths invalidate only the six-index interpretation. bytes[44] = 0; - ASSERT_NOK_WITH_MSG(VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr), - "Legacy five-index .video files require reimport"); + input = std::make_shared(0, bytes); + result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "Legacy five-index .video files require reimport"); + ASSERT_NOK_WITH_MSG(result, kVideoUri); } TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { @@ -263,45 +304,86 @@ TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { } } -TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { - class FooterOnlyStream : public MockInputStream { - public: - explicit FooterOnlyStream(const std::vector& index_lengths) - : footer_offset_( - std::accumulate(index_lengths.begin(), index_lengths.end(), int64_t{0})) { - AppendVideoFooter(&footer_, index_lengths); - } +TEST(VideoFileBatchReaderTest, ReadsJavaIndexesWithOneTailRead) { + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-v1-moov.hex")); + constexpr int64_t kPayloadSize = 24; + auto input = std::make_shared(kPayloadSize, bytes.substr(kPayloadSize)); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); + ASSERT_EQ(reader->GetNumberOfRows().value(), 2); + const std::vector> expected{{30, 29}, {24, 6}}; + ASSERT_EQ(input->reads, expected); +} - Result Length() const override { - return footer_offset_ + footer_.size(); - } +TEST(VideoFileBatchReaderTest, RecognizesLegacyIndexesWithinFooterRead) { + for (const auto& runs : {std::vector{}, std::vector{1}}) { + // A 25-byte empty file or a 28-byte file with one null row fits in the footer read. + std::string bytes; + AppendVideoIndexes(&bytes, {{}, + {}, + runs, + std::vector(runs.size(), -1), + std::vector(runs.size(), 0)}); + auto input = std::make_shared(0, std::move(bytes)); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "Legacy five-index .video files require reimport"); + ASSERT_EQ(input->reads.size(), 1u); + } +} - Result Read(char* buffer, int64_t size, int64_t offset) override { - if (offset != footer_offset_ || size != static_cast(footer_.size())) { - return Status::IOError("unexpected index read"); - } - std::memcpy(buffer, footer_.data(), footer_.size()); - return size; - } +TEST(VideoFileBatchReaderTest, RecognizesLegacyWhenSixIndexCandidateExceedsBudget) { + constexpr int64_t kVideoSize = 10 * 1024 * 1024; + constexpr int64_t kPayloadSize = 4 * kVideoSize; + std::string tail; + // The last four first-frame bytes also spell a 32 MiB six-index length. + AppendVideoIndexes(&tail, {{kVideoSize, kVideoSize, kVideoSize, kVideoSize}, + {0, 0, 0, 0}, + {1, 1, 1, 1}, + {0, 1, 2, 3}, + {0, 0, 0, 1}}); + auto input = std::make_shared(kPayloadSize, tail); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "Legacy five-index .video files require reimport"); + ASSERT_NOK_WITH_MSG(result, kVideoUri); + ASSERT_TRUE(result.status().IsInvalid()); + ASSERT_EQ(input->reads.size(), 2u); + ASSERT_EQ(input->reads.back().first, kPayloadSize); - private: - int64_t footer_offset_; - std::string footer_; - }; + // Losing access to the real legacy indexes leaves the layout undetermined. + input = std::make_shared(kPayloadSize + 1, tail.substr(1)); + result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_TRUE(result.status().IsIOError()) << result.status(); +} - constexpr uint32_t kMiB = 1024 * 1024; - // A single 64 MiB index exceeds the decode budget. Three 1.5 MiB run indexes fit - // during decoding but exceed the budget once the runs and decoded indexes coexist. - constexpr uint32_t kRunIndexBytes = 3 * kMiB / 2; +TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { + constexpr uint32_t kIndexSize = 64 * 1024 * 1024; for (const std::vector& lengths : - {std::vector{64 * kMiB, 0, 0, 0, 0, 0}, - std::vector{0, 0, 0, kRunIndexBytes, kRunIndexBytes, kRunIndexBytes}}) { - auto result = VideoFileBatchReader::Create(std::make_shared(lengths), 2, - GetDefaultPool(), false, nullptr); + {std::vector{kIndexSize, 0, 0, 0, 0, 0}, + std::vector{0, 0, 0, 0, 0, kIndexSize}}) { + std::string footer; + AppendVideoFooter(&footer, lengths); + auto input = std::make_shared(kIndexSize, footer); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); ASSERT_TRUE(result.status().IsCapacityError()) << result.status(); + ASSERT_NOK_WITH_MSG(result, kVideoUri); + ASSERT_EQ(input->reads.size(), 1u); } } +TEST(VideoFileBatchReaderTest, CountsSharedTailInMaterializationBudget) { + // The decoded indexes and frame runs alone fit just below 64 MiB. + constexpr uint32_t kRuns = 64 * 1024 * 1024 / 48; + std::string bytes(3 * kRuns, '\0'); + bytes[0] = 2; + bytes[kRuns] = 1; + AppendVideoFooter(&bytes, {0, 0, 0, kRuns, kRuns, kRuns}); + auto input = std::make_shared(0, std::move(bytes)); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_TRUE(result.status().IsCapacityError()) << result.status(); + ASSERT_EQ(input->reads.size(), 2u); + ASSERT_EQ(input->reads.back().first, 4); // Only the five-index candidate fits. +} + TEST(VideoFileBatchReaderTest, ReadsLargeIndexWithinMemoryBudget) { constexpr uint32_t kRuns = 1024 * 1024; // Each run contains one NULL row. The indexes encode deltas as single-byte varints. @@ -327,6 +409,7 @@ TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); ASSERT_NOK_WITH_MSG(result, "corrupt or unsupported .video layout"); ASSERT_NOK_WITH_MSG(result, "invalid moov range"); + ASSERT_NOK_WITH_MSG(result, path); } TEST(VideoFileBatchReaderTest, ExposesPlaceholdersOnlyForBlobFallback) { From ace18f2fb11c9e510795e1ed8e192b158b04e1e6 Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 02:37:41 -0800 Subject: [PATCH 11/19] perf(blob): open data evolution blob files by row range --- .../reader/blob_fallback_batch_reader.cpp | 16 +++- .../reader/blob_fallback_batch_reader.h | 6 +- .../operation/data_evolution_split_read.cpp | 55 ++++++----- test/inte/blob_table_inte_test.cpp | 92 +++++++++++++++++++ 4 files changed, 146 insertions(+), 23 deletions(-) diff --git a/src/paimon/common/reader/blob_fallback_batch_reader.cpp b/src/paimon/common/reader/blob_fallback_batch_reader.cpp index 24d902169..e019e265d 100644 --- a/src/paimon/common/reader/blob_fallback_batch_reader.cpp +++ b/src/paimon/common/reader/blob_fallback_batch_reader.cpp @@ -78,7 +78,7 @@ Result> BlobFallbackBatchReader::Create if (segment.reader != nullptr && segment.blob_context == nullptr) { return Status::Invalid("Blob fallback file segment needs a blob read context."); } - if (segment.reader == nullptr && segment.gap_selected_ranges.empty()) { + if (!segment.reader && !segment.open_file && segment.gap_selected_ranges.empty()) { return Status::Invalid( "Blob fallback gap segment should cover at least one selected row id."); } @@ -140,6 +140,19 @@ Result BlobFallbackBatchReader::FillWindow(size_t group_idx, int64_t wa break; } Segment& segment = cursor.segments[cursor.segment_idx]; + if (segment.open_file) { + // The newest layer sets the window. Return available rows before opening another file. + if (group_idx == 0 && collected > 0) { + break; + } + auto reader = segment.open_file(&segment.blob_context); + if (!reader.ok()) { + Close(); + return reader.status(); + } + segment.reader = std::move(reader).value(); + segment.open_file = nullptr; + } if (segment.reader == nullptr) { // gap segment: all rows are placeholders, stepped range by range so the row ids // stay available for all-placeholder rows @@ -442,6 +455,7 @@ void BlobFallbackBatchReader::Close() { } } } + groups_.clear(); closed_ = true; } diff --git a/src/paimon/common/reader/blob_fallback_batch_reader.h b/src/paimon/common/reader/blob_fallback_batch_reader.h index 0967bbe22..003fbecd5 100644 --- a/src/paimon/common/reader/blob_fallback_batch_reader.h +++ b/src/paimon/common/reader/blob_fallback_batch_reader.h @@ -19,6 +19,7 @@ #pragma once +#include #include #include @@ -67,13 +68,16 @@ class BlobFallbackBatchReader : public BatchReader { /// with the usual per-file mapping readers and row selection), or a virtual gap standing for /// row ids the group's files do not cover. Segments must be ordered by ascending row id. struct Segment { - /// File segment: emits the rows of one blob file. Null for a gap segment. + /// Open file segment. A deferred file installs its reader on first use. std::unique_ptr reader; /// Gap segment only: the selected row ids the gap emits (all placeholders), as sorted /// disjoint ranges. Must not be empty for a gap segment. std::vector gap_selected_ranges; /// File segment only: shared with the bottom blob reader before any per-file wrapping. std::shared_ptr blob_context = nullptr; + /// Opens the file and returns the context shared with its bottom reader. + std::function>(std::shared_ptr*)> + open_file = nullptr; }; /// `sequence_groups` must be ordered by descending max sequence number and contain at least diff --git a/src/paimon/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index d13cb9199..b636e5c88 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -1236,9 +1236,31 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR } sequence_groups[file->max_sequence_number].emplace_back(file_range.from, file); } - // the blob format reader must emit placeholder sentinels instead of failing on them - const std::map blob_format_options = { - {BlobDefs::kEmitPlaceholderSentinelKey, "true"}}; + auto split_read = + std::make_shared(path_factory_, context_, pool_, executor_); + split_read->file_indexes_evaluated_ = file_indexes_evaluated_; + split_read->group_selection_ = group_selection_; + const auto selected_ranges = + SelectedRangesInRange(union_first_row_id, union_last_row_id, row_ranges); + auto open_file = + [split_read, partition, file_read_schema, group_dv_factory, data_file_path_factory]( + const std::shared_ptr& file, const std::vector& ranges, + std::shared_ptr* context) -> Result> { + PAIMON_ASSIGN_OR_RAISE( + std::vector readers, + split_read->CreateRawFileReadersWithMeta( + partition, {file}, file_read_schema, /*predicate=*/nullptr, group_dv_factory, + ranges, data_file_path_factory, {{BlobDefs::kEmitPlaceholderSentinelKey, "true"}}, + /*attach_blob_context=*/true)); + if (readers.size() != 1) { + return Status::Invalid("Unexpected: blob fallback file reader was skipped."); + } + if (!readers[0].blob_context) { + return Status::Invalid("Blob fallback file segment needs a blob read context."); + } + *context = std::move(readers[0].blob_context); + return std::move(readers[0].reader); + }; std::vector> groups; groups.reserve(sequence_groups.size()); for (auto& [max_sequence_number, group_files] : sequence_groups) { @@ -1276,24 +1298,15 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR BlobFallbackBatchReader::Segment{nullptr, std::move(gap_selected_ranges)}); } } - std::optional> file_ranges = - SelectedRangesInRange(union_first_row_id, union_last_row_id, row_ranges); - if (!SelectedRangesInRange(first_row_id, first_row_id + file->row_count - 1, - file_ranges) - .empty()) { - PAIMON_ASSIGN_OR_RAISE(std::vector file_readers, - CreateRawFileReadersWithMeta( - partition, {file}, file_read_schema, - /*predicate=*/nullptr, group_dv_factory, file_ranges, - data_file_path_factory, blob_format_options, - /*attach_blob_context=*/true)); - if (file_readers.size() != 1) { - return Status::Invalid("Unexpected: blob fallback file reader was skipped."); - } - segments.push_back( - BlobFallbackBatchReader::Segment{std::move(file_readers[0].reader), - {}, - std::move(file_readers[0].blob_context)}); + auto file_ranges = Range::And({Range(first_row_id, first_row_id + file->row_count - 1)}, + selected_ranges); + if (!file_ranges.empty()) { + BlobFallbackBatchReader::Segment segment; + segment.open_file = [open_file, file, ranges = std::move(file_ranges)]( + std::shared_ptr* context) { + return open_file(file, ranges, context); + }; + segments.push_back(std::move(segment)); } next_row_id = std::max(next_row_id, first_row_id + file->row_count); } diff --git a/test/inte/blob_table_inte_test.cpp b/test/inte/blob_table_inte_test.cpp index 9d03b8fb1..942b66723 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -80,6 +80,7 @@ #include "paimon/table/source/data_split.h" #include "paimon/table/source/startup_mode.h" #include "paimon/table/source/table_read.h" +#include "paimon/testing/utils/counting_reader_file_system.h" #include "paimon/testing/utils/deletion_vector_test_helper.h" #include "paimon/testing/utils/io_exception_helper.h" #include "paimon/testing/utils/test_helper.h" @@ -1422,6 +1423,97 @@ TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { std::string_view(base).substr(0, 24)); } +TEST_P(BlobTableInteTest, TestOpenVideoFilesByRowRange) { + const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + BlobUtils::ToArrowField("video", /*nullable=*/true)}; + CreateTable(fields, {}, + {{Options::FILE_FORMAT, GetParam()}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, "video"}}); + const std::string table_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + auto ids = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({fields[0]}), + "[[0], [1], [2], [3]]") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto messages, WriteArray(table_path, {}, {"id"}, {ids})); + ASSERT_OK(Commit(table_path, messages)); + ASSERT_OK_AND_ASSIGN(auto plan, ScanTable(table_path)); + ASSERT_EQ(1u, plan->Splits().size()); + auto split = std::dynamic_pointer_cast(plan->Splits()[0]); + ASSERT_TRUE(split); + auto files = split->DataFiles(); + ASSERT_EQ(1u, files.size()); + ASSERT_OK_AND_ASSIGN(int64_t first, files.front()->NonNullFirstRowId()); + const int64_t seq = files.front()->max_sequence_number + 1; + ASSERT_OK_AND_ASSIGN(std::string video, ReadJavaVideoFixture("video-v1-moov.hex")); + for (int i = 0; i < 2; ++i) { + const std::string name = std::to_string(i) + ".video"; + ASSERT_OK(dir_->GetFileSystem()->WriteFile(PathUtil::JoinPath(split->BucketPath(), name), + video, true)); + ASSERT_OK_AND_ASSIGN( + auto file, DataFileMeta::ForAppend( + name, video.size(), /*row_count=*/2, SimpleStats::EmptyStats(), seq, seq, + /*schema_id=*/0, FileSource::Append(), std::nullopt, std::nullopt, + first + i * 2, std::vector{"video"})); + files.push_back(std::move(file)); + } + ASSERT_OK_AND_ASSIGN(auto video_split, + DataSplitImpl::Builder(split->Partition(), split->Bucket(), + split->BucketPath(), std::move(files)) + .WithSnapshot(split->SnapshotId()) + .WithTotalBuckets(split->TotalBuckets()) + .RawConvertible(false) + .Build()); + + auto open_reader = [&](const std::shared_ptr& fs) + -> Result> { + ReadContextBuilder builder(table_path); + builder.SetReadFieldNames({"id", "video"}) + .WithFileSystem(fs) + .AddOption(Options::READ_BATCH_SIZE, "128"); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr context, builder.Finish()); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr read, + TableRead::Create(std::move(context))); + return read->CreateReader(video_split); + }; + for (int batches_to_read : {1, 2}) { + auto fs = std::make_shared(".video"); + ASSERT_OK_AND_ASSIGN(auto reader, open_reader(fs)); + ASSERT_EQ(0u, fs->counts->opens.load()); + for (int i = 0; i < batches_to_read; ++i) { + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_FALSE(BatchReader::IsEofBatch(batch)); + auto array = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(array.ok()) << array.status().ToString(); + auto rows = checked_pointer_cast(*array); + ASSERT_EQ(2, rows->length()); + auto row_ids = checked_pointer_cast(rows->GetFieldByName("id")); + ASSERT_EQ(i * 2, row_ids->Value(0)); + ASSERT_EQ(i * 2 + 1, row_ids->Value(1)); + ASSERT_EQ(static_cast(i + 1), fs->counts->opens.load()); + } + if (batches_to_read == 2) { + ASSERT_OK_AND_ASSIGN(auto eof, reader->NextBatch()); + ASSERT_TRUE(BatchReader::IsEofBatch(eof)); + } + reader->Close(); + ASSERT_EQ(static_cast(batches_to_read), fs->counts->opens.load()); + } + + auto fs = std::make_shared("1.video"); + fs->before_open = [](const std::string&) { + return Status::IOError("cannot open second video"); + }; + ASSERT_OK_AND_ASSIGN(auto reader, open_reader(fs)); + ASSERT_OK_AND_ASSIGN(auto first_batch, reader->NextBatch()); + ASSERT_FALSE(BatchReader::IsEofBatch(first_batch)); + ReaderUtils::ReleaseReadBatch(std::move(first_batch)); + ASSERT_EQ(0u, fs->counts->opens.load()); + ASSERT_NOK_WITH_MSG(reader->NextBatch(), "cannot open second video"); + ASSERT_EQ(1u, fs->counts->opens.load()); + reader->Close(); +} + TEST_P(BlobTableInteTest, TestDataEvolutionBlobPartialUpdateFallback) { // the blob column is updated to null below, so it must be nullable arrow::FieldVector fields = {arrow::field("f0", arrow::int32()), From d71e30b2cb48c4b7d53eef4f88b0ff7596675abe Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 03:10:09 -0800 Subject: [PATCH 12/19] fix(blob): preserve video frame locations and enforce table declarations --- src/paimon/common/data/blob_utils.cpp | 13 ++++ src/paimon/common/data/blob_utils.h | 4 ++ .../common/data/video_frame_descriptor.cpp | 4 +- src/paimon/common/io/offset_input_stream.cpp | 14 ++++ src/paimon/common/io/offset_input_stream.h | 3 + .../common/utils/delta_varint_compressor.cpp | 8 +-- src/paimon/core/append/append_only_writer.cpp | 13 ---- src/paimon/core/schema/schema_validation.cpp | 42 +++++++----- .../table/append_only_file_store_table.cpp | 10 +++ .../format/blob/blob_format_writer_test.cpp | 12 ++++ .../format/blob/video_file_batch_reader.cpp | 13 ++++ .../blob/video_file_batch_reader_test.cpp | 65 ++++++++++++++++++- test/inte/blob_table_inte_test.cpp | 50 ++++++++++++-- 13 files changed, 209 insertions(+), 42 deletions(-) diff --git a/src/paimon/common/data/blob_utils.cpp b/src/paimon/common/data/blob_utils.cpp index 1afd2d5b2..4d49e4b9b 100644 --- a/src/paimon/common/data/blob_utils.cpp +++ b/src/paimon/common/data/blob_utils.cpp @@ -194,6 +194,19 @@ bool BlobUtils::IsBlobMetadata(const std::shared_ptr BlobUtils::GetVideoFrameFields( + const std::map& options) { + auto it = options.find(BlobDefs::kVideoFrameFieldOption); + if (it == options.end()) { + return {}; + } + auto names = StringUtils::Split(it->second, ","); + for (auto& name : names) { + StringUtils::Trim(&name); + } + return names; +} + bool BlobUtils::IsBlobFile(const std::string& file_name) { return StringUtils::EndsWith(file_name, ".blob") || StringUtils::EndsWith(file_name, ".video"); } diff --git a/src/paimon/common/data/blob_utils.h b/src/paimon/common/data/blob_utils.h index 8292c1085..b4130fe2b 100644 --- a/src/paimon/common/data/blob_utils.h +++ b/src/paimon/common/data/blob_utils.h @@ -20,6 +20,7 @@ #pragma once #include +#include #include #include #include @@ -93,6 +94,9 @@ class PAIMON_EXPORT BlobUtils { /// BOOLEAN, TINYINT, SMALLINT, INT, BIGINT, DATE, DECIMAL, CHAR/VARCHAR and BINARY/VARBINARY. static bool IsSupportedMapBlobKeyType(const arrow::DataType& key_type); static bool IsBlobMetadata(const std::shared_ptr& metadata); + static std::vector GetVideoFrameFields( + const std::map& options); + static bool IsBlobFile(const std::string& file_name); static std::shared_ptr ToArrowField( diff --git a/src/paimon/common/data/video_frame_descriptor.cpp b/src/paimon/common/data/video_frame_descriptor.cpp index c213054e3..9cfe92691 100644 --- a/src/paimon/common/data/video_frame_descriptor.cpp +++ b/src/paimon/common/data/video_frame_descriptor.cpp @@ -63,13 +63,13 @@ Result> VideoFrameDescriptor::Create( } bool VideoFrameDescriptor::HasMagic(const char* buffer, uint64_t size) { - return buffer != nullptr && size >= kHeaderSize && + return buffer != nullptr && size >= kHeaderSize && buffer[0] == kVersion && std::string_view(buffer + sizeof(kVersion), kMagic.size()) == kMagic; } Result> VideoFrameDescriptor::Deserialize(const char* buffer, uint64_t size) { - if (size < kFixedSize || !HasMagic(buffer, size) || buffer[0] != kVersion) { + if (size < kFixedSize || !HasMagic(buffer, size)) { return Status::Invalid("invalid or unsupported video frame descriptor header"); } DataInputStream input(std::make_shared(buffer, size)); diff --git a/src/paimon/common/io/offset_input_stream.cpp b/src/paimon/common/io/offset_input_stream.cpp index fe7d09673..cf05bc984 100644 --- a/src/paimon/common/io/offset_input_stream.cpp +++ b/src/paimon/common/io/offset_input_stream.cpp @@ -19,6 +19,7 @@ #include "paimon/common/io/offset_input_stream.h" +#include #include #include "fmt/format.h" @@ -126,6 +127,19 @@ Result OffsetInputStream::GetUri() const { return wrapped_->GetUri(); } +Result OffsetInputStream::GetFileOffset() const { + int64_t offset = offset_; + auto* parent = dynamic_cast(wrapped_.get()); + while (parent) { + if (parent->offset_ > std::numeric_limits::max() - offset) { + return Status::Invalid("file slice offset overflows int64"); + } + offset += parent->offset_; + parent = dynamic_cast(parent->wrapped_.get()); + } + return offset; +} + Result OffsetInputStream::GetPos() const { return inner_position_; } diff --git a/src/paimon/common/io/offset_input_stream.h b/src/paimon/common/io/offset_input_stream.h index 7c2a4db66..f304c1383 100644 --- a/src/paimon/common/io/offset_input_stream.h +++ b/src/paimon/common/io/offset_input_stream.h @@ -59,6 +59,9 @@ class PAIMON_EXPORT OffsetInputStream : public InputStream { Result GetUri() const override; + /// Offset of this view in the file identified by GetUri(), including enclosing slices. + Result GetFileOffset() const; + private: OffsetInputStream(const std::shared_ptr& wrapped, int64_t length, int64_t offset); Status AssertBoundary(int64_t inner_pos) const; diff --git a/src/paimon/common/utils/delta_varint_compressor.cpp b/src/paimon/common/utils/delta_varint_compressor.cpp index 0c7e098a8..cbb8d78d4 100644 --- a/src/paimon/common/utils/delta_varint_compressor.cpp +++ b/src/paimon/common/utils/delta_varint_compressor.cpp @@ -100,7 +100,10 @@ Result DeltaVarintCompressor::DecodeVarint(const char* data, size_t siz if (*pos >= size) { return Status::Invalid("Unexpected end of input"); } - char byte = data[(*pos)++]; + const uint8_t byte = static_cast(data[(*pos)++]); + if (shift == 63 && byte > 1) { + return Status::Invalid("Varint overflow"); + } // Extract 7 bits result |= (static_cast(byte & 0x7F) << shift); // MSB is 0, end of encoding @@ -108,9 +111,6 @@ Result DeltaVarintCompressor::DecodeVarint(const char* data, size_t siz break; } shift += 7; - if (shift > 63) { - return Status::Invalid("Varint overflow"); - } } return UnZigZag(result); } diff --git a/src/paimon/core/append/append_only_writer.cpp b/src/paimon/core/append/append_only_writer.cpp index 3550f4426..97e7853b2 100644 --- a/src/paimon/core/append/append_only_writer.cpp +++ b/src/paimon/core/append/append_only_writer.cpp @@ -29,7 +29,6 @@ #include "arrow/c/helpers.h" #include "arrow/type.h" #include "arrow/util/key_value_metadata.h" -#include "paimon/common/data/blob_defs.h" #include "paimon/common/data/shredding/shredding_write_plan_factories.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/types/row_kind.h" @@ -38,7 +37,6 @@ #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/long_counter.h" #include "paimon/common/utils/scope_guard.h" -#include "paimon/common/utils/string_utils.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" @@ -191,17 +189,6 @@ Status AppendOnlyWriter::Flush(bool wait_for_latest_compaction, bool forced_full } AppendOnlyWriter::RollingFileWriterResult AppendOnlyWriter::CreateRollingRowWriter() { - const auto& table_options = options_.ToMap(); - const auto video_fields = table_options.find(BlobDefs::kVideoFrameFieldOption); - if (video_fields != table_options.end()) { - for (std::string field : StringUtils::Split(video_fields->second, ",")) { - StringUtils::Trim(&field); - if (write_schema_->GetFieldIndex(field) >= 0) { - return Status::NotImplemented( - fmt::format("writing video-frame-field '{}' is not supported", field)); - } - } - } if (options_.GetVectorFileFormat()) { arrow::FieldVector main_fields; arrow::FieldVector vector_fields; diff --git a/src/paimon/core/schema/schema_validation.cpp b/src/paimon/core/schema/schema_validation.cpp index b8319f6cf..563fa52a8 100644 --- a/src/paimon/core/schema/schema_validation.cpp +++ b/src/paimon/core/schema/schema_validation.cpp @@ -37,6 +37,7 @@ #include "arrow/type.h" #include "fmt/format.h" #include "fmt/ranges.h" +#include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" #include "paimon/common/data/shredding/map_shared_shredding_utils.h" #include "paimon/common/data/variant/variant_type_utils.h" @@ -935,45 +936,52 @@ Status SchemaValidation::ValidateBlobFields(const TableSchema& schema, const Cor const auto& configured_blob_names = options.GetBlobFields(); const auto& blob_descriptor_names = options.GetBlobDescriptorFields(); const auto& blob_view_names = options.GetBlobViewFields(); - if (configured_blob_names.empty() && blob_descriptor_names.empty() && blob_view_names.empty()) { + const auto video_frame_names = BlobUtils::GetVideoFrameFields(schema.Options()); + if (configured_blob_names.empty() && blob_descriptor_names.empty() && blob_view_names.empty() && + video_frame_names.empty()) { return Status::OK(); } + std::unordered_map storage_option_by_field; auto validate_blob_fields = [&](const std::vector& field_names, - const std::string& option_key, - bool allow_container_blob) -> Status { + const std::string& option_key) -> Status { if (field_names.empty()) { return Status::OK(); } PAIMON_RETURN_NOT_OK(ValidateNoDuplicateField(field_names, option_key)); PAIMON_ASSIGN_OR_RAISE(std::vector blob_fields, schema.GetFields(field_names)); + const bool is_blob_field_option = option_key == Options::BLOB_FIELD; for (const auto& blob_field : blob_fields) { - bool is_blob = allow_container_blob ? BlobUtils::IsAnyBlobField(blob_field.ArrowField()) + bool is_blob = is_blob_field_option ? BlobUtils::IsAnyBlobField(blob_field.ArrowField()) : BlobUtils::IsBlobField(blob_field.ArrowField()); if (!is_blob) { const std::string expected_type = - allow_container_blob ? "BLOB, ARRAY or MAP<..., BLOB>" : "BLOB"; + is_blob_field_option ? "BLOB, ARRAY or MAP<..., BLOB>" : "BLOB"; return Status::Invalid( fmt::format("Field '{}' in '{}' must be a {} field in table schema.", blob_field.Name(), option_key, expected_type)); } + // blob-field can also name a video column. The other storage modes are exclusive. + if (!is_blob_field_option) { + auto [it, inserted] = + storage_option_by_field.emplace(blob_field.Name(), option_key); + if (!inserted) { + return Status::Invalid( + fmt::format("Field '{}' in '{}' can not also be in '{}'.", + blob_field.Name(), option_key, it->second)); + } + } } return Status::OK(); }; - PAIMON_RETURN_NOT_OK(validate_blob_fields(configured_blob_names, Options::BLOB_FIELD, true)); + PAIMON_RETURN_NOT_OK(validate_blob_fields(configured_blob_names, Options::BLOB_FIELD)); PAIMON_RETURN_NOT_OK( - validate_blob_fields(blob_descriptor_names, Options::BLOB_DESCRIPTOR_FIELD, false)); - PAIMON_RETURN_NOT_OK(validate_blob_fields(blob_view_names, Options::BLOB_VIEW_FIELD, false)); - - std::set blob_descriptor_name_set(blob_descriptor_names.begin(), - blob_descriptor_names.end()); - for (const auto& blob_view_name : blob_view_names) { - if (blob_descriptor_name_set.count(blob_view_name) > 0) { - return Status::Invalid(fmt::format("Field '{}' in '{}' can not also be in '{}'.", - blob_view_name, Options::BLOB_VIEW_FIELD, - Options::BLOB_DESCRIPTOR_FIELD)); - } + validate_blob_fields(blob_descriptor_names, Options::BLOB_DESCRIPTOR_FIELD)); + PAIMON_RETURN_NOT_OK(validate_blob_fields(blob_view_names, Options::BLOB_VIEW_FIELD)); + PAIMON_RETURN_NOT_OK(validate_blob_fields(video_frame_names, BlobDefs::kVideoFrameFieldOption)); + if (!video_frame_names.empty() && !schema.PrimaryKeys().empty()) { + return Status::Invalid("video-frame-field only supports append-only tables"); } return Status::OK(); } 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..c784520a3 100644 --- a/src/paimon/core/table/append_only_file_store_table.cpp +++ b/src/paimon/core/table/append_only_file_store_table.cpp @@ -26,6 +26,7 @@ #include #include "fmt/format.h" +#include "paimon/common/data/blob_utils.h" #include "paimon/common/utils/checked_cast.h" #include "paimon/core/deletionvectors/bucketed_dv_maintainer.h" #include "paimon/core/index/index_file_handler.h" @@ -116,6 +117,15 @@ Result> AppendOnlyFileStoreTable::CreateWrite( write_schema = arrow::schema(write_fields); } + // A per-write override must not turn a persisted video column into an ordinary blob. + for (const auto* declaration : {&schema->Options(), &options.ToMap()}) { + for (const auto& name : BlobUtils::GetVideoFrameFields(*declaration)) { + if (write_schema->GetFieldIndex(name) >= 0) { + return Status::NotImplemented( + fmt::format("writing video-frame-field '{}' is not supported", name)); + } + } + } std::shared_ptr realtime_schema_layout; if (ctx.GetRealtimeContext()) { const RealtimeStoreMode mode = diff --git a/src/paimon/format/blob/blob_format_writer_test.cpp b/src/paimon/format/blob/blob_format_writer_test.cpp index 3e3ca507c..bd539d875 100644 --- a/src/paimon/format/blob/blob_format_writer_test.cpp +++ b/src/paimon/format/blob/blob_format_writer_test.cpp @@ -731,6 +731,18 @@ TEST_F(BlobFormatWriterWriteNullTest, TestRejectVideoFrameDescriptor) { "video frame descriptors cannot be written to .blob files"); } +TEST_F(BlobFormatWriterWriteNullTest, WritesRawBytesWithVideoMagicAndDifferentVersion) { + const std::string bytes = "xMRFOEDIV"; + ASSERT_OK_AND_ASSIGN(std::shared_ptr writer, CreateDefaultWriter()); + ASSERT_OK_AND_ASSIGN(auto array, MakeBlobArrayFromBytes(bytes)); + ASSERT_OK(AddBatchOnce(writer, array)); + ASSERT_OK(writer->Finish()); + ASSERT_OK_AND_ASSIGN(auto rows, ReadBackAsData()); + auto values = checked_pointer_cast(rows->field(0)); + ASSERT_EQ(values->length(), 1); + ASSERT_EQ(values->GetView(0), bytes); +} + TEST_F(BlobFormatWriterWriteNullTest, TestWriteNullOnMissingFile) { ASSERT_OK_AND_ASSIGN( std::shared_ptr writer, diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 0d152698c..7958a1def 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -28,6 +28,7 @@ #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" #include "paimon/common/data/video_frame_descriptor.h" +#include "paimon/common/io/offset_input_stream.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/reader/blob_read_context.h" #include "paimon/common/utils/arrow/mem_utils.h" @@ -178,6 +179,18 @@ Result> VideoFileBatchReader::Create( return reader->uri_.empty() ? status : status.WithMessage(status.message(), " (", reader->uri_, ")"); } + if (!reader->videos_.empty() && reader->uri_.empty()) { + return Status::Invalid("video frame descriptors require a reopenable file URI"); + } + if (const auto* slice = dynamic_cast(input.get())) { + PAIMON_ASSIGN_OR_RAISE(int64_t base, slice->GetFileOffset()); + for (auto& video : reader->videos_) { + if (base > std::numeric_limits::max() - video.offset - video.length) { + return Status::Invalid("video payload range overflows the backing file offset"); + } + video.offset += base; + } + } return reader; } diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index e1794253a..01db93f0c 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -29,6 +29,7 @@ #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" #include "paimon/common/data/video_frame_descriptor.h" +#include "paimon/common/io/offset_input_stream.h" #include "paimon/common/reader/blob_read_context.h" #include "paimon/common/utils/delta_varint_compressor.h" #include "paimon/data/blob.h" @@ -195,6 +196,64 @@ TEST(VideoFileBatchReaderTest, ReadsJavaCompatibleRunsAndSelection) { ASSERT_EQ(imported.ValueOrDie()->length(), 2); } +TEST(VideoFileBatchReaderTest, ReopensFramesFromContainerSlice) { + auto dir = UniqueTestDirectory::Create(); + auto fs = dir->GetFileSystem(); + const std::string path = dir->Str() + "/container"; + const std::string pack = MakeVideoFile(); + ASSERT_OK(fs->WriteFile(path, "12345" + pack + "suffix", true)); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(4)); + for (int prefix : {5, 2}) { + ASSERT_OK_AND_ASSIGN(auto blob, Blob::FromPath(path, prefix, pack.size() + 5 - prefix)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, blob->NewInputStream(fs)); + if (prefix != 5) { + ASSERT_OK_AND_ASSIGN(input, OffsetInputStream::Create(input, pack.size(), 5 - prefix)); + } + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(input)); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, std::nullopt)); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + auto rows = std::static_pointer_cast( + arrow::ImportArray(batch.first.get(), batch.second.get()).ValueOrDie()); + reader->Close(); + ASSERT_OK(input->Close()); + auto values = std::static_pointer_cast(rows->field(0)); + ASSERT_EQ(values->length(), 4); + for (int i : {0, 3}) { + const auto bytes = values->GetView(i); + ASSERT_OK_AND_ASSIGN(auto frame, Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_EQ(frame->FrameIndex(), i == 0 ? 4 : 9); + ASSERT_EQ(frame->MoovOffset(), i == 0 ? 2 : 0); + ASSERT_OK_AND_ASSIGN(auto payload, frame->ToData(fs, GetDefaultPool())); + ASSERT_EQ(std::string_view(payload->data(), payload->size()), + i == 0 ? "VIDEO" : "film"); + } + } +} + +TEST(VideoFileBatchReaderTest, RejectsFramesWithoutFileUri) { + const auto bytes = MakeVideoFile(); + auto input = std::make_shared(bytes.data(), bytes.size()); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + ASSERT_NOK_WITH_MSG(builder->Build(input), "reopenable file URI"); +} + +TEST(VideoFileBatchReaderTest, RejectsOverflowingFrameIndex) { + // A tenth byte of 2 encodes 2^64, which would truncate to frame zero. + std::string bytes("V\x02\x00\x00\x02\x00", 6); + bytes.append(9, static_cast(0x80)); + bytes.push_back(2); + AppendVideoFooter(&bytes, {1, 1, 1, 1, 1, 10}); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(1)); + ASSERT_NOK_WITH_MSG(builder->Build(std::make_shared(0, bytes)), + "Varint overflow"); +} + TEST(VideoFileBatchReaderTest, RoundTripsJavaFrameDescriptor) { ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-frame-descriptor-v1.hex")); ASSERT_OK_AND_ASSIGN(std::unique_ptr blob, @@ -227,9 +286,10 @@ TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { ASSERT_OK(fs->WriteFile(path, bytes, true)); ASSERT_OK_AND_ASSIGN(auto input, fs->Open(path)); std::shared_ptr shared_input(std::move(input)); + ASSERT_OK_AND_ASSIGN(std::string uri, shared_input->GetUri()); auto result = VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr); ASSERT_NOK_WITH_MSG(result, "corrupt or unsupported .video footer"); - ASSERT_NOK_WITH_MSG(result, path); + ASSERT_NOK_WITH_MSG(result, uri); } TEST(VideoFileBatchReaderTest, RejectsLegacyAndAmbiguousVideoLayouts) { @@ -406,10 +466,11 @@ TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { ASSERT_OK( fs->WriteFile(path, MakeVideoFile(/*placeholder=*/false, /*first_moov_length=*/4), true)); ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs->Open(path)); + ASSERT_OK_AND_ASSIGN(std::string uri, input->GetUri()); auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); ASSERT_NOK_WITH_MSG(result, "corrupt or unsupported .video layout"); ASSERT_NOK_WITH_MSG(result, "invalid moov range"); - ASSERT_NOK_WITH_MSG(result, path); + ASSERT_NOK_WITH_MSG(result, uri); } TEST(VideoFileBatchReaderTest, ExposesPlaceholdersOnlyForBlobFallback) { diff --git a/test/inte/blob_table_inte_test.cpp b/test/inte/blob_table_inte_test.cpp index 942b66723..b8d24d6be 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -141,10 +141,11 @@ class BlobTableInteTest : public testing::Test, public ::testing::WithParamInter Result>> WriteArray( const std::string& table_path, const std::map& partition, const std::vector& write_cols, - const std::vector>& write_arrays) const { + const std::vector>& write_arrays, + const std::map& options = {}) const { // write WriteContextBuilder write_builder(table_path, "commit_user_1"); - write_builder.WithWriteSchema(write_cols); + write_builder.WithWriteSchema(write_cols).SetOptions(options); PAIMON_ASSIGN_OR_RAISE(std::unique_ptr write_context, write_builder.Finish()); PAIMON_ASSIGN_OR_RAISE(auto file_store_write, FileStoreWrite::Create(std::move(write_context))); @@ -1330,6 +1331,34 @@ std::shared_ptr MakeBlobUpdateArray( return std::dynamic_pointer_cast(array); } +TEST_P(BlobTableInteTest, ValidateVideoFrameFieldsOnCreateTable) { + auto schema = + arrow::schema({arrow::field("id", arrow::int32()), BlobUtils::ToArrowField("video", true), + arrow::field("frames", arrow::list(BlobUtils::ToArrowField("item", true)))}); + ASSERT_OK_AND_ASSIGN(auto catalog, Catalog::Create(dir_->Str(), {})); + ASSERT_OK(catalog->CreateDatabase("foo", {}, false)); + auto create = [&](const std::string& fields, const std::string& other_option = "") { + std::map options = {{Options::FILE_FORMAT, GetParam()}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, fields}}; + if (!other_option.empty()) { + options[other_option] = "video"; + } + ::ArrowSchema c_schema; + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*schema, &c_schema)); + return catalog->CreateTable(Identifier("foo", "bar"), &c_schema, {}, {}, options, false); + }; + for (const auto& name : {"missing", "id", "frames"}) { + ASSERT_NOK_WITH_MSG(create(name), name); + } + ASSERT_NOK_WITH_MSG(create("video,video"), "duplicate"); + for (const auto& conflict : {Options::BLOB_DESCRIPTOR_FIELD, Options::BLOB_VIEW_FIELD}) { + ASSERT_NOK_WITH_MSG(create("video", conflict), conflict); + } + ASSERT_OK(create("video", Options::BLOB_FIELD)); +} + TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), BlobUtils::ToArrowField("video", /*nullable=*/true)}; @@ -1343,13 +1372,26 @@ TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { auto id_array = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({fields[0]}), "[[10], [20]]") .ValueOrDie(); - // The table option is present, but a projection that excludes video can still write. - ASSERT_OK_AND_ASSIGN(auto commit_messages, WriteArray(table_path, {}, {"id"}, {id_array})); + const std::map override = {{BlobDefs::kVideoFrameFieldOption, ""}}; + // Clearing the declaration for a write still permits a projection that excludes video. + ASSERT_OK_AND_ASSIGN(auto commit_messages, + WriteArray(table_path, {}, {"id"}, {id_array}, override)); ASSERT_OK(Commit(table_path, commit_messages)); auto video_array = MakeBlobUpdateArray(fields[1], {"payload"}); ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"video"}, {video_array}), "writing video-frame-field 'video' is not supported"); + auto full_row = + arrow::StructArray::Make( + {std::static_pointer_cast(id_array)->field(0)->Slice(0, 1), + video_array->field(0)}, + fields) + .ValueOrDie(); + ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {}, {full_row}, override), + "writing video-frame-field 'video' is not supported"); + ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"video"}, {video_array}, override), + "writing video-frame-field 'video' is not supported"); + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, ScanTable(table_path)); ASSERT_EQ(plan->Splits().size(), 1); auto main_split = std::dynamic_pointer_cast(plan->Splits()[0]); From abbdbb894d71f880a49e442b1a4a3a0cf7215bd4 Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 04:13:00 -0800 Subject: [PATCH 13/19] fix(blob): use a C++17 capture for lazy file readers --- src/paimon/core/operation/data_evolution_split_read.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/paimon/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index b636e5c88..a71f17eda 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -1302,9 +1302,9 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR selected_ranges); if (!file_ranges.empty()) { BlobFallbackBatchReader::Segment segment; - segment.open_file = [open_file, file, ranges = std::move(file_ranges)]( + segment.open_file = [open_file, file_meta = file, ranges = std::move(file_ranges)]( std::shared_ptr* context) { - return open_file(file, ranges, context); + return open_file(file_meta, ranges, context); }; segments.push_back(std::move(segment)); } From 4f7f408fc6c7997f710b9ce0f81831a50e90c3b0 Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 05:13:06 -0800 Subject: [PATCH 14/19] fix(blob): preserve frame references across stream wrappers and inline writes --- docs/source/user_guide/read.rst | 7 ++-- include/paimon/io/buffered_input_stream.h | 2 + include/paimon/io/file_offset_input_stream.h | 41 +++++++++++++++++++ src/paimon/common/data/blob_utils.cpp | 11 ++++- src/paimon/common/data/blob_utils.h | 2 + src/paimon/common/io/cache_input_stream.h | 8 +++- .../common/io/cache_input_stream_test.cpp | 16 ++++++++ src/paimon/common/io/offset_input_stream.cpp | 29 +++++++++---- src/paimon/common/io/offset_input_stream.h | 6 +-- .../prefetch_file_batch_reader_impl.cpp | 7 +++- src/paimon/core/utils/blob_view_lookup.cpp | 8 ++-- .../format/blob/video_file_batch_reader.cpp | 6 +-- .../blob/video_file_batch_reader_test.cpp | 11 ++++- test/inte/blob_table_inte_test.cpp | 34 +++++++++++++++ 14 files changed, 159 insertions(+), 29 deletions(-) create mode 100644 include/paimon/io/file_offset_input_stream.h diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index 1b036e034..9db56ace2 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -338,9 +338,10 @@ Paimon C++ reads scalar BLOB columns from v1 ``.video`` files that match only the six-index layout (29-byte footer). It rejects files whose estimated peak index memory exceeds 64 MiB. -Reimport five-index or ambiguous files with a Java reader for the source -layout and a current Java writer. Verify row counts, frame ordinals and row -alignment in C++ before switching. +Reimport four-index (21-byte footer), five-index (25-byte footer), or ambiguous v1 +files with a Java reader for the source layout and a current Java writer. +Regenerate frame descriptors stored in downstream tables from the new files, +then verify row counts, frame ordinals and row alignment in C++ before switching. Non-null rows return frame descriptors even with ``blob-as-descriptor=false``. Open them with ``Blob::FromDescriptor()``. Use ``FrameIndex()`` for the zero-based diff --git a/include/paimon/io/buffered_input_stream.h b/include/paimon/io/buffered_input_stream.h index 6b172cb96..fa0af44a5 100644 --- a/include/paimon/io/buffered_input_stream.h +++ b/include/paimon/io/buffered_input_stream.h @@ -70,6 +70,8 @@ class PAIMON_EXPORT BufferedInputStream : public InputStream { static constexpr int64_t DEFAULT_BUFFER_SIZE = 8192; private: + friend class FileOffsetInputStream; + /// Fill the internal buffer from the underlying stream. Status Fill(); diff --git a/include/paimon/io/file_offset_input_stream.h b/include/paimon/io/file_offset_input_stream.h new file mode 100644 index 000000000..8fc155b89 --- /dev/null +++ b/include/paimon/io/file_offset_input_stream.h @@ -0,0 +1,41 @@ +/* + * 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 "paimon/fs/file_system.h" + +namespace paimon { + +/// A stream whose position zero can be at an offset in the file identified by GetUri(). +/// Wrappers that preserve positions forward the backing stream's file offset. +class PAIMON_EXPORT FileOffsetInputStream : public InputStream { + public: + ~FileOffsetInputStream() override = default; + + /// Returns the nonnegative backing-file offset of position zero. + virtual Result GetFileOffset() const = 0; + + /// Ordinary whole-file streams start at offset zero. + static Result GetFileOffset(const InputStream& stream); +}; + +} // namespace paimon diff --git a/src/paimon/common/data/blob_utils.cpp b/src/paimon/common/data/blob_utils.cpp index 4d49e4b9b..7acc17693 100644 --- a/src/paimon/common/data/blob_utils.cpp +++ b/src/paimon/common/data/blob_utils.cpp @@ -30,6 +30,7 @@ #include "fmt/format.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_view_struct.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" @@ -219,6 +220,14 @@ std::shared_ptr BlobUtils::ToArrowField( std::make_shared(metadata)); } +Result BlobUtils::IsBlobReference(std::string_view bytes) { + if (VideoFrameDescriptor::HasMagic(bytes.data(), bytes.size())) { + PAIMON_RETURN_NOT_OK(VideoFrameDescriptor::Deserialize(bytes.data(), bytes.size())); + return true; + } + return BlobDescriptor::IsBlobDescriptor(bytes.data(), bytes.size()); +} + Status BlobUtils::ValidateBlobInlineFields(const std::shared_ptr& struct_array, const std::set& field_names, const std::string& config_label) { @@ -246,7 +255,7 @@ Status BlobUtils::ValidateBlobInlineFields(const std::shared_ptrGetView(row); Result valid = is_descriptor - ? BlobDescriptor::IsBlobDescriptor(value.data(), value.size()) + ? IsBlobReference(value) : BlobViewStruct::IsBlobViewStruct(value.data(), value.size()); PAIMON_ASSIGN_OR_RAISE(bool is_valid, std::move(valid)); if (!is_valid) { diff --git a/src/paimon/common/data/blob_utils.h b/src/paimon/common/data/blob_utils.h index b4130fe2b..89170f363 100644 --- a/src/paimon/common/data/blob_utils.h +++ b/src/paimon/common/data/blob_utils.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -98,6 +99,7 @@ class PAIMON_EXPORT BlobUtils { const std::map& options); static bool IsBlobFile(const std::string& file_name); + static Result IsBlobReference(std::string_view bytes); static std::shared_ptr ToArrowField( const std::string& field_name, bool nullable = false, diff --git a/src/paimon/common/io/cache_input_stream.h b/src/paimon/common/io/cache_input_stream.h index 015b082c3..9b738239f 100644 --- a/src/paimon/common/io/cache_input_stream.h +++ b/src/paimon/common/io/cache_input_stream.h @@ -23,11 +23,11 @@ #include "paimon/common/utils/math.h" #include "paimon/common/utils/read_ahead_cache.h" -#include "paimon/fs/file_system.h" +#include "paimon/io/file_offset_input_stream.h" namespace paimon { -class CacheInputStream : public InputStream { +class CacheInputStream : public FileOffsetInputStream { public: CacheInputStream(std::unique_ptr input_stream, const std::shared_ptr& cache) @@ -89,6 +89,10 @@ class CacheInputStream : public InputStream { return input_stream_->GetUri(); } + Result GetFileOffset() const override { + return FileOffsetInputStream::GetFileOffset(*input_stream_); + } + Result Length() const override { return input_stream_->Length(); } diff --git a/src/paimon/common/io/cache_input_stream_test.cpp b/src/paimon/common/io/cache_input_stream_test.cpp index 4c05c57c3..7d4022975 100644 --- a/src/paimon/common/io/cache_input_stream_test.cpp +++ b/src/paimon/common/io/cache_input_stream_test.cpp @@ -26,10 +26,12 @@ #include "gtest/gtest.h" #include "paimon/common/factories/io_hook.h" +#include "paimon/common/io/offset_input_stream.h" #include "paimon/common/utils/read_ahead_cache.h" #include "paimon/common/utils/scope_guard.h" #include "paimon/fs/file_system.h" #include "paimon/fs/file_system_factory.h" +#include "paimon/io/buffered_input_stream.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/memory/memory_pool.h" #include "paimon/testing/utils/io_exception_helper.h" @@ -121,6 +123,20 @@ TEST_F(CacheInputStreamTest, TestReadWithOffsetNullCache) { ASSERT_EQ(buffer, "cdefg"); } +TEST_F(CacheInputStreamTest, CachedBufferedSliceKeepsFileOffset) { + ASSERT_OK_AND_ASSIGN(std::shared_ptr slice, + OffsetInputStream::Create(OpenFile(), /*length=*/8, /*offset=*/5)); + auto cache = std::make_shared(slice, CacheConfig(), 8, pool_); + ASSERT_OK(cache->AddRanges({{0, 8}})); + CacheInputStream stream(std::make_unique(slice, 8, pool_.get()), cache); + std::string bytes(4, '\0'); + ASSERT_OK_AND_ASSIGN(int64_t size, stream.Read(bytes.data(), bytes.size(), /*offset=*/0)); + ASSERT_EQ(size, 4); + ASSERT_EQ(bytes, content_.substr(5, 4)); + ASSERT_OK_AND_ASSIGN(int64_t base, stream.GetFileOffset()); + ASSERT_EQ(base, 5); +} + // Test Read(offset) with cache hit → memcpy from cache TEST_F(CacheInputStreamTest, TestReadWithOffsetCacheHit) { // Cache range [2, 5) i.e. offset=2, length=5 diff --git a/src/paimon/common/io/offset_input_stream.cpp b/src/paimon/common/io/offset_input_stream.cpp index cf05bc984..dc7362381 100644 --- a/src/paimon/common/io/offset_input_stream.cpp +++ b/src/paimon/common/io/offset_input_stream.cpp @@ -24,9 +24,25 @@ #include "fmt/format.h" #include "paimon/common/utils/math.h" +#include "paimon/io/buffered_input_stream.h" #include "paimon/macros.h" namespace paimon { +Result FileOffsetInputStream::GetFileOffset(const InputStream& stream) { + if (const auto* view = dynamic_cast(&stream)) { + PAIMON_ASSIGN_OR_RAISE(int64_t offset, view->GetFileOffset()); + if (offset < 0) { + return Status::Invalid("negative backing file offset"); + } + return offset; + } + // BufferedInputStream is an existing public wrapper. Preserve its class layout and vtable. + if (const auto* buffered = dynamic_cast(&stream)) { + return GetFileOffset(*buffered->in_); + } + return 0; +} + Result> OffsetInputStream::Create( const std::shared_ptr& wrapped, int64_t length, int64_t offset) { if (PAIMON_UNLIKELY(wrapped == nullptr)) { @@ -128,16 +144,11 @@ Result OffsetInputStream::GetUri() const { } Result OffsetInputStream::GetFileOffset() const { - int64_t offset = offset_; - auto* parent = dynamic_cast(wrapped_.get()); - while (parent) { - if (parent->offset_ > std::numeric_limits::max() - offset) { - return Status::Invalid("file slice offset overflows int64"); - } - offset += parent->offset_; - parent = dynamic_cast(parent->wrapped_.get()); + PAIMON_ASSIGN_OR_RAISE(int64_t base, FileOffsetInputStream::GetFileOffset(*wrapped_)); + if (base > std::numeric_limits::max() - offset_) { + return Status::Invalid("file slice offset overflows int64"); } - return offset; + return base + offset_; } Result OffsetInputStream::GetPos() const { diff --git a/src/paimon/common/io/offset_input_stream.h b/src/paimon/common/io/offset_input_stream.h index f304c1383..276db6116 100644 --- a/src/paimon/common/io/offset_input_stream.h +++ b/src/paimon/common/io/offset_input_stream.h @@ -24,7 +24,7 @@ #include #include -#include "paimon/fs/file_system.h" +#include "paimon/io/file_offset_input_stream.h" #include "paimon/result.h" #include "paimon/status.h" #include "paimon/visibility.h" @@ -33,7 +33,7 @@ namespace paimon { /// An `InputStream` wrapping another `InputStream` with offset and length. /// @note Not safe for concurrent or interleaved use with other views of the wrapped stream: Seek /// and sequential Read share the wrapped stream's position and may read from the wrong offset. -class PAIMON_EXPORT OffsetInputStream : public InputStream { +class PAIMON_EXPORT OffsetInputStream : public FileOffsetInputStream { public: static Result> Create( const std::shared_ptr& wrapped, int64_t length, int64_t offset); @@ -60,7 +60,7 @@ class PAIMON_EXPORT OffsetInputStream : public InputStream { Result GetUri() const override; /// Offset of this view in the file identified by GetUri(), including enclosing slices. - Result GetFileOffset() const; + Result GetFileOffset() const override; private: OffsetInputStream(const std::shared_ptr& wrapped, int64_t length, int64_t offset); diff --git a/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp b/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp index b3d89b2f7..77c4186cc 100644 --- a/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp +++ b/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp @@ -38,6 +38,7 @@ #include "paimon/common/utils/scope_guard.h" #include "paimon/format/reader_builder.h" #include "paimon/fs/file_system.h" +#include "paimon/io/file_offset_input_stream.h" #include "paimon/memory/memory_pool.h" namespace arrow { @@ -103,7 +104,7 @@ void RecordLatency(uint64_t latency_us, std::atomic* count, sum_us->fetch_add(latency_us, kMetricsMemoryOrder); } -class MetricsInputStream : public InputStream { +class MetricsInputStream : public FileOffsetInputStream { public: MetricsInputStream(const std::shared_ptr& stream, const std::shared_ptr& metrics) @@ -162,6 +163,10 @@ class MetricsInputStream : public InputStream { return stream_->GetUri(); } + Result GetFileOffset() const override { + return FileOffsetInputStream::GetFileOffset(*stream_); + } + Result Length() const override { return stream_->Length(); } diff --git a/src/paimon/core/utils/blob_view_lookup.cpp b/src/paimon/core/utils/blob_view_lookup.cpp index d6dfba625..d60c94c13 100644 --- a/src/paimon/core/utils/blob_view_lookup.cpp +++ b/src/paimon/core/utils/blob_view_lookup.cpp @@ -28,12 +28,11 @@ #include "arrow/c/bridge.h" #include "fmt/format.h" #include "paimon/catalog/catalog.h" -#include "paimon/common/data/video_frame_descriptor.h" +#include "paimon/common/data/blob_utils.h" #include "paimon/common/executor/future.h" #include "paimon/common/table/special_fields.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" -#include "paimon/data/blob_descriptor.h" #include "paimon/defs.h" #include "paimon/executor.h" #include "paimon/global_index/bitmap_global_index_result.h" @@ -251,9 +250,8 @@ Status BlobViewLookup::ExtractBlobDescriptors(const Identifier& identifier, continue; } std::string_view bytes = binary_array->GetView(row); - PAIMON_ASSIGN_OR_RAISE(bool is_descriptor, BlobDescriptor::IsBlobDescriptor( - bytes.data(), bytes.size())); - if (!is_descriptor && !VideoFrameDescriptor::HasMagic(bytes.data(), bytes.size())) { + PAIMON_ASSIGN_OR_RAISE(bool is_descriptor, BlobUtils::IsBlobReference(bytes)); + if (!is_descriptor) { return Status::Invalid( "requires a serialized BlobDescriptor or VideoFrameDescriptor in the " "source table."); diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 7958a1def..d808a70f5 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -28,7 +28,6 @@ #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" #include "paimon/common/data/video_frame_descriptor.h" -#include "paimon/common/io/offset_input_stream.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/reader/blob_read_context.h" #include "paimon/common/utils/arrow/mem_utils.h" @@ -37,6 +36,7 @@ #include "paimon/fs/file_system.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/io/data_input_stream.h" +#include "paimon/io/file_offset_input_stream.h" #include "paimon/memory/bytes.h" namespace paimon::blob { @@ -182,8 +182,8 @@ Result> VideoFileBatchReader::Create( if (!reader->videos_.empty() && reader->uri_.empty()) { return Status::Invalid("video frame descriptors require a reopenable file URI"); } - if (const auto* slice = dynamic_cast(input.get())) { - PAIMON_ASSIGN_OR_RAISE(int64_t base, slice->GetFileOffset()); + PAIMON_ASSIGN_OR_RAISE(int64_t base, FileOffsetInputStream::GetFileOffset(*input)); + if (base != 0) { for (auto& video : reader->videos_) { if (base > std::numeric_limits::max() - video.offset - video.length) { return Status::Invalid("video payload range overflows the backing file offset"); diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index 01db93f0c..ea6adab32 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -29,6 +29,7 @@ #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" #include "paimon/common/data/video_frame_descriptor.h" +#include "paimon/common/io/cache_input_stream.h" #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/reader/blob_read_context.h" #include "paimon/common/utils/delta_varint_compressor.h" @@ -204,9 +205,15 @@ TEST(VideoFileBatchReaderTest, ReopensFramesFromContainerSlice) { ASSERT_OK(fs->WriteFile(path, "12345" + pack + "suffix", true)); ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(4)); - for (int prefix : {5, 2}) { + for (const auto& [prefix, cached] : + {std::pair{5, false}, std::pair{2, false}, std::pair{5, true}, std::pair{2, true}}) { + SCOPED_TRACE(::testing::Message() << "prefix=" << prefix << ", cached=" << cached); ASSERT_OK_AND_ASSIGN(auto blob, Blob::FromPath(path, prefix, pack.size() + 5 - prefix)); - ASSERT_OK_AND_ASSIGN(std::shared_ptr input, blob->NewInputStream(fs)); + ASSERT_OK_AND_ASSIGN(auto slice, blob->NewInputStream(fs)); + if (cached) { + slice = std::make_unique(std::move(slice), nullptr); + } + std::shared_ptr input = std::move(slice); if (prefix != 5) { ASSERT_OK_AND_ASSIGN(input, OffsetInputStream::Create(input, pack.size(), 5 - prefix)); } diff --git a/test/inte/blob_table_inte_test.cpp b/test/inte/blob_table_inte_test.cpp index b8d24d6be..ed83b9df5 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -3750,6 +3750,40 @@ TEST_P(BlobTableInteTest, TestBlobDescriptorField) { ASSERT_TRUE(read_struct->GetFieldByName("b1")->Equals(desc_array->GetFieldByName("b1"))); } +TEST_P(BlobTableInteTest, RoundTripsInlineVideoFrameDescriptor) { + if (GetParam() == "mosaic") { + GTEST_SKIP() << "Mosaic does not support inline BLOB descriptor fields"; + } + const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + BlobUtils::ToArrowField("ref", true)}; + CreateTable(fields, {}, + {{Options::FILE_FORMAT, GetParam()}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {Options::BLOB_DESCRIPTOR_FIELD, "ref"}}); + const auto path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-frame-descriptor-v1.hex")); + auto ids = arrow::ipc::internal::json::ArrayFromJSON(arrow::int32(), "[1]").ValueOrDie(); + auto write = [&](const std::string& descriptor) { + auto refs = MakeBlobUpdateArray(fields[1], {descriptor}); + auto rows = arrow::StructArray::Make({ids, refs->field(0)}, fields).ValueOrDie(); + return WriteArray(path, {}, {"id", "ref"}, {rows}); + }; + ASSERT_NOK_WITH_MSG(write(bytes.substr(0, bytes.size() - 1)), + "invalid video frame descriptor length"); + ASSERT_OK_AND_ASSIGN(auto messages, write(bytes)); + ASSERT_OK(Commit(path, messages)); + ASSERT_OK_AND_ASSIGN(auto result, ScanAndReadResult(path, {"ref"})); + ASSERT_EQ(result->length(), 1); + auto rows = checked_pointer_cast(result->chunk(0)); + auto refs = checked_pointer_cast(rows->GetFieldByName("ref")); + const auto stored = refs->GetView(0); + ASSERT_EQ(stored, bytes); + ASSERT_OK_AND_ASSIGN(auto frame, Blob::FromDescriptor(stored.data(), stored.size())); + ASSERT_TRUE(frame->IsVideoFrame()); + ASSERT_EQ(frame->FrameIndex(), 42); +} + TEST_P(BlobTableInteTest, TestBlobDescriptorFieldPartialInline) { if (GetParam() == "mosaic") { return; From 1c19c1260cd73e85b781c53ad8989b87041bb2dc Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 05:58:24 -0800 Subject: [PATCH 15/19] fix(blob): reject ambiguous four-index video packs --- .../format/blob/video_file_batch_reader.cpp | 140 ++++++++++-------- .../blob/video_file_batch_reader_test.cpp | 93 +++++++----- 2 files changed, 140 insertions(+), 93 deletions(-) diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index d808a70f5..23434ce49 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -42,10 +42,10 @@ namespace paimon::blob { namespace { -// Encoded video payloads, six delta varint indexes, then the footer. -// The footer stores six little endian int32 index lengths followed by the magic and version. -constexpr int64_t kFooterSize = 29; -constexpr int64_t kLegacyFooterSize = 25; +// All v1 footers end with little-endian int32 index lengths, int32 magic and int8 version. +constexpr int64_t FooterSize(size_t index_count) { + return (index_count + 1) * sizeof(int32_t) + sizeof(int8_t); +} constexpr int32_t kMagic = 0x4F454449; constexpr int8_t kVersion = 1; constexpr uint64_t kMaxIndexMemoryBytes = 64 * 1024 * 1024; @@ -71,15 +71,16 @@ Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) return Status::OK(); } -Result PlanIndexStart(const IndexLengths& lengths, int64_t footer_start, int64_t tail_end, - uint64_t video_entry_size, uint64_t run_entry_size) { - if (footer_start < 0) { +Result PlanIndexStart(const IndexLengths& lengths, size_t index_count, int64_t file_size, + uint64_t video_entry_size = 0, uint64_t run_entry_size = 0) { + int64_t start = file_size - FooterSize(index_count); + if (start < 0) { return Status::Invalid("video file is smaller than its footer"); } - int64_t start = footer_start; uint64_t decoded_bytes = 0; uint64_t peak = 0; - for (int32_t length : lengths) { + for (size_t i = lengths.size() - index_count; i < lengths.size(); ++i) { + const int32_t length = lengths[i]; if (length < 0 || length > start) { return Status::Invalid("video indexes exceed the file size"); } @@ -90,10 +91,12 @@ Result PlanIndexStart(const IndexLengths& lengths, int64_t footer_start decoded_bytes += index_bytes; } // Each materialized group has equal entry counts, bounded by its shortest index. - const uint64_t videos = std::min({lengths[0], lengths[1], lengths[2]}); - const uint64_t runs = std::min({lengths[3], lengths[4], lengths[5]}); - peak = std::max(peak, decoded_bytes + videos * video_entry_size + runs * run_entry_size); - if (peak + (tail_end - start) > kMaxIndexMemoryBytes) { + if (index_count == lengths.size()) { + const uint64_t videos = std::min({lengths[0], lengths[1], lengths[2]}); + const uint64_t runs = std::min({lengths[3], lengths[4], lengths[5]}); + peak = std::max(peak, decoded_bytes + videos * video_entry_size + runs * run_entry_size); + } + if (peak + (file_size - FooterSize(4) - start) > kMaxIndexMemoryBytes) { return Status::CapacityError("video indexes exceed the memory budget of ", kMaxIndexMemoryBytes, " bytes"); } @@ -113,22 +116,29 @@ bool IsValidFrameRun(int64_t length, int64_t reference, int64_t first, size_t vi (reference >= 0 && static_cast(reference) < video_count && first >= 0)); } -Status ValidateLegacyLayout(std::string_view tail, const IndexLengths& lengths, +Status ValidateLegacyLayout(std::string_view tail, const IndexLengths& lengths, size_t index_count, int64_t index_start) { - // Before apache/paimon#10905, the payload area contained videos followed by keyframe - // indexes. The footer had two physical indexes and three run indexes. - PAIMON_ASSIGN_OR_RAISE(std::vector videos, DecodeIndex(&tail, lengths[1])); - PAIMON_ASSIGN_OR_RAISE(std::vector keyframes, DecodeIndex(&tail, lengths[2])); - if (videos.size() != keyframes.size()) { - return Status::Invalid("legacy video and keyframe indexes have different counts"); - } + PAIMON_ASSIGN_OR_RAISE(std::vector videos, + DecodeIndex(&tail, lengths[lengths.size() - index_count])); int64_t remaining = index_start; - for (size_t i = 0; i < videos.size(); ++i) { - if (videos[i] <= 0 || videos[i] > remaining || keyframes[i] < 0 || - keyframes[i] > remaining - videos[i]) { - return Status::Invalid("invalid legacy video or keyframe length"); + for (int64_t length : videos) { + if (length <= 0 || length > remaining) { + return Status::Invalid("invalid legacy video length"); + } + remaining -= length; + } + // The five-index layout added one keyframe index length per physical video. + if (index_count == 5) { + PAIMON_ASSIGN_OR_RAISE(std::vector keyframes, DecodeIndex(&tail, lengths[2])); + if (videos.size() != keyframes.size()) { + return Status::Invalid("legacy video and keyframe indexes have different counts"); + } + for (int64_t length : keyframes) { + if (length < 0 || length > remaining) { + return Status::Invalid("invalid legacy keyframe length"); + } + remaining -= length; } - remaining -= videos[i] + keyframes[i]; } if (remaining != 0) { return Status::Invalid("legacy payload length does not match its indexes"); @@ -196,12 +206,12 @@ Result> VideoFileBatchReader::Create( Status VideoFileBatchReader::ReadIndexes(InputStream* input) { PAIMON_ASSIGN_OR_RAISE(int64_t size, input->Length()); - if (size < kLegacyFooterSize) { + if (size < FooterSize(4)) { return Status::Invalid( "corrupt or unsupported .video layout. File is smaller than its footer"); } - // Both layouts end with the same five lengths, magic and version. The index data - // for those lengths starts four bytes earlier in the six-index interpretation. + // Read the longest footer. Shorter v1 layouts use a suffix of these length fields. + constexpr int64_t kFooterSize = FooterSize(6); char footer[kFooterSize] = {}; const int64_t footer_size = std::min(size, kFooterSize); PAIMON_RETURN_NOT_OK( @@ -218,26 +228,24 @@ Status VideoFileBatchReader::ReadIndexes(InputStream* input) { return Status::Invalid("corrupt or unsupported .video footer"); } - const int64_t tail_end = size - kLegacyFooterSize; - IndexLengths legacy_lengths = index_lengths; - legacy_lengths[0] = 0; - const Result legacy = PlanIndexStart(legacy_lengths, tail_end, tail_end, 0, 0); - // Every six-index candidate contains all five legacy lengths and needs at least - // as much memory. If the legacy range cannot be probed, neither layout can be read. - if (!legacy.ok()) { - return legacy.status().IsInvalid() + const Result four_start = PlanIndexStart(index_lengths, 4, size); + // Both longer candidates contain these four lengths and need at least as much memory. + if (!four_start.ok()) { + return four_start.status().IsInvalid() ? Status::Invalid("corrupt or unsupported .video layout. ", - legacy.status().message()) - : legacy.status(); + four_start.status().message()) + : four_start.status(); } - const Result modern = PlanIndexStart(index_lengths, size - kFooterSize, tail_end, - sizeof(VideoRange), sizeof(FrameRun)); + const Result five_start = PlanIndexStart(index_lengths, 5, size); + const Result six_start = + PlanIndexStart(index_lengths, 6, size, sizeof(VideoRange), sizeof(FrameRun)); - // The six-index range starts first and its budget covers both probes. If it does - // not fit, read only the five-index range to check whether the file needs reimport. - const int64_t start = modern.ok() ? modern.value() : legacy.value(); + // Read the union of all ranges that fit. The longest viable layout starts earliest. + const int64_t legacy_start = five_start.ok() ? five_start.value() : four_start.value(); + const int64_t start = six_start.ok() ? six_start.value() : legacy_start; + const int64_t tail_end = size - FooterSize(4); Bytes buffer(tail_end - start, pool_.get()); - constexpr int64_t kFooterOverlap = kFooterSize - kLegacyFooterSize; + constexpr int64_t kFooterOverlap = kFooterSize - FooterSize(4); const int64_t overlap = std::min(buffer.size(), kFooterOverlap); const int64_t read_size = buffer.size() - overlap; PAIMON_RETURN_NOT_OK(ReadAtFully(input, start, buffer.data(), read_size)); @@ -246,27 +254,39 @@ Status VideoFileBatchReader::ReadIndexes(InputStream* input) { } const std::string_view tail(buffer.data(), buffer.size()); - const Status legacy_status = - ValidateLegacyLayout(tail.substr(legacy.value() - start), legacy_lengths, legacy.value()); - Status modern_status = modern.status(); - if (modern.ok()) { - modern_status = ReadSixIndexLayout(tail, index_lengths, modern.value()); - } - if (legacy_status.ok()) { - if (modern_status.ok()) { + auto probe_legacy = [&](const Result& plan, size_t index_count) -> Status { + PAIMON_ASSIGN_OR_RAISE(int64_t offset, plan); + return ValidateLegacyLayout(tail.substr(offset - start), index_lengths, index_count, + offset); + }; + const Status four_status = probe_legacy(four_start, 4); + const Status five_status = probe_legacy(five_start, 5); + const Status six_status = six_start.ok() + ? ReadSixIndexLayout(tail, index_lengths, six_start.value()) + : six_start.status(); + if (four_status.ok() || five_status.ok()) { + const char* legacy_layout = four_status.ok() ? "four-index" : "five-index"; + if (six_status.ok()) { + return Status::Invalid("ambiguous v1 .video layout. Both ", legacy_layout, + " and six-index validation passed. Reimport the file"); + } + if (four_status.ok() && five_status.ok()) { return Status::Invalid( - "ambiguous v1 .video layout. Both five-index and six-index " + "ambiguous v1 .video layout. Both four-index and five-index " "validation passed. Reimport the file"); } - return Status::Invalid("Legacy five-index .video files require reimport"); + return Status::Invalid("Legacy ", legacy_layout, " .video files require reimport"); + } + if (!four_status.IsInvalid()) { + return four_status; } - if (!legacy_status.IsInvalid()) { - return legacy_status; + if (!five_status.IsInvalid()) { + return five_status; } - if (modern_status.IsInvalid()) { - return Status::Invalid("corrupt or unsupported .video layout. ", modern_status.message()); + if (six_status.IsInvalid()) { + return Status::Invalid("corrupt or unsupported .video layout. ", six_status.message()); } - return modern_status; + return six_status; } Status VideoFileBatchReader::ReadSixIndexLayout(std::string_view tail, diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index ea6adab32..e243e0081 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -299,6 +299,27 @@ TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { ASSERT_NOK_WITH_MSG(result, uri); } +TEST(VideoFileBatchReaderTest, RejectsFourIndexPackThatAlsoMatchesSixIndexes) { + // Two 25-byte videos, eight one-row runs. As six indexes the same pack describes + // 58 rows starting at frame 0 instead of eight rows starting at frame 1. + std::string bytes(50, '\0'); + bytes[38] = 38; + bytes[44] = 2; + AppendVideoIndexes( + &bytes, + {{25, 25}, {1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1}, {1, 1, 1, 1, 2, 2, 2, 2}}); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(64)); + auto open = [&] { return builder->Build(std::make_shared(0, bytes)); }; + auto ambiguous = open(); + ASSERT_NOK_WITH_MSG(ambiguous, "ambiguous v1 .video layout"); + ASSERT_NOK_WITH_MSG(ambiguous, "four-index and six-index"); + ASSERT_NOK_WITH_MSG(ambiguous, kVideoUri); + + bytes[38] = 0; // Invalidates the six-index lengths but is payload data in the old layout. + ASSERT_NOK_WITH_MSG(open(), "Legacy four-index .video files require reimport"); +} + TEST(VideoFileBatchReaderTest, RejectsLegacyAndAmbiguousVideoLayouts) { // Five indexes describe two 25-byte videos, no keyframe indexes and four // one-row runs. The same bytes also encode two 22-byte videos with no moov @@ -383,43 +404,49 @@ TEST(VideoFileBatchReaderTest, ReadsJavaIndexesWithOneTailRead) { } TEST(VideoFileBatchReaderTest, RecognizesLegacyIndexesWithinFooterRead) { - for (const auto& runs : {std::vector{}, std::vector{1}}) { - // A 25-byte empty file or a 28-byte file with one null row fits in the footer read. - std::string bytes; - AppendVideoIndexes(&bytes, {{}, - {}, - runs, - std::vector(runs.size(), -1), - std::vector(runs.size(), 0)}); - auto input = std::make_shared(0, std::move(bytes)); - auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - ASSERT_NOK_WITH_MSG(result, "Legacy five-index .video files require reimport"); - ASSERT_EQ(input->reads.size(), 1u); + // Empty packs and one-NULL-row packs of either legacy layout fit in the footer read. + for (size_t index_count : {4, 5}) { + const char* expected = index_count == 4 ? "Legacy four-index" : "Legacy five-index"; + for (const auto& runs : {std::vector{}, std::vector{1}}) { + std::string bytes; + std::vector> indexes(index_count - 3); + indexes.insert(indexes.end(), {runs, std::vector(runs.size(), -1), + std::vector(runs.size(), 0)}); + AppendVideoIndexes(&bytes, indexes); + auto input = std::make_shared(0, std::move(bytes)); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, expected); + ASSERT_EQ(input->reads.size(), 1u); + } } } -TEST(VideoFileBatchReaderTest, RecognizesLegacyWhenSixIndexCandidateExceedsBudget) { +TEST(VideoFileBatchReaderTest, RecognizesLegacyWhenLongerCandidatesExceedBudget) { constexpr int64_t kVideoSize = 10 * 1024 * 1024; constexpr int64_t kPayloadSize = 4 * kVideoSize; - std::string tail; - // The last four first-frame bytes also spell a 32 MiB six-index length. - AppendVideoIndexes(&tail, {{kVideoSize, kVideoSize, kVideoSize, kVideoSize}, - {0, 0, 0, 0}, - {1, 1, 1, 1}, - {0, 1, 2, 3}, - {0, 0, 0, 1}}); - auto input = std::make_shared(kPayloadSize, tail); - auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - ASSERT_NOK_WITH_MSG(result, "Legacy five-index .video files require reimport"); - ASSERT_NOK_WITH_MSG(result, kVideoUri); - ASSERT_TRUE(result.status().IsInvalid()); - ASSERT_EQ(input->reads.size(), 2u); - ASSERT_EQ(input->reads.back().first, kPayloadSize); - - // Losing access to the real legacy indexes leaves the layout undetermined. - input = std::make_shared(kPayloadSize + 1, tail.substr(1)); - result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - ASSERT_TRUE(result.status().IsIOError()) << result.status(); + for (bool has_keyframes : {false, true}) { + std::vector> indexes{{kVideoSize, kVideoSize, kVideoSize, kVideoSize}}; + if (has_keyframes) { + indexes.push_back({0, 0, 0, 0}); + } + // The last four first-frame bytes also spell a 32 MiB index length in a longer footer. + indexes.insert(indexes.end(), {{1, 1, 1, 1}, {0, 1, 2, 3}, {0, 0, 0, 1}}); + std::string tail; + AppendVideoIndexes(&tail, indexes); + auto input = std::make_shared(kPayloadSize, tail); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + const char* expected = has_keyframes ? "Legacy five-index" : "Legacy four-index"; + ASSERT_NOK_WITH_MSG(result, expected); + ASSERT_NOK_WITH_MSG(result, kVideoUri); + ASSERT_TRUE(result.status().IsInvalid()); + ASSERT_EQ(input->reads.size(), 2u); + ASSERT_EQ(input->reads.back().first, kPayloadSize); + + // Losing access to the real legacy indexes leaves the layout undetermined. + input = std::make_shared(kPayloadSize + 1, tail.substr(1)); + result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_TRUE(result.status().IsIOError()) << result.status(); + } } TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { @@ -448,7 +475,7 @@ TEST(VideoFileBatchReaderTest, CountsSharedTailInMaterializationBudget) { auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); ASSERT_TRUE(result.status().IsCapacityError()) << result.status(); ASSERT_EQ(input->reads.size(), 2u); - ASSERT_EQ(input->reads.back().first, 4); // Only the five-index candidate fits. + ASSERT_EQ(input->reads.back().first, 4); // Both legacy probes fit in the five-index range. } TEST(VideoFileBatchReaderTest, ReadsLargeIndexWithinMemoryBudget) { From 7e5cb7a8f051be460ace292f374131b46017292f Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 19:33:13 -0800 Subject: [PATCH 16/19] fix(blob): read the moov-based video layout directly --- docs/source/user_guide/read.rst | 14 +- .../format/blob/video_file_batch_reader.cpp | 169 +++--------------- .../format/blob/video_file_batch_reader.h | 4 +- .../blob/video_file_batch_reader_test.cpp | 133 +++++--------- 4 files changed, 76 insertions(+), 244 deletions(-) diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index 9db56ace2..08acada11 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -334,14 +334,12 @@ Implementation Guidance Reading Video Columns --------------------- -Paimon C++ reads scalar BLOB columns from v1 ``.video`` files that match only -the six-index layout (29-byte footer). It rejects files whose estimated peak -index memory exceeds 64 MiB. - -Reimport four-index (21-byte footer), five-index (25-byte footer), or ambiguous v1 -files with a Java reader for the source layout and a current Java writer. -Regenerate frame descriptors stored in downstream tables from the new files, -then verify row counts, frame ordinals and row alignment in C++ before switching. +Paimon C++ reads scalar BLOB columns using the same ``moov``-based v1 layout +as Java (29-byte footer). The estimated peak memory for indexes is limited to 64 MiB. + +Reimport older ``.video`` files with a Java reader for the original layout and a +current Java writer. Regenerate stored frame descriptors and verify row counts, +frame ordinals and row alignment before switching to the new files. Non-null rows return frame descriptors even with ``blob-as-descriptor=false``. Open them with ``Blob::FromDescriptor()``. Use ``FrameIndex()`` for the zero-based diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 23434ce49..6c1564912 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -42,10 +42,8 @@ namespace paimon::blob { namespace { -// All v1 footers end with little-endian int32 index lengths, int32 magic and int8 version. -constexpr int64_t FooterSize(size_t index_count) { - return (index_count + 1) * sizeof(int32_t) + sizeof(int8_t); -} +// Six little-endian index lengths, magic and version. +constexpr int64_t kFooterSize = 7 * sizeof(int32_t) + sizeof(int8_t); constexpr int32_t kMagic = 0x4F454449; constexpr int8_t kVersion = 1; constexpr uint64_t kMaxIndexMemoryBytes = 64 * 1024 * 1024; @@ -57,7 +55,6 @@ using IndexLengths = std::array; Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) { for (int64_t read = 0; read < size;) { const Result n = input->Read(data + read, size - read, offset + read); - // An I/O failure leaves the layout undetermined. if (!n.ok()) { return n.status().IsInvalid() ? Status::IOError("failed to read video file. ", n.status().ToString()) @@ -71,16 +68,12 @@ Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) return Status::OK(); } -Result PlanIndexStart(const IndexLengths& lengths, size_t index_count, int64_t file_size, - uint64_t video_entry_size = 0, uint64_t run_entry_size = 0) { - int64_t start = file_size - FooterSize(index_count); - if (start < 0) { - return Status::Invalid("video file is smaller than its footer"); - } +Result ComputeIndexStart(const IndexLengths& lengths, int64_t footer_start, + uint64_t video_entry_size, uint64_t run_entry_size) { + int64_t start = footer_start; uint64_t decoded_bytes = 0; uint64_t peak = 0; - for (size_t i = lengths.size() - index_count; i < lengths.size(); ++i) { - const int32_t length = lengths[i]; + for (int32_t length : lengths) { if (length < 0 || length > start) { return Status::Invalid("video indexes exceed the file size"); } @@ -91,24 +84,16 @@ Result PlanIndexStart(const IndexLengths& lengths, size_t index_count, decoded_bytes += index_bytes; } // Each materialized group has equal entry counts, bounded by its shortest index. - if (index_count == lengths.size()) { - const uint64_t videos = std::min({lengths[0], lengths[1], lengths[2]}); - const uint64_t runs = std::min({lengths[3], lengths[4], lengths[5]}); - peak = std::max(peak, decoded_bytes + videos * video_entry_size + runs * run_entry_size); - } - if (peak + (file_size - FooterSize(4) - start) > kMaxIndexMemoryBytes) { + const uint64_t videos = std::min({lengths[0], lengths[1], lengths[2]}); + const uint64_t runs = std::min({lengths[3], lengths[4], lengths[5]}); + peak = std::max(peak, decoded_bytes + videos * video_entry_size + runs * run_entry_size); + if (peak + (footer_start - start) > kMaxIndexMemoryBytes) { return Status::CapacityError("video indexes exceed the memory budget of ", kMaxIndexMemoryBytes, " bytes"); } return start; } -Result> DecodeIndex(std::string_view* tail, int32_t length) { - const char* data = tail->data(); - tail->remove_prefix(length); - return DeltaVarintCompressor::Decompress(data, length); -} - bool IsValidFrameRun(int64_t length, int64_t reference, int64_t first, size_t video_count, int64_t rows) { return length > 0 && length <= std::numeric_limits::max() - rows && @@ -116,50 +101,6 @@ bool IsValidFrameRun(int64_t length, int64_t reference, int64_t first, size_t vi (reference >= 0 && static_cast(reference) < video_count && first >= 0)); } -Status ValidateLegacyLayout(std::string_view tail, const IndexLengths& lengths, size_t index_count, - int64_t index_start) { - PAIMON_ASSIGN_OR_RAISE(std::vector videos, - DecodeIndex(&tail, lengths[lengths.size() - index_count])); - int64_t remaining = index_start; - for (int64_t length : videos) { - if (length <= 0 || length > remaining) { - return Status::Invalid("invalid legacy video length"); - } - remaining -= length; - } - // The five-index layout added one keyframe index length per physical video. - if (index_count == 5) { - PAIMON_ASSIGN_OR_RAISE(std::vector keyframes, DecodeIndex(&tail, lengths[2])); - if (videos.size() != keyframes.size()) { - return Status::Invalid("legacy video and keyframe indexes have different counts"); - } - for (int64_t length : keyframes) { - if (length < 0 || length > remaining) { - return Status::Invalid("invalid legacy keyframe length"); - } - remaining -= length; - } - } - if (remaining != 0) { - return Status::Invalid("legacy payload length does not match its indexes"); - } - - PAIMON_ASSIGN_OR_RAISE(std::vector runs, DecodeIndex(&tail, lengths[3])); - PAIMON_ASSIGN_OR_RAISE(std::vector references, DecodeIndex(&tail, lengths[4])); - PAIMON_ASSIGN_OR_RAISE(std::vector first_frames, DecodeIndex(&tail, lengths[5])); - if (runs.size() != references.size() || runs.size() != first_frames.size()) { - return Status::Invalid("legacy video run indexes have different counts"); - } - int64_t rows = 0; - for (size_t i = 0; i < runs.size(); ++i) { - if (!IsValidFrameRun(runs[i], references[i], first_frames[i], videos.size(), rows)) { - return Status::Invalid("invalid legacy video frame run"); - } - rows += runs[i]; - } - return Status::OK(); -} - } // namespace VideoFileBatchReader::VideoFileBatchReader(std::string uri, int32_t batch_size, @@ -184,7 +125,7 @@ Result> VideoFileBatchReader::Create( PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); auto reader = std::unique_ptr(new VideoFileBatchReader( std::move(uri), batch_size, pool, emit_placeholder_sentinel, blob_context)); - const Status status = reader->ReadIndexes(input.get()); + const Status status = reader->ReadVideoIndexes(input.get()); if (!status.ok()) { return reader->uri_.empty() ? status : status.WithMessage(status.message(), " (", reader->uri_, ")"); @@ -204,18 +145,14 @@ Result> VideoFileBatchReader::Create( return reader; } -Status VideoFileBatchReader::ReadIndexes(InputStream* input) { +Status VideoFileBatchReader::ReadVideoIndexes(InputStream* input) { PAIMON_ASSIGN_OR_RAISE(int64_t size, input->Length()); - if (size < FooterSize(4)) { - return Status::Invalid( - "corrupt or unsupported .video layout. File is smaller than its footer"); + if (size < kFooterSize) { + return Status::Invalid("video file is smaller than its footer"); } - // Read the longest footer. Shorter v1 layouts use a suffix of these length fields. - constexpr int64_t kFooterSize = FooterSize(6); - char footer[kFooterSize] = {}; - const int64_t footer_size = std::min(size, kFooterSize); - PAIMON_RETURN_NOT_OK( - ReadAtFully(input, size - footer_size, footer + kFooterSize - footer_size, footer_size)); + const int64_t footer_start = size - kFooterSize; + char footer[kFooterSize]; + PAIMON_RETURN_NOT_OK(ReadAtFully(input, footer_start, footer, kFooterSize)); DataInputStream footer_input(std::make_shared(footer, sizeof(footer))); footer_input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); IndexLengths index_lengths; @@ -228,73 +165,23 @@ Status VideoFileBatchReader::ReadIndexes(InputStream* input) { return Status::Invalid("corrupt or unsupported .video footer"); } - const Result four_start = PlanIndexStart(index_lengths, 4, size); - // Both longer candidates contain these four lengths and need at least as much memory. - if (!four_start.ok()) { - return four_start.status().IsInvalid() - ? Status::Invalid("corrupt or unsupported .video layout. ", - four_start.status().message()) - : four_start.status(); - } - const Result five_start = PlanIndexStart(index_lengths, 5, size); - const Result six_start = - PlanIndexStart(index_lengths, 6, size, sizeof(VideoRange), sizeof(FrameRun)); - - // Read the union of all ranges that fit. The longest viable layout starts earliest. - const int64_t legacy_start = five_start.ok() ? five_start.value() : four_start.value(); - const int64_t start = six_start.ok() ? six_start.value() : legacy_start; - const int64_t tail_end = size - FooterSize(4); - Bytes buffer(tail_end - start, pool_.get()); - constexpr int64_t kFooterOverlap = kFooterSize - FooterSize(4); - const int64_t overlap = std::min(buffer.size(), kFooterOverlap); - const int64_t read_size = buffer.size() - overlap; - PAIMON_RETURN_NOT_OK(ReadAtFully(input, start, buffer.data(), read_size)); - if (overlap > 0) { - std::copy_n(footer + kFooterOverlap - overlap, overlap, buffer.data() + read_size); - } - const std::string_view tail(buffer.data(), buffer.size()); - - auto probe_legacy = [&](const Result& plan, size_t index_count) -> Status { - PAIMON_ASSIGN_OR_RAISE(int64_t offset, plan); - return ValidateLegacyLayout(tail.substr(offset - start), index_lengths, index_count, - offset); - }; - const Status four_status = probe_legacy(four_start, 4); - const Status five_status = probe_legacy(five_start, 5); - const Status six_status = six_start.ok() - ? ReadSixIndexLayout(tail, index_lengths, six_start.value()) - : six_start.status(); - if (four_status.ok() || five_status.ok()) { - const char* legacy_layout = four_status.ok() ? "four-index" : "five-index"; - if (six_status.ok()) { - return Status::Invalid("ambiguous v1 .video layout. Both ", legacy_layout, - " and six-index validation passed. Reimport the file"); - } - if (four_status.ok() && five_status.ok()) { - return Status::Invalid( - "ambiguous v1 .video layout. Both four-index and five-index " - "validation passed. Reimport the file"); - } - return Status::Invalid("Legacy ", legacy_layout, " .video files require reimport"); - } - if (!four_status.IsInvalid()) { - return four_status; - } - if (!five_status.IsInvalid()) { - return five_status; - } - if (six_status.IsInvalid()) { - return Status::Invalid("corrupt or unsupported .video layout. ", six_status.message()); - } - return six_status; + PAIMON_ASSIGN_OR_RAISE( + int64_t index_start, + ComputeIndexStart(index_lengths, footer_start, sizeof(VideoRange), sizeof(FrameRun))); + Bytes buffer(footer_start - index_start, pool_.get()); + PAIMON_RETURN_NOT_OK(ReadAtFully(input, index_start, buffer.data(), buffer.size())); + return DecodeVideoIndexes(std::string_view(buffer.data(), buffer.size()), index_lengths, + index_start); } -Status VideoFileBatchReader::ReadSixIndexLayout(std::string_view tail, +Status VideoFileBatchReader::DecodeVideoIndexes(std::string_view data, const IndexLengths& index_lengths, int64_t index_start) { std::array, 6> indexes; for (size_t i = 0; i < indexes.size(); ++i) { - PAIMON_ASSIGN_OR_RAISE(indexes[i], DecodeIndex(&tail, index_lengths[i])); + PAIMON_ASSIGN_OR_RAISE(indexes[i], + DeltaVarintCompressor::Decompress(data.data(), index_lengths[i])); + data.remove_prefix(index_lengths[i]); } const auto& video_lengths = indexes[0]; diff --git a/src/paimon/format/blob/video_file_batch_reader.h b/src/paimon/format/blob/video_file_batch_reader.h index 76e60b8cf..c2efa4823 100644 --- a/src/paimon/format/blob/video_file_batch_reader.h +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -80,8 +80,8 @@ class VideoFileBatchReader : public FileBatchReader { bool emit_placeholder_sentinel, const std::shared_ptr& blob_context); - Status ReadIndexes(InputStream* input); - Status ReadSixIndexLayout(std::string_view tail, const std::array& index_lengths, + Status ReadVideoIndexes(InputStream* input); + Status DecodeVideoIndexes(std::string_view data, const std::array& index_lengths, int64_t index_start); std::string uri_; diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index e243e0081..6d1f4044b 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -299,53 +299,30 @@ TEST(VideoFileBatchReaderTest, RejectsInvalidFooter) { ASSERT_NOK_WITH_MSG(result, uri); } -TEST(VideoFileBatchReaderTest, RejectsFourIndexPackThatAlsoMatchesSixIndexes) { - // Two 25-byte videos, eight one-row runs. As six indexes the same pack describes - // 58 rows starting at frame 0 instead of eight rows starting at frame 1. - std::string bytes(50, '\0'); - bytes[38] = 38; - bytes[44] = 2; - AppendVideoIndexes( - &bytes, - {{25, 25}, {1, 1, 1, 1, 1, 1, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1}, {1, 1, 1, 1, 2, 2, 2, 2}}); +TEST(VideoFileBatchReaderTest, ReadsMoovLayoutWhenBytesAlsoFitLegacyLayout) { + // The current writer's layout describes 100 rows. A legacy keyframe footer + // interpretation of the same bytes would describe four rows. + std::string bytes(44, '\0'); + AppendVideoIndexes(&bytes, + {{22, 22}, {0, 0}, {0, 0}, {25, 25, 25, 25}, {1, 1, 1, 1}, {1, 1, 1, 1}}); ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); - ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(64)); - auto open = [&] { return builder->Build(std::make_shared(0, bytes)); }; - auto ambiguous = open(); - ASSERT_NOK_WITH_MSG(ambiguous, "ambiguous v1 .video layout"); - ASSERT_NOK_WITH_MSG(ambiguous, "four-index and six-index"); - ASSERT_NOK_WITH_MSG(ambiguous, kVideoUri); - - bytes[38] = 0; // Invalidates the six-index lengths but is payload data in the old layout. - ASSERT_NOK_WITH_MSG(open(), "Legacy four-index .video files require reimport"); -} + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(std::make_shared(0, bytes))); + ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); + ASSERT_EQ(rows, 100); -TEST(VideoFileBatchReaderTest, RejectsLegacyAndAmbiguousVideoLayouts) { - // Five indexes describe two 25-byte videos, no keyframe indexes and four - // one-row runs. The same bytes also encode two 22-byte videos with no moov - // ranges and four 25-row runs when read using the six-index footer. - std::string bytes(50, '\0'); - bytes[44] = 44; // Six-index video lengths: 22, 22. - constexpr char indexes[] = - "\x32\x00" // Legacy video lengths: 25, 25. - "\x00\x00" // Legacy keyframe lengths: 0, 0. - "\x02\x00\x00\x00" // Legacy run lengths: 1, 1, 1, 1. - "\x00\x02\x01\x02" // Legacy references: 0, 1, 0, 1. - "\x02\x00\x00\x00"; // Legacy first frames: 1, 1, 1, 1. - bytes.append(indexes, sizeof(indexes) - 1); - AppendVideoFooter(&bytes, {2, 2, 4, 4, 4}); - auto input = std::make_shared(0, bytes); - auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - ASSERT_NOK_WITH_MSG(result, "ambiguous v1 .video layout"); - ASSERT_NOK_WITH_MSG(result, kVideoUri); - - // This byte belongs to the five-index payload and the six-index video lengths. - // Zero video lengths invalidate only the six-index interpretation. - bytes[44] = 0; - input = std::make_shared(0, bytes); - result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - ASSERT_NOK_WITH_MSG(result, "Legacy five-index .video files require reimport"); - ASSERT_NOK_WITH_MSG(result, kVideoUri); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, RoaringBitmap32::From({99}))); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + auto selected = std::static_pointer_cast( + arrow::ImportArray(batch.first.get(), batch.second.get()).ValueOrDie()); + auto frames = std::static_pointer_cast(selected->field(0)); + ASSERT_EQ(frames->length(), 1); + const auto descriptor = frames->GetView(0); + ASSERT_OK_AND_ASSIGN(auto frame, Blob::FromDescriptor(descriptor.data(), descriptor.size())); + ASSERT_EQ(frame->FrameIndex(), 25); } TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { @@ -403,50 +380,22 @@ TEST(VideoFileBatchReaderTest, ReadsJavaIndexesWithOneTailRead) { ASSERT_EQ(input->reads, expected); } -TEST(VideoFileBatchReaderTest, RecognizesLegacyIndexesWithinFooterRead) { - // Empty packs and one-NULL-row packs of either legacy layout fit in the footer read. - for (size_t index_count : {4, 5}) { - const char* expected = index_count == 4 ? "Legacy four-index" : "Legacy five-index"; - for (const auto& runs : {std::vector{}, std::vector{1}}) { - std::string bytes; - std::vector> indexes(index_count - 3); - indexes.insert(indexes.end(), {runs, std::vector(runs.size(), -1), - std::vector(runs.size(), 0)}); - AppendVideoIndexes(&bytes, indexes); - auto input = std::make_shared(0, std::move(bytes)); - auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - ASSERT_NOK_WITH_MSG(result, expected); - ASSERT_EQ(input->reads.size(), 1u); - } - } -} - -TEST(VideoFileBatchReaderTest, RecognizesLegacyWhenLongerCandidatesExceedBudget) { - constexpr int64_t kVideoSize = 10 * 1024 * 1024; - constexpr int64_t kPayloadSize = 4 * kVideoSize; - for (bool has_keyframes : {false, true}) { - std::vector> indexes{{kVideoSize, kVideoSize, kVideoSize, kVideoSize}}; - if (has_keyframes) { - indexes.push_back({0, 0, 0, 0}); - } - // The last four first-frame bytes also spell a 32 MiB index length in a longer footer. - indexes.insert(indexes.end(), {{1, 1, 1, 1}, {0, 1, 2, 3}, {0, 0, 0, 1}}); - std::string tail; - AppendVideoIndexes(&tail, indexes); - auto input = std::make_shared(kPayloadSize, tail); - auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - const char* expected = has_keyframes ? "Legacy five-index" : "Legacy four-index"; - ASSERT_NOK_WITH_MSG(result, expected); - ASSERT_NOK_WITH_MSG(result, kVideoUri); - ASSERT_TRUE(result.status().IsInvalid()); - ASSERT_EQ(input->reads.size(), 2u); - ASSERT_EQ(input->reads.back().first, kPayloadSize); - - // Losing access to the real legacy indexes leaves the layout undetermined. - input = std::make_shared(kPayloadSize + 1, tail.substr(1)); - result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - ASSERT_TRUE(result.status().IsIOError()) << result.status(); - } +TEST(VideoFileBatchReaderTest, ReadsEmptyVideoFile) { + std::string bytes; + AppendVideoFooter(&bytes, {0, 0, 0, 0, 0, 0}); + auto input = std::make_shared(0, bytes); + ASSERT_OK_AND_ASSIGN(auto reader, + VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); + ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); + ASSERT_EQ(rows, 0); + ASSERT_EQ(input->reads.size(), 1u); + + bytes.pop_back(); + auto truncated = std::make_shared(0, bytes); + ASSERT_NOK_WITH_MSG( + VideoFileBatchReader::Create(truncated, 2, GetDefaultPool(), false, nullptr), + "smaller than its footer"); + ASSERT_TRUE(truncated->reads.empty()); } TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { @@ -464,7 +413,7 @@ TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { } } -TEST(VideoFileBatchReaderTest, CountsSharedTailInMaterializationBudget) { +TEST(VideoFileBatchReaderTest, CountsEncodedIndexesInMemoryBudget) { // The decoded indexes and frame runs alone fit just below 64 MiB. constexpr uint32_t kRuns = 64 * 1024 * 1024 / 48; std::string bytes(3 * kRuns, '\0'); @@ -474,8 +423,7 @@ TEST(VideoFileBatchReaderTest, CountsSharedTailInMaterializationBudget) { auto input = std::make_shared(0, std::move(bytes)); auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); ASSERT_TRUE(result.status().IsCapacityError()) << result.status(); - ASSERT_EQ(input->reads.size(), 2u); - ASSERT_EQ(input->reads.back().first, 4); // Both legacy probes fit in the five-index range. + ASSERT_EQ(input->reads.size(), 1u); } TEST(VideoFileBatchReaderTest, ReadsLargeIndexWithinMemoryBudget) { @@ -502,7 +450,6 @@ TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs->Open(path)); ASSERT_OK_AND_ASSIGN(std::string uri, input->GetUri()); auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); - ASSERT_NOK_WITH_MSG(result, "corrupt or unsupported .video layout"); ASSERT_NOK_WITH_MSG(result, "invalid moov range"); ASSERT_NOK_WITH_MSG(result, uri); } From 37f9deb72653acc861464ead3e244ecc35e9d578 Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 19:33:13 -0800 Subject: [PATCH 17/19] style(blob): satisfy clang-tidy in varint decoding --- src/paimon/common/utils/delta_varint_compressor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/paimon/common/utils/delta_varint_compressor.cpp b/src/paimon/common/utils/delta_varint_compressor.cpp index cbb8d78d4..e9f5f634c 100644 --- a/src/paimon/common/utils/delta_varint_compressor.cpp +++ b/src/paimon/common/utils/delta_varint_compressor.cpp @@ -100,7 +100,7 @@ Result DeltaVarintCompressor::DecodeVarint(const char* data, size_t siz if (*pos >= size) { return Status::Invalid("Unexpected end of input"); } - const uint8_t byte = static_cast(data[(*pos)++]); + const auto byte = static_cast(data[(*pos)++]); if (shift == 63 && byte > 1) { return Status::Invalid("Varint overflow"); } From 35d2593320b744c390b77de571dad0640e17609a Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Tue, 1 Dec 2026 20:03:07 -0800 Subject: [PATCH 18/19] fix(blob): handle video-only deltas and release video reader resources --- src/paimon/common/data/blob_utils.cpp | 6 +- src/paimon/common/data/blob_utils.h | 1 + .../common/io/buffered_input_stream.cpp | 2 +- .../common/io/buffered_input_stream_test.cpp | 6 +- .../operation/data_evolution_split_read.cpp | 17 ++- .../format/blob/video_file_batch_reader.cpp | 54 +++++--- .../format/blob/video_file_batch_reader.h | 9 +- .../blob/video_file_batch_reader_test.cpp | 59 ++++++++- test/inte/blob_table_inte_test.cpp | 118 ++++++++++++------ 9 files changed, 208 insertions(+), 64 deletions(-) diff --git a/src/paimon/common/data/blob_utils.cpp b/src/paimon/common/data/blob_utils.cpp index 7acc17693..5661869cf 100644 --- a/src/paimon/common/data/blob_utils.cpp +++ b/src/paimon/common/data/blob_utils.cpp @@ -208,8 +208,12 @@ std::vector BlobUtils::GetVideoFrameFields( return names; } +bool BlobUtils::IsVideoFile(const std::string& file_name) { + return StringUtils::EndsWith(file_name, ".video"); +} + bool BlobUtils::IsBlobFile(const std::string& file_name) { - return StringUtils::EndsWith(file_name, ".blob") || StringUtils::EndsWith(file_name, ".video"); + return StringUtils::EndsWith(file_name, ".blob") || IsVideoFile(file_name); } std::shared_ptr BlobUtils::ToArrowField( diff --git a/src/paimon/common/data/blob_utils.h b/src/paimon/common/data/blob_utils.h index 89170f363..1b57af0d1 100644 --- a/src/paimon/common/data/blob_utils.h +++ b/src/paimon/common/data/blob_utils.h @@ -98,6 +98,7 @@ class PAIMON_EXPORT BlobUtils { static std::vector GetVideoFrameFields( const std::map& options); + static bool IsVideoFile(const std::string& file_name); static bool IsBlobFile(const std::string& file_name); static Result IsBlobReference(std::string_view bytes); diff --git a/src/paimon/common/io/buffered_input_stream.cpp b/src/paimon/common/io/buffered_input_stream.cpp index e02620c0b..3cef58ea0 100644 --- a/src/paimon/common/io/buffered_input_stream.cpp +++ b/src/paimon/common/io/buffered_input_stream.cpp @@ -93,7 +93,7 @@ Result BufferedInputStream::Read(char* buffer, int64_t size) { } Result BufferedInputStream::Read(char* buffer, int64_t size, int64_t offset) { - return Status::Invalid("BufferedInputStream does not support Read from offset"); + return in_->Read(buffer, size, offset); } void BufferedInputStream::ReadAsync(char* buffer, int64_t size, int64_t offset, diff --git a/src/paimon/common/io/buffered_input_stream_test.cpp b/src/paimon/common/io/buffered_input_stream_test.cpp index 0f6c9ef95..e1691cf58 100644 --- a/src/paimon/common/io/buffered_input_stream_test.cpp +++ b/src/paimon/common/io/buffered_input_stream_test.cpp @@ -53,8 +53,10 @@ TEST(BufferedInputStreamTest, TestSimple) { ASSERT_EQ(6, input_stream->GetPos().value()); // read from pos 1 - ASSERT_NOK_WITH_MSG(input_stream->Read(value.data(), value.size(), /*offset=*/1), - "BufferedInputStream does not support Read from offset"); + ASSERT_OK_AND_ASSIGN(int64_t bytes_read, + input_stream->Read(value.data(), value.size(), /*offset=*/1)); + ASSERT_EQ(3, bytes_read); + ASSERT_EQ("bcd", value); ASSERT_EQ(6, input_stream->GetPos().value()); // seek to pos 3 diff --git a/src/paimon/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index a71f17eda..aa7ff9b76 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -420,6 +420,8 @@ Result> DataEvolutionSplitRead::InnerCreateReader( PAIMON_ASSIGN_OR_RAISE(std::vector>> split_by_row_id, MergeRangesAndSort(std::move(metas))); + const bool row_id_only = read_schema->num_fields() == 1 && + read_schema->field(0)->name() == SpecialFields::RowId().Name(); std::vector> sub_readers; for (const std::vector>& need_merge_files : split_by_row_id) { PAIMON_ASSIGN_OR_RAISE(std::optional group_selection, @@ -443,8 +445,9 @@ Result> DataEvolutionSplitRead::InnerCreateReader( DataEvolutionSplitRead group_read(path_factory_, context_, pool_, executor_); group_read.file_indexes_evaluated_ = true; group_read.group_selection_ = std::move(group_selection); - if (need_merge_files.size() == 1) { - // No need to merge fields, just create a single file reader + // A video-only delta can contain placeholders even when it has just one file. + if (need_merge_files.size() == 1 && + (row_id_only || !BlobUtils::IsVideoFile(need_merge_files[0]->file_name))) { PAIMON_ASSIGN_OR_RAISE( std::vector> raw_file_readers, group_read.CreateRawFileReaders(split_impl->Partition(), need_merge_files, @@ -1145,6 +1148,16 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea file_batch_readers[file_idx] = std::make_unique(std::move(sources), arrow_pool_); } else if (blob_bunch) { + // Fallback needs the value to distinguish placeholders from explicit NULLs + // even when only the winning sequence number is projected. + if (std::none_of(file_read_schema->fields().begin(), + file_read_schema->fields().end(), BlobUtils::IsAnyBlobField)) { + PAIMON_ASSIGN_OR_RAISE(DataField blob_field, + data_schema->GetField(first_file->write_cols->front())); + read_fields_in_file.push_back(std::move(blob_field)); + file_read_schema = + DataField::ConvertDataFieldsToArrowSchema(read_fields_in_file); + } PAIMON_ASSIGN_OR_RAISE(Range logical_range, blob_bunch->LogicalRange()); PAIMON_ASSIGN_OR_RAISE( file_batch_readers[file_idx], diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 6c1564912..19e87bef1 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -239,13 +239,18 @@ Result> VideoFileBatchReader::GetFileSchema() con Status VideoFileBatchReader::SetReadSchema(::ArrowSchema* schema, const std::shared_ptr&, const std::optional& selection) { + if (closed_) { + return Status::Invalid("video reader is closed"); + } if (!schema) { return Status::Invalid("video read schema is null"); } PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr arrow_schema, arrow::ImportSchema(schema)); - if (arrow_schema->num_fields() != 1 || !BlobUtils::IsBlobField(arrow_schema->field(0))) { - return Status::Invalid("video reader requires one scalar BLOB field"); + if (arrow_schema->num_fields() > 1 || + (arrow_schema->num_fields() == 1 && !BlobUtils::IsBlobField(arrow_schema->field(0)))) { + return Status::Invalid( + "video reader supports only an empty projection or one scalar BLOB field"); } // Create() bounds row_count_ by INT32_MAX. Seek once to check the entire upper range, // including bitmap entries above INT32_MAX, which appear negative when dereferenced. @@ -257,7 +262,7 @@ Status VideoFileBatchReader::SetReadSchema(::ArrowSchema* schema, const std::sha selection_ = selection; read_row_count_ = selection ? selection->Cardinality() : row_count_; previous_selected_rows_.clear(); - field_ = arrow_schema->field(0); + read_type_ = arrow::struct_(arrow_schema->fields()); current_ = 0; previous_batch_size_ = 0; return Status::OK(); @@ -281,10 +286,17 @@ std::shared_ptr VideoFileBatchReader::GetReaderMetrics() const { void VideoFileBatchReader::Close() { closed_ = true; + std::vector().swap(videos_); + std::vector().swap(runs_); + std::vector().swap(previous_selected_rows_); + selection_.reset(); + previous_batch_size_ = 0; + read_type_.reset(); + blob_context_.reset(); } Result VideoFileBatchReader::NextBatch() { - if (closed_ || !field_) { + if (!read_type_) { return Status::Invalid("video reader is closed or read schema is unset"); } if (current_ >= read_row_count_) { @@ -308,10 +320,29 @@ Result VideoFileBatchReader::NextBatch() { selected_rows.push_back(*selected); } } + arrow::ArrayVector columns; + if (read_type_->num_fields() != 0) { + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr frames, + ReadFrames(count, selected_rows, !request || request->read_payload)); + columns.push_back(std::move(frames)); + } + arrow::StructArray array(read_type_, count, columns); + auto c_array = std::make_unique<::ArrowArray>(); + auto c_schema = std::make_unique<::ArrowSchema>(); + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(array, c_array.get(), c_schema.get())); + PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(c_array.get(), c_schema.get(), arrow_pool_)); + current_ += count; + previous_batch_size_ = count; + previous_selected_rows_ = std::move(selected_rows); + return std::make_pair(std::move(c_array), std::move(c_schema)); +} + +Result> VideoFileBatchReader::ReadFrames( + uint64_t count, const std::vector& selected_rows, bool read_payload) { arrow::LargeBinaryBuilder builder(arrow_pool_.get()); PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Reserve(count)); for (uint64_t i = 0; i < count; ++i) { - if (request && !request->read_payload) { + if (!read_payload) { PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); continue; } @@ -338,17 +369,8 @@ Result VideoFileBatchReader::NextBatch() { PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Append(bytes->data(), bytes->size())); } } - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr values, builder.Finish()); - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr array, - arrow::StructArray::Make({values}, {field_})); - auto c_array = std::make_unique<::ArrowArray>(); - auto c_schema = std::make_unique<::ArrowSchema>(); - PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*array, c_array.get(), c_schema.get())); - PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(c_array.get(), c_schema.get(), arrow_pool_)); - current_ += count; - previous_batch_size_ = count; - previous_selected_rows_ = std::move(selected_rows); - return std::make_pair(std::move(c_array), std::move(c_schema)); + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr frames, builder.Finish()); + return frames; } } // namespace paimon::blob diff --git a/src/paimon/format/blob/video_file_batch_reader.h b/src/paimon/format/blob/video_file_batch_reader.h index c2efa4823..4d86e985b 100644 --- a/src/paimon/format/blob/video_file_batch_reader.h +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -30,7 +30,8 @@ #include "paimon/reader/file_batch_reader.h" namespace arrow { -class Field; +class Array; +class DataType; class MemoryPool; } // namespace arrow @@ -84,11 +85,15 @@ class VideoFileBatchReader : public FileBatchReader { Status DecodeVideoIndexes(std::string_view data, const std::array& index_lengths, int64_t index_start); + Result> ReadFrames(uint64_t count, + const std::vector& selected_rows, + bool read_payload); + std::string uri_; int32_t batch_size_; std::shared_ptr pool_; std::shared_ptr arrow_pool_; - std::shared_ptr field_; + std::shared_ptr read_type_; std::shared_ptr metrics_; bool emit_placeholder_sentinel_; std::shared_ptr blob_context_; diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index 6d1f4044b..d63be3297 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -20,6 +20,7 @@ #include "paimon/format/blob/video_file_batch_reader.h" #include +#include #include #include "arrow/api.h" @@ -33,11 +34,13 @@ #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/reader/blob_read_context.h" #include "paimon/common/utils/delta_varint_compressor.h" +#include "paimon/common/utils/read_ahead_cache.h" #include "paimon/data/blob.h" #include "paimon/data/blob_descriptor.h" #include "paimon/format/file_format.h" #include "paimon/format/file_format_factory.h" #include "paimon/fs/local/local_file_system.h" +#include "paimon/io/buffered_input_stream.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/testing/mock/mock_file_system.h" #include "paimon/testing/utils/testharness.h" @@ -205,13 +208,23 @@ TEST(VideoFileBatchReaderTest, ReopensFramesFromContainerSlice) { ASSERT_OK(fs->WriteFile(path, "12345" + pack + "suffix", true)); ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(4)); - for (const auto& [prefix, cached] : - {std::pair{5, false}, std::pair{2, false}, std::pair{5, true}, std::pair{2, true}}) { - SCOPED_TRACE(::testing::Message() << "prefix=" << prefix << ", cached=" << cached); + for (const auto& [prefix, buffered, cached] : + {std::tuple{5, false, false}, std::tuple{2, false, false}, std::tuple{5, false, true}, + std::tuple{2, false, true}, std::tuple{5, true, false}, std::tuple{2, true, true}}) { + SCOPED_TRACE(::testing::Message() + << "prefix=" << prefix << ", buffered=" << buffered << ", cached=" << cached); ASSERT_OK_AND_ASSIGN(auto blob, Blob::FromPath(path, prefix, pack.size() + 5 - prefix)); ASSERT_OK_AND_ASSIGN(auto slice, blob->NewInputStream(fs)); + if (buffered) { + slice = + std::make_unique(std::move(slice), 8, GetDefaultPool().get()); + } if (cached) { - slice = std::make_unique(std::move(slice), nullptr); + ASSERT_OK_AND_ASSIGN(std::shared_ptr cache_input, + blob->NewInputStream(fs)); + auto cache = std::make_shared(cache_input, CacheConfig(), + /*file_size=*/0, GetDefaultPool()); + slice = std::make_unique(std::move(slice), cache); } std::shared_ptr input = std::move(slice); if (prefix != 5) { @@ -369,6 +382,28 @@ TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { } } +TEST(VideoFileBatchReaderTest, EmptyProjectionPreservesSelectedFileRows) { + auto input = std::make_shared(0, MakeVideoFile(/*placeholder=*/true)); + ASSERT_OK_AND_ASSIGN(auto reader, + VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*arrow::schema({}), &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, RoaringBitmap32::From({0, 2, 3}))); + for (const auto& file_rows : {std::vector{0, 2}, std::vector{3}}) { + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_EQ(0, batch.first->n_children); + ASSERT_EQ(file_rows.size(), batch.first->length); + for (size_t i = 0; i < file_rows.size(); ++i) { + ASSERT_OK_AND_ASSIGN(uint64_t row, reader->GetPreviousBatchFileRowId(i)); + ASSERT_EQ(file_rows[i], row); + } + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); + } + ASSERT_OK_AND_ASSIGN(auto eof, reader->NextBatch()); + ASSERT_TRUE(BatchReader::IsEofBatch(eof)); +} + TEST(VideoFileBatchReaderTest, ReadsJavaIndexesWithOneTailRead) { ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-v1-moov.hex")); constexpr int64_t kPayloadSize = 24; @@ -378,6 +413,9 @@ TEST(VideoFileBatchReaderTest, ReadsJavaIndexesWithOneTailRead) { ASSERT_EQ(reader->GetNumberOfRows().value(), 2); const std::vector> expected{{30, 29}, {24, 6}}; ASSERT_EQ(input->reads, expected); + ASSERT_GT(reader->videos_.capacity(), 0u); + reader->Close(); + ASSERT_EQ(reader->videos_.capacity(), 0u); } TEST(VideoFileBatchReaderTest, ReadsEmptyVideoFile) { @@ -438,6 +476,19 @@ TEST(VideoFileBatchReaderTest, ReadsLargeIndexWithinMemoryBudget) { VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); ASSERT_EQ(rows, kRuns); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, RoaringBitmap32::From({1, 3}))); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + reader->Close(); + ASSERT_EQ(0u, reader->runs_.capacity()); + ASSERT_EQ(0u, reader->previous_selected_rows_.capacity()); + ASSERT_FALSE(reader->selection_); + ASSERT_NOK(reader->GetPreviousBatchFileRowId(0)); + ASSERT_NOK(reader->NextBatch()); + auto array = arrow::ImportArray(batch.first.get(), batch.second.get()).ValueOrDie(); + ASSERT_EQ(2, array->length()); } TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { diff --git a/test/inte/blob_table_inte_test.cpp b/test/inte/blob_table_inte_test.cpp index ed83b9df5..14b588b24 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -1376,7 +1376,6 @@ TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { // Clearing the declaration for a write still permits a projection that excludes video. ASSERT_OK_AND_ASSIGN(auto commit_messages, WriteArray(table_path, {}, {"id"}, {id_array}, override)); - ASSERT_OK(Commit(table_path, commit_messages)); auto video_array = MakeBlobUpdateArray(fields[1], {"payload"}); ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"video"}, {video_array}), "writing video-frame-field 'video' is not supported"); @@ -1392,50 +1391,97 @@ TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"video"}, {video_array}, override), "writing video-frame-field 'video' is not supported"); - ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, ScanTable(table_path)); - ASSERT_EQ(plan->Splits().size(), 1); - auto main_split = std::dynamic_pointer_cast(plan->Splits()[0]); - ASSERT_TRUE(main_split); - auto files = main_split->DataFiles(); - ASSERT_EQ(files.size(), 1); - const auto& data_file = files[0]; - ASSERT_TRUE(data_file->first_row_id); - const int64_t first_row_id = data_file->first_row_id.value(); - const int64_t sequence = data_file->max_sequence_number; + // Commit the Java-written video with its normal file, then commit a video-only update. auto fs = dir_->GetFileSystem(); - + ASSERT_EQ(1u, commit_messages.size()); + auto message = std::dynamic_pointer_cast(commit_messages.front()); + ASSERT_TRUE(message); + auto& files = message->data_increment_.new_files_; + ASSERT_EQ(1u, files.size()); + const auto data_file = files.front(); + auto write_video = + [&](const std::string& name, const std::string& bytes, int64_t sequence, + std::optional first_row_id) -> Result> { + PAIMON_RETURN_NOT_OK( + fs->WriteFile(PathUtil::JoinPath(table_path, "bucket-0/" + name), bytes, false)); + return DataFileMeta::ForAppend(name, bytes.size(), 2, SimpleStats::EmptyStats(), sequence, + sequence, data_file->schema_id, FileSource::Append(), + std::nullopt, std::nullopt, first_row_id, + std::vector{"video"}); + }; ASSERT_OK_AND_ASSIGN(std::string base, ReadJavaVideoFixture("video-v1-moov.hex")); + ASSERT_OK_AND_ASSIGN(auto base_file, write_video("base.video", base, + data_file->max_sequence_number, std::nullopt)); + files.push_back(std::move(base_file)); + ASSERT_OK(Commit(table_path, commit_messages)); + ScanContextBuilder scan_builder(table_path); + scan_builder.WithStreamingMode(true); + ASSERT_OK_AND_ASSIGN(auto scan_context, scan_builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto scan, TableScan::Create(std::move(scan_context))); + ASSERT_OK_AND_ASSIGN(auto initial, scan->CreatePlan()); + ASSERT_EQ(1u, initial->Splits().size()); + auto base_split = std::dynamic_pointer_cast(initial->Splits()[0]); + ASSERT_TRUE(base_split); + ASSERT_EQ(2u, base_split->DataFiles().size()); + ASSERT_OK_AND_ASSIGN(int64_t first_row_id, base_split->DataFiles()[0]->NonNullFirstRowId()); // Two runs with no physical payloads: the first falls back, the second overwrites with NULL. constexpr char overlay[] = "\x02\x00\x03\x02\x00\x00" // Run lengths, references, first frames. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00" "IDEO\x01"; + ASSERT_OK_AND_ASSIGN( + auto update, + write_video("overlay.video", std::string(overlay, sizeof(overlay) - 1), + base_split->DataFiles()[0]->max_sequence_number + 1, first_row_id)); ASSERT_OK( - fs->WriteFile(PathUtil::JoinPath(main_split->BucketPath(), "base.video"), base, true)); - ASSERT_OK(fs->WriteFile(PathUtil::JoinPath(main_split->BucketPath(), "overlay.video"), - std::string(overlay, sizeof(overlay) - 1), true)); - auto make_video_meta = [&](const std::string& name, int64_t file_size, int64_t seq) { - return DataFileMeta::ForAppend(name, file_size, /*row_count=*/2, SimpleStats::EmptyStats(), - seq, seq, /*schema_id=*/0, FileSource::Append(), - std::nullopt, std::nullopt, first_row_id, - std::vector{"video"}); - }; - ASSERT_OK_AND_ASSIGN(std::shared_ptr older, - make_video_meta("base.video", base.size(), sequence + 1)); - ASSERT_OK_AND_ASSIGN(std::shared_ptr newer, - make_video_meta("overlay.video", sizeof(overlay) - 1, sequence + 2)); - files.push_back(older); - files.push_back(newer); - ASSERT_OK_AND_ASSIGN(std::shared_ptr split, - DataSplitImpl::Builder(main_split->Partition(), main_split->Bucket(), - main_split->BucketPath(), std::move(files)) - .WithSnapshot(main_split->SnapshotId()) - .WithTotalBuckets(main_split->TotalBuckets()) - .RawConvertible(false) - .Build()); - auto video_plan = - std::make_shared(plan->SnapshotId(), std::vector>{split}); + Commit(table_path, {std::make_shared( + message->Partition(), message->Bucket(), message->TotalBuckets(), + DataIncrement({update}, {}, {}), CompactIncrement({}, {}, {}))})); + ASSERT_OK_AND_ASSIGN(auto delta, scan->CreatePlan()); + ASSERT_EQ(1u, delta->Splits().size()); + auto delta_split = std::dynamic_pointer_cast(delta->Splits()[0]); + ASSERT_TRUE(delta_split); + ASSERT_EQ(1u, delta_split->DataFiles().size()); + ASSERT_EQ("overlay.video", delta_split->DataFiles()[0]->file_name); + + // The delta has no older frame to fall back to. Only the placeholder has sequence -1. + ASSERT_OK_AND_ASSIGN(auto delta_values, + ReadTable(table_path, {"video", "_ROW_ID", "_SEQUENCE_NUMBER"}, delta)); + auto delta_rows = checked_pointer_cast( + arrow::Concatenate(delta_values->chunks()).ValueOrDie()); + ASSERT_EQ(2, delta_rows->length()); + ASSERT_EQ(2, delta_rows->GetFieldByName("video")->null_count()); + auto delta_ids = checked_pointer_cast(delta_rows->GetFieldByName("_ROW_ID")); + ASSERT_EQ(first_row_id, delta_ids->Value(0)); + ASSERT_EQ(first_row_id + 1, delta_ids->Value(1)); + auto sequences = + checked_pointer_cast(delta_rows->GetFieldByName("_SEQUENCE_NUMBER")); + ASSERT_EQ(-1, sequences->Value(0)); + ASSERT_EQ(delta_split->DataFiles()[0]->max_sequence_number, sequences->Value(1)); + + for (const std::string field : {"video", "_ROW_ID", "_SEQUENCE_NUMBER"}) { + ASSERT_OK_AND_ASSIGN(auto projected, ReadTable(table_path, {field}, delta)); + auto projected_rows = checked_pointer_cast( + arrow::Concatenate(projected->chunks()).ValueOrDie()); + ASSERT_TRUE( + projected_rows->GetFieldByName(field)->Equals(delta_rows->GetFieldByName(field))); + } + + auto selected_split = std::make_shared( + delta_split, std::vector{Range(first_row_id + 1, first_row_id + 1)}); + auto selected_plan = std::make_shared( + delta->SnapshotId(), std::vector>{selected_split}); + ASSERT_OK_AND_ASSIGN(auto selected, ReadTable(table_path, {"_ROW_ID"}, selected_plan)); + auto selected_rows = checked_pointer_cast( + arrow::Concatenate(selected->chunks()).ValueOrDie()); + ASSERT_EQ(1, selected_rows->length()); + ASSERT_EQ(first_row_id + 1, + checked_pointer_cast(selected_rows->GetFieldByName("_ROW_ID")) + ->Value(0)); + + // A full snapshot includes the base frame for the placeholder and preserves the explicit NULL. + ASSERT_OK_AND_ASSIGN(auto video_plan, ScanTable(table_path)); ASSERT_OK_AND_ASSIGN( std::shared_ptr result, ReadTable(table_path, {"id", "video", "_ROW_ID"}, video_plan, From b4848eaf8a21fc40ca7342f2f956ed6d57a7fe79 Mon Sep 17 00:00:00 2001 From: xiaohongbo Date: Thu, 3 Dec 2026 07:33:55 -0800 Subject: [PATCH 19/19] fix(blob): align video delta rows and preserve fallback metadata --- src/paimon/common/data/blob_utils.cpp | 4 +- .../reader/blob_fallback_batch_reader.cpp | 14 +- .../reader/blob_fallback_batch_reader.h | 9 +- src/paimon/common/reader/blob_read_context.h | 2 + src/paimon/core/io/field_mapping_reader.cpp | 49 +++---- src/paimon/core/io/field_mapping_reader.h | 3 + .../operation/data_evolution_split_read.cpp | 55 ++++++-- .../operation/data_evolution_split_read.h | 2 +- .../table/append_only_file_store_table.cpp | 2 +- .../format/blob/blob_file_batch_reader.h | 5 +- .../format/blob/video_file_batch_reader.cpp | 18 ++- .../blob/video_file_batch_reader_test.cpp | 68 +++++++++- test/inte/blob_table_inte_test.cpp | 123 +++++++++++++++++- 13 files changed, 301 insertions(+), 53 deletions(-) diff --git a/src/paimon/common/data/blob_utils.cpp b/src/paimon/common/data/blob_utils.cpp index 5661869cf..930b2a58b 100644 --- a/src/paimon/common/data/blob_utils.cpp +++ b/src/paimon/common/data/blob_utils.cpp @@ -205,7 +205,9 @@ std::vector BlobUtils::GetVideoFrameFields( for (auto& name : names) { StringUtils::Trim(&name); } - return names; + std::set fields(names.begin(), names.end()); + fields.erase(""); + return {fields.begin(), fields.end()}; } bool BlobUtils::IsVideoFile(const std::string& file_name) { diff --git a/src/paimon/common/reader/blob_fallback_batch_reader.cpp b/src/paimon/common/reader/blob_fallback_batch_reader.cpp index e019e265d..60c7c7d49 100644 --- a/src/paimon/common/reader/blob_fallback_batch_reader.cpp +++ b/src/paimon/common/reader/blob_fallback_batch_reader.cpp @@ -42,7 +42,8 @@ namespace paimon { Result> BlobFallbackBatchReader::Create( std::vector>&& sequence_groups, const std::shared_ptr& read_schema, int32_t read_batch_size, - const std::shared_ptr& arrow_pool) { + const std::shared_ptr& arrow_pool, + std::map> partition_values) { if (sequence_groups.empty()) { return Status::Invalid("Blob fallback needs at least one sequence group."); } @@ -87,9 +88,11 @@ Result> BlobFallbackBatchReader::Create cursor.segments = std::move(segments); groups.push_back(std::move(cursor)); } - return std::unique_ptr(new BlobFallbackBatchReader( + auto reader = std::unique_ptr(new BlobFallbackBatchReader( std::move(groups), read_schema, blob_field_idx, row_id_field_idx, seq_num_field_idx, read_batch_size, arrow_pool)); + reader->partition_values_ = std::move(partition_values); + return reader; } BlobFallbackBatchReader::BlobFallbackBatchReader( @@ -313,6 +316,13 @@ Result> BlobFallbackBatchReader::AssembleColumn( int32_t field_idx, const std::vector& group_choice, const std::vector>& group_chunks) const { const auto row_count = static_cast(group_choice.size()); + auto partition = partition_values_.find(field_idx); + if (partition != partition_values_.end()) { + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( + std::shared_ptr values, + arrow::MakeArrayFromScalar(*partition->second, row_count, arrow_pool_.get())); + return values; + } arrow::ArrayVector pieces; std::vector cursors(group_chunks.size()); int64_t run_start = 0; diff --git a/src/paimon/common/reader/blob_fallback_batch_reader.h b/src/paimon/common/reader/blob_fallback_batch_reader.h index 003fbecd5..c0df585da 100644 --- a/src/paimon/common/reader/blob_fallback_batch_reader.h +++ b/src/paimon/common/reader/blob_fallback_batch_reader.h @@ -20,6 +20,7 @@ #pragma once #include +#include #include #include @@ -61,7 +62,7 @@ namespace paimon { /// Older groups use a shared BlobReadContext to advance resolved rows without reading their /// payloads and to bound each batch by the current window and unresolved row runs. /// 4. A row that is a placeholder in every group degrades to a null blob: it keeps its -/// _ROW_ID, reports -1 as its _SEQUENCE_NUMBER, and returns null for every other field. +/// _ROW_ID, reports -1 as its _SEQUENCE_NUMBER, and preserves split partition values. class BlobFallbackBatchReader : public BatchReader { public: /// One piece of a sequence group: either a reader over a single blob file (already wrapped @@ -89,7 +90,8 @@ class BlobFallbackBatchReader : public BatchReader { static Result> Create( std::vector>&& sequence_groups, const std::shared_ptr& read_schema, int32_t read_batch_size, - const std::shared_ptr& arrow_pool); + const std::shared_ptr& arrow_pool, + std::map> partition_values = {}); Result NextBatch() override; @@ -157,7 +159,7 @@ class BlobFallbackBatchReader : public BatchReader { /// Assembles one output column by stitching, per run of rows choosing the same group, /// slices of that group's chunks. For rows choosing no group (placeholder in every layer), - /// _ROW_ID is kept, _SEQUENCE_NUMBER becomes -1, and every other field becomes null. + /// _ROW_ID and partition values are kept and _SEQUENCE_NUMBER becomes -1. Result> AssembleColumn( int32_t field_idx, const std::vector& group_choice, const std::vector>& group_chunks) const; @@ -178,6 +180,7 @@ class BlobFallbackBatchReader : public BatchReader { const int32_t read_batch_size_; std::shared_ptr arrow_pool_; std::shared_ptr finished_reader_metrics_; + std::map> partition_values_; bool closed_ = false; }; diff --git a/src/paimon/common/reader/blob_read_context.h b/src/paimon/common/reader/blob_read_context.h index 57fc01141..f061fdbfc 100644 --- a/src/paimon/common/reader/blob_read_context.h +++ b/src/paimon/common/reader/blob_read_context.h @@ -41,6 +41,8 @@ struct BlobBatchRequest { /// Access is confined to the thread reading that segment. struct BlobReadContext { std::optional request; + // The hidden BLOB column only distinguishes placeholders from resolved rows. + bool placeholder_only = false; }; /// Internal builder hook used before the format reader is wrapped. Only the blob builder diff --git a/src/paimon/core/io/field_mapping_reader.cpp b/src/paimon/core/io/field_mapping_reader.cpp index e271a579c..adbbba37d 100644 --- a/src/paimon/core/io/field_mapping_reader.cpp +++ b/src/paimon/core/io/field_mapping_reader.cpp @@ -229,73 +229,74 @@ Result FieldMappingReader::NextBatchWithBitmap Result> FieldMappingReader::GenerateSinglePartitionArray( int32_t idx, int32_t batch_size) const { const auto& type = partition_info_.value().partition_read_schema[idx].Type(); - if (partition_.IsNullAt(partition_info_.value().idx_in_partition[idx])) { - // for null partition value - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( - std::shared_ptr null_array, - arrow::MakeArrayOfNull(type, batch_size, arrow_pool_.get())); - return null_array; + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr scalar, + ReadPartitionScalar(partition_, partition_info_->idx_in_partition[idx], type)); + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( + std::shared_ptr arrow_array, + arrow::MakeArrayFromScalar(*scalar, batch_size, arrow_pool_.get())); + return arrow_array; +} + +Result> FieldMappingReader::ReadPartitionScalar( + const BinaryRow& partition, int32_t index, const std::shared_ptr& type) { + if (partition.IsNullAt(index)) { + return arrow::MakeNullScalar(type); } auto type_id = type->id(); std::shared_ptr scalar; switch (type_id) { case arrow::Type::type::BOOL: { - bool value = partition_.GetBoolean(partition_info_.value().idx_in_partition[idx]); + bool value = partition.GetBoolean(index); scalar = std::make_shared(value); break; } case arrow::Type::type::INT8: { - int8_t value = partition_.GetByte(partition_info_.value().idx_in_partition[idx]); + int8_t value = partition.GetByte(index); scalar = std::make_shared(value); break; } case arrow::Type::type::INT16: { - int16_t value = partition_.GetShort(partition_info_.value().idx_in_partition[idx]); + int16_t value = partition.GetShort(index); scalar = std::make_shared(value); break; } case arrow::Type::type::INT32: { - int32_t value = partition_.GetInt(partition_info_.value().idx_in_partition[idx]); + int32_t value = partition.GetInt(index); scalar = std::make_shared(value); break; } case arrow::Type::type::INT64: { - int64_t value = partition_.GetLong(partition_info_.value().idx_in_partition[idx]); + int64_t value = partition.GetLong(index); scalar = std::make_shared(value); break; } case arrow::Type::type::STRING: { - BinaryString value = - partition_.GetString(partition_info_.value().idx_in_partition[idx]); + BinaryString value = partition.GetString(index); scalar = std::make_shared(value.ToString()); break; } case arrow::Type::type::BINARY: { - auto value = partition_.GetBinary(partition_info_.value().idx_in_partition[idx]); + auto value = partition.GetBinary(index); std::string value_str(value->data(), value->size()); scalar = std::make_shared(value_str); break; } case arrow::Type::type::DATE32: { - int32_t value = partition_.GetDate(partition_info_.value().idx_in_partition[idx]); + int32_t value = partition.GetDate(index); scalar = std::make_shared(value); break; } case arrow::Type::type::TIME32: { - int32_t value = partition_.GetInt(partition_info_.value().idx_in_partition[idx]); - scalar = std::make_shared( - value, partition_info_.value().partition_read_schema[idx].Type()); + int32_t value = partition.GetInt(index); + scalar = std::make_shared(value, type); break; } default: return Status::Invalid( - fmt::format("Not support arrow type {} for partition", - partition_info_.value().partition_read_schema[idx].Type()->ToString())); + fmt::format("Not support arrow type {} for partition", type->ToString())); } - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( - std::shared_ptr arrow_array, - arrow::MakeArrayFromScalar(*scalar, batch_size, arrow_pool_.get())); - return arrow_array; + return scalar; } Result> FieldMappingReader::GeneratePartitionArray( diff --git a/src/paimon/core/io/field_mapping_reader.h b/src/paimon/core/io/field_mapping_reader.h index fa976b2f6..db76c95c7 100644 --- a/src/paimon/core/io/field_mapping_reader.h +++ b/src/paimon/core/io/field_mapping_reader.h @@ -55,6 +55,9 @@ class FieldMappingReader : public FileBatchReader { std::set&& skip_map_selected_keys_filter_field_ids, const std::shared_ptr& arrow_pool); + static Result> ReadPartitionScalar( + const BinaryRow& partition, int32_t index, const std::shared_ptr& type); + Result NextBatch() override { return Status::Invalid( "paimon inner reader FieldMappingReader should use NextBatchWithBitmap"); diff --git a/src/paimon/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index aa7ff9b76..6d7ab5b8c 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -54,6 +54,7 @@ #include "paimon/core/deletionvectors/apply_deletion_vector_batch_reader.h" #include "paimon/core/deletionvectors/bitmap_deletion_vector.h" #include "paimon/core/global_index/indexed_split_impl.h" +#include "paimon/core/io/field_mapping_reader.h" #include "paimon/core/io/file_index_evaluator.h" #include "paimon/core/io/file_index_options.h" #include "paimon/core/table/format/lazy_concat_batch_reader.h" @@ -691,6 +692,19 @@ DataEvolutionSplitRead::SplitFieldBunches( std::vector> fields_files; std::map> blob_bunch_map; std::optional expected_row_range; + // MergeRangesAndSort supplies one connected group. A dedicated-only update shares + // that group's row range across columns, even when each column covers only part of it. + if (!need_merge_files.empty() && + std::all_of(need_merge_files.begin(), need_merge_files.end(), + [](const auto& file) { return BlobUtils::IsBlobFile(file->file_name); })) { + for (const auto& file : need_merge_files) { + PAIMON_ASSIGN_OR_RAISE(Range range, file->NonNullRowIdRange()); + expected_row_range = expected_row_range + ? Range(std::min(expected_row_range->from, range.from), + std::max(expected_row_range->to, range.to)) + : range; + } + } for (const auto& file : need_merge_files) { if (BlobUtils::IsBlobFile(file->file_name)) { PAIMON_ASSIGN_OR_RAISE(int32_t field_id, blob_field_to_field_id(file)); @@ -1108,6 +1122,15 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea } } + // If no file supplies a projected column, one aligned bunch supplies the logical + // row count. DataEvolutionFileReader fills the missing columns with NULL. + if (!has_normal_file && !all_read_fields.empty() && read_fields_in_file.empty() && + file_idx + 1 == static_cast(fields_files.size()) && + std::dynamic_pointer_cast(bunch) && + std::all_of(reader_offsets.begin(), reader_offsets.end(), + [](int32_t offset) { return offset < 0; })) { + read_fields_in_file.push_back(SpecialFields::RowId()); + } if (!read_fields_in_file.empty()) { // create new FieldMappingReader for read partial fields auto file_read_schema = DataField::ConvertDataFieldsToArrowSchema(read_fields_in_file); @@ -1150,8 +1173,10 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea } else if (blob_bunch) { // Fallback needs the value to distinguish placeholders from explicit NULLs // even when only the winning sequence number is projected. - if (std::none_of(file_read_schema->fields().begin(), - file_read_schema->fields().end(), BlobUtils::IsAnyBlobField)) { + const bool placeholder_only = + std::none_of(file_read_schema->fields().begin(), + file_read_schema->fields().end(), BlobUtils::IsAnyBlobField); + if (placeholder_only) { PAIMON_ASSIGN_OR_RAISE(DataField blob_field, data_schema->GetField(first_file->write_cols->front())); read_fields_in_file.push_back(std::move(blob_field)); @@ -1163,7 +1188,7 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea file_batch_readers[file_idx], CreateBlobFallbackReader(partition, blob_bunch->Files(), logical_range, file_read_schema, row_ranges, data_file_path_factory, - group_dv_factory, group_dv)); + group_dv_factory, group_dv, placeholder_only)); } else { PAIMON_ASSIGN_OR_RAISE( std::vector> file_readers, @@ -1230,7 +1255,7 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR const std::optional>& row_ranges, const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, - const std::optional& group_dv) const { + const std::optional& group_dv, bool placeholder_only) const { if (files.empty()) { return Status::Invalid("Blob bunch should not be empty."); } @@ -1256,7 +1281,8 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR const auto selected_ranges = SelectedRangesInRange(union_first_row_id, union_last_row_id, row_ranges); auto open_file = - [split_read, partition, file_read_schema, group_dv_factory, data_file_path_factory]( + [split_read, partition, file_read_schema, group_dv_factory, data_file_path_factory, + placeholder_only]( const std::shared_ptr& file, const std::vector& ranges, std::shared_ptr* context) -> Result> { PAIMON_ASSIGN_OR_RAISE( @@ -1271,6 +1297,7 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR if (!readers[0].blob_context) { return Status::Invalid("Blob fallback file segment needs a blob read context."); } + readers[0].blob_context->placeholder_only = placeholder_only; *context = std::move(readers[0].blob_context); return std::move(readers[0].reader); }; @@ -1341,10 +1368,20 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR } groups.push_back(std::move(segments)); } - PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr fallback_reader, - BlobFallbackBatchReader::Create(std::move(groups), file_read_schema, - options_.GetReadBatchSize(), arrow_pool_)); + std::map> partition_values; + const auto& keys = context_->GetPartitionKeys(); + for (size_t i = 0; i < keys.size(); ++i) { + const int idx = file_read_schema->GetFieldIndex(keys[i]); + if (idx >= 0) { + PAIMON_ASSIGN_OR_RAISE(partition_values[idx], + FieldMappingReader::ReadPartitionScalar( + partition, i, file_read_schema->field(idx)->type())); + } + } + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr fallback_reader, + BlobFallbackBatchReader::Create(std::move(groups), file_read_schema, + options_.GetReadBatchSize(), arrow_pool_, + std::move(partition_values))); return std::move(fallback_reader); } diff --git a/src/paimon/core/operation/data_evolution_split_read.h b/src/paimon/core/operation/data_evolution_split_read.h index 70075fb7e..9cf498a12 100644 --- a/src/paimon/core/operation/data_evolution_split_read.h +++ b/src/paimon/core/operation/data_evolution_split_read.h @@ -313,7 +313,7 @@ class DataEvolutionSplitRead : public AbstractSplitRead { const std::optional>& row_ranges, const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, - const std::optional& group_dv) const; + const std::optional& group_dv, bool placeholder_only = false) const; /// Set only on a per-group reader after SelectByFileIndex has evaluated its indexes. /// Lazy child readers inherit it so no sidecar is reopened during reader construction. 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 c784520a3..a2591effa 100644 --- a/src/paimon/core/table/append_only_file_store_table.cpp +++ b/src/paimon/core/table/append_only_file_store_table.cpp @@ -120,7 +120,7 @@ Result> AppendOnlyFileStoreTable::CreateWrite( // A per-write override must not turn a persisted video column into an ordinary blob. for (const auto* declaration : {&schema->Options(), &options.ToMap()}) { for (const auto& name : BlobUtils::GetVideoFrameFields(*declaration)) { - if (write_schema->GetFieldIndex(name) >= 0) { + if (!write_schema->GetAllFieldIndices(name).empty()) { return Status::NotImplemented( fmt::format("writing video-frame-field '{}' is not supported", name)); } diff --git a/src/paimon/format/blob/blob_file_batch_reader.h b/src/paimon/format/blob/blob_file_batch_reader.h index 3610d059f..d7c65ddea 100644 --- a/src/paimon/format/blob/blob_file_batch_reader.h +++ b/src/paimon/format/blob/blob_file_batch_reader.h @@ -208,7 +208,10 @@ class BlobFileBatchReader : public FileBatchReader { /// Returns true if the blob at the given index is null (bin_length == kNullBinLength). bool IsTargetNull(size_t index) const { - return target_blob_lengths_[index] == BlobDefs::kNullBinLength; + // A hidden fallback field needs only the footer marker. Represent every resolved + // row as NULL so scalar and collection builders skip the payload entirely. + return target_blob_lengths_[index] == BlobDefs::kNullBinLength || + (blob_context_ && blob_context_->placeholder_only && !IsTargetPlaceholder(index)); } bool IsTargetPlaceholder(size_t index) const { diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp index 19e87bef1..4caaa69c6 100644 --- a/src/paimon/format/blob/video_file_batch_reader.cpp +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -118,7 +118,7 @@ VideoFileBatchReader::VideoFileBatchReader(std::string uri, int32_t batch_size, Result> VideoFileBatchReader::Create( const std::shared_ptr& input, int32_t batch_size, const std::shared_ptr& pool, bool emit_placeholder_sentinel, - const std::shared_ptr& blob_context) { + const std::shared_ptr& blob_context) try { if (!input || !pool || batch_size <= 0) { return Status::Invalid("invalid video reader input, pool, or batch size"); } @@ -130,9 +130,6 @@ Result> VideoFileBatchReader::Create( return reader->uri_.empty() ? status : status.WithMessage(status.message(), " (", reader->uri_, ")"); } - if (!reader->videos_.empty() && reader->uri_.empty()) { - return Status::Invalid("video frame descriptors require a reopenable file URI"); - } PAIMON_ASSIGN_OR_RAISE(int64_t base, FileOffsetInputStream::GetFileOffset(*input)); if (base != 0) { for (auto& video : reader->videos_) { @@ -143,6 +140,8 @@ Result> VideoFileBatchReader::Create( } } return reader; +} catch (const std::bad_alloc&) { + return Status::OutOfMemory("allocating video indexes"); } Status VideoFileBatchReader::ReadVideoIndexes(InputStream* input) { @@ -295,7 +294,7 @@ void VideoFileBatchReader::Close() { blob_context_.reset(); } -Result VideoFileBatchReader::NextBatch() { +Result VideoFileBatchReader::NextBatch() try { if (!read_type_) { return Status::Invalid("video reader is closed or read schema is unset"); } @@ -335,6 +334,8 @@ Result VideoFileBatchReader::NextBatch() { previous_batch_size_ = count; previous_selected_rows_ = std::move(selected_rows); return std::make_pair(std::move(c_array), std::move(c_schema)); +} catch (const std::bad_alloc&) { + return Status::OutOfMemory("allocating video frame batch"); } Result> VideoFileBatchReader::ReadFrames( @@ -358,6 +359,13 @@ Result> VideoFileBatchReader::ReadFrames( } PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Append(BlobDefs::PlaceholderSentinelView())); } else { + if (blob_context_ && blob_context_->placeholder_only) { + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); + continue; + } + if (uri_.empty()) { + return Status::Invalid("video frame descriptors require a reopenable file URI"); + } const auto& video = videos_[run->reference]; const uint64_t run_start = run == runs_.begin() ? 0 : (run - 1)->end; const int64_t frame = run->first_frame + static_cast(row - run_start); diff --git a/src/paimon/format/blob/video_file_batch_reader_test.cpp b/src/paimon/format/blob/video_file_batch_reader_test.cpp index d63be3297..01ff58378 100644 --- a/src/paimon/format/blob/video_file_batch_reader_test.cpp +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -254,12 +254,74 @@ TEST(VideoFileBatchReaderTest, ReopensFramesFromContainerSlice) { } } -TEST(VideoFileBatchReaderTest, RejectsFramesWithoutFileUri) { - const auto bytes = MakeVideoFile(); +TEST(VideoFileBatchReaderTest, RequiresUriOnlyWhenEmittingFrames) { + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-v1-moov.hex")); auto input = std::make_shared(bytes.data(), bytes.size()); ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); - ASSERT_NOK_WITH_MSG(builder->Build(input), "reopenable file URI"); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(input)); + ASSERT_OK_AND_ASSIGN(uint64_t count, reader->GetNumberOfRows()); + ASSERT_EQ(2u, count); + ::ArrowSchema schema; + ASSERT_TRUE(arrow::ExportSchema(*arrow::schema({}), &schema).ok()); + ASSERT_OK(reader->SetReadSchema(&schema, nullptr, std::nullopt)); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_GT(batch.first->length, 0); + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); + ASSERT_OK_AND_ASSIGN(reader, builder->Build(input)); + ASSERT_TRUE( + arrow::ExportSchema(*arrow::schema({BlobUtils::ToArrowField("video", true)}), &schema) + .ok()); + ASSERT_OK(reader->SetReadSchema(&schema, nullptr, std::nullopt)); + ASSERT_NOK_WITH_MSG(reader->NextBatch(), "reopenable file URI"); +} + +TEST(VideoFileBatchReaderTest, ReportsIndexAndFrameAllocationFailures) { + class FaultPool final : public MemoryPool { + public: + bool fail = true; + void* Malloc(uint64_t size, uint64_t alignment) override { + // Fail the Bytes allocation. Arrow's aligned builders may still allocate. + if (fail && alignment == 0) { + throw std::bad_alloc(); + } + return GetDefaultPool()->Malloc(size, alignment); + } + void* Realloc(void* ptr, size_t old_size, size_t new_size, uint64_t alignment) override { + return GetDefaultPool()->Realloc(ptr, old_size, new_size, alignment); + } + void Free(void* ptr, uint64_t size) override { + GetDefaultPool()->Free(ptr, size); + } + uint64_t CurrentUsage() const override { + return GetDefaultPool()->CurrentUsage(); + } + uint64_t MaxMemoryUsage() const override { + return GetDefaultPool()->MaxMemoryUsage(); + } + }; + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-v1-moov.hex")); + auto input = std::make_shared(0, bytes); + auto pool = std::make_shared(); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + builder->WithMemoryPool(pool); + ASSERT_TRUE(builder->Build(input).status().IsOutOfMemory()); + pool->fail = false; + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(input)); + ::ArrowSchema schema; + ASSERT_TRUE( + arrow::ExportSchema(*arrow::schema({BlobUtils::ToArrowField("video", true)}), &schema) + .ok()); + ASSERT_OK(reader->SetReadSchema(&schema, nullptr, std::nullopt)); + pool->fail = true; + ASSERT_TRUE(reader->NextBatch().status().IsOutOfMemory()); + pool->fail = false; + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_EQ(2, batch.first->length); + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); } TEST(VideoFileBatchReaderTest, RejectsOverflowingFrameIndex) { diff --git a/test/inte/blob_table_inte_test.cpp b/test/inte/blob_table_inte_test.cpp index 14b588b24..305cd6dea 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -1352,7 +1352,10 @@ TEST_P(BlobTableInteTest, ValidateVideoFrameFieldsOnCreateTable) { for (const auto& name : {"missing", "id", "frames"}) { ASSERT_NOK_WITH_MSG(create(name), name); } - ASSERT_NOK_WITH_MSG(create("video,video"), "duplicate"); + for (const auto& names : {"video,video", "video, ,"}) { + ASSERT_OK(create(names)); + ASSERT_OK(catalog->DropTable(Identifier("foo", "bar"), false)); + } for (const auto& conflict : {Options::BLOB_DESCRIPTOR_FIELD, Options::BLOB_VIEW_FIELD}) { ASSERT_NOK_WITH_MSG(create("video", conflict), conflict); } @@ -1380,6 +1383,10 @@ TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"video"}, {video_array}), "writing video-frame-field 'video' is not supported"); + ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"id", "video", "video"}, {}, + {{Options::BLOB_DESCRIPTOR_FIELD, "video"}}), + "writing video-frame-field"); + auto full_row = arrow::StructArray::Make( {std::static_pointer_cast(id_array)->field(0)->Slice(0, 1), @@ -1445,6 +1452,32 @@ TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { ASSERT_EQ(1u, delta_split->DataFiles().size()); ASSERT_EQ("overlay.video", delta_split->DataFiles()[0]->file_name); + std::vector> layers = delta_split->DataFiles(); + for (const auto& file : base_split->DataFiles()) { + if (BlobUtils::IsVideoFile(file->file_name)) { + layers.push_back(file); + } + } + ASSERT_EQ(2u, layers.size()); + ASSERT_OK_AND_ASSIGN(auto layered_split, + DataSplitImpl::Builder(delta_split->Partition(), delta_split->Bucket(), + delta_split->BucketPath(), std::move(layers)) + .WithSnapshot(delta_split->SnapshotId()) + .WithTotalBuckets(delta_split->TotalBuckets()) + .RawConvertible(false) + .Build()); + auto layered_plan = std::make_shared( + delta->SnapshotId(), std::vector>{layered_split}); + for (const auto& projection : + {std::vector{"id"}, std::vector{"id", "video"}}) { + ASSERT_OK_AND_ASSIGN(auto projected, ReadTable(table_path, projection, layered_plan)); + ASSERT_EQ(2, projected->length()); + for (const auto& chunk : projected->chunks()) { + auto rows = checked_pointer_cast(chunk); + ASSERT_EQ(rows->length(), rows->GetFieldByName("id")->null_count()); + } + } + // The delta has no older frame to fall back to. Only the placeholder has sequence -1. ASSERT_OK_AND_ASSIGN(auto delta_values, ReadTable(table_path, {"video", "_ROW_ID", "_SEQUENCE_NUMBER"}, delta)); @@ -1511,6 +1544,79 @@ TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { std::string_view(base).substr(0, 24)); } +TEST_P(BlobTableInteTest, VideoOnlyDeltaAlignsColumnsAndPreservesPartition) { + const arrow::FieldVector fields = { + arrow::field("id", arrow::int32()), arrow::field("part", arrow::int32()), + BlobUtils::ToArrowField("a", true), BlobUtils::ToArrowField("b", true)}; + CreateTable(fields, {"part"}, + {{Options::FILE_FORMAT, GetParam()}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, "a,b"}}); + const auto path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + auto ids = + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({fields[0]}), "[[10], [20]]") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto messages, WriteArray(path, {{"part", "7"}}, {"id"}, {ids})); + ASSERT_OK(Commit(path, messages)); + ScanContextBuilder scan_builder(path); + scan_builder.WithStreamingMode(true); + ASSERT_OK_AND_ASSIGN(auto context, scan_builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto scan, TableScan::Create(std::move(context))); + ASSERT_OK_AND_ASSIGN(auto initial, scan->CreatePlan()); + auto split = std::dynamic_pointer_cast(initial->Splits().at(0)); + auto anchor = split->DataFiles().at(0); + ASSERT_OK_AND_ASSIGN(int64_t first, anchor->NonNullFirstRowId()); + const int64_t seq = anchor->max_sequence_number + 1; + + // a has a placeholder and an explicit NULL. b supplies a frame only for the second row. + constexpr char overlay[] = + "\x02\x00\x03\x02\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00" + "IDEO\x01"; + ASSERT_OK_AND_ASSIGN(std::string frame, ReadJavaVideoFixture("video-v1-moov.hex")); + frame[27] = 2; // Zigzag-encoded run length 1. + auto add_file = [&](const std::string& column, const std::string& bytes, int64_t row, + int64_t count) -> Result> { + const auto name = column + ".video"; + PAIMON_RETURN_NOT_OK(dir_->GetFileSystem()->WriteFile( + PathUtil::JoinPath(split->BucketPath(), name), bytes, false)); + return DataFileMeta::ForAppend(name, bytes.size(), count, SimpleStats::EmptyStats(), seq, + seq, anchor->schema_id, FileSource::Append(), std::nullopt, + std::nullopt, row, std::vector{column}); + }; + ASSERT_OK_AND_ASSIGN(auto a, + add_file("a", std::string(overlay, sizeof(overlay) - 1), first, 2)); + ASSERT_OK_AND_ASSIGN(auto b, add_file("b", frame, first + 1, 1)); + ASSERT_OK(Commit(path, {std::make_shared( + split->Partition(), split->Bucket(), split->TotalBuckets(), + DataIncrement({a, b}, {}, {}), CompactIncrement({}, {}, {}))})); + ASSERT_OK_AND_ASSIGN(auto delta, scan->CreatePlan()); + for (const std::vector& projection : std::vector>{ + {"a", "b", "_ROW_ID", "part", "id"}, {"part"}, {"id"}}) { + ASSERT_OK_AND_ASSIGN(auto result, ReadTable(path, projection, delta)); + auto rows = checked_pointer_cast( + arrow::Concatenate(result->chunks()).ValueOrDie()); + ASSERT_EQ(2, rows->length()); + if (auto part = rows->GetFieldByName("part")) { + ASSERT_TRUE(part->Equals( + arrow::ipc::internal::json::ArrayFromJSON(arrow::int32(), "[7,7]").ValueOrDie())); + } + if (auto id = rows->GetFieldByName("id")) { + ASSERT_EQ(2, id->null_count()); + } + if (auto videos = rows->GetFieldByName("b")) { + ASSERT_TRUE(videos->IsNull(0)); + ASSERT_FALSE(videos->IsNull(1)); + ASSERT_EQ(2, rows->GetFieldByName("a")->null_count()); + auto row_ids = checked_pointer_cast(rows->GetFieldByName("_ROW_ID")); + ASSERT_EQ(first, row_ids->Value(0)); + ASSERT_EQ(first + 1, row_ids->Value(1)); + } + } +} + TEST_P(BlobTableInteTest, TestOpenVideoFilesByRowRange) { const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), BlobUtils::ToArrowField("video", /*nullable=*/true)}; @@ -2627,7 +2733,8 @@ TEST_P(BlobTableInteTest, TestDataEvolutionBlobPartialUpdateAllPlaceholderRowTra // the base layer itself holds a placeholder at row 1, so after the second layer also // leaves it untouched, row 1 is a placeholder in every layer - auto base_array = MakeBlobUpdateArray(fields[1], {"blob_a", "PH", "blob_c"}); + const std::string large_blob(1 << 20, 'a'); + auto base_array = MakeBlobUpdateArray(fields[1], {large_blob, "PH", "blob_c"}); ASSERT_OK_AND_ASSIGN(auto commit_msgs0, WriteArray(table_path, {}, {"b0"}, {base_array})); SetFirstRowId(/*reset_first_row_id=*/0, commit_msgs0); ASSERT_OK(Commit(table_path, commit_msgs0)); @@ -2652,7 +2759,17 @@ TEST_P(BlobTableInteTest, TestDataEvolutionBlobPartialUpdateAllPlaceholderRowTra struct_array->GetFieldByName(SpecialFields::SequenceNumber().Name())); ASSERT_TRUE(blob_col && row_id_col && seq_col); - ASSERT_EQ(blob_col->GetString(0), "blob_a"); + ASSERT_EQ(blob_col->GetString(0), large_blob); + ASSERT_OK_AND_ASSIGN(auto plan, ScanTable(table_path)); + std::shared_ptr measured_pool = GetMemoryPool(); + ReadContextBuilder builder(table_path); + builder.WithMemoryPool(measured_pool).SetReadFieldNames({"_SEQUENCE_NUMBER"}); + ASSERT_OK_AND_ASSIGN(auto read_context, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto read, TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(auto reader, read->CreateReader(plan->Splits())); + ASSERT_OK_AND_ASSIGN(auto sequence_only, ReadResultCollector::CollectResult(std::move(reader))); + ASSERT_EQ(3, sequence_only->length()); + ASSERT_LT(measured_pool->MaxMemoryUsage(), large_blob.size()); ASSERT_EQ(blob_col->GetString(2), "update_c"); // the all-placeholder row: null blob, row id kept, sequence number -1 ASSERT_TRUE(blob_col->IsNull(1));