Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/src/write.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Write a Ray Dataset to Lance format.
- `namespace`: LanceNamespace instance for metadata catalog integration (requires table_id)
- `table_id`: Table identifier as list of strings (requires namespace)
- `schema`: Optional PyArrow schema
- `mode`: Write mode - "create", "append", or "overwrite"
- `mode`: Write mode - "create" (default), "append", or "overwrite". "create" and "overwrite" use the schema of the incoming data, so an overwrite can add, drop or retype columns; "append" keeps the existing dataset schema
- `target_bases`: Optional list of registered base names or base path URIs where new data files should be written. In `create` mode, entries must match `initial_bases`; in `append` and `overwrite` modes, entries must match bases already registered in the dataset manifest
- `target_all_bases`: Select all registered bases, including primary storage when `True` and excluding it when `False`. `False` requires at least one registered base. `None` (default) leaves base selection unchanged. Mutually exclusive with non-empty `target_bases`
- `min_rows_per_file`: Minimum rows per file (default: 1024 * 1024)
Expand Down
52 changes: 49 additions & 3 deletions lance_ray/datasink.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,30 @@
WriteReturn = list[tuple[bytes, bytes]]


def _merge_block_schemas(committed: pa.Schema, block: pa.Schema) -> Optional[pa.Schema]:
"""Merge two block schemas field by field, or return None if they conflict.

Names must match in order. Types must be equal, except that a ``null``
column (a block where the column is all null) takes the other block's type.
A field is nullable if it is nullable in either block. Metadata comes from
``block``.
"""
if committed.names != block.names:
return None
fields = []
for committed_field, block_field in zip(committed, block, strict=True):
nullable = committed_field.nullable or block_field.nullable
if block_field.type == committed_field.type or pa.types.is_null(
committed_field.type
):
fields.append(block_field.with_nullable(nullable))
elif pa.types.is_null(block_field.type):
fields.append(committed_field.with_nullable(nullable))
else:
return None
return pa.schema(fields).with_metadata(block.metadata or {})


def _declare_table_with_fallback(
namespace: "LanceNamespace", table_id: list[str]
) -> tuple[Optional[str], Optional[dict[str, str]]]:
Expand Down Expand Up @@ -225,7 +249,26 @@ def on_write_complete(
for fragment_str, schema_str in batch:
fragment = pickle.loads(fragment_str)
fragments.append(fragment)
schema = pickle.loads(schema_str)
frag_schema = pickle.loads(schema_str)
# In create/overwrite mode every write task assigns field ids
# from its own block's schema, but all fragments are committed
# under one schema. Blocks whose columns differ in order or type
# (e.g. a union of different sources) would commit a version
# that cannot be read back, so fail before committing. A column
# that is all null in some blocks takes the other blocks' type.
# An explicit ``schema`` casts every block to the same fields.
if schema is not None and self.mode in {"create", "overwrite"}:
merged = _merge_block_schemas(schema, frag_schema)
if merged is None:
raise ValueError(
"Distributed create/overwrite received blocks with "
"different columns or column types "
f"({schema.remove_metadata()} vs "
f"{frag_schema.remove_metadata()}). Pass an explicit "
"`schema=` so every block is written with the same fields."
)
frag_schema = merged
schema = frag_schema
# Check weather writer has fragments or not.
# Skip commit when there are no fragments.
if not schema:
Expand Down Expand Up @@ -274,8 +317,10 @@ class LanceDatasink(_BaseLanceDatasink):
schema : pyarrow.Schema, optional.
The schema of the dataset.
mode : str, optional
The write mode. Default is 'append'.
Choices are 'append', 'create', 'overwrite'.
The write mode. Default is 'create'.
Choices are 'create', 'append', 'overwrite'. "create" and "overwrite"
use the schema of the incoming data; "append" keeps the existing
dataset schema.
min_rows_per_file : int, optional
The minimum number of rows per file. Default is 1024 * 1024.
max_rows_per_file : int, optional
Expand Down Expand Up @@ -429,6 +474,7 @@ def stream_factory() -> Iterator[Union[pa.Table, "pd.DataFrame"]]:
stream,
self.dataset_uri,
schema=self.schema,
mode=self.mode,
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,
Expand Down
28 changes: 28 additions & 0 deletions lance_ray/fragment.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def write_fragment(
uri: str,
*,
schema: Optional[pa.Schema] = None,
mode: Literal["create", "append", "overwrite"] = "append",
max_rows_per_file: int = 64 * 1024 * 1024,
max_bytes_per_file: Optional[int] = None,
# Only useful for v1 writer. ``None`` defers to the pylance writer default.
Expand Down Expand Up @@ -82,6 +83,13 @@ def write_fragment(
exit; caller-supplied one-shot iterators remain the caller's responsibility.
No input is staged or serialized for replay. Row-count validation does not
check content equivalence or clean up files from failed attempts.

``mode`` is the fragment write mode passed to pylance. "append" validates
fragments against the existing dataset schema (rejecting columns not
present in it); "create" and "overwrite" assign new field ids for the
incoming schema (schema evolution). The high-level ``write_lance``
defaults to "create", while this helper defaults to "append" to keep
append validation for direct callers.
"""
from lance.dependencies import _PANDAS_AVAILABLE
from lance.dependencies import pandas as pd
Expand Down Expand Up @@ -136,6 +144,7 @@ def _write_fragments(
uri,
return_transaction=False,
schema=attempt_schema,
mode=mode,
max_rows_per_file=max_rows_per_file,
max_rows_per_group=max_rows_per_group,
max_bytes_per_file=max_bytes_per_file,
Expand Down Expand Up @@ -368,6 +377,13 @@ class LanceFragmentWriter:
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) will use the 2.0 version. See the user guide for more details.
mode : {"create", "append", "overwrite"}, default "append"
Fragment write mode passed to pylance. "append" validates fragments
against the existing dataset schema (rejecting columns not present in
it); "create" and "overwrite" assign new field ids for the incoming schema
(schema evolution). Note the high-level ``write_lance`` defaults to
"create"; this writer defaults to "append" to preserve append-validation
semantics for direct callers.
enable_stable_row_ids : bool, default False
Enable stable row IDs for fragments written into a stable-row-ID dataset.
use_legacy_format : optional, bool, default None
Expand Down Expand Up @@ -411,6 +427,15 @@ class LanceFragmentWriter:
Arrow table, without IPC staging. The transform may execute more than
once and must return complete, logically equivalent output each time.

Notes
-----
When pairing this writer with :class:`LanceFragmentCommitter`, pass the
SAME ``mode`` to both: this writer assigns field ids (so "create"/
"overwrite" enable schema evolution), while the committer selects the
commit operation (append vs overwrite). Using the default ``mode="append"``
writer with a ``mode="overwrite"`` committer on an evolved schema raises a
schema-mismatch error rather than evolving the schema.

"""

def __init__(
Expand All @@ -423,6 +448,7 @@ def __init__(
max_bytes_per_file: Optional[int] = None,
max_rows_per_group: Optional[int] = None, # Only useful for v1 writer.
data_storage_version: Optional[str] = None,
mode: Literal["create", "append", "overwrite"] = "append",
enable_stable_row_ids: bool = False,
use_legacy_format: Optional[bool] = False,
storage_options: Optional[dict[str, Any]] = None,
Expand Down Expand Up @@ -464,6 +490,7 @@ def __init__(
self.max_rows_per_file = max_rows_per_file
self.max_bytes_per_file = max_bytes_per_file
self.data_storage_version = data_storage_version
self.mode = mode
self.enable_stable_row_ids = enable_stable_row_ids
self.storage_options = storage_options
self.base_store_params = base_store_params
Expand Down Expand Up @@ -514,6 +541,7 @@ def stream_factory() -> Iterator[pa.Table]:
stream_factory,
self.uri,
schema=self.schema,
mode=self.mode,
max_rows_per_file=self.max_rows_per_file,
max_rows_per_group=self.max_rows_per_group,
max_bytes_per_file=self.max_bytes_per_file,
Expand Down
15 changes: 13 additions & 2 deletions lance_ray/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,14 @@ 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.
mode: The write mode. Can be "create", "append", or "overwrite".
schema: The schema of the dataset. If not provided, it is inferred from the
data. For create/overwrite, provide it when input blocks may differ
in column order or types (e.g. a union of different sources);
otherwise the write raises before committing.
mode: The write mode (default "create"). Can be "create", "append", or
"overwrite". "create" and "overwrite" use the schema of the incoming
data, so an overwrite can add, drop or retype columns. "append" keeps
the existing dataset schema.
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
Expand Down Expand Up @@ -381,13 +387,18 @@ def write_lance(
fragment_initial_bases = (
initial_bases if mode == "create" and not first_commit_done else None
)
# Only the first committed batch carries the requested mode so that
# create/overwrite assign new field ids for the incoming schema. Every
# later batch appends to the dataset just created/overwritten above.
fragment_mode = "append" if first_commit_done else mode
writer = LanceFragmentWriter(
uri=dest_uri,
schema=schema, # if None, writer infers from first batch (preserves Arrow metadata)
max_rows_per_file=max_rows_per_file,
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,
mode=fragment_mode,
enable_stable_row_ids=enable_stable_row_ids,
storage_options=storage_options,
base_store_params=base_store_params,
Expand Down
6 changes: 6 additions & 0 deletions lance_ray/pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ def pd_to_arrow(
new_table = tbl.replace_schema_metadata(new_schema.metadata)
return new_table
elif isinstance(df, pa.Table) and df.num_rows > 0 and schema is not None:
# ``cast`` matches fields by position, so put the same columns in the
# schema's order first. Other name mismatches still fail in ``cast``.
if df.schema.names != schema.names and sorted(df.schema.names) == sorted(
schema.names
):
df = df.select(schema.names)
return df.cast(schema)
# Only a ``pa.Table`` can reach here: a ``pd.DataFrame`` argument implies
# pandas is importable, so the ``_PANDAS_AVAILABLE`` branch above handles it.
Expand Down
Loading
Loading