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:
@@ -305,6 +305,26 @@ It is a no-op when no writers are cached.
|
||||
|
||||
***
|
||||
|
||||
### ~~compactAsync()~~
|
||||
|
||||
```ts
|
||||
compactAsync(options?): Promise<Job<OptimizeResult>>
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
* **options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md)
|
||||
|
||||
#### Returns
|
||||
|
||||
`Promise`<[`Job`](Job.md)<[`OptimizeResult`](../interfaces/OptimizeResult.md)>>
|
||||
|
||||
#### Deprecated
|
||||
|
||||
Use optimizeAsync() instead.
|
||||
|
||||
***
|
||||
|
||||
### compactRTE()
|
||||
|
||||
```ts
|
||||
|
||||
@@ -74,6 +74,7 @@
|
||||
- [ClientConfig](interfaces/ClientConfig.md)
|
||||
- [ColumnAlteration](interfaces/ColumnAlteration.md)
|
||||
- [ColumnOrdering](interfaces/ColumnOrdering.md)
|
||||
- [CompactionOptions](interfaces/CompactionOptions.md)
|
||||
- [CompactionStats](interfaces/CompactionStats.md)
|
||||
- [ConnectNamespaceOptions](interfaces/ConnectNamespaceOptions.md)
|
||||
- [ConnectionOptions](interfaces/ConnectionOptions.md)
|
||||
@@ -181,6 +182,7 @@
|
||||
- [BlobRangeRequest](type-aliases/BlobRangeRequest.md)
|
||||
- [BlobReadOptions](type-aliases/BlobReadOptions.md)
|
||||
- [BlobUri](type-aliases/BlobUri.md)
|
||||
- [CompactionResult](type-aliases/CompactionResult.md)
|
||||
- [Data](type-aliases/Data.md)
|
||||
- [DataLike](type-aliases/DataLike.md)
|
||||
- [DataTypeLike](type-aliases/DataTypeLike.md)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / CompactionOptions
|
||||
|
||||
# Interface: ~~CompactionOptions~~
|
||||
|
||||
## Deprecated
|
||||
|
||||
Use OptimizeOptions with flat rewrite settings.
|
||||
|
||||
## Extends
|
||||
|
||||
- `Pick`<[`OptimizeOptions`](OptimizeOptions.md), `"targetRowsPerFragment"` \| `"maxSourceRows"` \| `"ioBufferSize"` \| `"batchSize"`>
|
||||
|
||||
## Properties
|
||||
|
||||
### ~~batchSize?~~
|
||||
|
||||
```ts
|
||||
optional batchSize: number;
|
||||
```
|
||||
|
||||
Positive scanner batch size in rows.
|
||||
|
||||
#### Inherited from
|
||||
|
||||
`Pick.batchSize`
|
||||
|
||||
***
|
||||
|
||||
### ~~ioBufferSize?~~
|
||||
|
||||
```ts
|
||||
optional ioBufferSize: number;
|
||||
```
|
||||
|
||||
Scanner read-ahead budget in bytes; zero disables byte-based backpressure.
|
||||
|
||||
#### Inherited from
|
||||
|
||||
`Pick.ioBufferSize`
|
||||
|
||||
***
|
||||
|
||||
### ~~maxSourceRows?~~
|
||||
|
||||
```ts
|
||||
optional maxSourceRows: number;
|
||||
```
|
||||
|
||||
Positive live-source-row budget across whole rewrite tasks.
|
||||
|
||||
#### Inherited from
|
||||
|
||||
`Pick.maxSourceRows`
|
||||
|
||||
***
|
||||
|
||||
### ~~targetRowsPerFragment?~~
|
||||
|
||||
```ts
|
||||
optional targetRowsPerFragment: number;
|
||||
```
|
||||
|
||||
Positive target rows per output fragment. Omitted remote values inherit table policy.
|
||||
|
||||
#### Inherited from
|
||||
|
||||
`Pick.targetRowsPerFragment`
|
||||
@@ -42,6 +42,18 @@ Cannot be combined with action="rewrite_data" or used with durable Optimize jobs
|
||||
|
||||
***
|
||||
|
||||
### ~~compactionOptions?~~
|
||||
|
||||
```ts
|
||||
optional compactionOptions: CompactionOptions;
|
||||
```
|
||||
|
||||
#### Deprecated
|
||||
|
||||
Pass rewrite settings directly on OptimizeOptions.
|
||||
|
||||
***
|
||||
|
||||
### deleteUnverified?
|
||||
|
||||
```ts
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
[**@lancedb/lancedb**](../README.md) • **Docs**
|
||||
|
||||
***
|
||||
|
||||
[@lancedb/lancedb](../globals.md) / CompactionResult
|
||||
|
||||
# Type Alias: ~~CompactionResult~~
|
||||
|
||||
```ts
|
||||
type CompactionResult: OptimizeResult;
|
||||
```
|
||||
|
||||
## Deprecated
|
||||
|
||||
Use OptimizeResult.
|
||||
@@ -373,7 +373,7 @@ index statistics, and search. For example, `table.delete(where="id = 1")`,
|
||||
`create_scalar_index` defaults to `replace=True` on both backends. Both scalar
|
||||
and full-text index creation accept `wait_timeout`. LanceDB Enterprise maintenance methods
|
||||
use the same Optimize submission options. `cleanup_old_versions()` remains a
|
||||
warning-only no-op; the former `compact_files()` method is removed.
|
||||
warning-only no-op; the deprecated `compact_files()` method preserves that behavior.
|
||||
`optimize` submits a durable compaction job and returns once that submission is
|
||||
accepted, not once compaction itself finishes. Pruning and index optimization
|
||||
are not yet supported remotely, so it silently skips them and returns with
|
||||
@@ -407,6 +407,10 @@ code that used the former LanceDB Enterprise-only argument order.
|
||||
|
||||
::: lancedb.table.Table
|
||||
|
||||
::: lancedb.table.CompactionOptions
|
||||
|
||||
Deprecated compatibility name for `OptimizeOptions`.
|
||||
|
||||
::: lancedb.table.OptimizeOptions
|
||||
|
||||
::: lancedb.table.FragmentStatistics
|
||||
@@ -1523,3 +1527,7 @@ Caches, hidden paths, symlinks and unsafe paths are excluded. Use `pip=` or
|
||||
::: lancedb.prewarm.PrewarmDataPlan
|
||||
|
||||
::: lancedb.prewarm.PrewarmPruningSummary
|
||||
|
||||
::: lancedb.compaction.CompactionResult
|
||||
|
||||
Deprecated compatibility name for `lancedb.optimize.OptimizeResult`.
|
||||
|
||||
@@ -504,7 +504,7 @@ const result = await job.wait();
|
||||
```
|
||||
|
||||
```rust
|
||||
use lancedb::table::OptimizeOptions;
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
|
||||
async fn optimize_table(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
table.optimize(OptimizeOptions::default()).await?;
|
||||
@@ -523,11 +523,15 @@ returning actual statistics. Select only data rewrites with Python
|
||||
versions and skip the separate index maintenance phase. Cleanup arguments cannot
|
||||
be combined with a rewrite-only action.
|
||||
|
||||
The former `compact_async()` / `compactAsync()` methods are now
|
||||
The preferred replacements for `compact_async()` / `compactAsync()` are
|
||||
`optimize_async()` / `optimizeAsync()`. Rust `compact(overrides)` becomes
|
||||
`optimize(overrides)`. Python `compact_files()` becomes
|
||||
`optimize(action="rewrite_data", target_rows_per_fragment=1000)`, with rewrite metrics
|
||||
under `stats.compaction`. The old names are removed without aliases.
|
||||
under `stats.compaction`. The old methods and imports remain available for compatibility.
|
||||
Python warns on deprecated methods and nested settings; TypeScript and Rust mark
|
||||
legacy APIs deprecated. The Embedded `compact_files()` implementation still accepts
|
||||
Lance options and returns its original statistics; the remote method remains a
|
||||
warning-only no-op.
|
||||
|
||||
### Optimize naming migration
|
||||
|
||||
@@ -536,18 +540,29 @@ The SDK uses Optimize names for submission, settings, and durable results:
|
||||
| Previous name | Current name |
|
||||
| --- | --- |
|
||||
| `CompactionResult` | `OptimizeResult` |
|
||||
| `CompactionOptions` | `OptimizeOptions` |
|
||||
| Python/TypeScript `CompactionOptions` | `OptimizeOptions` |
|
||||
| Rust `CompactionOptions` | `table::optimize::OptimizeOptions` |
|
||||
| Rust `CompactionOverrides` | `OptimizeOverrides` |
|
||||
| Rust `CompactionMode` | `OptimizeDataMode` |
|
||||
| Rust index-maintenance `OptimizeOptions` | `IndexOptimizeOptions` |
|
||||
| Python `compaction_options=` / `data_options=` | Flat keyword arguments |
|
||||
| TypeScript `compactionOptions` / `dataOptions` | Flat `OptimizeOptions` fields |
|
||||
| Rust `table::OptimizeOptions` (index maintenance) | `table::IndexOptimizeOptions` |
|
||||
| Python `compaction_options=` | Flat keyword arguments |
|
||||
| TypeScript `compactionOptions` | Flat `OptimizeOptions` fields |
|
||||
| Python `lancedb.compaction` | `lancedb.optimize` |
|
||||
| Rust `OptimizeAction::Compact` | `OptimizeAction::RewriteDataWithOptions` |
|
||||
|
||||
These names are replaced without compatibility aliases. TypeScript rejects the
|
||||
removed `compactionOptions` and `dataOptions` properties before submission.
|
||||
Python rejects the old wrapper keywords. This prevents a requested work limit from being silently ignored.
|
||||
Released names remain as deprecated compatibility APIs. Existing Python
|
||||
`optimize(compaction_options=...)` and TypeScript `optimize({ compactionOptions: ... })`
|
||||
calls preserve their settings. Combining nested and flat rewrite settings is rejected
|
||||
before submission, as are unknown nested settings. The intermediate, unreleased
|
||||
`data_options` / `dataOptions` wrappers are unsupported.
|
||||
|
||||
Rust retains `table::OptimizeOptions` as the index-maintenance type so existing
|
||||
`OptimizeAction::Index(...)` calls keep their meaning. Import data-rewrite options
|
||||
from `table::optimize::OptimizeOptions`; `table::IndexOptimizeOptions` is the preferred
|
||||
explicit name for index-maintenance settings.
|
||||
|
||||
`OptimizeAction` also has new rewrite variants. Rust callers that exhaustively
|
||||
match this enum must handle those variants when upgrading.
|
||||
|
||||
`CompactionStats` and `OptimizeStats.compaction` still identify the compaction
|
||||
phase within Embedded's broader maintenance cycle. The algorithm-specific
|
||||
@@ -577,7 +592,7 @@ const job = await table.optimizeAsync(options);
|
||||
```
|
||||
|
||||
```rust
|
||||
use lancedb::table::OptimizeOptions;
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
|
||||
let options = OptimizeOptions {
|
||||
target_rows_per_fragment: 1000,
|
||||
|
||||
@@ -4,5 +4,5 @@ export const PyStorageCompactionTuning = "from lancedb import OptimizeOptions\n\
|
||||
|
||||
export const PyStorageRebuildVectorIndex = "from lancedb.index import IvfFlat\n\ntable.create_index(\n \"vector\",\n config=IvfFlat(distance_type=\"l2\", num_partitions=4),\n replace=True,\n)\n";
|
||||
|
||||
export const RsStorageCompactionTuning = "use lancedb::table::{OptimizeOptions, OptimizeAction};\n\nlet desired_fragment_bytes: usize = 64 * 1024;\nlet average_row_bytes: usize = 1024; // Estimate from representative rows.\nlet options = OptimizeOptions {\n target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1),\n batch_size: Some(16),\n num_threads: Some(1),\n ..Default::default()\n};\ntable\n .optimize(OptimizeAction::RewriteDataWithOptions {\n options,\n remap_options: None,\n })\n .await?;\n";
|
||||
export const RsStorageCompactionTuning = "use lancedb::table::OptimizeAction;\nuse lancedb::table::optimize::OptimizeOptions;\n\nlet desired_fragment_bytes: usize = 64 * 1024;\nlet average_row_bytes: usize = 1024; // Estimate from representative rows.\nlet options = OptimizeOptions {\n target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1),\n batch_size: Some(16),\n num_threads: Some(1),\n ..Default::default()\n};\ntable\n .optimize(OptimizeAction::RewriteDataWithOptions {\n options,\n remap_options: None,\n })\n .await?;\n";
|
||||
|
||||
|
||||
@@ -11,7 +11,10 @@ import {
|
||||
AutoQuery,
|
||||
type BlobInput,
|
||||
type BlobMode,
|
||||
type CompactionOptions,
|
||||
type CompactionResult,
|
||||
Connection,
|
||||
type Job,
|
||||
MatchQuery,
|
||||
type OptimizeOptions,
|
||||
PhraseQuery,
|
||||
@@ -6081,7 +6084,7 @@ describe("Optimize action selection", () => {
|
||||
expect((await table.indexStats("id_idx"))?.numUnindexedRows).toBe(0);
|
||||
await table.checkout(1);
|
||||
expect(await table.countRows()).toBe(1);
|
||||
expect("compactAsync" in table).toBe(false);
|
||||
expect("compactAsync" in table).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects unknown actions and conflicting cleanup requests before changes", async () => {
|
||||
@@ -6098,15 +6101,47 @@ describe("Optimize action selection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects removed compactionOptions without silently submitting defaults", async () => {
|
||||
test("preserves nested compactionOptions including explicit zero", async () => {
|
||||
const optimize = jest.fn();
|
||||
const table = new LocalTable({ optimize } as never);
|
||||
await expect(
|
||||
table.optimize({ compactionOptions: { maxSourceRows: 1 } } as never),
|
||||
).rejects.toThrow("Unsupported Optimize option: compactionOptions");
|
||||
expect(optimize).not.toHaveBeenCalled();
|
||||
await table.optimize({
|
||||
compactionOptions: { maxSourceRows: 7, ioBufferSize: 0 },
|
||||
});
|
||||
expect(optimize).toHaveBeenCalledTimes(1);
|
||||
expect(optimize).toHaveBeenCalledWith(
|
||||
undefined,
|
||||
undefined,
|
||||
{ maxSourceRows: 7, ioBufferSize: 0 },
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the deprecated durable method on the same submission path", async () => {
|
||||
const optimizeAsync = jest.fn().mockResolvedValue({});
|
||||
const table = new LocalTable({ optimizeAsync } as never);
|
||||
const options: CompactionOptions = { maxSourceRows: 7, ioBufferSize: 0 };
|
||||
const job: Job<CompactionResult> = await table.compactAsync(options);
|
||||
expect(job).toBeDefined();
|
||||
expect(optimizeAsync).toHaveBeenCalledTimes(1);
|
||||
expect(optimizeAsync).toHaveBeenCalledWith({
|
||||
maxSourceRows: 7,
|
||||
ioBufferSize: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ compactionOptions: { maxSourceRows: 7 }, batchSize: 16 },
|
||||
{ compactionOptions: { unknownLimit: 7 } },
|
||||
])(
|
||||
"rejects ambiguous or unknown legacy settings before submission",
|
||||
async (options) => {
|
||||
const optimize = jest.fn();
|
||||
const table = new LocalTable({ optimize } as never);
|
||||
await expect(table.optimize(options as never)).rejects.toThrow();
|
||||
expect(optimize).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("uses the same flat OptimizeOptions for durable submission", async () => {
|
||||
const optimizeAsync = jest.fn().mockResolvedValue({});
|
||||
const table = new LocalTable({ optimizeAsync } as never);
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import type { OptimizeResult } from "./optimize";
|
||||
|
||||
/** @deprecated Use OptimizeResult. */
|
||||
export type CompactionResult = OptimizeResult;
|
||||
export { decodeOptimizeResult as decodeCompactionResult } from "./optimize";
|
||||
@@ -175,6 +175,7 @@ export {
|
||||
AddDataOptions,
|
||||
UpdateOptions,
|
||||
OptimizeOptions,
|
||||
CompactionOptions,
|
||||
PrewarmDataOptions,
|
||||
Version,
|
||||
WriteProgress,
|
||||
@@ -667,6 +668,7 @@ export {
|
||||
export { Listing, ListingOptions } from "./listing";
|
||||
|
||||
export type { OptimizeResult } from "./optimize";
|
||||
export type { CompactionResult } from "./compaction";
|
||||
|
||||
export type {
|
||||
PrewarmDataPlan,
|
||||
|
||||
@@ -197,6 +197,8 @@ export interface OptimizeOptions {
|
||||
ioBufferSize?: number;
|
||||
/** Positive scanner batch size in rows. */
|
||||
batchSize?: number;
|
||||
/** @deprecated Pass rewrite settings directly on OptimizeOptions. */
|
||||
compactionOptions?: CompactionOptions;
|
||||
/** Run only data rewriting, retaining history and skipping separate index maintenance. */
|
||||
action?: "rewrite_data";
|
||||
/** Embedded: remove versions committed before this cutoff. Defaults to seven days ago.
|
||||
@@ -207,6 +209,13 @@ export interface OptimizeOptions {
|
||||
deleteUnverified?: boolean;
|
||||
}
|
||||
|
||||
/** @deprecated Use OptimizeOptions with flat rewrite settings. */
|
||||
export interface CompactionOptions
|
||||
extends Pick<
|
||||
OptimizeOptions,
|
||||
"targetRowsPerFragment" | "maxSourceRows" | "ioBufferSize" | "batchSize"
|
||||
> {}
|
||||
|
||||
export interface Version {
|
||||
version: number;
|
||||
timestamp: Date;
|
||||
@@ -1331,6 +1340,13 @@ export abstract class Table {
|
||||
throw new Error("Optimize jobs are only supported on remote tables");
|
||||
}
|
||||
|
||||
/** @deprecated Use optimizeAsync() instead. */
|
||||
async compactAsync(
|
||||
options?: CompactionOptions,
|
||||
): Promise<Job<OptimizeResult>> {
|
||||
return this.optimizeAsync(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimize the on-disk data and indices for better performance.
|
||||
*
|
||||
@@ -2050,6 +2066,7 @@ export class LocalTable extends Table {
|
||||
}
|
||||
|
||||
async optimizeAsync(options?: OptimizeOptions): Promise<Job<OptimizeResult>> {
|
||||
options = normalizeOptimizeOptions(options);
|
||||
validateOptimizeOptions(options, true);
|
||||
return new Job(
|
||||
await this.inner.optimizeAsync(optimizeRewriteSettings(options)),
|
||||
@@ -2058,6 +2075,7 @@ export class LocalTable extends Table {
|
||||
}
|
||||
|
||||
async optimize(options?: OptimizeOptions): Promise<OptimizeStats> {
|
||||
options = normalizeOptimizeOptions(options);
|
||||
validateOptimizeOptions(options);
|
||||
return await this.inner.optimize(
|
||||
options?.cleanupOlderThan?.getTime(),
|
||||
@@ -2360,6 +2378,35 @@ function rowIdsToBigInts(rowIds: readonly (bigint | number)[]): bigint[] {
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeOptimizeOptions(
|
||||
options?: OptimizeOptions,
|
||||
): OptimizeOptions | undefined {
|
||||
if (options?.compactionOptions === undefined) return options;
|
||||
const { compactionOptions, ...flat } = options;
|
||||
if (
|
||||
compactionOptions === null ||
|
||||
typeof compactionOptions !== "object" ||
|
||||
Array.isArray(compactionOptions)
|
||||
)
|
||||
throw new Error("compactionOptions must be an object");
|
||||
const rewriteKeys = new Set([
|
||||
"targetRowsPerFragment",
|
||||
"maxSourceRows",
|
||||
"ioBufferSize",
|
||||
"batchSize",
|
||||
]);
|
||||
for (const key of Object.keys(compactionOptions)) {
|
||||
if (!rewriteKeys.has(key))
|
||||
throw new Error(`Unsupported Optimize option: ${key}`);
|
||||
}
|
||||
if (Object.keys(flat).some((key) => rewriteKeys.has(key))) {
|
||||
throw new Error(
|
||||
"cannot combine compactionOptions with flat rewrite settings",
|
||||
);
|
||||
}
|
||||
return { ...flat, ...compactionOptions };
|
||||
}
|
||||
|
||||
function validateOptimizeOptions(
|
||||
options?: OptimizeOptions,
|
||||
durable = false,
|
||||
@@ -2372,6 +2419,7 @@ function validateOptimizeOptions(
|
||||
"action",
|
||||
"cleanupOlderThan",
|
||||
"deleteUnverified",
|
||||
"compactionOptions",
|
||||
]);
|
||||
for (const key of Object.keys(options ?? {})) {
|
||||
if (!supported.has(key))
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -2701,7 +2701,8 @@ mod tests {
|
||||
)]
|
||||
async fn indexes_and_optimize_still_apply_to_a_view() {
|
||||
use crate::index::Index;
|
||||
use crate::table::{OptimizeAction, OptimizeOptions};
|
||||
use crate::table::OptimizeAction;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let source = conn
|
||||
|
||||
@@ -4327,7 +4327,8 @@ async fn remote_optimize_forwards_per_job_options_on_main_and_branch() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_optimize_preserves_omissions_and_explicit_default_values() {
|
||||
use crate::table::{OptimizeOptions, OptimizeOverrides};
|
||||
use crate::table::OptimizeOverrides;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
let target = OptimizeOptions::default().target_rows_per_fragment;
|
||||
for (options, suffix) in [
|
||||
(OptimizeOverrides::default(), String::new()),
|
||||
@@ -5081,17 +5082,27 @@ async fn remote_public_prewarm_rejects_invalid_options_before_submission() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[allow(deprecated)]
|
||||
async fn remote_public_optimize_options_preserve_submission_contract() {
|
||||
use crate::table::{OptimizeOptions, OptimizeOverrides};
|
||||
use crate::table::OptimizeOverrides;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
enum Input {
|
||||
Options(OptimizeOptions),
|
||||
Overrides(OptimizeOverrides),
|
||||
Legacy(crate::table::CompactionOverrides),
|
||||
}
|
||||
let default_target = OptimizeOptions::default().target_rows_per_fragment;
|
||||
let tuned_suffix = ", target_rows_per_fragment = 100, max_source_rows = 500, \
|
||||
io_buffer_size = 0, batch_size = 16";
|
||||
for (input, suffix) in [
|
||||
(Input::Options(OptimizeOptions::default()), String::new()),
|
||||
(
|
||||
Input::Legacy(crate::table::CompactionOverrides {
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
}),
|
||||
", io_buffer_size = 0".into(),
|
||||
),
|
||||
(
|
||||
Input::Overrides(OptimizeOverrides::default()),
|
||||
String::new(),
|
||||
@@ -5170,6 +5181,7 @@ async fn remote_public_optimize_options_preserve_submission_contract() {
|
||||
let job = match input {
|
||||
Input::Options(options) => table.optimize_async(options).await.unwrap(),
|
||||
Input::Overrides(options) => table.optimize_async(options).await.unwrap(),
|
||||
Input::Legacy(options) => table.compact_async(options).await.unwrap(),
|
||||
};
|
||||
assert_eq!(job.id(), Some("public-compaction-job"));
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 0);
|
||||
@@ -5194,7 +5206,8 @@ async fn remote_public_optimize_options_preserve_submission_contract() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_public_optimize_rejects_unsupported_requests_before_submission() {
|
||||
use crate::table::{IndexOptimizeOptions, OptimizeAction, OptimizeOptions, OptimizeOverrides};
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use crate::table::{IndexOptimizeOptions, OptimizeAction, OptimizeOverrides};
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
..Default::default()
|
||||
@@ -5338,3 +5351,46 @@ async fn remote_optimize_convenience_and_durable_validate_the_same_receipt() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[allow(deprecated)]
|
||||
async fn remote_optimize_legacy_compact_convenience_preserves_settings_without_polling() {
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
result: RecordBatch::try_from_iter([(
|
||||
"job_id",
|
||||
Arc::new(StringArray::from(vec!["legacy-optimize-job"])) as ArrayRef,
|
||||
)])
|
||||
.unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let table = public_remote_table(RemoteTable::new_with_sql_client(
|
||||
client_with_handler(|request| -> http::Response<String> {
|
||||
panic!("legacy convenience must not poll jobs: {}", request.url());
|
||||
}),
|
||||
"analytics".into(),
|
||||
"clips".into(),
|
||||
vec![],
|
||||
"clips".into(),
|
||||
Default::default(),
|
||||
Some(sql),
|
||||
));
|
||||
let result = table
|
||||
.compact(crate::table::CompactionOverrides {
|
||||
target_rows_per_fragment: Some(100),
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.compaction.is_some());
|
||||
assert_eq!(
|
||||
*statements.lock().unwrap(),
|
||||
[
|
||||
"OPTIMIZE \"clips\" REWRITE DATA WITH (target_rows_per_fragment = 100, io_buffer_size = 0)"
|
||||
]
|
||||
);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
|
||||
@@ -129,7 +129,8 @@ pub(super) fn map_optimize_error(error: Error) -> Error {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::error::JobFailure;
|
||||
use crate::table::{OptimizeOptions, OptimizeOverrides};
|
||||
use crate::table::OptimizeOverrides;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn sql_error(code: tonic::Code, message: &str) -> Error {
|
||||
|
||||
@@ -87,6 +87,8 @@ pub mod function_column_status;
|
||||
pub mod merge;
|
||||
pub mod optimize;
|
||||
pub use optimize::OptimizeResult;
|
||||
#[allow(deprecated)]
|
||||
pub use optimize::{CompactionMode, CompactionOptions, CompactionOverrides, CompactionResult};
|
||||
mod prewarm;
|
||||
pub use prewarm::{PrewarmDataOptions, PrewarmDataPlan, PrewarmDataResult, PrewarmPruningSummary};
|
||||
pub(crate) mod primary_key;
|
||||
@@ -119,9 +121,14 @@ use futures::future::join_all;
|
||||
pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags};
|
||||
pub use lance::dataset::scanner::DatasetRecordBatchStream;
|
||||
pub use lance_index::optimize::OptimizeOptions as IndexOptimizeOptions;
|
||||
/// Deprecated index-maintenance options. Use [`IndexOptimizeOptions`].
|
||||
/// Data-rewrite options live at [`optimize::OptimizeOptions`].
|
||||
#[deprecated(
|
||||
note = "use IndexOptimizeOptions for index maintenance; use table::optimize::OptimizeOptions for data rewrites"
|
||||
)]
|
||||
pub type OptimizeOptions = IndexOptimizeOptions;
|
||||
pub use optimize::{
|
||||
IndexRemapMode, OptimizeAction, OptimizeDataMode, OptimizeOptions, OptimizeOverrides,
|
||||
OptimizeStats,
|
||||
IndexRemapMode, OptimizeAction, OptimizeDataMode, OptimizeOverrides, OptimizeStats,
|
||||
};
|
||||
pub use refresh::{
|
||||
FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget,
|
||||
@@ -910,6 +917,21 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
message: "Optimize jobs are only supported on remote tables".into(),
|
||||
})
|
||||
}
|
||||
/// Deprecated: use [`Self::optimize_async`].
|
||||
#[deprecated(note = "use optimize_async")]
|
||||
async fn compact_async(
|
||||
&self,
|
||||
options: optimize::OptimizeOverrides,
|
||||
) -> Result<Job<OptimizeResult>> {
|
||||
self.optimize_async(options).await
|
||||
}
|
||||
|
||||
/// Deprecated: use [`Self::optimize`].
|
||||
#[deprecated(note = "use optimize with OptimizeOverrides")]
|
||||
async fn compact(&self, options: optimize::OptimizeOverrides) -> Result<OptimizeStats> {
|
||||
self.optimize(OptimizeAction::RewriteData(options)).await
|
||||
}
|
||||
|
||||
/// Add columns to the table.
|
||||
async fn add_columns(
|
||||
&self,
|
||||
@@ -2098,12 +2120,12 @@ impl Table {
|
||||
/// file counts, represented as `None`. Reopen with
|
||||
/// `connection.open_job(id).await?.into_typed::<OptimizeResult>()?`.
|
||||
///
|
||||
/// Accepts flat [`OptimizeOptions`] directly, or [`optimize::OptimizeOverrides`]
|
||||
/// Accepts flat [`optimize::OptimizeOptions`] directly, or [`optimize::OptimizeOverrides`]
|
||||
/// when omitted values must be distinguished from explicit SDK defaults.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # async fn optimize(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
/// let job = table.optimize_async(lancedb::table::OptimizeOptions::default()).await?;
|
||||
/// let job = table.optimize_async(lancedb::table::optimize::OptimizeOptions::default()).await?;
|
||||
/// let result = job.wait().await?;
|
||||
/// println!("Committed {} rows", result.rows_succeeded);
|
||||
/// # Ok(())
|
||||
@@ -2117,6 +2139,23 @@ impl Table {
|
||||
self.inner.optimize_async(options).await
|
||||
}
|
||||
|
||||
/// Deprecated: use [`Self::optimize`] with [`OptimizeOverrides`].
|
||||
#[deprecated(note = "use optimize with OptimizeOverrides")]
|
||||
pub async fn compact(&self, options: optimize::OptimizeOverrides) -> Result<OptimizeStats> {
|
||||
#[allow(deprecated)]
|
||||
self.inner.compact(options).await
|
||||
}
|
||||
|
||||
/// Deprecated: use [`Self::optimize_async`].
|
||||
#[deprecated(note = "use optimize_async")]
|
||||
pub async fn compact_async(
|
||||
&self,
|
||||
options: optimize::OptimizeOverrides,
|
||||
) -> Result<Job<OptimizeResult>> {
|
||||
#[allow(deprecated)]
|
||||
self.inner.compact_async(options).await
|
||||
}
|
||||
|
||||
/// Language-binding entry point retaining optional compaction fields.
|
||||
#[doc(hidden)]
|
||||
pub async fn optimize_full_with_overrides(
|
||||
@@ -2194,7 +2233,7 @@ impl Table {
|
||||
#[doc(hidden)]
|
||||
pub async fn optimize_full(
|
||||
&self,
|
||||
data_options: OptimizeOptions,
|
||||
data_options: optimize::OptimizeOptions,
|
||||
older_than: Option<chrono::Duration>,
|
||||
before_timestamp: Option<chrono::DateTime<chrono::Utc>>,
|
||||
delete_unverified: Option<bool>,
|
||||
@@ -7120,7 +7159,7 @@ mod tests {
|
||||
// Compaction materializes the deletions.
|
||||
table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions {
|
||||
options: optimize::OptimizeOptions {
|
||||
target_rows_per_fragment: 1000,
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -32,6 +32,19 @@ pub use lance::dataset::optimize::{
|
||||
CompactionMode as OptimizeDataMode, CompactionOptions as OptimizeOptions, IndexRemapMode,
|
||||
};
|
||||
|
||||
/// Deprecated: use [`OptimizeOptions`].
|
||||
#[deprecated(note = "use table::optimize::OptimizeOptions")]
|
||||
pub type CompactionOptions = OptimizeOptions;
|
||||
/// Deprecated: use [`OptimizeDataMode`].
|
||||
#[deprecated(note = "use OptimizeDataMode")]
|
||||
pub type CompactionMode = OptimizeDataMode;
|
||||
/// Deprecated: use [`OptimizeOverrides`].
|
||||
#[deprecated(note = "use OptimizeOverrides")]
|
||||
pub type CompactionOverrides = OptimizeOverrides;
|
||||
/// Deprecated: use [`OptimizeResult`].
|
||||
#[deprecated(note = "use OptimizeResult")]
|
||||
pub type CompactionResult = OptimizeResult;
|
||||
|
||||
const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64;
|
||||
|
||||
/// Actual outcome of one remote Optimize data rewrite, returned by its job handle.
|
||||
@@ -335,7 +348,7 @@ pub enum OptimizeAction {
|
||||
/// placeholder rather than the real counts a local table reports.
|
||||
///
|
||||
/// ```
|
||||
/// use lancedb::{Table, table::{OptimizeOptions, OptimizeAction}};
|
||||
/// use lancedb::{Table, table::{optimize::OptimizeOptions, OptimizeAction}};
|
||||
/// # async fn optimize(table: &Table) -> lancedb::Result<()> {
|
||||
/// table.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
/// options: OptimizeOptions {
|
||||
@@ -360,6 +373,12 @@ pub enum OptimizeAction {
|
||||
options: OptimizeOptions,
|
||||
remap_options: Option<Arc<dyn IndexRemapperOptions>>,
|
||||
},
|
||||
/// Deprecated spelling of [`Self::RewriteDataWithOptions`].
|
||||
#[deprecated(note = "use RewriteDataWithOptions or RewriteData")]
|
||||
Compact {
|
||||
options: OptimizeOptions,
|
||||
remap_options: Option<Arc<dyn IndexRemapperOptions>>,
|
||||
},
|
||||
/// Prune old version of datasets
|
||||
///
|
||||
/// Every change in LanceDb is additive. When data is removed from a dataset a new version is
|
||||
@@ -409,13 +428,14 @@ pub enum OptimizeAction {
|
||||
|
||||
impl OptimizeAction {
|
||||
/// Normalize an Enterprise data-rewrite request before any submission.
|
||||
#[allow(deprecated)]
|
||||
pub(crate) fn into_remote_overrides(self) -> Result<OptimizeOverrides> {
|
||||
match self {
|
||||
OptimizeAction::RewriteData(options) => Ok(options),
|
||||
OptimizeAction::RewriteDataWithOptions {
|
||||
options,
|
||||
remap_options,
|
||||
} => {
|
||||
} | OptimizeAction::Compact { options, remap_options } => {
|
||||
if remap_options.is_some() {
|
||||
return Err(Error::NotSupported {
|
||||
message: "a custom index remap strategy is not supported in LanceDB \
|
||||
@@ -426,7 +446,7 @@ impl OptimizeAction {
|
||||
}
|
||||
let target = options.target_rows_per_fragment;
|
||||
let mut overrides = crate::table::optimize::OptimizeOverrides::try_from(options)?;
|
||||
if target == crate::table::OptimizeOptions::default().target_rows_per_fragment {
|
||||
if target == crate::table::optimize::OptimizeOptions::default().target_rows_per_fragment {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
Ok(overrides)
|
||||
@@ -564,6 +584,7 @@ pub(crate) async fn compact_files_impl(
|
||||
/// Execute the optimize operation on the table.
|
||||
///
|
||||
/// This is the main entry point for all optimization operations.
|
||||
#[allow(deprecated)]
|
||||
pub(crate) async fn execute_optimize(
|
||||
table: &NativeTable,
|
||||
action: OptimizeAction,
|
||||
@@ -594,6 +615,10 @@ pub(crate) async fn execute_optimize(
|
||||
OptimizeAction::RewriteDataWithOptions {
|
||||
options,
|
||||
remap_options,
|
||||
}
|
||||
| OptimizeAction::Compact {
|
||||
options,
|
||||
remap_options,
|
||||
} => {
|
||||
stats.compaction = Some(compact_files_impl(table, options, remap_options).await?);
|
||||
}
|
||||
@@ -643,7 +668,8 @@ mod tests {
|
||||
vector::{IvfHnswSqIndexBuilder, IvfRqIndexBuilder},
|
||||
};
|
||||
use crate::query::{ExecutableQuery, QueryBase};
|
||||
use crate::table::{OptimizeAction, OptimizeOptions, OptimizeStats};
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use crate::table::{OptimizeAction, OptimizeStats};
|
||||
use futures::TryStreamExt;
|
||||
|
||||
/// Regression test for https://github.com/lancedb/lancedb/issues/2866.
|
||||
|
||||
@@ -1719,7 +1719,7 @@ mod tests {
|
||||
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::OptimizeOptions::default(),
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -1835,7 +1835,7 @@ mod tests {
|
||||
.unwrap();
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::OptimizeOptions::default(),
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -1892,7 +1892,7 @@ mod tests {
|
||||
table.checkout_latest().await.unwrap();
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::OptimizeOptions::default(),
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -1921,7 +1921,7 @@ mod tests {
|
||||
append(&table, vec![5]).await;
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::OptimizeOptions::default(),
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -2227,7 +2227,7 @@ mod tests {
|
||||
append(&table, vec![2_000_000]).await;
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::OptimizeOptions::default(),
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -2557,7 +2557,7 @@ mod tests {
|
||||
.unwrap();
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::OptimizeOptions::default(),
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -14,6 +14,7 @@ use lance::blob::blob_field as blob;
|
||||
use lance::dataset::WriteParams;
|
||||
use lance_file::version::{ConcreteFileVersion, LanceFileVersion};
|
||||
use lance_table::format::BasePath;
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
use lancedb::{
|
||||
Connection, Error, Result, Table,
|
||||
blob::BlobRangeRequest,
|
||||
@@ -23,7 +24,7 @@ use lancedb::{
|
||||
OPT_NEW_TABLE_STORAGE_VERSION,
|
||||
},
|
||||
query::{ExecutableQuery, QueryBase},
|
||||
table::{AddDataMode, OptimizeAction, OptimizeOptions, OptimizeStats, WriteOptions},
|
||||
table::{AddDataMode, OptimizeAction, OptimizeStats, WriteOptions},
|
||||
};
|
||||
use tempfile::tempdir;
|
||||
|
||||
|
||||
@@ -31,7 +31,8 @@ fn wide_rows(ids: Range<i64>) -> anyhow::Result<Box<dyn RecordBatchReader + Send
|
||||
|
||||
async fn tune_compaction(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
// --8<-- [start:storage_compaction_tuning]
|
||||
use lancedb::table::{OptimizeAction, OptimizeOptions};
|
||||
use lancedb::table::OptimizeAction;
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
|
||||
let desired_fragment_bytes: usize = 64 * 1024;
|
||||
let average_row_bytes: usize = 1024; // Estimate from representative rows.
|
||||
|
||||
@@ -435,7 +435,7 @@ async fn dedup_query_materializes_blob_payloads_and_null_vectors() -> anyhow::Re
|
||||
table.delete("id = 5").await?;
|
||||
table
|
||||
.optimize(lancedb::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: lancedb::table::OptimizeOptions::default(),
|
||||
options: lancedb::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! Compatibility with the Optimize APIs published before the naming cleanup.
|
||||
#![allow(deprecated)]
|
||||
|
||||
use std::any::TypeId;
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow_array::{ArrayRef, Int32Array, RecordBatch};
|
||||
use lancedb::table::{
|
||||
CompactionMode, CompactionOptions, CompactionOverrides, CompactionResult, IndexOptimizeOptions,
|
||||
OptimizeAction, OptimizeDataMode, OptimizeOptions, OptimizeResult,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn released_type_paths_keep_their_meaning() {
|
||||
assert_eq!(
|
||||
TypeId::of::<OptimizeOptions>(),
|
||||
TypeId::of::<IndexOptimizeOptions>()
|
||||
);
|
||||
assert_eq!(
|
||||
TypeId::of::<CompactionOptions>(),
|
||||
TypeId::of::<lancedb::table::optimize::OptimizeOptions>()
|
||||
);
|
||||
assert_eq!(
|
||||
TypeId::of::<CompactionMode>(),
|
||||
TypeId::of::<OptimizeDataMode>()
|
||||
);
|
||||
assert_eq!(
|
||||
TypeId::of::<CompactionResult>(),
|
||||
TypeId::of::<OptimizeResult>()
|
||||
);
|
||||
let _ = OptimizeAction::Index(OptimizeOptions::default());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn released_compact_action_rewrites_without_pruning() {
|
||||
let batch =
|
||||
RecordBatch::try_from_iter([("id", Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef)])
|
||||
.unwrap();
|
||||
let db = lancedb::connect("memory://").execute().await.unwrap();
|
||||
let table = db
|
||||
.create_table("legacy", batch.clone())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table.add(batch).execute().await.unwrap();
|
||||
let stats = table
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: CompactionOptions {
|
||||
target_rows_per_fragment: 100,
|
||||
..Default::default()
|
||||
},
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stats.compaction.unwrap().fragments_removed, 2);
|
||||
assert!(stats.prune.is_none());
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 4);
|
||||
table.checkout(1).await.unwrap();
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 2);
|
||||
table.checkout_latest().await.unwrap();
|
||||
assert!(
|
||||
table
|
||||
.compact(CompactionOverrides::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.prune
|
||||
.is_none()
|
||||
);
|
||||
assert!(matches!(
|
||||
table.compact_async(CompactionOverrides::default()).await,
|
||||
Err(lancedb::Error::NotSupported { .. })
|
||||
));
|
||||
}
|
||||
Reference in New Issue
Block a user