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 1/9] 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 2/9] 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 3/9] 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 4/9] 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 5/9] 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 6/9] 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 7/9] 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 8/9] 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 9/9] 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") {