This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git
The following commit(s) were added to refs/heads/main by this push:
new 1920eab1 [core][python] Support packed video frame writes (#1423)
1920eab1 is described below
commit 1920eab1c60d2b5680fb767dbd60ae0cf668db78
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 17 11:09:07 2026 +0800
[core][python] Support packed video frame writes (#1423)
---
bindings/python/README.md | 43 ++
bindings/python/python/pypaimon_rust/data.pyi | 47 +-
bindings/python/src/lib.rs | 2 +
bindings/python/src/video.rs | 308 +++++++++++++
.../python/tests/test_blob_partial_checkpoint.py | 115 +++++
bindings/python/tests/test_video_write.py | 267 ++++++++++++
crates/paimon/src/arrow/format/mod.rs | 8 +
crates/paimon/src/arrow/format/video.rs | 3 +
crates/paimon/src/arrow/format/video/writer.rs | 475 +++++++++++++++++++++
.../paimon/src/arrow/format/video/writer/tests.rs | 299 +++++++++++++
crates/paimon/src/table/data_evolution_reader.rs | 224 +++++++++-
crates/paimon/src/table/data_file_writer.rs | 17 +
.../src/table/dedicated_format_file_writer.rs | 10 +-
crates/paimon/src/table/internal.rs | 59 +++
crates/paimon/src/table/table_write.rs | 14 +-
crates/paimon/tests/blob_collection_write_test.rs | 5 +-
crates/paimon/tests/video_write_test.rs | 214 ++++++++++
docs/src/sql.md | 8 +
18 files changed, 2098 insertions(+), 20 deletions(-)
diff --git a/bindings/python/README.md b/bindings/python/README.md
index ef3d3ef0..7674ff9c 100644
--- a/bindings/python/README.md
+++ b/bindings/python/README.md
@@ -318,6 +318,49 @@ and closure for scalar, array and map Blob writes,
including managed primary-key
Blob packs. Exceptions raised by Python source callbacks are propagated to the
caller. The Python layer does not copy payloads or cache source streams.
+### Packed video frame writes
+
+Append-only tables with `data-evolution.enabled=true` can store scalar BLOB
+columns as packed videos by setting `video-frame-field` to their
comma-separated
+names. Supply serialized `VideoFrameDescriptor` values in Arrow binary columns;
+the batch and stream table writers route these columns to `.video` files and
+commit them alongside normal columns. Reads return lazy frame descriptors.
+Raw video bytes and ordinary BlobDescriptors are rejected for these columns.
+Video-column updates, video compaction, and BlobConsumer callbacks are
unsupported.
+
+For PyPaimon format-writer adapters, the low-level API owns a Python binary
+output stream and accepts the same descriptor bytes as PyPaimon:
+
+```python
+from pypaimon_rust.data import VideoFormatWriter, VideoFrameDescriptor
+
+output = open("packed.video", "wb")
+writer = VideoFormatWriter(output, copy_buffer_size=4096)
+try:
+ frames = [VideoFrameDescriptor("file:///data/source.mp4", 0, -1,
i).serialize()
+ for i in range(100)]
+ writer.write_frames(frames) # PyPaimon VideoFrameDescriptor.serialize()
also works
+ file_size = writer.close() # writes indexes and closes output; safe to
repeat
+except BaseException:
+ writer.abort()
+ raise
+```
+
+`write_arrow(batch)` accepts one `large_binary` column of descriptors and
NULLs.
+The same video URI/range is copied once per output file, and consecutive frame
+ordinals share one run. `num_bytes()` reports payload bytes before close and
total
+file bytes after close. Packing does not require the optional video decoding
+dependencies.
+
+Pass `uri_reader_factory=file_io.uri_reader_factory` to use PyPaimon's source
+readers; the factory/stream protocol is described above. Without a custom
+factory, the low-level API resolves local files and HTTP sources. Each distinct
+physical video is copied with bounded reads and its source stream is closed.
+The output stream must provide `write(bytes)` and `close()`; `flush()` is
optional.
+Write and close errors preserve the original Python exception and close the
output
+stream. `abort()` closes without writing a footer. The caller removes
incomplete
+destinations and owns table metadata and commit handling for this low-level
API.
+
### Native commit from serialized messages
The Python binding follows Java's batch/stream builder structure. Use
diff --git a/bindings/python/python/pypaimon_rust/data.pyi
b/bindings/python/python/pypaimon_rust/data.pyi
index aa876f29..58abb269 100644
--- a/bindings/python/python/pypaimon_rust/data.pyi
+++ b/bindings/python/python/pypaimon_rust/data.pyi
@@ -15,10 +15,55 @@
# specific language governing permissions and limitations
# under the License.
-from typing import Sequence
+from typing import BinaryIO, Optional, Sequence
import pyarrow
+from .uri_reader import UriReaderFactory
+
+class VideoFrameDescriptor:
+ """Java/PyPaimon-compatible reference to one frame of a complete encoded
video."""
+ def __init__(self, uri: str, offset: int, length: int, frame_index: int,
+ moov_offset: int = 0, moov_length: int = 0) -> None: ...
+ @property
+ def uri(self) -> str: ...
+ @property
+ def offset(self) -> int: ...
+ @property
+ def length(self) -> int: ...
+ @property
+ def frame_index(self) -> int: ...
+ @property
+ def moov_offset(self) -> int: ...
+ @property
+ def moov_length(self) -> int: ...
+ def serialize(self) -> bytes: ...
+ @staticmethod
+ def deserialize(value: bytes) -> "VideoFrameDescriptor": ...
+
+class VideoFormatWriter:
+ """Own an output stream and pack encoded videos without decoding them.
+
+ Sources default to local files/HTTP. Supply a URI factory for PyPaimon
FileIO.
+ A failed write closes the stream; callers remove the incomplete
destination.
+ """
+ def __init__(self, output_stream: BinaryIO, *,
+ uri_reader_factory: Optional[UriReaderFactory] = None,
+ copy_buffer_size: int = 4096) -> None: ...
+ def write_frames(self, frames: Sequence[Optional[bytes]]) -> None:
+ """Accept serialized VideoFrameDescriptors from Rust or PyPaimon, and
NULLs."""
+ ...
+ def write_arrow(self, batch: pyarrow.RecordBatch) -> None:
+ """Accept one large_binary column of frame descriptors."""
+ ...
+ def num_bytes(self) -> int: ...
+ def close(self) -> int:
+ """Finalize and close; return the total file size. Repeated close is
safe."""
+ ...
+ def abort(self) -> None:
+ """Close without finalizing. The caller removes the incomplete
output."""
+ ...
+
def read_arrow_schema(fields: str) -> pyarrow.Schema:
"""Build the runtime read schema from Paimon fields (JSON)."""
...
diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs
index 49565faf..70cf29a7 100644
--- a/bindings/python/src/lib.rs
+++ b/bindings/python/src/lib.rs
@@ -46,6 +46,7 @@ mod udf;
mod update_assignment;
mod variant;
mod vector_search;
+mod video;
mod vindex;
mod write;
mod write_routing;
@@ -62,5 +63,6 @@ fn pypaimon_rust(py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_function(wrap_pyfunction!(temporal::temporal_match, m)?)?;
variant::register_module(py, m)?;
evolution::register_module(m)?;
+ video::register_module(m)?;
Ok(())
}
diff --git a/bindings/python/src/video.rs b/bindings/python/src/video.rs
new file mode 100644
index 00000000..42935d6a
--- /dev/null
+++ b/bindings/python/src/video.rs
@@ -0,0 +1,308 @@
+// 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.
+
+//! Descriptor and stream transport for PyPaimon; packed-video semantics live
in core.
+
+use crate::blob_uri_reader::{
+ callback_error, to_callback_error, PythonUriReaderFactory,
PythonUriReferences,
+};
+use crate::error::to_py_err;
+use arrow::array::{ArrayRef, LargeBinaryArray, RecordBatch};
+use bytes::Bytes;
+use paimon::io::{FileIOBuilder, FileWrite, UriReaderFactory};
+use paimon::spec::VideoFrameDescriptor;
+use paimon::table::internal::PackedVideoWriter;
+use paimon_datafusion::runtime::runtime;
+use pyo3::exceptions::{PyIOError, PyRuntimeError, PyTypeError, PyValueError};
+use pyo3::prelude::*;
+use pyo3::types::PyBytes;
+use pyo3::{PyTraverseError, PyVisit};
+use std::sync::{Arc, Mutex};
+
+#[pyclass(
+ name = "VideoFrameDescriptor",
+ module = "pypaimon_rust.data",
+ frozen,
+ eq,
+ skip_from_py_object
+)]
+#[derive(Clone, PartialEq)]
+struct PyVideoFrameDescriptor {
+ inner: VideoFrameDescriptor,
+}
+
+#[pymethods]
+impl PyVideoFrameDescriptor {
+ #[new]
+ #[pyo3(signature = (uri, offset, length, frame_index, moov_offset=0,
moov_length=0))]
+ fn new(
+ uri: String,
+ offset: i64,
+ length: i64,
+ frame_index: i64,
+ moov_offset: i64,
+ moov_length: i64,
+ ) -> PyResult<Self> {
+ let inner = VideoFrameDescriptor::new(uri, offset, length, frame_index)
+ .and_then(|frame| frame.with_moov(moov_offset, moov_length))
+ .map_err(to_py_err)?;
+ inner.payload_descriptor().validate().map_err(to_py_err)?;
+ Ok(Self { inner })
+ }
+ #[getter]
+ fn uri(&self) -> &str {
+ self.inner.payload_descriptor().uri()
+ }
+ #[getter]
+ fn offset(&self) -> i64 {
+ self.inner.payload_descriptor().offset()
+ }
+ #[getter]
+ fn length(&self) -> i64 {
+ self.inner.payload_descriptor().length()
+ }
+ #[getter]
+ fn frame_index(&self) -> i64 {
+ self.inner.frame_index()
+ }
+ #[getter]
+ fn moov_offset(&self) -> i64 {
+ self.inner.moov_offset()
+ }
+ #[getter]
+ fn moov_length(&self) -> i64 {
+ self.inner.moov_length()
+ }
+ fn serialize<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
+ PyBytes::new(py, &self.inner.serialize())
+ }
+ #[staticmethod]
+ fn deserialize(value: &[u8]) -> PyResult<Self> {
+ Ok(Self {
+ inner:
VideoFrameDescriptor::deserialize(value).map_err(to_py_err)?,
+ })
+ }
+}
+
+type OutputSlot = Arc<Mutex<Option<Py<PyAny>>>>;
+
+struct PythonOutput(OutputSlot);
+
+impl PythonOutput {
+ fn close_stream(&self) -> PyResult<()> {
+ let stream = self.0.lock().unwrap().take();
+ if let Some(stream) = stream {
+ let flush: PyResult<()> = tokio::task::block_in_place(|| {
+ Python::attach(|py| {
+ if stream.bind(py).hasattr("flush")? {
+ stream.bind(py).call_method0("flush")?;
+ }
+ Ok(())
+ })
+ });
+ let close: PyResult<()> = tokio::task::block_in_place(|| {
+ Python::attach(|py| {
+ stream.bind(py).call_method0("close")?;
+ Ok(())
+ })
+ });
+ flush?;
+ close?;
+ }
+ Ok(())
+ }
+}
+
+#[async_trait::async_trait]
+impl FileWrite for PythonOutput {
+ async fn write(&mut self, bytes: Bytes) -> paimon::Result<()> {
+ tokio::task::block_in_place(|| {
+ Python::attach(|py| {
+ let stream = self
+ .0
+ .lock()
+ .unwrap()
+ .as_ref()
+ .map(|stream| stream.clone_ref(py))
+ .ok_or_else(|| PyRuntimeError::new_err("Video output
stream is closed"))?;
+ let written = stream
+ .bind(py)
+ .call_method1("write", (PyBytes::new(py, &bytes),))?;
+ if !written.is_none() && written.extract::<usize>()? !=
bytes.len() {
+ return Err(PyIOError::new_err("Short write to video output
stream"));
+ }
+ Ok(())
+ })
+ })
+ .map_err(callback_error)
+ }
+ async fn close(&mut self) -> paimon::Result<()> {
+ self.close_stream().map_err(callback_error)
+ }
+}
+
+impl Drop for PythonOutput {
+ fn drop(&mut self) {
+ let _ = self.close_stream();
+ }
+}
+
+#[pyclass(name = "VideoFormatWriter", module = "pypaimon_rust.data")]
+struct PyVideoFormatWriter {
+ inner: Mutex<Option<PackedVideoWriter>>,
+ output: OutputSlot,
+ references: Arc<PythonUriReferences>,
+ completed_size: Option<u64>,
+}
+
+impl PyVideoFormatWriter {
+ fn write_batch(&mut self, py: Python<'_>, batch: RecordBatch) ->
PyResult<()> {
+ let writer = self
+ .inner
+ .get_mut()
+ .unwrap()
+ .as_mut()
+ .ok_or_else(|| PyRuntimeError::new_err("Video writer is closed"))?;
+ let result = py.detach(|| runtime().block_on(writer.write(&batch)));
+ self.references.prune();
+ if let Err(error) = result {
+ self.abort(py);
+ return Err(to_callback_error(error));
+ }
+ Ok(())
+ }
+}
+
+#[pymethods]
+impl PyVideoFormatWriter {
+ #[new]
+ #[pyo3(signature = (output_stream, *, uri_reader_factory=None,
copy_buffer_size=4096))]
+ fn new(
+ py: Python<'_>,
+ output_stream: Py<PyAny>,
+ uri_reader_factory: Option<Py<PyAny>>,
+ copy_buffer_size: usize,
+ ) -> PyResult<Self> {
+ if copy_buffer_size == 0 {
+ return Err(PyValueError::new_err(
+ "Video copy buffer size must be positive",
+ ));
+ }
+ for name in ["write", "close"] {
+ if !output_stream.bind(py).getattr(name)?.is_callable() {
+ return Err(PyTypeError::new_err(format!(
+ "output_stream.{name} must be callable"
+ )));
+ }
+ }
+ let references = Arc::new(PythonUriReferences::default());
+ let factory = uri_reader_factory
+ .map(|factory| {
+ PythonUriReaderFactory::tracked(factory, py,
references.clone())
+ .map(|factory| Arc::new(factory) as Arc<dyn
UriReaderFactory>)
+ })
+ .transpose()?;
+ let io = FileIOBuilder::new("fs").build().map_err(to_py_err)?;
+ let output = Arc::new(Mutex::new(Some(output_stream)));
+ let inner = PackedVideoWriter::new(
+ Box::new(PythonOutput(output.clone())),
+ Some(io),
+ factory,
+ copy_buffer_size,
+ )
+ .map_err(to_py_err)?;
+ Ok(Self {
+ inner: Mutex::new(Some(inner)),
+ output,
+ references,
+ completed_size: None,
+ })
+ }
+
+ /// Write serialized frame descriptors (including bytes from PyPaimon) and
NULLs.
+ fn write_frames(&mut self, py: Python<'_>, frames: Vec<Option<Vec<u8>>>)
-> PyResult<()> {
+ let values = LargeBinaryArray::from(
+ frames
+ .iter()
+ .map(|frame| frame.as_deref())
+ .collect::<Vec<_>>(),
+ );
+ let batch = RecordBatch::try_from_iter([("frame", Arc::new(values) as
ArrayRef)])
+ .map_err(|error| PyTypeError::new_err(error.to_string()))?;
+ self.write_batch(py, batch)
+ }
+
+ /// Write one large_binary Arrow column of serialized frame descriptors.
+ fn write_arrow(&mut self, py: Python<'_>, batch: &Bound<'_, PyAny>) ->
PyResult<()> {
+ self.write_batch(py, crate::arrow_input::batch_from_pyarrow(batch)?)
+ }
+
+ fn num_bytes(&self) -> usize {
+ self.completed_size.map_or_else(
+ || {
+ self.inner
+ .lock()
+ .unwrap()
+ .as_ref()
+ .map_or(0, |writer| writer.num_bytes())
+ },
+ |size| size as usize,
+ )
+ }
+
+ /// Finalize indexes, close the owned output stream, and return its total
size.
+ fn close(&mut self, py: Python<'_>) -> PyResult<u64> {
+ if let Some(size) = self.completed_size {
+ return Ok(size);
+ }
+ let mut writer = self
+ .inner
+ .get_mut()
+ .unwrap()
+ .take()
+ .ok_or_else(|| PyRuntimeError::new_err("Video writer is closed"))?;
+ let result = py.detach(|| runtime().block_on(writer.close()));
+ self.references.clear();
+ let size = result.map_err(to_callback_error)?;
+ self.completed_size = Some(size);
+ Ok(size)
+ }
+
+ /// Close without a footer. The caller removes any incomplete destination.
+ fn abort(&mut self, py: Python<'_>) {
+ if let Some(mut writer) = self.inner.get_mut().unwrap().take() {
+ let _ = py.detach(|| runtime().block_on(writer.abort()));
+ }
+ self.references.clear();
+ }
+
+ fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
+ visit.call(&*self.output.lock().unwrap())?;
+ self.references.traverse(visit)
+ }
+
+ fn __clear__(&mut self) {
+ self.inner.get_mut().unwrap().take();
+ self.references.clear();
+ }
+}
+
+pub(crate) fn register_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
+ let data = module.getattr("data")?.cast_into::<PyModule>()?;
+ data.add_class::<PyVideoFrameDescriptor>()?;
+ data.add_class::<PyVideoFormatWriter>()
+}
diff --git a/bindings/python/tests/test_blob_partial_checkpoint.py
b/bindings/python/tests/test_blob_partial_checkpoint.py
new file mode 100644
index 00000000..19b99cb3
--- /dev/null
+++ b/bindings/python/tests/test_blob_partial_checkpoint.py
@@ -0,0 +1,115 @@
+# 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.
+
+from pathlib import Path
+from urllib.parse import urlparse
+
+import pyarrow as pa
+import pytest
+
+from pypaimon_rust.data import VideoFrameDescriptor
+from pypaimon_rust.datafusion import PaimonCatalog, SQLContext
+
+
[email protected]('video', [False, True], ids=['blob', 'video'])
+def
test_update_checkpoints_then_append_without_blob_preserves_payloads(tmp_path,
video):
+ source = tmp_path / 'source.mp4'
+ source.write_bytes(b'abc')
+ context = SQLContext()
+ context.register_catalog('paimon', {'warehouse': str(tmp_path)})
+ context.sql('CREATE SCHEMA paimon.checkpoints')
+ video_option = ", 'video-frame-field' = 'frame'" if video else ''
+ context.sql("""CREATE TABLE paimon.checkpoints.t (id INT, n INT, frame
BLOB) WITH (
+ 'data-evolution.enabled' = 'true', 'row-tracking.enabled' = 'true',
+ 'compaction.min.file-num' = '5' %s)"""
+ % video_option)
+ table = PaimonCatalog({'warehouse':
str(tmp_path)}).get_table('checkpoints.t')
+ payload = (VideoFrameDescriptor(source.as_uri(), 0, 3, 7).serialize()
+ if video else b'abc')
+
+ def batch(index):
+ return pa.record_batch([pa.array([index], type=pa.int32()),
+ pa.array([index], type=pa.int32()),
+ pa.array([payload], type=pa.large_binary())],
+ names=['id', 'n', 'frame'])
+
+ builder = table.new_batch_write_builder()
+ writer = builder.new_write()
+ try:
+ writer.write_arrow(batch(0))
+ builder.new_commit().commit(writer.prepare_commit())
+ finally:
+ writer.close()
+ row_id = context.sql('SELECT "_ROW_ID" FROM
paimon.checkpoints.t')[0].column(0)[0].as_py()
+ builder = table.new_batch_write_builder()
+ update = builder.new_update()
+ builder.new_commit().commit(update.update_by_arrow_with_row_id(pa.table({
+ '_ROW_ID': pa.array([row_id], type=pa.int64()),
+ 'n': pa.array([99], type=pa.int32()),
+ })))
+
+ builder =
table.new_stream_write_builder().with_commit_user('blob-checkpoints')
+ writer = builder.new_write()
+ try:
+ for checkpoint in [1, 2]:
+ writer.write_arrow(batch(checkpoint))
+ builder.new_commit().commit(checkpoint,
writer.prepare_commit(True, checkpoint))
+ finally:
+ writer.close()
+
+ builder = table.new_batch_write_builder()
+ writer = builder.new_write()
+ try:
+ writer.with_write_type(['id', 'n'])
+ writer.write_arrow(pa.record_batch([pa.array([4], type=pa.int32()),
+ pa.array([4], type=pa.int32())],
+ names=['id', 'n']))
+ builder.new_commit().commit(writer.prepare_commit())
+ finally:
+ writer.close()
+
+ # The seed, update and three appends reach five normal files. Compaction
merges
+ # their logical rows, while the physical BLOB files cover only the first
three.
+ files = pa.Table.from_batches(context.sql(
+ 'SELECT file_format, record_count, first_row_id, file_source '
+ 'FROM paimon.checkpoints.t$files')).to_pylist()
+ assert any(file['file_format'] == 'parquet' and file['record_count'] == 4
+ and file['first_row_id'] == row_id and file['file_source'] ==
'COMPACT'
+ for file in files)
+ rows = pa.Table.from_batches(context.sql(
+ 'SELECT "_ROW_ID", id, n, frame FROM paimon.checkpoints.t ORDER BY
id')).to_pydict()
+ assert rows['id'] == [0, 1, 2, 4]
+ assert rows['n'] == [99, 1, 2, 4]
+ assert rows['_ROW_ID'] == [row_id + offset for offset in range(4)]
+ assert rows['frame'][3] is None
+ if video:
+ for value in rows['frame'][:3]:
+ frame = VideoFrameDescriptor.deserialize(value)
+ assert frame.frame_index == 7
+ assert frame.length == 3
+ assert frame.uri.endswith('.video')
+ uri = urlparse(frame.uri)
+ path = Path(uri.path if uri.scheme == 'file' else frame.uri)
+ with path.open('rb') as packed:
+ packed.seek(frame.offset)
+ assert packed.read(frame.length) == b'abc'
+ else:
+ assert rows['frame'][:3] == [b'abc'] * 3
+ omitted = pa.Table.from_batches(context.sql(
+ 'SELECT id, frame FROM paimon.checkpoints.t WHERE "_ROW_ID" = %d'
+ % (row_id + 3))).to_pydict()
+ assert omitted == {'id': [4], 'frame': [None]}
diff --git a/bindings/python/tests/test_video_write.py
b/bindings/python/tests/test_video_write.py
new file mode 100644
index 00000000..e5572e3e
--- /dev/null
+++ b/bindings/python/tests/test_video_write.py
@@ -0,0 +1,267 @@
+# 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.
+
+import gc
+import io
+import struct
+import threading
+import weakref
+from pathlib import Path
+
+import pyarrow as pa
+import pytest
+
+from pypaimon_rust.data import VideoFormatWriter, VideoFrameDescriptor
+from pypaimon_rust.datafusion import PaimonCatalog, SQLContext
+from test_blob_uri_reader import ReaderFactory
+
+
+class Output(io.BytesIO):
+ def __init__(self):
+ super().__init__()
+ self.result = None
+ self.close_count = 0
+
+ def close(self):
+ if not self.closed:
+ self.result = self.getvalue()
+ self.close_count += 1
+ super().close()
+
+
+def fixture(name):
+ root = Path(__file__).resolve().parents[3]
+ text = (root / 'crates/paimon/testdata/video' / name).read_text()
+ return bytes.fromhex(next(line for line in text.splitlines()
+ if line and not line.startswith('#')))
+
+
+def test_descriptor_matches_pypaimon_wire_layout_and_java_fixture():
+ value = VideoFrameDescriptor('s3://bucket/视频.mp4', 7, 99, 42)
+ assert value.serialize() == fixture('video-frame-descriptor-v1.hex')
+ assert VideoFrameDescriptor.deserialize(value.serialize()) == value
+ uri = b'custom://source'
+ # PyPaimon serializes descriptors independently of the native binding.
+ encoded = struct.pack('<BQi', 1, 0x564944454F46524D, len(uri)) + uri
+ encoded += struct.pack('<qqqqq', 0, 3, 7, 0, 0)
+ restored = VideoFrameDescriptor.deserialize(encoded)
+ assert (restored.uri, restored.offset, restored.length,
restored.frame_index) == (
+ 'custom://source', 0, 3, 7)
+ assert restored.serialize() == encoded
+ with pytest.raises(ValueError):
+ VideoFrameDescriptor('x', -1, 3, 0)
+
+
+def test_low_level_writer_matches_golden_file_and_owns_output(tmp_path):
+ source = tmp_path / 'mp4'
+ expected = fixture('video-v1-moov.hex')
+ source.write_bytes(expected[:24])
+ output = Output()
+ writer = VideoFormatWriter(output, copy_buffer_size=1)
+ writer.write_frames([VideoFrameDescriptor(source.as_uri(), 0, -1,
7).serialize()])
+ writer.write_arrow(pa.record_batch([
+ pa.array([VideoFrameDescriptor(source.as_uri(), 0, -1, 8).serialize()],
+ type=pa.large_binary())], names=['frame']))
+ assert writer.num_bytes() == 24
+ assert writer.close() == len(expected)
+ assert writer.close() == len(expected)
+ assert writer.num_bytes() == len(expected)
+ assert output.result == expected
+ assert output.close_count == 1
+ with pytest.raises(RuntimeError, match='closed'):
+ writer.write_frames([])
+
+
+def test_pypaimon_descriptors_writer_and_reader_interoperate(tmp_path):
+ blob = pytest.importorskip('pypaimon.table.row.blob')
+ from pypaimon.execution.python.read.reader.video_format_reader import
VideoFileMeta
+ from pypaimon.execution.python.write.video_format_writer import
VideoFormatWriter as PythonWriter
+ from pypaimon.schema.data_types import AtomicType, DataField
+ from pypaimon.table.row.generic_row import GenericRow
+ from pypaimon.table.row.row_kind import RowKind
+
+ source = tmp_path / 'source.mp4'
+ source.write_bytes(fixture('video-v1-moov.hex')[:24])
+
+ class Reader:
+ def new_input_stream(self, uri):
+ assert uri == source.as_uri()
+ return source.open('rb')
+
+ reader = Reader()
+
+ class Factory:
+ def create(self, uri):
+ return reader
+
+ descriptors = [blob.VideoFrameDescriptor(source.as_uri(), 0, 24, index)
+ for index in [7, 8, 10]]
+ encoded = [value.serialize() for value in descriptors] + [None]
+ output = Output()
+ writer = VideoFormatWriter(output, uri_reader_factory=Factory())
+ writer.write_frames(encoded)
+ writer.close()
+ meta = VideoFileMeta(io.BytesIO(output.result), len(output.result))
+ assert meta.record_count == 4
+ assert [meta.frame(i) for i in range(4)] == [
+ (0, 24, 7), (0, 24, 8), (0, 24, 10), None]
+ python_output = Output()
+ python_writer = PythonWriter(python_output)
+ field = DataField(0, 'frame', AtomicType('BLOB'))
+ for descriptor in [*descriptors, None]:
+ value = None if descriptor is None else
blob.Blob.from_descriptor(reader, descriptor)
+ python_writer.add_element(GenericRow([value], [field], RowKind.INSERT))
+ python_writer.close()
+ assert output.result == python_output.result
+
+
+def test_custom_sources_are_bounded_deduplicated_and_closed_once():
+ factory = ReaderFactory()
+ output = Output()
+ writer = VideoFormatWriter(output, uri_reader_factory=factory,
copy_buffer_size=3)
+ value = VideoFrameDescriptor('custom://source', 2, 3, 7).serialize()
+ writer.write_frames([value])
+ writer.write_frames([value, None])
+ writer.close()
+ assert output.result.startswith(b'234')
+ assert writer.num_bytes() == len(output.result)
+ assert factory.opens == factory.closes == 1
+
+
+def test_source_failure_preserves_python_exception_and_closes_output():
+ factory = ReaderFactory()
+ factory.failure = LookupError('video source failed')
+ output = Output()
+ writer = VideoFormatWriter(output, uri_reader_factory=factory)
+ with pytest.raises(LookupError) as caught:
+ writer.write_frames([VideoFrameDescriptor('custom://source', 0, 3,
0).serialize()])
+ assert caught.value is factory.failure
+ assert factory.opens == factory.closes == 1
+ assert output.close_count == 1
+ assert output.result == b''
+ writer.abort()
+
+
[email protected]('failure', ['write', 'flush', 'close', 'short'])
+def test_destination_failure_closes_once_and_preserves_exception(failure):
+ original = OSError('video output failed')
+
+ class FailingOutput(Output):
+ def write(self, value):
+ if failure == 'write':
+ raise original
+ if failure == 'short':
+ return max(0, len(value) - 1)
+ return super().write(value)
+
+ def flush(self):
+ if failure == 'flush':
+ raise original
+ return super().flush()
+
+ def close(self):
+ super().close()
+ if failure == 'close':
+ raise original
+
+ output = FailingOutput()
+ writer = VideoFormatWriter(output)
+ writer.write_frames([None])
+ with pytest.raises(OSError) as caught:
+ writer.close()
+ if failure != 'short':
+ assert caught.value is original
+ assert output.close_count == 1
+ writer.abort()
+
+
+def test_abandoned_writer_cycles_are_collected_on_another_thread():
+ output = Output()
+ factory = ReaderFactory()
+ writer = VideoFormatWriter(output, uri_reader_factory=factory)
+ output.writer = factory.writer = writer
+ references = [weakref.ref(output), weakref.ref(factory)]
+ del writer, output, factory
+ collector = threading.Thread(target=gc.collect)
+ collector.start()
+ collector.join()
+ assert all(reference() is None for reference in references)
+
+
[email protected]('stream', [False, True])
+def
test_table_writer_accepts_video_descriptors_and_reads_lazy_frames(tmp_path,
stream):
+ context = SQLContext()
+ context.register_catalog('paimon', {'warehouse': str(tmp_path)})
+ context.sql('CREATE SCHEMA paimon.videos')
+ context.sql("""CREATE TABLE paimon.videos.t (id INT, frame BLOB) WITH (
+ 'data-evolution.enabled' = 'true', 'row-tracking.enabled' = 'true',
+ 'video-frame-field' = 'frame', 'target-file-row-num' = '2')""")
+ table = PaimonCatalog({'warehouse': str(tmp_path)}).get_table('videos.t')
+ builder = table.new_stream_write_builder() if stream else
table.new_batch_write_builder()
+ writer = builder.new_write()
+ factory = ReaderFactory()
+ frames = [VideoFrameDescriptor('custom://source', 0, 5, index).serialize()
+ for index in [7, 8, 10]]
+ try:
+ with pytest.raises(NotImplementedError, match='BlobConsumer'):
+ writer.with_blob_consumer(lambda *args: False)
+ writer.with_blob_uri_reader_factory(factory)
+ data = pa.record_batch([pa.array([0, 1, 2, 3], type=pa.int32()),
+ pa.array([*frames, None],
type=pa.large_binary())],
+ names=['id', 'frame'])
+ writer.write_arrow(data.slice(0, 1))
+ writer.write_arrow(data.slice(1))
+ messages = writer.prepare_commit(True, 1) if stream else
writer.prepare_commit()
+ committer = builder.new_commit()
+ committer.commit(1, messages) if stream else committer.commit(messages)
+ finally:
+ writer.close()
+ assert factory.opens == factory.closes == 2 # one copy per rolled file
+ assert list(tmp_path.rglob('*.video'))
+ assert not list(tmp_path.rglob('*.blob'))
+ rows = pa.Table.from_batches(context.sql(
+ 'SELECT id, frame FROM paimon.videos.t ORDER BY id')).to_pydict()
+ assert rows['id'] == [0, 1, 2, 3]
+ assert rows['frame'][3] is None
+ for encoded, index in zip(rows['frame'], [7, 8, 10]):
+ frame = VideoFrameDescriptor.deserialize(encoded)
+ assert frame.frame_index == index
+ assert frame.uri.endswith('.video')
+ assert frame.length == 5
+
+
+def test_table_write_failure_discards_all_partial_files(tmp_path):
+ context = SQLContext()
+ context.register_catalog('paimon', {'warehouse': str(tmp_path)})
+ context.sql('CREATE SCHEMA paimon.videos')
+ context.sql("""CREATE TABLE paimon.videos.t (id INT, frame BLOB) WITH (
+ 'data-evolution.enabled' = 'true', 'row-tracking.enabled' = 'true',
+ 'video-frame-field' = 'frame')""")
+ table = PaimonCatalog({'warehouse': str(tmp_path)}).get_table('videos.t')
+ writer = table.new_batch_write_builder().new_write()
+ try:
+ writer.write_arrow(pa.record_batch([pa.array([0], type=pa.int32()),
+ pa.array([b'not a frame
descriptor'],
+ type=pa.large_binary())],
+ names=['id', 'frame']))
+ pytest.fail('raw video bytes must be rejected')
+ except ValueError:
+ pass
+ finally:
+ writer.close()
+ assert not list(tmp_path.rglob('*.video'))
+ assert not list(tmp_path.rglob('*.parquet'))
diff --git a/crates/paimon/src/arrow/format/mod.rs
b/crates/paimon/src/arrow/format/mod.rs
index 2b24de7e..b51f403a 100644
--- a/crates/paimon/src/arrow/format/mod.rs
+++ b/crates/paimon/src/arrow/format/mod.rs
@@ -506,6 +506,7 @@ fn supported_write_formats() -> Vec<&'static str> {
vec![
".parquet",
".blob",
+ ".video",
".orc",
".csv",
".json",
@@ -585,6 +586,13 @@ pub(crate) fn create_format_writer_factory(
format_options,
)?));
}
+ if file_format.eq_ignore_ascii_case("video") {
+ return Ok(Arc::new(video::VideoWriterFactory::new(
+ file_io,
+ write_fields,
+ format_options,
+ )?));
+ }
Ok(Arc::new(PlainFormatWriterFactory {
schema,
zstd_level,
diff --git a/crates/paimon/src/arrow/format/video.rs
b/crates/paimon/src/arrow/format/video.rs
index da8ac3c3..ecfbcd08 100644
--- a/crates/paimon/src/arrow/format/video.rs
+++ b/crates/paimon/src/arrow/format/video.rs
@@ -36,6 +36,9 @@ const FOOTER_SIZE: u64 = 29;
const MAGIC: i32 = 0x4F454449;
const VERSION: u8 = 1;
+pub(crate) mod writer;
+pub(crate) use writer::VideoWriterFactory;
+
fn corrupt(message: impl Into<String>) -> Error {
Error::DataInvalid {
message: format!("Corrupt video file: {}", message.into()),
diff --git a/crates/paimon/src/arrow/format/video/writer.rs
b/crates/paimon/src/arrow/format/video/writer.rs
new file mode 100644
index 00000000..5aff34e3
--- /dev/null
+++ b/crates/paimon/src/arrow/format/video/writer.rs
@@ -0,0 +1,475 @@
+// 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.
+
+//! Pack encoded videos once per physical source range and index logical frame
runs.
+
+use super::{FOOTER_SIZE, MAGIC, VERSION};
+use crate::arrow::format::delta_varint::encode_delta_varints;
+use crate::arrow::format::{FormatFileWriter, FormatWriteResult,
FormatWriterFactory};
+use crate::io::{FileIO, FileWrite, OutputFile, UriInputStream,
UriReaderFactory};
+use crate::spec::{BlobDescriptor, CoreOptions, DataField, DataType,
VideoFrameDescriptor};
+use crate::{Error, Result};
+use arrow_array::{LargeBinaryArray, RecordBatch};
+use async_trait::async_trait;
+use bytes::Bytes;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+fn invalid(message: impl Into<String>) -> Error {
+ Error::DataInvalid {
+ message: message.into(),
+ source: None,
+ }
+}
+
+pub(crate) struct VideoWriterFactory {
+ file_io: Option<FileIO>,
+ copy_buffer_size: usize,
+ uri_reader_factory: Option<Arc<dyn UriReaderFactory>>,
+}
+
+impl VideoWriterFactory {
+ pub(crate) fn new(
+ file_io: Option<FileIO>,
+ fields: Option<&[DataField]>,
+ options: Option<&HashMap<String, String>>,
+ ) -> Result<Self> {
+ if fields.is_some_and(|fields| {
+ fields.len() != 1 || !matches!(fields[0].data_type(),
DataType::Blob(_))
+ }) {
+ return Err(invalid("Video format only supports one scalar BLOB
field"));
+ }
+ let defaults = HashMap::new();
+ Ok(Self {
+ file_io,
+ copy_buffer_size: CoreOptions::new(options.unwrap_or(&defaults))
+ .blob_copy_buffer_size()?,
+ uri_reader_factory: None,
+ })
+ }
+
+ pub(crate) fn with_uri_reader_factory(
+ mut self,
+ factory: Option<Arc<dyn UriReaderFactory>>,
+ ) -> Self {
+ self.uri_reader_factory = factory;
+ self
+ }
+}
+
+#[async_trait]
+impl FormatWriterFactory for VideoWriterFactory {
+ async fn create_writer(
+ &self,
+ output: &OutputFile,
+ _compression: &str,
+ ) -> Result<Box<dyn FormatFileWriter>> {
+ Ok(Box::new(VideoFormatWriter::new(
+ output.writer().await?,
+ self.file_io.clone(),
+ self.uri_reader_factory.clone(),
+ self.copy_buffer_size,
+ )?))
+ }
+}
+
+struct FrameRun {
+ length: i64,
+ reference: i64,
+ first_frame: i64,
+}
+
+pub(crate) struct VideoFormatWriter {
+ writer: Box<dyn FileWrite>,
+ file_io: Option<FileIO>,
+ uri_reader_factory: Option<Arc<dyn UriReaderFactory>>,
+ copy_buffer_size: usize,
+ bytes_written: u64,
+ rows: i64,
+ physical_videos: HashMap<(String, i64, i64), i64>,
+ physical_lengths: Vec<i64>,
+ moov_offsets: Vec<i64>,
+ moov_lengths: Vec<i64>,
+ runs: Vec<FrameRun>,
+}
+
+impl VideoFormatWriter {
+ #[cfg(feature = "internal-api")]
+ pub(crate) async fn abort(mut self: Box<Self>) -> Result<()> {
+ self.writer.close().await
+ }
+
+ pub(crate) fn new(
+ writer: Box<dyn FileWrite>,
+ file_io: Option<FileIO>,
+ uri_reader_factory: Option<Arc<dyn UriReaderFactory>>,
+ copy_buffer_size: usize,
+ ) -> Result<Self> {
+ if copy_buffer_size == 0 {
+ return Err(invalid("Video copy buffer size must be positive"));
+ }
+ Ok(Self {
+ writer,
+ file_io,
+ uri_reader_factory,
+ copy_buffer_size,
+ bytes_written: 0,
+ rows: 0,
+ physical_videos: HashMap::new(),
+ physical_lengths: Vec::new(),
+ moov_offsets: Vec::new(),
+ moov_lengths: Vec::new(),
+ runs: Vec::new(),
+ })
+ }
+
+ fn append(&mut self, reference: i64, frame: i64) -> Result<()> {
+ if self.rows == i64::from(i32::MAX) {
+ return Err(invalid("Video row count exceeds i32"));
+ }
+ self.rows += 1;
+ if let Some(run) = self.runs.last_mut() {
+ if run.reference == reference
+ && (reference < 0 || run.first_frame.checked_add(run.length)
== Some(frame))
+ {
+ run.length += 1;
+ return Ok(());
+ }
+ }
+ self.runs.push(FrameRun {
+ length: 1,
+ reference,
+ first_frame: frame,
+ });
+ Ok(())
+ }
+
+ async fn write_bytes(&mut self, bytes: Bytes, locator: &mut MoovLocator)
-> Result<()> {
+ let end = self
+ .bytes_written
+ .checked_add(bytes.len() as u64)
+ .filter(|end| *end <= i64::MAX as u64)
+ .ok_or_else(|| invalid("Video payload size exceeds i64"))?;
+ locator.feed(&bytes);
+ self.writer.write(bytes).await?;
+ self.bytes_written = end;
+ Ok(())
+ }
+
+ async fn copy_stream(
+ &mut self,
+ stream: &mut dyn UriInputStream,
+ length: Option<u64>,
+ locator: &mut MoovLocator,
+ ) -> Result<()> {
+ let mut copied = 0;
+ loop {
+ let requested = length.map_or(self.copy_buffer_size, |length| {
+ (length - copied).min(self.copy_buffer_size as u64) as usize
+ });
+ if requested == 0 {
+ return Ok(());
+ }
+ let bytes = stream.read(requested).await?;
+ if bytes.len() > requested {
+ return Err(invalid("URI stream returned more bytes than
requested"));
+ }
+ if bytes.is_empty() {
+ return if length.is_some_and(|length| length != copied) {
+ Err(invalid("Unexpected EOF copying video payload"))
+ } else {
+ Ok(())
+ };
+ }
+ copied += bytes.len() as u64;
+ self.write_bytes(bytes, locator).await?;
+ }
+ }
+
+ async fn copy_video(
+ &mut self,
+ payload: &BlobDescriptor,
+ locator: &mut MoovLocator,
+ ) -> Result<()> {
+ let range = payload.range_spec()?;
+ if let Some(factory) = &self.uri_reader_factory {
+ if factory.supports_uri(payload.uri())? {
+ let reader = factory.create(payload.uri())?;
+ let mut stream = reader.new_input_stream(payload.uri()).await?;
+ let result = async {
+ if range.offset() != 0 {
+ stream.seek(range.offset()).await?;
+ }
+ self.copy_stream(stream.as_mut(), range.length(), locator)
+ .await
+ }
+ .await;
+ let close = stream.close().await;
+ result?;
+ return close;
+ }
+ }
+ let io = self.file_io.as_ref().ok_or_else(|| {
+ invalid(
+ "Video writer requires FileIO or a URI reader factory to
resolve frame payloads",
+ )
+ })?;
+ let input = crate::io::uri_reader::UriInput::new(io, payload.uri())?;
+ let length = match range.length() {
+ Some(length) => length,
+ None => input
+ .size()
+ .await?
+ .checked_sub(range.offset())
+ .ok_or_else(|| invalid("Video payload offset exceeds source
size"))?,
+ };
+ let end = range
+ .offset()
+ .checked_add(length)
+ .ok_or_else(|| invalid("Video payload range overflows u64"))?;
+ if length == 0 {
+ return Err(invalid("Encoded video payload must not be empty"));
+ }
+ let reader = input.reader_for_range(range.offset()..end).await?;
+ let mut position = range.offset();
+ while position < end {
+ // Separate remote read-ahead from the configured copy buffer.
+ let chunk_end = position.saturating_add(8 * 1024 * 1024).min(end);
+ let chunk = reader.read(position..chunk_end).await?;
+ if chunk.len() as u64 != chunk_end - position {
+ return Err(invalid("Unexpected EOF copying video payload"));
+ }
+ for start in (0..chunk.len()).step_by(self.copy_buffer_size) {
+ self.write_bytes(
+ chunk
+
.slice(start..start.saturating_add(self.copy_buffer_size).min(chunk.len())),
+ locator,
+ )
+ .await?;
+ }
+ position = chunk_end;
+ }
+ Ok(())
+ }
+
+ async fn write_frame(&mut self, value: &[u8]) -> Result<()> {
+ // Raw bytes and ordinary BlobDescriptors must never become encoded
videos.
+ let frame = VideoFrameDescriptor::deserialize(value)?;
+ let payload = frame.payload_descriptor();
+ let key = (
+ payload.uri().to_string(),
+ payload.offset(),
+ payload.length(),
+ );
+ let reference = match self.physical_videos.get(&key) {
+ Some(reference) => *reference,
+ None => {
+ let start = self.bytes_written;
+ let mut locator = MoovLocator::default();
+ self.copy_video(payload, &mut locator).await?;
+ let length = self.bytes_written - start;
+ if length == 0 {
+ return Err(invalid("Encoded video payload must not be
empty"));
+ }
+ let (offset, moov_length) = locator.finish();
+ let reference = self.physical_lengths.len() as i64;
+ self.physical_lengths.push(length as i64);
+ self.moov_offsets.push(offset);
+ self.moov_lengths.push(moov_length);
+ self.physical_videos.insert(key, reference);
+ reference
+ }
+ };
+ self.append(reference, frame.frame_index())
+ }
+}
+
+#[async_trait]
+impl FormatFileWriter for VideoFormatWriter {
+ async fn write(&mut self, batch: &RecordBatch) -> Result<()> {
+ if batch.num_columns() != 1 {
+ return Err(invalid("Video format only supports one scalar BLOB
field"));
+ }
+ let values = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<LargeBinaryArray>()
+ .ok_or_else(|| invalid("Video frame descriptors require
LargeBinaryArray"))?;
+ if batch.num_rows() as u64 > (i64::from(i32::MAX) - self.rows) as u64 {
+ return Err(invalid("Video row count exceeds i32"));
+ }
+ for value in values {
+ match value {
+ None => self.append(-1, 0)?,
+ Some(value) => self.write_frame(value).await?,
+ }
+ }
+ Ok(())
+ }
+ fn num_bytes(&self) -> usize {
+ self.bytes_written as usize
+ }
+ fn in_progress_size(&self) -> usize {
+ 0
+ }
+ async fn flush(&mut self) -> Result<()> {
+ self.writer.flush().await
+ }
+ async fn close(mut self: Box<Self>) -> Result<FormatWriteResult> {
+ let result: Result<FormatWriteResult> = async {
+ let indexes = [
+ encode_delta_varints(&self.physical_lengths),
+ encode_delta_varints(&self.moov_offsets),
+ encode_delta_varints(&self.moov_lengths),
+ encode_delta_varints(&self.runs.iter().map(|run|
run.length).collect::<Vec<_>>()),
+ encode_delta_varints(
+ &self
+ .runs
+ .iter()
+ .map(|run| run.reference)
+ .collect::<Vec<_>>(),
+ ),
+ encode_delta_varints(
+ &self
+ .runs
+ .iter()
+ .map(|run| run.first_frame)
+ .collect::<Vec<_>>(),
+ ),
+ ];
+ let mut footer = Vec::with_capacity(FOOTER_SIZE as usize);
+ for index in indexes {
+ let length =
+ i32::try_from(index.len()).map_err(|_| invalid("Video
index exceeds i32"))?;
+ footer.extend_from_slice(&length.to_le_bytes());
+ self.writer.write(index.into()).await?;
+ self.bytes_written += length as u64;
+ }
+ footer.extend_from_slice(&MAGIC.to_le_bytes());
+ footer.push(VERSION);
+ self.writer.write(footer.into()).await?;
+ Ok(FormatWriteResult::new(self.bytes_written + FOOTER_SIZE))
+ }
+ .await;
+ let close = self.writer.close().await;
+ let result = result?;
+ close?;
+ Ok(result)
+ }
+}
+
+/// Bounded-memory top-level MP4 box scanner. Invalid or non-MP4 streams have
no hint.
+struct MoovLocator {
+ position: u64,
+ next_box: Option<u64>,
+ header: Vec<u8>,
+ header_size: usize,
+ found: Option<(u64, u64)>,
+ valid: bool,
+}
+
+impl Default for MoovLocator {
+ fn default() -> Self {
+ Self {
+ position: 0,
+ next_box: Some(0),
+ header: Vec::with_capacity(16),
+ header_size: 8,
+ found: None,
+ valid: true,
+ }
+ }
+}
+
+impl MoovLocator {
+ fn feed(&mut self, data: &[u8]) {
+ let end = self.position + data.len() as u64;
+ while self.valid {
+ let Some(next) = self.next_box.filter(|next| *next < end) else {
+ break;
+ };
+ let start = (next + self.header.len() as
u64).saturating_sub(self.position) as usize;
+ let count = (self.header_size - self.header.len()).min(data.len()
- start);
+ self.header.extend_from_slice(&data[start..start + count]);
+ if self.header.len() < self.header_size {
+ break;
+ }
+ let size =
u32::from_be_bytes(self.header[..4].try_into().unwrap());
+ let moov = &self.header[4..8] == b"moov";
+ let size = if size == 1 {
+ self.header_size = 16;
+ if self.header.len() < 16 {
+ continue;
+ }
+ let size =
u64::from_be_bytes(self.header[8..16].try_into().unwrap());
+ if size == 0 {
+ self.valid = false;
+ break;
+ }
+ size
+ } else {
+ u64::from(size)
+ };
+ if moov {
+ if self.found.is_some() {
+ self.valid = false;
+ break;
+ }
+ self.found = Some((next, size));
+ }
+ if size == 0 {
+ self.next_box = None;
+ break;
+ }
+ if size < self.header_size as u64 {
+ self.valid = false;
+ break;
+ }
+ self.next_box = next.checked_add(size);
+ if self.next_box.is_none() {
+ self.valid = false;
+ break;
+ }
+ self.header.clear();
+ self.header_size = 8;
+ }
+ self.position = end;
+ }
+
+ fn finish(self) -> (i64, i64) {
+ if !self.valid
+ || self
+ .next_box
+ .is_some_and(|next| next != self.position ||
!self.header.is_empty())
+ {
+ return (0, 0);
+ }
+ self.found.map_or((0, 0), |(offset, size)| {
+ (
+ offset as i64,
+ if size == 0 {
+ self.position - offset
+ } else {
+ size
+ } as i64,
+ )
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/paimon/src/arrow/format/video/writer/tests.rs
b/crates/paimon/src/arrow/format/video/writer/tests.rs
new file mode 100644
index 00000000..2073500a
--- /dev/null
+++ b/crates/paimon/src/arrow/format/video/writer/tests.rs
@@ -0,0 +1,299 @@
+// 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.
+
+use super::*;
+use crate::arrow::format::video::IndexedVideoReader;
+use crate::io::{FileIOBuilder, UriReader};
+use arrow_array::ArrayRef;
+use std::sync::Mutex;
+
+fn batch(values: &[Option<Vec<u8>>]) -> RecordBatch {
+ RecordBatch::try_from_iter([(
+ "frame",
+ Arc::new(LargeBinaryArray::from(
+ values.iter().map(|v| v.as_deref()).collect::<Vec<_>>(),
+ )) as ArrayRef,
+ )])
+ .unwrap()
+}
+
+fn frame(uri: &str, index: i64) -> Option<Vec<u8>> {
+ Some(
+ VideoFrameDescriptor::new(uri.into(), 0, -1, index)
+ .unwrap()
+ .serialize(),
+ )
+}
+
+fn fixture(text: &str) -> Vec<u8> {
+ hex::decode(
+ text.lines()
+ .find(|line| !line.is_empty() && !line.starts_with('#'))
+ .unwrap(),
+ )
+ .unwrap()
+}
+
+#[tokio::test]
+async fn video_writer_matches_java_python_golden_bytes_across_batches() {
+ let io = FileIOBuilder::new("memory").build().unwrap();
+ for (uri, bytes) in [
+ ("memory:/a", b"abc".as_slice()),
+ ("memory:/b", b"WXYZ".as_slice()),
+ ] {
+ io.new_output(uri)
+ .unwrap()
+ .write(Bytes::copy_from_slice(bytes))
+ .await
+ .unwrap();
+ }
+ let mut writer = Box::new(
+ VideoFormatWriter::new(
+ io.new_output("memory:/out.video")
+ .unwrap()
+ .writer()
+ .await
+ .unwrap(),
+ Some(io.clone()),
+ None,
+ 2,
+ )
+ .unwrap(),
+ );
+ writer
+ .write(&batch(&[frame("memory:/a", 2)]))
+ .await
+ .unwrap();
+ writer
+ .write(&batch(&[frame("memory:/a", 3), None]))
+ .await
+ .unwrap();
+ writer.append(-2, 0).unwrap();
+ writer
+ .write(&batch(&[
+ frame("memory:/b", 7),
+ frame("memory:/b", 8),
+ frame("memory:/a", 10),
+ ]))
+ .await
+ .unwrap();
+ assert_eq!(
+ writer.num_bytes(),
+ 7,
+ "repeated sources must not copy payload bytes again"
+ );
+ let result = writer.close().await.unwrap();
+ let actual = io
+ .new_input("memory:/out.video")
+ .unwrap()
+ .read()
+ .await
+ .unwrap();
+ assert_eq!(
+ actual.as_ref(),
+ fixture(include_str!("../../../../../testdata/video/video-v1.hex"))
+ );
+ assert_eq!(result.file_size, actual.len() as u64);
+}
+
+#[test]
+fn moov_scanner_handles_chunk_boundaries_extended_sizes_and_invalid_boxes() {
+ let mut ordinary = Vec::from(&b"\0\0\0\x10ftyp12345678\0\0\0\x08moov"[..]);
+ let extended = b"\0\0\0\x01moov\0\0\0\0\0\0\0\x10";
+ for (bytes, expected) in [
+ (ordinary.as_slice(), (16, 8)),
+ (extended.as_slice(), (0, 16)),
+ (b"\0\0\0\0moovdata".as_slice(), (0, 12)),
+ (b"not an mp4".as_slice(), (0, 0)),
+ (b"\0\0\0\x09moov".as_slice(), (0, 0)),
+ ] {
+ for size in 1..=bytes.len() {
+ let mut locator = MoovLocator::default();
+ for chunk in bytes.chunks(size) {
+ locator.feed(chunk);
+ }
+ assert_eq!(locator.finish(), expected, "chunk size {size}");
+ }
+ }
+ ordinary.extend_from_slice(b"\0\0\0\x08moov");
+ let mut locator = MoovLocator::default();
+ locator.feed(&ordinary);
+ assert_eq!(
+ locator.finish(),
+ (0, 0),
+ "duplicate moov is not a trustworthy hint"
+ );
+}
+
+#[tokio::test]
+async fn video_writer_matches_moov_fixture_and_rejects_non_frame_values() {
+ let io = FileIOBuilder::new("memory").build().unwrap();
+ let expected = fixture(include_str!(
+ "../../../../../testdata/video/video-v1-moov.hex"
+ ));
+ io.new_output("memory:/mp4")
+ .unwrap()
+ .write(Bytes::copy_from_slice(&expected[..24]))
+ .await
+ .unwrap();
+ let output = io.new_output("memory:/out.video").unwrap();
+ let mut writer = VideoWriterFactory::new(Some(io.clone()), None, None)
+ .unwrap()
+ .create_writer(&output, "")
+ .await
+ .unwrap();
+ writer
+ .write(&batch(&[frame("memory:/mp4", 7), frame("memory:/mp4", 8)]))
+ .await
+ .unwrap();
+ writer.close().await.unwrap();
+ let bytes = io
+ .new_input("memory:/out.video")
+ .unwrap()
+ .read()
+ .await
+ .unwrap();
+ assert_eq!(bytes.as_ref(), expected);
+ for value in [
+ b"raw mp4".to_vec(),
+ BlobDescriptor::new("memory:/mp4".into(), 0, 24).serialize(),
+ VideoFrameDescriptor::new("memory:/mp4".into(), -1, 24, 0)
+ .unwrap()
+ .serialize(),
+ VideoFrameDescriptor::new("memory:/mp4".into(), 0, 25, 0)
+ .unwrap()
+ .serialize(),
+ ] {
+ let mut writer = VideoWriterFactory::new(Some(io.clone()), None, None)
+ .unwrap()
+ .create_writer(&output, "")
+ .await
+ .unwrap();
+ assert!(writer.write(&batch(&[Some(value)])).await.is_err());
+ }
+ let mut writer = VideoWriterFactory::new(Some(io.clone()), None, None)
+ .unwrap()
+ .create_writer(&output, "")
+ .await
+ .unwrap();
+ writer.write(&batch(&[None, None])).await.unwrap();
+ writer.close().await.unwrap();
+ let input = io.new_input("memory:/out.video").unwrap();
+ let reader = input.reader().await.unwrap();
+ assert_eq!(
+ IndexedVideoReader::open(
+ &reader,
+ input.metadata().await.unwrap().size,
+ "memory:/out.video".into()
+ )
+ .await
+ .unwrap()
+ .num_rows(),
+ 2
+ );
+}
+
+struct Factory(Arc<Mutex<Vec<String>>>);
+struct Reader(Arc<Mutex<Vec<String>>>);
+struct Stream(Arc<Mutex<Vec<String>>>);
+impl UriReaderFactory for Factory {
+ fn create(&self, _: &str) -> Result<Arc<dyn UriReader>> {
+ Ok(Arc::new(Reader(self.0.clone())))
+ }
+}
+#[async_trait]
+impl UriReader for Reader {
+ async fn new_input_stream(&self, _: &str) -> Result<Box<dyn
UriInputStream>> {
+ self.0.lock().unwrap().push("open".into());
+ Ok(Box::new(Stream(self.0.clone())))
+ }
+}
+#[async_trait]
+impl UriInputStream for Stream {
+ async fn read(&mut self, _: usize) -> Result<Bytes> {
+ Err(invalid("source read failed"))
+ }
+ async fn close(&mut self) -> Result<()> {
+ self.0.lock().unwrap().push("close".into());
+ Err(invalid("source close failed"))
+ }
+}
+
+#[tokio::test]
+async fn copy_failure_closes_source_and_preserves_original_error() {
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let io = FileIOBuilder::new("memory").build().unwrap();
+ let mut writer = VideoWriterFactory::new(None, None, None)
+ .unwrap()
+ .with_uri_reader_factory(Some(Arc::new(Factory(events.clone()))))
+ .create_writer(&io.new_output("memory:/failed.video").unwrap(), "")
+ .await
+ .unwrap();
+ let error = writer
+ .write(&batch(&[frame("custom:/a", 0)]))
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("source read failed"));
+ assert_eq!(*events.lock().unwrap(), ["open", "close"]);
+}
+
+#[tokio::test]
+async fn frame_ordinals_and_row_counts_do_not_wrap() {
+ let io = FileIOBuilder::new("memory").build().unwrap();
+ let mut writer = VideoFormatWriter::new(
+ io.new_output("memory:/boundary.video")
+ .unwrap()
+ .writer()
+ .await
+ .unwrap(),
+ None,
+ None,
+ 1,
+ )
+ .unwrap();
+ writer.append(0, i64::MAX).unwrap();
+ writer.append(0, 0).unwrap();
+ writer.append(0, 1).unwrap();
+ assert_eq!(writer.runs.len(), 2);
+ assert_eq!(writer.runs[1].length, 2);
+ writer.rows = i64::from(i32::MAX);
+ assert!(writer.append(-1, 0).is_err());
+ assert!(writer.write(&batch(&[None])).await.is_err());
+}
+
+struct FailedOutput(Arc<Mutex<Vec<String>>>);
+#[async_trait]
+impl FileWrite for FailedOutput {
+ async fn write(&mut self, _: Bytes) -> Result<()> {
+ Err(invalid("footer write failed"))
+ }
+ async fn close(&mut self) -> Result<()> {
+ self.0.lock().unwrap().push("output close".into());
+ Err(invalid("output close failed"))
+ }
+}
+
+#[tokio::test]
+async fn footer_failure_still_closes_output_and_keeps_the_first_error() {
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let writer = Box::new(
+ VideoFormatWriter::new(Box::new(FailedOutput(events.clone())), None,
None, 1).unwrap(),
+ );
+ let error = writer.close().await.err().unwrap();
+ assert!(error.to_string().contains("footer write failed"));
+ assert_eq!(*events.lock().unwrap(), ["output close"]);
+}
diff --git a/crates/paimon/src/table/data_evolution_reader.rs
b/crates/paimon/src/table/data_evolution_reader.rs
index 42d25e3d..dfba3024 100644
--- a/crates/paimon/src/table/data_evolution_reader.rs
+++ b/crates/paimon/src/table/data_evolution_reader.rs
@@ -1941,7 +1941,13 @@ fn open_source_stream(
row_ranges.as_deref(),
anchor_deletion_vector.map(|context|
context.deletion_vector.as_ref()),
)?;
- if let Some(selected_ranges) = selected_ranges.as_deref() {
+ // The normal file owns the logical rows. A compacted normal file can
+ // span rows appended without this BLOB column, even on a full scan.
+ let expected_range = bunch.expected_range()?;
+ {
+ let selected_ranges = selected_ranges
+ .as_deref()
+ .unwrap_or(std::slice::from_ref(&expected_range));
let uncovered_ranges =
crate::table::source::exclude_row_ranges(selected_ranges,
bunch.logical_ranges());
if !uncovered_ranges.is_empty() {
@@ -2913,7 +2919,7 @@ fn build_source_plan_with_row_id_pushdown(
{
bunch.finalize()?;
if !read_fields.is_empty() && !row_id_pushdown {
- bunch.validate_logical_range()?;
+ bunch.validate_anchor_bounds()?;
}
}
}
@@ -3192,6 +3198,23 @@ impl BlobBunch {
Ok(())
}
+ /// Java BlobFileBunch uses the normal file's logical range. Physical BLOB
+ /// ranges may leave gaps, but cannot extend beyond that anchor on a full
scan.
+ fn validate_anchor_bounds(&self) -> crate::Result<()> {
+ let expected = self.expected_range()?;
+ for range in self.logical_ranges() {
+ if range.from() < expected.from() || range.to() > expected.to() {
+ return Err(Error::DataInvalid {
+ message: format!(
+ "Blob file range {range:?} should be within normal
file range {expected:?}"
+ ),
+ source: None,
+ });
+ }
+ }
+ Ok(())
+ }
+
#[cfg(test)]
fn sequence_groups(&self) -> impl Iterator<Item = &[DataFileMeta]> {
self.sequence_group_ranges
@@ -4750,7 +4773,7 @@ mod tests {
}
#[test]
- fn
test_build_source_plan_validates_complete_range_only_for_read_blob_source() {
+ fn test_build_source_plan_accepts_incomplete_read_blob_source() {
let files = vec![
data_file("data.parquet", 0, 100, 1, None),
data_file("payload.blob", 10, 90, 1, Some(vec!["payload"])),
@@ -4773,16 +4796,61 @@ mod tests {
DataField::new(1, "id".to_string(), DataType::Int(IntType::new())),
DataField::new(2, "payload".to_string(),
DataType::Blob(BlobType::new())),
];
- let err = build_source_plan(
+ let plan = build_source_plan(
&prepared_group,
&file_infos,
&read_type_with_blob,
&HashSet::new(),
)
- .unwrap_err();
- assert!(
- matches!(err, Error::DataInvalid { message, .. } if
message.contains("logical row ranges"))
- );
+ .unwrap();
+ assert_eq!(plan.column_plan, vec![Some((0, 0)), Some((1, 0))]);
+ }
+
+ #[test]
+ fn test_blob_anchor_bounds_allow_gaps_but_reject_shifted_ranges() {
+ for extension in ["blob", "video"] {
+ let mut bunch = BlobBunch::new(10, 10);
+ for (index, first) in [11, 16].into_iter().enumerate() {
+ bunch
+ .add(data_file(
+ &format!("gap-{index}.{extension}"),
+ first,
+ 2,
+ 1,
+ Some(vec!["payload"]),
+ ))
+ .unwrap();
+ }
+ bunch.finalize().unwrap();
+ bunch.validate_anchor_bounds().unwrap();
+ // Compaction of a physical range still requires complete coverage.
+ assert!(bunch.validate_logical_range().is_err());
+ for first in [9, 19] {
+ let files = vec![
+ data_file("normal.parquet", 10, 10, 1, Some(vec!["id"])),
+ data_file(
+ &format!("outside.{extension}"),
+ first,
+ 2,
+ 1,
+ Some(vec!["payload"]),
+ ),
+ ];
+ let group = PreparedMergeGroup::new(&files).unwrap();
+ let fields = vec![
+ DataField::new(1, "id".into(),
DataType::Int(IntType::new())),
+ DataField::new(2, "payload".into(),
DataType::Blob(BlobType::new())),
+ ];
+ let error = build_source_plan(
+ &group,
+ &[resolved_info(vec![1]), resolved_info(vec![2])],
+ &fields,
+ &HashSet::new(),
+ )
+ .unwrap_err();
+ assert!(error.to_string().contains("within normal file
range"));
+ }
+ }
}
#[test]
@@ -5655,6 +5723,146 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn test_full_blob_and_video_reads_fill_nullable_anchor_gaps() {
+ use crate::arrow::format::create_format_writer;
+ use crate::spec::VideoFrameDescriptor;
+
+ for extension in ["blob", "video"] {
+ for nullable in [true, false] {
+ let directory = tempdir().unwrap();
+ let table_path = local_file_path(directory.path());
+ let bucket_dir = directory.path().join("bucket-0");
+ fs::create_dir_all(&bucket_dir).unwrap();
+ let parquet_path = bucket_dir.join("data.parquet");
+ write_int_parquet_file(&parquet_path, vec![("id", vec![0, 1,
2, 3, 4])], None);
+ let source_path = directory.path().join("source.mp4");
+ fs::write(&source_path, b"payload").unwrap();
+ let file_io = FileIOBuilder::new("file").build().unwrap();
+ let mut schema = Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .column("payload",
DataType::Blob(BlobType::with_nullable(nullable)))
+ .option("data-evolution.enabled", "true")
+ .option("row-tracking.enabled", "true");
+ if extension == "video" {
+ schema = schema.option("video-frame-field", "payload");
+ }
+ let table = Table::new(
+ file_io.clone(),
+ Identifier::new("default", "gaps"),
+ table_path,
+ TableSchema::new(0, &schema.build().unwrap()),
+ None,
+ );
+ let mut files = vec![data_file_meta_with_path(
+ "data.parquet",
+ 100,
+ 5,
+ 1,
+ parquet_path.metadata().unwrap().len() as i64,
+ Some(vec!["id"]),
+ )];
+ for (index, first) in [101, 103].into_iter().enumerate() {
+ let name = format!("payload-{index}.{extension}");
+ let output = file_io
+ .new_output(&local_file_path(&bucket_dir.join(&name)))
+ .unwrap();
+ let value = if extension == "video" {
+
VideoFrameDescriptor::new(local_file_path(&source_path), 0, 7, index as i64)
+ .unwrap()
+ .serialize()
+ } else {
+ b"payload".to_vec()
+ };
+ let batch = RecordBatch::try_from_iter([(
+ "payload",
+
Arc::new(LargeBinaryArray::from(vec![Some(value.as_slice())]))
+ as arrow_array::ArrayRef,
+ )])
+ .unwrap();
+ let mut writer = create_format_writer(
+ &output,
+ batch.schema(),
+ "",
+ 0,
+ Some(file_io.clone()),
+ Some(&table.schema().fields()[1..]),
+ None,
+ )
+ .await
+ .unwrap();
+ writer.write(&batch).await.unwrap();
+ let size = writer.close().await.unwrap().file_size;
+ files.push(data_file_meta_with_path(
+ &name,
+ first,
+ 1,
+ 1,
+ size as i64,
+ Some(vec!["payload"]),
+ ));
+ }
+ for selected in [false, true] {
+ let mut builder = DataSplitBuilder::new()
+ .with_snapshot(1)
+ .with_partition(BinaryRow::new(0))
+ .with_bucket(0)
+ .with_bucket_path(local_file_path(&bucket_dir))
+ .with_total_buckets(1)
+ .with_data_files(files.clone());
+ if selected {
+ builder = builder.with_row_ranges(vec![
+ RowRange::new(101, 101),
+ RowRange::new(103, 103),
+ ]);
+ }
+ let split = builder.build().unwrap();
+ let read = TableRead::new(&table,
table.schema().fields().to_vec(), Vec::new());
+ let result = read
+ .to_arrow(&[split])
+ .unwrap()
+ .try_collect::<Vec<_>>()
+ .await;
+ if !nullable && !selected {
+ assert!(result
+ .unwrap_err()
+ .to_string()
+ .contains("non-nullable BLOB"));
+ continue;
+ }
+ let batches = result.unwrap();
+ assert_eq!(
+ collect_int_values(&batches, "id"),
+ if selected {
+ vec![1, 3]
+ } else {
+ vec![0, 1, 2, 3, 4]
+ }
+ );
+ let values = collect_binary_values(&batches, "payload");
+ let present: Vec<_> = values
+ .iter()
+ .enumerate()
+ .filter_map(|(index, value)| value.as_ref().map(|_|
index))
+ .collect();
+ assert_eq!(present, if selected { vec![0, 1] } else {
vec![1, 3] });
+ for (index, value) in
values.into_iter().flatten().enumerate() {
+ if extension == "video" {
+ assert_eq!(
+ VideoFrameDescriptor::deserialize(&value)
+ .unwrap()
+ .frame_index(),
+ index as i64
+ );
+ } else {
+ assert_eq!(value, b"payload");
+ }
+ }
+ }
+ }
+ }
+ }
+
#[tokio::test]
async fn test_selected_blob_fallback_fills_uncovered_nullable_range() {
use BlobFixtureValue::{Placeholder, Value};
diff --git a/crates/paimon/src/table/data_file_writer.rs
b/crates/paimon/src/table/data_file_writer.rs
index bc191f0f..a97ebea2 100644
--- a/crates/paimon/src/table/data_file_writer.rs
+++ b/crates/paimon/src/table/data_file_writer.rs
@@ -116,6 +116,7 @@ impl DataFileWriter {
let row_sidecar_enabled = options.data_evolution_enabled()
&& options.data_evolution_row_sidecar_enabled()?
&& !file_format.eq_ignore_ascii_case("blob")
+ && !file_format.eq_ignore_ascii_case("video")
&& !file_format.starts_with("vector.");
Ok(Self {
row_sidecar_enabled,
@@ -169,6 +170,22 @@ impl DataFileWriter {
uri_reader_factory: Option<Arc<dyn crate::io::UriReaderFactory>>,
) -> Result<()> {
debug_assert!(self.current_writer.is_none());
+ if self.file_format.eq_ignore_ascii_case("video") {
+ if consumer.is_some() {
+ return Err(crate::Error::Unsupported {
+ message: "BlobConsumer is not supported for video frame
fields".into(),
+ });
+ }
+ self.format_writer_factory = Some(Arc::new(
+ crate::arrow::format::video::VideoWriterFactory::new(
+ Some(self.file_io.clone()),
+ Some(&self.write_fields),
+ Some(&self.format_options),
+ )?
+ .with_uri_reader_factory(uri_reader_factory),
+ ));
+ return Ok(());
+ }
let mut factory = self.blob_writer_factory()?;
// Java BlobFormatWriter relinquishes deletion rights whenever a
// consumer can expose a descriptor, even if a later callback fails.
diff --git a/crates/paimon/src/table/dedicated_format_file_writer.rs
b/crates/paimon/src/table/dedicated_format_file_writer.rs
index a07d9829..cd090374 100644
--- a/crates/paimon/src/table/dedicated_format_file_writer.rs
+++ b/crates/paimon/src/table/dedicated_format_file_writer.rs
@@ -46,7 +46,7 @@ struct VectorFieldWriter {
///
/// Remaining columns go to the table's normal append `DataFileWriter`.
/// Each non-descriptor blob column gets its own `DataFileWriter` with
-/// `file_format = "blob"` and `write_cols = Some(vec![field_name])`.
+/// `file_format = "blob"` (or "video" for video-frame-field) and one write
column.
/// When `vector.file.format` is configured, all VECTOR columns are written
/// together to a dedicated `*.vector.<format>` file.
///
@@ -106,6 +106,7 @@ impl AppendDedicatedFormatFileWriter {
let mut vector_arrow_fields = Vec::new();
let mut vector_table_fields = Vec::new();
let mut vector_field_names = Vec::new();
+ let video_fields =
CoreOptions::new(format_options).video_frame_fields();
for (idx, field) in write_fields.iter().enumerate() {
let is_blob = field.data_type().is_blob_file_field();
@@ -130,7 +131,12 @@ impl AppendDedicatedFormatFileWriter {
String::new(),
0,
write_buffer_size,
- "blob".to_string(),
+ if video_fields.contains(field.name()) {
+ "video"
+ } else {
+ "blob"
+ }
+ .to_string(),
vec![field.clone()],
format_options.clone(),
Some(0),
diff --git a/crates/paimon/src/table/internal.rs
b/crates/paimon/src/table/internal.rs
index 497b57d5..29026069 100644
--- a/crates/paimon/src/table/internal.rs
+++ b/crates/paimon/src/table/internal.rs
@@ -28,6 +28,65 @@ use super::{
VectorRead, VectorScanPlan,
};
+/// Low-level packed video encoder for language bindings. The caller owns the
+/// output stream and publication; table writers should use the normal write
API.
+pub struct PackedVideoWriter {
+ inner: Option<Box<crate::arrow::format::video::writer::VideoFormatWriter>>,
+}
+
+impl PackedVideoWriter {
+ pub fn new(
+ output: Box<dyn crate::io::FileWrite>,
+ file_io: Option<crate::io::FileIO>,
+ uri_reader_factory: Option<std::sync::Arc<dyn
crate::io::UriReaderFactory>>,
+ copy_buffer_size: usize,
+ ) -> crate::Result<Self> {
+ Ok(Self {
+ inner: Some(Box::new(
+ crate::arrow::format::video::writer::VideoFormatWriter::new(
+ output,
+ file_io,
+ uri_reader_factory,
+ copy_buffer_size,
+ )?,
+ )),
+ })
+ }
+
+ pub async fn write(&mut self, batch: &arrow_array::RecordBatch) ->
crate::Result<()> {
+ use crate::arrow::format::FormatFileWriter;
+ self.inner
+ .as_mut()
+ .ok_or_else(|| crate::Error::DataInvalid {
+ message: "Video writer is closed".into(),
+ source: None,
+ })?
+ .write(batch)
+ .await
+ }
+
+ pub fn num_bytes(&self) -> usize {
+ use crate::arrow::format::FormatFileWriter;
+ self.inner.as_ref().map_or(0, |writer| writer.num_bytes())
+ }
+
+ pub async fn close(&mut self) -> crate::Result<u64> {
+ use crate::arrow::format::FormatFileWriter;
+ let writer = self.inner.take().ok_or_else(|| crate::Error::DataInvalid
{
+ message: "Video writer is closed".into(),
+ source: None,
+ })?;
+ Ok(writer.close().await?.file_size)
+ }
+
+ pub async fn abort(&mut self) -> crate::Result<()> {
+ if let Some(writer) = self.inner.take() {
+ writer.abort().await?;
+ }
+ Ok(())
+ }
+}
+
pub async fn execute_search_task(
table: &Table,
task: &[u8],
diff --git a/crates/paimon/src/table/table_write.rs
b/crates/paimon/src/table/table_write.rs
index 2f289d44..c4e07ca6 100644
--- a/crates/paimon/src/table/table_write.rs
+++ b/crates/paimon/src/table/table_write.rs
@@ -299,11 +299,6 @@ impl TableWrite {
let write_schema = build_target_arrow_schema(schema.fields())?;
let core_options = CoreOptions::new(schema.options());
let blob_descriptor_fields = core_options.blob_descriptor_fields();
- if !core_options.video_frame_fields().is_empty() {
- return Err(crate::Error::Unsupported {
- message: "Writing packed video files is not supported
yet".into(),
- });
- }
let blob_view_fields = core_options.blob_view_fields();
let blob_inline_fields = core_options.blob_inline_fields();
@@ -770,6 +765,15 @@ impl TableWrite {
message: "with_blob_consumer requires a Paimon table".into(),
});
}
+ if consumer.is_some()
+ && !CoreOptions::new(self.table.schema().options())
+ .video_frame_fields()
+ .is_empty()
+ {
+ return Err(crate::Error::Unsupported {
+ message: "BlobConsumer is not supported for video frame
fields".into(),
+ });
+ }
self.blob_consumer = consumer;
Ok(self)
}
diff --git a/crates/paimon/tests/blob_collection_write_test.rs
b/crates/paimon/tests/blob_collection_write_test.rs
index fa5df004..93f1943e 100644
--- a/crates/paimon/tests/blob_collection_write_test.rs
+++ b/crates/paimon/tests/blob_collection_write_test.rs
@@ -233,10 +233,7 @@ fn
video_configuration_matches_java_and_does_not_fall_through_to_blob_writes() {
let scalar = DataType::Blob(BlobType::new());
let valid = schema(scalar.clone(), &[], false).unwrap();
let (_, table) = memory_table("memory:/video", TableSchema::new(0,
&valid));
- assert!(
- table.new_write_builder().new_write().is_err(),
- "native video writes must not silently become ordinary .blob files"
- );
+ assert!(table.new_write_builder().new_write().is_ok());
assert!(schema(scalar.clone(), &[("blob-descriptor-field", "video")],
false).is_err());
assert!(schema(scalar.clone(), &[("blob-view-field", "video")],
false).is_err());
assert!(schema(scalar.clone(), &[], true).is_err());
diff --git a/crates/paimon/tests/video_write_test.rs
b/crates/paimon/tests/video_write_test.rs
new file mode 100644
index 00000000..f4945692
--- /dev/null
+++ b/crates/paimon/tests/video_write_test.rs
@@ -0,0 +1,214 @@
+// 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.
+
+mod common;
+
+use arrow_array::{Array, ArrayRef, Int32Array, LargeBinaryArray, RecordBatch};
+use common::incremental_helpers::{memory_table, persist_table_schema,
setup_dirs};
+use futures::TryStreamExt;
+use paimon::io::FileRead;
+use paimon::spec::{BlobType, DataType, IntType, Schema, TableSchema,
VideoFrameDescriptor};
+use paimon::table::Table;
+use std::sync::Arc;
+
+async fn table(size_roll: bool) -> Table {
+ let schema = Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .column("frame", DataType::Blob(BlobType::new()))
+ .column("payload", DataType::Blob(BlobType::new()))
+ .option("data-evolution.enabled", "true")
+ .option("data-evolution.row-sidecar.enabled", "true")
+ .option("row-tracking.enabled", "true")
+ .option("video-frame-field", "frame")
+ .option("target-file-row-num", if size_roll { "100" } else { "3" })
+ .option(
+ "blob.target-file-size",
+ if size_roll { "5 B" } else { "1 MB" },
+ )
+ .build()
+ .unwrap();
+ let (io, table) = memory_table("memory:/videos", TableSchema::new(0,
&schema));
+ setup_dirs(&io, table.location()).await;
+ persist_table_schema(&io, table.location(), table.schema()).await;
+ io.new_output("memory:/source")
+ .unwrap()
+ .write(b"prefixabcWXYZ".to_vec().into())
+ .await
+ .unwrap();
+ table
+}
+
+fn input() -> RecordBatch {
+ let descriptors: Vec<_> = [
+ (6, 3, 2),
+ (6, 3, 3),
+ (9, 4, 7),
+ (6, 3, 10),
+ (9, -1, 8),
+ (6, 3, i64::MAX),
+ ]
+ .into_iter()
+ .map(|(offset, length, frame)| {
+ VideoFrameDescriptor::new("memory:/source".into(), offset, length,
frame)
+ .unwrap()
+ .serialize()
+ })
+ .collect();
+ RecordBatch::try_from_iter([
+ (
+ "id",
+ Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6])) as ArrayRef,
+ ),
+ (
+ "frame",
+ Arc::new(LargeBinaryArray::from(vec![
+ Some(descriptors[0].as_slice()),
+ Some(&descriptors[1]),
+ Some(&descriptors[2]),
+ None,
+ Some(&descriptors[3]),
+ Some(&descriptors[4]),
+ Some(&descriptors[5]),
+ ])) as ArrayRef,
+ ),
+ (
+ "payload",
+ Arc::new(LargeBinaryArray::from(vec![Some(b"blob".as_slice());
7])) as ArrayRef,
+ ),
+ ])
+ .unwrap()
+}
+
+#[tokio::test]
+async fn video_columns_round_trip_with_ordinary_blobs_and_rolled_row_ranges() {
+ for size_roll in [false, true] {
+ let table = table(size_roll).await;
+ let builder = table.new_write_builder();
+ let mut writer = builder.new_write().unwrap();
+ let input = input();
+ writer.write_arrow_batch(&input.slice(0, 1)).await.unwrap();
+ writer.write_arrow_batch(&input.slice(1, 2)).await.unwrap();
+ writer.write_arrow_batch(&input.slice(3, 4)).await.unwrap();
+ let messages = writer.prepare_commit().await.unwrap();
+ let files: Vec<_> = messages
+ .iter()
+ .flat_map(|message| &message.new_files)
+ .collect();
+ let videos: Vec<_> = files
+ .iter()
+ .filter(|file| file.file_name.ends_with(".video"))
+ .collect();
+ assert!(
+ videos.len() > 1,
+ "both row and physical byte limits must roll video files"
+ );
+ assert_eq!(videos.iter().map(|file| file.row_count).sum::<i64>(), 7);
+ assert!(videos
+ .iter()
+ .all(|file| file.write_cols == Some(vec!["frame".into()])));
+ assert!(files.iter().any(|file| file.file_name.ends_with(".blob")
+ && file.write_cols == Some(vec!["payload".into()])));
+ builder.new_commit().commit(messages).await.unwrap();
+ for descriptor_mode in [false, true] {
+ let read_table = table.copy_with_options(
+ [("blob-as-descriptor".into(), descriptor_mode.to_string())]
+ .into_iter()
+ .collect(),
+ );
+ let reader = read_table.new_read_builder();
+ let plan = reader.new_scan().plan().await.unwrap();
+ let batches: Vec<RecordBatch> = reader
+ .new_read()
+ .unwrap()
+ .to_arrow(plan.splits())
+ .unwrap()
+ .try_collect()
+ .await
+ .unwrap();
+ let mut rows = Vec::new();
+ for batch in batches {
+ let ids = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<Int32Array>()
+ .unwrap();
+ let frames = batch
+ .column(1)
+ .as_any()
+ .downcast_ref::<LargeBinaryArray>()
+ .unwrap();
+ for row in 0..batch.num_rows() {
+ let value = if frames.is_null(row) {
+ None
+ } else {
+ let frame =
VideoFrameDescriptor::deserialize(frames.value(row)).unwrap();
+ let payload = frame.payload_descriptor();
+ assert!(payload.uri().ends_with(".video"));
+ let bytes = table
+ .file_io()
+ .new_input(payload.uri())
+ .unwrap()
+ .reader()
+ .await
+ .unwrap()
+ .read(
+ payload.offset() as u64
+ ..(payload.offset() + payload.length()) as
u64,
+ )
+ .await
+ .unwrap();
+ Some((frame.frame_index(), bytes.to_vec()))
+ };
+ rows.push((ids.value(row), value));
+ }
+ }
+ rows.sort_by_key(|row| row.0);
+ assert_eq!(
+ rows,
+ vec![
+ (0, Some((2, b"abc".to_vec()))),
+ (1, Some((3, b"abc".to_vec()))),
+ (2, Some((7, b"WXYZ".to_vec()))),
+ (3, None),
+ (4, Some((10, b"abc".to_vec()))),
+ (5, Some((8, b"WXYZ".to_vec()))),
+ (6, Some((i64::MAX, b"abc".to_vec())))
+ ]
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn video_table_rejects_consumers_before_any_output_is_created() {
+ let table = table(false).await;
+ let builder = table.new_write_builder();
+ let mut writer = builder.new_write().unwrap();
+ let error = writer
+ .with_blob_consumer(Some(Arc::new(
+ |_: &str, _: Option<&paimon::spec::BlobDescriptor>| Ok(false),
+ )))
+ .err()
+ .unwrap();
+ assert!(error.to_string().contains("BlobConsumer is not supported"));
+ writer.with_blob_consumer(None).unwrap();
+ writer
+ .write_arrow_batch(&input().slice(0, 1))
+ .await
+ .unwrap();
+ assert!(!writer.prepare_commit().await.unwrap().is_empty());
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 8ae7c4aa..175f036f 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -358,6 +358,14 @@ The offset must be non-negative, and lengths below `-1`
are invalid.
The same directives are supported by `ALTER TABLE ... ADD COLUMN`.
+Append-only data-evolution tables can set `video-frame-field` to a
+comma-separated list of scalar BLOB columns. Native writers accept serialized
+`VideoFrameDescriptor` values for these columns and pack complete encoded
videos
+into `.video` files, deduplicating each source URI/range within one file and
+indexing logical frame runs. Readers return lazy frame descriptors. Video
packing
+does not decode or re-encode frames. Raw video bytes, ordinary BlobDescriptors,
+video-column updates, video compaction, and BlobConsumer callbacks are
unsupported.
+
### Blob Descriptor Functions
`path_to_descriptor(path)` converts a string path into Java-compatible