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 24708924fc [python] Build training datasets from search results 
(#10960)
24708924fc is described below

commit 24708924fcb169b79620312127486aed4b177ddc
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 3 12:10:41 2026 +0800

    [python] Build training datasets from search results (#10960)
---
 docs/docs/pypaimon/multimodal-reading.md           |   5 +
 docs/docs/pypaimon/multimodal-search.md            |  12 +
 docs/docs/pypaimon/pytorch.md                      |  48 +++
 paimon-python/pypaimon/multimodal/query.py         |  76 +++-
 .../pypaimon/multimodal/window_dataset.py          |  42 ++-
 .../tests/contiguous_window_dataset_test.py        |   7 +-
 .../pypaimon/tests/search_training_test.py         | 385 +++++++++++++++++++++
 7 files changed, 564 insertions(+), 11 deletions(-)

diff --git a/docs/docs/pypaimon/multimodal-reading.md 
b/docs/docs/pypaimon/multimodal-reading.md
index 40c9909f55..7d6afa95c2 100644
--- a/docs/docs/pypaimon/multimodal-reading.md
+++ b/docs/docs/pypaimon/multimodal-reading.md
@@ -369,6 +369,11 @@ original history, future and stride must be preserved. See
 [task-local context and anchor 
selection](pytorch#task-local-context-and-anchor-selection)
 for a metadata-only selection example and distributed ownership guidance.
 
+On data-evolution tables, search queries also expose
+`to_contiguous_window_dataset()`: hits automatically select anchors while a
+separate scan on the same snapshot preserves their history and future context.
+See [search hits as training samples and window 
anchors](pytorch#search-hits-as-training-samples-and-window-anchors).
+
 The Dataset plans and authorizes all requested columns once, reads only the
 index columns at construction, and reuses the resulting split metadata for
 lazy payload reads across projections and workers.
diff --git a/docs/docs/pypaimon/multimodal-search.md 
b/docs/docs/pypaimon/multimodal-search.md
index 57513fae0f..bbbdaccaf9 100644
--- a/docs/docs/pypaimon/multimodal-search.md
+++ b/docs/docs/pypaimon/multimodal-search.md
@@ -145,6 +145,18 @@ matches = (
 )
 ```
 
+## Training from Search Results
+
+On data-evolution tables, search queries can call `to_torch()` to train on 
their
+matching rows, or `to_contiguous_window_dataset()` to use those rows as 
training
+anchors. Both capture one snapshot for search, post-filtering, and subsequent
+training reads. Window history and future frames come from the full snapshot
+context, optionally restricted with `context_filter`; search filters and top-k
+only select anchors. Batch vector search returns one Dataset per input query.
+
+See [search hits as training samples and window 
anchors](pytorch#search-hits-as-training-samples-and-window-anchors)
+for examples, ordering, projection, and snapshot retention requirements.
+
 ## Scores and Result Ordering
 
 On data-evolution tables, use `with_score()` to append a `float64` relevance
diff --git a/docs/docs/pypaimon/pytorch.md b/docs/docs/pypaimon/pytorch.md
index cc9bf72fbe..5d263fbb3d 100644
--- a/docs/docs/pypaimon/pytorch.md
+++ b/docs/docs/pypaimon/pytorch.md
@@ -328,6 +328,54 @@ physical file/split boundaries inside those episodes. If 
context has already
 been divided among ranks, use a local sampler instead of sharding it again
 with a world-size `DistributedSampler`; coordinate rank step counts separately.
 
+### Search hits as training samples and window anchors
+
+On data-evolution tables, vector, full-text, and hybrid queries can directly
+call `to_torch()` or `to_contiguous_window_dataset()`. Both resolve the search
+and its post-filtered row IDs eagerly, then read training values lazily from
+that same snapshot. Reusing the query creates a new Dataset at the next
+execution's snapshot; an existing Dataset keeps its original read view.
+
+```python
+hits = (
+    frames.search(query_embedding, column="embedding", tag_name="train-v1")
+    .pre_filter("task_id = 'pick'")
+    .where("eligible = true")
+    .select(["state", "image", "action"])
+    .limit(1000)
+)
+
+# Train on the matching rows, with ordinary scan().to_torch() options.
+rows = hits.to_torch(streaming=True)
+
+# Use the matching rows as anchors while retaining their surrounding frames.
+windows = hits.to_contiguous_window_dataset(
+    context_filter="task_id = 'pick'",
+    frame_offsets={"state": [-2, -1, 0], "action": list(range(16))},
+    boundary="pad",
+)
+```
+
+For search windows, `pre_filter()`, `where()`, and `limit()` select anchors;
+they do not restrict the context or truncate its groups. The context defaults
+to the entire captured snapshot. Use `context_filter` to restrict it to 
complete
+episodes for the task. A selected anchor outside that context raises
+`ValueError`. The search supplies `anchor_row_ids`, so passing a separate
+selection is rejected. Stride, boundary handling, per-column offsets,
+transforms, and adapters retain the scan window semantics described above.
+
+`select()` supplies the training projection; windows can override it with
+`columns`. `to_torch()` returns rows in scan order, or in its requested shuffle
+order. Windows retain group/order and stride order. Neither conversion accepts
+`with_score()` or `order_by_score()`. Batch vector queries via `search_vectors`
+return one Dataset per input query, in input-query order, with a shared
+snapshot and context index. The context is read, validated, and sorted once
+for the batch; each Dataset keeps its own anchor selection, read cache, and
+video decoders. The search execution options `execution`, `concurrency`, and
+`ray_remote_args` match `to_arrow()`; training reads use the local PyTorch
+Dataset and its DataLoader workers. Retain the snapshot's files for the whole
+training run, for example with `tag_name="train-v1"`.
+
 ### Resuming a CWD training run
 
 Install `torchdata>=0.11,<0.12` alongside your compatible PyTorch installation.
diff --git a/paimon-python/pypaimon/multimodal/query.py 
b/paimon-python/pypaimon/multimodal/query.py
index e194628b33..0d9297292c 100644
--- a/paimon-python/pypaimon/multimodal/query.py
+++ b/paimon-python/pypaimon/multimodal/query.py
@@ -649,11 +649,77 @@ class _PreFilterQuery(ScanQuery):
             "not search queries."
         )
 
-    def to_contiguous_window_dataset(self, *args, **kwargs):
-        raise TypeError(
-            "to_contiguous_window_dataset is only supported on scan(), "
-            "not search queries."
-        )
+    def _training_selection(self, execution, concurrency, ray_remote_args):
+        if not self._table.options.data_evolution_enabled():
+            raise NotImplementedError("Search training datasets require a 
data-evolution table.")
+        if self._score_column or self._sort_by_score:
+            raise ValueError(
+                "Training datasets do not expose search scores or score 
ordering; "
+                "remove with_score() and order_by_score().")
+        query = self._for_execution()
+        lookup = copy(query)
+        # Resolve only row IDs, including post-filtering, on the captured
+        # snapshot. Keep payloads lazy and leave the reusable query untouched.
+        lookup._projection = [SpecialFields.ROW_ID.name]
+        lookup._include_row_id = False
+        matches = lookup.to_arrow(
+            execution=execution, concurrency=concurrency, 
ray_remote_args=ray_remote_args)
+        return query, matches
+
+    def to_torch(self, *args, execution="local", concurrency=None, 
ray_remote_args=None, **kwargs):
+        """Read search hits as a snapshot-pinned PyTorch Dataset.
+
+        Accepts the same Dataset options as ``scan().to_torch()`` and search
+        execution options as ``to_arrow()``. Search and post-filtering resolve
+        row IDs eagerly; projected payloads are read lazily, with BLOBs kept as
+        descriptors. Samples use scan order, or the requested Torch shuffle.
+        Search score output and score ordering are unsupported. Requires a
+        data-evolution table. Batch vector search returns one Dataset per 
query.
+        Retain the captured snapshot's files until training finishes.
+        """
+        query, matches = self._training_selection(execution, concurrency, 
ray_remote_args)
+
+        def convert(rows):
+            scan = ScanQuery(query._table)
+            scan._projection = query._projection
+            scan._include_row_id = query._include_row_id
+            builder = query._table.new_read_builder().with_projection(
+                [field.name for field in query._table.fields] + 
[SpecialFields.ROW_ID.name])
+            scan._predicate = builder.new_predicate_builder().is_in(
+                SpecialFields.ROW_ID.name, 
rows.column(SpecialFields.ROW_ID.name).to_pylist())
+            return scan.to_torch(*args, **kwargs)
+
+        return [convert(rows) for rows in matches] if isinstance(matches, 
list) else convert(matches)
+
+    def to_contiguous_window_dataset(
+            self, *, context_filter=None, execution="local", concurrency=None,
+            ray_remote_args=None, **kwargs):
+        """Build training windows anchored at search hits on the same snapshot.
+
+        Search pre_filter(), where() and limit() select anchors only. History
+        and future frames come from a separate scan of the captured snapshot,
+        optionally restricted by the SQL-like ``context_filter``. Keep complete
+        episodes in that context to preserve their bounds and stride schedule.
+        Other arguments match ``scan().to_contiguous_window_dataset()`` except
+        ``anchor_row_ids``, which this method supplies from the search results.
+        Search score output and score ordering are unsupported. Requires a
+        data-evolution table. Batch vector search returns one Dataset per 
query.
+        Retain the captured snapshot's files until training finishes.
+        """
+        if kwargs.pop("anchor_row_ids", None) is not None:
+            raise ValueError("Search supplies anchor_row_ids; use where() to 
further select anchors.")
+        predicate = self._coerce_predicate(context_filter, "context_filter")
+        query, matches = self._training_selection(execution, concurrency, 
ray_remote_args)
+        context = ScanQuery(query._table)
+        context._projection = query._projection
+        context._predicate = predicate
+
+        if isinstance(matches, list):
+            from pypaimon.multimodal.window_dataset import 
ContiguousWindowDataset
+            return ContiguousWindowDataset._from_anchor_selections(
+                context, [rows.column(SpecialFields.ROW_ID.name).to_pylist() 
for rows in matches], **kwargs)
+        return context.to_contiguous_window_dataset(
+            
anchor_row_ids=matches.column(SpecialFields.ROW_ID.name).to_pylist(), **kwargs)
 
 
 class VectorQuery(_PreFilterQuery):
diff --git a/paimon-python/pypaimon/multimodal/window_dataset.py 
b/paimon-python/pypaimon/multimodal/window_dataset.py
index c697d6eac9..991c224666 100644
--- a/paimon-python/pypaimon/multimodal/window_dataset.py
+++ b/paimon-python/pypaimon/multimodal/window_dataset.py
@@ -24,6 +24,7 @@ import operator
 import pickle
 import random
 from functools import partial
+from itertools import chain
 
 import numpy as np
 import pyarrow as pa
@@ -193,13 +194,17 @@ class ContiguousWindowDataset(Dataset):
         self.snapshot_id = plan.snapshot_id
         self._table = _pin_table(query._table, self.snapshot_id)
         self._splits = plan.splits()
+        self._build_index(index, anchor_row_ids)
+        self._reset_read_state()
+
+    def _reset_read_state(self):
         self._plans = {}
         self._video_collators = {
             name: VideoFrameCollator(
                 self._table,
                 video_column=name,
                 decoder_factory=partial(
-                    _open_default_video_decoder, backend=video_backend),
+                    _open_default_video_decoder, backend=self.video_backend),
                 decode_batch_fn=_decode_video_frames,
                 output_column=name,
                 collate_fn=list,
@@ -207,7 +212,6 @@ class ContiguousWindowDataset(Dataset):
             )
             for name in self._video_columns
         }
-        self._build_index(index, anchor_row_ids)
         self._checkpoint_identity = None
 
     @classmethod
@@ -215,6 +219,35 @@ class ContiguousWindowDataset(Dataset):
         """Build a contiguous-window Dataset from a ``ScanQuery``."""
         return cls(query, **kwargs)
 
+    @classmethod
+    def _from_anchor_selections(cls, query, anchor_selections, **kwargs):
+        """Share one validated context and authorized plan across a search 
batch."""
+        if not anchor_selections:
+            return []
+        context = cls(query, 
anchor_row_ids=dict.fromkeys(chain.from_iterable(anchor_selections)), **kwargs)
+        for name in ("_row_ids", "_group_starts", "_group_lengths", 
"_group_first_orders"):
+            getattr(context, name).flags.writeable = False
+        # Schedule and check boundaries only once, over the union of selected
+        # anchors. Each view then filters this small schedule, not the context.
+        anchor_ids = pa.array(context._row_ids[
+            context._group_starts[context._anchor_groups] + 
context._anchor_starts])
+        datasets = []
+        for selected in anchor_selections:
+            mask = pc.is_in(anchor_ids, value_set=pa.array(selected, 
type=pa.int64())).to_numpy(
+                zero_copy_only=False)
+            dataset = copy.copy(context)
+            dataset._anchor_groups = context._anchor_groups[mask]
+            dataset._anchor_starts = context._anchor_starts[mask]
+            for name in ("columns", "anchor_columns", "_video_columns"):
+                setattr(dataset, name, list(getattr(context, name)))
+            for name in ("frame_offsets", "column_transforms", "pad_values"):
+                setattr(dataset, name, dict(getattr(context, name)))
+            dataset._read_groups = {key: list(columns) for key, columns in 
context._read_groups.items()}
+            # Readers, decoders and checkpoint identity belong to each view.
+            dataset._reset_read_state()
+            datasets.append(dataset)
+        return datasets
+
     def __len__(self):
         return int(self._anchor_groups.size)
 
@@ -815,6 +848,11 @@ def _pin_table(table, snapshot_id):
     """
     if snapshot_id is None:
         return table
+    captured = getattr(table, "_read_snapshot", None)
+    if captured is not None and captured.id == snapshot_id:
+        # Search already captured the complete read view. Replacing it with
+        # a raw ID would lose tag-retained metadata after snapshot expiration.
+        return table
     tag_name = table.options.scan_tag_name()
     if tag_name is not None:
         _require_tag_snapshot(table, tag_name, snapshot_id)
diff --git a/paimon-python/pypaimon/tests/contiguous_window_dataset_test.py 
b/paimon-python/pypaimon/tests/contiguous_window_dataset_test.py
index d08c0c7106..77053e5b05 100644
--- a/paimon-python/pypaimon/tests/contiguous_window_dataset_test.py
+++ b/paimon-python/pypaimon/tests/contiguous_window_dataset_test.py
@@ -802,7 +802,7 @@ class ContiguousWindowDatasetTest(unittest.TestCase):
         self.assertEqual(0, dataset[0]["frame_index"])
         self.assertEqual([10, 11], dataset[0]["value"])
 
-    def test_rejects_scan_and_batch_vector_search_queries(self):
+    def test_constructor_requires_scan_instead_of_search_queries(self):
         table = self.conn.create_table(
             "vectors",
             schema=pa.schema([
@@ -826,8 +826,6 @@ class ContiguousWindowDatasetTest(unittest.TestCase):
         for query in (table.search([1.0, 0.0]),
                       table.search_vectors([[1.0, 0.0]])):
             with self.subTest(query=type(query).__name__):
-                with self.assertRaisesRegex(TypeError, "only supported on 
scan"):
-                    query.to_contiguous_window_dataset(**kwargs)
                 with self.assertRaisesRegex(TypeError, "only supported on 
scan"):
                     ContiguousWindowDataset.from_query(query, **kwargs)
 
@@ -1140,7 +1138,8 @@ class ContiguousWindowDatasetTest(unittest.TestCase):
                 group_key="is_pad", order_key="step")
 
         with self.assertRaisesRegex(TypeError, "only supported on scan"):
-            table.search("anything", 
column="episode").to_contiguous_window_dataset(
+            ContiguousWindowDataset.from_query(
+                table.search("anything", column="episode"),
                 window_size=2, columns=["value"],
                 group_key="episode", order_key="step")
 
diff --git a/paimon-python/pypaimon/tests/search_training_test.py 
b/paimon-python/pypaimon/tests/search_training_test.py
new file mode 100644
index 0000000000..ec8ee444f6
--- /dev/null
+++ b/paimon-python/pypaimon/tests/search_training_test.py
@@ -0,0 +1,385 @@
+# 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 pickle
+from unittest.mock import Mock, patch
+
+import numpy as np
+import pyarrow as pa
+import pytest
+import torch
+
+import pypaimon.multimodal as pm
+from pypaimon import CatalogFactory, Schema
+from pypaimon.multimodal.blob_read import fetch_blob_bodies
+from pypaimon.multimodal.query import ScanQuery, VectorQuery
+from pypaimon.multimodal import window_dataset
+from pypaimon.table.row.blob import BlobDescriptor
+
+
[email protected]
+def frames(tmp_path):
+    schema = pa.schema([
+        ("episode_index", pa.int64()), ("frame_index", pa.int64()),
+        ("state", pa.int64()), ("action", pa.int64()),
+        ("eligible", pa.bool_()), ("text", pa.string()),
+        ("embedding", pa.list_(pa.float32(), 2)), ("payload", 
pa.large_binary()),
+    ])
+    table = pm.connect(options={"warehouse": str(tmp_path)}).create_table(
+        "frames", schema=schema,
+        options={"file.format": "parquet", "vector.file.format": "parquet",
+                 "vector-index.search-mode": "full", 
"full-text-index.search-mode": "full",
+                 "read.batch-size": "2"})
+    for start in (0, 3, 6):
+        table.add(pa.Table.from_pylist([
+            {"episode_index": 0, "frame_index": step, "state": step,
+             "action": 10 + step, "eligible": step in (2, 5),
+             "text": "anchor" if step in (2, 5) else "context",
+             "embedding": [float(step), 0.], "payload": str(step).encode()}
+            for step in range(start, min(start + 3, 8))], schema=schema))
+    return table
+
+
+def search(frames, kind="vector", **options):
+    if kind in ("text", "hybrid"):
+        pytest.importorskip("paimon_ftindex")
+        frames.raw_table.copy({"deletion-vectors.enabled": 
"false"}).create_global_index(
+            "text", "full-text")
+    if kind == "text":
+        query = frames.search("anchor", column="text", **options)
+    elif kind == "hybrid":
+        query = frames.search_hybrid([
+            pm.vector_route("embedding", [2., 0.]),
+            pm.text_route("anchor", column="text")], **options)
+    elif kind == "batch":
+        query = frames.search_vectors([[2., 0.], [5., 0.]], **options)
+    else:
+        query = frames.search([2., 0.], **options)
+    return query.pre_filter("eligible = true").select(["state", 
"action"]).limit(2)
+
+
+def datasets(result, kind):
+    return result if kind == "batch" else [result]
+
+
[email protected]("kind", ["vector", "text", "hybrid", "batch"])
+def test_search_selects_anchors_and_retains_history_and_future(frames, kind):
+    query = search(frames, kind)
+    result = query.to_contiguous_window_dataset(
+        frame_offsets={"state": [-1, 0], "action": [0, 1]}, boundary="error")
+
+    for dataset in datasets(result, kind):
+        assert isinstance(dataset, torch.utils.data.Dataset)
+        assert len(dataset) == 2
+        samples = dataset[:]
+        assert [sample["frame_index"] for sample in samples] == [2, 5]
+        assert [sample["state"] for sample in samples] == [[1, 2], [4, 5]]
+        assert [sample["action"] for sample in samples] == [[12, 13], [15, 16]]
+        assert all(not sample["state_is_pad"].any() for sample in samples)
+    assert query._projection == ["state", "action"]
+    assert query._limit == 2
+
+
[email protected]("kind", ["vector", "text", "hybrid", "batch"])
[email protected]("streaming", [True, False])
+def test_search_to_torch_returns_only_post_filtered_hits(frames, kind, 
streaming):
+    query = search(frames, kind).where("frame_index = 5").with_row_id()
+    result = query.to_torch(streaming=streaming)
+    for dataset in datasets(result, kind):
+        assert list(dataset) == [{"state": 5, "action": 15, "_ROW_ID": 5}]
+
+
[email protected]("target", ["to_torch", 
"to_contiguous_window_dataset"])
+def test_search_and_training_share_snapshot_during_concurrent_update(frames, 
target):
+    query = search(frames).where("frame_index = 5")
+    snapshot = frames.raw_table.snapshot_manager().get_latest_snapshot().id
+    lookup = ScanQuery._read_global_index_result
+
+    def update_after_lookup(execution, result):
+        rows = lookup(execution, result)
+        frames.update("frame_index >= 0", {"action": 100})
+        return rows
+
+    options = ({"streaming": False} if target == "to_torch" else
+               {"frame_offsets": {"action": [-1, 0, 1]}, "boundary": "error"})
+    with patch.object(ScanQuery, "_read_global_index_result", 
update_after_lookup):
+        dataset = getattr(query, target)(**options)
+    if target == "to_torch":
+        assert list(dataset) == [{"state": 5, "action": 15}]
+        assert list(query.to_torch(streaming=False)) == [{"state": 5, 
"action": 100}]
+    else:
+        assert dataset.snapshot_id == snapshot
+        assert dataset[0]["action"] == [14, 15, 16]
+        assert query.to_contiguous_window_dataset(**options)[0]["action"] == 
[100, 100, 100]
+
+
[email protected]("selector", ["snapshot_id", "tag_name"])
+def test_search_training_honors_time_travel(frames, selector):
+    snapshot = frames.raw_table.snapshot_manager().get_latest_snapshot().id
+    frames.raw_table.create_tag("training", snapshot_id=snapshot)
+    frames.update("frame_index >= 0", {"action": 100})
+    if selector == "tag_name":
+        frames.raw_table.file_io.delete(
+            frames.raw_table.snapshot_manager().get_snapshot_path(snapshot))
+    options = {selector: snapshot if selector == "snapshot_id" else "training"}
+    query = search(frames, **options).where("frame_index = 5")
+    assert list(query.to_torch(streaming=False)) == [{"state": 5, "action": 
15}]
+    dataset = query.to_contiguous_window_dataset(frame_offsets={"action": [-1, 
0, 1]})
+    assert dataset.snapshot_id == snapshot
+    assert dataset[0]["action"] == [14, 15, 16]
+    dataset.load_state_dict(dataset.state_dict())
+
+
+def test_search_windows_resume_from_retained_tag(frames):
+    loader_type = 
pytest.importorskip("torchdata.stateful_dataloader").StatefulDataLoader
+    snapshot = frames.raw_table.snapshot_manager().get_latest_snapshot().id
+    frames.raw_table.create_tag("training", snapshot_id=snapshot)
+    frames.update("frame_index >= 0", {"action": 100})
+    
frames.raw_table.file_io.delete(frames.raw_table.snapshot_manager().get_snapshot_path(snapshot))
+    query = search(frames, tag_name="training")
+    offsets = {"action": [-1, 0, 1]}
+    loader = 
loader_type(query.to_contiguous_window_dataset(frame_offsets=offsets), 
batch_size=None)
+    iterator = iter(loader)
+    assert next(iterator)["action"] == [11, 12, 13]
+    state = loader.state_dict()
+    restored = 
loader_type(query.to_contiguous_window_dataset(frame_offsets=offsets), 
batch_size=None)
+    restored.load_state_dict(state)
+    assert [sample["action"] for sample in restored] == [[14, 15, 16]]
+
+
+def test_empty_search_does_not_expand_to_all_training_rows(frames):
+    query = search(frames).where("frame_index < 0")
+    with patch("pypaimon.multimodal.window_dataset.fetch_blob_bodies") as 
fetch:
+        dataset = query.to_contiguous_window_dataset(
+            columns=["payload"], frame_offsets={"payload": [-10, 10]}, 
boundary="error")
+        assert len(dataset) == 0
+        assert dataset[:] == []
+        fetch.assert_not_called()
+    assert list(query.to_torch()) == []
+    empty = query.to_torch(streaming=False)
+    assert len(empty) == 0
+    assert list(torch.utils.data.DataLoader(empty)) == []
+
+
+def test_window_context_filter_does_not_become_an_anchor_filter(frames):
+    query = search(frames).where("frame_index = 5")
+    dataset = query.to_contiguous_window_dataset(
+        context_filter="episode_index = 0", frame_offsets={"state": [-1, 0, 
1]})
+    assert dataset[0]["state"] == [4, 5, 6]
+    with pytest.raises(ValueError, match="outside the context query"):
+        query.to_contiguous_window_dataset(context_filter="frame_index < 5")
+
+
+def test_search_windows_keep_stride_and_boundary_semantics(frames):
+    dataset = search(frames).to_contiguous_window_dataset(
+        stride=2, frame_offsets={"state": [-2, 0, 5]}, boundary="error")
+    assert len(dataset) == 1
+    assert dataset[0]["state"] == [0, 2, 7]
+    padded = search(frames).where("frame_index = 
5").to_contiguous_window_dataset(
+        frame_offsets={"action": [-6, 0, 3]}, boundary="pad")
+    assert padded[0]["action"] == [10, 15, 17]
+    assert padded[0]["action_is_pad"].tolist() == [True, False, True]
+
+
[email protected]("target", ["to_torch", 
"to_contiguous_window_dataset"])
[email protected]("option", ["with_score", "order_by_score"])
+def test_training_rejects_search_score_output(frames, target, option):
+    with pytest.raises(ValueError, match="score"):
+        getattr(getattr(search(frames), option)(), target)()
+
+
+def test_search_windows_reject_explicit_anchor_override(frames):
+    with pytest.raises(ValueError, match="anchor_row_ids"):
+        search(frames).to_contiguous_window_dataset(anchor_row_ids=[0])
+
+
+def test_batch_search_keeps_query_specific_anchors(frames):
+    query = search(frames, "batch").limit(1)
+    windows = query.to_contiguous_window_dataset(frame_offsets={"state": [-1, 
0, 1]})
+    assert len(windows) == 2
+    assert [dataset[0]["state"] for dataset in windows] == [[1, 2, 3], [4, 5, 
6]]
+    rows = query.to_torch(streaming=False)
+    assert [list(dataset) for dataset in rows] == [
+        [{"state": 2, "action": 12}], [{"state": 5, "action": 15}]]
+    filtered = query.where("frame_index = 5").to_contiguous_window_dataset()
+    assert [len(dataset) for dataset in filtered] == [0, 1]
+
+
[email protected]("predicate,expected", [
+    (None, [[1, 2, 3], [4, 5, 6], [1, 2, 3]]),
+    ("frame_index = 5", [None, [4, 5, 6], None]),
+    ("frame_index < 0", [None, None, None]),
+])
+def test_batch_windows_read_and_retain_context_once(frames, predicate, 
expected):
+    query = (frames.search_vectors([[2., 0.], [5., 0.], [2., 0.]])
+             .pre_filter("eligible = true").select(["state"]).limit(1))
+    if predicate is not None:
+        query.where(predicate)
+    with patch.object(window_dataset, "_read_window_index", 
wraps=window_dataset._read_window_index) as read:
+        windows = query.to_contiguous_window_dataset(
+            frame_offsets={"state": [-1, 0, 1]}, boundary="error")
+    assert read.call_count == 1
+    assert [dataset[0]["state"] if len(dataset) else None for dataset in 
windows] == expected
+    for dataset in windows[1:]:
+        assert dataset._splits is windows[0]._splits
+        for name in ("_row_ids", "_group_starts", "_group_lengths", 
"_group_first_orders"):
+            assert np.shares_memory(getattr(dataset, name), 
getattr(windows[0], name))
+            assert not getattr(dataset, name).flags.writeable
+        assert dataset._plans is not windows[0]._plans
+        assert dataset.column_transforms is not windows[0].column_transforms
+
+
+def test_batch_window_views_keep_stride_checkpoints_and_worker_reads(frames):
+    query = search(frames, "batch").limit(1)
+    kwargs = {"frame_offsets": {"state": [-1, 0, 1]}, "boundary": "error"}
+    windows = query.to_contiguous_window_dataset(**kwargs)
+    state = windows[0].state_dict()
+    standalone = 
(frames.scan(snapshot_id=windows[0].snapshot_id).select(["state", "action"])
+                  .to_contiguous_window_dataset(anchor_row_ids=[2], **kwargs))
+    standalone.load_state_dict(state)
+    with pytest.raises(ValueError, match="different CWD"):
+        windows[1].load_state_dict(state)
+    windows[0][0]  # Warm one view's local read plan before serialization.
+    assert windows[0]._plans
+    assert not windows[1]._plans
+    restored = pickle.loads(pickle.dumps(windows))
+    assert restored[0]._row_ids is restored[1]._row_ids
+    assert not restored[0]._plans and not restored[1]._plans
+    restored[0].load_state_dict(state)
+    loader = torch.utils.data.DataLoader(
+        restored[1], batch_size=None, num_workers=1, 
multiprocessing_context="spawn")
+    assert [sample["state"] for sample in loader] == [[4, 5, 6]]
+    strided = query.to_contiguous_window_dataset(stride=2, **kwargs)
+    assert [len(dataset) for dataset in strided] == [1, 0]
+    assert strided[0][0]["state"] == [1, 2, 3]
+
+
+def test_batch_window_views_own_video_collators(tmp_path):
+    from pypaimon.table.row.blob import Blob
+
+    table = pm.connect(options={"warehouse": str(tmp_path)}).create_table(
+        "video", schema=pa.schema([
+            ("episode_index", pa.int64()), ("frame_index", pa.int64()),
+            ("embedding", pa.list_(pa.float32(), 2)), ("video", 
pa.large_binary()),
+        ]), options={"file.format": "parquet", "vector.file.format": "parquet",
+                     "vector-index.search-mode": "full", "video-frame-field": 
"video"})
+    video = tmp_path / "episode.mp4"
+    video.write_bytes(b"video-content")
+    table.add_video(Blob.from_local(str(video)), [
+        {"episode_index": 0, "frame_index": step, "embedding": [float(step), 
0.]}
+        for step in range(3)])
+    query = table.search_vectors([[0., 0.], [2., 0.]]).limit(1)
+    with patch.object(window_dataset, "VideoFrameCollator", side_effect=lambda 
*args, **kwargs: Mock()):
+        first, second = query.to_contiguous_window_dataset(columns=["video"])
+        assert first._video_collators["video"] is not 
second._video_collators["video"]
+        first.close()
+        first._video_collators["video"].close.assert_called_once()
+        second._video_collators["video"].close.assert_not_called()
+        second.close()
+
+
[email protected]("streaming", [True, False])
+def test_search_payloads_stay_lazy_and_torch_keeps_blob_descriptors(frames, 
streaming):
+    query = search(frames).select(["payload"]).where("frame_index = 5")
+    dataset = query.to_torch(streaming=streaming)
+    descriptor = BlobDescriptor.deserialize(list(dataset)[0]["payload"])
+    assert descriptor.length == 1
+    assert descriptor.uri.endswith(".blob")
+    with patch("pypaimon.multimodal.window_dataset.fetch_blob_bodies", 
wraps=fetch_blob_bodies) as fetch:
+        windows = query.to_contiguous_window_dataset(frame_offsets={"payload": 
[-1, 0, 1]})
+        fetch.assert_not_called()
+        assert windows[0]["payload"] == [b"4", b"5", b"6"]
+        assert fetch.call_count == 1
+
+
[email protected]("target", ["to_torch", 
"to_contiguous_window_dataset"])
+def test_training_dataset_can_be_read_in_spawned_workers(frames, target):
+    dataset = getattr(search(frames), target)()
+    loader = torch.utils.data.DataLoader(
+        dataset, batch_size=None, num_workers=2, 
multiprocessing_context="spawn")
+    assert sorted(sample["state"] if target == "to_torch" else 
sample["state"][0]
+                  for sample in loader) == [2, 5]
+
+
[email protected]("target", ["to_torch", 
"to_contiguous_window_dataset"])
+def test_training_rejects_primary_key_table(tmp_path, target):
+    catalog = CatalogFactory.create({"warehouse": str(tmp_path)})
+    catalog.create_database("db", False)
+    catalog.create_table("db.frames", Schema.from_pyarrow_schema(
+        pa.schema([("id", pa.int64()), ("embedding", pa.list_(pa.float32(), 
2))]),
+        primary_keys=["id"], options={"file.format": "parquet"}), False)
+    query = VectorQuery(catalog.get_table("db.frames"), [0., 0.], "embedding")
+    with pytest.raises(NotImplementedError, match="data-evolution"):
+        getattr(query, target)()
+
+
[email protected]("target", ["to_torch", 
"to_contiguous_window_dataset"])
+def test_training_validates_search_execution_options(frames, target):
+    with pytest.raises(ValueError, match="Ray options"):
+        getattr(search(frames), target)(concurrency=2)
+    with pytest.raises(ValueError, match="execution"):
+        getattr(search(frames), target)(execution="invalid")
+
+
[email protected]("target", ["to_torch", 
"to_contiguous_window_dataset"])
+def test_initially_empty_search_keeps_empty_training_view(tmp_path, target):
+    from pypaimon.execution.python.read.search.vector_search_scan import 
DataEvolutionVectorScan
+
+    schema = pa.schema([("episode_index", pa.int64()), ("frame_index", 
pa.int64()),
+                        ("state", pa.int64()), ("embedding", 
pa.list_(pa.float32(), 2))])
+    table = pm.connect(options={"warehouse": str(tmp_path)}).create_table(
+        "empty", schema=schema, options={
+            "file.format": "parquet", "vector.file.format": "parquet", 
"vector-index.search-mode": "full"})
+    query = table.search([0., 0.]).select(["state"])
+    scan = DataEvolutionVectorScan.scan
+
+    def append_before_search(execution):
+        table.add(pa.Table.from_pylist([
+            {"episode_index": 0, "frame_index": 0, "state": 10, "embedding": 
[0., 0.]}], schema=schema))
+        return scan(execution)
+
+    options = {"streaming": False} if target == "to_torch" else {}
+    with patch.object(DataEvolutionVectorScan, "scan", append_before_search):
+        dataset = getattr(query, target)(**options)
+    assert len(dataset) == 0
+    assert list(torch.utils.data.DataLoader(dataset)) == []
+    assert len(getattr(query, target)(**options)) == 1
+
+
[email protected]("kind,backend", [
+    ("vector", "vector_search._execute_vector_search"),
+    ("text", "full_text_search._execute_full_text_search"),
+    ("hybrid", "full_text_search._execute_hybrid_search"),
+    ("batch", "batch_vector_search._execute_batch_vector_search"),
+])
[email protected]("target", ["to_torch", 
"to_contiguous_window_dataset"])
+def test_training_delegates_ray_search_and_keeps_its_snapshot(frames, kind, 
backend, target):
+    query = search(frames, kind).where("frame_index = 5")
+    calls = []
+
+    def execute(builder, **options):
+        calls.append(options)
+        result = builder.execute_batch_local() if kind == "batch" else 
builder.execute_local()
+        frames.update("frame_index >= 0", {"action": 100})
+        return result
+
+    with patch("pypaimon.ray." + backend, side_effect=execute):
+        result = getattr(query, target)(
+            execution="ray", concurrency=2, ray_remote_args={"num_cpus": 1})
+    assert calls == [{"concurrency": 2, "ray_remote_args": {"num_cpus": 1}}]
+    for dataset in datasets(result, kind):
+        assert list(dataset)[0]["action"] == (15 if target == "to_torch" else 
[15])

Reply via email to