diff --git a/docs/source/user_guide/read.rst b/docs/source/user_guide/read.rst index d55a141c1..906364bfb 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``. +Use ``VideoFrameDescriptor::Deserialize()`` for the frame index and MP4 moov range. +Open the encoded video with ``Blob::FromPath()`` using the URI, offset and length +from ``Payload()``. + +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/video_frame_descriptor.h b/include/paimon/data/video_frame_descriptor.h new file mode 100644 index 000000000..00873734a --- /dev/null +++ b/include/paimon/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/include/paimon/defs.h b/include/paimon/defs.h index a39a2e128..e10be2c46 100644 --- a/include/paimon/defs.h +++ b/include/paimon/defs.h @@ -608,6 +608,8 @@ struct PAIMON_EXPORT Options { /// serialized BlobViewStruct bytes inline in data files and resolve from upstream tables at /// read time. No default value. static const char BLOB_VIEW_FIELD[]; + /// Scalar BLOB columns that store video frame descriptors. + static const char VIDEO_FRAME_FIELD[]; /// "blob-view.resolve.enabled" - Whether to resolve blob-view-field values from upstream /// tables at read time. Set to false to preserve serialized BlobViewStruct bytes when /// forwarding blob view values to another blob-view table. Default value is "true". 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..87a1fa09e 100644 --- a/src/paimon/CMakeLists.txt +++ b/src/paimon/CMakeLists.txt @@ -30,6 +30,7 @@ set(PAIMON_COMMON_SRCS common/data/blob_descriptor.cpp common/data/blob_view.cpp common/data/blob_view_struct.cpp + common/data/video_frame_descriptor.cpp common/data/blob_utils.cpp common/data/columnar/columnar_array.cpp common/data/columnar/columnar_map.cpp diff --git a/src/paimon/common/data/blob_descriptor.cpp b/src/paimon/common/data/blob_descriptor.cpp index 5a020c9fc..f2d08652a 100644 --- a/src/paimon/common/data/blob_descriptor.cpp +++ b/src/paimon/common/data/blob_descriptor.cpp @@ -24,6 +24,7 @@ #include "fmt/format.h" #include "paimon/common/io/memory_segment_output_stream.h" #include "paimon/common/memory/memory_segment_utils.h" +#include "paimon/data/video_frame_descriptor.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/io/byte_order.h" #include "paimon/io/data_input_stream.h" @@ -73,6 +74,13 @@ 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 VideoFrameDescriptor::Deserialize"); + } auto input_stream = std::make_shared(buffer, size); DataInputStream in(std::move(input_stream)); in.SetOrder(ByteOrder::PAIMON_LITTLE_ENDIAN); @@ -91,6 +99,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 +114,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..35fdd3d83 100644 --- a/src/paimon/common/data/blob_utils.cpp +++ b/src/paimon/common/data/blob_utils.cpp @@ -35,6 +35,7 @@ #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/string_utils.h" #include "paimon/data/blob_descriptor.h" +#include "paimon/data/video_frame_descriptor.h" namespace arrow { class Array; } @@ -194,8 +195,12 @@ bool BlobUtils::IsBlobMetadata(const std::shared_ptr BlobUtils::ToArrowField( @@ -206,6 +211,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 +246,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..8bf89dd4c 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,10 @@ 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 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..5ee2f7a7e --- /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/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/defs.cpp b/src/paimon/common/defs.cpp index 703d13bda..5214ebe34 100644 --- a/src/paimon/common/defs.cpp +++ b/src/paimon/common/defs.cpp @@ -158,6 +158,7 @@ const char Options::BLOB_AS_DESCRIPTOR[] = "blob-as-descriptor"; const char Options::BLOB_FIELD[] = "blob-field"; const char Options::BLOB_DESCRIPTOR_FIELD[] = "blob-descriptor-field"; const char Options::FALLBACK_BLOB_DESCRIPTOR_FIELD[] = "blob.stored-descriptor-fields"; +const char Options::VIDEO_FRAME_FIELD[] = "video-frame-field"; const char Options::BLOB_VIEW_FIELD[] = "blob-view-field"; const char Options::BLOB_VIEW_RESOLVE_ENABLED[] = "blob-view.resolve.enabled"; const char Options::BLOB_WRITE_NULL_ON_MISSING_FILE[] = "blob-write-null-on-missing-file"; 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_evolution_file_reader.cpp b/src/paimon/common/reader/data_evolution_file_reader.cpp index 5cace4181..3e8853cef 100644 --- a/src/paimon/common/reader/data_evolution_file_reader.cpp +++ b/src/paimon/common/reader/data_evolution_file_reader.cpp @@ -20,11 +20,13 @@ #include "paimon/common/reader/data_evolution_file_reader.h" #include "arrow/array/array_nested.h" +#include "arrow/array/builder_primitive.h" #include "arrow/array/util.h" #include "arrow/c/abi.h" #include "arrow/c/bridge.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/reader/reader_utils.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/utils/arrow/arrow_utils.h" #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/arrow/status_utils.h" @@ -36,7 +38,8 @@ Result> DataEvolutionFileReader::Create std::vector>&& readers, const std::shared_ptr& read_schema, int32_t read_batch_size, const std::vector& reader_offsets, const std::vector& field_offsets, - const std::shared_ptr& arrow_pool) { + const std::shared_ptr& arrow_pool, + std::vector> sequence_columns) { if (read_schema->num_fields() == 0) { return Status::Invalid("read schema must not be empty"); } @@ -53,9 +56,11 @@ Result> DataEvolutionFileReader::Create return Status::Invalid("reader offset is out of range of readers"); } } - return std::unique_ptr( + auto result = std::unique_ptr( new DataEvolutionFileReader(std::move(readers), read_schema, read_batch_size, reader_offsets, field_offsets, arrow_pool)); + result->sequence_columns_ = std::move(sequence_columns); + return result; } Result DataEvolutionFileReader::NextBatchWithBitmap() { @@ -109,6 +114,26 @@ Result DataEvolutionFileReader::NextBatchWithB target_sub_array_vec.push_back(null_array); continue; } + if (!sequence_columns_.empty() && + read_schema_->field(i)->name() == SpecialFields::SequenceNumber().Name()) { + std::vector sequences; + for (const auto& [reader, field] : sequence_columns_) { + const auto values = checked_pointer_cast( + array_for_each_reader[reader]->field(field)); + sequences.push_back(values->raw_values()); + } + arrow::Int64Builder builder(arrow_pool_.get()); + PAIMON_RETURN_NOT_OK_FROM_ARROW(builder.Reserve(array_length)); + for (int64_t row = 0; row < array_length; ++row) { + int64_t latest = -1; + for (const auto* values : sequences) latest = std::max(latest, values[row]); + builder.UnsafeAppend(latest); + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr merged, + builder.Finish()); + target_sub_array_vec.push_back(std::move(merged)); + continue; + } const auto& sub_array = array_for_each_reader[reader_offsets_[i]]; assert(sub_array->num_fields() > field_offsets_[i]); // Each file is already aligned to its read schema by its FieldMappingReader. diff --git a/src/paimon/common/reader/data_evolution_file_reader.h b/src/paimon/common/reader/data_evolution_file_reader.h index 7f6961d8c..b077dd914 100644 --- a/src/paimon/common/reader/data_evolution_file_reader.h +++ b/src/paimon/common/reader/data_evolution_file_reader.h @@ -59,7 +59,8 @@ class DataEvolutionFileReader : public BatchReader { std::vector>&& readers, const std::shared_ptr& read_schema, int32_t read_batch_size, const std::vector& reader_offsets, const std::vector& field_offsets, - const std::shared_ptr& arrow_pool); + const std::shared_ptr& arrow_pool, + std::vector> sequence_columns = {}); Result NextBatch() override { return Status::Invalid( @@ -88,6 +89,8 @@ class DataEvolutionFileReader : public BatchReader { reader_eof_(readers_.size(), false), non_exist_array_vec_(read_schema->num_fields(), nullptr) {} + std::vector> sequence_columns_; + int64_t CalculateCachedArrayLength(size_t reader_idx) const; Result EnsureCachedArray(size_t reader_idx); 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..598eec177 100644 --- a/src/paimon/common/utils/delta_varint_compressor.cpp +++ b/src/paimon/common/utils/delta_varint_compressor.cpp @@ -52,27 +52,12 @@ std::vector DeltaVarintCompressor::Compress(const std::vector& da } Result> DeltaVarintCompressor::Decompress(const std::vector& bytes) { - if (bytes.empty()) { - return std::vector(); - } - - // 1. Decode ZigZag + Varint → delta - std::vector deltas; - deltas.reserve(bytes.size()); - size_t pos = 0; - while (pos < bytes.size()) { - PAIMON_ASSIGN_OR_RAISE(int64_t delta, DecodeVarint(bytes, &pos)); - deltas.push_back(delta); - } + return Decompress(bytes.data(), bytes.size()); +} - // 2. Delta decoding (use unsigned addition to avoid signed overflow UB) - std::vector result(deltas.size()); - result[0] = deltas[0]; - for (size_t i = 1; i < result.size(); i++) { - uint64_t reconstructed = - static_cast(result[i - 1]) + static_cast(deltas[i]); - result[i] = static_cast(reconstructed); - } +Result> DeltaVarintCompressor::Decompress(const char* data, size_t size) { + std::vector result; + PAIMON_RETURN_NOT_OK(DecompressInto(data, size, &result)); return result; } @@ -89,14 +74,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 +92,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..647777bc0 100644 --- a/src/paimon/common/utils/delta_varint_compressor.h +++ b/src/paimon/common/utils/delta_varint_compressor.h @@ -34,12 +34,27 @@ 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); + + template + static Status DecompressInto(const char* data, size_t size, + std::vector* values) { + values->clear(); + values->reserve(size); + uint64_t value = 0; + for (size_t pos = 0; pos < size;) { + PAIMON_ASSIGN_OR_RAISE(int64_t delta, DecodeVarint(data, size, &pos)); + value += static_cast(delta); + values->push_back(static_cast(value)); + } + return Status::OK(); + } 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/core_options.cpp b/src/paimon/core/core_options.cpp index 2e92d7c98..446cc517a 100644 --- a/src/paimon/core/core_options.cpp +++ b/src/paimon/core/core_options.cpp @@ -2077,6 +2077,21 @@ const std::vector& CoreOptions::GetBlobDescriptorFields() const { return impl_->blob_descriptor_fields; } +std::vector CoreOptions::GetVideoFrameFields( + const std::map& options) { + auto it = options.find(Options::VIDEO_FRAME_FIELD); + 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()}; +} + const std::vector& CoreOptions::GetBlobViewFields() const { return impl_->blob_view_fields; } diff --git a/src/paimon/core/core_options.h b/src/paimon/core/core_options.h index e513d5d93..cc8d20b78 100644 --- a/src/paimon/core/core_options.h +++ b/src/paimon/core/core_options.h @@ -314,6 +314,9 @@ class PAIMON_EXPORT CoreOptions { const std::vector& GetBlobFields() const; const std::vector& GetBlobDescriptorFields() const; + static std::vector GetVideoFrameFields( + const std::map& options); + const std::vector& GetBlobViewFields() const; bool BlobViewResolveEnabled() const; std::vector GetBlobInlineFields() const; 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..414d02957 100644 --- a/src/paimon/core/operation/abstract_split_read.cpp +++ b/src/paimon/core/operation/abstract_split_read.cpp @@ -459,11 +459,19 @@ Result> AbstractSplitRead::CreateFieldMappingRe PAIMON_ASSIGN_OR_RAISE(std::unique_ptr file_reader, CreateFileBatchReader(file_format_identifier, data_file_path, file_meta->file_size, std::move(reader_builder))); + if (BlobUtils::IsVideoFile(file_meta->file_name)) { + PAIMON_ASSIGN_OR_RAISE(uint64_t actual, file_reader->GetNumberOfRows()); + if (file_meta->row_count < 0 || actual != static_cast(file_meta->row_count)) { + return Status::Invalid(fmt::format("{}: manifest row count {}, video row count {}", + data_file_path, file_meta->row_count, actual)); + } + } if (VectorFileBatchReader::ContainsVector(read_schema)) { 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 +482,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..3bcd23b68 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" @@ -440,30 +441,44 @@ Result> DataEvolutionSplitRead::InnerCreateReader( continue; } } - DataEvolutionSplitRead group_read(path_factory_, context_, pool_, executor_); - group_read.file_indexes_evaluated_ = true; - group_read.group_selection_ = std::move(group_selection); + auto group_read = + std::make_shared(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 - PAIMON_ASSIGN_OR_RAISE( - std::vector> raw_file_readers, - group_read.CreateRawFileReaders(split_impl->Partition(), need_merge_files, - read_schema, push_down_predicate, group_dv_factory, - row_ranges, data_file_path_factory, - /*extra_format_options=*/{})); - if (raw_file_readers.empty()) { - continue; - } - if (raw_file_readers.size() != 1) { - return Status::Invalid("Single-file data evolution group created multiple readers"); + auto open = [group_read, partition = split_impl->Partition(), + file = need_merge_files.front(), read_schema, push_down_predicate, + group_dv_factory, row_ranges, + data_file_path_factory]() -> Result> { + PAIMON_ASSIGN_OR_RAISE( + std::vector> readers, + group_read->CreateRawFileReaders(partition, {file}, read_schema, + push_down_predicate, group_dv_factory, + row_ranges, data_file_path_factory, {})); + if (readers.empty()) { + return std::unique_ptr(); + } + if (readers.size() != 1) { + return Status::Invalid( + "Single-file data evolution group created multiple readers"); + } + return std::move(readers.front()); + }; + if (BlobUtils::IsVideoFile(need_merge_files.front()->file_name)) { + std::vector sources; + sources.push_back({need_merge_files.front()->file_name, std::move(open)}); + sub_readers.push_back( + std::make_unique(std::move(sources), arrow_pool_)); + } else { + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, open()); + if (reader) sub_readers.push_back(std::move(reader)); } - sub_readers.push_back(std::move(raw_file_readers[0])); } else { PAIMON_ASSIGN_OR_RAISE( std::unique_ptr evolution_reader, - group_read.CreateUnionReader(split_impl->Partition(), need_merge_files, row_ranges, - data_file_path_factory, group_dv_factory, group_dv, - read_schema)); + group_read->CreateUnionReader(split_impl->Partition(), need_merge_files, row_ranges, + data_file_path_factory, group_dv_factory, group_dv, + read_schema)); sub_readers.push_back(std::move(evolution_reader)); } } @@ -688,6 +703,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)); @@ -1067,6 +1095,12 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea return DataEvolutionUtils::IsNormalFile(bunch->Files()[0]->file_name); }); + const bool merge_blob_sequences = + fields_files.size() > 1 && + std::all_of(fields_files.begin(), fields_files.end(), [](const auto& bunch) { + return BlobUtils::IsBlobFile(bunch->Files()[0]->file_name); + }); + std::vector> sequence_columns; for (int32_t file_idx = 0; file_idx < static_cast(fields_files.size()); file_idx++) { const auto& bunch = fields_files[file_idx]; const auto& first_file = bunch->Files()[0]; @@ -1083,7 +1117,10 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea for (int32_t read_field_idx = 0; read_field_idx < static_cast(read_field_ids.size()); read_field_idx++) { // -1 indicates that the read fields are not matched - if (reader_offsets[read_field_idx] != -1) { + const bool collect_sequence = + merge_blob_sequences && + read_field_ids[read_field_idx] == SpecialFields::SequenceNumber().Id(); + if (!collect_sequence && reader_offsets[read_field_idx] != -1) { continue; } // Java takes sequence numbers from normal files before dedicated column files. @@ -1099,12 +1136,24 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea // is the offset the that row reader_offsets[read_field_idx] = file_idx; field_offsets[read_field_idx] = read_fields_in_file.size(); + if (collect_sequence) { + sequence_columns.emplace_back(file_idx, field_offsets[read_field_idx]); + } read_fields_in_file.push_back(all_read_fields[read_field_idx]); break; } } } + // 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 +1194,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, @@ -1187,7 +1248,7 @@ Result> DataEvolutionSplitRead::CreateFieldUnionRea std::unique_ptr reader, DataEvolutionFileReader::Create(std::move(file_batch_readers), read_schema, options_.GetReadBatchSize(), reader_offsets, field_offsets, - arrow_pool_)); + arrow_pool_, std::move(sequence_columns))); return reader; } @@ -1217,7 +1278,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 +1297,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 +1361,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 +1391,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..a2f65b09b 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 = CoreOptions::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, Options::VIDEO_FRAME_FIELD)); + 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..3baaead37 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 : CoreOptions::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..9cc81168c 100644 --- a/src/paimon/format/blob/CMakeLists.txt +++ b/src/paimon/format/blob/CMakeLists.txt @@ -14,8 +14,13 @@ # 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_format_factory.cpp + video_file_batch_reader.cpp) add_paimon_lib(paimon_blob_file_format SOURCES @@ -41,6 +46,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_format_writer.cpp b/src/paimon/format/blob/blob_format_writer.cpp index 1838849e7..3992f5e4a 100644 --- a/src/paimon/format/blob/blob_format_writer.cpp +++ b/src/paimon/format/blob/blob_format_writer.cpp @@ -41,6 +41,7 @@ #include "paimon/common/utils/math.h" #include "paimon/data/blob_descriptor.h" #include "paimon/data/decimal.h" +#include "paimon/data/video_frame_descriptor.h" #include "paimon/fs/file_system.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/logging.h" @@ -419,6 +420,10 @@ Result> BlobFormatWriter::WriteBlobElements( Result BlobFormatWriter::OpenBlobInputStream( std::string_view blob_data, std::optional element_index) { + if (VideoFrameDescriptor::HasMagic(blob_data.data(), blob_data.size()) && + VideoFrameDescriptor::Deserialize(blob_data.data(), blob_data.size()).ok()) { + 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..1110f340d 100644 --- a/src/paimon/format/blob/blob_format_writer_test.cpp +++ b/src/paimon/format/blob/blob_format_writer_test.cpp @@ -38,6 +38,7 @@ #include "paimon/common/utils/stream_utils.h" #include "paimon/data/blob.h" #include "paimon/data/blob_descriptor.h" +#include "paimon/data/video_frame_descriptor.h" #include "paimon/format/blob/blob_file_batch_reader.h" #include "paimon/fs/local/local_file_system.h" #include "paimon/testing/utils/read_result_collector.h" @@ -714,6 +715,37 @@ 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, WritesRawBytesWithOnlyVideoHeader) { + ASSERT_OK_AND_ASSIGN(std::shared_ptr writer, CreateDefaultWriter()); + const std::vector headers = {"xMRFOEDIV", "\x01MRFOEDIV"}; + for (const auto& bytes : headers) { + 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(), 2); + ASSERT_EQ(values->GetView(0), headers[0]); + ASSERT_EQ(values->GetView(1), headers[1]); +} + 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..352fd51e9 --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader.cpp @@ -0,0 +1,381 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "paimon/format/blob/video_file_batch_reader.h" + +#include +#include +#include + +#include "arrow/api.h" +#include "arrow/c/bridge.h" +#include "paimon/common/data/blob_defs.h" +#include "paimon/common/data/blob_utils.h" +#include "paimon/common/metrics/metrics_impl.h" +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/common/utils/arrow/mem_utils.h" +#include "paimon/common/utils/arrow/status_utils.h" +#include "paimon/common/utils/delta_varint_compressor.h" +#include "paimon/data/video_frame_descriptor.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;) { + PAIMON_ASSIGN_OR_RAISE(int64_t n, input->Read(data + read, size - read, offset + read)); + if (n <= 0) { + return Status::IOError("truncated video file"); + } + read += n; + } + 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; + for (int32_t length : lengths) { + if (length < 0 || length > start) { + return Status::Invalid("video indexes exceed the file size"); + } + start -= length; + // At most one decoded int64 per encoded byte. + decoded_bytes += static_cast(length) * sizeof(int64_t); + } + // 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]}); + const uint64_t 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), + videos_(arrow::stl::allocator(arrow_pool_.get())), + runs_(arrow::stl::allocator(arrow_pool_.get())) {} + +Result> VideoFileBatchReader::Create( + const std::shared_ptr& input, int32_t batch_size, bool emit_placeholder_sentinel, + const std::shared_ptr& blob_context, + const std::shared_ptr& pool) 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) { + using Index = std::vector>; + std::vector indexes; + indexes.reserve(index_lengths.size()); + for (size_t i = 0; i < index_lengths.size(); ++i) { + indexes.emplace_back(arrow::stl::allocator(arrow_pool_.get())); + PAIMON_RETURN_NOT_OK( + DeltaVarintCompressor::DecompressInto(data.data(), index_lengths[i], &indexes.back())); + 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; + decltype(videos_)(videos_.get_allocator()).swap(videos_); + decltype(runs_)(runs_.get_allocator()).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..49862ab37 --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader.h @@ -0,0 +1,112 @@ +/* + * 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 "arrow/stl_allocator.h" +#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, + bool emit_placeholder_sentinel, const std::shared_ptr& blob_context, + const std::shared_ptr& pool); + + 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..edc2cbdaa --- /dev/null +++ b/src/paimon/format/blob/video_file_batch_reader_test.cpp @@ -0,0 +1,636 @@ +/* + * 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 + +#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/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/data/video_frame_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, + VideoFrameDescriptor::Deserialize(bytes.data(), bytes.size())); + 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->Serialize(GetDefaultPool()); + ASSERT_EQ(std::string_view(serialized->data(), serialized->size()), bytes); + const auto& range = blob->Payload(); + ASSERT_OK_AND_ASSIGN(auto encoded_video, + Blob::FromPath(range.Uri(), range.Offset(), range.Length())); + ASSERT_OK_AND_ASSIGN(auto payload, encoded_video->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, VideoFrameDescriptor::Deserialize(bytes.data(), bytes.size())); + ASSERT_EQ(blob->FrameIndex(), 9); + ASSERT_EQ(blob->MoovOffset(), 0); + ASSERT_EQ(blob->MoovLength(), 0); + const auto& range = blob->Payload(); + ASSERT_OK_AND_ASSIGN(auto encoded_video, + Blob::FromPath(range.Uri(), range.Offset(), range.Length())); + ASSERT_OK_AND_ASSIGN(auto second_payload, encoded_video->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, + VideoFrameDescriptor::Deserialize(bytes.data(), bytes.size())); + ASSERT_EQ(frame->FrameIndex(), i == 0 ? 4 : 9); + ASSERT_EQ(frame->MoovOffset(), i == 0 ? 2 : 0); + const auto& range = frame->Payload(); + ASSERT_OK_AND_ASSIGN(auto encoded_video, + Blob::FromPath(range.Uri(), range.Offset(), range.Length())); + ASSERT_OK_AND_ASSIGN(auto payload, encoded_video->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, ReadVideoFixture("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"); +} + +class FaultPool final : public MemoryPool { + public: + bool fail = true; + uint64_t limit = std::numeric_limits::max(); + std::shared_ptr delegate = GetMemoryPool(); + void* Malloc(uint64_t size, uint64_t alignment) override { + // Fail the Bytes allocation. Arrow's aligned builders may still allocate. + if ((fail && alignment == 0) || size > limit - CurrentUsage()) { + throw std::bad_alloc(); + } + return delegate->Malloc(size, alignment); + } + void* Realloc(void* ptr, size_t old_size, size_t new_size, uint64_t alignment) override { + return delegate->Realloc(ptr, old_size, new_size, alignment); + } + void Free(void* ptr, uint64_t size) override { + delegate->Free(ptr, size); + } + uint64_t CurrentUsage() const override { + return delegate->CurrentUsage(); + } + uint64_t MaxMemoryUsage() const override { + return delegate->MaxMemoryUsage(); + } +}; + +TEST(VideoFileBatchReaderTest, ReportsIndexAndFrameAllocationFailures) { + ASSERT_OK_AND_ASSIGN(std::string bytes, ReadVideoFixture("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, ReadVideoFixture("video-frame-descriptor-v1.hex")); + ASSERT_OK_AND_ASSIGN(std::unique_ptr blob, + VideoFrameDescriptor::Deserialize(bytes.data(), bytes.size())); + ASSERT_EQ(blob->Payload().Uri(), "s3://bucket/视频.mp4"); + ASSERT_EQ(blob->FrameIndex(), 42); + ASSERT_EQ(blob->MoovOffset(), 0); + ASSERT_EQ(blob->MoovLength(), 0); + auto serialized = blob->Serialize(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(), bytes.size())); + ASSERT_NOK(VideoFrameDescriptor::Deserialize(bytes.data(), 5)); + ASSERT_NOK(VideoFrameDescriptor::Deserialize(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, false, nullptr, GetDefaultPool()); + 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, + VideoFrameDescriptor::Deserialize(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, false, context, GetDefaultPool())); + 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, false, nullptr, GetDefaultPool())); + ::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, ReadVideoFixture("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, false, nullptr, GetDefaultPool())); + 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, false, nullptr, GetDefaultPool())); + 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, false, nullptr, GetDefaultPool()), + "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, false, nullptr, GetDefaultPool()); + 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, false, nullptr, GetDefaultPool()); + 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()); + auto pool = std::make_shared(); + pool->fail = false; + pool->limit = 4 * 1024 * 1024; + auto limited = VideoFileBatchReader::Create(input, 2, false, nullptr, pool); + ASSERT_TRUE(limited.status().IsOutOfMemory()); + ASSERT_EQ(pool->CurrentUsage(), 0u); + pool->limit = 64 * 1024 * 1024; + ASSERT_OK_AND_ASSIGN(auto reader, VideoFileBatchReader::Create(input, 2, false, nullptr, pool)); + ASSERT_GE(pool->CurrentUsage(), kRuns * 3 * sizeof(int64_t)); + 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, false, nullptr, GetDefaultPool()); + 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/format/blob/video_file_format.h b/src/paimon/format/blob/video_file_format.h new file mode 100644 index 000000000..22950137d --- /dev/null +++ b/src/paimon/format/blob/video_file_format.h @@ -0,0 +1,54 @@ +/* + * 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 "paimon/format/blob/video_reader_builder.h" +#include "paimon/format/file_format.h" + +namespace paimon::blob { + +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_; +}; + +} // namespace paimon::blob diff --git a/src/paimon/format/blob/video_file_format_factory.cpp b/src/paimon/format/blob/video_file_format_factory.cpp new file mode 100644 index 000000000..42c411836 --- /dev/null +++ b/src/paimon/format/blob/video_file_format_factory.cpp @@ -0,0 +1,42 @@ +/* + * 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/blob_defs.h" +#include "paimon/common/utils/options_utils.h" +#include "paimon/factories/factory.h" +#include "paimon/format/blob/video_file_format.h" +#include "paimon/format/file_format_factory.h" + +namespace paimon::blob { +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); + } +}; + +REGISTER_PAIMON_FACTORY(VideoFileFormatFactory); +} // namespace paimon::blob diff --git a/src/paimon/format/blob/video_reader_builder.h b/src/paimon/format/blob/video_reader_builder.h new file mode 100644 index 000000000..dfa70f3c5 --- /dev/null +++ b/src/paimon/format/blob/video_reader_builder.h @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "paimon/common/reader/blob_read_context.h" +#include "paimon/format/blob/video_file_batch_reader.h" +#include "paimon/format/reader_builder.h" +#include "paimon/memory/memory_pool.h" + +namespace paimon::blob { + +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_, emit_placeholder_sentinel_, + blob_context_, pool_); + } + + private: + int32_t batch_size_; + bool emit_placeholder_sentinel_; + std::shared_ptr pool_ = GetDefaultPool(); + std::shared_ptr blob_context_; +}; + +} // namespace paimon::blob 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..892728ef0 --- /dev/null +++ b/src/paimon/testing/utils/video_test_utils.h @@ -0,0 +1,58 @@ +/* + * 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 ReadVideoFixture(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; + std::string line; + if (!std::getline(input, line) || line.empty()) { + return Status::Invalid("empty video fixture"); + } + 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)); + } + 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..0fd0c359c 100644 --- a/test/inte/blob_table_inte_test.cpp +++ b/test/inte/blob_table_inte_test.cpp @@ -62,6 +62,7 @@ #include "paimon/core/utils/snapshot_manager.h" #include "paimon/data/blob.h" #include "paimon/data/blob_descriptor.h" +#include "paimon/data/video_frame_descriptor.h" #include "paimon/defs.h" #include "paimon/file_store_write.h" #include "paimon/format/mosaic/mosaic_format_defs.h" @@ -80,10 +81,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 +142,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 +1332,410 @@ 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"}, + {Options::VIDEO_FRAME_FIELD, 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"}, + {Options::VIDEO_FRAME_FIELD, "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 = {{Options::VIDEO_FRAME_FIELD, ""}}; + // 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, ReadVideoFixture("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()); + } + } + + ASSERT_NOK_WITH_MSG(ReadTable(table_path, {"video", "_ROW_ID", "_SEQUENCE_NUMBER"}, delta), + "placeholder"); + 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, + VideoFrameDescriptor::Deserialize(bytes.data(), bytes.size())); + ASSERT_EQ(frame->FrameIndex(), 7); + ASSERT_EQ(frame->MoovOffset(), 16); + ASSERT_EQ(frame->MoovLength(), 8); + const auto& range = frame->Payload(); + ASSERT_OK_AND_ASSIGN(auto encoded_video, + Blob::FromPath(range.Uri(), range.Offset(), range.Length())); + ASSERT_OK_AND_ASSIGN(auto payload, encoded_video->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"}, + {Options::VIDEO_FRAME_FIELD, "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 first 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, ReadVideoFixture("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)); + 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()); + ASSERT_EQ(1u, delta->Splits().size()); + auto committed = checked_pointer_cast(delta->Splits()[0]); + ASSERT_EQ(2u, committed->DataFiles().size()); + const auto update_sequence = committed->DataFiles().front()->max_sequence_number; + for (const std::vector& projection : std::vector>{ + {"a", "b", "_ROW_ID", "part", "id", "_SEQUENCE_NUMBER"}, + {"part"}, + {"id"}, + {"_SEQUENCE_NUMBER"}}) { + 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 numbers = rows->GetFieldByName("_SEQUENCE_NUMBER")) { + auto values = checked_pointer_cast(numbers); + ASSERT_EQ(update_sequence, values->Value(0)); + ASSERT_EQ(update_sequence, values->Value(1)); + } + if (auto videos = rows->GetFieldByName("b")) { + ASSERT_FALSE(videos->IsNull(0)); + ASSERT_TRUE(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"}, + {Options::VIDEO_FRAME_FIELD, "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, ReadVideoFixture("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 packs = video_split->DataFiles(); + packs.erase(packs.begin()); + ASSERT_OK_AND_ASSIGN(auto only_video, + DataSplitImpl::Builder(split->Partition(), split->Bucket(), + split->BucketPath(), std::move(packs)) + .WithSnapshot(split->SnapshotId()) + .WithTotalBuckets(split->TotalBuckets()) + .RawConvertible(false) + .Build()); + { + auto fs = std::make_shared(".video"); + ReadContextBuilder builder(table_path); + builder.SetReadFieldNames({"_ROW_ID"}).WithFileSystem(fs); + ASSERT_OK_AND_ASSIGN(auto ctx, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto read, TableRead::Create(std::move(ctx))); + ASSERT_OK_AND_ASSIGN(auto reader, read->CreateReader(only_video)); + ASSERT_EQ(0u, fs->counts->opens.load()); + ASSERT_OK_AND_ASSIGN(auto batch, reader->NextBatch()); + ASSERT_EQ(2, batch.first->length); + ReaderUtils::ReleaseReadBatch(std::move(batch)); + reader->Close(); + ASSERT_EQ(1u, fs->counts->opens.load()); + } + + 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(); + + only_video->DataFiles().front()->row_count = 1; + auto mismatch = std::make_shared(plan->SnapshotId(), + std::vector>{only_video}); + for (const auto& projection : + {std::vector{"_ROW_ID"}, std::vector{"video", "_ROW_ID"}}) { + auto result = ReadTable(table_path, projection, mismatch); + ASSERT_NOK_WITH_MSG(result, "0.video"); + ASSERT_NOK_WITH_MSG(result, "manifest row count 1, video row count 2"); + } +} + 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 +2761,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 +2787,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 +3941,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, ReadVideoFixture("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, + VideoFrameDescriptor::Deserialize(stored.data(), stored.size())); + ASSERT_EQ(frame->FrameIndex(), 42); +} + TEST_P(BlobTableInteTest, TestBlobDescriptorFieldPartialInline) { if (GetParam() == "mosaic") { return; @@ -4550,6 +5003,94 @@ 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"}, + {Options::VIDEO_FRAME_FIELD, "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, ReadVideoFixture("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, + VideoFrameDescriptor::Deserialize(bytes.data(), bytes.size())); + ASSERT_EQ(frame->FrameIndex(), 8 - row); + ASSERT_EQ(frame->MoovOffset(), 16); + ASSERT_EQ(frame->MoovLength(), 8); + const auto& range = frame->Payload(); + ASSERT_OK_AND_ASSIGN(auto encoded_video, + Blob::FromPath(range.Uri(), range.Offset(), range.Length())); + ASSERT_OK_AND_ASSIGN(auto payload, encoded_video->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/README.md b/test/test_data/video_format.data/README.md new file mode 100644 index 000000000..a3d06436c --- /dev/null +++ b/test/test_data/video_format.data/README.md @@ -0,0 +1,25 @@ + + +# Java video fixtures + +Apache Paimon #10905, commit `5faef60f6fee`. Each file contains one hex-encoded record. + +- video-v1-moov.hex — Single video, moov at offset 16, two frames starting at 7. +- video-frame-descriptor-v1.hex — Video frame descriptor v1 with optional moov range. 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..41c1b9b93 --- /dev/null +++ b/test/test_data/video_format.data/video-frame-descriptor-v1.hex @@ -0,0 +1 @@ +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..61b22a14a --- /dev/null +++ b/test/test_data/video_format.data/video-v1-moov.hex @@ -0,0 +1 @@ +0000000866747970000000086d646174000000086d6f6f7630201004000e0100000001000000010000000100000001000000010000004944454f01