Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions docs/src/write.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,20 +43,18 @@ 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. Appends that omit the version use the destination's default.

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")
```

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`.

## Write retries

`write_lance` uses `LanceDatasink`, which allows up to ten fragment write attempts
Expand Down
151 changes: 118 additions & 33 deletions lance_ray/datasink.py
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -15,6 +17,7 @@
from ray.data.datasource.datasink import Datasink, WriteResult

from .fragment import (
FragmentBlock,
FragmentStream,
FragmentStreamFactory,
prepare_fragment_write_options,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
40 changes: 7 additions & 33 deletions lance_ray/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,16 +215,19 @@ 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.
max_bytes_per_file: The maximum number of bytes per file. This is a soft
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"). 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.
Expand Down Expand Up @@ -268,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:
Expand Down Expand Up @@ -388,6 +384,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,
Expand Down Expand Up @@ -1224,26 +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
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))
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."
)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
10 changes: 5 additions & 5 deletions tests/test_basic_read_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -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), (
Expand Down Expand Up @@ -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), (
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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), (
Expand Down Expand Up @@ -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
Loading
Loading