From d5fddf8372bd740387ef3df5a078760eff145403 Mon Sep 17 00:00:00 2001 From: Xin Sun Date: Thu, 5 Nov 2026 11:12:05 +0800 Subject: [PATCH 1/2] chore: update pylance dependency to v14.0.3 --- docs/src/write.md | 18 +++++---- lance_ray/io.py | 20 +++++----- pyproject.toml | 2 +- tests/test_basic_read_write.py | 10 ++--- tests/test_blob.py | 70 ++++++++++++++++++++++++---------- uv.lock | 28 +++++++------- 6 files changed, 89 insertions(+), 59 deletions(-) diff --git a/docs/src/write.md b/docs/src/write.md index 792de1b1..069563bc 100644 --- a/docs/src/write.md +++ b/docs/src/write.md @@ -43,19 +43,21 @@ Write a Ray Dataset to Lance format. ### Blob storage formats -`data_storage_version=None` uses PyLance's default stable format. Legacy blob -columns declared with `lance-encoding:blob=true` field metadata are supported by -file formats 2.0 and 2.1. When the version is omitted, `write_lance` rejects a -legacy blob schema before dispatching the write. To write these columns, -explicitly select a compatible format for both regular and streaming writes, -for example: +For new datasets, omitting `data_storage_version` uses PyLance's stable format, +currently 2.2. To write Blob v2 with the default format, construct the input with +`lance.blob_field` and `lance.blob_array`. For writes to an existing dataset, +PyLance uses that dataset's format when the version is omitted. + +Legacy Blob fields marked with `lance-encoding:blob=true` require an explicit +`data_storage_version` in both regular and streaming writes. Choose 2.1 to +preserve Blob v1 encoding. ```python write_lance(ds, uri, data_storage_version="2.1") ``` -To write blob columns in file formats 2.2 and later, use the Blob v2 extension -type (`lance.blob.v2`), constructed with `lance.blob_field` and `lance.blob_array`. +When creating a table from a legacy Blob schema, explicitly selecting 2.2 lets +PyLance convert the fields to Blob v2. ## Write retries diff --git a/lance_ray/io.py b/lance_ray/io.py index 83bfcb25..90f3b35b 100644 --- a/lance_ray/io.py +++ b/lance_ray/io.py @@ -223,8 +223,9 @@ def write_lance( limit. If not provided, the PyLance default is used. data_storage_version: The version of the data storage format to use. Newer versions are more efficient but require newer versions of lance to read. The default - (None) uses PyLance's stable format. Legacy blob columns require an - explicit compatible version such as "2.1". + (None) lets PyLance select the format for the destination. New datasets + use the stable format (currently "2.2"). Legacy Blob schemas require an + explicit version, such as "2.1" to preserve Blob v1 encoding. enable_stable_row_ids: Enable stable row IDs for the dataset and all fragments written by this operation. Default is False. storage_options: The storage options for the writer. Default is None. @@ -388,6 +389,7 @@ def write_lance( max_bytes_per_file=max_bytes_per_file, max_rows_per_group=min_rows_per_file, # keep naming aligned with v1 semantics data_storage_version=data_storage_version, + use_legacy_format=None, # Let PyLance resolve an omitted format. enable_stable_row_ids=enable_stable_row_ids, storage_options=storage_options, base_store_params=base_store_params, @@ -1232,18 +1234,16 @@ def _validate_legacy_blob_storage_version(schema: Optional[pa.Schema]) -> None: def legacy_blob_paths(field: "pa.Field[Any]", parent: str = "") -> list[str]: path = f"{parent}.{field.name}" if parent else field.name - metadata = field.metadata or {} - paths = [path] if metadata.get(b"lance-encoding:blob") == b"true" else [] - if pa.types.is_struct(field.type): - for child in field.type: - paths.extend(legacy_blob_paths(child, path)) + paths = [path] if b"lance-encoding:blob" in (field.metadata or {}) else [] + for index in range(field.type.num_fields): + paths.extend(legacy_blob_paths(field.type.field(index), path)) return paths paths = [path for field in schema for path in legacy_blob_paths(field)] if paths: fields = ", ".join(repr(path) for path in paths) raise ValueError( - f"Legacy blob field(s) {fields} are incompatible with the default " - 'stable data storage version. Set data_storage_version="2.1" to ' - "keep using legacy blob encoding, or migrate the field(s) to Blob v2." + f"Legacy Blob field(s) {fields} require an explicit data_storage_version. " + 'Use data_storage_version="2.1" to preserve Blob v1 encoding, or provide ' + "a Blob v2 schema to use the default format." ) diff --git a/pyproject.toml b/pyproject.toml index 1aa28ac3..fd181946 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,7 @@ classifiers = [ dependencies = [ "ray[data]>=2.41.0", - "pylance>=12.0.0", + "pylance>=14.0.3", "lance-namespace", "packaging", "pyarrow>=17.0.0", diff --git a/tests/test_basic_read_write.py b/tests/test_basic_read_write.py index 2a216af7..b6bd8238 100644 --- a/tests/test_basic_read_write.py +++ b/tests/test_basic_read_write.py @@ -579,7 +579,7 @@ def test_multiple_initial_bases_without_explicit_id(self, temp_dir: str) -> None ds = lance.dataset(uri) assert ds.count_rows() == 3 - base_paths = ds._ds.base_paths() # type: ignore[attr-defined] + base_paths = ds._ds.base_paths() assert len(base_paths) >= 2 base_ids = list(base_paths.keys()) assert len(set(base_ids)) == len(base_ids), ( @@ -642,7 +642,7 @@ def test_multiple_initial_bases_with_blob_v2(self, temp_dir: str) -> None: ds = lance.dataset(uri, base_store_params=base_store_params) assert ds.count_rows() == 2 - base_paths = ds._ds.base_paths() # type: ignore[attr-defined] + base_paths = ds._ds.base_paths() assert len(base_paths) >= 2 base_ids = list(base_paths.keys()) assert len(set(base_ids)) == len(base_ids), ( @@ -679,7 +679,7 @@ def test_explicit_ids_are_preserved(self, temp_dir: str) -> None: ds = lance.dataset(uri) assert ds.count_rows() == 2 - base_paths = ds._ds.base_paths() # type: ignore[attr-defined] + base_paths = ds._ds.base_paths() assert 5 in base_paths assert 10 in base_paths @@ -713,7 +713,7 @@ def test_mixed_explicit_and_implicit_ids(self, temp_dir: str) -> None: ds = lance.dataset(uri) assert ds.count_rows() == 2 - base_paths = ds._ds.base_paths() # type: ignore[attr-defined] + base_paths = ds._ds.base_paths() assert 3 in base_paths base_ids = list(base_paths.keys()) assert len(set(base_ids)) == len(base_ids), ( @@ -752,5 +752,5 @@ def test_dataset_root_base_gets_id_zero(self, temp_dir: str) -> None: ds = lance.dataset(uri) assert ds.count_rows() == 2 - base_paths = ds._ds.base_paths() # type: ignore[attr-defined] + base_paths = ds._ds.base_paths() assert 0 in base_paths diff --git a/tests/test_blob.py b/tests/test_blob.py index 83ed6868..c6af219d 100755 --- a/tests/test_blob.py +++ b/tests/test_blob.py @@ -3,8 +3,8 @@ This test ensures that pa.large_binary fields with metadata {"lance-encoding:blob": "true"} are written and read back with byte-for-byte fidelity using write_lance and read_lance. -These tests explicitly use file format 2.1 to exercise legacy blob -encoding, which is not supported by file formats 2.2 and later. +The tests cover explicit file-format selection for legacy Blob fields and +PyLance's default format for native Blob v2 fields. Tests cover: - Single blob column round-trip @@ -36,6 +36,7 @@ # Skip cleanly if Lance isn't available in the environment pytest.importorskip("lance") +import lance import lance_ray.io as lr @@ -73,34 +74,61 @@ def _generate_jpg_bytes() -> bytes: return os.urandom(64 * 64 * 3) -@pytest.mark.parametrize("provide_schema", [True, False]) +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("provide_schema", [False, True]) def test_legacy_blob_requires_explicit_version( - temp_dir: str, provide_schema: bool + tmp_path: Path, stream: bool, provide_schema: bool ) -> None: - """Reject legacy blobs before dispatch when the file version is omitted.""" - path = Path(temp_dir) / "legacy_blob_default_version.lance" - schema_fields: list[pa.Field[Any]] = [ - pa.field( - "blob", - pa.large_binary(), - metadata={"lance-encoding:blob": "true"}, - ), - pa.field("id", pa.int64()), - ] - schema = pa.schema(schema_fields) - table = pa.table({"blob": [b"foo", None], "id": [1, 2]}, schema=schema) + path = tmp_path / "legacy_blob_default_version.lance" + schema = pa.schema( + [pa.field("blob", pa.large_binary(), metadata={"lance-encoding:blob": "true"})] + ) + table = pa.table({"blob": [b"foo", None]}, schema=schema) - with pytest.raises(ValueError) as exc_info: + with pytest.raises(ValueError, match="data_storage_version"): lr.write_lance( ray.data.from_arrow(table), str(path), schema=schema if provide_schema else None, + stream=stream, ) - message = str(exc_info.value) - assert "blob" in message - assert 'data_storage_version="2.1"' in message - assert "Blob v2" in message + assert not path.exists() + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize( + "legacy_input", [False, True], ids=["native-default", "legacy-2.2"] +) +def test_write_blob_v2(tmp_path: Path, stream: bool, legacy_input: bool) -> None: + path = tmp_path / "blob_v2.lance" + values = [b"foo", None] + if legacy_input: + schema = pa.schema( + [ + pa.field( + "blob", pa.large_binary(), metadata={"lance-encoding:blob": "true"} + ) + ] + ) + table = pa.table({"blob": values}, schema=schema) + lr.write_lance( + ray.data.from_arrow(table), + str(path), + stream=stream, + data_storage_version="2.2", + ) + else: + table = pa.table({"blob": lance.blob_array(values)}) + lr.write_lance(ray.data.from_arrow(table), str(path), stream=stream) + + dataset = lance.dataset(path) + assert dataset.data_storage_version == "2.2" + blob_type = dataset.schema.field("blob").type + assert isinstance(blob_type, pa.ExtensionType) + assert blob_type.extension_name == "lance.blob.v2" + blobs = dataset.take_blobs("blob", indices=[0, 1]) + assert [blob.read() if blob is not None else None for blob in blobs] == values def test_single_blob_roundtrip(temp_dir: str) -> None: diff --git a/uv.lock b/uv.lock index b9ce0832..96d3de5c 100644 --- a/uv.lock +++ b/uv.lock @@ -482,19 +482,19 @@ wheels = [ [[package]] name = "lance-namespace" -version = "0.11.1" +version = "0.13.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "lance-namespace-urllib3-client" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/bf/93/da5f7fcac690db9b282a3439ed9e34960c147619a0d6e1f4eb8cd240e7a5/lance_namespace-0.11.1.tar.gz", hash = "sha256:f67cfbbe0647b7cb42f23b673e7edf8a75b7d8a047265a916492f8d247ee1bc2", size = 11631, upload-time = "2026-08-18T17:40:06.294Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c0/e7/d5d46594678ee479c0eda830c47b2f5c46133bd100e84e9aa6e01306eca7/lance_namespace-0.13.0.tar.gz", hash = "sha256:24554a0997bdb39595c6e4cb3ac6722069f6cd3bd1a74e7acbba7bfaf774a40d", size = 11636, upload-time = "2026-09-14T02:47:03.871Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fa/bc/601f2b3cc4cfa0070d858a33223bc823fffdd7981a25c45984a5216ca952/lance_namespace-0.11.1-py3-none-any.whl", hash = "sha256:07643fce9a42ad4d58cc8bf91e3f592bc7f4cbd8d0ad5233223506debf67551c", size = 13507, upload-time = "2026-08-18T17:40:03.561Z" }, + { url = "https://files.pythonhosted.org/packages/e7/47/cfa33cca1ba7c749fd2918cfc5c8ded788f378cc6424d23e4fead5a14125/lance_namespace-0.13.0-py3-none-any.whl", hash = "sha256:438c7b17aef421c21c138196e715f2510d62f07e865372047f87c1e75e618c7a", size = 13507, upload-time = "2026-09-14T02:47:01.765Z" }, ] [[package]] name = "lance-namespace-urllib3-client" -version = "0.11.1" +version = "0.13.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pydantic" }, @@ -502,9 +502,9 @@ dependencies = [ { name = "typing-extensions" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e4/c5/2bdd0ff98b469894c8a73be809d26ffdad5402517b0e5f9e758026cba29e/lance_namespace_urllib3_client-0.11.1.tar.gz", hash = "sha256:145a9e9424d7597487249b5b95ee274423bf2910e1a9160b6a07b676b61ea46a", size = 237345, upload-time = "2026-08-18T17:40:07.308Z" } +sdist = { url = "https://files.pythonhosted.org/packages/69/25/9aaa4a5e8999693fb0f227c2c0c4b97bd8f0539066408cdff0b89d41b2d5/lance_namespace_urllib3_client-0.13.0.tar.gz", hash = "sha256:1e8a79c6e4e6277033597fd76aa0e2f33d909ca1436c935936e9e569221f43ef", size = 238348, upload-time = "2026-09-14T02:47:04.521Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/2a/eaaefd55d1190291207049fedc6b3eb22b506e57d6de91bae46bbaaa9c60/lance_namespace_urllib3_client-0.11.1-py3-none-any.whl", hash = "sha256:36537f529294da6d884ba0fe783704483f0a75463497c7705fd083a4d0257990", size = 406311, upload-time = "2026-08-18T17:40:04.842Z" }, + { url = "https://files.pythonhosted.org/packages/60/4c/7b8f0712a7fe1b8655b711342bc4989696635a79e7027ee56ba3cae23e99/lance_namespace_urllib3_client-0.13.0-py3-none-any.whl", hash = "sha256:fb361eb4f6c7f2d1f9e92809609657b73e38241393e9c4516e12d6b6ee643a0a", size = 406848, upload-time = "2026-09-14T02:47:02.715Z" }, ] [[package]] @@ -552,7 +552,7 @@ requires-dist = [ { name = "pandas-stubs", marker = "extra == 'dev'" }, { name = "pyarrow", specifier = ">=17.0.0" }, { name = "pyarrow-stubs", marker = "extra == 'dev'", specifier = ">=20.0.0.20260819" }, - { name = "pylance", specifier = ">=12.0.0" }, + { name = "pylance", specifier = ">=14.0.3" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.4.0" }, { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=1.0.0" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=5.0.0" }, @@ -1355,7 +1355,7 @@ wheels = [ [[package]] name = "pylance" -version = "12.0.0" +version = "14.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "lance-namespace" }, @@ -1364,12 +1364,12 @@ dependencies = [ { name = "pyarrow" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/32/e6/f95aaa102e141a133418ed247051df3077aacb1851ee3bad88f3045fb5fc/pylance-12.0.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:58583827b01ae14da220dcea2ea258b008e8d2d20915cf462dee18ddcea068a5", size = 72336247, upload-time = "2026-09-17T16:41:26.318Z" }, - { url = "https://files.pythonhosted.org/packages/4f/24/1f38770557db8189c63b0eeff497f0a6a9fc799ed2e3b2b023365b3a3ad9/pylance-12.0.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca5af2bf6e489b76768b56848b8e9c692ad42d7eedb31a8097fcb57e3146a211", size = 76717015, upload-time = "2026-09-17T16:44:55.744Z" }, - { url = "https://files.pythonhosted.org/packages/da/a4/4e87599ed6120bb6ae91b7611b9a1685759cc2e12898585c5ee347827168/pylance-12.0.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bac18e8f6fecb9c998c2a7301d782281bac075cf06bb0df5d89fc6fc4e8768e1", size = 80868316, upload-time = "2026-09-17T16:53:32.971Z" }, - { url = "https://files.pythonhosted.org/packages/c6/81/b1a578be4c3845183f84bcc19cc0e3bacff2052868faeec975e00e3b7bad/pylance-12.0.0-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:df80a7991fbeab9ca206da4c0110e611696e29fc7b79bc9a88309b1b42c5849f", size = 76735408, upload-time = "2026-09-17T16:45:07.137Z" }, - { url = "https://files.pythonhosted.org/packages/63/1c/2596ba2f0a7dedb28b7e4d07b6d1996365f501fb9329af422afd31a95179/pylance-12.0.0-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:d002980aa548336682f1445427ea89cf39e71a452297741ca97627192e4a1678", size = 80846740, upload-time = "2026-09-17T17:01:03.452Z" }, - { url = "https://files.pythonhosted.org/packages/2d/0c/69df299e26b5594e8b919bc16a6a951295da96f2237eadb2e2b52c2b0316/pylance-12.0.0-cp310-abi3-win_amd64.whl", hash = "sha256:0cd59044927c5ee5a6811ea28b6f4860b2d21932828e770d9e5b39522afcf19d", size = 87083663, upload-time = "2026-09-17T16:55:09.236Z" }, + { url = "https://files.pythonhosted.org/packages/29/7e/b8030828178529ee8c7b78dad7c680cb8ea970d96a5b972aae1d91b2dd14/pylance-14.0.3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:7211e5ac9189133694add2eb1d49088501e1206971c4454233307495ecacf1dc", size = 76486181, upload-time = "2026-11-15T06:52:45.448Z" }, + { url = "https://files.pythonhosted.org/packages/61/e8/9144845106aed0210ec0eff833a2154f0bc2b7b0386916d5efe0acd566e4/pylance-14.0.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2557754ad9008105a666d4fab1041652bed400f7d8485cd8ec043b08c6273fa1", size = 80910738, upload-time = "2026-11-15T06:52:36.282Z" }, + { url = "https://files.pythonhosted.org/packages/b4/47/1fdf43ae978fb336f65f7e4ed1b3d878d07a0432d224156b4934251c4dcd/pylance-14.0.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd9c4457284532bfccf874f87d3024aee4c9afb2ed6f35a1e4d2a01942837b37", size = 85335706, upload-time = "2026-11-15T07:01:47.888Z" }, + { url = "https://files.pythonhosted.org/packages/17/b6/da9ca6aee877b1a52ebcdd2b2de5ee1e60bea1ae5d2a98d59286a6a76cc0/pylance-14.0.3-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:4a3bb895705235d2ea930f50a085182d679857465df233bebce0756a4f814e69", size = 80934425, upload-time = "2026-11-15T06:51:38.956Z" }, + { url = "https://files.pythonhosted.org/packages/ac/09/b76892021cef4676ad5c5f30f4ac4658dd876acc73469633d7308483db88/pylance-14.0.3-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:5e243a163bcea26d5762e1d5325bb49a81afa80b259aad923ec58521461a370c", size = 85340490, upload-time = "2026-11-15T06:53:51.239Z" }, + { url = "https://files.pythonhosted.org/packages/db/60/4a2b465b2b2508c9643318f2198bc72746029bce53259fe5955c2f89a07e/pylance-14.0.3-cp310-abi3-win_amd64.whl", hash = "sha256:df814dd79b3efca4403f2f2a4286687d7de6b913599b87acbaea217bdc06fe6b", size = 92616501, upload-time = "2026-11-15T06:55:00.894Z" }, ] [[package]] From 9661b64069e2727359155a8aab993580fcd1104a Mon Sep 17 00:00:00 2001 From: Xin Sun Date: Mon, 16 Nov 2026 22:04:12 +0800 Subject: [PATCH 2/2] fix: align legacy Blob writes with PyLance --- docs/src/write.md | 12 ++-- lance_ray/datasink.py | 151 ++++++++++++++++++++++++++++++++--------- lance_ray/io.py | 36 ++-------- tests/test_blob.py | 121 +++++++++++++++++++++++++++++---- tests/test_fragment.py | 44 ++++++++++++ 5 files changed, 277 insertions(+), 87 deletions(-) diff --git a/docs/src/write.md b/docs/src/write.md index 069563bc..83ba7b65 100644 --- a/docs/src/write.md +++ b/docs/src/write.md @@ -44,21 +44,17 @@ Write a Ray Dataset to Lance format. ### Blob storage formats For new datasets, omitting `data_storage_version` uses PyLance's stable format, -currently 2.2. To write Blob v2 with the default format, construct the input with -`lance.blob_field` and `lance.blob_array`. For writes to an existing dataset, -PyLance uses that dataset's format when the version is omitted. +currently 2.2. Appends that omit the version use the destination's default. -Legacy Blob fields marked with `lance-encoding:blob=true` require an explicit -`data_storage_version` in both regular and streaming writes. Choose 2.1 to +In format 2.2, PyLance accepts Blob v2 inputs created with `lance.blob_field` and +`lance.blob_array` and converts legacy Blob fields marked with +`lance-encoding:blob=true` to Blob v2. Choose 2.1 with a legacy Blob schema to preserve Blob v1 encoding. ```python write_lance(ds, uri, data_storage_version="2.1") ``` -When creating a table from a legacy Blob schema, explicitly selecting 2.2 lets -PyLance convert the fields to Blob v2. - ## Write retries `write_lance` uses `LanceDatasink`, which allows up to ten fragment write attempts diff --git a/lance_ray/datasink.py b/lance_ray/datasink.py index 4d8b136e..b35147fe 100644 --- a/lance_ray/datasink.py +++ b/lance_ray/datasink.py @@ -1,5 +1,7 @@ import pickle from collections.abc import Iterable, Iterator +from contextlib import ExitStack +from itertools import chain, dropwhile from typing import ( TYPE_CHECKING, Any, @@ -15,6 +17,7 @@ from ray.data.datasource.datasink import Datasink, WriteResult from .fragment import ( + FragmentBlock, FragmentStream, FragmentStreamFactory, prepare_fragment_write_options, @@ -138,6 +141,7 @@ def __init__( self.uri = uri self.schema = schema + self._append_target_schema: Optional[pa.Schema] = None self.mode = mode self.enable_stable_row_ids = enable_stable_row_ids self.read_version: Optional[int] = None @@ -185,7 +189,7 @@ def on_write_start(self, schema: Optional[pa.Schema] = None) -> None: ) self.read_version = ds.version if self.schema is None: - self.schema = ds.schema + self._append_target_schema = ds.schema def on_write_complete( self, @@ -285,9 +289,8 @@ class LanceDatasink(_BaseLanceDatasink): provided, the PyLance default is used. data_storage_version: optional, str, default None The version of the data storage format to use. Newer versions are more - efficient but require newer versions of lance to read. The default is - "legacy" which will use the legacy v1 version. See the user guide - for more details. + efficient but require newer versions of lance to read. When omitted, + PyLance uses the destination's default or the stable format for a new dataset. enable_stable_row_ids : bool, default False Enable stable row IDs for the dataset and all written fragments. storage_options : Dict[str, Any], optional @@ -416,35 +419,62 @@ def write( ctx: Any, ) -> WriteReturn: stream: FragmentStream | FragmentStreamFactory = blocks - if self._retry_params.get("max_attempts", 1) > 1: - # Retain the existing block objects, without copying their Arrow data. - replayable_blocks = list(blocks) - - def stream_factory() -> Iterator[Union[pa.Table, "pd.DataFrame"]]: - return iter(replayable_blocks) - - stream = stream_factory - - fragments_and_schema = write_fragment( - stream, - self.dataset_uri, - schema=self.schema, - max_rows_per_file=self.max_rows_per_file, - max_bytes_per_file=self.max_bytes_per_file, - data_storage_version=self.data_storage_version, - enable_stable_row_ids=self.enable_stable_row_ids, - storage_options=self.storage_options, - base_store_params=self.base_store_params, - initial_bases=self.initial_bases if self.mode == "create" else None, - target_bases=self.target_bases, - target_all_bases=self.target_all_bases, - external_blob_mode=self.external_blob_mode, - allow_external_blob_outside_bases=self.allow_external_blob_outside_bases, - namespace_impl=self._namespace_impl, - namespace_properties=self._namespace_properties, - table_id=self.table_id, - retry_params=self._retry_params, - ) + target_schema = self._append_target_schema if self.schema is None else None + cast_schema = self.schema if target_schema is None else target_schema + first: FragmentBlock | None = None + + with ExitStack() as resources: + if self._retry_params.get("max_attempts", 1) > 1: + # Retain the existing block objects, without copying their Arrow data. + replayable_blocks = list(blocks) + if target_schema is not None: + first = next( + dropwhile(_is_empty_block_without_columns, replayable_blocks), + None, + ) + + def stream_factory() -> Iterator[Union[pa.Table, "pd.DataFrame"]]: + return iter(replayable_blocks) + + stream = stream_factory + elif target_schema is not None: + block_iter = iter(blocks) + # The wrapped iterator has no close() of its own. + if not isinstance(blocks, Iterator): + close = getattr(block_iter, "close", None) + if callable(close): + resources.callback(close) + data_blocks = dropwhile(_is_empty_block_without_columns, block_iter) + try: + first = next(data_blocks) + except StopIteration: + stream = () + else: + stream = chain((first,), data_blocks) + + if target_schema is not None and isinstance(first, pa.Table): + cast_schema = _append_cast_schema(target_schema, first.schema) + + fragments_and_schema = write_fragment( + stream, + self.dataset_uri, + schema=cast_schema, + max_rows_per_file=self.max_rows_per_file, + max_bytes_per_file=self.max_bytes_per_file, + data_storage_version=self.data_storage_version, + enable_stable_row_ids=self.enable_stable_row_ids, + storage_options=self.storage_options, + base_store_params=self.base_store_params, + initial_bases=self.initial_bases if self.mode == "create" else None, + target_bases=self.target_bases, + target_all_bases=self.target_all_bases, + external_blob_mode=self.external_blob_mode, + allow_external_blob_outside_bases=self.allow_external_blob_outside_bases, + namespace_impl=self._namespace_impl, + namespace_properties=self._namespace_properties, + table_id=self.table_id, + retry_params=self._retry_params, + ) return [ (pickle.dumps(fragment), pickle.dumps(schema)) for fragment, schema in fragments_and_schema @@ -482,3 +512,58 @@ def write( ): v.append((fragment, schema)) return v + + +def _is_empty_block_without_columns(block: FragmentBlock) -> bool: + return isinstance(block, pa.Table) and block.num_rows == block.num_columns == 0 + + +def _append_cast_schema(target: pa.Schema, source: pa.Schema) -> pa.Schema: + """Keep legacy Blob values intact for PyLance while casting ordinary fields.""" + metadata = target.metadata + return pa.schema( + _append_fields_with_legacy_blobs(target, source), + metadata=dict(metadata.items()) if metadata is not None else None, + ) + + +def _append_fields_with_legacy_blobs( + target: pa.Schema | pa.StructType, source: pa.Schema | pa.StructType +) -> "list[pa.Field[Any]]": + fields = [] + for field in target: + source_index = source.get_field_index(field.name) + if source_index != -1: + field = _append_field_with_legacy_blob(field, source.field(source_index)) + fields.append(field) + return fields + + +def _append_field_with_legacy_blob( + target: "pa.Field[Any]", source: "pa.Field[Any]" +) -> "pa.Field[Any]": + target_type, source_type = target.type, source.type + if ( + isinstance(target_type, pa.ExtensionType) + and target_type.extension_name == "lance.blob.v2" + and source_type in (pa.binary(), pa.large_binary()) + and b"lance-encoding:blob" in (source.metadata or {}) + ): + return source.with_name(target.name).with_nullable(target.nullable) + if isinstance(target_type, pa.StructType) and isinstance( + source_type, pa.StructType + ): + return target.with_type( + pa.struct(_append_fields_with_legacy_blobs(target_type, source_type)) + ) + if isinstance(target_type, pa.ListType | pa.LargeListType) and isinstance( + source_type, pa.ListType | pa.LargeListType + ): + value = _append_field_with_legacy_blob( + target_type.value_field, source_type.value_field + ) + list_type = ( + pa.large_list if isinstance(target_type, pa.LargeListType) else pa.list_ + ) + return target.with_type(list_type(value)) + return target diff --git a/lance_ray/io.py b/lance_ray/io.py index 90f3b35b..278c4f80 100644 --- a/lance_ray/io.py +++ b/lance_ray/io.py @@ -215,7 +215,9 @@ def write_lance( with namespace parameters when creating a new dataset (mode='create' or 'overwrite'). table_id: The table identifier as a list of strings. Must be provided together with namespace_impl and namespace_properties. - schema: The schema of the dataset. If not provided, it is inferred from the data. + schema: The Arrow schema to use for the input. Regular appends default to + the destination schema for casting, leaving legacy Blob inputs for + PyLance to handle. Other writes infer the schema from the input. mode: The write mode. Can be "create", "append", or "overwrite". min_rows_per_file: The minimum number of rows per file. max_rows_per_file: The maximum number of rows per file. @@ -224,8 +226,8 @@ def write_lance( data_storage_version: The version of the data storage format to use. Newer versions are more efficient but require newer versions of lance to read. The default (None) lets PyLance select the format for the destination. New datasets - use the stable format (currently "2.2"). Legacy Blob schemas require an - explicit version, such as "2.1" to preserve Blob v1 encoding. + use the stable format (currently "2.2"). Appends use the destination's + default. Choose "2.1" with a legacy Blob schema to preserve Blob v1 encoding. enable_stable_row_ids: Enable stable row IDs for the dataset and all fragments written by this operation. Default is False. storage_options: The storage options for the writer. Default is None. @@ -269,13 +271,6 @@ def write_lance( stacklevel=2, ) initial_bases = normalize_initial_bases(initial_bases) - if data_storage_version is None: - write_schema = schema - if write_schema is None: - ray_schema = ds.schema() - if ray_schema is not None and isinstance(ray_schema.base_schema, pa.Schema): - write_schema = ray_schema.base_schema - _validate_legacy_blob_storage_version(write_schema) # Fast path: non-streaming write using the Datasink API. if not stream: @@ -1226,24 +1221,3 @@ def _validate_write_args( raise ValueError( "Must provide either 'uri' OR ('namespace_impl' + 'table_id')." ) - - -def _validate_legacy_blob_storage_version(schema: Optional[pa.Schema]) -> None: - if schema is None: - return - - def legacy_blob_paths(field: "pa.Field[Any]", parent: str = "") -> list[str]: - path = f"{parent}.{field.name}" if parent else field.name - paths = [path] if b"lance-encoding:blob" in (field.metadata or {}) else [] - for index in range(field.type.num_fields): - paths.extend(legacy_blob_paths(field.type.field(index), path)) - return paths - - paths = [path for field in schema for path in legacy_blob_paths(field)] - if paths: - fields = ", ".join(repr(path) for path in paths) - raise ValueError( - f"Legacy Blob field(s) {fields} require an explicit data_storage_version. " - 'Use data_storage_version="2.1" to preserve Blob v1 encoding, or provide ' - "a Blob v2 schema to use the default format." - ) diff --git a/tests/test_blob.py b/tests/test_blob.py index c6af219d..58f57933 100755 --- a/tests/test_blob.py +++ b/tests/test_blob.py @@ -3,8 +3,8 @@ This test ensures that pa.large_binary fields with metadata {"lance-encoding:blob": "true"} are written and read back with byte-for-byte fidelity using write_lance and read_lance. -The tests cover explicit file-format selection for legacy Blob fields and -PyLance's default format for native Blob v2 fields. +The tests cover PyLance's default file format and explicit format selection +for legacy Blob and native Blob v2 fields. Tests cover: - Single blob column round-trip @@ -75,25 +75,35 @@ def _generate_jpg_bytes() -> bytes: @pytest.mark.parametrize("stream", [False, True]) -@pytest.mark.parametrize("provide_schema", [False, True]) -def test_legacy_blob_requires_explicit_version( - tmp_path: Path, stream: bool, provide_schema: bool +@pytest.mark.parametrize("create_version", [None, "2.1"], ids=["default", "v2.1"]) +def test_legacy_blob_uses_default_version( + tmp_path: Path, stream: bool, create_version: str | None ) -> None: - path = tmp_path / "legacy_blob_default_version.lance" + path = str(tmp_path / "legacy_blob_default_version.lance") schema = pa.schema( [pa.field("blob", pa.large_binary(), metadata={"lance-encoding:blob": "true"})] ) - table = pa.table({"blob": [b"foo", None]}, schema=schema) + data = ray.data.from_arrow(pa.table({"blob": [b"foo", None]}, schema=schema)) - with pytest.raises(ValueError, match="data_storage_version"): - lr.write_lance( - ray.data.from_arrow(table), - str(path), - schema=schema if provide_schema else None, - stream=stream, - ) + lr.write_lance(data, path, stream=stream, data_storage_version=create_version) + lr.write_lance(data, path, mode="append", stream=stream) - assert not path.exists() + dataset = lance.dataset(path) + expected_version = create_version or "2.2" + assert dataset.data_storage_version == expected_version + file_versions = { + f"{file.file_major_version}.{file.file_minor_version}" + for fragment in dataset.get_fragments() + for file in fragment.data_files() + } + assert file_versions == {expected_version} + blobs = dataset.take_blobs("blob", indices=[0, 1, 2, 3]) + assert [blob.read() if blob is not None else None for blob in blobs] == [ + b"foo", + None, + b"foo", + None, + ] @pytest.mark.parametrize("stream", [False, True]) @@ -131,6 +141,87 @@ def test_write_blob_v2(tmp_path: Path, stream: bool, legacy_input: bool) -> None assert [blob.read() if blob is not None else None for blob in blobs] == values +def test_append_legacy_blob_to_blob_v2(tmp_path: Path) -> None: + path = str(tmp_path / "blob_v2.lance") + lance.write_dataset( + pa.table( + {"id": pa.array([1], type=pa.int32()), "blob": lance.blob_array([b"first"])} + ), + path, + ) + legacy_fields: list[pa.Field[Any]] = [ + pa.field("id", pa.int64()), + pa.field("blob", pa.large_binary(), metadata={b"lance-encoding:blob": b"true"}), + ] + data = pa.table({"id": [2], "blob": [b"second"]}, schema=pa.schema(legacy_fields)) + + lr.write_lance(ray.data.from_arrow([pa.table({}), data]), path, mode="append") + + dataset = lance.dataset(path) + ids = dataset.to_table(columns=["id"]).column("id") + assert ids.type == pa.int32() + assert ids.to_pylist() == [1, 2] + blobs = dataset.take_blobs("blob", indices=[0, 1]) + assert [blob.read() if blob is not None else None for blob in blobs] == [ + b"first", + b"second", + ] + + +@pytest.mark.parametrize("container", ["struct", "list", "large_list"]) +def test_append_nested_legacy_blob_to_blob_v2(tmp_path: Path, container: str) -> None: + def table(values: pa.StructArray) -> pa.Table: + if container == "list": + return pa.table( + {"payload": pa.ListArray.from_arrays([0, len(values)], values)} + ) + if container == "large_list": + return pa.table( + { + "payload": pa.LargeListArray.from_arrays( + pa.array([0, len(values)], type=pa.int64()), values + ) + } + ) + return pa.table({"payload": values}) + + path = str(tmp_path / "nested_blob_v2.lance") + native = pa.StructArray.from_arrays( + [pa.array([1], type=pa.int32()), lance.blob_array([b"first"])], + fields=[pa.field("id", pa.int32()), lance.blob_field("blob")], + ) + legacy = pa.StructArray.from_arrays( + [ + pa.array([2, 3], type=pa.int64()), + pa.array([b"second", None], type=pa.large_binary()), + ], + fields=[ + pa.field("id", pa.int64()), + pa.field( + "blob", pa.large_binary(), metadata={b"lance-encoding:blob": b"true"} + ), + ], + ) + + lance.write_dataset(table(native), path, data_storage_version="2.2") + lr.write_lance(ray.data.from_arrow(table(legacy)), path, mode="append") + + payload = ( + lance.dataset(path) + .scanner(blob_handling="all_binary") + .to_table() + .column("payload") + .combine_chunks() + ) + if isinstance(payload, pa.ListArray | pa.LargeListArray): + assert payload.offsets.to_pylist() == [0, 1, 3] + payload = payload.values + assert isinstance(payload, pa.StructArray) + assert payload.field("id").type == pa.int32() + assert payload.field("id").to_pylist() == [1, 2, 3] + assert payload.field("blob").to_pylist() == [b"first", b"second", None] + + def test_single_blob_roundtrip(temp_dir: str) -> None: """Test single blob column round-trip.""" path = Path(temp_dir) / "single_blob_roundtrip.lance" diff --git a/tests/test_fragment.py b/tests/test_fragment.py index cafc0cbb..d4e6fb3d 100644 --- a/tests/test_fragment.py +++ b/tests/test_fragment.py @@ -584,6 +584,50 @@ def write( source.close() +@pytest.mark.parametrize("caller_owns_iterator", [False, True]) +def test_datasink_single_attempt_append_preserves_iterator_ownership( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caller_owns_iterator: bool +) -> None: + path = str(tmp_path / "append.lance") + lance.write_dataset(pa.table({"blob": lance.blob_array([b"existing"])}), path) + legacy_schema = pa.schema( + [ + pa.field( + "blob", pa.large_binary(), metadata={b"lance-encoding:blob": b"true"} + ) + ] + ) + first = pa.table({"blob": [b"first"]}, schema=legacy_schema) + second = pa.table({"blob": [b"second"]}, schema=legacy_schema) + replayable = ReplayableBlocks([pa.table({}), first, second]) + block_iter = iter(replayable) + + class Blocks: + def __iter__(self) -> Iterator[pa.Table]: + return block_iter + + def write( + stream: FragmentStream | FragmentStreamFactory, _uri: str, **kwargs: Any + ) -> list[tuple[FragmentMetadata, pa.Schema]]: + assert not callable(stream) + assert next(iter(stream)) is first + assert kwargs["schema"].equals(legacy_schema, check_metadata=True) + raise RuntimeError("injected write error") + + monkeypatch.setattr("lance_ray.datasink.write_fragment", write) + sink = LanceDatasink(path, mode="append") + sink._retry_params["max_attempts"] = 1 + sink.on_write_start() + + with pytest.raises(RuntimeError, match="injected write error"): + sink.write(block_iter if caller_owns_iterator else Blocks(), None) + + if caller_owns_iterator: + assert replayable.closed == 0 + assert list(block_iter) == [second] + assert replayable.closed == 1 + + @pytest.mark.parametrize("output_kind", ["table", "list", "generator"]) @pytest.mark.usefixtures("no_replay_staging") def test_fragment_writer_repeats_transform(