mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(sdk): add typed Optimize previews
This commit is contained in:
@@ -806,6 +806,9 @@ class Table:
|
||||
async def update_field_metadata(
|
||||
self, updates: list[dict[str, Any]]
|
||||
) -> UpdateFieldMetadataResult: ...
|
||||
async def explain_optimize(
|
||||
self, data_options: Optional[Dict[str, Any]] = None
|
||||
) -> str: ...
|
||||
async def optimize_async(
|
||||
self, data_options: Optional[Dict[str, Any]] = None
|
||||
) -> Job: ...
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of durable Enterprise Optimize jobs."""
|
||||
"""Typed previews and results of Enterprise Optimize data rewrites."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
from typing import List, Literal, Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -35,3 +35,48 @@ class OptimizeResult:
|
||||
value = json.loads(raw)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OptimizeResolvedOptions:
|
||||
"""Effective rewrite settings after Enterprise policy resolution."""
|
||||
|
||||
target_rows_per_fragment: int
|
||||
max_source_rows: Optional[int] = None
|
||||
io_buffer_size: Optional[int] = None
|
||||
batch_size: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OptimizePlan:
|
||||
"""Data-rewrite preview without submitting a maintenance job.
|
||||
|
||||
Counts describe planned work, not committed results, memory use, or runtime.
|
||||
A later submission plans its own snapshot and may select different work.
|
||||
"""
|
||||
|
||||
operation: Literal["rewrite_data"]
|
||||
table: str
|
||||
namespace: List[str]
|
||||
branch: str
|
||||
source_version: int
|
||||
effective_options: OptimizeResolvedOptions
|
||||
planned_groups: int
|
||||
planned_fragments: int
|
||||
planned_source_rows: int
|
||||
more_work: bool
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "OptimizePlan":
|
||||
# The native decoder validates the versioned server contract first.
|
||||
value = json.loads(raw)
|
||||
option_names = {field.name for field in fields(OptimizeResolvedOptions)}
|
||||
value["effective_options"] = OptimizeResolvedOptions(
|
||||
**{
|
||||
key: item
|
||||
for key, item in value["effective_options"].items()
|
||||
if key in option_names
|
||||
}
|
||||
)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
|
||||
@@ -51,6 +51,7 @@ from lancedb.index import (
|
||||
Bitmap,
|
||||
LabelList,
|
||||
)
|
||||
from lancedb.optimize import OptimizePlan
|
||||
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
|
||||
from lancedb.job import Job
|
||||
from lancedb.functions import (
|
||||
@@ -1128,6 +1129,9 @@ class RemoteTable(Table):
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def explain_optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizePlan:
|
||||
return LOOP.run(self._table.explain_optimize(**options))
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ from lancedb.background_loop import LOOP, embedding_executor
|
||||
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
|
||||
from lancedb.job import AsyncJob, Job, _typed_job
|
||||
from lancedb.compaction import CompactionResult # noqa: F401 - public compatibility import
|
||||
from lancedb.optimize import OptimizeResult
|
||||
from lancedb.optimize import OptimizePlan, OptimizeResult
|
||||
from .dependencies import (
|
||||
_check_for_hugging_face,
|
||||
_check_for_lance,
|
||||
@@ -3230,6 +3230,23 @@ class Table(ABC):
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def explain_optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizePlan:
|
||||
"""Preview Enterprise data rewriting without creating a maintenance job.
|
||||
|
||||
Accepts the same flat rewrite settings as ``optimize_async()``. Cleanup
|
||||
and separate index maintenance are unsupported, as are Embedded and
|
||||
historical-version handles. Requires SQL preview support, table
|
||||
Ownership and parent Usage. A later submission plans its own snapshot.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> plan = table.explain_optimize(max_source_rows=1_000_000) # doctest: +SKIP
|
||||
>>> print(plan.source_version, plan.planned_source_rows) # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"Optimize previews are only supported by LanceDB Enterprise"
|
||||
)
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
"""Submit Enterprise Optimize and return a durable job after acceptance.
|
||||
|
||||
@@ -5990,6 +6007,9 @@ class LanceTable(Table):
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def explain_optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizePlan:
|
||||
return LOOP.run(self._table.explain_optimize(**options))
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
@@ -9690,6 +9710,16 @@ class AsyncTable:
|
||||
)
|
||||
return await self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
async def explain_optimize(
|
||||
self, **options: Unpack[OptimizeOptions]
|
||||
) -> OptimizePlan:
|
||||
"""Preview Enterprise data rewriting without submitting a job.
|
||||
|
||||
See [Table.explain_optimize][lancedb.table.Table.explain_optimize].
|
||||
"""
|
||||
tuning, _, _, _ = _split_optimize_options(options, durable=True)
|
||||
return OptimizePlan.from_json(await self._inner.explain_optimize(tuning))
|
||||
|
||||
async def optimize_async(
|
||||
self, **options: Unpack[OptimizeOptions]
|
||||
) -> AsyncJob[OptimizeResult]:
|
||||
|
||||
@@ -8810,3 +8810,177 @@ def test_legacy_optimize_rejects_ambiguous_or_unknown_settings(options):
|
||||
|
||||
with pytest.warns(DeprecationWarning), pytest.raises(TypeError):
|
||||
_split_optimize_options(options)
|
||||
|
||||
|
||||
def _optimize_preview_payload():
|
||||
return {
|
||||
"format_version": 1,
|
||||
"operation": "rewrite_data",
|
||||
"table": "test",
|
||||
"namespace": [],
|
||||
"branch": "main",
|
||||
"source_version": 42,
|
||||
"effective_options": {
|
||||
"target_rows_per_fragment": 1000,
|
||||
"max_source_rows": None,
|
||||
"io_buffer_size": 0,
|
||||
"batch_size": None,
|
||||
},
|
||||
"planned_groups": 0,
|
||||
"planned_fragments": 0,
|
||||
"planned_source_rows": 0,
|
||||
"more_work": False,
|
||||
"future_field": "ignored",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"options, expected",
|
||||
[
|
||||
({}, None),
|
||||
({"compaction_options": {"io_buffer_size": 0}}, b"io_buffer_size = 0"),
|
||||
(
|
||||
{"target_rows_per_fragment": 1_048_576},
|
||||
b"target_rows_per_fragment = 1048576",
|
||||
),
|
||||
(
|
||||
{"max_source_rows": 500, "io_buffer_size": 0, "batch_size": 16},
|
||||
b"io_buffer_size = 0",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_explain_optimize_forwards_flat_options_without_creating_jobs(
|
||||
asynchronous, options, expected
|
||||
):
|
||||
from lancedb.optimize import OptimizePlan, OptimizeResolvedOptions
|
||||
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table(
|
||||
{
|
||||
"plan_type": ["logical_plan"],
|
||||
"plan": [json.dumps(_optimize_preview_payload())],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
plan = await table.explain_optimize(**options)
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
plan = table.explain_optimize(**options)
|
||||
assert isinstance(plan, OptimizePlan)
|
||||
assert isinstance(plan.effective_options, OptimizeResolvedOptions)
|
||||
assert plan.operation == "rewrite_data"
|
||||
assert plan.source_version == 42
|
||||
assert plan.planned_source_rows == 0
|
||||
assert plan.effective_options.io_buffer_size == 0
|
||||
assert plan.effective_options.batch_size is None
|
||||
assert not plan.more_work
|
||||
assert len(server.tickets) == 1
|
||||
assert b"EXPLAIN (FORMAT JSON) OPTIMIZE" in server.tickets[0]
|
||||
if expected:
|
||||
assert expected in server.tickets[0]
|
||||
else:
|
||||
assert b"WITH (" not in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"change", ["version", "operation", "missing", "negative", "text", "duplicate"]
|
||||
)
|
||||
async def test_explain_optimize_rejects_malformed_previews_without_retry(
|
||||
asynchronous, change
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(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
|
||||
plan = _optimize_preview_payload()
|
||||
if change == "version":
|
||||
plan["format_version"] = 99
|
||||
elif change == "operation":
|
||||
plan["operation"] = "cleanup"
|
||||
elif change == "missing":
|
||||
del plan["source_version"]
|
||||
elif change == "negative":
|
||||
plan["planned_groups"] = -1
|
||||
value = "display text" if change == "text" else json.dumps(plan)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"plan": [value] * (2 if change == "duplicate" else 1)})
|
||||
)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="structured preview"):
|
||||
await table.explain_optimize()
|
||||
else:
|
||||
table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
|
||||
with pytest.raises(Exception, match="structured preview"):
|
||||
table.explain_optimize()
|
||||
assert server.calls == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"cleanup_older_than": timedelta(days=1)},
|
||||
{"delete_unverified": True},
|
||||
{"action": "cleanup"},
|
||||
{"data_options": {}},
|
||||
{"batch_size": 0},
|
||||
{"max_source_bytes": 1024},
|
||||
],
|
||||
)
|
||||
async def test_explain_optimize_rejects_unsupported_options_before_requests(
|
||||
asynchronous, options
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class Server(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("invalid previews must not send SQL")
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
with pytest.raises((ValueError, TypeError, NotImplementedError)):
|
||||
await table.explain_optimize(**options)
|
||||
else:
|
||||
table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
|
||||
with pytest.raises((ValueError, TypeError, NotImplementedError)):
|
||||
table.explain_optimize(**options)
|
||||
assert server.calls == 0
|
||||
|
||||
@@ -6542,3 +6542,13 @@ async def test_optimize_inherits_embedded_table_config(tmp_path, asynchronous):
|
||||
)
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert table.count_rows() == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_explain_optimize_requires_enterprise(mem_db, mem_db_async):
|
||||
table = mem_db.create_table("preview", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="Enterprise"):
|
||||
table.explain_optimize()
|
||||
table = await mem_db_async.create_table("preview", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="Enterprise"):
|
||||
await table.explain_optimize()
|
||||
|
||||
@@ -26,6 +26,7 @@ import pytest
|
||||
"search",
|
||||
"cleanup_old_versions",
|
||||
"optimize_async",
|
||||
"explain_optimize",
|
||||
"optimize",
|
||||
"to_polars",
|
||||
],
|
||||
|
||||
@@ -8,7 +8,7 @@ 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
|
||||
from lancedb.optimize import OptimizePlan, OptimizeResult
|
||||
|
||||
|
||||
def synchronous(table: Table) -> None:
|
||||
@@ -17,6 +17,8 @@ def synchronous(table: Table) -> None:
|
||||
assert_type(table.optimize(retrain=False), OptimizeStats)
|
||||
table.optimize_async(retrain=True) # pyright: ignore[reportCallIssue]
|
||||
assert_type(table.optimize_async(**options), Job[OptimizeResult])
|
||||
assert_type(table.explain_optimize(**options), OptimizePlan)
|
||||
table.explain_optimize(data_options={}) # pyright: ignore[reportCallIssue]
|
||||
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]
|
||||
@@ -27,6 +29,7 @@ async def asynchronous(table: AsyncTable) -> None:
|
||||
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})
|
||||
assert_type(await table.explain_optimize(**options), OptimizePlan)
|
||||
|
||||
|
||||
async def legacy_types(table: AsyncTable) -> None:
|
||||
@@ -39,3 +42,8 @@ async def legacy_types(table: AsyncTable) -> None:
|
||||
await table.compact_async(compaction_options=options),
|
||||
AsyncJob[CompactionResult],
|
||||
)
|
||||
|
||||
|
||||
def preview_types(table: Table, options: OptimizeOptions) -> None:
|
||||
assert_type(table.explain_optimize(**options), OptimizePlan)
|
||||
table.explain_optimize(compaction_options={})
|
||||
|
||||
Reference in New Issue
Block a user