mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
fix(sdk): retain deprecated compaction API compatibility
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, OptimizeOptions, Table
|
||||
from .table import AsyncTable, CompactionOptions, OptimizeOptions, Table
|
||||
from .types import BaseTokenizerType
|
||||
from ._lancedb import Session
|
||||
from .namespace import (
|
||||
@@ -677,6 +677,7 @@ __all__ = [
|
||||
"AsyncLanceNamespaceDBConnection",
|
||||
"AsyncTable",
|
||||
"OptimizeOptions",
|
||||
"CompactionOptions",
|
||||
"FtsToken",
|
||||
"FunctionColumnAutoRefreshStatus",
|
||||
"FunctionColumnLastRefreshJob",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
"""Deprecated result imports. Use :mod:`lancedb.optimize` instead."""
|
||||
|
||||
from .optimize import OptimizeResult
|
||||
|
||||
CompactionResult = OptimizeResult
|
||||
|
||||
__all__ = ["CompactionResult"]
|
||||
@@ -85,6 +85,7 @@ from ..table import (
|
||||
AsyncTable,
|
||||
BlobMode,
|
||||
Branches,
|
||||
CompactionOptions,
|
||||
OptimizeOptions,
|
||||
OptimizeResult,
|
||||
IndexStatistics,
|
||||
@@ -1106,6 +1107,27 @@ class RemoteTable(Table):
|
||||
)
|
||||
pass
|
||||
|
||||
def compact_files(self, *args, **kwargs):
|
||||
"""
|
||||
compact_files() is a no-op in LanceDB Enterprise.
|
||||
"""
|
||||
warnings.warn(
|
||||
"compact_files() is a no-op in LanceDB Enterprise.",
|
||||
stacklevel=2,
|
||||
)
|
||||
pass
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[OptimizeResult]:
|
||||
"""Deprecated: use optimize_async() with flat rewrite settings."""
|
||||
warnings.warn(
|
||||
"compact_async() is deprecated; use optimize_async()",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ from lancedb.sql import QueryParameters, to_parameter_batch
|
||||
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 .dependencies import (
|
||||
_check_for_hugging_face,
|
||||
@@ -305,6 +306,7 @@ if TYPE_CHECKING:
|
||||
Table as LanceDBTable,
|
||||
OptimizeStats,
|
||||
CleanupStats,
|
||||
CompactionStats,
|
||||
Tag,
|
||||
AddColumnsResult,
|
||||
RefreshColumnResult,
|
||||
@@ -443,6 +445,9 @@ class OptimizeOptions(TypedDict, total=False):
|
||||
data_storage_version: str
|
||||
"""Data-file version or release selector for compacted output."""
|
||||
|
||||
compaction_options: Optional[Mapping[str, Any]]
|
||||
"""Deprecated nested rewrite settings; pass the settings as flat keywords."""
|
||||
|
||||
cleanup_older_than: Optional[timedelta]
|
||||
"""Embedded version-retention age; unsupported by remote Optimize jobs."""
|
||||
|
||||
@@ -456,6 +461,10 @@ class OptimizeOptions(TypedDict, total=False):
|
||||
"""Select only data rewriting; omit for Embedded's full maintenance cycle."""
|
||||
|
||||
|
||||
# Deprecated compatibility name; use OptimizeOptions for new code.
|
||||
CompactionOptions = OptimizeOptions
|
||||
|
||||
|
||||
def _split_optimize_options(
|
||||
options: OptimizeOptions, *, durable: bool = False
|
||||
) -> Tuple[
|
||||
@@ -470,6 +479,32 @@ def _split_optimize_options(
|
||||
if unknown:
|
||||
raise TypeError(f"Unsupported Optimize option: {sorted(unknown)[0]}")
|
||||
tuning: Dict[str, Any] = dict(options)
|
||||
legacy = tuning.pop("compaction_options", None)
|
||||
if legacy is not None:
|
||||
warnings.warn(
|
||||
"compaction_options is deprecated; pass Optimize settings as flat "
|
||||
"keyword arguments",
|
||||
DeprecationWarning,
|
||||
stacklevel=3,
|
||||
)
|
||||
if not isinstance(legacy, dict):
|
||||
raise TypeError("compaction_options must be a dictionary")
|
||||
controls = {
|
||||
"cleanup_older_than",
|
||||
"delete_unverified",
|
||||
"retrain",
|
||||
"action",
|
||||
"compaction_options",
|
||||
}
|
||||
rewrite_keys = OptimizeOptions.__annotations__.keys() - controls
|
||||
unknown_legacy = legacy.keys() - rewrite_keys
|
||||
if unknown_legacy:
|
||||
raise TypeError(f"Unsupported Optimize option: {sorted(unknown_legacy)[0]}")
|
||||
if tuning.keys() & rewrite_keys:
|
||||
raise TypeError(
|
||||
"cannot combine compaction_options with flat rewrite settings"
|
||||
)
|
||||
tuning.update(legacy)
|
||||
cleanup_older_than = tuning.pop("cleanup_older_than", None)
|
||||
delete_unverified = tuning.pop("delete_unverified", False)
|
||||
retrain = tuning.pop("retrain", False)
|
||||
@@ -3162,6 +3197,39 @@ class Table(ABC):
|
||||
cleanup for you automatically.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def compact_files(self, *args, **kwargs):
|
||||
"""
|
||||
Run the compaction process on the table.
|
||||
This can be run after making several small appends to optimize the table
|
||||
for faster reads.
|
||||
|
||||
Arguments are passed onto Lance's
|
||||
`lance.dataset.DatasetOptimizer.compact_files`.
|
||||
For most cases, the default should be fine.
|
||||
|
||||
See Also
|
||||
--------
|
||||
[Table.optimize][lancedb.table.Table.optimize]: A more comprehensive
|
||||
optimization operation that includes cleanup as well as other operations.
|
||||
|
||||
Notes
|
||||
-----
|
||||
This function is not available in LanceDB Enterprise, which manages
|
||||
compaction for you automatically.
|
||||
"""
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[OptimizeResult]:
|
||||
"""Deprecated: use optimize_async() with flat rewrite settings."""
|
||||
warnings.warn(
|
||||
"compact_async() is deprecated; use optimize_async()",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
"""Submit remote Optimize and return a durable job after acceptance.
|
||||
|
||||
@@ -5887,6 +5955,37 @@ class LanceTable(Table):
|
||||
older_than, delete_unverified=delete_unverified
|
||||
)
|
||||
|
||||
@deprecation.deprecated(
|
||||
deprecated_in="0.21.0",
|
||||
current_version=__version__,
|
||||
details="Use `Table.optimize` instead.",
|
||||
)
|
||||
def compact_files(self, *args, **kwargs) -> CompactionStats:
|
||||
"""
|
||||
Run the compaction process on the table.
|
||||
|
||||
This can be run after making several small appends to optimize the table
|
||||
for faster reads.
|
||||
|
||||
Arguments are passed onto `lance.dataset.DatasetOptimizer.compact_files`.
|
||||
(see Lance documentation for more details) For most cases, the default
|
||||
should be fine.
|
||||
"""
|
||||
stats = self.to_lance().optimize.compact_files(*args, **kwargs)
|
||||
self.checkout_latest()
|
||||
return stats
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[OptimizeResult]:
|
||||
"""Deprecated: use optimize_async() with flat rewrite settings."""
|
||||
warnings.warn(
|
||||
"compact_async() is deprecated; use optimize_async()",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
@@ -9576,6 +9675,17 @@ class AsyncTable:
|
||||
"""The branch this table handle is scoped to, or ``None`` for ``main``."""
|
||||
return self._inner.current_branch()
|
||||
|
||||
async def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> AsyncJob[OptimizeResult]:
|
||||
"""Deprecated: use optimize_async() with flat rewrite settings."""
|
||||
warnings.warn(
|
||||
"compact_async() is deprecated; use optimize_async()",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return await self.optimize_async(**(compaction_options or {}))
|
||||
|
||||
async def optimize_async(
|
||||
self, **options: Unpack[OptimizeOptions]
|
||||
) -> AsyncJob[OptimizeResult]:
|
||||
|
||||
@@ -8708,7 +8708,7 @@ def test_remote_prewarm_preview_reports_old_server_format_support():
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["optimize", "optimize_async"])
|
||||
@pytest.mark.parametrize("key", ["data_options", "compaction_options"])
|
||||
@pytest.mark.parametrize("key", ["data_options"])
|
||||
def test_remote_optimize_rejects_wrapped_options_before_submission(method, key):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
@@ -8753,3 +8753,57 @@ def test_remote_optimize_job_rejects_maintenance_options_before_submission(optio
|
||||
with pytest.raises(ValueError, match="unsupported by Optimize jobs"):
|
||||
table.optimize_async(**options)
|
||||
assert server.calls == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("method", ["optimize", "compact_async"])
|
||||
async def test_legacy_optimize_submits_once_with_settings(asynchronous, method):
|
||||
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({"job_id": ["legacy-optimize-job"]})
|
||||
)
|
||||
|
||||
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.warns(DeprecationWarning):
|
||||
result = await getattr(table, method)(
|
||||
compaction_options={"io_buffer_size": 0, "max_source_rows": 7}
|
||||
)
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
with pytest.warns(DeprecationWarning):
|
||||
result = getattr(table, method)(
|
||||
compaction_options={"io_buffer_size": 0, "max_source_rows": 7}
|
||||
)
|
||||
if method == "compact_async":
|
||||
assert result.id == "legacy-optimize-job"
|
||||
assert len(server.tickets) == 1
|
||||
assert b"io_buffer_size = 0" in server.tickets[0]
|
||||
assert b"max_source_rows = 7" in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"compaction_options": {"max_source_rows": 7}, "batch_size": 16},
|
||||
{"compaction_options": {"unknown_limit": 7}},
|
||||
],
|
||||
)
|
||||
def test_legacy_optimize_rejects_ambiguous_or_unknown_settings(options):
|
||||
from lancedb.table import _split_optimize_options
|
||||
|
||||
with pytest.warns(DeprecationWarning), pytest.raises(TypeError):
|
||||
_split_optimize_options(options)
|
||||
|
||||
@@ -6486,4 +6486,24 @@ async def test_optimize_async_requires_remote(mem_db, mem_db_async):
|
||||
async_table = await mem_db_async.create_table("local_job", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="only supported on remote tables"):
|
||||
await async_table.optimize_async()
|
||||
assert not hasattr(async_table, "compact_async")
|
||||
assert hasattr(async_table, "compact_async")
|
||||
|
||||
|
||||
def test_legacy_compact_files_preserves_data_and_history(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table("legacy", [{"id": 1}])
|
||||
table.add([{"id": 2}])
|
||||
with pytest.warns(DeprecationWarning):
|
||||
stats = table.compact_files(target_rows_per_fragment=100)
|
||||
assert stats.fragments_removed == 2
|
||||
assert table.count_rows() == 2
|
||||
table.checkout(1)
|
||||
assert table.count_rows() == 1
|
||||
|
||||
|
||||
def test_legacy_optimize_nested_settings_embedded(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table("legacy", [{"id": 1}])
|
||||
table.add([{"id": 2}])
|
||||
with pytest.warns(DeprecationWarning, match="compaction_options"):
|
||||
stats = table.optimize(compaction_options={"target_rows_per_fragment": 100})
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert table.count_rows() == 2
|
||||
|
||||
@@ -255,9 +255,9 @@ def test_index_replacement_defaults(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cls", [Table, LanceTable, RemoteTable])
|
||||
def test_optimize_has_no_legacy_compaction_aliases(cls):
|
||||
assert not hasattr(cls, "compact_files")
|
||||
assert not hasattr(cls, "compact_async")
|
||||
def test_optimize_retains_legacy_compaction_aliases(cls):
|
||||
assert hasattr(cls, "compact_files")
|
||||
assert hasattr(cls, "compact_async")
|
||||
|
||||
|
||||
def test_remote_optimize_rewrite_action():
|
||||
@@ -283,9 +283,12 @@ def test_optimize_public_types():
|
||||
from lancedb.table import OptimizeOptions
|
||||
|
||||
assert lancedb.OptimizeOptions is OptimizeOptions
|
||||
assert not hasattr(lancedb, "CompactionOptions")
|
||||
assert lancedb.CompactionOptions is OptimizeOptions
|
||||
assert not hasattr(lancedb, "OptimizeDataOptions")
|
||||
assert importlib.util.find_spec("lancedb.compaction") is None
|
||||
assert importlib.util.find_spec("lancedb.compaction") is not None
|
||||
from lancedb.compaction import CompactionResult
|
||||
|
||||
assert CompactionResult is OptimizeResult
|
||||
result = OptimizeResult.from_json(
|
||||
'{"partial_commit":false,"rows_succeeded":1,"rows_failed":0,'
|
||||
'"completion_percentage":100}'
|
||||
@@ -300,3 +303,36 @@ def test_flat_optimize_forwarding(sync_table):
|
||||
handle._do_optimize.assert_awaited_once_with(
|
||||
None, False, {"target_rows_per_fragment": 100, "io_buffer_size": 0}, None
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"compaction_options": {"target_rows_per_fragment": 100, "io_buffer_size": 0}},
|
||||
],
|
||||
)
|
||||
def test_legacy_optimize_options_forwarded(sync_table, options):
|
||||
table, handle = sync_table
|
||||
handle._do_optimize = AsyncMock(return_value="accepted")
|
||||
with pytest.warns(DeprecationWarning, match="compaction_options"):
|
||||
assert table.optimize(**options) == "accepted"
|
||||
handle._do_optimize.assert_awaited_once_with(
|
||||
None, False, {"target_rows_per_fragment": 100, "io_buffer_size": 0}, None
|
||||
)
|
||||
|
||||
|
||||
def test_legacy_compact_async_forwarded(sync_table):
|
||||
table, handle = sync_table
|
||||
handle.optimize_async = AsyncMock(return_value=MagicMock())
|
||||
with pytest.warns(DeprecationWarning, match="compact_async"):
|
||||
table.compact_async(compaction_options={"io_buffer_size": 0})
|
||||
handle.optimize_async.assert_awaited_once_with(io_buffer_size=0)
|
||||
|
||||
|
||||
def test_remote_legacy_compact_files_is_still_noop():
|
||||
handle = MagicMock()
|
||||
table = RemoteTable(handle, "test_db")
|
||||
with pytest.warns(UserWarning, match="no-op"):
|
||||
assert table.compact_files(target_rows_per_fragment=10) is None
|
||||
handle.optimize_async.assert_not_called()
|
||||
handle._do_optimize.assert_not_called()
|
||||
|
||||
@@ -24,4 +24,16 @@ 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]
|
||||
await table.optimize(compaction_options={"max_source_rows": 1})
|
||||
|
||||
|
||||
async def legacy_types(table: AsyncTable) -> None:
|
||||
from lancedb import CompactionOptions
|
||||
from lancedb.compaction import CompactionResult
|
||||
|
||||
options: CompactionOptions = {"max_source_rows": 7}
|
||||
assert_type(await table.optimize(compaction_options=options), OptimizeStats)
|
||||
assert_type(
|
||||
await table.compact_async(compaction_options=options),
|
||||
AsyncJob[CompactionResult],
|
||||
)
|
||||
|
||||
+2
-1
@@ -28,10 +28,11 @@ use arrow::{
|
||||
use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest};
|
||||
use lancedb::connection::LanceFileVersion;
|
||||
use lancedb::index::scalar::FtsIndexBuilder;
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
use lancedb::table::{
|
||||
AddDataMode, ColumnAlteration, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken,
|
||||
FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget,
|
||||
IndexRemapMode, NewColumnTransform, OptimizeDataMode, OptimizeOptions, OptimizeOverrides, Ref,
|
||||
IndexRemapMode, NewColumnTransform, OptimizeDataMode, OptimizeOverrides, Ref,
|
||||
RefreshColumnOptions, Table as LanceDbTable,
|
||||
};
|
||||
use lancedb::tokenize as lancedb_tokenize;
|
||||
|
||||
Reference in New Issue
Block a user