mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
refactor(sdk)!: flatten Optimize options across bindings
BREAKING CHANGE: Pass Optimize settings as Python keyword arguments or one flat TypeScript OptimizeOptions object. Remove data_options/dataOptions wrappers and OptimizeDataOptions, accept Rust OptimizeOptions directly, retain OptimizeOverrides for field presence, and rename index-maintenance options to IndexOptimizeOptions.
This commit is contained in:
@@ -78,7 +78,7 @@ from .materialized_view import (
|
||||
)
|
||||
from .view import ViewDescription as ViewDescription
|
||||
from .graph import PropertyGraph, PropertyGraphDescription
|
||||
from .table import AsyncTable, OptimizeDataOptions, Table
|
||||
from .table import AsyncTable, OptimizeOptions, Table
|
||||
from .types import BaseTokenizerType
|
||||
from ._lancedb import Session
|
||||
from .namespace import (
|
||||
@@ -676,7 +676,7 @@ __all__ = [
|
||||
"AsyncSqlQuery",
|
||||
"AsyncLanceNamespaceDBConnection",
|
||||
"AsyncTable",
|
||||
"OptimizeDataOptions",
|
||||
"OptimizeOptions",
|
||||
"FtsToken",
|
||||
"FunctionColumnAutoRefreshStatus",
|
||||
"FunctionColumnLastRefreshJob",
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing_extensions import Unpack
|
||||
|
||||
from collections.abc import Mapping
|
||||
from datetime import timedelta
|
||||
import deprecation
|
||||
@@ -65,7 +67,11 @@ from lancedb.common import DATA, VEC, VECTOR_COLUMN_NAME
|
||||
from lancedb._blob import validate_blob_mode
|
||||
from lancedb.merge import LanceMergeInsertBuilder
|
||||
from lancedb.embeddings import EmbeddingFunctionRegistry
|
||||
from lancedb.table import _normalize_progress
|
||||
from lancedb.table import (
|
||||
_normalize_progress,
|
||||
_split_optimize_options,
|
||||
_optimize_cleanup_since_ms,
|
||||
)
|
||||
|
||||
from ..query import (
|
||||
FullTextOperator,
|
||||
@@ -79,7 +85,7 @@ from ..table import (
|
||||
AsyncTable,
|
||||
BlobMode,
|
||||
Branches,
|
||||
OptimizeDataOptions,
|
||||
OptimizeOptions,
|
||||
OptimizeResult,
|
||||
IndexStatistics,
|
||||
Query,
|
||||
@@ -1100,20 +1106,10 @@ class RemoteTable(Table):
|
||||
)
|
||||
pass
|
||||
|
||||
def optimize_async(
|
||||
self, *, data_options: Optional[OptimizeDataOptions] = None
|
||||
) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(data_options=data_options)))
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
cleanup_older_than: Optional[timedelta] = None,
|
||||
delete_unverified: bool = False,
|
||||
retrain: bool = False,
|
||||
data_options: Optional[OptimizeDataOptions] = None,
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
"""Compact the table's data files via a durable, asynchronous
|
||||
Enterprise job. Pruning old versions and index optimization are not
|
||||
yet supported remotely, so this call skips them and returns
|
||||
@@ -1126,13 +1122,15 @@ class RemoteTable(Table):
|
||||
before submission. Errors from older servers are propagated without
|
||||
retrying with the settings removed.
|
||||
"""
|
||||
tuning, cleanup, delete_unverified, retrain, action = _split_optimize_options(
|
||||
options
|
||||
)
|
||||
return LOOP.run(
|
||||
self._table.optimize(
|
||||
cleanup_older_than=cleanup_older_than,
|
||||
delete_unverified=delete_unverified,
|
||||
retrain=retrain,
|
||||
data_options=data_options,
|
||||
action=action,
|
||||
self._table._do_optimize(
|
||||
_optimize_cleanup_since_ms(cleanup, retrain),
|
||||
delete_unverified,
|
||||
tuning,
|
||||
action,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ from typing import (
|
||||
overload,
|
||||
)
|
||||
from urllib.parse import urlparse
|
||||
from typing_extensions import Unpack
|
||||
|
||||
from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable
|
||||
|
||||
@@ -349,9 +350,11 @@ IndexConfigType = Union[
|
||||
]
|
||||
|
||||
|
||||
class OptimizeDataOptions(TypedDict, total=False):
|
||||
"""Options that control file compaction during table optimization.
|
||||
class OptimizeOptions(TypedDict, total=False):
|
||||
"""Flat settings for optimize() and optimize_async(), passed as keywords.
|
||||
|
||||
Cleanup controls apply to Embedded convenience Optimize. Durable jobs
|
||||
reject cleanup and separate index-maintenance requests before submission.
|
||||
Unspecified options use Lance's defaults for local tables. Remote tables
|
||||
forward ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``,
|
||||
and ``batch_size`` as per-job SQL options; other non-default settings are
|
||||
@@ -373,12 +376,12 @@ class OptimizeDataOptions(TypedDict, total=False):
|
||||
|
||||
>>> desired_fragment_bytes = 750 * 1024 * 1024
|
||||
>>> average_row_bytes = 1_500_000
|
||||
>>> options: OptimizeDataOptions = {
|
||||
>>> options: OptimizeOptions = {
|
||||
... "target_rows_per_fragment": max(
|
||||
... 1, desired_fragment_bytes // average_row_bytes
|
||||
... ),
|
||||
... }
|
||||
>>> await table.optimize(data_options=options) # doctest: +SKIP
|
||||
>>> await table.optimize(**options) # doctest: +SKIP
|
||||
"""
|
||||
|
||||
target_rows_per_fragment: int
|
||||
@@ -440,6 +443,51 @@ class OptimizeDataOptions(TypedDict, total=False):
|
||||
data_storage_version: str
|
||||
"""Data-file version or release selector for compacted output."""
|
||||
|
||||
cleanup_older_than: Optional[timedelta]
|
||||
"""Embedded version-retention age; unsupported by remote Optimize jobs."""
|
||||
|
||||
delete_unverified: bool
|
||||
"""Allow Embedded cleanup of unverified files; default False."""
|
||||
|
||||
retrain: bool
|
||||
"""Deprecated convenience argument; unsupported by durable Optimize jobs."""
|
||||
|
||||
action: Optional[Literal["rewrite_data"]]
|
||||
"""Select only data rewriting; omit for Embedded's full maintenance cycle."""
|
||||
|
||||
|
||||
def _split_optimize_options(
|
||||
options: OptimizeOptions, *, durable: bool = False
|
||||
) -> Tuple[
|
||||
Optional[Dict[str, Any]],
|
||||
Optional[timedelta],
|
||||
bool,
|
||||
bool,
|
||||
Optional[Literal["rewrite_data"]],
|
||||
]:
|
||||
"""Validate the public flat request and extract maintenance controls."""
|
||||
unknown = set(options) - OptimizeOptions.__annotations__.keys()
|
||||
if unknown:
|
||||
raise TypeError(f"Unsupported Optimize option: {sorted(unknown)[0]}")
|
||||
tuning: Dict[str, Any] = dict(options)
|
||||
cleanup_older_than = tuning.pop("cleanup_older_than", None)
|
||||
delete_unverified = tuning.pop("delete_unverified", False)
|
||||
retrain = tuning.pop("retrain", False)
|
||||
action = tuning.pop("action", None)
|
||||
if action not in (None, "rewrite_data"):
|
||||
raise ValueError("action must be 'rewrite_data' or None")
|
||||
if durable and (cleanup_older_than is not None or delete_unverified or retrain):
|
||||
raise ValueError(
|
||||
"cleanup and index-maintenance options are unsupported by Optimize jobs"
|
||||
)
|
||||
if action == "rewrite_data" and (
|
||||
cleanup_older_than is not None or delete_unverified
|
||||
):
|
||||
raise ValueError(
|
||||
"action='rewrite_data' cannot be combined with cleanup options"
|
||||
)
|
||||
return tuning or None, cleanup_older_than, delete_unverified, retrain, action
|
||||
|
||||
|
||||
# Known distance metrics for legacy API detection
|
||||
KNOWN_METRICS = {"l2", "cosine", "dot", "hamming"}
|
||||
@@ -3114,14 +3162,12 @@ class Table(ABC):
|
||||
cleanup for you automatically.
|
||||
"""
|
||||
|
||||
def optimize_async(
|
||||
self, *, data_options: Optional[OptimizeDataOptions] = None
|
||||
) -> Job[OptimizeResult]:
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
"""Submit remote compaction and return a durable job after acceptance.
|
||||
|
||||
Uses SQL OPTIMIZE with the table handle's branch and namespace. Supports
|
||||
the four per-job settings in
|
||||
[OptimizeDataOptions][lancedb.table.OptimizeDataOptions].
|
||||
[OptimizeOptions][lancedb.table.OptimizeOptions].
|
||||
Requires a compatible remote server, table Ownership and parent Usage.
|
||||
Local and historical-version handles are unsupported. Existing
|
||||
``optimize()`` retains its return-on-submission behavior remotely.
|
||||
@@ -3135,22 +3181,14 @@ class Table(ABC):
|
||||
cancellation use generic HTTP job APIs and their existing permissions.
|
||||
|
||||
>>> job = table.optimize_async( # doctest: +SKIP
|
||||
... data_options={"target_rows_per_fragment": 1000})
|
||||
... target_rows_per_fragment=1000)
|
||||
>>> result = job.wait() # doctest: +SKIP
|
||||
>>> print(result.rows_succeeded) # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError("compaction jobs are only supported on remote tables")
|
||||
|
||||
@abstractmethod
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
cleanup_older_than: Optional[timedelta] = None,
|
||||
delete_unverified: bool = False,
|
||||
retrain: bool = False,
|
||||
data_options: Optional[OptimizeDataOptions] = None,
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
|
||||
@@ -3209,11 +3247,12 @@ class Table(ABC):
|
||||
separate index maintenance phase. Omit for Embedded's full cycle.
|
||||
Cannot be combined with cleanup options. Enterprise always submits
|
||||
compaction only; use optimize_async() to retain its durable job.
|
||||
data_options: OptimizeDataOptions, optional
|
||||
Options that control file compaction. For large rows, derive a lower
|
||||
**options: Unpack[OptimizeOptions]
|
||||
Flat Optimize settings, passed directly as keywords.
|
||||
For large rows, derive a lower
|
||||
``target_rows_per_fragment`` from the expected row size to bound later
|
||||
passes. This does not cap the first pass over an existing oversized
|
||||
fragment; see [OptimizeDataOptions][lancedb.table.OptimizeDataOptions].
|
||||
fragment; see [OptimizeOptions][lancedb.table.OptimizeOptions].
|
||||
|
||||
Notes
|
||||
-----
|
||||
@@ -5848,20 +5887,10 @@ class LanceTable(Table):
|
||||
older_than, delete_unverified=delete_unverified
|
||||
)
|
||||
|
||||
def optimize_async(
|
||||
self, *, data_options: Optional[OptimizeDataOptions] = None
|
||||
) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(data_options=data_options)))
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
cleanup_older_than: Optional[timedelta] = None,
|
||||
delete_unverified: bool = False,
|
||||
retrain: bool = False,
|
||||
data_options: Optional[OptimizeDataOptions] = None,
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
|
||||
@@ -5905,11 +5934,12 @@ class LanceTable(Table):
|
||||
separate index maintenance phase. Omit for Embedded's full cycle.
|
||||
Cannot be combined with cleanup options. Enterprise always submits
|
||||
compaction only; use optimize_async() to retain its durable job.
|
||||
data_options: OptimizeDataOptions, optional
|
||||
Options that control file compaction. For large rows, derive a lower
|
||||
**options: Unpack[OptimizeOptions]
|
||||
Flat Optimize settings, passed directly as keywords.
|
||||
For large rows, derive a lower
|
||||
``target_rows_per_fragment`` from the expected row size to bound later
|
||||
passes. This does not cap the first pass over an existing oversized
|
||||
fragment; see [OptimizeDataOptions][lancedb.table.OptimizeDataOptions].
|
||||
fragment; see [OptimizeOptions][lancedb.table.OptimizeOptions].
|
||||
|
||||
Notes
|
||||
-----
|
||||
@@ -5919,11 +5949,14 @@ class LanceTable(Table):
|
||||
you have added or modified 100,000 or more records or run more than 20 data
|
||||
modification operations.
|
||||
"""
|
||||
tuning, cleanup, delete_unverified, retrain, action = _split_optimize_options(
|
||||
options
|
||||
)
|
||||
return LOOP.run(
|
||||
self._table._do_optimize(
|
||||
_optimize_cleanup_since_ms(cleanup_older_than, retrain),
|
||||
_optimize_cleanup_since_ms(cleanup, retrain),
|
||||
delete_unverified,
|
||||
data_options,
|
||||
tuning,
|
||||
action,
|
||||
)
|
||||
)
|
||||
@@ -9544,27 +9577,20 @@ class AsyncTable:
|
||||
return self._inner.current_branch()
|
||||
|
||||
async def optimize_async(
|
||||
self, *, data_options: Optional[OptimizeDataOptions] = None
|
||||
self, **options: Unpack[OptimizeOptions]
|
||||
) -> AsyncJob[OptimizeResult]:
|
||||
"""Submit remote compaction; await the returned job for actual results.
|
||||
|
||||
See [Table.optimize_async][lancedb.table.Table.optimize_async] for options,
|
||||
permissions, completion semantics and compatibility requirements.
|
||||
"""
|
||||
data_options, _, _, _, _ = _split_optimize_options(options, durable=True)
|
||||
return _typed_job(
|
||||
await self._inner.optimize_async(data_options),
|
||||
OptimizeResult.from_json,
|
||||
)
|
||||
|
||||
async def optimize(
|
||||
self,
|
||||
*,
|
||||
cleanup_older_than: Optional[timedelta] = None,
|
||||
delete_unverified: bool = False,
|
||||
retrain=False,
|
||||
data_options: Optional[OptimizeDataOptions] = None,
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
async def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
|
||||
@@ -9623,11 +9649,12 @@ class AsyncTable:
|
||||
separate index maintenance phase. Omit for Embedded's full cycle.
|
||||
Cannot be combined with cleanup options. Enterprise always submits
|
||||
compaction only; use optimize_async() to retain its durable job.
|
||||
data_options: OptimizeDataOptions, optional
|
||||
Options that control file compaction. For large rows, derive a lower
|
||||
**options: Unpack[OptimizeOptions]
|
||||
Flat Optimize settings, passed directly as keywords.
|
||||
For large rows, derive a lower
|
||||
``target_rows_per_fragment`` from the expected row size to bound later
|
||||
passes. This does not cap the first pass over an existing oversized
|
||||
fragment; see [OptimizeDataOptions][lancedb.table.OptimizeDataOptions].
|
||||
fragment; see [OptimizeOptions][lancedb.table.OptimizeOptions].
|
||||
|
||||
Notes
|
||||
-----
|
||||
@@ -9637,6 +9664,9 @@ class AsyncTable:
|
||||
you have added or modified 100,000 or more records or run more than 20 data
|
||||
modification operations.
|
||||
"""
|
||||
data_options, cleanup_older_than, delete_unverified, retrain, action = (
|
||||
_split_optimize_options(options)
|
||||
)
|
||||
return await self._do_optimize(
|
||||
_optimize_cleanup_since_ms(cleanup_older_than, retrain),
|
||||
delete_unverified,
|
||||
@@ -9648,7 +9678,7 @@ class AsyncTable:
|
||||
self,
|
||||
cleanup_since_ms: Optional[int],
|
||||
delete_unverified: bool,
|
||||
data_options: Optional[OptimizeDataOptions] = None,
|
||||
data_options: Optional[Dict[str, Any]] = None,
|
||||
action: Optional[Literal["rewrite_data"]] = None,
|
||||
) -> OptimizeStats:
|
||||
return await self._inner.optimize(
|
||||
|
||||
@@ -71,11 +71,9 @@ async def test_maintenance_job_result_and_reopen_against_server(
|
||||
if operation == "compact":
|
||||
job = await call(
|
||||
table.optimize_async,
|
||||
data_options={
|
||||
"target_rows_per_fragment": 100,
|
||||
"batch_size": 128,
|
||||
"io_buffer_size": 0,
|
||||
},
|
||||
target_rows_per_fragment=100,
|
||||
batch_size=128,
|
||||
io_buffer_size=0,
|
||||
)
|
||||
elif operation == "prewarm_legacy":
|
||||
assert (
|
||||
|
||||
@@ -7593,10 +7593,10 @@ async def test_remote_optimize_forwards_per_job_data_options(
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
stats = await table.optimize(data_options=options)
|
||||
stats = await table.optimize(**options)
|
||||
else:
|
||||
table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
|
||||
stats = table.optimize(data_options=options)
|
||||
stats = table.optimize(**options)
|
||||
assert len(server.tickets) == 1
|
||||
assert b"OPTIMIZE" in server.tickets[0]
|
||||
assert all(option in server.tickets[0] for option in sql_options)
|
||||
@@ -7620,7 +7620,7 @@ def test_remote_optimize_does_not_drop_options_after_server_rejection():
|
||||
server = OldServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(Exception, match="max_source_rows"):
|
||||
table.optimize(data_options={"max_source_rows": 500})
|
||||
table.optimize(max_source_rows=500)
|
||||
assert server.tickets
|
||||
assert all(b"max_source_rows = 500" in ticket for ticket in server.tickets)
|
||||
|
||||
@@ -7666,7 +7666,7 @@ def test_remote_optimize_rejects_unsupported_data_options_before_submitting():
|
||||
non-default value was silently ignored -- the server-side guard against
|
||||
unsupported options never saw it. It should now reach that guard and
|
||||
raise before any SQL statement is submitted."""
|
||||
from lancedb.table import OptimizeDataOptions
|
||||
from lancedb.table import OptimizeOptions
|
||||
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
@@ -7682,10 +7682,10 @@ def test_remote_optimize_rejects_unsupported_data_options_before_submitting():
|
||||
)
|
||||
|
||||
server = UnreachableServer()
|
||||
options: OptimizeDataOptions = {"max_source_bytes": 1024}
|
||||
options: OptimizeOptions = {"max_source_bytes": 1024}
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(NotImplementedError, match="OptimizeDataOptions"):
|
||||
table.optimize(data_options=options)
|
||||
with pytest.raises(NotImplementedError, match="OptimizeOptions"):
|
||||
table.optimize(**options)
|
||||
|
||||
assert server.tickets == []
|
||||
|
||||
@@ -8471,9 +8471,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
job = await table.optimize_async(
|
||||
data_options={"target_rows_per_fragment": 100}
|
||||
)
|
||||
job = await table.optimize_async(target_rows_per_fragment=100)
|
||||
assert job.id == "compacting-job" and not polls
|
||||
if outcome in ("missing", "FAILED", "CANCELLED"):
|
||||
with pytest.raises(
|
||||
@@ -8492,7 +8490,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome):
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
job = table.optimize_async(data_options={"target_rows_per_fragment": 100})
|
||||
job = table.optimize_async(target_rows_per_fragment=100)
|
||||
assert job.id == "compacting-job" and not polls
|
||||
if outcome in ("missing", "FAILED", "CANCELLED"):
|
||||
with pytest.raises(
|
||||
@@ -8572,7 +8570,7 @@ def test_remote_compaction_rejects_boolean_budgets_without_submitting(
|
||||
server = UnusedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(ValueError, match="must be an integer, not a bool"):
|
||||
getattr(table, method)(data_options={option: value})
|
||||
getattr(table, method)(**{option: value})
|
||||
assert server.calls == 0
|
||||
|
||||
|
||||
@@ -8696,3 +8694,51 @@ def test_remote_prewarm_preview_reports_old_server_format_support():
|
||||
):
|
||||
table.explain_prewarm_data()
|
||||
assert len(server.tickets) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["optimize", "optimize_async"])
|
||||
@pytest.mark.parametrize("key", ["data_options", "compaction_options"])
|
||||
def test_remote_optimize_rejects_wrapped_options_before_submission(method, key):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class UnusedServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.calls = 0
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.calls += 1
|
||||
raise AssertionError("wrapped settings must not submit SQL")
|
||||
|
||||
server = UnusedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(TypeError, match="Unsupported Optimize option"):
|
||||
getattr(table, method)(**{key: {"max_source_rows": 1}})
|
||||
assert server.calls == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"cleanup_older_than": timedelta(days=1)},
|
||||
{"delete_unverified": True},
|
||||
{"retrain": True},
|
||||
],
|
||||
)
|
||||
def test_remote_optimize_job_rejects_maintenance_options_before_submission(options):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class UnusedServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.calls = 0
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.calls += 1
|
||||
raise AssertionError("unsupported maintenance must not submit SQL")
|
||||
|
||||
server = UnusedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(ValueError, match="unsupported by Optimize jobs"):
|
||||
table.optimize_async(**options)
|
||||
assert server.calls == 0
|
||||
|
||||
@@ -5457,27 +5457,23 @@ async def test_optimize_data_options(mem_db_async: AsyncConnection):
|
||||
await table.add([{"x": 2}])
|
||||
|
||||
stats = await table.optimize(
|
||||
data_options={
|
||||
"target_rows_per_fragment": 1,
|
||||
"batch_size": 1,
|
||||
"num_threads": 1,
|
||||
}
|
||||
target_rows_per_fragment=1, batch_size=1, num_threads=1
|
||||
)
|
||||
assert stats.compaction.fragments_removed == 0
|
||||
assert stats.compaction.fragments_added == 0
|
||||
|
||||
stats = await table.optimize(data_options={"target_rows_per_fragment": 3})
|
||||
stats = await table.optimize(target_rows_per_fragment=3)
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert stats.compaction.fragments_added == 1
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid compaction option: unknown"):
|
||||
await table.optimize(data_options={"unknown": 1})
|
||||
with pytest.raises(TypeError, match="Unsupported Optimize option: unknown"):
|
||||
await table.optimize(unknown=1)
|
||||
|
||||
|
||||
def test_optimize_data_options_sync(mem_db: DBConnection):
|
||||
table = mem_db.create_table("test", data=[{"x": 1}])
|
||||
with pytest.raises(ValueError, match="target_rows_per_fragment must be between"):
|
||||
table.optimize(data_options={"target_rows_per_fragment": 0})
|
||||
table.optimize(target_rows_per_fragment=0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("option", ["max_source_rows", "max_source_bytes"])
|
||||
@@ -5489,7 +5485,7 @@ async def test_optimize_compaction_source_limits(
|
||||
await table.add([{"x": 2}])
|
||||
|
||||
stats = await table.optimize(
|
||||
data_options={
|
||||
**{
|
||||
"target_rows_per_fragment": 3,
|
||||
option: 1,
|
||||
}
|
||||
@@ -5505,24 +5501,14 @@ async def test_optimize_compaction_data_storage_version(
|
||||
table = await mem_db_async.create_table("test", data=[{"x": 1}])
|
||||
await table.add([{"x": 2}])
|
||||
|
||||
stats = await table.optimize(
|
||||
data_options={
|
||||
"target_rows_per_fragment": 3,
|
||||
"data_storage_version": "2.2",
|
||||
}
|
||||
)
|
||||
stats = await table.optimize(target_rows_per_fragment=3, data_storage_version="2.2")
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert stats.compaction.fragments_added == 1
|
||||
|
||||
table = await mem_db_async.create_table("cross_family", data=[{"x": 1}])
|
||||
await table.add([{"x": 2}])
|
||||
with pytest.raises(ValueError, match="V1 and V2 storage versions cannot be mixed"):
|
||||
await table.optimize(
|
||||
data_options={
|
||||
"target_rows_per_fragment": 3,
|
||||
"data_storage_version": "legacy",
|
||||
}
|
||||
)
|
||||
await table.optimize(target_rows_per_fragment=3, data_storage_version="legacy")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -5530,16 +5516,11 @@ async def test_optimize_compaction_excluded_fragments(mem_db_async: AsyncConnect
|
||||
table = await mem_db_async.create_table("test", data=[{"x": 1}])
|
||||
await table.add([{"x": 2}])
|
||||
|
||||
stats = await table.optimize(
|
||||
data_options={
|
||||
"target_rows_per_fragment": 3,
|
||||
"excluded_fragment_ids": [0],
|
||||
}
|
||||
)
|
||||
stats = await table.optimize(target_rows_per_fragment=3, excluded_fragment_ids=[0])
|
||||
assert stats.compaction.fragments_removed == 0
|
||||
assert stats.compaction.fragments_added == 0
|
||||
|
||||
stats = await table.optimize(data_options={"target_rows_per_fragment": 3})
|
||||
stats = await table.optimize(target_rows_per_fragment=3)
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert stats.compaction.fragments_added == 1
|
||||
|
||||
@@ -5576,7 +5557,7 @@ async def test_optimize_data_options_validation(
|
||||
):
|
||||
table = await mem_db_async.create_table("test", data=[{"x": 1}])
|
||||
with pytest.raises(ValueError, match=message):
|
||||
await table.optimize(data_options={option: value})
|
||||
await table.optimize(**{option: value})
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -189,18 +189,12 @@ def test_remote_maintenance_options_warn(method, kwargs):
|
||||
|
||||
def test_remote_optimize_options():
|
||||
handle = MagicMock()
|
||||
handle.optimize = AsyncMock(side_effect=NotImplementedError("remote optimize"))
|
||||
handle._do_optimize = AsyncMock(side_effect=NotImplementedError("remote optimize"))
|
||||
table = RemoteTable(handle, "test_db")
|
||||
age = timedelta(days=1)
|
||||
with pytest.raises(NotImplementedError, match="remote optimize"):
|
||||
table.optimize(cleanup_older_than=age, delete_unverified=True, retrain=True)
|
||||
handle.optimize.assert_awaited_once_with(
|
||||
cleanup_older_than=age,
|
||||
delete_unverified=True,
|
||||
retrain=True,
|
||||
data_options=None,
|
||||
action=None,
|
||||
)
|
||||
handle._do_optimize.assert_awaited_once_with(86_400_000, True, None, None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -268,36 +262,41 @@ def test_optimize_has_no_legacy_compaction_aliases(cls):
|
||||
|
||||
def test_remote_optimize_rewrite_action():
|
||||
handle = MagicMock()
|
||||
handle.optimize = AsyncMock(return_value="accepted")
|
||||
handle._do_optimize = AsyncMock(return_value="accepted")
|
||||
table = RemoteTable(handle, "test_db")
|
||||
assert table.optimize(action="rewrite_data") == "accepted"
|
||||
handle.optimize.assert_awaited_once_with(
|
||||
cleanup_older_than=None,
|
||||
delete_unverified=False,
|
||||
retrain=False,
|
||||
data_options=None,
|
||||
action="rewrite_data",
|
||||
)
|
||||
handle._do_optimize.assert_awaited_once_with(None, False, None, "rewrite_data")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [Table, LanceTable, RemoteTable])
|
||||
@pytest.mark.parametrize("method", ["optimize", "optimize_async"])
|
||||
def test_optimize_public_options_names(cls, method):
|
||||
parameters = inspect.signature(getattr(cls, method)).parameters
|
||||
assert "data_options" in parameters
|
||||
assert parameters["options"].kind is inspect.Parameter.VAR_KEYWORD
|
||||
assert "data_options" not in parameters
|
||||
assert "compaction_options" not in parameters
|
||||
|
||||
|
||||
def test_optimize_public_types():
|
||||
import importlib.util
|
||||
from lancedb.optimize import OptimizeResult
|
||||
from lancedb.table import OptimizeDataOptions
|
||||
from lancedb.table import OptimizeOptions
|
||||
|
||||
assert lancedb.OptimizeDataOptions is OptimizeDataOptions
|
||||
assert lancedb.OptimizeOptions is OptimizeOptions
|
||||
assert not hasattr(lancedb, "CompactionOptions")
|
||||
assert not hasattr(lancedb, "OptimizeDataOptions")
|
||||
assert importlib.util.find_spec("lancedb.compaction") is None
|
||||
result = OptimizeResult.from_json(
|
||||
'{"partial_commit":false,"rows_succeeded":1,"rows_failed":0,'
|
||||
'"completion_percentage":100}'
|
||||
)
|
||||
assert result.rows_succeeded == 1
|
||||
|
||||
|
||||
def test_flat_optimize_forwarding(sync_table):
|
||||
table, handle = sync_table
|
||||
handle._do_optimize = AsyncMock(return_value="accepted")
|
||||
assert table.optimize(target_rows_per_fragment=100, io_buffer_size=0) == "accepted"
|
||||
handle._do_optimize.assert_awaited_once_with(
|
||||
None, False, {"target_rows_per_fragment": 100, "io_buffer_size": 0}, None
|
||||
)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
# pyright: reportUnnecessaryTypeIgnoreComment=true
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import assert_type
|
||||
|
||||
from lancedb import AsyncTable, OptimizeOptions, Table
|
||||
from lancedb._lancedb import OptimizeStats
|
||||
from lancedb.job import AsyncJob, Job
|
||||
from lancedb.optimize import OptimizeResult
|
||||
|
||||
|
||||
def synchronous(table: Table) -> None:
|
||||
options: OptimizeOptions = {"target_rows_per_fragment": 100, "io_buffer_size": 0}
|
||||
assert_type(table.optimize(**options), OptimizeStats)
|
||||
assert_type(table.optimize_async(**options), Job[OptimizeResult])
|
||||
assert_type(table.optimize(cleanup_older_than=timedelta(days=1)), OptimizeStats)
|
||||
table.optimize(data_options={"max_source_rows": 1}) # pyright: ignore[reportCallIssue]
|
||||
table.optimize_async(data_options={"max_source_rows": 1}) # pyright: ignore[reportCallIssue]
|
||||
|
||||
|
||||
async def asynchronous(table: AsyncTable) -> None:
|
||||
options: OptimizeOptions = {"target_rows_per_fragment": 100, "batch_size": 16}
|
||||
assert_type(await table.optimize(**options), OptimizeStats)
|
||||
assert_type(await table.optimize_async(**options), AsyncJob[OptimizeResult])
|
||||
await table.optimize(compaction_options={"max_source_rows": 1}) # pyright: ignore[reportCallIssue]
|
||||
Reference in New Issue
Block a user