mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
fix(sdk): align Optimize behavior and inherit Embedded policy
This commit is contained in:
@@ -1125,10 +1125,10 @@ retrying with the settings removed.
|
||||
optimizeAsync(_options?): Promise<Job<OptimizeResult>>
|
||||
```
|
||||
|
||||
Submit remote Optimize and return its durable job after acceptance.
|
||||
Submit Enterprise Optimize and return its durable job after acceptance.
|
||||
|
||||
Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires
|
||||
a compatible remote server and table Ownership plus parent Usage. Local and
|
||||
a compatible Enterprise server and table Ownership plus parent Usage. Embedded and
|
||||
historical-version handles are unsupported. Existing optimize() behavior is unchanged.
|
||||
Waiting tracks the rewrite itself and returns actual row/file statistics.
|
||||
Missing result payloads are errors; older workers can omit file counts.
|
||||
|
||||
@@ -64,7 +64,7 @@ Positive live-source-row budget across whole rewrite tasks.
|
||||
optional targetRowsPerFragment: number;
|
||||
```
|
||||
|
||||
Positive target rows per output fragment. Omitted remote values inherit table policy.
|
||||
Positive target rows per output fragment. Omitted Enterprise values inherit table policy.
|
||||
|
||||
#### Inherited from
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
# Interface: OptimizeOptions
|
||||
|
||||
Flat Optimize settings for submission and durable jobs.
|
||||
Remote jobs support data rewrites; cleanup options are Embedded-only.
|
||||
Enterprise jobs support data rewrites; cleanup options are Embedded-only.
|
||||
|
||||
## Properties
|
||||
|
||||
@@ -17,7 +17,9 @@ Remote jobs support data rewrites; cleanup options are Embedded-only.
|
||||
optional action: "rewrite_data";
|
||||
```
|
||||
|
||||
Run only data rewriting, retaining history and skipping separate index maintenance.
|
||||
Select only data rewriting, retaining history and skipping separate index maintenance.
|
||||
For convenience calls, omit for Embedded's full rewrite/prune/index cycle.
|
||||
Enterprise, durable jobs, and previews support rewriting only.
|
||||
|
||||
***
|
||||
|
||||
@@ -91,4 +93,4 @@ Positive live-source-row budget across whole rewrite tasks.
|
||||
optional targetRowsPerFragment: number;
|
||||
```
|
||||
|
||||
Positive target rows per output fragment. Omitted remote values inherit table policy.
|
||||
Positive target rows per output fragment. Omitted Enterprise values inherit table policy.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
# Interface: OptimizeResult
|
||||
|
||||
Actual committed outcome of one remote Optimize data rewrite.
|
||||
Actual committed outcome of one Enterprise Optimize data rewrite.
|
||||
|
||||
## Properties
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ even though `optimize()` bundles both in one LanceDB Embedded call.
|
||||
|
||||
On compatible Enterprise deployments, `optimize_async()` / `optimizeAsync()`
|
||||
submits SQL `OPTIMIZE ... REWRITE DATA` and returns a durable job handle.
|
||||
The table handle supplies the namespace and branch. The existing remote
|
||||
The table handle supplies the namespace and branch. The existing Enterprise
|
||||
`optimize()` call keeps returning after submission with placeholder statistics;
|
||||
use the job-returning API to wait for the actual rewrite and obtain its result.
|
||||
|
||||
@@ -102,9 +102,9 @@ if (job.id !== null) {
|
||||
```rust Rust
|
||||
use std::time::Duration;
|
||||
use lancedb::job::JobWaitOptions;
|
||||
use lancedb::table::{OptimizeResult, optimize::OptimizeOverrides};
|
||||
use lancedb::table::{OptimizeResult, optimize::OptimizeOptions};
|
||||
|
||||
let job = table.optimize_async(OptimizeOverrides {
|
||||
let job = table.optimize_async(OptimizeOptions {
|
||||
target_rows_per_fragment: Some(1000),
|
||||
batch_size: Some(128),
|
||||
..Default::default()
|
||||
@@ -133,7 +133,7 @@ Submission requires Flight SQL connectivity and, under Standard authorization,
|
||||
table Ownership plus Usage on the database and namespace hierarchy. Status,
|
||||
progress, events, and cancellation use the generic HTTP job APIs and their
|
||||
existing permissions. A wait timeout or dropping the handle does not cancel
|
||||
the job. Local tables and historical-version checkouts are unsupported by the
|
||||
the job. Embedded tables and historical-version checkouts are unsupported by the
|
||||
job-returning API; ordinary embedded `optimize()` remains available.
|
||||
|
||||
## Submit Enterprise compaction {#enterprise-manual-compaction}
|
||||
@@ -198,7 +198,7 @@ through the service catalog before creating a job.
|
||||
SQL and the CLI without `--wait` return after durable submission. The
|
||||
job-returning SDK methods above preserve the ID and return committed statistics
|
||||
when waiting completes. The CLI's `--wait` polls the same durable job and prints
|
||||
its result. A timeout leaves the job running. Legacy remote `optimize()` still
|
||||
its result. A timeout leaves the job running. Enterprise `optimize()` still
|
||||
returns after acceptance with placeholder statistics.
|
||||
|
||||
Find earlier submissions with a table-scoped list, replacing `DATABASE` with
|
||||
@@ -225,7 +225,7 @@ the job's existence; denied list/events requests return 403. Submission does not
|
||||
grant system-level access to job lists or events.
|
||||
|
||||
Manual compaction uses one worker with atomic execution and inline index
|
||||
remapping. Remote `optimize` does not prune old versions or optimize indexes;
|
||||
remapping. Enterprise `optimize` does not prune old versions or optimize indexes;
|
||||
explicit pruning, index optimization, and unsupported non-default compaction
|
||||
settings are rejected. Cleanup continues through the deployment's separate
|
||||
[cleanup policy](/maintenance/cleanup).
|
||||
@@ -372,19 +372,18 @@ attempts retain pending continuation; explicit cancellation clears it. Changing
|
||||
the effective source-row budget re-arms automatic failures recorded under a
|
||||
different budget; toggling automatic enablement alone does not reset backoff.
|
||||
|
||||
SDKs forward supplied fields and leave inheritance to the server. An explicitly
|
||||
supplied SDK-default fragment target still overrides table tuning. Rust callers
|
||||
can use `Table::optimize(OptimizeOverrides)` or
|
||||
`Table::optimize_async(OptimizeOverrides)` for that distinction: the legacy
|
||||
`OptimizeAction::RewriteDataWithOptions` path treats its default-valued Lance fragment target
|
||||
as unspecified because the options type has no presence bit.
|
||||
SDKs forward supplied fields and leave Enterprise inheritance to the server.
|
||||
Embedded resolves omitted settings from `lance.compaction.*` table configuration,
|
||||
then built-in defaults. Explicit invocation settings override policy even when
|
||||
identical to a built-in default. Rust `OptimizeOptions` fields use `Option` to
|
||||
preserve that distinction. Nullable Embedded Python settings can also be cleared
|
||||
for one invocation by explicitly passing `None`.
|
||||
|
||||
## Retraining indexes {#retrain}
|
||||
|
||||
Folding new rows into an index preserves the structure the index was trained on.
|
||||
When the data distribution has shifted enough that the index's clusters are a
|
||||
poor fit, recreate the index with `replace=True` to train it on the current data.
|
||||
The deprecated `retrain` argument to `optimize()` does not rebuild indexes.
|
||||
|
||||
This example assumes a populated table whose `vector` column has an IVF_FLAT
|
||||
index configured for L2 distance and four partitions:
|
||||
@@ -463,8 +462,9 @@ task at a time can also reduce memory use.
|
||||
</CodeBlock>
|
||||
</CodeGroup>
|
||||
|
||||
The Rust example runs compaction only. Run pruning and index optimization
|
||||
separately when needed; Python's `optimize()` includes those steps.
|
||||
Python and Rust's options-only `optimize()` calls both run Embedded's full
|
||||
rewrite, prune, and index-maintenance cycle. Select the explicit rewrite-only
|
||||
action to preserve versions and skip separate index maintenance.
|
||||
|
||||
TypeScript's `optimize()` exposes the fragment row target through
|
||||
`targetRowsPerFragment` and the scanner batch size through
|
||||
@@ -519,58 +519,10 @@ Embedded `optimize()` still waits for compaction, cleanup, and index maintenance
|
||||
returning actual statistics. Select only data rewrites with Python
|
||||
`optimize(action="rewrite_data")`, TypeScript
|
||||
`optimize({ action: "rewrite_data" })`, or Rust
|
||||
`optimize(OptimizeOverrides::default())`. Rewrite-only requests preserve old
|
||||
`optimize(OptimizeAction::RewriteData { options: OptimizeOptions::default(), remap_options: None })`. Rewrite-only requests preserve old
|
||||
versions and skip the separate index maintenance phase. Cleanup arguments cannot
|
||||
be combined with a rewrite-only action.
|
||||
|
||||
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 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
|
||||
|
||||
The SDK uses Optimize names for submission, settings, and durable results:
|
||||
|
||||
| Previous name | Current name |
|
||||
| --- | --- |
|
||||
| `CompactionResult` | `OptimizeResult` |
|
||||
| Python/TypeScript `CompactionOptions` | `OptimizeOptions` |
|
||||
| Rust `CompactionOptions` | `table::optimize::OptimizeOptions` |
|
||||
| Rust `CompactionOverrides` | `OptimizeOverrides` |
|
||||
| Rust `CompactionMode` | `OptimizeDataMode` |
|
||||
| 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` |
|
||||
|
||||
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
|
||||
`compaction_mode` field remains in Python and Rust's underlying Lance options.
|
||||
The server job type `compact`,
|
||||
table tuning key `job_types.compaction`, and realtime SSTable maintenance methods
|
||||
are unchanged.
|
||||
|
||||
### Flat Optimize options
|
||||
|
||||
Pass settings directly to both convenience and durable submissions:
|
||||
@@ -595,7 +547,7 @@ const job = await table.optimizeAsync(options);
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
|
||||
let options = OptimizeOptions {
|
||||
target_rows_per_fragment: 1000,
|
||||
target_rows_per_fragment: Some(1000),
|
||||
batch_size: Some(128),
|
||||
..Default::default()
|
||||
};
|
||||
@@ -606,10 +558,13 @@ let job = table.optimize_async(options).await?;
|
||||
Python/TypeScript Embedded convenience Optimize also accepts cleanup settings in
|
||||
the same request.
|
||||
Durable Optimize jobs reject cleanup and separate index-maintenance requests before
|
||||
submission. Rust accepts `OptimizeOptions` directly for both submission methods, and
|
||||
`OptimizeOverrides` when omission must be distinguished from explicit defaults.
|
||||
submission. Rust accepts `OptimizeOptions` directly for both submission methods. Its optional
|
||||
fields distinguish omitted settings from explicitly supplied defaults.
|
||||
Its separate index-maintenance options are `IndexOptimizeOptions`.
|
||||
`OptimizeOverrides` retains omitted-versus-explicit values when inheriting remote
|
||||
Embedded resolves omitted rewrite settings from `lance.compaction.*` table configuration,
|
||||
then Lance defaults. Explicit invocation settings take precedence, including
|
||||
values equal to built-in defaults and zero I/O buffering.
|
||||
`OptimizeOptions` retains omitted-versus-explicit values when inheriting Enterprise
|
||||
policy. No `data_options` or `dataOptions` wrapper is accepted.
|
||||
|
||||
Enterprise convenience and durable Optimize use the same SQL submission and
|
||||
|
||||
@@ -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::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";
|
||||
export const RsStorageCompactionTuning = "use 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: Some((desired_fragment_bytes / average_row_bytes).max(1)),\n batch_size: Some(16),\n num_threads: Some(1),\n ..Default::default()\n};\ntable.optimize(options).await?;\n";
|
||||
|
||||
|
||||
@@ -6007,9 +6007,7 @@ describe("durable compaction validation", () => {
|
||||
test("rejects local tables and unknown options", async () => {
|
||||
const db = await connect(`memory://compaction-job-${Date.now()}`);
|
||||
const table = await db.createTable("test", [{ id: 1 }]);
|
||||
await expect(table.optimizeAsync()).rejects.toThrow(
|
||||
"only supported on remote tables",
|
||||
);
|
||||
await expect(table.optimizeAsync()).rejects.toThrow("LanceDB Enterprise");
|
||||
await expect(
|
||||
table.optimizeAsync({ unrecognizedLimit: 1 } as never),
|
||||
).rejects.toThrow("Unsupported Optimize option");
|
||||
@@ -6080,7 +6078,7 @@ describe("Optimize action selection", () => {
|
||||
expect(stats.prune.oldVersionsRemoved).toBe(0);
|
||||
expect((await table.listVersions()).length).toBeGreaterThan(before.length);
|
||||
expect((await table.indexStats("id_idx"))?.numUnindexedRows).toBe(2);
|
||||
await table.optimize();
|
||||
await table.optimize({ targetRowsPerFragment: 100 });
|
||||
expect((await table.indexStats("id_idx"))?.numUnindexedRows).toBe(0);
|
||||
await table.checkout(1);
|
||||
expect(await table.countRows()).toBe(1);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
/** Actual committed outcome of one remote Optimize data rewrite. */
|
||||
/** Actual committed outcome of one Enterprise Optimize data rewrite. */
|
||||
export interface OptimizeResult {
|
||||
/** A bounded run left eligible work for another invocation. */
|
||||
moreWork: boolean;
|
||||
|
||||
@@ -187,9 +187,9 @@ export interface PrewarmDataOptions {
|
||||
}
|
||||
|
||||
/** Flat Optimize settings for submission and durable jobs.
|
||||
* Remote jobs support data rewrites; cleanup options are Embedded-only. */
|
||||
* Enterprise jobs support data rewrites; cleanup options are Embedded-only. */
|
||||
export interface OptimizeOptions {
|
||||
/** Positive target rows per output fragment. Omitted remote values inherit table policy. */
|
||||
/** Positive target rows per output fragment. Omitted Enterprise values inherit table policy. */
|
||||
targetRowsPerFragment?: number;
|
||||
/** Positive live-source-row budget across whole rewrite tasks. */
|
||||
maxSourceRows?: number;
|
||||
@@ -199,7 +199,9 @@ export interface OptimizeOptions {
|
||||
batchSize?: number;
|
||||
/** @deprecated Pass rewrite settings directly on OptimizeOptions. */
|
||||
compactionOptions?: CompactionOptions;
|
||||
/** Run only data rewriting, retaining history and skipping separate index maintenance. */
|
||||
/** Select only data rewriting, retaining history and skipping separate index maintenance.
|
||||
* For convenience calls, omit for Embedded's full rewrite/prune/index cycle.
|
||||
* Enterprise, durable jobs, and previews support rewriting only. */
|
||||
action?: "rewrite_data";
|
||||
/** Embedded: remove versions committed before this cutoff. Defaults to seven days ago.
|
||||
* Cannot be combined with action="rewrite_data" or used with durable Optimize jobs. */
|
||||
@@ -1319,10 +1321,10 @@ export abstract class Table {
|
||||
*/
|
||||
abstract restore(): Promise<void>;
|
||||
/**
|
||||
* Submit remote Optimize and return its durable job after acceptance.
|
||||
* Submit Enterprise Optimize and return its durable job after acceptance.
|
||||
*
|
||||
* Uses SQL OPTIMIZE, inheriting branch and namespace from this table. Requires
|
||||
* a compatible remote server and table Ownership plus parent Usage. Local and
|
||||
* a compatible Enterprise server and table Ownership plus parent Usage. Embedded and
|
||||
* historical-version handles are unsupported. Existing optimize() behavior is unchanged.
|
||||
* Waiting tracks the rewrite itself and returns actual row/file statistics.
|
||||
* Missing result payloads are errors; older workers can omit file counts.
|
||||
@@ -1337,7 +1339,7 @@ export abstract class Table {
|
||||
async optimizeAsync(
|
||||
_options?: OptimizeOptions,
|
||||
): Promise<Job<OptimizeResult>> {
|
||||
throw new Error("Optimize jobs are only supported on remote tables");
|
||||
throw new Error("Optimize jobs are only supported in LanceDB Enterprise");
|
||||
}
|
||||
|
||||
/** @deprecated Use optimizeAsync() instead. */
|
||||
|
||||
+6
-1
@@ -1057,7 +1057,12 @@ impl Table {
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let stats = if rewrite_only {
|
||||
inner.optimize(overrides).await
|
||||
inner
|
||||
.optimize(lancedb::table::OptimizeAction::RewriteData {
|
||||
options: overrides.into(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
inner
|
||||
.optimize_full_with_overrides(overrides, None, before_timestamp, delete_unverified)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of durable remote Optimize jobs."""
|
||||
"""Results of durable Enterprise Optimize jobs."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
@@ -10,7 +10,7 @@ from typing import Optional
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OptimizeResult:
|
||||
"""Actual committed outcome of one remote Optimize data rewrite.
|
||||
"""Actual committed outcome of one Enterprise Optimize data rewrite.
|
||||
|
||||
``rows_failed`` counts planned live rows that were not committed, including
|
||||
partial progress. ``more_work`` means a bounded run left eligible work for
|
||||
|
||||
@@ -1131,10 +1131,12 @@ class RemoteTable(Table):
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
def optimize(
|
||||
self, *, retrain: bool = False, **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
|
||||
yet supported in Enterprise, so this call skips them and returns
|
||||
successfully with placeholder statistics once the compaction job
|
||||
has been submitted; it does not wait for that job to finish. The
|
||||
per-job options ``target_rows_per_fragment``, ``max_source_rows``,
|
||||
@@ -1144,9 +1146,7 @@ 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
|
||||
)
|
||||
tuning, cleanup, delete_unverified, action = _split_optimize_options(options)
|
||||
return LOOP.run(
|
||||
self._table._do_optimize(
|
||||
_optimize_cleanup_since_ms(cleanup, retrain),
|
||||
|
||||
@@ -357,12 +357,12 @@ class OptimizeOptions(TypedDict, total=False):
|
||||
|
||||
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
|
||||
Unspecified options use Lance's defaults for Embedded tables. Enterprise 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
|
||||
unsupported. Omitted remote options inherit table tuning, then deployment/built-in
|
||||
defaults. The server must support these SQL options. These settings do not
|
||||
change table policy.
|
||||
unsupported. Omitted Enterprise options inherit table tuning, then
|
||||
deployment/built-in defaults. The server must support these SQL options.
|
||||
These settings do not change table policy.
|
||||
|
||||
Compaction planning is row based. Lowering ``target_rows_per_fragment``
|
||||
based on the expected row size can bound later compaction passes once
|
||||
@@ -449,16 +449,16 @@ class OptimizeOptions(TypedDict, total=False):
|
||||
"""Deprecated nested rewrite settings; pass the settings as flat keywords."""
|
||||
|
||||
cleanup_older_than: Optional[timedelta]
|
||||
"""Embedded version-retention age; unsupported by remote Optimize jobs."""
|
||||
"""Embedded version-retention age; unsupported by Enterprise 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."""
|
||||
"""Convenience calls: omit for Embedded's full maintenance cycle;
|
||||
Enterprise submits rewriting only. Jobs and previews always cover rewriting.
|
||||
The only explicit action currently supported is ``rewrite_data``.
|
||||
"""
|
||||
|
||||
|
||||
# Deprecated compatibility name; use OptimizeOptions for new code.
|
||||
@@ -471,7 +471,6 @@ def _split_optimize_options(
|
||||
Optional[Dict[str, Any]],
|
||||
Optional[timedelta],
|
||||
bool,
|
||||
bool,
|
||||
Optional[Literal["rewrite_data"]],
|
||||
]:
|
||||
"""Validate the public flat request and extract maintenance controls."""
|
||||
@@ -507,11 +506,10 @@ def _split_optimize_options(
|
||||
tuning.update(legacy)
|
||||
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):
|
||||
if durable and (cleanup_older_than is not None or delete_unverified):
|
||||
raise ValueError(
|
||||
"cleanup and index-maintenance options are unsupported by Optimize jobs"
|
||||
)
|
||||
@@ -521,7 +519,7 @@ def _split_optimize_options(
|
||||
raise ValueError(
|
||||
"action='rewrite_data' cannot be combined with cleanup options"
|
||||
)
|
||||
return tuning or None, cleanup_older_than, delete_unverified, retrain, action
|
||||
return tuning or None, cleanup_older_than, delete_unverified, action
|
||||
|
||||
|
||||
# Known distance metrics for legacy API detection
|
||||
@@ -3231,14 +3229,14 @@ class Table(ABC):
|
||||
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.
|
||||
"""Submit Enterprise Optimize 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
|
||||
[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.
|
||||
Requires a compatible Enterprise server, table Ownership and parent Usage.
|
||||
Embedded and historical-version handles are unsupported. Existing
|
||||
``optimize()`` retains its return-on-submission behavior in Enterprise.
|
||||
|
||||
``job.wait()`` waits for the actual rewrite and returns
|
||||
[OptimizeResult][lancedb.optimize.OptimizeResult]. Partial/bounded
|
||||
@@ -3253,21 +3251,25 @@ class Table(ABC):
|
||||
>>> result = job.wait() # doctest: +SKIP
|
||||
>>> print(result.rows_succeeded) # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError("Optimize jobs are only supported on remote tables")
|
||||
raise NotImplementedError(
|
||||
"Optimize jobs are only supported in LanceDB Enterprise"
|
||||
)
|
||||
|
||||
@abstractmethod
|
||||
def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
def optimize(
|
||||
self, *, retrain: bool = False, **options: Unpack[OptimizeOptions]
|
||||
) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
|
||||
.. note::
|
||||
|
||||
On a LanceDB Enterprise (remote) table, only compaction is
|
||||
On a LanceDB Enterprise (Enterprise) table, only compaction is
|
||||
currently supported. Pruning old versions and index optimization
|
||||
are silently skipped there instead of being attempted, so this
|
||||
call returns placeholder statistics (not completed work) once
|
||||
the compaction job has been submitted; it does not wait for that
|
||||
job to finish. Remote compaction supports per-job
|
||||
job to finish. Enterprise compaction supports per-job
|
||||
``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``,
|
||||
and ``batch_size``. Omitted fields inherit table tuning, then
|
||||
deployment/built-in defaults. Other non-default compaction settings raise
|
||||
@@ -5989,7 +5991,9 @@ class LanceTable(Table):
|
||||
def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]:
|
||||
return Job(LOOP.run(self._table.optimize_async(**options)))
|
||||
|
||||
def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
def optimize(
|
||||
self, *, retrain: bool = False, **options: Unpack[OptimizeOptions]
|
||||
) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
|
||||
@@ -6048,9 +6052,7 @@ 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
|
||||
)
|
||||
tuning, cleanup, delete_unverified, action = _split_optimize_options(options)
|
||||
return LOOP.run(
|
||||
self._table._do_optimize(
|
||||
_optimize_cleanup_since_ms(cleanup, retrain),
|
||||
@@ -9689,29 +9691,31 @@ class AsyncTable:
|
||||
async def optimize_async(
|
||||
self, **options: Unpack[OptimizeOptions]
|
||||
) -> AsyncJob[OptimizeResult]:
|
||||
"""Submit remote Optimize; await the returned job for actual results.
|
||||
"""Submit Enterprise Optimize; 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)
|
||||
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, **options: Unpack[OptimizeOptions]) -> OptimizeStats:
|
||||
async def optimize(
|
||||
self, *, retrain: bool = False, **options: Unpack[OptimizeOptions]
|
||||
) -> OptimizeStats:
|
||||
"""
|
||||
Optimize the on-disk data and indices for better performance.
|
||||
|
||||
.. note::
|
||||
|
||||
On a LanceDB Enterprise (remote) table, only compaction is
|
||||
On a LanceDB Enterprise (Enterprise) table, only compaction is
|
||||
currently supported. Pruning old versions and index optimization
|
||||
are silently skipped there instead of being attempted, so this
|
||||
call returns placeholder statistics (not completed work) once
|
||||
the compaction job has been submitted; it does not wait for that
|
||||
job to finish. Remote compaction supports per-job
|
||||
job to finish. Enterprise compaction supports per-job
|
||||
``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``,
|
||||
and ``batch_size``. Omitted fields inherit table tuning, then
|
||||
deployment/built-in defaults. Other non-default compaction settings raise
|
||||
@@ -9774,7 +9778,7 @@ 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 = (
|
||||
data_options, cleanup_older_than, delete_unverified, action = (
|
||||
_split_optimize_options(options)
|
||||
)
|
||||
return await self._do_optimize(
|
||||
|
||||
@@ -8750,7 +8750,10 @@ def test_remote_optimize_job_rejects_maintenance_options_before_submission(optio
|
||||
|
||||
server = UnusedServer()
|
||||
with _mock_remote_table_with_sql(server) as table:
|
||||
with pytest.raises(ValueError, match="unsupported by Optimize jobs"):
|
||||
with pytest.raises(
|
||||
(ValueError, TypeError),
|
||||
match="unsupported by Optimize jobs|Unsupported Optimize option",
|
||||
):
|
||||
table.optimize_async(**options)
|
||||
assert server.calls == 0
|
||||
|
||||
|
||||
@@ -6481,10 +6481,10 @@ async def test_optimize_action_validation(mem_db_async, kwargs):
|
||||
@pytest.mark.asyncio
|
||||
async def test_optimize_async_requires_remote(mem_db, mem_db_async):
|
||||
table = mem_db.create_table("local_job", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="only supported on remote tables"):
|
||||
with pytest.raises(NotImplementedError, match="LanceDB Enterprise"):
|
||||
table.optimize_async()
|
||||
async_table = await mem_db_async.create_table("local_job", [{"id": 1}])
|
||||
with pytest.raises(NotImplementedError, match="only supported on remote tables"):
|
||||
with pytest.raises(NotImplementedError, match="LanceDB Enterprise"):
|
||||
await async_table.optimize_async()
|
||||
assert hasattr(async_table, "compact_async")
|
||||
|
||||
@@ -6507,3 +6507,36 @@ def test_legacy_optimize_nested_settings_embedded(tmp_path):
|
||||
stats = table.optimize(compaction_options={"target_rows_per_fragment": 100})
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert table.count_rows() == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
async def test_optimize_inherits_embedded_table_config(tmp_path, asynchronous):
|
||||
seed = lancedb.connect(tmp_path).create_table("policy", [{"id": 1}])
|
||||
seed.add([{"id": 2}])
|
||||
seed.to_lance().update_config(
|
||||
{
|
||||
"lance.compaction.target_rows_per_fragment": "1",
|
||||
"lance.compaction.io_buffer_size": "4096",
|
||||
"lance.compaction.max_source_rows": "1",
|
||||
}
|
||||
)
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.open_table("policy")
|
||||
stats = await table.optimize()
|
||||
assert stats.compaction.fragments_removed == 0
|
||||
stats = await table.optimize(
|
||||
target_rows_per_fragment=100, io_buffer_size=0, max_source_rows=None
|
||||
)
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert await table.count_rows() == 2
|
||||
else:
|
||||
table = lancedb.connect(tmp_path).open_table("policy")
|
||||
stats = table.optimize()
|
||||
assert stats.compaction.fragments_removed == 0
|
||||
stats = table.optimize(
|
||||
target_rows_per_fragment=100, io_buffer_size=0, max_source_rows=None
|
||||
)
|
||||
assert stats.compaction.fragments_removed == 2
|
||||
assert table.count_rows() == 2
|
||||
|
||||
@@ -283,6 +283,7 @@ def test_optimize_public_types():
|
||||
from lancedb.table import OptimizeOptions
|
||||
|
||||
assert lancedb.OptimizeOptions is OptimizeOptions
|
||||
assert "retrain" not in OptimizeOptions.__annotations__
|
||||
assert lancedb.CompactionOptions is OptimizeOptions
|
||||
assert not hasattr(lancedb, "OptimizeDataOptions")
|
||||
assert importlib.util.find_spec("lancedb.compaction") is not None
|
||||
|
||||
@@ -14,6 +14,8 @@ 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(retrain=False), OptimizeStats)
|
||||
table.optimize_async(retrain=True) # pyright: ignore[reportCallIssue]
|
||||
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]
|
||||
|
||||
+44
-60
@@ -32,8 +32,8 @@ use lancedb::table::optimize::OptimizeOptions;
|
||||
use lancedb::table::{
|
||||
AddDataMode, ColumnAlteration, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken,
|
||||
FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget,
|
||||
IndexRemapMode, NewColumnTransform, OptimizeDataMode, OptimizeOverrides, Ref,
|
||||
RefreshColumnOptions, Table as LanceDbTable,
|
||||
IndexRemapMode, NewColumnTransform, OptimizeDataMode, Ref, RefreshColumnOptions,
|
||||
Table as LanceDbTable,
|
||||
};
|
||||
use lancedb::tokenize as lancedb_tokenize;
|
||||
use pyo3::{
|
||||
@@ -488,27 +488,10 @@ fn optional_i64_bounded_u64(value: &Bound<'_, PyAny>, name: &str) -> PyResult<Op
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Preserve Python field presence while sharing Embedded and Enterprise parsing.
|
||||
#[derive(Default)]
|
||||
struct ParsedOptimizeOptions {
|
||||
options: OptimizeOptions,
|
||||
target_specified: bool,
|
||||
}
|
||||
|
||||
impl ParsedOptimizeOptions {
|
||||
fn into_remote_overrides(self) -> PyResult<OptimizeOverrides> {
|
||||
let mut overrides = OptimizeOverrides::try_from(self.options).infer_error()?;
|
||||
if !self.target_specified {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
Ok(overrides)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_optimize_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<ParsedOptimizeOptions> {
|
||||
fn parse_optimize_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<OptimizeOptions> {
|
||||
let mut parsed = OptimizeOptions::default();
|
||||
let Some(options) = options else {
|
||||
return Ok(ParsedOptimizeOptions::default());
|
||||
return Ok(OptimizeOptions::default());
|
||||
};
|
||||
|
||||
for (key, value) in options.iter() {
|
||||
@@ -523,24 +506,44 @@ fn parse_optimize_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<Parse
|
||||
"{key} must be an integer, not a bool"
|
||||
)));
|
||||
}
|
||||
if value.is_none()
|
||||
&& matches!(
|
||||
key.as_str(),
|
||||
"max_bytes_per_file"
|
||||
| "num_threads"
|
||||
| "batch_size"
|
||||
| "io_buffer_size"
|
||||
| "compaction_mode"
|
||||
| "binary_copy_read_batch_bytes"
|
||||
| "max_source_fragments"
|
||||
| "max_source_rows"
|
||||
| "max_source_bytes"
|
||||
| "max_overlays_per_fragment"
|
||||
| "data_storage_version"
|
||||
)
|
||||
{
|
||||
parsed.cleared_fields.insert(key.clone());
|
||||
}
|
||||
match key.as_str() {
|
||||
"target_rows_per_fragment" => {
|
||||
parsed.target_rows_per_fragment = positive_u32(&value, &key)?
|
||||
parsed.target_rows_per_fragment = Some(positive_u32(&value, &key)?)
|
||||
}
|
||||
"max_rows_per_group" => parsed.max_rows_per_group = positive_u32(&value, &key)?,
|
||||
"max_rows_per_group" => parsed.max_rows_per_group = Some(positive_u32(&value, &key)?),
|
||||
"max_bytes_per_file" => parsed.max_bytes_per_file = value.extract()?,
|
||||
"materialize_deletions" => parsed.materialize_deletions = value.extract()?,
|
||||
"materialize_deletions" => parsed.materialize_deletions = Some(value.extract()?),
|
||||
"materialize_deletions_threshold" => {
|
||||
parsed.materialize_deletions_threshold = value.extract()?
|
||||
parsed.materialize_deletions_threshold = Some(value.extract()?)
|
||||
}
|
||||
"num_threads" => parsed.num_threads = optional_positive_usize(&value, &key)?,
|
||||
"batch_size" => parsed.batch_size = optional_positive_u32(&value, &key)?,
|
||||
"io_buffer_size" => parsed.io_buffer_size = optional_i64_bounded_u64(&value, &key)?,
|
||||
"defer_index_remap" => parsed.defer_index_remap = value.extract()?,
|
||||
"defer_index_remap" => parsed.defer_index_remap = Some(value.extract()?),
|
||||
"index_remap_mode" => {
|
||||
let mode: String = value.extract()?;
|
||||
parsed.index_remap_mode = IndexRemapMode::try_from(mode.as_str())
|
||||
.map_err(|err| PyValueError::new_err(err.to_string()))?;
|
||||
parsed.index_remap_mode = Some(
|
||||
IndexRemapMode::try_from(mode.as_str())
|
||||
.map_err(|err| PyValueError::new_err(err.to_string()))?,
|
||||
);
|
||||
}
|
||||
"compaction_mode" => {
|
||||
let mode: Option<String> = value.extract()?;
|
||||
@@ -557,7 +560,7 @@ fn parse_optimize_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<Parse
|
||||
"max_source_fragments" => parsed.max_source_fragments = value.extract()?,
|
||||
"max_source_rows" => parsed.max_source_rows = optional_positive_usize(&value, &key)?,
|
||||
"max_source_bytes" => parsed.max_source_bytes = optional_positive_u64(&value, &key)?,
|
||||
"excluded_fragment_ids" => parsed.excluded_fragment_ids = u32_list(&value, &key)?,
|
||||
"excluded_fragment_ids" => parsed.excluded_fragment_ids = Some(u32_list(&value, &key)?),
|
||||
"max_overlays_per_fragment" => parsed.max_overlays_per_fragment = value.extract()?,
|
||||
"data_storage_version" => {
|
||||
let version: String = value.extract()?;
|
||||
@@ -575,10 +578,7 @@ fn parse_optimize_options(options: Option<&Bound<'_, PyDict>>) -> PyResult<Parse
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ParsedOptimizeOptions {
|
||||
options: parsed,
|
||||
target_specified: options.contains("target_rows_per_fragment")?,
|
||||
})
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
/// Statistics about a compaction operation.
|
||||
@@ -2323,7 +2323,7 @@ impl Table {
|
||||
data_options: Option<&Bound<'py, PyDict>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let overrides = parse_optimize_options(data_options)?.into_remote_overrides()?;
|
||||
let overrides = parse_optimize_options(data_options)?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let job = inner.optimize_async(overrides).await.infer_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
@@ -2368,33 +2368,17 @@ impl Table {
|
||||
None
|
||||
};
|
||||
future_into_py(self_.py(), async move {
|
||||
let stats = if inner.as_native().is_some() {
|
||||
if rewrite_only {
|
||||
inner
|
||||
.optimize(lancedb::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: data_options.options,
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
inner
|
||||
.optimize_full(data_options.options, older_than, None, delete_unverified)
|
||||
.await
|
||||
}
|
||||
let stats = if rewrite_only {
|
||||
inner
|
||||
.optimize(lancedb::table::OptimizeAction::RewriteData {
|
||||
options: data_options,
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
let overrides = data_options.into_remote_overrides()?;
|
||||
if rewrite_only {
|
||||
inner.optimize(overrides).await
|
||||
} else {
|
||||
inner
|
||||
.optimize_full_with_overrides(
|
||||
overrides,
|
||||
older_than,
|
||||
None,
|
||||
delete_unverified,
|
||||
)
|
||||
.await
|
||||
}
|
||||
inner
|
||||
.optimize_full_with_options(data_options, older_than, None, delete_unverified)
|
||||
.await
|
||||
}
|
||||
.infer_error()?;
|
||||
let compaction_stats = stats.compaction.unwrap();
|
||||
|
||||
@@ -2286,7 +2286,9 @@ impl Connection {
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve coverage of released full-snapshot Compact requests.
|
||||
#[cfg(test)]
|
||||
#[allow(deprecated)]
|
||||
mod tests {
|
||||
use arrow_array::{FixedSizeListArray, Float32Array, Int32Array, RecordBatch, record_batch};
|
||||
use futures::TryStreamExt;
|
||||
@@ -2702,7 +2704,7 @@ mod tests {
|
||||
async fn indexes_and_optimize_still_apply_to_a_view() {
|
||||
use crate::index::Index;
|
||||
use crate::table::OptimizeAction;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use lance::dataset::optimize::CompactionOptions as OptimizeOptions;
|
||||
|
||||
let conn = connect("memory://").execute().await.unwrap();
|
||||
let source = conn
|
||||
@@ -2722,7 +2724,7 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(view.table().list_indices().await.unwrap().len(), 1);
|
||||
view.table()
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
// Exercise released Compact request shapes alongside the preferred API.
|
||||
#![allow(deprecated)]
|
||||
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
use arrow_array::builder::{ListBuilder, StringBuilder, StringDictionaryBuilder};
|
||||
@@ -2713,12 +2716,10 @@ async fn remote_optimize_submits_a_compaction_job_over_sql() {
|
||||
);
|
||||
|
||||
let stats = table
|
||||
.optimize(
|
||||
crate::table::optimize::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
},
|
||||
)
|
||||
.optimize(crate::table::optimize::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -2769,12 +2770,10 @@ async fn remote_optimize_on_a_branch_submits_a_with_clause_over_sql() {
|
||||
.with_branch(Some("o'brien".to_string()));
|
||||
|
||||
table
|
||||
.optimize(
|
||||
crate::table::optimize::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
},
|
||||
)
|
||||
.optimize(crate::table::optimize::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -2823,7 +2822,7 @@ async fn remote_optimize_full_skips_prune_and_index() {
|
||||
|
||||
let stats = table
|
||||
.optimize_full(
|
||||
crate::table::optimize::OptimizeOptions::default(),
|
||||
lance::dataset::optimize::CompactionOptions::default(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
@@ -2884,7 +2883,7 @@ async fn remote_optimize_full_treats_delete_unverified_false_as_default() {
|
||||
|
||||
let stats = table
|
||||
.optimize_full(
|
||||
crate::table::optimize::OptimizeOptions::default(),
|
||||
lance::dataset::optimize::CompactionOptions::default(),
|
||||
None,
|
||||
None,
|
||||
Some(false),
|
||||
@@ -2941,7 +2940,7 @@ async fn remote_optimize_full_rejects_explicit_pruning_options() {
|
||||
|
||||
let error = table
|
||||
.optimize_full(
|
||||
crate::table::optimize::OptimizeOptions::default(),
|
||||
lance::dataset::optimize::CompactionOptions::default(),
|
||||
older_than,
|
||||
before_timestamp,
|
||||
delete_unverified,
|
||||
@@ -4289,18 +4288,16 @@ async fn remote_optimize_forwards_per_job_options_on_main_and_branch() {
|
||||
)
|
||||
.with_branch(branch.map(str::to_string));
|
||||
table
|
||||
.optimize(
|
||||
crate::table::optimize::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions {
|
||||
target_rows_per_fragment: 100,
|
||||
max_source_rows: Some(500),
|
||||
io_buffer_size: Some(0),
|
||||
batch_size: Some(16),
|
||||
..Default::default()
|
||||
},
|
||||
remap_options: None,
|
||||
.optimize(crate::table::optimize::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions {
|
||||
target_rows_per_fragment: 100,
|
||||
max_source_rows: Some(500),
|
||||
io_buffer_size: Some(0),
|
||||
batch_size: Some(16),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let prefix = if branch.is_some() {
|
||||
@@ -4328,7 +4325,7 @@ 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::OptimizeOverrides;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use lance::dataset::optimize::CompactionOptions as OptimizeOptions;
|
||||
let target = OptimizeOptions::default().target_rows_per_fragment;
|
||||
for (options, suffix) in [
|
||||
(OptimizeOverrides::default(), String::new()),
|
||||
@@ -4367,7 +4364,10 @@ async fn remote_optimize_preserves_omissions_and_explicit_default_values() {
|
||||
Some(sql_client),
|
||||
);
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteData(options))
|
||||
.optimize(crate::table::OptimizeAction::RewriteData {
|
||||
options: (options).into(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
@@ -4441,9 +4441,10 @@ async fn remote_optimize_parser_errors_are_clear_without_resubmission() {
|
||||
Some(sql_client),
|
||||
);
|
||||
let error = table
|
||||
.optimize(crate::table::OptimizeAction::RewriteData(
|
||||
OptimizeOverrides::default(),
|
||||
))
|
||||
.optimize(crate::table::OptimizeAction::RewriteData {
|
||||
options: (OptimizeOverrides::default()).into(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
@@ -4481,12 +4482,14 @@ async fn remote_optimize_branch_options_are_not_dropped() {
|
||||
)
|
||||
.with_branch(Some("exp".into()));
|
||||
let error = table
|
||||
.optimize(crate::table::OptimizeAction::RewriteData(
|
||||
crate::table::optimize::OptimizeOverrides {
|
||||
.optimize(crate::table::OptimizeAction::RewriteData {
|
||||
options: (crate::table::optimize::OptimizeOverrides {
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
})
|
||||
.into(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, Error::NotSupported { .. }));
|
||||
@@ -5085,8 +5088,9 @@ async fn remote_public_prewarm_rejects_invalid_options_before_submission() {
|
||||
#[allow(deprecated)]
|
||||
async fn remote_public_optimize_options_preserve_submission_contract() {
|
||||
use crate::table::OptimizeOverrides;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use lance::dataset::optimize::CompactionOptions as OptimizeOptions;
|
||||
enum Input {
|
||||
Preferred(crate::table::optimize::OptimizeOptions),
|
||||
Options(OptimizeOptions),
|
||||
Overrides(OptimizeOverrides),
|
||||
Legacy(crate::table::CompactionOverrides),
|
||||
@@ -5096,6 +5100,18 @@ async fn remote_public_optimize_options_preserve_submission_contract() {
|
||||
io_buffer_size = 0, batch_size = 16";
|
||||
for (input, suffix) in [
|
||||
(Input::Options(OptimizeOptions::default()), String::new()),
|
||||
(
|
||||
Input::Preferred(crate::table::optimize::OptimizeOptions::default()),
|
||||
String::new(),
|
||||
),
|
||||
(
|
||||
Input::Preferred(crate::table::optimize::OptimizeOptions {
|
||||
target_rows_per_fragment: Some(default_target),
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
}),
|
||||
format!(", target_rows_per_fragment = {default_target}, io_buffer_size = 0"),
|
||||
),
|
||||
(
|
||||
Input::Legacy(crate::table::CompactionOverrides {
|
||||
io_buffer_size: Some(0),
|
||||
@@ -5179,6 +5195,7 @@ async fn remote_public_optimize_options_preserve_submission_contract() {
|
||||
.with_branch(Some("o'brien".into()));
|
||||
let table = public_remote_table(remote);
|
||||
let job = match input {
|
||||
Input::Preferred(options) => table.optimize_async(options).await.unwrap(),
|
||||
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(),
|
||||
@@ -5187,7 +5204,10 @@ async fn remote_public_optimize_options_preserve_submission_contract() {
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 0);
|
||||
let expected =
|
||||
format!("OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'o''brien'{suffix})");
|
||||
assert_eq!(*statements.lock().unwrap(), [expected.clone()]);
|
||||
assert_eq!(
|
||||
statements.lock().unwrap().as_slice(),
|
||||
std::slice::from_ref(&expected)
|
||||
);
|
||||
let result = job.wait().await.unwrap();
|
||||
assert_eq!(result.rows_succeeded, 12);
|
||||
assert_eq!(result.fragments_removed, Some(3));
|
||||
@@ -5206,8 +5226,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::optimize::OptimizeOptions;
|
||||
use crate::table::{IndexOptimizeOptions, OptimizeAction, OptimizeOverrides};
|
||||
use lance::dataset::optimize::CompactionOptions as OptimizeOptions;
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
..Default::default()
|
||||
@@ -5332,7 +5352,7 @@ async fn remote_optimize_convenience_and_durable_validate_the_same_receipt() {
|
||||
stats.compaction,
|
||||
Some(lance::dataset::optimize::CompactionMetrics::default())
|
||||
);
|
||||
assert!(stats.prune.is_none());
|
||||
assert!(stats.prune.is_some());
|
||||
})
|
||||
};
|
||||
if valid {
|
||||
@@ -5355,42 +5375,56 @@ 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),
|
||||
for preferred in [false, true] {
|
||||
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()
|
||||
})
|
||||
.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();
|
||||
};
|
||||
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 = if preferred {
|
||||
table
|
||||
.optimize(crate::table::optimize::OptimizeOptions {
|
||||
target_rows_per_fragment: Some(100),
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
} else {
|
||||
table
|
||||
.compact(crate::table::CompactionOverrides {
|
||||
target_rows_per_fragment: Some(100),
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(result.prune.is_some(), preferred);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4051,6 +4051,18 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
prune: None,
|
||||
})
|
||||
}
|
||||
#[allow(deprecated)]
|
||||
async fn compact(
|
||||
&self,
|
||||
options: crate::table::optimize::OptimizeOverrides,
|
||||
) -> Result<OptimizeStats> {
|
||||
self.optimize(OptimizeAction::RewriteData {
|
||||
options: options.into(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn optimize_async(
|
||||
&self,
|
||||
options: crate::table::optimize::OptimizeOverrides,
|
||||
@@ -4939,7 +4951,9 @@ impl TryFrom<MergeInsertBuilder> for MergeInsertRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve coverage of released full-snapshot Compact requests.
|
||||
#[cfg(test)]
|
||||
#[allow(deprecated)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -17804,8 +17818,8 @@ mod tests {
|
||||
panic!("unexpected REST request: {}", request.url().path())
|
||||
});
|
||||
let error = table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -17825,8 +17839,8 @@ mod tests {
|
||||
});
|
||||
|
||||
let error = table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: Some(Arc::new(lance::dataset::optimize::IgnoreRemap::default())),
|
||||
})
|
||||
.await
|
||||
@@ -17843,8 +17857,8 @@ mod tests {
|
||||
});
|
||||
|
||||
let error = table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions {
|
||||
target_rows_per_fragment: 17,
|
||||
max_source_bytes: Some(1024),
|
||||
..Default::default()
|
||||
@@ -17902,8 +17916,8 @@ mod tests {
|
||||
// not reject the branch itself or send a REST request
|
||||
// (see `test_optimize_requires_sql`).
|
||||
let error = branch
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! Optimize options supported by the remote SQL submission protocol.
|
||||
//! Optimize options supported by the Enterprise SQL submission protocol.
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
pub(super) fn statement(
|
||||
@@ -130,7 +130,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::error::JobFailure;
|
||||
use crate::table::OptimizeOverrides;
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use lance::dataset::optimize::CompactionOptions as OptimizeOptions;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn sql_error(code: tonic::Code, message: &str) -> Error {
|
||||
|
||||
+122
-66
@@ -908,13 +908,13 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
async fn tags(&self) -> Result<Box<dyn Tags + '_>>;
|
||||
/// Optimize the dataset.
|
||||
async fn optimize(&self, action: OptimizeAction) -> Result<OptimizeStats>;
|
||||
/// Submit remote Optimize and retain its durable job and actual outcome.
|
||||
/// Submit Enterprise Optimize and retain its durable job and actual outcome.
|
||||
async fn optimize_async(
|
||||
&self,
|
||||
_options: optimize::OptimizeOverrides,
|
||||
) -> Result<Job<OptimizeResult>> {
|
||||
Err(Error::NotSupported {
|
||||
message: "Optimize jobs are only supported on remote tables".into(),
|
||||
message: "Optimize jobs are only supported in LanceDB Enterprise".into(),
|
||||
})
|
||||
}
|
||||
/// Deprecated: use [`Self::optimize_async`].
|
||||
@@ -927,9 +927,22 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync {
|
||||
}
|
||||
|
||||
/// Deprecated: use [`Self::optimize`].
|
||||
#[deprecated(note = "use optimize with OptimizeOverrides")]
|
||||
#[deprecated(note = "use optimize with OptimizeAction::RewriteData")]
|
||||
#[allow(deprecated)]
|
||||
async fn compact(&self, options: optimize::OptimizeOverrides) -> Result<OptimizeStats> {
|
||||
self.optimize(OptimizeAction::RewriteData(options)).await
|
||||
self.optimize(OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions {
|
||||
target_rows_per_fragment: options.target_rows_per_fragment.unwrap_or_else(|| {
|
||||
lance::dataset::optimize::CompactionOptions::default().target_rows_per_fragment
|
||||
}),
|
||||
max_source_rows: options.max_source_rows,
|
||||
io_buffer_size: options.io_buffer_size,
|
||||
batch_size: options.batch_size,
|
||||
..Default::default()
|
||||
},
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Add columns to the table.
|
||||
@@ -2079,38 +2092,45 @@ impl Table {
|
||||
/// you have added or modified 100,000 or more records or run more than 20 data
|
||||
/// modification operations.
|
||||
///
|
||||
/// # LanceDB Enterprise (remote tables)
|
||||
/// Passing [`optimize::OptimizeOptions`] runs the full Embedded maintenance
|
||||
/// cycle (rewrite, prune, index maintenance), just like Python and TypeScript.
|
||||
/// Enterprise submits its supported data rewrite and returns after acceptance;
|
||||
/// convenience statistics are placeholders. Use [`Self::optimize_async`] for
|
||||
/// a durable handle and actual results. Explicit cleanup/index requests remain
|
||||
/// unsupported in Enterprise.
|
||||
///
|
||||
/// [`OptimizeAction::RewriteData`] accepts [`optimize::OptimizeOverrides`]
|
||||
/// directly, preserving omitted options and explicit default values.
|
||||
/// [`OptimizeAction::RewriteDataWithOptions`] supports per-job `target_rows_per_fragment`,
|
||||
/// `max_source_rows`, `io_buffer_size`, and `batch_size`, with no custom
|
||||
/// `remap_options`. Other non-default options, `All`, `Prune`, and `Index` return
|
||||
/// [`crate::Error::NotSupported`]. See [`OptimizeAction::RewriteDataWithOptions`] for
|
||||
/// what a remote call submits and what it does and does not wait for.
|
||||
/// Select [`OptimizeAction::RewriteData`] to preserve Embedded versions and
|
||||
/// skip separate index maintenance. Omitted settings inherit table policy;
|
||||
/// explicit values, including zero I/O buffering, override it.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # async fn optimize(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
/// use lancedb::table::OptimizeOverrides;
|
||||
/// // Rewrite only data; omitted settings retain remote table policy.
|
||||
/// table.optimize(OptimizeOverrides {
|
||||
/// io_buffer_size: Some(0),
|
||||
/// ..Default::default()
|
||||
/// use lancedb::table::{OptimizeAction, optimize::OptimizeOptions};
|
||||
/// table.optimize(OptimizeOptions { io_buffer_size: Some(0), ..Default::default() }).await?;
|
||||
/// table.optimize(OptimizeAction::RewriteData {
|
||||
/// options: OptimizeOptions { io_buffer_size: Some(0), ..Default::default() },
|
||||
/// remap_options: None,
|
||||
/// }).await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn optimize(&self, action: impl Into<OptimizeAction>) -> Result<OptimizeStats> {
|
||||
self.inner.optimize(action.into()).await
|
||||
match action.into() {
|
||||
OptimizeAction::AllWithOptions(options) => {
|
||||
self.optimize_full_with_options(options, None, None, None)
|
||||
.await
|
||||
}
|
||||
action => self.inner.optimize(action).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Submit remote Optimize and return its durable job after acceptance.
|
||||
/// Submit Enterprise Optimize and return its durable job after acceptance.
|
||||
///
|
||||
/// Uses SQL `OPTIMIZE ... REWRITE DATA` with the table handle's namespace
|
||||
/// and branch. The four fields of [`optimize::OptimizeOverrides`] retain
|
||||
/// server defaults when omitted. Requires a compatible remote SQL server
|
||||
/// and branch. Omitted [`optimize::OptimizeOptions`] fields retain table
|
||||
/// policy and server defaults. Requires a compatible Enterprise SQL server
|
||||
/// and table Ownership plus database/namespace Usage under Standard authorization.
|
||||
/// Historical-version and local handles are unsupported.
|
||||
/// Historical-version and Embedded handles are unsupported.
|
||||
///
|
||||
/// Unlike [`Self::optimize`], waiting on this handle waits for compaction
|
||||
/// itself and returns actual [`OptimizeResult`] values. Status, progress,
|
||||
@@ -2120,8 +2140,8 @@ impl Table {
|
||||
/// file counts, represented as `None`. Reopen with
|
||||
/// `connection.open_job(id).await?.into_typed::<OptimizeResult>()?`.
|
||||
///
|
||||
/// Accepts flat [`optimize::OptimizeOptions`] directly, or [`optimize::OptimizeOverrides`]
|
||||
/// when omitted values must be distinguished from explicit SDK defaults.
|
||||
/// Accepts [`optimize::OptimizeOptions`] directly. Fields use `Option` so
|
||||
/// explicit values, including SDK defaults and zero I/O buffering, override policy.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # async fn optimize(table: &lancedb::Table) -> lancedb::Result<()> {
|
||||
@@ -2139,8 +2159,8 @@ impl Table {
|
||||
self.inner.optimize_async(options).await
|
||||
}
|
||||
|
||||
/// Deprecated: use [`Self::optimize`] with [`OptimizeOverrides`].
|
||||
#[deprecated(note = "use optimize with OptimizeOverrides")]
|
||||
/// Deprecated: use [`Self::optimize`] with [`OptimizeAction::RewriteData`].
|
||||
#[deprecated(note = "use optimize with OptimizeAction::RewriteData")]
|
||||
pub async fn compact(&self, options: optimize::OptimizeOverrides) -> Result<OptimizeStats> {
|
||||
#[allow(deprecated)]
|
||||
self.inner.compact(options).await
|
||||
@@ -2165,24 +2185,34 @@ impl Table {
|
||||
before_timestamp: Option<chrono::DateTime<chrono::Utc>>,
|
||||
delete_unverified: Option<bool>,
|
||||
) -> Result<OptimizeStats> {
|
||||
if self.as_native().is_some() {
|
||||
return self
|
||||
.optimize_full(
|
||||
options.into_options(),
|
||||
older_than,
|
||||
before_timestamp,
|
||||
delete_unverified,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if older_than.is_some() || before_timestamp.is_some() || delete_unverified == Some(true) {
|
||||
return Err(Error::NotSupported { message: "pruning is not supported in LanceDB Enterprise; omit pruning options to run compaction only".into() });
|
||||
}
|
||||
let stats = self.optimize(options).await?;
|
||||
Ok(OptimizeStats {
|
||||
compaction: stats.compaction,
|
||||
prune: Some(RemovalStats::default()),
|
||||
})
|
||||
self.optimize_full_with_options(
|
||||
options.into(),
|
||||
older_than,
|
||||
before_timestamp,
|
||||
delete_unverified,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Language-binding entry point retaining all provided rewrite fields.
|
||||
#[doc(hidden)]
|
||||
pub async fn optimize_full_with_options(
|
||||
&self,
|
||||
options: optimize::OptimizeOptions,
|
||||
older_than: Option<chrono::Duration>,
|
||||
before_timestamp: Option<chrono::DateTime<chrono::Utc>>,
|
||||
delete_unverified: Option<bool>,
|
||||
) -> Result<OptimizeStats> {
|
||||
self.optimize_full_action(
|
||||
OptimizeAction::RewriteData {
|
||||
options,
|
||||
remap_options: None,
|
||||
},
|
||||
older_than,
|
||||
before_timestamp,
|
||||
delete_unverified,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Prune versions committed before an absolute timestamp.
|
||||
@@ -2213,11 +2243,11 @@ impl Table {
|
||||
}
|
||||
|
||||
/// Run the maintenance cycle used by language bindings' `optimize()`
|
||||
/// convenience method: compact, then -- on a local table -- prune and
|
||||
/// convenience method: compact, then -- on a Embedded table -- prune and
|
||||
/// optimize indices.
|
||||
///
|
||||
/// This is an internal entry point for language bindings. On a remote
|
||||
/// table (LanceDB Enterprise) only [`OptimizeAction::RewriteDataWithOptions`] with its
|
||||
/// This is an internal entry point for language bindings. On a Enterprise
|
||||
/// table (LanceDB Enterprise) only [`OptimizeAction::RewriteData`] with its
|
||||
/// supported per-job options is supported. A caller asking for anything pruning-related
|
||||
/// (`older_than`, `before_timestamp`, or `delete_unverified: Some(true)`)
|
||||
/// gets `NotSupported` before anything is submitted, the same way
|
||||
@@ -2228,12 +2258,32 @@ impl Table {
|
||||
/// failed, since by this point the compaction job has already been
|
||||
/// durably submitted and a caller retrying on that failure would
|
||||
/// resubmit it. The returned prune stats are zeroed in that case. See
|
||||
/// [`OptimizeAction::RewriteDataWithOptions`] for what the submission does and does not
|
||||
/// [`OptimizeAction::RewriteData`] for what the submission does and does not
|
||||
/// wait for.
|
||||
#[doc(hidden)]
|
||||
#[allow(deprecated)]
|
||||
pub async fn optimize_full(
|
||||
&self,
|
||||
data_options: optimize::OptimizeOptions,
|
||||
data_options: lance::dataset::optimize::CompactionOptions,
|
||||
older_than: Option<chrono::Duration>,
|
||||
before_timestamp: Option<chrono::DateTime<chrono::Utc>>,
|
||||
delete_unverified: Option<bool>,
|
||||
) -> Result<OptimizeStats> {
|
||||
self.optimize_full_action(
|
||||
OptimizeAction::Compact {
|
||||
options: data_options,
|
||||
remap_options: None,
|
||||
},
|
||||
older_than,
|
||||
before_timestamp,
|
||||
delete_unverified,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn optimize_full_action(
|
||||
&self,
|
||||
action: OptimizeAction,
|
||||
older_than: Option<chrono::Duration>,
|
||||
before_timestamp: Option<chrono::DateTime<chrono::Utc>>,
|
||||
delete_unverified: Option<bool>,
|
||||
@@ -2252,13 +2302,7 @@ impl Table {
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
let compaction = self
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: data_options,
|
||||
remap_options: None,
|
||||
})
|
||||
.await?
|
||||
.compaction;
|
||||
let compaction = self.inner.optimize(action).await?.compaction;
|
||||
if is_remote {
|
||||
return Ok(OptimizeStats {
|
||||
compaction,
|
||||
@@ -2270,15 +2314,17 @@ impl Table {
|
||||
.await?
|
||||
.prune
|
||||
} else {
|
||||
self.optimize(OptimizeAction::Prune {
|
||||
older_than,
|
||||
delete_unverified,
|
||||
error_if_tagged_old_versions: None,
|
||||
})
|
||||
.await?
|
||||
.prune
|
||||
self.inner
|
||||
.optimize(OptimizeAction::Prune {
|
||||
older_than,
|
||||
delete_unverified,
|
||||
error_if_tagged_old_versions: None,
|
||||
})
|
||||
.await?
|
||||
.prune
|
||||
};
|
||||
self.optimize(OptimizeAction::Index(IndexOptimizeOptions::default()))
|
||||
self.inner
|
||||
.optimize(OptimizeAction::Index(IndexOptimizeOptions::default()))
|
||||
.await?;
|
||||
Ok(OptimizeStats { compaction, prune })
|
||||
}
|
||||
@@ -4605,6 +4651,15 @@ impl BaseTable for NativeTable {
|
||||
optimize::execute_optimize(self, action).await
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
async fn compact(&self, options: optimize::OptimizeOverrides) -> Result<OptimizeStats> {
|
||||
self.optimize(OptimizeAction::RewriteData {
|
||||
options: options.into(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn add_columns(
|
||||
&self,
|
||||
transforms: NewColumnTransform,
|
||||
@@ -5036,6 +5091,7 @@ pub struct FragmentSummaryStats {
|
||||
pub p99: usize,
|
||||
}
|
||||
|
||||
// Preserve coverage of released full-snapshot Compact requests.
|
||||
#[cfg(test)]
|
||||
#[allow(deprecated)]
|
||||
mod tests {
|
||||
@@ -7158,8 +7214,8 @@ mod tests {
|
||||
|
||||
// Compaction materializes the deletions.
|
||||
table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: optimize::OptimizeOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions {
|
||||
target_rows_per_fragment: 1000,
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -544,7 +544,9 @@ impl NativeTable {
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve coverage of released full-snapshot Compact requests.
|
||||
#[cfg(test)]
|
||||
#[allow(deprecated)]
|
||||
mod tests {
|
||||
use lance::index::DatasetIndexExt;
|
||||
use std::sync::Arc;
|
||||
@@ -573,7 +575,8 @@ mod tests {
|
||||
IvfHnswFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder,
|
||||
};
|
||||
use crate::query::{ExecutableQuery, QueryBase};
|
||||
use crate::table::optimize::{OptimizeAction, OptimizeOptions};
|
||||
use crate::table::optimize::OptimizeAction;
|
||||
use lance::dataset::optimize::CompactionOptions as OptimizeOptions;
|
||||
use lance_index::scalar::FullTextSearchQuery;
|
||||
use lance_index::scalar::inverted::query::{FtsQuery, MatchQuery};
|
||||
|
||||
@@ -2559,7 +2562,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: OptimizeOptions {
|
||||
target_rows_per_fragment: 2_000,
|
||||
defer_index_remap: true,
|
||||
|
||||
+361
-164
@@ -28,26 +28,198 @@ use log::{debug, info};
|
||||
use super::NativeTable;
|
||||
use crate::error::{Error, Result};
|
||||
pub use chrono::Duration;
|
||||
pub use lance::dataset::optimize::{
|
||||
CompactionMode as OptimizeDataMode, CompactionOptions as OptimizeOptions, IndexRemapMode,
|
||||
};
|
||||
use lance::dataset::optimize::CompactionOptions as LanceOptimizeOptions;
|
||||
pub use lance::dataset::optimize::{CompactionMode as OptimizeDataMode, IndexRemapMode};
|
||||
|
||||
/// Deprecated: use [`OptimizeOptions`].
|
||||
#[deprecated(note = "use table::optimize::OptimizeOptions")]
|
||||
pub type CompactionOptions = OptimizeOptions;
|
||||
pub type CompactionOptions = LanceOptimizeOptions;
|
||||
/// Deprecated: use [`OptimizeDataMode`].
|
||||
#[deprecated(note = "use OptimizeDataMode")]
|
||||
pub type CompactionMode = OptimizeDataMode;
|
||||
/// Deprecated: use [`OptimizeOverrides`].
|
||||
#[deprecated(note = "use OptimizeOverrides")]
|
||||
/// Deprecated: use [`OptimizeOptions`].
|
||||
#[deprecated(note = "use table::optimize::OptimizeOptions")]
|
||||
pub type CompactionOverrides = OptimizeOverrides;
|
||||
/// Deprecated: use [`OptimizeResult`].
|
||||
#[deprecated(note = "use OptimizeResult")]
|
||||
pub type CompactionResult = OptimizeResult;
|
||||
|
||||
/// Per-invocation Optimize settings. Omitted fields inherit Embedded table
|
||||
/// `lance.compaction.*` settings or Enterprise table policy, then built-in defaults.
|
||||
/// Explicit values, including zero I/O buffering, override table policy.
|
||||
///
|
||||
/// Passing these settings to [`crate::Table::optimize`] runs Embedded's full
|
||||
/// maintenance cycle or submits Enterprise data rewriting. Select
|
||||
/// [`OptimizeAction::RewriteData`] explicitly to rewrite only Embedded data.
|
||||
/// Durable jobs and previews cover data rewriting only. Enterprise supports
|
||||
/// `target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and `batch_size`;
|
||||
/// other non-default settings and custom remappers are Embedded-only.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct OptimizeOptions {
|
||||
/// Override Lance data-rewrite `target_rows_per_fragment`; `None` inherits table policy.
|
||||
pub target_rows_per_fragment: Option<usize>,
|
||||
/// Override Lance data-rewrite `max_rows_per_group`; `None` inherits table policy.
|
||||
pub max_rows_per_group: Option<usize>,
|
||||
/// Override Lance data-rewrite `max_bytes_per_file`; `None` inherits table policy.
|
||||
pub max_bytes_per_file: Option<usize>,
|
||||
/// Override Lance data-rewrite `min_bytes_per_file`; `None` inherits table policy.
|
||||
pub min_bytes_per_file: Option<usize>,
|
||||
/// Override Lance data-rewrite `materialize_deletions`; `None` inherits table policy.
|
||||
pub materialize_deletions: Option<bool>,
|
||||
/// Override Lance data-rewrite `materialize_deletions_threshold`; `None` inherits table policy.
|
||||
pub materialize_deletions_threshold: Option<f32>,
|
||||
/// Override Lance data-rewrite `num_threads`; `None` inherits table policy.
|
||||
pub num_threads: Option<usize>,
|
||||
/// Override Lance data-rewrite `batch_size`; `None` inherits table policy.
|
||||
pub batch_size: Option<usize>,
|
||||
/// Override Lance data-rewrite `io_buffer_size`; `None` inherits table policy.
|
||||
pub io_buffer_size: Option<u64>,
|
||||
/// Override Lance data-rewrite `defer_index_remap`; `None` inherits table policy.
|
||||
pub defer_index_remap: Option<bool>,
|
||||
/// Override Lance data-rewrite `index_remap_mode`; `None` inherits table policy.
|
||||
pub index_remap_mode: Option<IndexRemapMode>,
|
||||
/// Override Lance data-rewrite `compaction_mode`; `None` inherits table policy.
|
||||
pub compaction_mode: Option<OptimizeDataMode>,
|
||||
/// Override Lance data-rewrite `binary_copy_read_batch_bytes`; `None` inherits table policy.
|
||||
pub binary_copy_read_batch_bytes: Option<usize>,
|
||||
/// Override Lance data-rewrite `max_source_fragments`; `None` inherits table policy.
|
||||
pub max_source_fragments: Option<usize>,
|
||||
/// Override Lance data-rewrite `max_source_rows`; `None` inherits table policy.
|
||||
pub max_source_rows: Option<usize>,
|
||||
/// Override Lance data-rewrite `max_source_bytes`; `None` inherits table policy.
|
||||
pub max_source_bytes: Option<u64>,
|
||||
/// Override Lance data-rewrite `source_budget_mode`; `None` inherits table policy.
|
||||
pub source_budget_mode: Option<lance::dataset::optimize::SourceBudgetMode>,
|
||||
/// Override Lance data-rewrite `excluded_fragment_ids`; `None` inherits table policy.
|
||||
pub excluded_fragment_ids: Option<Vec<u32>>,
|
||||
/// Override Lance data-rewrite `max_overlays_per_fragment`; `None` inherits table policy.
|
||||
pub max_overlays_per_fragment: Option<usize>,
|
||||
/// Override Lance data-rewrite `max_data_files_per_fragment`; `None` inherits table policy.
|
||||
pub max_data_files_per_fragment: Option<usize>,
|
||||
/// Override Lance data-rewrite `scope`; `None` inherits table policy.
|
||||
pub scope: Option<lance::dataset::optimize::CompactionScope>,
|
||||
/// Override Lance data-rewrite `data_storage_version`; `None` inherits table policy.
|
||||
pub data_storage_version: Option<crate::connection::LanceFileVersion>,
|
||||
/// Override Lance data-rewrite `transaction_properties`; `None` inherits table policy.
|
||||
pub transaction_properties: Option<Arc<std::collections::HashMap<String, String>>>,
|
||||
/// Override Lance data-rewrite `data_cache_bytes`; `None` inherits table policy.
|
||||
pub data_cache_bytes: Option<u64>,
|
||||
// Python's released nullable settings distinguish explicit None from omission.
|
||||
// Public only to allow Rust struct-update syntax; callers normally leave empty.
|
||||
#[doc(hidden)]
|
||||
pub cleared_fields: HashSet<String>,
|
||||
}
|
||||
|
||||
impl OptimizeOptions {
|
||||
fn resolve(
|
||||
self,
|
||||
config: &std::collections::HashMap<String, String>,
|
||||
) -> Result<LanceOptimizeOptions> {
|
||||
let mut resolved = LanceOptimizeOptions::from_dataset_config(config)?;
|
||||
for field in &self.cleared_fields {
|
||||
match field.as_str() {
|
||||
"max_bytes_per_file" => resolved.max_bytes_per_file = None,
|
||||
"min_bytes_per_file" => resolved.min_bytes_per_file = None,
|
||||
"num_threads" => resolved.num_threads = None,
|
||||
"batch_size" => resolved.batch_size = None,
|
||||
"io_buffer_size" => resolved.io_buffer_size = None,
|
||||
"compaction_mode" => resolved.compaction_mode = None,
|
||||
"binary_copy_read_batch_bytes" => resolved.binary_copy_read_batch_bytes = None,
|
||||
"max_source_fragments" => resolved.max_source_fragments = None,
|
||||
"max_source_rows" => resolved.max_source_rows = None,
|
||||
"max_source_bytes" => resolved.max_source_bytes = None,
|
||||
"max_overlays_per_fragment" => resolved.max_overlays_per_fragment = None,
|
||||
"max_data_files_per_fragment" => resolved.max_data_files_per_fragment = None,
|
||||
"data_storage_version" => resolved.data_storage_version = None,
|
||||
"transaction_properties" => resolved.transaction_properties = None,
|
||||
"data_cache_bytes" => resolved.data_cache_bytes = None,
|
||||
_ => {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!("Unknown nullable Optimize setting: {field}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(value) = self.target_rows_per_fragment {
|
||||
resolved.target_rows_per_fragment = value;
|
||||
}
|
||||
if let Some(value) = self.max_rows_per_group {
|
||||
resolved.max_rows_per_group = value;
|
||||
}
|
||||
if let Some(value) = self.max_bytes_per_file {
|
||||
resolved.max_bytes_per_file = Some(value);
|
||||
}
|
||||
if let Some(value) = self.min_bytes_per_file {
|
||||
resolved.min_bytes_per_file = Some(value);
|
||||
}
|
||||
if let Some(value) = self.materialize_deletions {
|
||||
resolved.materialize_deletions = value;
|
||||
}
|
||||
if let Some(value) = self.materialize_deletions_threshold {
|
||||
resolved.materialize_deletions_threshold = value;
|
||||
}
|
||||
if let Some(value) = self.num_threads {
|
||||
resolved.num_threads = Some(value);
|
||||
}
|
||||
if let Some(value) = self.batch_size {
|
||||
resolved.batch_size = Some(value);
|
||||
}
|
||||
if let Some(value) = self.io_buffer_size {
|
||||
resolved.io_buffer_size = Some(value);
|
||||
}
|
||||
if let Some(value) = self.defer_index_remap {
|
||||
resolved.defer_index_remap = value;
|
||||
}
|
||||
if let Some(value) = self.index_remap_mode {
|
||||
resolved.index_remap_mode = value;
|
||||
}
|
||||
if let Some(value) = self.compaction_mode {
|
||||
resolved.compaction_mode = Some(value);
|
||||
}
|
||||
if let Some(value) = self.binary_copy_read_batch_bytes {
|
||||
resolved.binary_copy_read_batch_bytes = Some(value);
|
||||
}
|
||||
if let Some(value) = self.max_source_fragments {
|
||||
resolved.max_source_fragments = Some(value);
|
||||
}
|
||||
if let Some(value) = self.max_source_rows {
|
||||
resolved.max_source_rows = Some(value);
|
||||
}
|
||||
if let Some(value) = self.max_source_bytes {
|
||||
resolved.max_source_bytes = Some(value);
|
||||
}
|
||||
if let Some(value) = self.source_budget_mode {
|
||||
resolved.source_budget_mode = value;
|
||||
}
|
||||
if let Some(value) = self.excluded_fragment_ids {
|
||||
resolved.excluded_fragment_ids = value;
|
||||
}
|
||||
if let Some(value) = self.max_overlays_per_fragment {
|
||||
resolved.max_overlays_per_fragment = Some(value);
|
||||
}
|
||||
if let Some(value) = self.max_data_files_per_fragment {
|
||||
resolved.max_data_files_per_fragment = Some(value);
|
||||
}
|
||||
if let Some(value) = self.scope {
|
||||
resolved.scope = value;
|
||||
}
|
||||
if let Some(value) = self.data_storage_version {
|
||||
resolved.data_storage_version = Some(value);
|
||||
}
|
||||
if let Some(value) = self.transaction_properties {
|
||||
resolved.transaction_properties = Some(value);
|
||||
}
|
||||
if let Some(value) = self.data_cache_bytes {
|
||||
resolved.data_cache_bytes = Some(value);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
/// Actual outcome of one Enterprise Optimize data rewrite, returned by its job handle.
|
||||
///
|
||||
/// A successful bounded run can leave more work for another invocation. A
|
||||
/// partial commit reports uncommitted rows rather than inventing file counts.
|
||||
@@ -139,7 +311,7 @@ fn oversized_sq_partition(
|
||||
|
||||
async fn validate_sq_index_remapping(
|
||||
dataset: &lance::Dataset,
|
||||
options: &OptimizeOptions,
|
||||
options: &LanceOptimizeOptions,
|
||||
has_custom_remapper: bool,
|
||||
) -> Result<CompactionPlan> {
|
||||
let plan = plan_compaction(dataset, options).await?;
|
||||
@@ -228,9 +400,9 @@ async fn validate_sq_index_remapping(
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Optional compaction tuning. Remote tables inherit omitted values from table
|
||||
/// policy, then deployment/built-in defaults. Explicit values, including a zero
|
||||
/// I/O budget, take precedence. Local tables use Lance defaults for omissions.
|
||||
/// Four common rewrite settings, retained for compatibility. Prefer
|
||||
/// [`OptimizeOptions`] for the complete Embedded tuning surface. Omitted fields
|
||||
/// inherit table policy, then built-in defaults; explicit zero I/O buffering wins.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct OptimizeOverrides {
|
||||
pub target_rows_per_fragment: Option<usize>,
|
||||
@@ -240,31 +412,18 @@ pub struct OptimizeOverrides {
|
||||
pub batch_size: Option<usize>,
|
||||
}
|
||||
|
||||
impl OptimizeOverrides {
|
||||
pub(crate) fn into_options(self) -> OptimizeOptions {
|
||||
let mut options = OptimizeOptions::default();
|
||||
if let Some(target) = self.target_rows_per_fragment {
|
||||
options.target_rows_per_fragment = target;
|
||||
}
|
||||
options.max_source_rows = self.max_source_rows;
|
||||
options.io_buffer_size = self.io_buffer_size;
|
||||
options.batch_size = self.batch_size;
|
||||
options
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<OptimizeOptions> for OptimizeOverrides {
|
||||
impl TryFrom<LanceOptimizeOptions> for OptimizeOverrides {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(options: OptimizeOptions) -> Result<Self> {
|
||||
fn try_from(options: LanceOptimizeOptions) -> Result<Self> {
|
||||
let mut remaining = options.clone();
|
||||
let defaults = OptimizeOptions::default();
|
||||
let defaults = LanceOptimizeOptions::default();
|
||||
remaining.target_rows_per_fragment = defaults.target_rows_per_fragment;
|
||||
remaining.max_source_rows = defaults.max_source_rows;
|
||||
remaining.io_buffer_size = defaults.io_buffer_size;
|
||||
remaining.batch_size = defaults.batch_size;
|
||||
if remaining != defaults {
|
||||
return Err(Error::NotSupported { message: "remote OptimizeOptions support only target_rows_per_fragment, max_source_rows, io_buffer_size, and batch_size; other options must retain their defaults".into() });
|
||||
return Err(Error::NotSupported { message: "Enterprise OptimizeOptions support only target_rows_per_fragment, max_source_rows, io_buffer_size, and batch_size; other options must retain their defaults".into() });
|
||||
}
|
||||
Ok(Self {
|
||||
target_rows_per_fragment: Some(options.target_rows_per_fragment),
|
||||
@@ -275,15 +434,43 @@ impl TryFrom<OptimizeOptions> for OptimizeOverrides {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<OptimizeOverrides> for OptimizeAction {
|
||||
impl From<OptimizeOverrides> for OptimizeOptions {
|
||||
fn from(options: OptimizeOverrides) -> Self {
|
||||
Self::RewriteData(options)
|
||||
Self {
|
||||
target_rows_per_fragment: options.target_rows_per_fragment,
|
||||
max_source_rows: options.max_source_rows,
|
||||
io_buffer_size: options.io_buffer_size,
|
||||
batch_size: options.batch_size,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<OptimizeOptions> for OptimizeOverrides {
|
||||
type Error = Error;
|
||||
fn try_from(options: OptimizeOptions) -> Result<Self> {
|
||||
let target = options.target_rows_per_fragment;
|
||||
let mut resolved = Self::try_from(options.resolve(&Default::default())?)?;
|
||||
resolved.target_rows_per_fragment = target;
|
||||
Ok(resolved)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<OptimizeOverrides> for OptimizeAction {
|
||||
fn from(options: OptimizeOverrides) -> Self {
|
||||
Self::AllWithOptions(options.into())
|
||||
}
|
||||
}
|
||||
impl From<OptimizeOptions> for OptimizeAction {
|
||||
fn from(options: OptimizeOptions) -> Self {
|
||||
Self::RewriteDataWithOptions {
|
||||
Self::AllWithOptions(options)
|
||||
}
|
||||
}
|
||||
// Preserve full-snapshot Lance options through the deprecated compatibility path.
|
||||
#[allow(deprecated)]
|
||||
impl From<LanceOptimizeOptions> for OptimizeAction {
|
||||
fn from(options: LanceOptimizeOptions) -> Self {
|
||||
Self::Compact {
|
||||
options,
|
||||
remap_options: None,
|
||||
}
|
||||
@@ -298,85 +485,24 @@ impl From<OptimizeOptions> for OptimizeAction {
|
||||
/// By default, it optimizes everything, as [`OptimizeAction::All`].
|
||||
#[derive(Default)]
|
||||
pub enum OptimizeAction {
|
||||
/// Rewrite data using optional settings. Omitted values retain Enterprise
|
||||
/// table policy; Embedded uses Lance defaults. This does not prune versions
|
||||
/// or run the separate index-maintenance phase.
|
||||
RewriteData(OptimizeOverrides),
|
||||
/// Run all optimizations with default values
|
||||
/// Run all Embedded optimizations using table configuration and defaults.
|
||||
#[default]
|
||||
All,
|
||||
/// Compacts files in the dataset
|
||||
///
|
||||
/// LanceDb uses a readonly filesystem for performance and safe concurrency. Every time
|
||||
/// new data is added it will be added into new files. Small files
|
||||
/// can hurt both read and write performance. Compaction will merge small files
|
||||
/// into larger ones.
|
||||
///
|
||||
/// All operations that modify data (add, delete, update, merge insert, etc.) will create
|
||||
/// new files. If these operations are run frequently then compaction should run frequently.
|
||||
///
|
||||
/// If these operations are never run (search only) then compaction is not necessary.
|
||||
///
|
||||
/// # LanceDB Enterprise (remote tables)
|
||||
///
|
||||
/// A remote table supports per-job `target_rows_per_fragment`,
|
||||
/// `max_source_rows`, `io_buffer_size`, and `batch_size`. Other non-default
|
||||
/// options and custom `remap_options` return [`crate::Error::NotSupported`]
|
||||
/// before submission. The server must support these SQL options; errors
|
||||
/// from older servers are returned without dropping the settings.
|
||||
/// The source-row budget admits whole tasks. On current Enterprise servers,
|
||||
/// worker planning fails if the budget cannot admit the first useful task,
|
||||
/// reporting its required live rows and source fragment count. Older servers
|
||||
/// may instead finish without rewriting data in this case.
|
||||
/// Zero I/O buffer size disables byte-based I/O
|
||||
/// backpressure. Use a positive size to limit I/O read-ahead; this is not a
|
||||
/// total-memory limit. Row targets, source-row budgets, and batch sizes must
|
||||
/// be positive.
|
||||
/// The Lance options type cannot distinguish an omitted fragment target
|
||||
/// from its default value; that default is treated as unspecified remotely.
|
||||
/// Use [`crate::Table::optimize`] with [`OptimizeOverrides`] to explicitly
|
||||
/// override a table target with the Lance default value.
|
||||
/// Omitted options inherit table tuning, then deployment/built-in defaults; options
|
||||
/// affect only this job, without changing ongoing table policy.
|
||||
///
|
||||
/// It submits a durable
|
||||
/// compaction job to the server over SQL and waits for that submission to
|
||||
/// be confirmed, not for compaction itself to finish: the job then runs
|
||||
/// asynchronously on the server, so this call can return well before the
|
||||
/// data is actually compacted. Because of that, the returned
|
||||
/// [`OptimizeStats::compaction`] is a zeroed [`CompactionMetrics`]
|
||||
/// placeholder rather than the real counts a local table reports.
|
||||
///
|
||||
/// ```
|
||||
/// use lancedb::{Table, table::{optimize::OptimizeOptions, OptimizeAction}};
|
||||
/// # async fn optimize(table: &Table) -> lancedb::Result<()> {
|
||||
/// table.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
/// options: OptimizeOptions {
|
||||
/// target_rows_per_fragment: 100_000,
|
||||
/// max_source_rows: Some(1_000_000),
|
||||
/// io_buffer_size: Some(64 * 1024 * 1024),
|
||||
/// batch_size: Some(1024),
|
||||
/// ..Default::default()
|
||||
/// },
|
||||
/// remap_options: None,
|
||||
/// }).await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// A branch-scoped table handle compacts that branch. Current Enterprise
|
||||
/// servers validate the table and branch through the service catalog before
|
||||
/// creating the compaction job, so a nonexistent branch fails submission.
|
||||
/// Older servers may accept submission and fail the compaction job
|
||||
/// asynchronously instead.
|
||||
RewriteDataWithOptions {
|
||||
/// Run the convenience maintenance cycle with per-invocation settings.
|
||||
/// Embedded rewrites data, prunes versions, and optimizes indexes. Enterprise
|
||||
/// submits only its supported data rewrite, returning after acceptance.
|
||||
AllWithOptions(OptimizeOptions),
|
||||
/// Rewrite only data, preserving versions and skipping separate index maintenance.
|
||||
/// Settings inherit table policy. Custom remappers are Embedded-only.
|
||||
RewriteData {
|
||||
options: OptimizeOptions,
|
||||
remap_options: Option<Arc<dyn IndexRemapperOptions>>,
|
||||
},
|
||||
/// Deprecated spelling of [`Self::RewriteDataWithOptions`].
|
||||
#[deprecated(note = "use RewriteDataWithOptions or RewriteData")]
|
||||
/// Deprecated full-snapshot Lance options. Use [`Self::RewriteData`] with
|
||||
/// [`OptimizeOptions`] to preserve field presence and inherit table policy.
|
||||
#[deprecated(note = "use RewriteData with OptimizeOptions")]
|
||||
Compact {
|
||||
options: OptimizeOptions,
|
||||
options: LanceOptimizeOptions,
|
||||
remap_options: Option<Arc<dyn IndexRemapperOptions>>,
|
||||
},
|
||||
/// Prune old version of datasets
|
||||
@@ -431,34 +557,25 @@ impl OptimizeAction {
|
||||
#[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 \
|
||||
Enterprise; omit remap_options to use the server's managed, \
|
||||
index-safe compaction path."
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
Self::AllWithOptions(options)
|
||||
| Self::RewriteData { options, remap_options: None } => options.try_into(),
|
||||
Self::Compact { options, remap_options: None } => {
|
||||
let target = options.target_rows_per_fragment;
|
||||
let mut overrides = crate::table::optimize::OptimizeOverrides::try_from(options)?;
|
||||
if target == crate::table::optimize::OptimizeOptions::default().target_rows_per_fragment {
|
||||
let mut overrides = OptimizeOverrides::try_from(options)?;
|
||||
// Only the deprecated full-snapshot conversion treats the old
|
||||
// default target as omitted; preferred options retain presence.
|
||||
if target == LanceOptimizeOptions::default().target_rows_per_fragment {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
Ok(overrides)
|
||||
}
|
||||
_ => {
|
||||
Err(Error::NotSupported {
|
||||
message: "optimize supports only data rewrites in LanceDB Enterprise; \
|
||||
version pruning and separate index optimization are unsupported. \
|
||||
Use OptimizeAction::RewriteData or OptimizeAction::RewriteDataWithOptions."
|
||||
.into(),
|
||||
})
|
||||
}
|
||||
Self::RewriteData { remap_options: Some(_), .. }
|
||||
| Self::Compact { remap_options: Some(_), .. } => Err(Error::NotSupported {
|
||||
message: "a custom index remap strategy is not supported in LanceDB Enterprise; omit remap_options to use the server's managed, index-safe compaction path.".into(),
|
||||
}),
|
||||
_ => Err(Error::NotSupported {
|
||||
message: "Optimize jobs support only data rewriting in LanceDB Enterprise; version pruning and separate index optimization are unsupported. Use OptimizeOptions or OptimizeAction::RewriteData.".into(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -566,13 +683,32 @@ pub(crate) async fn cleanup_old_versions_before(
|
||||
/// for faster reads.
|
||||
///
|
||||
/// This calls into [lance::dataset::optimize::compact_files_with_planner].
|
||||
pub(crate) enum RewriteOptions {
|
||||
Policy(OptimizeOptions),
|
||||
Resolved(LanceOptimizeOptions),
|
||||
}
|
||||
impl From<OptimizeOptions> for RewriteOptions {
|
||||
fn from(options: OptimizeOptions) -> Self {
|
||||
Self::Policy(options)
|
||||
}
|
||||
}
|
||||
impl From<LanceOptimizeOptions> for RewriteOptions {
|
||||
fn from(options: LanceOptimizeOptions) -> Self {
|
||||
Self::Resolved(options)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn compact_files_impl(
|
||||
table: &NativeTable,
|
||||
options: OptimizeOptions,
|
||||
options: impl Into<RewriteOptions>,
|
||||
remap_options: Option<Arc<dyn IndexRemapperOptions>>,
|
||||
) -> Result<CompactionMetrics> {
|
||||
table.dataset.ensure_mutable()?;
|
||||
let mut dataset = (*table.dataset.get().await?).clone();
|
||||
let options = match options.into() {
|
||||
RewriteOptions::Policy(options) => options.resolve(&dataset.manifest().config)?,
|
||||
RewriteOptions::Resolved(options) => options,
|
||||
};
|
||||
tracing::info!(target: TRACE_DATASET_EVENTS, event=DATASET_COMPACTING_EVENT, uri = dataset.uri());
|
||||
let plan = validate_sq_index_remapping(&dataset, &options, remap_options.is_some()).await?;
|
||||
let planner = PrecomputedCompactionPlanner::new(plan);
|
||||
@@ -593,11 +729,15 @@ pub(crate) async fn execute_optimize(
|
||||
compaction: None,
|
||||
prune: None,
|
||||
};
|
||||
let action = match action {
|
||||
OptimizeAction::All => OptimizeAction::AllWithOptions(OptimizeOptions::default()),
|
||||
action => action,
|
||||
};
|
||||
match action {
|
||||
OptimizeAction::All => {
|
||||
OptimizeAction::All => unreachable!(),
|
||||
OptimizeAction::AllWithOptions(options) => {
|
||||
// Call helper functions directly to avoid async recursion issues
|
||||
stats.compaction =
|
||||
Some(compact_files_impl(table, OptimizeOptions::default(), None).await?);
|
||||
stats.compaction = Some(compact_files_impl(table, options, None).await?);
|
||||
stats.prune = Some(
|
||||
cleanup_old_versions(
|
||||
table,
|
||||
@@ -609,14 +749,13 @@ pub(crate) async fn execute_optimize(
|
||||
);
|
||||
optimize_indices(table, &IndexOptimizeOptions::default()).await?;
|
||||
}
|
||||
OptimizeAction::RewriteData(options) => {
|
||||
stats.compaction = Some(compact_files_impl(table, options.into_options(), None).await?);
|
||||
}
|
||||
OptimizeAction::RewriteDataWithOptions {
|
||||
OptimizeAction::RewriteData {
|
||||
options,
|
||||
remap_options,
|
||||
} => {
|
||||
stats.compaction = Some(compact_files_impl(table, options, remap_options).await?);
|
||||
}
|
||||
| OptimizeAction::Compact {
|
||||
OptimizeAction::Compact {
|
||||
options,
|
||||
remap_options,
|
||||
} => {
|
||||
@@ -644,7 +783,9 @@ pub(crate) async fn execute_optimize(
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
// Preserve coverage of released full-snapshot Compact requests.
|
||||
#[cfg(test)]
|
||||
#[allow(deprecated)]
|
||||
mod tests {
|
||||
use super::{oversized_sq_partition, segment_touches_fragments, sq_vector_dimension};
|
||||
use arrow::compute::concat_batches;
|
||||
@@ -668,9 +809,9 @@ mod tests {
|
||||
vector::{IvfHnswSqIndexBuilder, IvfRqIndexBuilder},
|
||||
};
|
||||
use crate::query::{ExecutableQuery, QueryBase};
|
||||
use crate::table::optimize::OptimizeOptions;
|
||||
use crate::table::{OptimizeAction, OptimizeStats};
|
||||
use futures::TryStreamExt;
|
||||
use lance::dataset::optimize::CompactionOptions as LanceOptimizeOptions;
|
||||
|
||||
/// Regression test for https://github.com/lancedb/lancedb/issues/2866.
|
||||
#[test]
|
||||
@@ -825,8 +966,8 @@ mod tests {
|
||||
);
|
||||
|
||||
let stats = table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: LanceOptimizeOptions {
|
||||
target_rows_per_fragment: 1_000,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -878,14 +1019,17 @@ mod tests {
|
||||
// Both Optimize entry points rewrite only data and preserve history.
|
||||
let stats = if optional_overrides {
|
||||
table
|
||||
.optimize(super::OptimizeOverrides {
|
||||
target_rows_per_fragment: Some(1000),
|
||||
..Default::default()
|
||||
.optimize(OptimizeAction::RewriteData {
|
||||
options: super::OptimizeOptions {
|
||||
target_rows_per_fragment: Some(1000),
|
||||
..Default::default()
|
||||
},
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
table
|
||||
.optimize(OptimizeOptions {
|
||||
.optimize(LanceOptimizeOptions {
|
||||
target_rows_per_fragment: 1000,
|
||||
..Default::default()
|
||||
})
|
||||
@@ -926,14 +1070,10 @@ mod tests {
|
||||
let expected: Vec<i32> = (0..600).collect();
|
||||
assert_eq!(all_values, expected);
|
||||
let error = table
|
||||
.optimize_async(OptimizeOptions::default())
|
||||
.optimize_async(LanceOptimizeOptions::default())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("only supported on remote tables")
|
||||
);
|
||||
assert!(error.to_string().contains("LanceDB Enterprise"));
|
||||
table.checkout(1).await.unwrap();
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 100);
|
||||
}
|
||||
@@ -977,8 +1117,8 @@ mod tests {
|
||||
|
||||
let version_before = table.version().await.unwrap();
|
||||
let stats = table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: LanceOptimizeOptions {
|
||||
target_rows_per_fragment: 20,
|
||||
num_threads: Some(64),
|
||||
..Default::default()
|
||||
@@ -1045,8 +1185,8 @@ mod tests {
|
||||
.unwrap();
|
||||
let compact_task = tokio::spawn(async move {
|
||||
compact_table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: LanceOptimizeOptions {
|
||||
target_rows_per_fragment: 1_000,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1075,8 +1215,8 @@ mod tests {
|
||||
|
||||
// A second compaction exposed the original out-of-order row-id bug.
|
||||
table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: LanceOptimizeOptions {
|
||||
target_rows_per_fragment: 1_000,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1526,8 +1666,8 @@ mod tests {
|
||||
|
||||
// Run compaction with deferred index remap
|
||||
let stats = table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: LanceOptimizeOptions {
|
||||
target_rows_per_fragment: 2000,
|
||||
defer_index_remap: true,
|
||||
..Default::default()
|
||||
@@ -1641,8 +1781,8 @@ mod tests {
|
||||
let before = concat_batches(&before[0].schema(), &before).unwrap();
|
||||
|
||||
let stats = table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: LanceOptimizeOptions {
|
||||
target_rows_per_fragment: 256,
|
||||
defer_index_remap: true,
|
||||
..Default::default()
|
||||
@@ -1733,8 +1873,8 @@ mod tests {
|
||||
|
||||
// Run compaction
|
||||
table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions::default(),
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: LanceOptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -1794,10 +1934,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::rewrite_data(OptimizeAction::RewriteData(Default::default()))]
|
||||
#[case::rewrite_data(OptimizeAction::RewriteData { options: crate::table::optimize::OptimizeOptions::default(), remap_options: None })]
|
||||
#[case::all(OptimizeAction::All)]
|
||||
#[case::compact(OptimizeAction::RewriteDataWithOptions {
|
||||
options: OptimizeOptions::default(),
|
||||
#[case::compact(OptimizeAction::Compact {
|
||||
options: LanceOptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})]
|
||||
#[case::prune(OptimizeAction::Prune {
|
||||
@@ -1838,3 +1978,60 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod policy_tests {
|
||||
use super::{LanceOptimizeOptions, OptimizeOptions};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
#[test]
|
||||
fn optimize_policy_preserves_omissions_explicit_defaults_and_zero() {
|
||||
let config = HashMap::from([
|
||||
(
|
||||
"lance.compaction.target_rows_per_fragment".into(),
|
||||
"10".into(),
|
||||
),
|
||||
(
|
||||
"lance.compaction.materialize_deletions".into(),
|
||||
"false".into(),
|
||||
),
|
||||
("lance.compaction.io_buffer_size".into(), "4096".into()),
|
||||
]);
|
||||
let inherited = OptimizeOptions::default().resolve(&config).unwrap();
|
||||
assert_eq!(inherited.target_rows_per_fragment, 10);
|
||||
assert!(!inherited.materialize_deletions);
|
||||
assert_eq!(inherited.io_buffer_size, Some(4096));
|
||||
let explicit = OptimizeOptions {
|
||||
target_rows_per_fragment: Some(
|
||||
LanceOptimizeOptions::default().target_rows_per_fragment,
|
||||
),
|
||||
materialize_deletions: Some(true),
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
}
|
||||
.resolve(&config)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
explicit.target_rows_per_fragment,
|
||||
LanceOptimizeOptions::default().target_rows_per_fragment
|
||||
);
|
||||
assert!(explicit.materialize_deletions);
|
||||
assert_eq!(explicit.io_buffer_size, Some(0));
|
||||
let cleared = OptimizeOptions {
|
||||
cleared_fields: HashSet::from(["io_buffer_size".into()]),
|
||||
..Default::default()
|
||||
}
|
||||
.resolve(&config)
|
||||
.unwrap();
|
||||
assert_eq!(cleared.io_buffer_size, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_rejects_invalid_table_policy() {
|
||||
let config = HashMap::from([(
|
||||
"lance.compaction.target_rows_per_fragment".into(),
|
||||
"not-an-integer".into(),
|
||||
)]);
|
||||
assert!(OptimizeOptions::default().resolve(&config).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1196,7 +1196,9 @@ async fn fill_stream(
|
||||
}))
|
||||
}
|
||||
|
||||
// Preserve coverage of released full-snapshot Compact requests.
|
||||
#[cfg(test)]
|
||||
#[allow(deprecated)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -1718,8 +1720,8 @@ mod tests {
|
||||
table.refresh_column("doubled").await.unwrap();
|
||||
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(crate::table::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -1834,8 +1836,8 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(crate::table::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -1891,8 +1893,8 @@ mod tests {
|
||||
.unwrap();
|
||||
table.checkout_latest().await.unwrap();
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(crate::table::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -1920,8 +1922,8 @@ mod tests {
|
||||
|
||||
append(&table, vec![5]).await;
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(crate::table::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -2226,8 +2228,8 @@ mod tests {
|
||||
|
||||
append(&table, vec![2_000_000]).await;
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(crate::table::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
@@ -2556,8 +2558,8 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
table
|
||||
.optimize(crate::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: crate::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(crate::table::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -12,9 +12,9 @@ use futures::TryStreamExt;
|
||||
use lance::Dataset;
|
||||
use lance::blob::blob_field as blob;
|
||||
use lance::dataset::WriteParams;
|
||||
use lance::dataset::optimize::CompactionOptions as OptimizeOptions;
|
||||
use lance_file::version::{ConcreteFileVersion, LanceFileVersion};
|
||||
use lance_table::format::BasePath;
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
use lancedb::{
|
||||
Connection, Error, Result, Table,
|
||||
blob::BlobRangeRequest,
|
||||
@@ -1180,6 +1180,7 @@ async fn fetch_blobs_after_delete() -> Result<()> {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[allow(deprecated)] // Exercise the released full-snapshot Compact action.
|
||||
async fn fetch_blobs_with_precompaction_row_ids_survives_compaction() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let db = connect(tmp.path().to_str().unwrap())
|
||||
@@ -1196,7 +1197,7 @@ async fn fetch_blobs_with_precompaction_row_ids_survives_compaction() -> Result<
|
||||
let ids_before: Vec<u64> = pairs_before.iter().map(|(_, rowid)| *rowid).collect();
|
||||
|
||||
table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
|
||||
@@ -31,23 +31,17 @@ 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;
|
||||
use lancedb::table::optimize::OptimizeOptions;
|
||||
|
||||
let desired_fragment_bytes: usize = 64 * 1024;
|
||||
let average_row_bytes: usize = 1024; // Estimate from representative rows.
|
||||
let options = OptimizeOptions {
|
||||
target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1),
|
||||
target_rows_per_fragment: Some((desired_fragment_bytes / average_row_bytes).max(1)),
|
||||
batch_size: Some(16),
|
||||
num_threads: Some(1),
|
||||
..Default::default()
|
||||
};
|
||||
table
|
||||
.optimize(OptimizeAction::RewriteDataWithOptions {
|
||||
options,
|
||||
remap_options: None,
|
||||
})
|
||||
.await?;
|
||||
table.optimize(options).await?;
|
||||
// --8<-- [end:storage_compaction_tuning]
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -381,6 +381,7 @@ async fn sql_pairs_match_native_snapshot_and_partition_tasks() -> anyhow::Result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[allow(deprecated)] // Exercise the released full-snapshot Compact action.
|
||||
async fn dedup_query_materializes_blob_payloads_and_null_vectors() -> anyhow::Result<()> {
|
||||
use arrow_array::{LargeBinaryArray, StringArray, StructArray, types::Float32Type};
|
||||
for stable in [false, true] {
|
||||
@@ -434,8 +435,8 @@ async fn dedup_query_materializes_blob_payloads_and_null_vectors() -> anyhow::Re
|
||||
.await?;
|
||||
table.delete("id = 5").await?;
|
||||
table
|
||||
.optimize(lancedb::table::OptimizeAction::RewriteDataWithOptions {
|
||||
options: lancedb::table::optimize::OptimizeOptions::default(),
|
||||
.optimize(lancedb::table::OptimizeAction::Compact {
|
||||
options: lance::dataset::optimize::CompactionOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -21,7 +21,7 @@ fn released_type_paths_keep_their_meaning() {
|
||||
);
|
||||
assert_eq!(
|
||||
TypeId::of::<CompactionOptions>(),
|
||||
TypeId::of::<lancedb::table::optimize::OptimizeOptions>()
|
||||
TypeId::of::<lance::dataset::optimize::CompactionOptions>()
|
||||
);
|
||||
assert_eq!(
|
||||
TypeId::of::<CompactionMode>(),
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use arrow_array::{ArrayRef, Int32Array, RecordBatch};
|
||||
use lancedb::{
|
||||
Table,
|
||||
index::{Index, scalar::BTreeIndexBuilder},
|
||||
table::{OptimizeAction, optimize::OptimizeOptions},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn rows(ids: Vec<i32>) -> RecordBatch {
|
||||
RecordBatch::try_from_iter([("id", Arc::new(Int32Array::from(ids)) as ArrayRef)]).unwrap()
|
||||
}
|
||||
async fn table() -> Table {
|
||||
let db = lancedb::connect("memory://").execute().await.unwrap();
|
||||
db.create_table("events", rows(vec![1]))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn optimize_options_run_full_cycle_while_rewrite_is_explicit() {
|
||||
let table = table().await;
|
||||
table
|
||||
.create_index(&["id"], Index::BTree(BTreeIndexBuilder::default()))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table.add(rows(vec![2])).execute().await.unwrap();
|
||||
// The configured target prevents a rewrite so index maintenance is observable.
|
||||
table
|
||||
.as_native()
|
||||
.unwrap()
|
||||
.update_config([(
|
||||
"lance.compaction.target_rows_per_fragment".into(),
|
||||
"1".into(),
|
||||
)])
|
||||
.await
|
||||
.unwrap();
|
||||
let index = table.list_indices().await.unwrap()[0].name.clone();
|
||||
let stats = table
|
||||
.optimize(OptimizeAction::RewriteData {
|
||||
options: OptimizeOptions::default(),
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(stats.prune.is_none());
|
||||
assert_eq!(
|
||||
table
|
||||
.index_stats(&index)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.num_unindexed_rows,
|
||||
1
|
||||
);
|
||||
let stats = table.optimize(OptimizeOptions::default()).await.unwrap();
|
||||
assert!(stats.prune.is_some());
|
||||
assert_eq!(
|
||||
table
|
||||
.index_stats(&index)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.num_unindexed_rows,
|
||||
0
|
||||
);
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[allow(deprecated)]
|
||||
async fn optimize_inherits_table_policy_and_invocation_overrides_it() {
|
||||
let table = table().await;
|
||||
table.add(rows(vec![2])).execute().await.unwrap();
|
||||
table
|
||||
.as_native()
|
||||
.unwrap()
|
||||
.update_config([
|
||||
(
|
||||
"lance.compaction.target_rows_per_fragment".into(),
|
||||
"1".into(),
|
||||
),
|
||||
("lance.compaction.io_buffer_size".into(), "4096".into()),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
let stats = table.optimize(OptimizeOptions::default()).await.unwrap();
|
||||
assert_eq!(stats.compaction.unwrap().fragments_removed, 0);
|
||||
let legacy = table
|
||||
.compact(lancedb::table::CompactionOverrides::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(legacy.compaction.unwrap().fragments_removed, 0);
|
||||
assert!(legacy.prune.is_none());
|
||||
let stats = table
|
||||
.optimize(OptimizeOptions {
|
||||
target_rows_per_fragment: Some(100),
|
||||
io_buffer_size: Some(0),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stats.compaction.unwrap().fragments_removed, 2);
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 2);
|
||||
let config = table.as_native().unwrap().manifest().await.unwrap().config;
|
||||
assert_eq!(
|
||||
config
|
||||
.get("lance.compaction.target_rows_per_fragment")
|
||||
.unwrap(),
|
||||
"1"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user