This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 2ac209f0be [python] Preserve bounded positional reads for BLOB indexes
(#11192)
2ac209f0be is described below
commit 2ac209f0be4211576759b8e3d7f4fe5824e6e086
Author: Yann Byron <[email protected]>
AuthorDate: Mon Nov 16 17:26:19 2026 +0800
[python] Preserve bounded positional reads for BLOB indexes (#11192)
---
paimon-python/pypaimon/common/file_io.py | 2 +-
.../python/read/reader/format_blob_reader.py | 22 ++--
.../filesystem/jindo_file_system_handler.py | 17 ++-
.../pypaimon/filesystem/pyarrow_file_io.py | 4 +
paimon-python/pypaimon/tests/blob_test.py | 111 +++++++++++++++++--
.../pypaimon/tests/jindo_file_system_test.py | 120 +++++++++++++++++++++
.../tests/write/format_file_writer_test.py | 3 +-
7 files changed, 261 insertions(+), 18 deletions(-)
diff --git a/paimon-python/pypaimon/common/file_io.py
b/paimon-python/pypaimon/common/file_io.py
index 0049b94104..6a1a313047 100644
--- a/paimon-python/pypaimon/common/file_io.py
+++ b/paimon-python/pypaimon/common/file_io.py
@@ -65,7 +65,7 @@ def supports_pread(stream) -> bool:
"""Check if the stream supports position-based reads (thread-safe I/O)."""
if hasattr(stream, 'read_at'):
return True
- if hasattr(stream, 'fileno'):
+ if callable(getattr(os, 'pread', None)) and hasattr(stream, 'fileno'):
try:
stream.fileno()
return True
diff --git
a/paimon-python/pypaimon/execution/python/read/reader/format_blob_reader.py
b/paimon-python/pypaimon/execution/python/read/reader/format_blob_reader.py
index abf629c2f1..10d3bf1ea7 100644
--- a/paimon-python/pypaimon/execution/python/read/reader/format_blob_reader.py
+++ b/paimon-python/pypaimon/execution/python/read/reader/format_blob_reader.py
@@ -24,7 +24,7 @@ from pyarrow import RecordBatch
from pypaimon.common.blob_index_cache import BlobIndexCache
from pypaimon.common.delta_varint_compressor import DeltaVarintCompressor
-from pypaimon.common.file_io import FileIO
+from pypaimon.common.file_io import FileIO, pread, supports_pread
from pypaimon.execution.python.map_blob_key_serializer import
create_map_blob_key_serializer
from pypaimon.common.memory_size import MemorySize
from pypaimon.read.reader.iface.record_batch_reader import RecordBatchReader
@@ -378,9 +378,16 @@ class FormatBlobReader(RecordBatchReader):
self._input_stream = self._file_io.new_input_stream(self.file_path)
f = self._input_stream
- # Seek to header: last 5 bytes
- f.seek(self._file_size - 5)
- header = f.read(5)
+ def read_range(offset, length):
+ if supports_pread(f):
+ return pread(f, length, offset)
+ f.seek(offset)
+ return f.read(length)
+
+ # Footer/index reads do not benefit from sequential payload read-ahead.
+ if self._file_size < 5:
+ raise IOError("Invalid blob file: cannot read header")
+ header = read_range(self._file_size - 5, 5)
if len(header) != 5:
raise IOError("Invalid blob file: cannot read header")
@@ -392,9 +399,12 @@ class FormatBlobReader(RecordBatchReader):
if version != 1:
raise IOError(f"Unsupported blob file version: {version}")
+ # Reject a corrupt footer before passing a negative offset to FileIO.
+ if index_length > self._file_size - 5:
+ raise IOError("Invalid blob file: index length exceeds file size")
+
# Read index data
- f.seek(self._file_size - 5 - index_length)
- index_bytes = f.read(index_length)
+ index_bytes = read_range(self._file_size - 5 - index_length,
index_length)
if len(index_bytes) != index_length:
raise IOError("Invalid blob file: cannot read index")
diff --git a/paimon-python/pypaimon/filesystem/jindo_file_system_handler.py
b/paimon-python/pypaimon/filesystem/jindo_file_system_handler.py
index 25db0ba1a7..e1c710ab28 100644
--- a/paimon-python/pypaimon/filesystem/jindo_file_system_handler.py
+++ b/paimon-python/pypaimon/filesystem/jindo_file_system_handler.py
@@ -303,6 +303,19 @@ class JindoInputFile:
return False
+class _JindoPythonFile(PythonFile):
+ """Keep positional reads on the SDK's pread path for Python FileIO
callers."""
+
+ def __init__(self, source, mode="r"):
+ # PythonFile is initialized by its Cython __cinit__, not __init__.
+ self._range_source = source
+
+ def read_at(self, nbytes: int, offset: int):
+ if callable(getattr(self._range_source._stream, 'pread', None)):
+ return self._range_source.read_at(nbytes, offset)
+ return super().read_at(nbytes, offset)
+
+
class JindoOutputFile:
def __init__(self, jindo_stream, *, owner):
self._stream = jindo_stream
@@ -510,7 +523,7 @@ class JindoFileSystemHandler(FileSystemHandler):
def open_input_stream(self, path: str):
normalized = self._normalize_path(path)
jindo_stream = self._jindo_fs.open(normalized, "rb")
- return PythonFile(
+ return _JindoPythonFile(
JindoInputFile(jindo_stream, self._known_file_size(normalized),
owner=self._jindo_fs,
pread_max_size=self._pread_max_size),
mode="r")
@@ -518,7 +531,7 @@ class JindoFileSystemHandler(FileSystemHandler):
def open_input_file(self, path: str):
normalized = self._normalize_path(path)
jindo_stream = self._jindo_fs.open(normalized, "rb")
- return PythonFile(
+ return _JindoPythonFile(
JindoInputFile(jindo_stream, self._known_file_size(normalized),
owner=self._jindo_fs,
pread_max_size=self._pread_max_size),
mode="r")
diff --git a/paimon-python/pypaimon/filesystem/pyarrow_file_io.py
b/paimon-python/pypaimon/filesystem/pyarrow_file_io.py
index 2b3fd3d6b7..fa0510fbbb 100644
--- a/paimon-python/pypaimon/filesystem/pyarrow_file_io.py
+++ b/paimon-python/pypaimon/filesystem/pyarrow_file_io.py
@@ -438,6 +438,10 @@ class PyArrowFileIO(FileIO):
def new_input_stream(self, path: str):
path_str = self.to_filesystem_path(path)
+ if self._use_jindo:
+ # PyFileSystem's C facade erases PythonFile.read_at overrides.
+ # Keep the handler's NativeFile for exact Python range reads.
+ return self.filesystem.handler.open_input_file(path_str)
return self.filesystem.open_input_file(path_str)
def new_output_stream(self, path: str):
diff --git a/paimon-python/pypaimon/tests/blob_test.py
b/paimon-python/pypaimon/tests/blob_test.py
index 063f34db09..8e2ab94765 100644
--- a/paimon-python/pypaimon/tests/blob_test.py
+++ b/paimon-python/pypaimon/tests/blob_test.py
@@ -28,7 +28,7 @@ import unittest
import zlib
from decimal import Decimal
from pathlib import Path
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
import pyarrow as pa
import pytest
@@ -81,6 +81,20 @@ class MockFileIO:
return self._file_io.new_input_stream(path)
+def counting_positional_stream(source):
+ def read_at(size, offset):
+ position = source.tell()
+ try:
+ source.seek(offset)
+ return source.read(size)
+ finally:
+ source.seek(position)
+
+ stream = MagicMock(wraps=source)
+ stream.read_at = MagicMock(side_effect=read_at)
+ return stream
+
+
class CountingBlobFileIO(LocalFileIO):
def __init__(self, root):
super().__init__(root, Options({}))
@@ -92,7 +106,7 @@ class CountingBlobFileIO(LocalFileIO):
return super().get_file_size(path)
def new_input_stream(self, path):
- stream = MagicMock(wraps=super().new_input_stream(path))
+ stream = counting_positional_stream(super().new_input_stream(path))
stream.__enter__.return_value = stream
stream.__exit__.side_effect = lambda *args: stream.close()
self.streams.append(stream)
@@ -100,7 +114,7 @@ class CountingBlobFileIO(LocalFileIO):
def counts(self):
return (self.stat_count, len(self.streams),
- sum(stream.read.call_count for stream in self.streams),
+ sum(stream.read.call_count + stream.read_at.call_count for
stream in self.streams),
sum(stream.close.call_count for stream in self.streams))
@@ -3259,7 +3273,7 @@ class BlobEndToEndTest(unittest.TestCase):
streams = []
def counted_open(path):
- stream = MagicMock(wraps=open_stream(path))
+ stream = counting_positional_stream(open_stream(path))
streams.append(stream)
return stream
@@ -3278,7 +3292,8 @@ class BlobEndToEndTest(unittest.TestCase):
finally:
reader.close()
results.append(descriptors)
- reads.append(sum(stream.read.call_count for stream in
streams))
+ reads.append(sum(stream.read.call_count +
stream.read_at.call_count
+ for stream in streams))
self.assertEqual(reads, [34, expected_reads])
self.assertEqual(results[0], results[1])
self.assertLessEqual(cache.size_bytes,
cache.max_size_bytes)
@@ -3442,6 +3457,83 @@ class BlobEndToEndTest(unittest.TestCase):
self.assertEqual(counting_file_io.input_stream_count, 1)
reader.close()
+ def test_blob_index_reads_exact_ranges_without_stream_read_ahead(self):
+ field = DataField(0, "blob_field", AtomicType("BLOB"))
+ path = os.path.join(self.temp_dir, "positional-index.blob")
+ self._write_single_blob(path, field, b"payload")
+ file_size = os.path.getsize(path)
+ with open(path, "rb") as input_file:
+ data = input_file.read()
+ index_size = struct.unpack('<I', data[-5:-1])[0]
+ file_io = CountingBlobFileIO(self.temp_dir)
+ reader = FormatBlobReader(file_io, path, [field.name], [field], None,
True,
+ file_size=file_size)
+ try:
+ descriptor =
BlobDescriptor.deserialize(reader.read_arrow_batch().column(0)[0].as_py())
+ self.assertEqual((path, 4, 7), (descriptor.uri, descriptor.offset,
descriptor.length))
+ stream = file_io.streams[0]
+ self.assertEqual([call(5, file_size - 5),
+ call(index_size, file_size - 5 - index_size)],
+ stream.read_at.call_args_list)
+ stream.seek.assert_not_called()
+ stream.read.assert_not_called()
+ self.assertEqual(1, len(file_io.streams))
+ finally:
+ reader.close()
+ self.assertEqual(1, file_io.streams[0].close.call_count)
+
+ def test_blob_index_falls_back_for_streams_without_positional_reads(self):
+ field = DataField(0, "blob_field", AtomicType("BLOB"))
+ path = os.path.join(self.temp_dir, "stream-index.blob")
+ self._write_single_blob(path, field, b"payload")
+ with open(path, "rb") as input_file:
+ data = input_file.read()
+ stream = MagicMock(wraps=io.BytesIO(data))
+ file_io = LocalFileIO(self.temp_dir, Options({}))
+ with patch.object(file_io, 'new_input_stream', return_value=stream):
+ reader = FormatBlobReader(file_io, path, [field.name], [field],
None, True,
+ file_size=len(data))
+ try:
+ descriptor =
BlobDescriptor.deserialize(reader.read_arrow_batch().column(0)[0].as_py())
+ self.assertEqual((path, 4, 7), (descriptor.uri,
descriptor.offset, descriptor.length))
+ self.assertEqual(2, stream.seek.call_count)
+ self.assertEqual(2, stream.read.call_count)
+ finally:
+ reader.close()
+ self.assertEqual(1, stream.close.call_count)
+
+ def test_blob_index_rejects_ranges_outside_the_file(self):
+ field = DataField(0, "blob_field", AtomicType("BLOB"))
+
+ class PositionalStream(io.BytesIO):
+ def read_at(self, length, offset):
+ if offset < 0:
+ raise AssertionError("invalid offset must not reach the
filesystem")
+ return self.getvalue()[offset:offset + length]
+
+ for content in (b"1234", struct.pack('<IB', 100, 1)):
+ with self.subTest(content=content):
+ stream = PositionalStream(content)
+ file_io = LocalFileIO(self.temp_dir, Options({}))
+ with patch.object(file_io, 'new_input_stream',
return_value=stream):
+ with self.assertRaisesRegex(IOError, "Invalid blob file"):
+ FormatBlobReader(file_io, str(id(stream)) + ".blob",
[field.name],
+ [field], None, True,
file_size=len(content))
+ self.assertTrue(stream.closed)
+
+ def test_blob_index_falls_back_when_os_pread_is_unavailable(self):
+ field = DataField(0, "blob_field", AtomicType("BLOB"))
+ path = os.path.join(self.temp_dir, "local-index.blob")
+ self._write_single_blob(path, field, b"payload")
+ file_io = LocalFileIO(self.temp_dir, Options({}))
+ with patch.object(os, 'pread', None, create=True):
+ reader = FormatBlobReader(file_io, path, [field.name], [field],
None, True)
+ try:
+ descriptor =
BlobDescriptor.deserialize(reader.read_arrow_batch().column(0)[0].as_py())
+ self.assertEqual((path, 4, 7), (descriptor.uri,
descriptor.offset, descriptor.length))
+ finally:
+ reader.close()
+
def test_blob_reader_uses_provided_file_size(self):
field = DataField(0, "blob_field", AtomicType("BLOB"))
path = os.path.join(self.temp_dir, "provided-size.blob")
@@ -3644,10 +3736,11 @@ class BlobEndToEndTest(unittest.TestCase):
def open_stream(file_path):
stream = original_open(file_path)
if failure == 'read':
- stream.read.side_effect = IOError("injected read
failure")
+ stream.read_at.side_effect = IOError("injected read
failure")
elif failure == 'index':
- read = stream._mock_wraps.read
- stream.read.side_effect = lambda size: read(size) if
size == 5 else read(size)[:-1]
+ read_at = stream.read_at.side_effect
+ stream.read_at.side_effect = lambda size, offset: (
+ read_at(size, offset) if size == 5 else
read_at(size, offset)[:-1])
return stream
with patch.object(file_io, 'new_input_stream',
side_effect=open_stream):
@@ -4655,6 +4748,8 @@ class BlobEndToEndTest(unittest.TestCase):
blob_parallelism=4,
)
+ # The reader has already fetched its footer/index; count payload
ranges below.
+ range_reads.clear()
batch = reader.read_arrow_batch()
self.assertEqual(
diff --git a/paimon-python/pypaimon/tests/jindo_file_system_test.py
b/paimon-python/pypaimon/tests/jindo_file_system_test.py
index e2df910cce..be9843d2ed 100644
--- a/paimon-python/pypaimon/tests/jindo_file_system_test.py
+++ b/paimon-python/pypaimon/tests/jindo_file_system_test.py
@@ -29,7 +29,9 @@ import warnings
import weakref
from unittest import mock
+import pyarrow as pa
import pyarrow.fs as pafs
+import pyarrow.parquet as pq
from pyarrow import PythonFile
from pyarrow.fs import PyFileSystem
@@ -234,6 +236,124 @@ class JindoInputFileTest(unittest.TestCase):
self.assertEqual([], stream.reads)
+class JindoFileIOPositionalReadTest(unittest.TestCase):
+ @staticmethod
+ def _file_io(data, positional=True):
+ class Stream(io.BytesIO):
+ def __init__(self):
+ super().__init__(data)
+ self.preads = []
+ self.reads = []
+ self.closes = 0
+
+ def pread(self, size, offset):
+ self.preads.append((size, offset))
+ return self.getvalue()[offset:offset + size]
+
+ def read(self, size=-1):
+ self.reads.append((size, self.tell()))
+ return super().read(size)
+
+ def close(self):
+ if not self.closed:
+ self.closes += 1
+ super().close()
+
+ if not positional:
+ del Stream.pread
+
+ class FileSystem:
+ def __init__(self):
+ self.opened = []
+
+ def open(self, path, mode):
+ stream = Stream()
+ self.opened.append((path, stream))
+ return stream
+
+ filesystem = FileSystem()
+ with mock.patch.object(jindo_module, "JINDO_AVAILABLE", True), \
+ mock.patch.object(pyarrow_file_io_module, "JINDO_AVAILABLE",
True), \
+ mock.patch.object(jindo_module, "jfs", types.SimpleNamespace(
+ connect=lambda *args, **kwargs: filesystem)), \
+ mock.patch.object(jindo_module, "jutil",
+
types.SimpleNamespace(Config=_RecordingConfig)):
+ file_io = pyarrow_file_io_module.PyArrowFileIO(
+ "oss://bucket/", Options({"fs.oss.impl": "jindo"}))
+ return file_io, filesystem
+
+ def test_file_io_read_at_uses_pread_without_changing_position(self):
+ file_io, filesystem = self._file_io(b"abcdefghij")
+ stream = file_io.new_input_stream("oss://bucket/data.blob")
+ self.addCleanup(stream.close)
+ native = filesystem.opened[0][1]
+
+ self.assertIsInstance(stream, pa.NativeFile)
+ stream.seek(2)
+ self.assertEqual(b"fgh", stream.read_at(3, 5))
+ self.assertEqual(2, stream.tell())
+ self.assertEqual(b"cd", stream.read(2))
+ self.assertEqual([(3, 5)], native.preads)
+ self.assertEqual([(2, 2)], native.reads)
+ self.assertEqual(1, len(filesystem.opened))
+ self.assertEqual("oss://bucket/data.blob", filesystem.opened[0][0])
+
+ def test_stream_without_pread_keeps_original_arrow_read_at(self):
+ file_io, filesystem = self._file_io(b"abcdefghij", positional=False)
+ with file_io.new_input_stream("oss://bucket/data.blob") as stream:
+ self.assertEqual(b"ef", stream.read_at(2, 4))
+ native = filesystem.opened[0][1]
+ self.assertEqual([(2, 4)], native.reads)
+ self.assertEqual(1, len(filesystem.opened))
+ self.assertEqual(1, native.closes)
+
+ def test_arrow_consumer_keeps_reading_through_native_file(self):
+ expected = pa.table({"id": [1, 2, 3]})
+ output = pa.BufferOutputStream()
+ pq.write_table(expected, output)
+ file_io, filesystem = self._file_io(output.getvalue().to_pybytes())
+ with file_io.new_input_stream("oss://bucket/data.parquet") as stream:
+ self.assertTrue(pq.ParquetFile(stream).read().equals(expected))
+ self.assertEqual(1, filesystem.opened[0][1].closes)
+ # Arrow's filesystem entry remains a C NativeFile using seek + read.
+ with file_io.filesystem.open_input_file("data.parquet") as stream:
+ self.assertTrue(pq.ParquetFile(stream).read().equals(expected))
+ self.assertEqual(1, filesystem.opened[1][1].closes)
+
+ def test_file_io_stream_pins_owner_until_close(self):
+ file_io, filesystem = self._file_io(b"abcdefghij")
+ owner_ref = weakref.ref(filesystem)
+ handler_ref = weakref.ref(file_io.filesystem.handler)
+ stream = file_io.new_input_stream("oss://bucket/data.blob")
+ native = filesystem.opened[0][1]
+ del file_io, filesystem
+ gc.collect()
+ self.assertIsNone(handler_ref())
+ self.assertIsNotNone(owner_ref())
+ self.assertEqual(b"ef", stream.read_at(2, 4))
+ stream.close()
+ stream.close()
+ gc.collect()
+ self.assertIsNone(owner_ref())
+ self.assertEqual(1, native.closes)
+ with self.assertRaises(ValueError):
+ stream.read_at(1, 0)
+ del stream
+ gc.collect()
+ self.assertEqual(1, native.closes)
+
+ def test_non_jindo_file_io_keeps_filesystem_entry(self):
+ file_io = pyarrow_file_io_module.PyArrowFileIO.__new__(
+ pyarrow_file_io_module.PyArrowFileIO)
+ file_io._use_jindo = False
+ file_io.filesystem = mock.Mock()
+ file_io.to_filesystem_path = mock.Mock(return_value="bucket/object")
+ stream = file_io.new_input_stream("s3://bucket/object")
+ self.assertIs(stream, file_io.filesystem.open_input_file.return_value)
+
file_io.filesystem.open_input_file.assert_called_once_with("bucket/object")
+ file_io.filesystem.handler.open_input_file.assert_not_called()
+
+
class JindoStreamStatsTest(unittest.TestCase):
def setUp(self):
diff --git a/paimon-python/pypaimon/tests/write/format_file_writer_test.py
b/paimon-python/pypaimon/tests/write/format_file_writer_test.py
index cc8916aa85..4de398f759 100644
--- a/paimon-python/pypaimon/tests/write/format_file_writer_test.py
+++ b/paimon-python/pypaimon/tests/write/format_file_writer_test.py
@@ -128,7 +128,8 @@ def
test_blob_descriptor_input_routes_by_source_uri(tmp_path, wrapper, destinati
else (destination / 'table' / 'result.blob').as_uri())
def local_bucket_filesystem(file_io, path):
- file_io._use_jindo = True
+ file_io._use_jindo = False
+ file_io.to_filesystem_path = lambda uri: urlparse(uri).path.lstrip('/')
bucket_dir = tmp_path / urlparse(path).netloc
return pa.fs.SubTreeFileSystem(os.fspath(bucket_dir),
pa.fs.LocalFileSystem())