diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index d55a141c1..08acada11 100644 --- a/docs/source/user_guide/read.rst +++ b/docs/source/user_guide/read.rst @@ -331,6 +331,25 @@ 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++ reads scalar BLOB columns using the same ``moov``-based v1 layout +as Java (29-byte footer). The estimated peak memory for indexes is limited to 64 MiB. + +Reimport older ``.video`` files with a Java reader for the original layout and a +current Java writer. Regenerate stored frame descriptors and verify row counts, +frame ordinals and row alignment before switching to the new files. + +Non-null rows return frame descriptors even with ``blob-as-descriptor=false``. +Open them with ``Blob::FromDescriptor()``. Use ``FrameIndex()`` for the zero-based +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: 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/io/buffered_input_stream.h b/include/paimon/io/buffered_input_stream.h index 6b172cb96..fa0af44a5 100644 --- a/include/paimon/io/buffered_input_stream.h +++ b/include/paimon/io/buffered_input_stream.h @@ -70,6 +70,8 @@ class PAIMON_EXPORT BufferedInputStream : public InputStream { static constexpr int64_t DEFAULT_BUFFER_SIZE = 8192; private: + friend class FileOffsetInputStream; + /// Fill the internal buffer from the underlying stream. Status Fill(); diff --git a/include/paimon/io/file_offset_input_stream.h b/include/paimon/io/file_offset_input_stream.h new file mode 100644 index 000000000..8fc155b89 --- /dev/null +++ b/include/paimon/io/file_offset_input_stream.h @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#pragma once + +#include + +#include "paimon/fs/file_system.h" + +namespace paimon { + +/// A stream whose position zero can be at an offset in the file identified by GetUri(). +/// Wrappers that preserve positions forward the backing stream's file offset. +class PAIMON_EXPORT FileOffsetInputStream : public InputStream { + public: + ~FileOffsetInputStream() override = default; + + /// Returns the nonnegative backing-file offset of position zero. + virtual Result GetFileOffset() const = 0; + + /// Ordinary whole-file streams start at offset zero. + static Result GetFileOffset(const InputStream& stream); +}; + +} // namespace paimon diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt index 4ab30167d..e0c645051 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 @@ -1144,6 +1145,8 @@ if(PAIMON_BUILD_TESTS) if(PAIMON_ENABLE_OSS OR PAIMON_ENABLE_S3) list(APPEND PAIMON_OBJECT_STORE_FS_TEST_SOURCES common/fs/object_store_file_system_test.cpp) + set(PAIMON_OBJECT_STORE_FS_TEST_LINK_LIBS + ${PAIMON_BLOB_FILE_FORMAT_STATIC_LINK_LIBS}) endif() add_paimon_test(fs_test @@ -1158,6 +1161,7 @@ if(PAIMON_BUILD_TESTS) paimon_shared ${PAIMON_LOCAL_FILE_SYSTEM_STATIC_LINK_LIBS} ${PAIMON_JINDO_FS_TEST_LINK_LIBS} + ${PAIMON_OBJECT_STORE_FS_TEST_LINK_LIBS} test_utils_static ${GTEST_LINK_TOOLCHAIN} EXTRA_INCLUDES diff --git a/src/paimon/common/data/blob.cpp b/src/paimon/common/data/blob.cpp index 707dd475d..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)); @@ -89,6 +102,22 @@ const std::string& Blob::Uri() const { return impl_->Uri(); } +bool Blob::IsVideoFrame() const { + return impl_->VideoFrame() != nullptr; +} + +int64_t Blob::FrameIndex() const { + return impl_->VideoFrame() ? impl_->VideoFrame()->FrameIndex() : -1; +} + +int64_t Blob::MoovOffset() const { + return impl_->VideoFrame() ? impl_->VideoFrame()->MoovOffset() : 0; +} + +int64_t Blob::MoovLength() const { + return impl_->VideoFrame() ? impl_->VideoFrame()->MoovLength() : 0; +} + Result> Blob::NewInputStream( const std::shared_ptr& fs) const { if (fs == nullptr) { 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 5a020c9fc..947575ede 100644 --- a/src/paimon/common/data/blob_descriptor.cpp +++ b/src/paimon/common/data/blob_descriptor.cpp @@ -22,6 +22,7 @@ #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" @@ -73,6 +74,12 @@ PAIMON_UNIQUE_PTR BlobDescriptor::Serialize(const std::shared_ptr> BlobDescriptor::Deserialize(const char* buffer, uint64_t size) { + 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); @@ -91,6 +98,13 @@ 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()); + 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()); @@ -99,7 +113,7 @@ Result> BlobDescriptor::Deserialize(const char* } 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); diff --git a/src/paimon/common/data/blob_utils.cpp b/src/paimon/common/data/blob_utils.cpp index fd12cbcd9..930b2a58b 100644 --- a/src/paimon/common/data/blob_utils.cpp +++ b/src/paimon/common/data/blob_utils.cpp @@ -30,6 +30,7 @@ #include "fmt/format.h" #include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_view_struct.h" +#include "paimon/common/data/video_frame_descriptor.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" @@ -194,8 +195,27 @@ bool BlobUtils::IsBlobMetadata(const std::shared_ptr BlobUtils::GetVideoFrameFields( + const std::map& options) { + auto it = options.find(BlobDefs::kVideoFrameFieldOption); + if (it == options.end()) { + return {}; + } + auto names = StringUtils::Split(it->second, ","); + for (auto& name : names) { + StringUtils::Trim(&name); + } + std::set fields(names.begin(), names.end()); + fields.erase(""); + return {fields.begin(), fields.end()}; +} + +bool BlobUtils::IsVideoFile(const std::string& file_name) { + return StringUtils::EndsWith(file_name, ".video"); +} + bool BlobUtils::IsBlobFile(const std::string& file_name) { - return StringUtils::EndsWith(file_name, ".blob"); + return StringUtils::EndsWith(file_name, ".blob") || IsVideoFile(file_name); } std::shared_ptr BlobUtils::ToArrowField( @@ -206,6 +226,14 @@ std::shared_ptr BlobUtils::ToArrowField( std::make_shared(metadata)); } +Result BlobUtils::IsBlobReference(std::string_view bytes) { + if (VideoFrameDescriptor::HasMagic(bytes.data(), bytes.size())) { + PAIMON_RETURN_NOT_OK(VideoFrameDescriptor::Deserialize(bytes.data(), bytes.size())); + return true; + } + return BlobDescriptor::IsBlobDescriptor(bytes.data(), bytes.size()); +} + Status BlobUtils::ValidateBlobInlineFields(const std::shared_ptr& struct_array, const std::set& field_names, const std::string& config_label) { @@ -233,7 +261,7 @@ Status BlobUtils::ValidateBlobInlineFields(const std::shared_ptrGetView(row); Result valid = is_descriptor - ? BlobDescriptor::IsBlobDescriptor(value.data(), value.size()) + ? IsBlobReference(value) : BlobViewStruct::IsBlobViewStruct(value.data(), value.size()); PAIMON_ASSIGN_OR_RAISE(bool is_valid, std::move(valid)); if (!is_valid) { diff --git a/src/paimon/common/data/blob_utils.h b/src/paimon/common/data/blob_utils.h index 8292c1085..1b57af0d1 100644 --- a/src/paimon/common/data/blob_utils.h +++ b/src/paimon/common/data/blob_utils.h @@ -20,9 +20,11 @@ #pragma once #include +#include #include #include #include +#include #include #include @@ -93,7 +95,12 @@ class PAIMON_EXPORT BlobUtils { /// BOOLEAN, TINYINT, SMALLINT, INT, BIGINT, DATE, DECIMAL, CHAR/VARCHAR and BINARY/VARBINARY. static bool IsSupportedMapBlobKeyType(const arrow::DataType& key_type); static bool IsBlobMetadata(const std::shared_ptr& metadata); + static std::vector GetVideoFrameFields( + const std::map& options); + + static bool IsVideoFile(const std::string& file_name); static bool IsBlobFile(const std::string& file_name); + static Result IsBlobReference(std::string_view bytes); static std::shared_ptr ToArrowField( const std::string& field_name, bool nullable = false, diff --git a/src/paimon/common/data/video_frame_descriptor.cpp b/src/paimon/common/data/video_frame_descriptor.cpp new file mode 100644 index 000000000..9cfe92691 --- /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 && buffer[0] == kVersion && + std::string_view(buffer + sizeof(kVersion), kMagic.size()) == kMagic; +} + +Result> VideoFrameDescriptor::Deserialize(const char* buffer, + uint64_t size) { + if (size < kFixedSize || !HasMagic(buffer, size)) { + 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/common/fs/object_store_file_system_test.cpp b/src/paimon/common/fs/object_store_file_system_test.cpp index 880d02bd2..6f3970a8e 100644 --- a/src/paimon/common/fs/object_store_file_system_test.cpp +++ b/src/paimon/common/fs/object_store_file_system_test.cpp @@ -30,7 +30,10 @@ #include #include +#include "paimon/format/file_format.h" +#include "paimon/format/file_format_factory.h" #include "paimon/testing/utils/testharness.h" +#include "paimon/testing/utils/video_test_utils.h" namespace paimon::test { namespace { @@ -276,6 +279,28 @@ TEST(ObjectStoreInputStreamTest, TestShortReadFails) { "range read for s3://bucket/file returned"); } +TEST(ObjectStoreInputStreamTest, VideoReaderOpensWithTwoRangeRequests) { + auto client = std::make_shared(); + ASSERT_OK_AND_ASSIGN(client->objects_["part.video"], ReadJavaVideoFixture("video-v1-moov.hex")); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + + ObjectStoreFileSystem default_fs("s3", client); + ObjectStoreFileSystem no_read_ahead_fs("s3", client, 0); + for (auto* fs : {&default_fs, &no_read_ahead_fs}) { + SCOPED_TRACE(fs == &default_fs ? "default read-ahead" : "no read-ahead budget"); + client->ranges_.clear(); + ASSERT_OK_AND_ASSIGN(auto input, fs->Open("s3://bucket/part.video")); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(std::move(input))); + ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); + ASSERT_EQ(rows, 2u); + // The Java fixture has 24 bytes of payload, six bytes of indexes and a 29-byte footer. + ASSERT_EQ(client->ranges_.size(), 2u); + ASSERT_EQ(client->ranges_[0], Range(30, 29)); + ASSERT_EQ(client->ranges_[1].first, 24); + } +} + TEST(ObjectStoreInputStreamTest, TestSequentialReadAheadGrows) { auto client = std::make_shared(); client->objects_["file"] = std::string(1024 * 1024, 'x'); diff --git a/src/paimon/common/io/buffered_input_stream.cpp b/src/paimon/common/io/buffered_input_stream.cpp index e02620c0b..3cef58ea0 100644 --- a/src/paimon/common/io/buffered_input_stream.cpp +++ b/src/paimon/common/io/buffered_input_stream.cpp @@ -93,7 +93,7 @@ Result BufferedInputStream::Read(char* buffer, int64_t size) { } Result BufferedInputStream::Read(char* buffer, int64_t size, int64_t offset) { - return Status::Invalid("BufferedInputStream does not support Read from offset"); + return in_->Read(buffer, size, offset); } void BufferedInputStream::ReadAsync(char* buffer, int64_t size, int64_t offset, diff --git a/src/paimon/common/io/buffered_input_stream_test.cpp b/src/paimon/common/io/buffered_input_stream_test.cpp index 0f6c9ef95..e1691cf58 100644 --- a/src/paimon/common/io/buffered_input_stream_test.cpp +++ b/src/paimon/common/io/buffered_input_stream_test.cpp @@ -53,8 +53,10 @@ TEST(BufferedInputStreamTest, TestSimple) { ASSERT_EQ(6, input_stream->GetPos().value()); // read from pos 1 - ASSERT_NOK_WITH_MSG(input_stream->Read(value.data(), value.size(), /*offset=*/1), - "BufferedInputStream does not support Read from offset"); + ASSERT_OK_AND_ASSIGN(int64_t bytes_read, + input_stream->Read(value.data(), value.size(), /*offset=*/1)); + ASSERT_EQ(3, bytes_read); + ASSERT_EQ("bcd", value); ASSERT_EQ(6, input_stream->GetPos().value()); // seek to pos 3 diff --git a/src/paimon/common/io/cache_input_stream.h b/src/paimon/common/io/cache_input_stream.h index 015b082c3..9b738239f 100644 --- a/src/paimon/common/io/cache_input_stream.h +++ b/src/paimon/common/io/cache_input_stream.h @@ -23,11 +23,11 @@ #include "paimon/common/utils/math.h" #include "paimon/common/utils/read_ahead_cache.h" -#include "paimon/fs/file_system.h" +#include "paimon/io/file_offset_input_stream.h" namespace paimon { -class CacheInputStream : public InputStream { +class CacheInputStream : public FileOffsetInputStream { public: CacheInputStream(std::unique_ptr input_stream, const std::shared_ptr& cache) @@ -89,6 +89,10 @@ class CacheInputStream : public InputStream { return input_stream_->GetUri(); } + Result GetFileOffset() const override { + return FileOffsetInputStream::GetFileOffset(*input_stream_); + } + Result Length() const override { return input_stream_->Length(); } diff --git a/src/paimon/common/io/cache_input_stream_test.cpp b/src/paimon/common/io/cache_input_stream_test.cpp index 4c05c57c3..7d4022975 100644 --- a/src/paimon/common/io/cache_input_stream_test.cpp +++ b/src/paimon/common/io/cache_input_stream_test.cpp @@ -26,10 +26,12 @@ #include "gtest/gtest.h" #include "paimon/common/factories/io_hook.h" +#include "paimon/common/io/offset_input_stream.h" #include "paimon/common/utils/read_ahead_cache.h" #include "paimon/common/utils/scope_guard.h" #include "paimon/fs/file_system.h" #include "paimon/fs/file_system_factory.h" +#include "paimon/io/buffered_input_stream.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/memory/memory_pool.h" #include "paimon/testing/utils/io_exception_helper.h" @@ -121,6 +123,20 @@ TEST_F(CacheInputStreamTest, TestReadWithOffsetNullCache) { ASSERT_EQ(buffer, "cdefg"); } +TEST_F(CacheInputStreamTest, CachedBufferedSliceKeepsFileOffset) { + ASSERT_OK_AND_ASSIGN(std::shared_ptr slice, + OffsetInputStream::Create(OpenFile(), /*length=*/8, /*offset=*/5)); + auto cache = std::make_shared(slice, CacheConfig(), 8, pool_); + ASSERT_OK(cache->AddRanges({{0, 8}})); + CacheInputStream stream(std::make_unique(slice, 8, pool_.get()), cache); + std::string bytes(4, '\0'); + ASSERT_OK_AND_ASSIGN(int64_t size, stream.Read(bytes.data(), bytes.size(), /*offset=*/0)); + ASSERT_EQ(size, 4); + ASSERT_EQ(bytes, content_.substr(5, 4)); + ASSERT_OK_AND_ASSIGN(int64_t base, stream.GetFileOffset()); + ASSERT_EQ(base, 5); +} + // Test Read(offset) with cache hit → memcpy from cache TEST_F(CacheInputStreamTest, TestReadWithOffsetCacheHit) { // Cache range [2, 5) i.e. offset=2, length=5 diff --git a/src/paimon/common/io/offset_input_stream.cpp b/src/paimon/common/io/offset_input_stream.cpp index fe7d09673..dc7362381 100644 --- a/src/paimon/common/io/offset_input_stream.cpp +++ b/src/paimon/common/io/offset_input_stream.cpp @@ -19,13 +19,30 @@ #include "paimon/common/io/offset_input_stream.h" +#include #include #include "fmt/format.h" #include "paimon/common/utils/math.h" +#include "paimon/io/buffered_input_stream.h" #include "paimon/macros.h" namespace paimon { +Result FileOffsetInputStream::GetFileOffset(const InputStream& stream) { + if (const auto* view = dynamic_cast(&stream)) { + PAIMON_ASSIGN_OR_RAISE(int64_t offset, view->GetFileOffset()); + if (offset < 0) { + return Status::Invalid("negative backing file offset"); + } + return offset; + } + // BufferedInputStream is an existing public wrapper. Preserve its class layout and vtable. + if (const auto* buffered = dynamic_cast(&stream)) { + return GetFileOffset(*buffered->in_); + } + return 0; +} + Result> OffsetInputStream::Create( const std::shared_ptr& wrapped, int64_t length, int64_t offset) { if (PAIMON_UNLIKELY(wrapped == nullptr)) { @@ -126,6 +143,14 @@ Result OffsetInputStream::GetUri() const { return wrapped_->GetUri(); } +Result OffsetInputStream::GetFileOffset() const { + PAIMON_ASSIGN_OR_RAISE(int64_t base, FileOffsetInputStream::GetFileOffset(*wrapped_)); + if (base > std::numeric_limits::max() - offset_) { + return Status::Invalid("file slice offset overflows int64"); + } + return base + offset_; +} + Result OffsetInputStream::GetPos() const { return inner_position_; } diff --git a/src/paimon/common/io/offset_input_stream.h b/src/paimon/common/io/offset_input_stream.h index 7c2a4db66..276db6116 100644 --- a/src/paimon/common/io/offset_input_stream.h +++ b/src/paimon/common/io/offset_input_stream.h @@ -24,7 +24,7 @@ #include #include -#include "paimon/fs/file_system.h" +#include "paimon/io/file_offset_input_stream.h" #include "paimon/result.h" #include "paimon/status.h" #include "paimon/visibility.h" @@ -33,7 +33,7 @@ namespace paimon { /// An `InputStream` wrapping another `InputStream` with offset and length. /// @note Not safe for concurrent or interleaved use with other views of the wrapped stream: Seek /// and sequential Read share the wrapped stream's position and may read from the wrong offset. -class PAIMON_EXPORT OffsetInputStream : public InputStream { +class PAIMON_EXPORT OffsetInputStream : public FileOffsetInputStream { public: static Result> Create( const std::shared_ptr& wrapped, int64_t length, int64_t offset); @@ -59,6 +59,9 @@ class PAIMON_EXPORT OffsetInputStream : public InputStream { Result GetUri() const override; + /// Offset of this view in the file identified by GetUri(), including enclosing slices. + Result GetFileOffset() const override; + private: OffsetInputStream(const std::shared_ptr& wrapped, int64_t length, int64_t offset); Status AssertBoundary(int64_t inner_pos) const; diff --git a/src/paimon/common/reader/blob_fallback_batch_reader.cpp b/src/paimon/common/reader/blob_fallback_batch_reader.cpp index 24d902169..60c7c7d49 100644 --- a/src/paimon/common/reader/blob_fallback_batch_reader.cpp +++ b/src/paimon/common/reader/blob_fallback_batch_reader.cpp @@ -42,7 +42,8 @@ namespace paimon { Result> BlobFallbackBatchReader::Create( std::vector>&& sequence_groups, const std::shared_ptr& read_schema, int32_t read_batch_size, - const std::shared_ptr& arrow_pool) { + const std::shared_ptr& arrow_pool, + std::map> partition_values) { if (sequence_groups.empty()) { return Status::Invalid("Blob fallback needs at least one sequence group."); } @@ -78,7 +79,7 @@ Result> BlobFallbackBatchReader::Create if (segment.reader != nullptr && segment.blob_context == nullptr) { return Status::Invalid("Blob fallback file segment needs a blob read context."); } - if (segment.reader == nullptr && segment.gap_selected_ranges.empty()) { + if (!segment.reader && !segment.open_file && segment.gap_selected_ranges.empty()) { return Status::Invalid( "Blob fallback gap segment should cover at least one selected row id."); } @@ -87,9 +88,11 @@ Result> BlobFallbackBatchReader::Create cursor.segments = std::move(segments); groups.push_back(std::move(cursor)); } - return std::unique_ptr(new BlobFallbackBatchReader( + auto reader = std::unique_ptr(new BlobFallbackBatchReader( std::move(groups), read_schema, blob_field_idx, row_id_field_idx, seq_num_field_idx, read_batch_size, arrow_pool)); + reader->partition_values_ = std::move(partition_values); + return reader; } BlobFallbackBatchReader::BlobFallbackBatchReader( @@ -140,6 +143,19 @@ Result BlobFallbackBatchReader::FillWindow(size_t group_idx, int64_t wa break; } Segment& segment = cursor.segments[cursor.segment_idx]; + if (segment.open_file) { + // The newest layer sets the window. Return available rows before opening another file. + if (group_idx == 0 && collected > 0) { + break; + } + auto reader = segment.open_file(&segment.blob_context); + if (!reader.ok()) { + Close(); + return reader.status(); + } + segment.reader = std::move(reader).value(); + segment.open_file = nullptr; + } if (segment.reader == nullptr) { // gap segment: all rows are placeholders, stepped range by range so the row ids // stay available for all-placeholder rows @@ -300,6 +316,13 @@ Result> BlobFallbackBatchReader::AssembleColumn( int32_t field_idx, const std::vector& group_choice, const std::vector>& group_chunks) const { const auto row_count = static_cast(group_choice.size()); + auto partition = partition_values_.find(field_idx); + if (partition != partition_values_.end()) { + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( + std::shared_ptr values, + arrow::MakeArrayFromScalar(*partition->second, row_count, arrow_pool_.get())); + return values; + } arrow::ArrayVector pieces; std::vector cursors(group_chunks.size()); int64_t run_start = 0; @@ -442,6 +465,7 @@ void BlobFallbackBatchReader::Close() { } } } + groups_.clear(); closed_ = true; } diff --git a/src/paimon/common/reader/blob_fallback_batch_reader.h b/src/paimon/common/reader/blob_fallback_batch_reader.h index 0967bbe22..c0df585da 100644 --- a/src/paimon/common/reader/blob_fallback_batch_reader.h +++ b/src/paimon/common/reader/blob_fallback_batch_reader.h @@ -19,6 +19,8 @@ #pragma once +#include +#include #include #include @@ -60,20 +62,23 @@ namespace paimon { /// Older groups use a shared BlobReadContext to advance resolved rows without reading their /// payloads and to bound each batch by the current window and unresolved row runs. /// 4. A row that is a placeholder in every group degrades to a null blob: it keeps its -/// _ROW_ID, reports -1 as its _SEQUENCE_NUMBER, and returns null for every other field. +/// _ROW_ID, reports -1 as its _SEQUENCE_NUMBER, and preserves split partition values. class BlobFallbackBatchReader : public BatchReader { public: /// One piece of a sequence group: either a reader over a single blob file (already wrapped /// with the usual per-file mapping readers and row selection), or a virtual gap standing for /// row ids the group's files do not cover. Segments must be ordered by ascending row id. struct Segment { - /// File segment: emits the rows of one blob file. Null for a gap segment. + /// Open file segment. A deferred file installs its reader on first use. std::unique_ptr reader; /// Gap segment only: the selected row ids the gap emits (all placeholders), as sorted /// disjoint ranges. Must not be empty for a gap segment. std::vector gap_selected_ranges; /// File segment only: shared with the bottom blob reader before any per-file wrapping. std::shared_ptr blob_context = nullptr; + /// Opens the file and returns the context shared with its bottom reader. + std::function>(std::shared_ptr*)> + open_file = nullptr; }; /// `sequence_groups` must be ordered by descending max sequence number and contain at least @@ -85,7 +90,8 @@ class BlobFallbackBatchReader : public BatchReader { static Result> Create( std::vector>&& sequence_groups, const std::shared_ptr& read_schema, int32_t read_batch_size, - const std::shared_ptr& arrow_pool); + const std::shared_ptr& arrow_pool, + std::map> partition_values = {}); Result NextBatch() override; @@ -153,7 +159,7 @@ class BlobFallbackBatchReader : public BatchReader { /// Assembles one output column by stitching, per run of rows choosing the same group, /// slices of that group's chunks. For rows choosing no group (placeholder in every layer), - /// _ROW_ID is kept, _SEQUENCE_NUMBER becomes -1, and every other field becomes null. + /// _ROW_ID and partition values are kept and _SEQUENCE_NUMBER becomes -1. Result> AssembleColumn( int32_t field_idx, const std::vector& group_choice, const std::vector>& group_chunks) const; @@ -174,6 +180,7 @@ class BlobFallbackBatchReader : public BatchReader { const int32_t read_batch_size_; std::shared_ptr arrow_pool_; std::shared_ptr finished_reader_metrics_; + std::map> partition_values_; bool closed_ = false; }; diff --git a/src/paimon/common/reader/blob_read_context.h b/src/paimon/common/reader/blob_read_context.h index 57fc01141..f061fdbfc 100644 --- a/src/paimon/common/reader/blob_read_context.h +++ b/src/paimon/common/reader/blob_read_context.h @@ -41,6 +41,8 @@ struct BlobBatchRequest { /// Access is confined to the thread reading that segment. struct BlobReadContext { std::optional request; + // The hidden BLOB column only distinguishes placeholders from resolved rows. + bool placeholder_only = false; }; /// Internal builder hook used before the format reader is wrapped. Only the blob builder diff --git a/src/paimon/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/common/reader/prefetch_file_batch_reader_impl.cpp b/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp index b3d89b2f7..77c4186cc 100644 --- a/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp +++ b/src/paimon/common/reader/prefetch_file_batch_reader_impl.cpp @@ -38,6 +38,7 @@ #include "paimon/common/utils/scope_guard.h" #include "paimon/format/reader_builder.h" #include "paimon/fs/file_system.h" +#include "paimon/io/file_offset_input_stream.h" #include "paimon/memory/memory_pool.h" namespace arrow { @@ -103,7 +104,7 @@ void RecordLatency(uint64_t latency_us, std::atomic* count, sum_us->fetch_add(latency_us, kMetricsMemoryOrder); } -class MetricsInputStream : public InputStream { +class MetricsInputStream : public FileOffsetInputStream { public: MetricsInputStream(const std::shared_ptr& stream, const std::shared_ptr& metrics) @@ -162,6 +163,10 @@ class MetricsInputStream : public InputStream { return stream_->GetUri(); } + Result GetFileOffset() const override { + return FileOffsetInputStream::GetFileOffset(*stream_); + } + Result Length() const override { return stream_->Length(); } diff --git a/src/paimon/common/utils/delta_varint_compressor.cpp b/src/paimon/common/utils/delta_varint_compressor.cpp index 89f908da9..e9f5f634c 100644 --- a/src/paimon/common/utils/delta_varint_compressor.cpp +++ b/src/paimon/common/utils/delta_varint_compressor.cpp @@ -52,16 +52,20 @@ std::vector DeltaVarintCompressor::Compress(const std::vector& da } Result> DeltaVarintCompressor::Decompress(const std::vector& bytes) { - if (bytes.empty()) { + return Decompress(bytes.data(), bytes.size()); +} + +Result> DeltaVarintCompressor::Decompress(const char* data, size_t size) { + if (size == 0) { return std::vector(); } // 1. Decode ZigZag + Varint → delta std::vector deltas; - deltas.reserve(bytes.size()); + deltas.reserve(size); size_t pos = 0; - while (pos < bytes.size()) { - PAIMON_ASSIGN_OR_RAISE(int64_t delta, DecodeVarint(bytes, &pos)); + while (pos < size) { + PAIMON_ASSIGN_OR_RAISE(int64_t delta, DecodeVarint(data, size, &pos)); deltas.push_back(delta); } @@ -89,14 +93,17 @@ void DeltaVarintCompressor::EncodeVarint(int64_t value, std::vector* out) out->push_back(static_cast(tmp)); } -Result DeltaVarintCompressor::DecodeVarint(const std::vector& in, size_t* pos) { +Result DeltaVarintCompressor::DecodeVarint(const char* data, size_t size, size_t* pos) { uint64_t result = 0; int32_t shift = 0; while (true) { - if (*pos >= in.size()) { + if (*pos >= size) { return Status::Invalid("Unexpected end of input"); } - char byte = in[(*pos)++]; + const auto byte = static_cast(data[(*pos)++]); + if (shift == 63 && byte > 1) { + return Status::Invalid("Varint overflow"); + } // Extract 7 bits result |= (static_cast(byte & 0x7F) << shift); // MSB is 0, end of encoding @@ -104,9 +111,6 @@ Result DeltaVarintCompressor::DecodeVarint(const std::vector& in, break; } shift += 7; - if (shift > 63) { - return Status::Invalid("Varint overflow"); - } } return UnZigZag(result); } diff --git a/src/paimon/common/utils/delta_varint_compressor.h b/src/paimon/common/utils/delta_varint_compressor.h index a66cbcf31..268ace63b 100644 --- a/src/paimon/common/utils/delta_varint_compressor.h +++ b/src/paimon/common/utils/delta_varint_compressor.h @@ -34,12 +34,13 @@ class PAIMON_EXPORT DeltaVarintCompressor { static std::vector Compress(const std::vector& data); // Decompresses a byte array back to the original long array static Result> Decompress(const std::vector& bytes); + static Result> Decompress(const char* data, size_t size); private: // Encodes a long value using ZigZag and Varints static void EncodeVarint(int64_t value, std::vector* out); // Decodes a Varints-encoded value and reverses ZigZag transformation - static Result DecodeVarint(const std::vector& in, size_t* pos); + static Result DecodeVarint(const char* data, size_t size, size_t* pos); inline static uint64_t ZigZag(int64_t value) { return ((static_cast(value) << 1) ^ (value >> 63)); diff --git a/src/paimon/core/io/field_mapping_reader.cpp b/src/paimon/core/io/field_mapping_reader.cpp index e271a579c..adbbba37d 100644 --- a/src/paimon/core/io/field_mapping_reader.cpp +++ b/src/paimon/core/io/field_mapping_reader.cpp @@ -229,73 +229,74 @@ Result FieldMappingReader::NextBatchWithBitmap Result> FieldMappingReader::GenerateSinglePartitionArray( int32_t idx, int32_t batch_size) const { const auto& type = partition_info_.value().partition_read_schema[idx].Type(); - if (partition_.IsNullAt(partition_info_.value().idx_in_partition[idx])) { - // for null partition value - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( - std::shared_ptr null_array, - arrow::MakeArrayOfNull(type, batch_size, arrow_pool_.get())); - return null_array; + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr scalar, + ReadPartitionScalar(partition_, partition_info_->idx_in_partition[idx], type)); + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( + std::shared_ptr arrow_array, + arrow::MakeArrayFromScalar(*scalar, batch_size, arrow_pool_.get())); + return arrow_array; +} + +Result> FieldMappingReader::ReadPartitionScalar( + const BinaryRow& partition, int32_t index, const std::shared_ptr& type) { + if (partition.IsNullAt(index)) { + return arrow::MakeNullScalar(type); } auto type_id = type->id(); std::shared_ptr scalar; switch (type_id) { case arrow::Type::type::BOOL: { - bool value = partition_.GetBoolean(partition_info_.value().idx_in_partition[idx]); + bool value = partition.GetBoolean(index); scalar = std::make_shared(value); break; } case arrow::Type::type::INT8: { - int8_t value = partition_.GetByte(partition_info_.value().idx_in_partition[idx]); + int8_t value = partition.GetByte(index); scalar = std::make_shared(value); break; } case arrow::Type::type::INT16: { - int16_t value = partition_.GetShort(partition_info_.value().idx_in_partition[idx]); + int16_t value = partition.GetShort(index); scalar = std::make_shared(value); break; } case arrow::Type::type::INT32: { - int32_t value = partition_.GetInt(partition_info_.value().idx_in_partition[idx]); + int32_t value = partition.GetInt(index); scalar = std::make_shared(value); break; } case arrow::Type::type::INT64: { - int64_t value = partition_.GetLong(partition_info_.value().idx_in_partition[idx]); + int64_t value = partition.GetLong(index); scalar = std::make_shared(value); break; } case arrow::Type::type::STRING: { - BinaryString value = - partition_.GetString(partition_info_.value().idx_in_partition[idx]); + BinaryString value = partition.GetString(index); scalar = std::make_shared(value.ToString()); break; } case arrow::Type::type::BINARY: { - auto value = partition_.GetBinary(partition_info_.value().idx_in_partition[idx]); + auto value = partition.GetBinary(index); std::string value_str(value->data(), value->size()); scalar = std::make_shared(value_str); break; } case arrow::Type::type::DATE32: { - int32_t value = partition_.GetDate(partition_info_.value().idx_in_partition[idx]); + int32_t value = partition.GetDate(index); scalar = std::make_shared(value); break; } case arrow::Type::type::TIME32: { - int32_t value = partition_.GetInt(partition_info_.value().idx_in_partition[idx]); - scalar = std::make_shared( - value, partition_info_.value().partition_read_schema[idx].Type()); + int32_t value = partition.GetInt(index); + scalar = std::make_shared(value, type); break; } default: return Status::Invalid( - fmt::format("Not support arrow type {} for partition", - partition_info_.value().partition_read_schema[idx].Type()->ToString())); + fmt::format("Not support arrow type {} for partition", type->ToString())); } - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( - std::shared_ptr arrow_array, - arrow::MakeArrayFromScalar(*scalar, batch_size, arrow_pool_.get())); - return arrow_array; + return scalar; } Result> FieldMappingReader::GeneratePartitionArray( diff --git a/src/paimon/core/io/field_mapping_reader.h b/src/paimon/core/io/field_mapping_reader.h index fa976b2f6..db76c95c7 100644 --- a/src/paimon/core/io/field_mapping_reader.h +++ b/src/paimon/core/io/field_mapping_reader.h @@ -55,6 +55,9 @@ class FieldMappingReader : public FileBatchReader { std::set&& skip_map_selected_keys_filter_field_ids, const std::shared_ptr& arrow_pool); + static Result> ReadPartitionScalar( + const BinaryRow& partition, int32_t index, const std::shared_ptr& type); + Result NextBatch() override { return Status::Invalid( "paimon inner reader FieldMappingReader should use NextBatchWithBitmap"); diff --git a/src/paimon/core/operation/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/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index d13cb9199..6d7ab5b8c 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -54,6 +54,7 @@ #include "paimon/core/deletionvectors/apply_deletion_vector_batch_reader.h" #include "paimon/core/deletionvectors/bitmap_deletion_vector.h" #include "paimon/core/global_index/indexed_split_impl.h" +#include "paimon/core/io/field_mapping_reader.h" #include "paimon/core/io/file_index_evaluator.h" #include "paimon/core/io/file_index_options.h" #include "paimon/core/table/format/lazy_concat_batch_reader.h" @@ -420,6 +421,8 @@ Result> DataEvolutionSplitRead::InnerCreateReader( PAIMON_ASSIGN_OR_RAISE(std::vector>> split_by_row_id, MergeRangesAndSort(std::move(metas))); + const bool row_id_only = read_schema->num_fields() == 1 && + read_schema->field(0)->name() == SpecialFields::RowId().Name(); std::vector> sub_readers; for (const std::vector>& need_merge_files : split_by_row_id) { PAIMON_ASSIGN_OR_RAISE(std::optional group_selection, @@ -443,8 +446,9 @@ Result> DataEvolutionSplitRead::InnerCreateReader( DataEvolutionSplitRead group_read(path_factory_, context_, pool_, executor_); group_read.file_indexes_evaluated_ = true; group_read.group_selection_ = std::move(group_selection); - if (need_merge_files.size() == 1) { - // No need to merge fields, just create a single file reader + // A video-only delta can contain placeholders even when it has just one file. + if (need_merge_files.size() == 1 && + (row_id_only || !BlobUtils::IsVideoFile(need_merge_files[0]->file_name))) { PAIMON_ASSIGN_OR_RAISE( std::vector> raw_file_readers, group_read.CreateRawFileReaders(split_impl->Partition(), need_merge_files, @@ -688,6 +692,19 @@ DataEvolutionSplitRead::SplitFieldBunches( std::vector> fields_files; std::map> blob_bunch_map; std::optional expected_row_range; + // MergeRangesAndSort supplies one connected group. A dedicated-only update shares + // that group's row range across columns, even when each column covers only part of it. + if (!need_merge_files.empty() && + std::all_of(need_merge_files.begin(), need_merge_files.end(), + [](const auto& file) { return BlobUtils::IsBlobFile(file->file_name); })) { + for (const auto& file : need_merge_files) { + PAIMON_ASSIGN_OR_RAISE(Range range, file->NonNullRowIdRange()); + expected_row_range = expected_row_range + ? Range(std::min(expected_row_range->from, range.from), + std::max(expected_row_range->to, range.to)) + : range; + } + } for (const auto& file : need_merge_files) { if (BlobUtils::IsBlobFile(file->file_name)) { PAIMON_ASSIGN_OR_RAISE(int32_t field_id, blob_field_to_field_id(file)); @@ -1105,6 +1122,15 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea } } + // If no file supplies a projected column, one aligned bunch supplies the logical + // row count. DataEvolutionFileReader fills the missing columns with NULL. + if (!has_normal_file && !all_read_fields.empty() && read_fields_in_file.empty() && + file_idx + 1 == static_cast(fields_files.size()) && + std::dynamic_pointer_cast(bunch) && + std::all_of(reader_offsets.begin(), reader_offsets.end(), + [](int32_t offset) { return offset < 0; })) { + read_fields_in_file.push_back(SpecialFields::RowId()); + } if (!read_fields_in_file.empty()) { // create new FieldMappingReader for read partial fields auto file_read_schema = DataField::ConvertDataFieldsToArrowSchema(read_fields_in_file); @@ -1145,12 +1171,24 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea file_batch_readers[file_idx] = std::make_unique(std::move(sources), arrow_pool_); } else if (blob_bunch) { + // Fallback needs the value to distinguish placeholders from explicit NULLs + // even when only the winning sequence number is projected. + const bool placeholder_only = + std::none_of(file_read_schema->fields().begin(), + file_read_schema->fields().end(), BlobUtils::IsAnyBlobField); + if (placeholder_only) { + PAIMON_ASSIGN_OR_RAISE(DataField blob_field, + data_schema->GetField(first_file->write_cols->front())); + read_fields_in_file.push_back(std::move(blob_field)); + file_read_schema = + DataField::ConvertDataFieldsToArrowSchema(read_fields_in_file); + } PAIMON_ASSIGN_OR_RAISE(Range logical_range, blob_bunch->LogicalRange()); PAIMON_ASSIGN_OR_RAISE( file_batch_readers[file_idx], CreateBlobFallbackReader(partition, blob_bunch->Files(), logical_range, file_read_schema, row_ranges, data_file_path_factory, - group_dv_factory, group_dv)); + group_dv_factory, group_dv, placeholder_only)); } else { PAIMON_ASSIGN_OR_RAISE( std::vector> file_readers, @@ -1217,7 +1255,7 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR const std::optional>& row_ranges, const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, - const std::optional& group_dv) const { + const std::optional& group_dv, bool placeholder_only) const { if (files.empty()) { return Status::Invalid("Blob bunch should not be empty."); } @@ -1236,9 +1274,33 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR } sequence_groups[file->max_sequence_number].emplace_back(file_range.from, file); } - // the blob format reader must emit placeholder sentinels instead of failing on them - const std::map blob_format_options = { - {BlobDefs::kEmitPlaceholderSentinelKey, "true"}}; + auto split_read = + std::make_shared(path_factory_, context_, pool_, executor_); + split_read->file_indexes_evaluated_ = file_indexes_evaluated_; + split_read->group_selection_ = group_selection_; + const auto selected_ranges = + SelectedRangesInRange(union_first_row_id, union_last_row_id, row_ranges); + auto open_file = + [split_read, partition, file_read_schema, group_dv_factory, data_file_path_factory, + placeholder_only]( + const std::shared_ptr& file, const std::vector& ranges, + std::shared_ptr* context) -> Result> { + PAIMON_ASSIGN_OR_RAISE( + std::vector readers, + split_read->CreateRawFileReadersWithMeta( + partition, {file}, file_read_schema, /*predicate=*/nullptr, group_dv_factory, + ranges, data_file_path_factory, {{BlobDefs::kEmitPlaceholderSentinelKey, "true"}}, + /*attach_blob_context=*/true)); + if (readers.size() != 1) { + return Status::Invalid("Unexpected: blob fallback file reader was skipped."); + } + if (!readers[0].blob_context) { + return Status::Invalid("Blob fallback file segment needs a blob read context."); + } + readers[0].blob_context->placeholder_only = placeholder_only; + *context = std::move(readers[0].blob_context); + return std::move(readers[0].reader); + }; std::vector> groups; groups.reserve(sequence_groups.size()); for (auto& [max_sequence_number, group_files] : sequence_groups) { @@ -1276,24 +1338,15 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR BlobFallbackBatchReader::Segment{nullptr, std::move(gap_selected_ranges)}); } } - std::optional> file_ranges = - SelectedRangesInRange(union_first_row_id, union_last_row_id, row_ranges); - if (!SelectedRangesInRange(first_row_id, first_row_id + file->row_count - 1, - file_ranges) - .empty()) { - PAIMON_ASSIGN_OR_RAISE(std::vector file_readers, - CreateRawFileReadersWithMeta( - partition, {file}, file_read_schema, - /*predicate=*/nullptr, group_dv_factory, file_ranges, - data_file_path_factory, blob_format_options, - /*attach_blob_context=*/true)); - if (file_readers.size() != 1) { - return Status::Invalid("Unexpected: blob fallback file reader was skipped."); - } - segments.push_back( - BlobFallbackBatchReader::Segment{std::move(file_readers[0].reader), - {}, - std::move(file_readers[0].blob_context)}); + auto file_ranges = Range::And({Range(first_row_id, first_row_id + file->row_count - 1)}, + selected_ranges); + if (!file_ranges.empty()) { + BlobFallbackBatchReader::Segment segment; + segment.open_file = [open_file, file_meta = file, ranges = std::move(file_ranges)]( + std::shared_ptr* context) { + return open_file(file_meta, ranges, context); + }; + segments.push_back(std::move(segment)); } next_row_id = std::max(next_row_id, first_row_id + file->row_count); } @@ -1315,10 +1368,20 @@ Result> DataEvolutionSplitRead::CreateBlobFallbackR } groups.push_back(std::move(segments)); } - PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr fallback_reader, - BlobFallbackBatchReader::Create(std::move(groups), file_read_schema, - options_.GetReadBatchSize(), arrow_pool_)); + std::map> partition_values; + const auto& keys = context_->GetPartitionKeys(); + for (size_t i = 0; i < keys.size(); ++i) { + const int idx = file_read_schema->GetFieldIndex(keys[i]); + if (idx >= 0) { + PAIMON_ASSIGN_OR_RAISE(partition_values[idx], + FieldMappingReader::ReadPartitionScalar( + partition, i, file_read_schema->field(idx)->type())); + } + } + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr fallback_reader, + BlobFallbackBatchReader::Create(std::move(groups), file_read_schema, + options_.GetReadBatchSize(), arrow_pool_, + std::move(partition_values))); return std::move(fallback_reader); } diff --git a/src/paimon/core/operation/data_evolution_split_read.h b/src/paimon/core/operation/data_evolution_split_read.h index 70075fb7e..9cf498a12 100644 --- a/src/paimon/core/operation/data_evolution_split_read.h +++ b/src/paimon/core/operation/data_evolution_split_read.h @@ -313,7 +313,7 @@ class DataEvolutionSplitRead : public AbstractSplitRead { const std::optional>& row_ranges, const std::shared_ptr& data_file_path_factory, const DeletionVector::Factory& group_dv_factory, - const std::optional& group_dv) const; + const std::optional& group_dv, bool placeholder_only = false) const; /// Set only on a per-group reader after SelectByFileIndex has evaluated its indexes. /// Lazy child readers inherit it so no sidecar is reopened during reader construction. diff --git a/src/paimon/core/schema/schema_validation.cpp b/src/paimon/core/schema/schema_validation.cpp index b8319f6cf..563fa52a8 100644 --- a/src/paimon/core/schema/schema_validation.cpp +++ b/src/paimon/core/schema/schema_validation.cpp @@ -37,6 +37,7 @@ #include "arrow/type.h" #include "fmt/format.h" #include "fmt/ranges.h" +#include "paimon/common/data/blob_defs.h" #include "paimon/common/data/blob_utils.h" #include "paimon/common/data/shredding/map_shared_shredding_utils.h" #include "paimon/common/data/variant/variant_type_utils.h" @@ -935,45 +936,52 @@ Status SchemaValidation::ValidateBlobFields(const TableSchema& schema, const Cor const auto& configured_blob_names = options.GetBlobFields(); const auto& blob_descriptor_names = options.GetBlobDescriptorFields(); const auto& blob_view_names = options.GetBlobViewFields(); - if (configured_blob_names.empty() && blob_descriptor_names.empty() && blob_view_names.empty()) { + const auto video_frame_names = BlobUtils::GetVideoFrameFields(schema.Options()); + if (configured_blob_names.empty() && blob_descriptor_names.empty() && blob_view_names.empty() && + video_frame_names.empty()) { return Status::OK(); } + std::unordered_map storage_option_by_field; auto validate_blob_fields = [&](const std::vector& field_names, - const std::string& option_key, - bool allow_container_blob) -> Status { + const std::string& option_key) -> Status { if (field_names.empty()) { return Status::OK(); } PAIMON_RETURN_NOT_OK(ValidateNoDuplicateField(field_names, option_key)); PAIMON_ASSIGN_OR_RAISE(std::vector blob_fields, schema.GetFields(field_names)); + const bool is_blob_field_option = option_key == Options::BLOB_FIELD; for (const auto& blob_field : blob_fields) { - bool is_blob = allow_container_blob ? BlobUtils::IsAnyBlobField(blob_field.ArrowField()) + bool is_blob = is_blob_field_option ? BlobUtils::IsAnyBlobField(blob_field.ArrowField()) : BlobUtils::IsBlobField(blob_field.ArrowField()); if (!is_blob) { const std::string expected_type = - allow_container_blob ? "BLOB, ARRAY or MAP<..., BLOB>" : "BLOB"; + is_blob_field_option ? "BLOB, ARRAY or MAP<..., BLOB>" : "BLOB"; return Status::Invalid( fmt::format("Field '{}' in '{}' must be a {} field in table schema.", blob_field.Name(), option_key, expected_type)); } + // blob-field can also name a video column. The other storage modes are exclusive. + if (!is_blob_field_option) { + auto [it, inserted] = + storage_option_by_field.emplace(blob_field.Name(), option_key); + if (!inserted) { + return Status::Invalid( + fmt::format("Field '{}' in '{}' can not also be in '{}'.", + blob_field.Name(), option_key, it->second)); + } + } } return Status::OK(); }; - PAIMON_RETURN_NOT_OK(validate_blob_fields(configured_blob_names, Options::BLOB_FIELD, true)); + PAIMON_RETURN_NOT_OK(validate_blob_fields(configured_blob_names, Options::BLOB_FIELD)); PAIMON_RETURN_NOT_OK( - validate_blob_fields(blob_descriptor_names, Options::BLOB_DESCRIPTOR_FIELD, false)); - PAIMON_RETURN_NOT_OK(validate_blob_fields(blob_view_names, Options::BLOB_VIEW_FIELD, false)); - - std::set blob_descriptor_name_set(blob_descriptor_names.begin(), - blob_descriptor_names.end()); - for (const auto& blob_view_name : blob_view_names) { - if (blob_descriptor_name_set.count(blob_view_name) > 0) { - return Status::Invalid(fmt::format("Field '{}' in '{}' can not also be in '{}'.", - blob_view_name, Options::BLOB_VIEW_FIELD, - Options::BLOB_DESCRIPTOR_FIELD)); - } + validate_blob_fields(blob_descriptor_names, Options::BLOB_DESCRIPTOR_FIELD)); + PAIMON_RETURN_NOT_OK(validate_blob_fields(blob_view_names, Options::BLOB_VIEW_FIELD)); + PAIMON_RETURN_NOT_OK(validate_blob_fields(video_frame_names, BlobDefs::kVideoFrameFieldOption)); + if (!video_frame_names.empty() && !schema.PrimaryKeys().empty()) { + return Status::Invalid("video-frame-field only supports append-only tables"); } return Status::OK(); } diff --git a/src/paimon/core/table/append_only_file_store_table.cpp b/src/paimon/core/table/append_only_file_store_table.cpp index b8e3906f6..a2591effa 100644 --- a/src/paimon/core/table/append_only_file_store_table.cpp +++ b/src/paimon/core/table/append_only_file_store_table.cpp @@ -26,6 +26,7 @@ #include #include "fmt/format.h" +#include "paimon/common/data/blob_utils.h" #include "paimon/common/utils/checked_cast.h" #include "paimon/core/deletionvectors/bucketed_dv_maintainer.h" #include "paimon/core/index/index_file_handler.h" @@ -116,6 +117,15 @@ Result> AppendOnlyFileStoreTable::CreateWrite( write_schema = arrow::schema(write_fields); } + // A per-write override must not turn a persisted video column into an ordinary blob. + for (const auto* declaration : {&schema->Options(), &options.ToMap()}) { + for (const auto& name : BlobUtils::GetVideoFrameFields(*declaration)) { + if (!write_schema->GetAllFieldIndices(name).empty()) { + return Status::NotImplemented( + fmt::format("writing video-frame-field '{}' is not supported", name)); + } + } + } std::shared_ptr realtime_schema_layout; if (ctx.GetRealtimeContext()) { const RealtimeStoreMode mode = diff --git a/src/paimon/core/utils/blob_view_lookup.cpp b/src/paimon/core/utils/blob_view_lookup.cpp index 30999fe62..d60c94c13 100644 --- a/src/paimon/core/utils/blob_view_lookup.cpp +++ b/src/paimon/core/utils/blob_view_lookup.cpp @@ -28,11 +28,11 @@ #include "arrow/c/bridge.h" #include "fmt/format.h" #include "paimon/catalog/catalog.h" +#include "paimon/common/data/blob_utils.h" #include "paimon/common/executor/future.h" #include "paimon/common/table/special_fields.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" -#include "paimon/data/blob_descriptor.h" #include "paimon/defs.h" #include "paimon/executor.h" #include "paimon/global_index/bitmap_global_index_result.h" @@ -250,12 +250,11 @@ Status BlobViewLookup::ExtractBlobDescriptors(const Identifier& identifier, continue; } std::string_view bytes = binary_array->GetView(row); - PAIMON_ASSIGN_OR_RAISE(bool is_descriptor, BlobDescriptor::IsBlobDescriptor( - bytes.data(), bytes.size())); + PAIMON_ASSIGN_OR_RAISE(bool is_descriptor, BlobUtils::IsBlobReference(bytes)); if (!is_descriptor) { 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/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_batch_reader.h b/src/paimon/format/blob/blob_file_batch_reader.h index 3610d059f..d7c65ddea 100644 --- a/src/paimon/format/blob/blob_file_batch_reader.h +++ b/src/paimon/format/blob/blob_file_batch_reader.h @@ -208,7 +208,10 @@ class BlobFileBatchReader : public FileBatchReader { /// Returns true if the blob at the given index is null (bin_length == kNullBinLength). bool IsTargetNull(size_t index) const { - return target_blob_lengths_[index] == BlobDefs::kNullBinLength; + // A hidden fallback field needs only the footer marker. Represent every resolved + // row as NULL so scalar and collection builders skip the payload entirely. + return target_blob_lengths_[index] == BlobDefs::kNullBinLength || + (blob_context_ && blob_context_->placeholder_only && !IsTargetPlaceholder(index)); } bool IsTargetPlaceholder(size_t index) const { diff --git a/src/paimon/format/blob/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/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..bd539d875 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,34 @@ 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, WritesRawBytesWithVideoMagicAndDifferentVersion) { + const std::string bytes = "xMRFOEDIV"; + ASSERT_OK_AND_ASSIGN(std::shared_ptr writer, CreateDefaultWriter()); + ASSERT_OK_AND_ASSIGN(auto array, MakeBlobArrayFromBytes(bytes)); + ASSERT_OK(AddBatchOnce(writer, array)); + ASSERT_OK(writer->Finish()); + ASSERT_OK_AND_ASSIGN(auto rows, ReadBackAsData()); + auto values = checked_pointer_cast(rows->field(0)); + ASSERT_EQ(values->length(), 1); + ASSERT_EQ(values->GetView(0), bytes); +} + TEST_F(BlobFormatWriterWriteNullTest, TestWriteNullOnMissingFile) { ASSERT_OK_AND_ASSIGN( std::shared_ptr writer, diff --git a/src/paimon/format/blob/video_file_batch_reader.cpp b/src/paimon/format/blob/video_file_batch_reader.cpp new file mode 100644 index 000000000..4caaa69c6 --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -0,0 +1,384 @@ +/* + * 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/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/fs/file_system.h" +#include "paimon/io/byte_array_input_stream.h" +#include "paimon/io/data_input_stream.h" +#include "paimon/io/file_offset_input_stream.h" +#include "paimon/memory/bytes.h" + +namespace paimon::blob { +namespace { + +// Six little-endian index lengths, magic and version. +constexpr int64_t kFooterSize = 7 * sizeof(int32_t) + sizeof(int8_t); +constexpr int32_t kMagic = 0x4F454449; +constexpr int8_t kVersion = 1; +constexpr uint64_t kMaxIndexMemoryBytes = 64 * 1024 * 1024; +constexpr int64_t kNullReference = -1; +constexpr int64_t kPlaceholderReference = -2; + +using IndexLengths = std::array; + +Status ReadAtFully(InputStream* input, int64_t offset, char* data, int64_t size) { + for (int64_t read = 0; read < size;) { + const Result n = input->Read(data + read, size - read, offset + read); + 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 ComputeIndexStart(const IndexLengths& lengths, int64_t footer_start, + uint64_t video_entry_size, uint64_t run_entry_size) { + int64_t start = footer_start; + uint64_t decoded_bytes = 0; + uint64_t peak = 0; + for (int32_t length : lengths) { + if (length < 0 || length > start) { + return Status::Invalid("video indexes exceed the file size"); + } + start -= length; + // A varint can be one byte. The decoder holds both deltas and decoded values. + const uint64_t index_bytes = static_cast(length) * sizeof(int64_t); + peak = std::max(peak, decoded_bytes + 2 * index_bytes); + decoded_bytes += index_bytes; + } + // Each materialized group has equal entry counts, bounded by its shortest index. + const uint64_t videos = std::min({lengths[0], lengths[1], lengths[2]}); + const uint64_t runs = std::min({lengths[3], lengths[4], lengths[5]}); + peak = std::max(peak, decoded_bytes + videos * video_entry_size + runs * run_entry_size); + if (peak + (footer_start - start) > kMaxIndexMemoryBytes) { + return Status::CapacityError("video indexes exceed the memory budget of ", + kMaxIndexMemoryBytes, " bytes"); + } + return start; +} + +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)); +} + +} // 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) try { + if (!input || !pool || batch_size <= 0) { + return Status::Invalid("invalid video reader input, pool, or batch size"); + } + PAIMON_ASSIGN_OR_RAISE(std::string uri, input->GetUri()); + auto reader = std::unique_ptr(new VideoFileBatchReader( + std::move(uri), batch_size, pool, emit_placeholder_sentinel, blob_context)); + const Status status = reader->ReadVideoIndexes(input.get()); + if (!status.ok()) { + return reader->uri_.empty() ? status + : status.WithMessage(status.message(), " (", reader->uri_, ")"); + } + PAIMON_ASSIGN_OR_RAISE(int64_t base, FileOffsetInputStream::GetFileOffset(*input)); + if (base != 0) { + for (auto& video : reader->videos_) { + if (base > std::numeric_limits::max() - video.offset - video.length) { + return Status::Invalid("video payload range overflows the backing file offset"); + } + video.offset += base; + } + } + return reader; +} catch (const std::bad_alloc&) { + return Status::OutOfMemory("allocating video indexes"); +} + +Status VideoFileBatchReader::ReadVideoIndexes(InputStream* input) { + PAIMON_ASSIGN_OR_RAISE(int64_t size, input->Length()); + if (size < kFooterSize) { + return Status::Invalid("video file is smaller than its footer"); + } + const int64_t footer_start = size - kFooterSize; + char footer[kFooterSize]; + PAIMON_RETURN_NOT_OK(ReadAtFully(input, footer_start, footer, kFooterSize)); + DataInputStream footer_input(std::make_shared(footer, sizeof(footer))); + footer_input.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); + IndexLengths index_lengths; + for (int32_t& index_length : index_lengths) { + PAIMON_ASSIGN_OR_RAISE(index_length, footer_input.ReadValue()); + } + 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("corrupt or unsupported .video footer"); + } + + PAIMON_ASSIGN_OR_RAISE( + int64_t index_start, + ComputeIndexStart(index_lengths, footer_start, sizeof(VideoRange), sizeof(FrameRun))); + Bytes buffer(footer_start - index_start, pool_.get()); + PAIMON_RETURN_NOT_OK(ReadAtFully(input, index_start, buffer.data(), buffer.size())); + return DecodeVideoIndexes(std::string_view(buffer.data(), buffer.size()), index_lengths, + index_start); +} + +Status VideoFileBatchReader::DecodeVideoIndexes(std::string_view data, + const IndexLengths& index_lengths, + int64_t index_start) { + std::array, 6> indexes; + for (size_t i = 0; i < indexes.size(); ++i) { + PAIMON_ASSIGN_OR_RAISE(indexes[i], + DeltaVarintCompressor::Decompress(data.data(), index_lengths[i])); + data.remove_prefix(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"); + } + + int64_t payload_offset = 0; + 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"); + } + 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; + 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 (!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; + runs_.push_back({static_cast(rows), ref, first}); + } + row_count_ = rows; + return Status::OK(); +} + +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 (closed_) { + return Status::Invalid("video reader is closed"); + } + if (!schema) { + return Status::Invalid("video read schema is null"); + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr arrow_schema, + arrow::ImportSchema(schema)); + if (arrow_schema->num_fields() > 1 || + (arrow_schema->num_fields() == 1 && !BlobUtils::IsBlobField(arrow_schema->field(0)))) { + return Status::Invalid( + "video reader supports only an empty projection or one scalar BLOB field"); + } + // Create() bounds row_count_ by INT32_MAX. Seek once to check the entire upper range, + // including bitmap entries above INT32_MAX, which appear negative when dereferenced. + if (selection && + selection->EqualOrLarger(static_cast(row_count_)) != selection->End()) { + return Status::Invalid("video selection row exceeds row count"); + } + + selection_ = selection; + read_row_count_ = selection ? selection->Cardinality() : row_count_; + previous_selected_rows_.clear(); + read_type_ = arrow::struct_(arrow_schema->fields()); + current_ = 0; + previous_batch_size_ = 0; + return Status::OK(); +} + +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 selection_ ? previous_selected_rows_[batch_row_id] + : 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; + std::vector().swap(videos_); + std::vector().swap(runs_); + std::vector().swap(previous_selected_rows_); + selection_.reset(); + previous_batch_size_ = 0; + read_type_.reset(); + blob_context_.reset(); +} + +Result VideoFileBatchReader::NextBatch() try { + if (!read_type_) { + return Status::Invalid("video reader is closed or read schema is unset"); + } + if (current_ >= read_row_count_) { + previous_batch_size_ = 0; + return BatchReader::MakeEofBatch(); + } + 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"); + } + const uint64_t batch_limit = request ? std::min(batch_size_, request->max_rows) : batch_size_; + 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::ArrayVector columns; + if (read_type_->num_fields() != 0) { + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr frames, + ReadFrames(count, selected_rows, !request || request->read_payload)); + columns.push_back(std::move(frames)); + } + arrow::StructArray array(read_type_, count, columns); + auto c_array = std::make_unique<::ArrowArray>(); + auto c_schema = std::make_unique<::ArrowSchema>(); + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(array, c_array.get(), c_schema.get())); + PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(c_array.get(), c_schema.get(), arrow_pool_)); + current_ += count; + previous_batch_size_ = count; + previous_selected_rows_ = std::move(selected_rows); + return std::make_pair(std::move(c_array), std::move(c_schema)); +} catch (const std::bad_alloc&) { + return Status::OutOfMemory("allocating video frame batch"); +} + +Result> VideoFileBatchReader::ReadFrames( + uint64_t count, const std::vector& selected_rows, bool read_payload) { + arrow::LargeBinaryBuilder builder(arrow_pool_.get()); + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Reserve(count)); + for (uint64_t i = 0; i < count; ++i) { + if (!read_payload) { + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); + continue; + } + 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; }); + 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 { + if (blob_context_ && blob_context_->placeholder_only) { + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.AppendNull()); + continue; + } + if (uri_.empty()) { + return Status::Invalid("video frame descriptors require a reopenable file URI"); + } + const auto& video = videos_[run->reference]; + const uint64_t run_start = run == runs_.begin() ? 0 : (run - 1)->end; + const int64_t frame = run->first_frame + static_cast(row - run_start); + PAIMON_ASSIGN_OR_RAISE( + 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())); + } + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr frames, builder.Finish()); + return frames; +} + +} // namespace paimon::blob diff --git a/src/paimon/format/blob/video_file_batch_reader.h b/src/paimon/format/blob/video_file_batch_reader.h new file mode 100644 index 000000000..4d86e985b --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -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. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "paimon/reader/file_batch_reader.h" + +namespace arrow { +class Array; +class DataType; +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); + + Status ReadVideoIndexes(InputStream* input); + Status DecodeVideoIndexes(std::string_view data, const std::array& index_lengths, + int64_t index_start); + + Result> ReadFrames(uint64_t count, + const std::vector& selected_rows, + bool read_payload); + + std::string uri_; + int32_t batch_size_; + std::shared_ptr pool_; + std::shared_ptr arrow_pool_; + std::shared_ptr read_type_; + std::shared_ptr metrics_; + bool emit_placeholder_sentinel_; + std::shared_ptr blob_context_; + std::vector videos_; + std::vector runs_; + 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; +}; + +} // 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..01ff58378 --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -0,0 +1,614 @@ +/* + * 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 "arrow/c/helpers.h" +#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/io/cache_input_stream.h" +#include "paimon/common/io/offset_input_stream.h" +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/common/utils/delta_varint_compressor.h" +#include "paimon/common/utils/read_ahead_cache.h" +#include "paimon/data/blob.h" +#include "paimon/data/blob_descriptor.h" +#include "paimon/format/file_format.h" +#include "paimon/format/file_format_factory.h" +#include "paimon/fs/local/local_file_system.h" +#include "paimon/io/buffered_input_stream.h" +#include "paimon/io/byte_array_input_stream.h" +#include "paimon/testing/mock/mock_file_system.h" +#include "paimon/testing/utils/testharness.h" +#include "paimon/testing/utils/video_test_utils.h" + +namespace paimon::test { +namespace { + +using blob::VideoFileBatchReader; + +constexpr char kVideoUri[] = "s3://bucket/part-2.video"; + +// Serves only the stored suffix, so a read into an omitted payload fails the test. +class VideoTailStream : public MockInputStream { + public: + VideoTailStream(int64_t offset, std::string tail) : offset_(offset), tail_(std::move(tail)) {} + + Result Length() const override { + return offset_ + tail_.size(); + } + + Result GetUri() const override { + return std::string(kVideoUri); + } + + Result Read(char* buffer, int64_t size, int64_t offset) override { + reads.emplace_back(offset, size); + const int64_t end = offset_ + tail_.size(); + if (offset < offset_ || offset > end || size > end - offset) { + return Status::IOError("unexpected read outside the stored video tail"); + } + std::memcpy(buffer, tail_.data() + (offset - offset_), size); + return size; + } + + std::vector> reads; + + private: + int64_t offset_; + std::string tail_; +}; + +void Append32(std::string* data, uint32_t value) { + for (int32_t i = 0; i < 4; ++i) { + data->push_back(static_cast(value >> (8 * i))); + } +} + +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); +} + +void AppendVideoIndexes(std::string* data, const std::vector>& indexes) { + std::vector sizes; + for (const auto& values : indexes) { + const auto bytes = DeltaVarintCompressor::Compress(values); + sizes.push_back(bytes.size()); + data->append(bytes.data(), bytes.size()); + } + AppendVideoFooter(data, sizes); +} + +std::string MakeVideoFile(bool placeholder = false, int64_t first_moov_length = 3) { + std::string data = "VIDEOfilm"; + const std::vector> indexes = { + {5, 4}, {2, 0}, {first_moov_length, 0}, {2, 1, 1}, {0, placeholder ? -2 : -1, 1}, + {4, 0, 9}}; + AppendVideoIndexes(&data, indexes); + return data; +} + +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_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())); + 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, ReopensFramesFromContainerSlice) { + auto dir = UniqueTestDirectory::Create(); + auto fs = dir->GetFileSystem(); + const std::string path = dir->Str() + "/container"; + const std::string pack = MakeVideoFile(); + ASSERT_OK(fs->WriteFile(path, "12345" + pack + "suffix", true)); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(4)); + for (const auto& [prefix, buffered, cached] : + {std::tuple{5, false, false}, std::tuple{2, false, false}, std::tuple{5, false, true}, + std::tuple{2, false, true}, std::tuple{5, true, false}, std::tuple{2, true, true}}) { + SCOPED_TRACE(::testing::Message() + << "prefix=" << prefix << ", buffered=" << buffered << ", cached=" << cached); + ASSERT_OK_AND_ASSIGN(auto blob, Blob::FromPath(path, prefix, pack.size() + 5 - prefix)); + ASSERT_OK_AND_ASSIGN(auto slice, blob->NewInputStream(fs)); + if (buffered) { + slice = + std::make_unique(std::move(slice), 8, GetDefaultPool().get()); + } + if (cached) { + ASSERT_OK_AND_ASSIGN(std::shared_ptr cache_input, + blob->NewInputStream(fs)); + auto cache = std::make_shared(cache_input, CacheConfig(), + /*file_size=*/0, GetDefaultPool()); + slice = std::make_unique(std::move(slice), cache); + } + std::shared_ptr input = std::move(slice); + if (prefix != 5) { + ASSERT_OK_AND_ASSIGN(input, OffsetInputStream::Create(input, pack.size(), 5 - prefix)); + } + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(input)); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, std::nullopt)); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + auto rows = std::static_pointer_cast( + arrow::ImportArray(batch.first.get(), batch.second.get()).ValueOrDie()); + reader->Close(); + ASSERT_OK(input->Close()); + auto values = std::static_pointer_cast(rows->field(0)); + ASSERT_EQ(values->length(), 4); + for (int i : {0, 3}) { + const auto bytes = values->GetView(i); + ASSERT_OK_AND_ASSIGN(auto frame, Blob::FromDescriptor(bytes.data(), bytes.size())); + ASSERT_EQ(frame->FrameIndex(), i == 0 ? 4 : 9); + ASSERT_EQ(frame->MoovOffset(), i == 0 ? 2 : 0); + ASSERT_OK_AND_ASSIGN(auto payload, frame->ToData(fs, GetDefaultPool())); + ASSERT_EQ(std::string_view(payload->data(), payload->size()), + i == 0 ? "VIDEO" : "film"); + } + } +} + +TEST(VideoFileBatchReaderTest, RequiresUriOnlyWhenEmittingFrames) { + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-v1-moov.hex")); + auto input = std::make_shared(bytes.data(), bytes.size()); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(input)); + ASSERT_OK_AND_ASSIGN(uint64_t count, reader->GetNumberOfRows()); + ASSERT_EQ(2u, count); + ::ArrowSchema schema; + ASSERT_TRUE(arrow::ExportSchema(*arrow::schema({}), &schema).ok()); + ASSERT_OK(reader->SetReadSchema(&schema, nullptr, std::nullopt)); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_GT(batch.first->length, 0); + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); + ASSERT_OK_AND_ASSIGN(reader, builder->Build(input)); + ASSERT_TRUE( + arrow::ExportSchema(*arrow::schema({BlobUtils::ToArrowField("video", true)}), &schema) + .ok()); + ASSERT_OK(reader->SetReadSchema(&schema, nullptr, std::nullopt)); + ASSERT_NOK_WITH_MSG(reader->NextBatch(), "reopenable file URI"); +} + +TEST(VideoFileBatchReaderTest, ReportsIndexAndFrameAllocationFailures) { + class FaultPool final : public MemoryPool { + public: + bool fail = true; + void* Malloc(uint64_t size, uint64_t alignment) override { + // Fail the Bytes allocation. Arrow's aligned builders may still allocate. + if (fail && alignment == 0) { + throw std::bad_alloc(); + } + return GetDefaultPool()->Malloc(size, alignment); + } + void* Realloc(void* ptr, size_t old_size, size_t new_size, uint64_t alignment) override { + return GetDefaultPool()->Realloc(ptr, old_size, new_size, alignment); + } + void Free(void* ptr, uint64_t size) override { + GetDefaultPool()->Free(ptr, size); + } + uint64_t CurrentUsage() const override { + return GetDefaultPool()->CurrentUsage(); + } + uint64_t MaxMemoryUsage() const override { + return GetDefaultPool()->MaxMemoryUsage(); + } + }; + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-v1-moov.hex")); + auto input = std::make_shared(0, bytes); + auto pool = std::make_shared(); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + builder->WithMemoryPool(pool); + ASSERT_TRUE(builder->Build(input).status().IsOutOfMemory()); + pool->fail = false; + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(input)); + ::ArrowSchema schema; + ASSERT_TRUE( + arrow::ExportSchema(*arrow::schema({BlobUtils::ToArrowField("video", true)}), &schema) + .ok()); + ASSERT_OK(reader->SetReadSchema(&schema, nullptr, std::nullopt)); + pool->fail = true; + ASSERT_TRUE(reader->NextBatch().status().IsOutOfMemory()); + pool->fail = false; + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_EQ(2, batch.first->length); + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); +} + +TEST(VideoFileBatchReaderTest, RejectsOverflowingFrameIndex) { + // A tenth byte of 2 encodes 2^64, which would truncate to frame zero. + std::string bytes("V\x02\x00\x00\x02\x00", 6); + bytes.append(9, static_cast(0x80)); + bytes.push_back(2); + AppendVideoFooter(&bytes, {1, 1, 1, 1, 1, 10}); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(1)); + ASSERT_NOK_WITH_MSG(builder->Build(std::make_shared(0, bytes)), + "Varint overflow"); +} + +TEST(VideoFileBatchReaderTest, RoundTripsJavaFrameDescriptor) { + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-frame-descriptor-v1.hex")); + ASSERT_OK_AND_ASSIGN(std::unique_ptr blob, + 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); + 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_OK_AND_ASSIGN(std::string uri, shared_input->GetUri()); + auto result = VideoFileBatchReader::Create(shared_input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "corrupt or unsupported .video footer"); + ASSERT_NOK_WITH_MSG(result, uri); +} + +TEST(VideoFileBatchReaderTest, ReadsMoovLayoutWhenBytesAlsoFitLegacyLayout) { + // The current writer's layout describes 100 rows. A legacy keyframe footer + // interpretation of the same bytes would describe four rows. + std::string bytes(44, '\0'); + AppendVideoIndexes(&bytes, + {{22, 22}, {0, 0}, {0, 0}, {25, 25, 25, 25}, {1, 1, 1, 1}, {1, 1, 1, 1}}); + ASSERT_OK_AND_ASSIGN(auto format, FileFormatFactory::Get("video", {})); + ASSERT_OK_AND_ASSIGN(auto builder, format->CreateReaderBuilder(2)); + ASSERT_OK_AND_ASSIGN(auto reader, builder->Build(std::make_shared(0, bytes))); + ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); + ASSERT_EQ(rows, 100); + + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, RoaringBitmap32::From({99}))); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + auto selected = std::static_pointer_cast( + arrow::ImportArray(batch.first.get(), batch.second.get()).ValueOrDie()); + auto frames = std::static_pointer_cast(selected->field(0)); + ASSERT_EQ(frames->length(), 1); + const auto descriptor = frames->GetView(0); + ASSERT_OK_AND_ASSIGN(auto frame, Blob::FromDescriptor(descriptor.data(), descriptor.size())); + ASSERT_EQ(frame->FrameIndex(), 25); +} + +TEST(VideoFileBatchReaderTest, ReadsDenseSelectionInSmallBatches) { + 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, EmptyProjectionPreservesSelectedFileRows) { + auto input = std::make_shared(0, MakeVideoFile(/*placeholder=*/true)); + ASSERT_OK_AND_ASSIGN(auto reader, + VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*arrow::schema({}), &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, RoaringBitmap32::From({0, 2, 3}))); + for (const auto& file_rows : {std::vector{0, 2}, std::vector{3}}) { + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_EQ(0, batch.first->n_children); + ASSERT_EQ(file_rows.size(), batch.first->length); + for (size_t i = 0; i < file_rows.size(); ++i) { + ASSERT_OK_AND_ASSIGN(uint64_t row, reader->GetPreviousBatchFileRowId(i)); + ASSERT_EQ(file_rows[i], row); + } + ArrowArrayRelease(batch.first.get()); + ArrowSchemaRelease(batch.second.get()); + } + ASSERT_OK_AND_ASSIGN(auto eof, reader->NextBatch()); + ASSERT_TRUE(BatchReader::IsEofBatch(eof)); +} + +TEST(VideoFileBatchReaderTest, ReadsJavaIndexesWithOneTailRead) { + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-v1-moov.hex")); + constexpr int64_t kPayloadSize = 24; + auto input = std::make_shared(kPayloadSize, bytes.substr(kPayloadSize)); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); + ASSERT_EQ(reader->GetNumberOfRows().value(), 2); + const std::vector> expected{{30, 29}, {24, 6}}; + ASSERT_EQ(input->reads, expected); + ASSERT_GT(reader->videos_.capacity(), 0u); + reader->Close(); + ASSERT_EQ(reader->videos_.capacity(), 0u); +} + +TEST(VideoFileBatchReaderTest, ReadsEmptyVideoFile) { + std::string bytes; + AppendVideoFooter(&bytes, {0, 0, 0, 0, 0, 0}); + auto input = std::make_shared(0, bytes); + ASSERT_OK_AND_ASSIGN(auto reader, + VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr)); + ASSERT_OK_AND_ASSIGN(uint64_t rows, reader->GetNumberOfRows()); + ASSERT_EQ(rows, 0); + ASSERT_EQ(input->reads.size(), 1u); + + bytes.pop_back(); + auto truncated = std::make_shared(0, bytes); + ASSERT_NOK_WITH_MSG( + VideoFileBatchReader::Create(truncated, 2, GetDefaultPool(), false, nullptr), + "smaller than its footer"); + ASSERT_TRUE(truncated->reads.empty()); +} + +TEST(VideoFileBatchReaderTest, RejectsOversizedIndexesBeforeReadingThem) { + constexpr uint32_t kIndexSize = 64 * 1024 * 1024; + for (const std::vector& lengths : + {std::vector{kIndexSize, 0, 0, 0, 0, 0}, + std::vector{0, 0, 0, 0, 0, kIndexSize}}) { + std::string footer; + AppendVideoFooter(&footer, lengths); + auto input = std::make_shared(kIndexSize, footer); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_TRUE(result.status().IsCapacityError()) << result.status(); + ASSERT_NOK_WITH_MSG(result, kVideoUri); + ASSERT_EQ(input->reads.size(), 1u); + } +} + +TEST(VideoFileBatchReaderTest, CountsEncodedIndexesInMemoryBudget) { + // The decoded indexes and frame runs alone fit just below 64 MiB. + constexpr uint32_t kRuns = 64 * 1024 * 1024 / 48; + std::string bytes(3 * kRuns, '\0'); + bytes[0] = 2; + bytes[kRuns] = 1; + AppendVideoFooter(&bytes, {0, 0, 0, kRuns, kRuns, kRuns}); + auto input = std::make_shared(0, std::move(bytes)); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_TRUE(result.status().IsCapacityError()) << result.status(); + ASSERT_EQ(input->reads.size(), 1u); +} + +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); + auto schema = arrow::schema({BlobUtils::ToArrowField("video", true)}); + ::ArrowSchema c_schema; + ASSERT_TRUE(arrow::ExportSchema(*schema, &c_schema).ok()); + ASSERT_OK(reader->SetReadSchema(&c_schema, nullptr, RoaringBitmap32::From({1, 3}))); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + reader->Close(); + ASSERT_EQ(0u, reader->runs_.capacity()); + ASSERT_EQ(0u, reader->previous_selected_rows_.capacity()); + ASSERT_FALSE(reader->selection_); + ASSERT_NOK(reader->GetPreviousBatchFileRowId(0)); + ASSERT_NOK(reader->NextBatch()); + auto array = arrow::ImportArray(batch.first.get(), batch.second.get()).ValueOrDie(); + ASSERT_EQ(2, array->length()); +} + +TEST(VideoFileBatchReaderTest, RejectsMoovRangeOutsideVideo) { + 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_OK_AND_ASSIGN(std::string uri, input->GetUri()); + auto result = VideoFileBatchReader::Create(input, 2, GetDefaultPool(), false, nullptr); + ASSERT_NOK_WITH_MSG(result, "invalid moov range"); + ASSERT_NOK_WITH_MSG(result, uri); +} + +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 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..305cd6dea 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -80,10 +80,12 @@ #include "paimon/table/source/data_split.h" #include "paimon/table/source/startup_mode.h" #include "paimon/table/source/table_read.h" +#include "paimon/testing/utils/counting_reader_file_system.h" #include "paimon/testing/utils/deletion_vector_test_helper.h" #include "paimon/testing/utils/io_exception_helper.h" #include "paimon/testing/utils/test_helper.h" #include "paimon/testing/utils/testharness.h" +#include "paimon/testing/utils/video_test_utils.h" #include "paimon/write_context.h" namespace paimon { @@ -139,10 +141,11 @@ class BlobTableInteTest : public testing::Test, public ::testing::WithParamInter Result>> WriteArray( const std::string& table_path, const std::map& partition, const std::vector& write_cols, - const std::vector>& write_arrays) const { + const std::vector>& write_arrays, + const std::map& options = {}) const { // write WriteContextBuilder write_builder(table_path, "commit_user_1"); - write_builder.WithWriteSchema(write_cols); + write_builder.WithWriteSchema(write_cols).SetOptions(options); PAIMON_ASSIGN_OR_RAISE(std::unique_ptr write_context, write_builder.Finish()); PAIMON_ASSIGN_OR_RAISE(auto file_store_write, FileStoreWrite::Create(std::move(write_context))); @@ -1328,6 +1331,383 @@ std::shared_ptr MakeBlobUpdateArray( return std::dynamic_pointer_cast(array); } +TEST_P(BlobTableInteTest, ValidateVideoFrameFieldsOnCreateTable) { + auto schema = + arrow::schema({arrow::field("id", arrow::int32()), BlobUtils::ToArrowField("video", true), + arrow::field("frames", arrow::list(BlobUtils::ToArrowField("item", true)))}); + ASSERT_OK_AND_ASSIGN(auto catalog, Catalog::Create(dir_->Str(), {})); + ASSERT_OK(catalog->CreateDatabase("foo", {}, false)); + auto create = [&](const std::string& fields, const std::string& other_option = "") { + std::map options = {{Options::FILE_FORMAT, GetParam()}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, fields}}; + if (!other_option.empty()) { + options[other_option] = "video"; + } + ::ArrowSchema c_schema; + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*schema, &c_schema)); + return catalog->CreateTable(Identifier("foo", "bar"), &c_schema, {}, {}, options, false); + }; + for (const auto& name : {"missing", "id", "frames"}) { + ASSERT_NOK_WITH_MSG(create(name), name); + } + for (const auto& names : {"video,video", "video, ,"}) { + ASSERT_OK(create(names)); + ASSERT_OK(catalog->DropTable(Identifier("foo", "bar"), false)); + } + for (const auto& conflict : {Options::BLOB_DESCRIPTOR_FIELD, Options::BLOB_VIEW_FIELD}) { + ASSERT_NOK_WITH_MSG(create("video", conflict), conflict); + } + ASSERT_OK(create("video", Options::BLOB_FIELD)); +} + +TEST_P(BlobTableInteTest, TestReadVideoLayersInManagedSplit) { + const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + BlobUtils::ToArrowField("video", /*nullable=*/true)}; + 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(); + const std::map override = {{BlobDefs::kVideoFrameFieldOption, ""}}; + // Clearing the declaration for a write still permits a projection that excludes video. + ASSERT_OK_AND_ASSIGN(auto commit_messages, + WriteArray(table_path, {}, {"id"}, {id_array}, override)); + 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_NOK_WITH_MSG(WriteArray(table_path, {}, {"id", "video", "video"}, {}, + {{Options::BLOB_DESCRIPTOR_FIELD, "video"}}), + "writing video-frame-field"); + + auto full_row = + arrow::StructArray::Make( + {std::static_pointer_cast(id_array)->field(0)->Slice(0, 1), + video_array->field(0)}, + fields) + .ValueOrDie(); + ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {}, {full_row}, override), + "writing video-frame-field 'video' is not supported"); + ASSERT_NOK_WITH_MSG(WriteArray(table_path, {}, {"video"}, {video_array}, override), + "writing video-frame-field 'video' is not supported"); + + // Commit the Java-written video with its normal file, then commit a video-only update. + auto fs = dir_->GetFileSystem(); + ASSERT_EQ(1u, commit_messages.size()); + auto message = std::dynamic_pointer_cast(commit_messages.front()); + ASSERT_TRUE(message); + auto& files = message->data_increment_.new_files_; + ASSERT_EQ(1u, files.size()); + const auto data_file = files.front(); + auto write_video = + [&](const std::string& name, const std::string& bytes, int64_t sequence, + std::optional first_row_id) -> Result> { + PAIMON_RETURN_NOT_OK( + fs->WriteFile(PathUtil::JoinPath(table_path, "bucket-0/" + name), bytes, false)); + return DataFileMeta::ForAppend(name, bytes.size(), 2, SimpleStats::EmptyStats(), sequence, + sequence, data_file->schema_id, FileSource::Append(), + std::nullopt, std::nullopt, first_row_id, + std::vector{"video"}); + }; + ASSERT_OK_AND_ASSIGN(std::string base, ReadJavaVideoFixture("video-v1-moov.hex")); + ASSERT_OK_AND_ASSIGN(auto base_file, write_video("base.video", base, + data_file->max_sequence_number, std::nullopt)); + files.push_back(std::move(base_file)); + ASSERT_OK(Commit(table_path, commit_messages)); + ScanContextBuilder scan_builder(table_path); + scan_builder.WithStreamingMode(true); + ASSERT_OK_AND_ASSIGN(auto scan_context, scan_builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto scan, TableScan::Create(std::move(scan_context))); + ASSERT_OK_AND_ASSIGN(auto initial, scan->CreatePlan()); + ASSERT_EQ(1u, initial->Splits().size()); + auto base_split = std::dynamic_pointer_cast(initial->Splits()[0]); + ASSERT_TRUE(base_split); + ASSERT_EQ(2u, base_split->DataFiles().size()); + ASSERT_OK_AND_ASSIGN(int64_t first_row_id, base_split->DataFiles()[0]->NonNullFirstRowId()); + // Two runs with no physical payloads: the first falls back, the second overwrites with NULL. + constexpr char overlay[] = + "\x02\x00\x03\x02\x00\x00" // Run lengths, references, first frames. + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00" + "IDEO\x01"; + ASSERT_OK_AND_ASSIGN( + auto update, + write_video("overlay.video", std::string(overlay, sizeof(overlay) - 1), + base_split->DataFiles()[0]->max_sequence_number + 1, first_row_id)); + ASSERT_OK( + Commit(table_path, {std::make_shared( + message->Partition(), message->Bucket(), message->TotalBuckets(), + DataIncrement({update}, {}, {}), CompactIncrement({}, {}, {}))})); + ASSERT_OK_AND_ASSIGN(auto delta, scan->CreatePlan()); + ASSERT_EQ(1u, delta->Splits().size()); + auto delta_split = std::dynamic_pointer_cast(delta->Splits()[0]); + ASSERT_TRUE(delta_split); + ASSERT_EQ(1u, delta_split->DataFiles().size()); + ASSERT_EQ("overlay.video", delta_split->DataFiles()[0]->file_name); + + std::vector> layers = delta_split->DataFiles(); + for (const auto& file : base_split->DataFiles()) { + if (BlobUtils::IsVideoFile(file->file_name)) { + layers.push_back(file); + } + } + ASSERT_EQ(2u, layers.size()); + ASSERT_OK_AND_ASSIGN(auto layered_split, + DataSplitImpl::Builder(delta_split->Partition(), delta_split->Bucket(), + delta_split->BucketPath(), std::move(layers)) + .WithSnapshot(delta_split->SnapshotId()) + .WithTotalBuckets(delta_split->TotalBuckets()) + .RawConvertible(false) + .Build()); + auto layered_plan = std::make_shared( + delta->SnapshotId(), std::vector>{layered_split}); + for (const auto& projection : + {std::vector{"id"}, std::vector{"id", "video"}}) { + ASSERT_OK_AND_ASSIGN(auto projected, ReadTable(table_path, projection, layered_plan)); + ASSERT_EQ(2, projected->length()); + for (const auto& chunk : projected->chunks()) { + auto rows = checked_pointer_cast(chunk); + ASSERT_EQ(rows->length(), rows->GetFieldByName("id")->null_count()); + } + } + + // The delta has no older frame to fall back to. Only the placeholder has sequence -1. + ASSERT_OK_AND_ASSIGN(auto delta_values, + ReadTable(table_path, {"video", "_ROW_ID", "_SEQUENCE_NUMBER"}, delta)); + auto delta_rows = checked_pointer_cast( + arrow::Concatenate(delta_values->chunks()).ValueOrDie()); + ASSERT_EQ(2, delta_rows->length()); + ASSERT_EQ(2, delta_rows->GetFieldByName("video")->null_count()); + auto delta_ids = checked_pointer_cast(delta_rows->GetFieldByName("_ROW_ID")); + ASSERT_EQ(first_row_id, delta_ids->Value(0)); + ASSERT_EQ(first_row_id + 1, delta_ids->Value(1)); + auto sequences = + checked_pointer_cast(delta_rows->GetFieldByName("_SEQUENCE_NUMBER")); + ASSERT_EQ(-1, sequences->Value(0)); + ASSERT_EQ(delta_split->DataFiles()[0]->max_sequence_number, sequences->Value(1)); + + for (const std::string field : {"video", "_ROW_ID", "_SEQUENCE_NUMBER"}) { + ASSERT_OK_AND_ASSIGN(auto projected, ReadTable(table_path, {field}, delta)); + auto projected_rows = checked_pointer_cast( + arrow::Concatenate(projected->chunks()).ValueOrDie()); + ASSERT_TRUE( + projected_rows->GetFieldByName(field)->Equals(delta_rows->GetFieldByName(field))); + } + + auto selected_split = std::make_shared( + delta_split, std::vector{Range(first_row_id + 1, first_row_id + 1)}); + auto selected_plan = std::make_shared( + delta->SnapshotId(), std::vector>{selected_split}); + ASSERT_OK_AND_ASSIGN(auto selected, ReadTable(table_path, {"_ROW_ID"}, selected_plan)); + auto selected_rows = checked_pointer_cast( + arrow::Concatenate(selected->chunks()).ValueOrDie()); + ASSERT_EQ(1, selected_rows->length()); + ASSERT_EQ(first_row_id + 1, + checked_pointer_cast(selected_rows->GetFieldByName("_ROW_ID")) + ->Value(0)); + + // A full snapshot includes the base frame for the placeholder and preserves the explicit NULL. + ASSERT_OK_AND_ASSIGN(auto video_plan, ScanTable(table_path)); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr result, + ReadTable(table_path, {"id", "video", "_ROW_ID"}, video_plan, + /*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, VideoOnlyDeltaAlignsColumnsAndPreservesPartition) { + const arrow::FieldVector fields = { + arrow::field("id", arrow::int32()), arrow::field("part", arrow::int32()), + BlobUtils::ToArrowField("a", true), BlobUtils::ToArrowField("b", true)}; + CreateTable(fields, {"part"}, + {{Options::FILE_FORMAT, GetParam()}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, "a,b"}}); + const auto path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + auto ids = + arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({fields[0]}), "[[10], [20]]") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto messages, WriteArray(path, {{"part", "7"}}, {"id"}, {ids})); + ASSERT_OK(Commit(path, messages)); + ScanContextBuilder scan_builder(path); + scan_builder.WithStreamingMode(true); + ASSERT_OK_AND_ASSIGN(auto context, scan_builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto scan, TableScan::Create(std::move(context))); + ASSERT_OK_AND_ASSIGN(auto initial, scan->CreatePlan()); + auto split = std::dynamic_pointer_cast(initial->Splits().at(0)); + auto anchor = split->DataFiles().at(0); + ASSERT_OK_AND_ASSIGN(int64_t first, anchor->NonNullFirstRowId()); + const int64_t seq = anchor->max_sequence_number + 1; + + // a has a placeholder and an explicit NULL. b supplies a frame only for the second row. + constexpr char overlay[] = + "\x02\x00\x03\x02\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00" + "IDEO\x01"; + ASSERT_OK_AND_ASSIGN(std::string frame, ReadJavaVideoFixture("video-v1-moov.hex")); + frame[27] = 2; // Zigzag-encoded run length 1. + auto add_file = [&](const std::string& column, const std::string& bytes, int64_t row, + int64_t count) -> Result> { + const auto name = column + ".video"; + PAIMON_RETURN_NOT_OK(dir_->GetFileSystem()->WriteFile( + PathUtil::JoinPath(split->BucketPath(), name), bytes, false)); + return DataFileMeta::ForAppend(name, bytes.size(), count, SimpleStats::EmptyStats(), seq, + seq, anchor->schema_id, FileSource::Append(), std::nullopt, + std::nullopt, row, std::vector{column}); + }; + ASSERT_OK_AND_ASSIGN(auto a, + add_file("a", std::string(overlay, sizeof(overlay) - 1), first, 2)); + ASSERT_OK_AND_ASSIGN(auto b, add_file("b", frame, first + 1, 1)); + ASSERT_OK(Commit(path, {std::make_shared( + split->Partition(), split->Bucket(), split->TotalBuckets(), + DataIncrement({a, b}, {}, {}), CompactIncrement({}, {}, {}))})); + ASSERT_OK_AND_ASSIGN(auto delta, scan->CreatePlan()); + for (const std::vector& projection : std::vector>{ + {"a", "b", "_ROW_ID", "part", "id"}, {"part"}, {"id"}}) { + ASSERT_OK_AND_ASSIGN(auto result, ReadTable(path, projection, delta)); + auto rows = checked_pointer_cast( + arrow::Concatenate(result->chunks()).ValueOrDie()); + ASSERT_EQ(2, rows->length()); + if (auto part = rows->GetFieldByName("part")) { + ASSERT_TRUE(part->Equals( + arrow::ipc::internal::json::ArrayFromJSON(arrow::int32(), "[7,7]").ValueOrDie())); + } + if (auto id = rows->GetFieldByName("id")) { + ASSERT_EQ(2, id->null_count()); + } + if (auto videos = rows->GetFieldByName("b")) { + ASSERT_TRUE(videos->IsNull(0)); + ASSERT_FALSE(videos->IsNull(1)); + ASSERT_EQ(2, rows->GetFieldByName("a")->null_count()); + auto row_ids = checked_pointer_cast(rows->GetFieldByName("_ROW_ID")); + ASSERT_EQ(first, row_ids->Value(0)); + ASSERT_EQ(first + 1, row_ids->Value(1)); + } + } +} + +TEST_P(BlobTableInteTest, TestOpenVideoFilesByRowRange) { + const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + BlobUtils::ToArrowField("video", /*nullable=*/true)}; + CreateTable(fields, {}, + {{Options::FILE_FORMAT, GetParam()}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {BlobDefs::kVideoFrameFieldOption, "video"}}); + const std::string table_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + auto ids = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_({fields[0]}), + "[[0], [1], [2], [3]]") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto messages, WriteArray(table_path, {}, {"id"}, {ids})); + ASSERT_OK(Commit(table_path, messages)); + ASSERT_OK_AND_ASSIGN(auto plan, ScanTable(table_path)); + ASSERT_EQ(1u, plan->Splits().size()); + auto split = std::dynamic_pointer_cast(plan->Splits()[0]); + ASSERT_TRUE(split); + auto files = split->DataFiles(); + ASSERT_EQ(1u, files.size()); + ASSERT_OK_AND_ASSIGN(int64_t first, files.front()->NonNullFirstRowId()); + const int64_t seq = files.front()->max_sequence_number + 1; + ASSERT_OK_AND_ASSIGN(std::string video, ReadJavaVideoFixture("video-v1-moov.hex")); + for (int i = 0; i < 2; ++i) { + const std::string name = std::to_string(i) + ".video"; + ASSERT_OK(dir_->GetFileSystem()->WriteFile(PathUtil::JoinPath(split->BucketPath(), name), + video, true)); + ASSERT_OK_AND_ASSIGN( + auto file, DataFileMeta::ForAppend( + name, video.size(), /*row_count=*/2, SimpleStats::EmptyStats(), seq, seq, + /*schema_id=*/0, FileSource::Append(), std::nullopt, std::nullopt, + first + i * 2, std::vector{"video"})); + files.push_back(std::move(file)); + } + ASSERT_OK_AND_ASSIGN(auto video_split, + DataSplitImpl::Builder(split->Partition(), split->Bucket(), + split->BucketPath(), std::move(files)) + .WithSnapshot(split->SnapshotId()) + .WithTotalBuckets(split->TotalBuckets()) + .RawConvertible(false) + .Build()); + + auto open_reader = [&](const std::shared_ptr& fs) + -> Result> { + ReadContextBuilder builder(table_path); + builder.SetReadFieldNames({"id", "video"}) + .WithFileSystem(fs) + .AddOption(Options::READ_BATCH_SIZE, "128"); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr context, builder.Finish()); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr read, + TableRead::Create(std::move(context))); + return read->CreateReader(video_split); + }; + for (int batches_to_read : {1, 2}) { + auto fs = std::make_shared(".video"); + ASSERT_OK_AND_ASSIGN(auto reader, open_reader(fs)); + ASSERT_EQ(0u, fs->counts->opens.load()); + for (int i = 0; i < batches_to_read; ++i) { + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_FALSE(BatchReader::IsEofBatch(batch)); + auto array = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(array.ok()) << array.status().ToString(); + auto rows = checked_pointer_cast(*array); + ASSERT_EQ(2, rows->length()); + auto row_ids = checked_pointer_cast(rows->GetFieldByName("id")); + ASSERT_EQ(i * 2, row_ids->Value(0)); + ASSERT_EQ(i * 2 + 1, row_ids->Value(1)); + ASSERT_EQ(static_cast(i + 1), fs->counts->opens.load()); + } + if (batches_to_read == 2) { + ASSERT_OK_AND_ASSIGN(auto eof, reader->NextBatch()); + ASSERT_TRUE(BatchReader::IsEofBatch(eof)); + } + reader->Close(); + ASSERT_EQ(static_cast(batches_to_read), fs->counts->opens.load()); + } + + auto fs = std::make_shared("1.video"); + fs->before_open = [](const std::string&) { + return Status::IOError("cannot open second video"); + }; + ASSERT_OK_AND_ASSIGN(auto reader, open_reader(fs)); + ASSERT_OK_AND_ASSIGN(auto first_batch, reader->NextBatch()); + ASSERT_FALSE(BatchReader::IsEofBatch(first_batch)); + ReaderUtils::ReleaseReadBatch(std::move(first_batch)); + ASSERT_EQ(0u, fs->counts->opens.load()); + ASSERT_NOK_WITH_MSG(reader->NextBatch(), "cannot open second video"); + ASSERT_EQ(1u, fs->counts->opens.load()); + reader->Close(); +} + TEST_P(BlobTableInteTest, TestDataEvolutionBlobPartialUpdateFallback) { // the blob column is updated to null below, so it must be nullable arrow::FieldVector fields = {arrow::field("f0", arrow::int32()), @@ -2353,7 +2733,8 @@ TEST_P(BlobTableInteTest, TestDataEvolutionBlobPartialUpdateAllPlaceholderRowTra // the base layer itself holds a placeholder at row 1, so after the second layer also // leaves it untouched, row 1 is a placeholder in every layer - auto base_array = MakeBlobUpdateArray(fields[1], {"blob_a", "PH", "blob_c"}); + const std::string large_blob(1 << 20, 'a'); + auto base_array = MakeBlobUpdateArray(fields[1], {large_blob, "PH", "blob_c"}); ASSERT_OK_AND_ASSIGN(auto commit_msgs0, WriteArray(table_path, {}, {"b0"}, {base_array})); SetFirstRowId(/*reset_first_row_id=*/0, commit_msgs0); ASSERT_OK(Commit(table_path, commit_msgs0)); @@ -2378,7 +2759,17 @@ TEST_P(BlobTableInteTest, TestDataEvolutionBlobPartialUpdateAllPlaceholderRowTra struct_array->GetFieldByName(SpecialFields::SequenceNumber().Name())); ASSERT_TRUE(blob_col && row_id_col && seq_col); - ASSERT_EQ(blob_col->GetString(0), "blob_a"); + ASSERT_EQ(blob_col->GetString(0), large_blob); + ASSERT_OK_AND_ASSIGN(auto plan, ScanTable(table_path)); + std::shared_ptr measured_pool = GetMemoryPool(); + ReadContextBuilder builder(table_path); + builder.WithMemoryPool(measured_pool).SetReadFieldNames({"_SEQUENCE_NUMBER"}); + ASSERT_OK_AND_ASSIGN(auto read_context, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto read, TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(auto reader, read->CreateReader(plan->Splits())); + ASSERT_OK_AND_ASSIGN(auto sequence_only, ReadResultCollector::CollectResult(std::move(reader))); + ASSERT_EQ(3, sequence_only->length()); + ASSERT_LT(measured_pool->MaxMemoryUsage(), large_blob.size()); ASSERT_EQ(blob_col->GetString(2), "update_c"); // the all-placeholder row: null blob, row id kept, sequence number -1 ASSERT_TRUE(blob_col->IsNull(1)); @@ -3522,6 +3913,40 @@ TEST_P(BlobTableInteTest, TestBlobDescriptorField) { ASSERT_TRUE(read_struct->GetFieldByName("b1")->Equals(desc_array->GetFieldByName("b1"))); } +TEST_P(BlobTableInteTest, RoundTripsInlineVideoFrameDescriptor) { + if (GetParam() == "mosaic") { + GTEST_SKIP() << "Mosaic does not support inline BLOB descriptor fields"; + } + const arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + BlobUtils::ToArrowField("ref", true)}; + CreateTable(fields, {}, + {{Options::FILE_FORMAT, GetParam()}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {Options::BLOB_DESCRIPTOR_FIELD, "ref"}}); + const auto path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadJavaVideoFixture("video-frame-descriptor-v1.hex")); + auto ids = arrow::ipc::internal::json::ArrayFromJSON(arrow::int32(), "[1]").ValueOrDie(); + auto write = [&](const std::string& descriptor) { + auto refs = MakeBlobUpdateArray(fields[1], {descriptor}); + auto rows = arrow::StructArray::Make({ids, refs->field(0)}, fields).ValueOrDie(); + return WriteArray(path, {}, {"id", "ref"}, {rows}); + }; + ASSERT_NOK_WITH_MSG(write(bytes.substr(0, bytes.size() - 1)), + "invalid video frame descriptor length"); + ASSERT_OK_AND_ASSIGN(auto messages, write(bytes)); + ASSERT_OK(Commit(path, messages)); + ASSERT_OK_AND_ASSIGN(auto result, ScanAndReadResult(path, {"ref"})); + ASSERT_EQ(result->length(), 1); + auto rows = checked_pointer_cast(result->chunk(0)); + auto refs = checked_pointer_cast(rows->GetFieldByName("ref")); + const auto stored = refs->GetView(0); + ASSERT_EQ(stored, bytes); + ASSERT_OK_AND_ASSIGN(auto frame, Blob::FromDescriptor(stored.data(), stored.size())); + ASSERT_TRUE(frame->IsVideoFrame()); + ASSERT_EQ(frame->FrameIndex(), 42); +} + TEST_P(BlobTableInteTest, TestBlobDescriptorFieldPartialInline) { if (GetParam() == "mosaic") { return; @@ -4550,6 +4975,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") { 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