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 a89a2f03f5 [python] Support Variant projections in map-style Torch 
datasets (#10971)
a89a2f03f5 is described below

commit a89a2f03f51635743edb41494d80f032756a436b
Author: QuakeWang <[email protected]>
AuthorDate: Wed Nov 4 14:26:23 2026 +0800

    [python] Support Variant projections in map-style Torch datasets (#10971)
---
 docs/docs/pypaimon/pytorch.md                      |  26 +++-
 paimon-python/pypaimon/read/table_read.py          |  14 +--
 .../tests/named_projection_iterator_test.py        |   4 +-
 .../pypaimon/tests/native_torch_variant_test.py    | 137 ++++++++++++++++++++-
 .../pypaimon/tests/native_variant_iterator_test.py |  10 +-
 paimon-python/pypaimon/tests/variant_test.py       |   5 +-
 6 files changed, 175 insertions(+), 21 deletions(-)

diff --git a/docs/docs/pypaimon/pytorch.md b/docs/docs/pypaimon/pytorch.md
index 61ad8533ec..05b4908f24 100644
--- a/docs/docs/pypaimon/pytorch.md
+++ b/docs/docs/pypaimon/pytorch.md
@@ -90,8 +90,30 @@ Each sample uses the specified aliases in projection order. 
These requests
 materialize their Arrow result in memory when the dataset is constructed,
 including on Data Evolution tables. Indexing preserves the requested order
 and duplicate indices. Values and supported reads follow `to_arrow`, including
-its table, format, and authorization restrictions. VARIANT extraction
-expressions still require streaming.
+its table, format, and authorization restrictions.
+
+Map-style row datasets also support the existing float32 `variant_get` and
+`try_variant_get` projections, including mixtures with ordinary columns and
+nested paths:
+
+```python
+read_builder = table.new_read_builder().with_projection({
+    "user_id": "id",
+    "score": "try_variant_get(payload, '$.score', 'float')",
+})
+splits = read_builder.new_scan().plan().splits()
+dataset = read_builder.new_read().to_torch(splits, streaming=False, 
batch_format="row")
+sample = dataset[0]
+samples = dataset.__getitems__([2, 0, 2])
+```
+
+VARIANT extractions require a compatible Native reader. These requests
+materialize through `to_arrow` when the dataset is constructed, including on
+Data Evolution tables; they do not use lazy row-ID reads. Aliases, output 
order,
+repeated sources, extracted values and nulls follow the same Arrow request.
+`variant_get` cast errors propagate during construction, while 
`try_variant_get`
+returns null for failed casts. Initialization retains the Arrow result in 
memory.
+Batch formats (`"pyarrow"` and `"torch"`) still require `streaming=True`.
 
 ### Distributed Sharding
 
diff --git a/paimon-python/pypaimon/read/table_read.py 
b/paimon-python/pypaimon/read/table_read.py
index 9de0586c56..74a52f32a4 100644
--- a/paimon-python/pypaimon/read/table_read.py
+++ b/paimon-python/pypaimon/read/table_read.py
@@ -27,7 +27,6 @@ from pypaimon.read.push_down_utils import 
predicate_field_names
 from pypaimon.read.query_auth_split import QueryAuthSplit
 from pypaimon.read.split import Split
 from pypaimon.read.read_type import OutputProjection, output_schema, 
reader_adapter
-from pypaimon.read.variant_read_type import has_variant_extractions
 from pypaimon.read.blob_read_support import deferred_blob_field_names
 from pypaimon.schema.data_types import DataField
 
@@ -488,9 +487,10 @@ class TableRead:
                 prefix.
             batch_format: ``"row"``, ``"pyarrow"``, or ``"torch"``. Batch
                 formats require streaming. Map-style row format supports named
-                columns and nested paths; named nested paths materialize 
through
-                Arrow with its existing read restrictions. Streaming row format
-                also supports float32 VARIANT extractions through native 
reading.
+                columns, nested paths and float32 VARIANT extractions. Named
+                nested paths and VARIANT extractions materialize through Arrow
+                with its existing read restrictions. VARIANT extractions 
require
+                native reading in both map-style and streaming row formats.
             batch_size: Rows per batch; ``None`` preserves reader batches when
                 unshuffled, or emits shuffle blocks of at most buffer_size 
rows.
             to_tensor_fn: Optional RecordBatch converter for Torch batches.
@@ -518,12 +518,6 @@ class TableRead:
         ):
             raise ValueError("batch_size must be a positive int or None")
         if batch_format == "row":
-            if (not streaming and self.output_projection is not None
-                    and self.output_projection.named
-                    and has_variant_extractions(self.read_type)):
-                raise RuntimeError(
-                    "VARIANT expressions are not supported by Torch row 
format; "
-                    "use streaming=True")
             if batch_size is not None:
                 raise ValueError(
                     "batch_size requires batch_format='pyarrow' or 'torch'"
diff --git a/paimon-python/pypaimon/tests/named_projection_iterator_test.py 
b/paimon-python/pypaimon/tests/named_projection_iterator_test.py
index 9c35a12e84..e441e252f8 100644
--- a/paimon-python/pypaimon/tests/named_projection_iterator_test.py
+++ b/paimon-python/pypaimon/tests/named_projection_iterator_test.py
@@ -280,11 +280,11 @@ def 
test_variant_iterator_and_torch_rows_require_native(tmp_path, function, nest
             patch.object(PythonTableRead, 'read_rows', 
side_effect=AssertionError('Python Variant execution')):
         with pytest.raises(RuntimeError, match='Variant extraction requires a 
compatible native reader'):
             list(read.to_iterator([]))
-        with pytest.raises(RuntimeError, match='not supported by Torch row 
format'):
-            read.to_torch([], streaming=False, batch_format='row')
         native.assert_not_called()
 
         pytest.importorskip('torch')
+        with pytest.raises(RuntimeError, match='Variant extraction requires a 
compatible native reader'):
+            read.to_torch([], streaming=False, batch_format='row')
         dataset = read.to_torch([], streaming=True, batch_format='row')
         with pytest.raises(RuntimeError, match='Variant extraction requires a 
compatible native reader'):
             list(dataset)
diff --git a/paimon-python/pypaimon/tests/native_torch_variant_test.py 
b/paimon-python/pypaimon/tests/native_torch_variant_test.py
index ded0255968..de634cda5c 100644
--- a/paimon-python/pypaimon/tests/native_torch_variant_test.py
+++ b/paimon-python/pypaimon/tests/native_torch_variant_test.py
@@ -15,11 +15,12 @@
 # specific language governing permissions and limitations
 # under the License.
 
-"""Streaming Torch rows retain Native Variant projection semantics."""
+"""Torch row datasets retain Native Variant projection semantics."""
 
 from types import SimpleNamespace
 from unittest.mock import patch
 
+import pyarrow as pa
 import pytest
 
 pytest.importorskip('torch')
@@ -28,6 +29,8 @@ from torch.utils.data import DataLoader
 
 from pypaimon.execution.native.read.table_read import native_read
 from pypaimon.execution.native.runtime import native_runtime_available
+from pypaimon.read.datasource.torch_dataset import TorchDataset
+from pypaimon.read.table_read import TableRead
 from pypaimon.tests import native_variant_iterator_test
 
 
@@ -211,8 +214,134 @@ def 
test_streaming_variant_closes_native_streams(variant_builder, row_options, s
     assert bool(opened) == (stop != 'unstarted')
 
 
-def test_non_streaming_variant_rows_remain_unsupported(variant_builder):
+def _assert_map_indexing(read, splits):
+    arrow = read.to_arrow(splits, parallelism=1)
+    expected = arrow.to_pylist()
+    with patch.object(TableRead, 'to_arrow', autospec=True, 
side_effect=TableRead.to_arrow) as fetch, \
+            patch.object(TorchDataset, '_compact_row_id_index', 
side_effect=AssertionError('Lazy row-ID read')):
+        dataset = read.to_torch(splits, streaming=False, batch_format='row')
+    fetch.assert_called_once_with(read, splits)
+    assert dataset._data is not None and dataset._row_ids is None
+    assert len(dataset) == len(expected)
+    assert dataset._data.column_names == [alias for alias, _ in 
read.output_projection.columns]
+    assert dataset._data.schema == arrow.schema
+    with patch.object(TableRead, 'to_arrow', side_effect=AssertionError('Read 
after materialization')):
+        assert dataset.__getitems__([]) == []
+        if expected:
+            indices = [len(dataset) - 1, 0, -1, 0, -len(dataset)]
+            assert dataset[0] == expected[0]
+            assert dataset[-1] == expected[-1]
+            assert list(dataset[0]) == list(expected[0])
+            assert dataset[1::2] == expected[1::2]
+            assert dataset[::-1] == expected[::-1]
+            assert dataset[2:2] == []
+            assert dataset.__getitems__(indices) == [expected[i] for i in 
indices]
+            assert list(DataLoader(dataset, batch_sampler=[indices], 
collate_fn=list)) == [
+                [expected[i] for i in indices]]
+            for index in (len(dataset), -len(dataset) - 1):
+                with pytest.raises(IndexError, match='TorchDataset index out 
of range'):
+                    dataset[index]
+                with pytest.raises(IndexError, match='TorchDataset index out 
of range'):
+                    dataset.__getitems__([0, index, 0])
+        else:
+            assert dataset[0] is None
+            with pytest.raises(IndexError, match='TorchDataset index out of 
range'):
+                dataset.__getitems__([0])
+    return expected
+
+
+def test_map_variant_rows(variant_builder):
+    builder, _ = variant_builder
+    builder.table = builder.table.copy({'read.parallelism': '1'})
+    read, splits = builder.new_read(), builder.new_scan().plan().splits()
+    assert read._output_arrow_schema().field('score').type == pa.float32()
+    _assert_rows(_assert_map_indexing(read, splits), _expected_rows())
+
+
[email protected]('aliases', [False, True])
+def test_map_variant_only_and_aliases(variant_builder, aliases):
+    builder, source = variant_builder
+    expression = "try_variant_get(%s, '$.score', 'float')" % source
+    projection = ({'id': expression, '_ROW_ID': 'id', 'payload': 'id', 
'again': expression}
+                  if aliases else {'score': expression})
+    builder.with_projection(projection)
+    builder.table = builder.table.copy({'read.parallelism': '1'})
+    read, splits = builder.new_read(), builder.new_scan().plan().splits()
+    actual = _assert_map_indexing(read, splits)
+    expected = [dict(zip(projection, [row['score'], row['identifier'], 
row['identifier'], row['score']]))
+                if aliases else {'score': row['score']} for row in 
_expected_rows()]
+    assert sorted(actual, key=repr) == sorted(expected, key=repr)
+
+
+def test_map_variant_mixed_nested_paths(variant_builder):
+    builder, source = variant_builder
+    projection = {
+        'city': 'profile.city', 'source': "attributes['source']",
+        'score': "try_variant_get(%s, '$.score', 'float')" % source,
+        'user_id': 'id', 'score_copy': "try_variant_get(%s, '$.score', 
'float')" % source,
+    }
+    builder.with_projection(projection)
+    builder.table = builder.table.copy({'read.parallelism': '1'})
+    read, splits = builder.new_read(), builder.new_scan().plan().splits()
+    actual = _assert_map_indexing(read, splits)
+    cities = ['Hangzhou', 'Beijing', None, 'Shenzhen', 'Suzhou', None]
+    sources = ['web', None, None, None, None, 'app']
+    expected = [dict(zip(projection, [city, value, row['score'], 
row['identifier'], row['score']]))
+                for city, value, row in zip(cities, sources, _expected_rows())]
+    assert sorted(actual, key=lambda row: row['user_id']) == expected
+
+
[email protected]('limit', [0, 1, 3])
[email protected]('filtered', [False, True])
+def test_map_variant_filter_and_limit(variant_builder, limit, filtered):
+    builder, _ = variant_builder
+    builder.table = builder.table.copy({'read.parallelism': '1'})
+    if filtered:
+        
builder.with_filter(builder.table.new_read_builder().new_predicate_builder().greater_than('id',
 2))
+    splits = builder.new_scan().plan().splits()
+    builder.with_limit(limit)
+    actual = _assert_map_indexing(builder.new_read(), splits)
+    _assert_rows(actual, (_expected_rows()[2:] if filtered else 
_expected_rows())[:limit])
+
+
+def test_map_variant_empty_input(variant_builder):
+    builder, _ = variant_builder
+    assert _assert_map_indexing(builder.new_read(), []) == []
+
+
+def test_map_variant_strict_cast_errors(variant_builder):
+    builder, source = variant_builder
+    builder.with_projection({'score': "variant_get(%s, '$.score', 'float')" % 
source})
+    read, splits = builder.new_read(), builder.new_scan().plan().splits()
+    with pytest.raises(Exception, match='Cannot cast Variant'):
+        read.to_arrow(splits, parallelism=1)
+    with pytest.raises(Exception, match='Cannot cast Variant'):
+        read.to_torch(splits, streaming=False, batch_format='row')
+
+
[email protected]('failure', ['disabled', 'missing_runtime', 'setup', 
'unsupported_split'])
+def test_map_variant_requires_native(variant_builder, failure):
     builder, _ = variant_builder
     splits = builder.new_scan().plan().splits()
-    with pytest.raises(RuntimeError, match='VARIANT expressions are not 
supported by Torch row format'):
-        builder.new_read().to_torch(splits)
+    target = 'pypaimon.execution.native.read.table_read.native_read'
+    if failure == 'disabled':
+        builder.table = builder.table.copy({'read.native.enabled': 'false'})
+        options = {'wraps': native_read}
+    elif failure == 'missing_runtime':
+        target = 'pypaimon.execution.native.runtime.native_runtime_available'
+        options = {'return_value': False}
+    elif failure == 'setup':
+        options = {'side_effect': RuntimeError('Native setup failed')}
+    else:
+        target = 
'pypaimon.execution.native.read.table_read.NativeTableRead._split_files_supported'
+        options = {'return_value': False}
+    with patch(target, **options):
+        with pytest.raises(RuntimeError, match='Variant extraction requires a 
compatible native reader'):
+            builder.new_read().to_torch(splits, streaming=False, 
batch_format='row')
+
+
[email protected]('batch_format', ['pyarrow', 'torch'])
+def test_map_variant_batch_formats_remain_unsupported(variant_builder, 
batch_format):
+    builder, _ = variant_builder
+    with pytest.raises(ValueError, match='requires streaming=True'):
+        builder.new_read().to_torch([], streaming=False, 
batch_format=batch_format)
diff --git a/paimon-python/pypaimon/tests/native_variant_iterator_test.py 
b/paimon-python/pypaimon/tests/native_variant_iterator_test.py
index 7cd902fcbd..0b6a240def 100644
--- a/paimon-python/pypaimon/tests/native_variant_iterator_test.py
+++ b/paimon-python/pypaimon/tests/native_variant_iterator_test.py
@@ -54,8 +54,14 @@ def variant_table(tmp_path, request):
         options.update({'data-evolution.enabled': 'true', 
'row-tracking.enabled': 'true'})
     data = pa.Table.from_arrays([
         pa.array(range(1, 7), type=pa.int64()), payload,
-        pa.StructArray.from_arrays([payload], names=['payload'], 
mask=pa.array([False] * 5 + [True])),
-    ], names=['id', 'payload', 'profile'])
+        pa.StructArray.from_arrays([
+            payload, pa.array(['Hangzhou', 'Beijing', None, 'Shenzhen', 
'Suzhou', 'hidden']),
+        ], names=['payload', 'city'], mask=pa.array([False] * 5 + [True])),
+        pa.array([
+            [('source', 'web'), ('source', 'mobile')], [('source', None), 
('source', 'later')],
+            [], None, [('other', 'value')], [('source', 'app')],
+        ], type=pa.map_(pa.string(), pa.string())),
+    ], names=['id', 'payload', 'profile', 'attributes'])
     catalog = CatalogFactory.create({'warehouse': str(tmp_path)})
     catalog.create_database('db', True)
     catalog.create_table('db.t', Schema.from_pyarrow_schema(
diff --git a/paimon-python/pypaimon/tests/variant_test.py 
b/paimon-python/pypaimon/tests/variant_test.py
index c8e2067ff2..950eaea1cb 100644
--- a/paimon-python/pypaimon/tests/variant_test.py
+++ b/paimon-python/pypaimon/tests/variant_test.py
@@ -1297,7 +1297,7 @@ class TestVariantPaimonTable(unittest.TestCase):
                 self.assertTrue(splits)
                 read = builder.new_read()
 
-                with self.assertRaisesRegex(RuntimeError, 'Torch row format'):
+                with self.assertRaisesRegex(RuntimeError, 'Variant extraction 
requires a compatible native reader'):
                     read.to_torch(splits, streaming=False)
 
                 dataset = read.to_torch(splits, streaming=True)
@@ -1307,11 +1307,14 @@ class TestVariantPaimonTable(unittest.TestCase):
                 builder = table.copy({'read.native.enabled': 
'true'}).new_read_builder().with_projection(projection)
                 read = builder.new_read()
                 with 
patch('pypaimon.execution.native.runtime.native_runtime_available', 
return_value=False):
+                    with self.assertRaisesRegex(RuntimeError, 'Variant 
extraction requires a compatible native reader'):
+                        read.to_torch(splits, streaming=False)
                     dataset = read.to_torch(splits, streaming=True)
                     with self.assertRaisesRegex(RuntimeError, 'Variant 
extraction requires a compatible native reader'):
                         list(dataset)
 
                 if _native_variant_projection_available():
+                    self.assertEqual(read.to_torch(splits, 
streaming=False)[0], {'ratio': 1.25})
                     self.assertEqual(list(read.to_torch(splits, 
streaming=True)), [{'ratio': 1.25}])
 
     def _check_variant_projection_literal_top_level_names(

Reply via email to