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 8db451dc1a [python] Add ordered row-ID batch sampling (#10957)
8db451dc1a is described below

commit 8db451dc1a372bbf3e4f6986ccba217eeb8e42c0
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 3 10:37:49 2026 +0800

    [python] Add ordered row-ID batch sampling (#10957)
---
 docs/docs/pypaimon/multimodal-reading.md           | 81 +++++++++++++---------
 docs/docs/pypaimon/pytorch.md                      |  8 +++
 paimon-python/pypaimon/multimodal/table.py         | 47 +++++++++++++
 .../pypaimon/read/datasource/torch_dataset.py      |  6 ++
 .../pypaimon/tests/multimodal_table_test.py        | 79 +++++++++++++++++++++
 paimon-python/pypaimon/tests/torch_read_test.py    | 33 +++++++++
 6 files changed, 221 insertions(+), 33 deletions(-)

diff --git a/docs/docs/pypaimon/multimodal-reading.md 
b/docs/docs/pypaimon/multimodal-reading.md
index 9db933334b..40c9909f55 100644
--- a/docs/docs/pypaimon/multimodal-reading.md
+++ b/docs/docs/pypaimon/multimodal-reading.md
@@ -540,27 +540,48 @@ row_ids = candidates["_ROW_ID"].tolist()
 
 When a row-id manifest is persisted beyond a short-lived latest-snapshot
 workflow, record the source snapshot or tag and pass it back to the read API.
-`scan`, `search`, `search_vectors`, `search_hybrid`, and `take_row_ids` accept
+`scan`, `search`, `search_vectors`, `search_hybrid`, `take_row_ids`, and 
`take_batch` accept
 `snapshot_id` or `tag_name`. These two options are mutually exclusive.
 
 Use `take_row_ids` to fetch rows selected by an earlier scan, vector search,
-full-text search, hybrid search, sampler, or split manifest. Results are not
-guaranteed to follow the input row-id order. Include `_ROW_ID` and reorder on
-the client if order matters.
+full-text search, hybrid search, or split manifest when only membership 
matters.
+It is a filtering query: input duplicates do not repeat rows, missing or 
deleted
+IDs are omitted, and result order is unspecified. For example,
+`take_row_ids([2, 0, 2])` can return row IDs `[0, 2]`.
+
+Use `take_batch` for training samplers, sampling with replacement, or any read
+that must align one-for-one with the supplied IDs:
+
+| API | Input identifiers | Order and duplicates | Missing rows |
+| --- | --- | --- | --- |
+| `take_row_ids(ids)` | Paimon `_ROW_ID` | Membership only; no order guarantee 
or repetition | Omitted |
+| `take_batch(ids, columns=...)` | Paimon `_ROW_ID` | Preserved exactly | 
Raises `KeyError` |
+| Map-style Torch Dataset `__getitems__(indices)` | Positions in that Dataset 
| Preserved exactly | Out-of-range positions raise `IndexError` |
 
 ```python
-payload = (
-    docs.take_row_ids(row_ids, snapshot_id=source_snapshot_id)
-    .select(["id", "content", "image"])
-    .with_row_id()
-    .to_arrow()
-    .to_pylist()
+batch = docs.take_batch(
+    row_ids,
+    columns=["id", "content", "image", "_ROW_ID"],
+    snapshot_id=source_snapshot_id,
 )
-
-payload_by_row_id = {row["_ROW_ID"]: row for row in payload}
-ordered_payload = [payload_by_row_id[row_id] for row_id in row_ids]
+assert batch["_ROW_ID"].to_pylist() == row_ids
+ordered_payload = batch.to_pylist()
 ```
 
+`take_batch` executes immediately and returns a `pyarrow.Table`. It requires
+row tracking. For existing row IDs `[2, 0, 2]`, it returns three rows in 
exactly
+that order. Empty input returns an empty table with the projected schema.
+`columns` defaults to all table columns; request `_ROW_ID` explicitly to 
include
+it. BLOB columns follow the table's read options, including
+`blob-as-descriptor`. A deleted, unavailable, or filtered-out ID fails the 
whole
+batch instead of silently reducing its size.
+
+For `scan().to_torch(streaming=False)`, let DataLoader pass sampler batches to
+the Dataset's `__getitems__`. These inputs are Dataset positions, so position
+`2` need not refer to Paimon row ID `2`. Both lazy and materialized map-style
+Datasets preserve sampler order and repeated positions; an empty batch returns
+an empty list.
+
 This pattern keeps broad candidate generation cheap: first search or filter to
 produce a compact row-id manifest, then fetch only the columns needed by the
 next stage.
@@ -580,24 +601,19 @@ manifest = (
 )
 
 # Stage 2: expensive reranking payload, fetched only for candidates.
-rerank_payload = (
-    docs.take_row_ids(
-        manifest["_ROW_ID"].tolist(),
-        snapshot_id=source_snapshot_id,
-    )
-    .select(["id", "content", "image"])
-    .with_row_id()
-    .to_list()
-)
+rerank_payload = docs.take_batch(
+    manifest["_ROW_ID"].tolist(),
+    columns=["id", "content", "image", "_ROW_ID"],
+    snapshot_id=source_snapshot_id,
+).to_pylist()
 
-payload_by_row_id = {row["_ROW_ID"]: row for row in rerank_payload}
 rerank_inputs = [
     {
-        "row_id": row_id,
+        "row_id": row["_ROW_ID"],
         "candidate_rank": rank,
-        "doc": payload_by_row_id[row_id],
+        "doc": row,
     }
-    for rank, row_id in enumerate(manifest["_ROW_ID"])
+    for rank, row in enumerate(rerank_payload)
 ]
 ```
 
@@ -608,12 +624,11 @@ they need:
 
 ```python
 def run_inference_worker(docs, row_id_batch, source_snapshot_id):
-    rows = (
-        docs.take_row_ids(row_id_batch, snapshot_id=source_snapshot_id)
-        .select(["id", "content"])
-        .with_row_id()
-        .to_list()
-    )
+    rows = docs.take_batch(
+        row_id_batch,
+        columns=["id", "content", "_ROW_ID"],
+        snapshot_id=source_snapshot_id,
+    ).to_pylist()
 
     outputs = []
     for row in rows:
@@ -635,7 +650,7 @@ Best practices:
   manifests.
 - Use business keys or application columns when writing inference or training
   outputs back to a table.
-- Reorder `take_row_ids` results client-side when input order matters.
+- Use `take_batch` when input order, repeated samples, or exact batch size 
matters.
 
 ### BLOB URI affinity
 
diff --git a/docs/docs/pypaimon/pytorch.md b/docs/docs/pypaimon/pytorch.md
index 865357b6f3..cc9bf72fbe 100644
--- a/docs/docs/pypaimon/pytorch.md
+++ b/docs/docs/pypaimon/pytorch.md
@@ -58,6 +58,14 @@ When the `streaming` parameter is true, it will iteratively 
read. When it is
 false, eligible data-evolution reads fetch each DataLoader batch lazily by row
 ID; other reads retain an Arrow table in memory for map-style access.
 
+In map-style mode, `__getitems__(indices)` preserves input order and repeated
+positions, including sampling with replacement. For example, `[2, 0, 2]`
+returns `[dataset[2], dataset[0], dataset[2]]`. DataLoader uses this batch
+interface for sampler output. Empty input returns an empty list; out-of-range
+positions raise `IndexError`. These indices are Dataset positions, not Paimon
+`_ROW_ID` values. To fetch an ordered batch of Paimon row IDs directly, use
+[`MultimodalTable.take_batch`](./multimodal-reading#row-ids).
+
 **`prefetch_concurrency`** (default: 1): In streaming row mode, controls
 reader threads per DataLoader worker. It has no effect in non-streaming mode.
 
diff --git a/paimon-python/pypaimon/multimodal/table.py 
b/paimon-python/pypaimon/multimodal/table.py
index 4c9a36b95c..045ae6a04b 100644
--- a/paimon-python/pypaimon/multimodal/table.py
+++ b/paimon-python/pypaimon/multimodal/table.py
@@ -21,6 +21,7 @@ from dataclasses import dataclass
 from typing import Dict, Mapping, Optional, Sequence
 
 import pyarrow as pa
+import pyarrow.compute as pc
 
 from pypaimon.common.options.core_options import CoreOptions
 from pypaimon.multimodal.query import (
@@ -532,9 +533,17 @@ class MultimodalTable:
             *,
             snapshot_id: Optional[int] = None,
             tag_name: Optional[str] = None):
+        """Return a scan filtering rows by Paimon row ID; requires row 
tracking.
+
+        Input order and duplicates do not affect this membership query.
+        Missing or deleted IDs are omitted. Use ``take_batch`` for ordered
+        sampling with replacement.
+        """
         row_ids = _coerce_row_ids(row_ids)
         read_table = _time_travel_table(
             self.raw_table, snapshot_id=snapshot_id, tag_name=tag_name)
+        if not read_table.options.row_tracking_enabled():
+            raise ValueError("Row ID reads require row-tracking.enabled=true.")
         read_builder = read_table.new_read_builder().with_projection(
             [field.name for field in read_table.fields]
             + [SpecialFields.ROW_ID.name]
@@ -545,6 +554,44 @@ class MultimodalTable:
         query._predicate = predicate
         return query
 
+    def take_batch(
+            self,
+            row_ids,
+            *,
+            columns=None,
+            snapshot_id: Optional[int] = None,
+            tag_name: Optional[str] = None) -> pa.Table:
+        """Fetch an ordered batch by Paimon row ID, preserving duplicates.
+
+        Returns an Arrow table with one row per input ID, in input order.
+        ``columns`` defaults to all table columns; include ``_ROW_ID``
+        explicitly to return it. Missing, deleted, or filtered-out IDs raise
+        KeyError instead of shortening the batch. An empty input returns an
+        empty table with the projected schema.
+
+        Requires row tracking. IDs are table row handles, not Dataset position
+        indices. Pass the source snapshot or tag when sampling a saved 
manifest.
+        BLOB columns follow the table's read options, as in ``scan()``.
+        """
+        row_ids = _coerce_row_ids(row_ids)
+        query = self.take_row_ids(
+            row_ids, snapshot_id=snapshot_id, tag_name=tag_name)
+        if columns is None:
+            columns = [field.name for field in query._table.fields]
+        elif isinstance(columns, str):
+            columns = [columns]
+        else:
+            columns = list(columns)
+
+        batch = query.select(columns).with_row_id().to_arrow()
+        requested = pa.array(row_ids, type=pa.int64())
+        positions = pc.index_in(
+            requested, value_set=batch.column(SpecialFields.ROW_ID.name))
+        if positions.null_count:
+            missing = requested.filter(pc.is_null(positions)).to_pylist()
+            raise KeyError("Row IDs not found: %s" % 
list(dict.fromkeys(missing)))
+        return batch.take(positions).select(columns)
+
     def blobs(self, *, column: Optional[str] = None, key_column: Optional[str] 
= None):
         from pypaimon.multimodal.blob_store import BlobStore
         return BlobStore(self, column=column, key_column=key_column)
diff --git a/paimon-python/pypaimon/read/datasource/torch_dataset.py 
b/paimon-python/pypaimon/read/datasource/torch_dataset.py
index 32663ca1a6..4a0d9542db 100644
--- a/paimon-python/pypaimon/read/datasource/torch_dataset.py
+++ b/paimon-python/pypaimon/read/datasource/torch_dataset.py
@@ -358,6 +358,12 @@ class TorchDataset(Dataset):
         return self.__getitems__([index])[0]
 
     def __getitems__(self, indices) -> List[dict]:
+        """Return one row per Dataset position, preserving order and repeats.
+
+        These are position indices in this Dataset, not Paimon ``_ROW_ID``s.
+        An empty batch returns an empty list; out-of-range positions raise
+        IndexError. Both lazy and materialized reads obey the same contract.
+        """
         normalized = [self._normalize_index(index) for index in indices]
         if not normalized:
             return []
diff --git a/paimon-python/pypaimon/tests/multimodal_table_test.py 
b/paimon-python/pypaimon/tests/multimodal_table_test.py
index be94381585..60a62bf936 100644
--- a/paimon-python/pypaimon/tests/multimodal_table_test.py
+++ b/paimon-python/pypaimon/tests/multimodal_table_test.py
@@ -2201,6 +2201,85 @@ class MultimodalTableTest(unittest.TestCase):
 
         self.assertEqual([], docs.take_row_ids([]).select(["id"]).to_list())
 
+    def test_row_id_filter_and_ordered_batch_have_distinct_contracts(self):
+        docs = self.conn.create_table(
+            "docs",
+            data=[{"id": i, "content": str(i)} for i in range(3)],
+            schema=_schema({"id": pa.int32(), "content": pa.string()}),
+            options=_PARQUET_OPTIONS,
+        )
+        requested = [2, 0, 2]
+
+        filtered = 
docs.take_row_ids(requested).select("id").with_row_id().to_list()
+        self.assertEqual(
+            [{"id": 0, "_ROW_ID": 0}, {"id": 2, "_ROW_ID": 2}],
+            sorted(filtered, key=lambda row: row["_ROW_ID"]),
+        )
+        batch = docs.take_batch(requested, columns=["content", "_ROW_ID"])
+        self.assertIsInstance(batch, pa.Table)
+        self.assertEqual(["content", "_ROW_ID"], batch.column_names)
+        self.assertEqual(
+            [{"content": str(i), "_ROW_ID": i} for i in requested],
+            batch.to_pylist(),
+        )
+        self.assertEqual(
+            [{"id": i, "content": str(i)} for i in requested],
+            docs.take_batch(iter(requested)).to_pylist(),
+        )
+        self.assertEqual(
+            [{"id": i} for i in requested],
+            docs.take_batch(pa.chunked_array([[2], [0, 2]]), 
columns="id").to_pylist(),
+        )
+
+    def test_take_batch_empty_and_missing_rows(self):
+        docs = self.conn.create_table(
+            "docs", data=[{"id": i} for i in range(3)],
+            schema=_schema({"id": pa.int32()}), options=_PARQUET_OPTIONS,
+        )
+        empty = docs.take_batch([], columns=["id", "_ROW_ID"])
+        self.assertEqual(
+            pa.schema([pa.field("id", pa.int32()), pa.field("_ROW_ID", 
pa.int64())]),
+            empty.schema,
+        )
+        self.assertEqual([], empty.to_pylist())
+        self.assertEqual(3, docs.take_batch([2, 0, 2], columns=[]).num_rows)
+
+        docs.delete(where="id = 1")
+        for row_ids in ([2, 1, 2], [99], [99, 1, 99]):
+            with self.subTest(row_ids=row_ids):
+                with self.assertRaisesRegex(KeyError, "Row IDs not found"):
+                    docs.take_batch(row_ids, columns="id")
+        self.assertEqual(
+            [2, 0, 2], docs.take_batch([2, 0, 2], 
columns="id")["id"].to_pylist())
+
+    def test_take_batch_reads_one_snapshot_with_order_and_duplicates(self):
+        docs = self.conn.create_table(
+            "docs", data=[{"id": i} for i in range(3)],
+            schema=_schema({"id": pa.int32()}), options=_PARQUET_OPTIONS,
+        )
+        snapshot_id = 
docs.raw_table.snapshot_manager().get_latest_snapshot().id
+        docs.raw_table.create_tag("training", snapshot_id=snapshot_id)
+        docs.delete(where="id = 2")
+
+        for selection in ({"snapshot_id": snapshot_id}, {"tag_name": 
"training"}):
+            with self.subTest(selection=selection):
+                self.assertEqual(
+                    [{"id": i, "_ROW_ID": i} for i in [2, 0, 2]],
+                    docs.take_batch(
+                        [2, 0, 2], columns=["id", "_ROW_ID"], 
**selection).to_pylist(),
+                )
+        with self.assertRaisesRegex(ValueError, "cannot be set at the same 
time"):
+            docs.take_batch([0], snapshot_id=snapshot_id, tag_name="training")
+
+    def test_row_id_reads_require_row_tracking(self):
+        docs = self.conn.create_table(
+            "docs", schema=_schema({"id": pa.int32()}), 
options=_PARQUET_OPTIONS)
+        untracked = docs.copy({"row-tracking.enabled": "false"})
+        for read in (untracked.take_row_ids, untracked.take_batch):
+            with self.subTest(read=read.__name__):
+                with self.assertRaisesRegex(ValueError, "require 
row-tracking.enabled=true"):
+                    read([0])
+
     def test_take_row_ids_supports_snapshot_and_tag_time_travel(self):
         docs = self.conn.create_table(
             "docs",
diff --git a/paimon-python/pypaimon/tests/torch_read_test.py 
b/paimon-python/pypaimon/tests/torch_read_test.py
index 192b2b7537..c961827600 100644
--- a/paimon-python/pypaimon/tests/torch_read_test.py
+++ b/paimon-python/pypaimon/tests/torch_read_test.py
@@ -715,6 +715,39 @@ class TorchReadTest(unittest.TestCase):
 
         print(f"✓ Test passed: Successfully read {len(all_user_ids)} rows with 
correct data")
 
+    @parameterized.expand([("materialized", False), ("lazy", True)])
+    def test_map_style_batch_sampling_preserves_order_and_replacement(self, 
name, lazy):
+        schema = Schema.from_pyarrow_schema(
+            self.pa_schema,
+            partition_keys=['dt'],
+            options={
+                'data-evolution.enabled': str(lazy).lower(),
+                'row-tracking.enabled': str(lazy).lower(),
+            },
+        )
+        identifier = 'default.test_torch_sampling_' + name
+        self.catalog.create_table(identifier, schema, False)
+        table = self.catalog.get_table(identifier)
+        self._write_test_table(table)
+        builder = table.new_read_builder().with_projection(['user_id', 
'behavior'])
+        read, splits = builder.new_read(), builder.new_scan().plan().splits()
+        expected = read.to_arrow(splits).to_pylist()
+        dataset = read.to_torch(splits, streaming=False)
+        self.assertEqual([], dataset.__getitems__([]))
+
+        batches = [[2, 0, 2], [len(dataset) - 1, 0, len(dataset) - 1]]
+        actual_batches = list(DataLoader(dataset, batch_sampler=batches))
+        self.assertEqual(len(batches), len(actual_batches))
+        for indices, actual in zip(batches, actual_batches):
+            self.assertEqual(
+                [expected[index]['user_id'] for index in indices],
+                actual['user_id'].tolist(),
+            )
+            self.assertEqual(
+                [expected[index]['behavior'] for index in indices], 
actual['behavior'])
+        with self.assertRaises(IndexError):
+            dataset.__getitems__([0, len(dataset)])
+
     def test_non_streaming_row_tracking_reads_batches_lazily(self):
         schema = Schema.from_pyarrow_schema(
             self.pa_schema,

Reply via email to