From c629d5b4aa3e802d9510309113c22f29ff4f0add Mon Sep 17 00:00:00 2001 From: ChilePiquin Date: Tue, 17 Nov 2026 16:51:15 -0800 Subject: [PATCH] refactor(sdk)!: standardize compaction APIs on Optimize BREAKING CHANGE: Replace compact_async/compactAsync with optimize_async/optimizeAsync, Rust compact(overrides) with optimize(overrides), and Python compact_files() with optimize(action="rewrite_data"). No compatibility aliases are retained. --- docs/src/js/classes/Table.md | 76 ++++++++--------- docs/src/js/interfaces/OptimizeOptions.md | 12 +++ docs/web/basics/embedded-vs-enterprise.mdx | 12 +-- docs/web/maintenance/compaction.mdx | 58 +++++++++++-- nodejs/__test__/table.test.ts | 50 ++++++++++- nodejs/lancedb/table.ts | 34 ++++++-- nodejs/src/table.rs | 45 ++++++---- python/python/lancedb/_lancedb.pyi | 3 +- python/python/lancedb/remote/table.py | 22 ++--- python/python/lancedb/table.py | 89 ++++++++------------ python/python/tests/test_e2e_remote_db.py | 2 +- python/python/tests/test_remote_db.py | 10 +-- python/python/tests/test_table.py | 83 ++++++++++++++++-- python/python/tests/test_table_signatures.py | 24 +++++- python/src/table.rs | 53 +++++++++--- rust/lancedb/src/remote/sql_test.rs | 21 +++-- rust/lancedb/src/remote/table.rs | 70 +++++++-------- rust/lancedb/src/table.rs | 42 ++++----- rust/lancedb/src/table/optimize.rs | 55 +++++++++--- 19 files changed, 506 insertions(+), 255 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 72f68c40f..d040ac523 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -305,40 +305,6 @@ It is a no-op when no writers are cached. *** -### compactAsync() - -```ts -compactAsync(_options?): Promise> -``` - -Submit remote compaction 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 -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. -Status, progress, events and cancellation reuse the generic HTTP job APIs. -Reopen with db.openJob(job.id!). A wait timeout does not cancel work. - -#### Parameters - -* **\_options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md) - -#### Returns - -`Promise`<[`Job`](Job.md)<[`CompactionResult`](../interfaces/CompactionResult.md)>> - -#### Example - -```ts -const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); -const result = await job.wait(); -console.log(result.rowsSucceeded, result.fragmentsRemoved); -``` - -*** - ### compactRTE() ```ts @@ -561,8 +527,8 @@ Drop one or more columns from the dataset This is a metadata-only operation and does not remove the data from the underlying storage. In order to remove the data, you must subsequently -call ``compact_files`` to rewrite the data without the removed columns and -then call ``cleanup_files`` to remove the old files. +call `optimize({ action: "rewrite_data" })` to rewrite the data without the +removed columns, then prune old versions using Optimize cleanup options. Local tables reject dropping source or vector columns referenced by `embedding_functions` schema metadata, preserving the embedding binding. @@ -1117,8 +1083,8 @@ Modeled after ``VACUUM`` in PostgreSQL. On a LanceDB Enterprise (remote) table, only compaction is currently supported. Pruning old versions and index optimization are silently skipped there instead of being attempted, so this call resolves -successfully, with zeroed pruning statistics, once the compaction job -has been submitted; it does not wait for that job to finish. +successfully with placeholder statistics (not completed work) once the +compaction job has been submitted; it does not wait for that job to finish. `compactionOptions` can tune the four per-job settings documented in [CompactionOptions](../interfaces/CompactionOptions.md). Older-server errors are propagated without retrying with the settings removed. @@ -1133,6 +1099,40 @@ retrying with the settings removed. *** +### optimizeAsync() + +```ts +optimizeAsync(_options?): Promise> +``` + +Submit remote compaction 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 +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. +Status, progress, events and cancellation reuse the generic HTTP job APIs. +Reopen with db.openJob(job.id!). A wait timeout does not cancel work. + +#### Parameters + +* **\_options?**: [`CompactionOptions`](../interfaces/CompactionOptions.md) + +#### Returns + +`Promise`<[`Job`](Job.md)<[`CompactionResult`](../interfaces/CompactionResult.md)>> + +#### Example + +```ts +const job = await table.optimizeAsync({ targetRowsPerFragment: 1000 }); +const result = await job.wait(); +console.log(result.rowsSucceeded, result.fragmentsRemoved); +``` + +*** + ### prewarmData() #### prewarmData(options) diff --git a/docs/src/js/interfaces/OptimizeOptions.md b/docs/src/js/interfaces/OptimizeOptions.md index faf1d2724..611c8948a 100644 --- a/docs/src/js/interfaces/OptimizeOptions.md +++ b/docs/src/js/interfaces/OptimizeOptions.md @@ -8,6 +8,18 @@ ## Properties +### action? + +```ts +optional action: "rewrite_data"; +``` + +Run only data compaction, preserving versions and skipping separate index +maintenance. Omit for Embedded's full maintenance cycle. Cannot be combined +with cleanup options. Enterprise always submits data compaction only. + +*** + ### cleanupOlderThan ```ts diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index 430d26885..1b85300e5 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -142,14 +142,14 @@ indexes, and removes old table versions. LanceDB Enterprise schedules that work through separate background jobs and also accepts explicit compaction requests with compatible releases. -Python sync/async `compact_async()`, TypeScript `compactAsync()`, and Rust -`Table::compact_async(CompactionOverrides)` return durable compaction job handles; -waiting returns the committed rewrite statistics. Legacy remote `optimize()` -and Rust `Table::compact()` return after submission with placeholder counts. +Python sync/async `optimize_async()`, TypeScript `optimizeAsync()`, and Rust +`Table::optimize_async(CompactionOverrides)` return durable compaction job handles; +waiting returns the committed rewrite statistics. Remote `optimize()` +returns after submission with placeholder counts. Remote optimize does not prune versions or optimize indexes; explicit requests for those unsupported operations are rejected. The synchronous -Python `compact_files()` and `cleanup_old_versions()` helpers remain warning-only -no-ops in LanceDB Enterprise. +Python `cleanup_old_versions()` remains a warning-only no-op in LanceDB Enterprise. +Use `optimize(action="rewrite_data")` for Embedded compaction only. Manual compaction accepts four invocation options and inherits omitted fields from the selected branch's table tuning, then deployment/built-in defaults. diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index ad3fe636d..636e9425b 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -67,7 +67,7 @@ even though `optimize()` bundles both in one LanceDB Embedded call. ## Track on-demand Enterprise compaction {#compaction-jobs} -On compatible Enterprise deployments, `compact_async()` / `compactAsync()` +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 `optimize()` call keeps returning after submission with placeholder statistics; @@ -77,7 +77,7 @@ use the job-returning API to wait for the actual rewrite and obtain its result. ```python Python from datetime import timedelta -job = table.compact_async( +job = table.optimize_async( compaction_options={"target_rows_per_fragment": 1000, "batch_size": 128} ) result = job.wait(timeout=timedelta(minutes=10)) @@ -89,7 +89,7 @@ result = db.open_job(job.id).wait() ```typescript TypeScript import type { CompactionResult } from "@lancedb/lancedb"; -const job = await table.compactAsync({ +const job = await table.optimizeAsync({ targetRowsPerFragment: 1000, batchSize: 128, }); const result = await job.wait({ timeoutMs: 600_000 }); @@ -104,7 +104,7 @@ use std::time::Duration; use lancedb::job::JobWaitOptions; use lancedb::table::{CompactionResult, optimize::CompactionOverrides}; -let job = table.compact_async(CompactionOverrides { +let job = table.optimize_async(CompactionOverrides { target_rows_per_fragment: Some(1000), batch_size: Some(128), ..Default::default() @@ -374,7 +374,8 @@ 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 -should use `Table::compact_async(CompactionOverrides)` for that distinction: the legacy +can use `Table::optimize(CompactionOverrides)` or +`Table::optimize_async(CompactionOverrides)` for that distinction: the legacy `OptimizeAction::Compact` path treats its default-valued Lance fragment target as unspecified because the options type has no presence bit. @@ -480,3 +481,50 @@ If the first task exceeds a budget, that run performs no compaction. See the [CompactionOptions reference](https://lancedb.github.io/lancedb/python/python/#lancedb.table.CompactionOptions) for all options and their limits. */} + +## Optimize submission and job handles + +Enterprise `optimize()` returns once the compaction request is accepted. Its +statistics are placeholders, not completed-work metrics. Use the durable job +method to wait for actual results: + +```python +# Submit and discard the handle. +table.optimize(compaction_options={"target_rows_per_fragment": 1000}) +# Submit and retain status, cancellation, and actual results. +job = table.optimize_async(compaction_options={"target_rows_per_fragment": 1000}) +result = job.wait() +# Async Python: job = await table.optimize_async(); result = await job.wait() +``` + +```typescript +await table.optimize({ compactionOptions: { targetRowsPerFragment: 1000 } }); +const job = await table.optimizeAsync({ targetRowsPerFragment: 1000 }); +const result = await job.wait(); +``` + +```rust +use lancedb::table::CompactionOverrides; + +async fn optimize_table(table: &lancedb::Table) -> lancedb::Result<()> { + table.optimize(CompactionOverrides::default()).await?; + let job = table.optimize_async(CompactionOverrides::default()).await?; + let result = job.wait().await?; + println!("Committed {} rows", result.rows_succeeded); + Ok(()) +} +``` + +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(CompactionOverrides::default())`. Rewrite-only requests preserve old +versions and skip the separate index maintenance phase. Cleanup arguments cannot +be combined with a rewrite-only action. + +The former `compact_async()` / `compactAsync()` methods are now +`optimize_async()` / `optimizeAsync()`. Rust `compact(overrides)` becomes +`optimize(overrides)`. Python `compact_files()` becomes +`optimize(action="rewrite_data", compaction_options=...)`, with rewrite metrics +under `stats.compaction`. The old names are removed without aliases. diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 7aac3864c..9e9a1a125 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -4111,7 +4111,12 @@ it("passes cleanupOlderThan to the native binding as an absolute timestamp", asy await table.optimize({ cleanupOlderThan: cutoff, deleteUnverified: true }); - expect(optimize).toHaveBeenCalledWith(cutoff.getTime(), true, undefined); + expect(optimize).toHaveBeenCalledWith( + cutoff.getTime(), + true, + undefined, + undefined, + ); }); it("forwards per-job compaction options to the native binding", async () => { @@ -4128,6 +4133,7 @@ it("forwards per-job compaction options to the native binding", async () => { undefined, undefined, compactionOptions, + undefined, ); }); @@ -6000,14 +6006,14 @@ 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.compactAsync()).rejects.toThrow( + await expect(table.optimizeAsync()).rejects.toThrow( "only supported on remote tables", ); await expect( - table.compactAsync({ unrecognizedLimit: 1 } as never), + table.optimizeAsync({ unrecognizedLimit: 1 } as never), ).rejects.toThrow("Unsupported compaction option"); await expect( - table.compactAsync({ targetRowsPerFragment: 0 }), + table.optimizeAsync({ targetRowsPerFragment: 0 }), ).rejects.toThrow("safe integer"); }); }); @@ -6057,3 +6063,39 @@ describe("Enterprise table overrides", () => { } }); }); + +describe("Optimize action selection", () => { + test("rewrites data while retaining versions and deferring index maintenance", async () => { + const db = await connect(`memory://optimize-action-${Date.now()}`); + const table = await db.createTable("test", [{ id: 1 }]); + await table.add([{ id: 2 }]); + await table.createIndex("id", { config: Index.btree() }); + await table.add([{ id: 3 }]); + await table.add([{ id: 4 }]); + const before = await table.listVersions(); + const stats = await table.optimize({ action: "rewrite_data" }); + expect(stats.compaction.fragmentsRemoved).toBe(4); + expect(stats.compaction.fragmentsAdded).toBe(2); + 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(); + expect((await table.indexStats("id_idx"))?.numUnindexedRows).toBe(0); + await table.checkout(1); + expect(await table.countRows()).toBe(1); + expect("compactAsync" in table).toBe(false); + }); + + test("rejects unknown actions and conflicting cleanup requests before changes", async () => { + const db = await connect(`memory://optimize-invalid-${Date.now()}`); + const table = await db.createTable("test", [{ id: 1 }]); + for (const options of [ + { action: "unknown" }, + { action: "rewrite_data", cleanupOlderThan: new Date() }, + { action: "rewrite_data", deleteUnverified: true }, + ]) { + await expect(table.optimize(options as never)).rejects.toThrow("action"); + } + expect(await table.version()).toBe(1); + }); +}); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index eecb83fb6..11c285763 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -199,6 +199,11 @@ export interface CompactionOptions { } export interface OptimizeOptions { + /** Run only data compaction, preserving versions and skipping separate index + * maintenance. Omit for Embedded's full maintenance cycle. Cannot be combined + * with cleanup options. Enterprise always submits data compaction only. */ + action?: "rewrite_data"; + /** * Compaction settings for this invocation. Omitted remote values inherit table * tuning, then deployment/built-in defaults. @@ -1063,8 +1068,8 @@ export abstract class Table { * * This is a metadata-only operation and does not remove the data from the * underlying storage. In order to remove the data, you must subsequently - * call ``compact_files`` to rewrite the data without the removed columns and - * then call ``cleanup_files`` to remove the old files. + * call `optimize({ action: "rewrite_data" })` to rewrite the data without the + * removed columns, then prune old versions using Optimize cleanup options. * * Local tables reject dropping source or vector columns referenced by * `embedding_functions` schema metadata, preserving the embedding binding. @@ -1353,11 +1358,11 @@ export abstract class Table { * Reopen with db.openJob(job.id!). A wait timeout does not cancel work. * * @example - * const job = await table.compactAsync({ targetRowsPerFragment: 1000 }); + * const job = await table.optimizeAsync({ targetRowsPerFragment: 1000 }); * const result = await job.wait(); * console.log(result.rowsSucceeded, result.fragmentsRemoved); */ - async compactAsync( + async optimizeAsync( _options?: CompactionOptions, ): Promise> { throw new Error("compaction jobs are only supported on remote tables"); @@ -1384,8 +1389,8 @@ export abstract class Table { * On a LanceDB Enterprise (remote) table, only compaction is currently * supported. Pruning old versions and index optimization are silently * skipped there instead of being attempted, so this call resolves - * successfully, with zeroed pruning statistics, once the compaction job - * has been submitted; it does not wait for that job to finish. + * successfully with placeholder statistics (not completed work) once the + * compaction job has been submitted; it does not wait for that job to finish. * `compactionOptions` can tune the four per-job settings documented in * {@link CompactionOptions}. Older-server errors are propagated without * retrying with the settings removed. @@ -2081,22 +2086,35 @@ export class LocalTable extends Table { return this.inner.currentBranch() ?? null; } - async compactAsync( + async optimizeAsync( options?: CompactionOptions, ): Promise> { validateCompactionOptions(options); return new Job( - await this.inner.compactAsync(options), + await this.inner.optimizeAsync(options), decodeCompactionResult, ); } async optimize(options?: Partial): Promise { validateCompactionOptions(options?.compactionOptions); + if (options?.action !== undefined && options.action !== "rewrite_data") { + throw new Error('action must be "rewrite_data" or undefined'); + } + if ( + options?.action === "rewrite_data" && + (options.cleanupOlderThan !== undefined || + options.deleteUnverified === true) + ) { + throw new Error( + 'action="rewrite_data" cannot be combined with cleanup options', + ); + } return await this.inner.optimize( options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, options?.compactionOptions, + options?.action, ); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 1a4c3e91c..13c9fe043 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1002,7 +1002,7 @@ impl Table { } #[napi(catch_unwind)] - pub async fn compact_async( + pub async fn optimize_async( &self, options: Option, ) -> napi::Result { @@ -1012,7 +1012,7 @@ impl Table { .unwrap_or_default(); let job = self .inner_ref()? - .compact_async(options) + .optimize_async(options) .await .default_error()?; Ok(crate::job::Job::new_typed(job)) @@ -1024,7 +1024,22 @@ impl Table { before_timestamp_ms: Option, delete_unverified: Option, compaction_options: Option, + action: Option, ) -> napi::Result { + let rewrite_only = match action.as_deref() { + None => false, + Some("rewrite_data") => true, + Some(_) => { + return Err(napi::Error::from_reason( + "action must be 'rewrite_data' or undefined", + )); + } + }; + if rewrite_only && (before_timestamp_ms.is_some() || delete_unverified == Some(true)) { + return Err(napi::Error::from_reason( + "action='rewrite_data' cannot be combined with cleanup options", + )); + } let inner = self.inner_ref()?; let before_timestamp = before_timestamp_ms @@ -1037,20 +1052,20 @@ impl Table { }) .transpose()?; - let stats = inner - .optimize_full_with_overrides( - compaction_options - .map(CompactionOptions::into_overrides) - .transpose()? - .unwrap_or_default(), - None, - before_timestamp, - delete_unverified, - ) - .await - .default_error()?; + let overrides = compaction_options + .map(CompactionOptions::into_overrides) + .transpose()? + .unwrap_or_default(); + let stats = if rewrite_only { + inner.optimize(overrides).await + } else { + inner + .optimize_full_with_overrides(overrides, None, before_timestamp, delete_unverified) + .await + } + .default_error()?; let compaction_stats = stats.compaction.unwrap(); - let prune_stats = stats.prune.unwrap(); + let prune_stats = stats.prune.unwrap_or_default(); Ok(OptimizeStats { compaction: CompactionStats { files_added: compaction_stats.files_added as i64, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 54b9f8083..ce37918d5 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -806,7 +806,7 @@ class Table: async def update_field_metadata( self, updates: list[dict[str, Any]] ) -> UpdateFieldMetadataResult: ... - async def compact_async( + async def optimize_async( self, compaction_options: Optional[Dict[str, Any]] = None ) -> Job: ... async def optimize( @@ -815,6 +815,7 @@ class Table: cleanup_since_ms: Optional[int] = None, delete_unverified: Optional[bool] = None, compaction_options: Optional[Dict[str, Any]] = None, + action: Optional[str] = None, ) -> OptimizeStats: ... async def uri(self) -> str: ... async def initial_storage_options(self) -> Optional[Dict[str, str]]: ... diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 51a656a52..506f3553d 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -90,6 +90,8 @@ from ..types import BaseTokenizerType, ScalarIndexType from ..util import infer_vector_column_name if TYPE_CHECKING: + from lancedb._lancedb import OptimizeStats + import lance import polars as pl @@ -1098,21 +1100,11 @@ class RemoteTable(Table): ) pass - def compact_files(self, *args, **kwargs): - """ - compact_files() is a no-op in LanceDB Enterprise. - """ - warnings.warn( - "compact_files() is a no-op in LanceDB Enterprise.", - stacklevel=2, - ) - pass - - def compact_async( + def optimize_async( self, *, compaction_options: Optional[CompactionOptions] = None ) -> Job[CompactionResult]: return Job( - LOOP.run(self._table.compact_async(compaction_options=compaction_options)) + LOOP.run(self._table.optimize_async(compaction_options=compaction_options)) ) def optimize( @@ -1122,11 +1114,12 @@ class RemoteTable(Table): delete_unverified: bool = False, retrain: bool = False, compaction_options: Optional[CompactionOptions] = None, - ): + action: Optional[Literal["rewrite_data"]] = None, + ) -> 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 - successfully with zeroed pruning statistics once the compaction job + 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``, ``io_buffer_size``, and ``batch_size`` are supported on compatible @@ -1141,6 +1134,7 @@ class RemoteTable(Table): delete_unverified=delete_unverified, retrain=retrain, compaction_options=compaction_options, + action=action, ) ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ff014396c..32a5e0cc5 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -304,7 +304,6 @@ if TYPE_CHECKING: Table as LanceDBTable, OptimizeStats, CleanupStats, - CompactionStats, Tag, AddColumnsResult, RefreshColumnResult, @@ -3115,29 +3114,7 @@ class Table(ABC): cleanup for you automatically. """ - @abstractmethod - def compact_files(self, *args, **kwargs): - """ - Run the compaction process on the table. - This can be run after making several small appends to optimize the table - for faster reads. - - Arguments are passed onto Lance's - `lance.dataset.DatasetOptimizer.compact_files`. - For most cases, the default should be fine. - - See Also - -------- - [Table.optimize][lancedb.table.Table.optimize]: A more comprehensive - optimization operation that includes cleanup as well as other operations. - - Notes - ----- - This function is not available in LanceDB Enterprise, which manages - compaction for you automatically. - """ - - def compact_async( + def optimize_async( self, *, compaction_options: Optional[CompactionOptions] = None ) -> Job[CompactionResult]: """Submit remote compaction and return a durable job after acceptance. @@ -3157,7 +3134,7 @@ class Table(ABC): Save ``job.id`` and reopen with ``db.open_job(id)``. Monitoring and cancellation use generic HTTP job APIs and their existing permissions. - >>> job = table.compact_async( # doctest: +SKIP + >>> job = table.optimize_async( # doctest: +SKIP ... compaction_options={"target_rows_per_fragment": 1000}) >>> result = job.wait() # doctest: +SKIP >>> print(result.rows_succeeded) # doctest: +SKIP @@ -3172,7 +3149,8 @@ class Table(ABC): delete_unverified: bool = False, retrain: bool = False, compaction_options: Optional[CompactionOptions] = None, - ): + action: Optional[Literal["rewrite_data"]] = None, + ) -> OptimizeStats: """ Optimize the on-disk data and indices for better performance. @@ -3181,7 +3159,7 @@ class Table(ABC): On a LanceDB Enterprise (remote) table, only compaction is currently supported. Pruning old versions and index optimization are silently skipped there instead of being attempted, so this - call returns successfully, with zeroed pruning statistics, once + 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 ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, @@ -3226,6 +3204,11 @@ class Table(ABC): retrain: bool, default False This parameter is no longer used and is deprecated. + action: "rewrite_data", optional + Run only data compaction, retaining old versions and skipping the + separate index maintenance phase. Omit for Embedded's full cycle. + Cannot be combined with cleanup options. Enterprise always submits + compaction only; use optimize_async() to retain its durable job. compaction_options: CompactionOptions, optional Options that control file compaction. For large rows, derive a lower ``target_rows_per_fragment`` from the expected row size to bound later @@ -5865,31 +5848,11 @@ class LanceTable(Table): older_than, delete_unverified=delete_unverified ) - @deprecation.deprecated( - deprecated_in="0.21.0", - current_version=__version__, - details="Use `Table.optimize` instead.", - ) - def compact_files(self, *args, **kwargs) -> CompactionStats: - """ - Run the compaction process on the table. - - This can be run after making several small appends to optimize the table - for faster reads. - - Arguments are passed onto `lance.dataset.DatasetOptimizer.compact_files`. - (see Lance documentation for more details) For most cases, the default - should be fine. - """ - stats = self.to_lance().optimize.compact_files(*args, **kwargs) - self.checkout_latest() - return stats - - def compact_async( + def optimize_async( self, *, compaction_options: Optional[CompactionOptions] = None ) -> Job[CompactionResult]: return Job( - LOOP.run(self._table.compact_async(compaction_options=compaction_options)) + LOOP.run(self._table.optimize_async(compaction_options=compaction_options)) ) def optimize( @@ -5899,7 +5862,8 @@ class LanceTable(Table): delete_unverified: bool = False, retrain: bool = False, compaction_options: Optional[CompactionOptions] = None, - ): + action: Optional[Literal["rewrite_data"]] = None, + ) -> OptimizeStats: """ Optimize the on-disk data and indices for better performance. @@ -5938,6 +5902,11 @@ class LanceTable(Table): retrain: bool, default False This parameter is no longer used and is deprecated. + action: "rewrite_data", optional + Run only data compaction, retaining old versions and skipping the + separate index maintenance phase. Omit for Embedded's full cycle. + Cannot be combined with cleanup options. Enterprise always submits + compaction only; use optimize_async() to retain its durable job. compaction_options: CompactionOptions, optional Options that control file compaction. For large rows, derive a lower ``target_rows_per_fragment`` from the expected row size to bound later @@ -5952,11 +5921,12 @@ class LanceTable(Table): you have added or modified 100,000 or more records or run more than 20 data modification operations. """ - LOOP.run( + return LOOP.run( self._table._do_optimize( _optimize_cleanup_since_ms(cleanup_older_than, retrain), delete_unverified, compaction_options, + action, ) ) @@ -9575,16 +9545,16 @@ class AsyncTable: """The branch this table handle is scoped to, or ``None`` for ``main``.""" return self._inner.current_branch() - async def compact_async( + async def optimize_async( self, *, compaction_options: Optional[CompactionOptions] = None ) -> AsyncJob[CompactionResult]: """Submit remote compaction; await the returned job for actual results. - See [Table.compact_async][lancedb.table.Table.compact_async] for options, + See [Table.optimize_async][lancedb.table.Table.optimize_async] for options, permissions, completion semantics and compatibility requirements. """ return _typed_job( - await self._inner.compact_async(compaction_options), + await self._inner.optimize_async(compaction_options), CompactionResult.from_json, ) @@ -9595,6 +9565,7 @@ class AsyncTable: delete_unverified: bool = False, retrain=False, compaction_options: Optional[CompactionOptions] = None, + action: Optional[Literal["rewrite_data"]] = None, ) -> OptimizeStats: """ Optimize the on-disk data and indices for better performance. @@ -9604,7 +9575,7 @@ class AsyncTable: On a LanceDB Enterprise (remote) table, only compaction is currently supported. Pruning old versions and index optimization are silently skipped there instead of being attempted, so this - call returns successfully, with zeroed pruning statistics, once + 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 ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, @@ -9649,6 +9620,11 @@ class AsyncTable: retrain: bool, default False This parameter is no longer used and is deprecated. + action: "rewrite_data", optional + Run only data compaction, retaining old versions and skipping the + separate index maintenance phase. Omit for Embedded's full cycle. + Cannot be combined with cleanup options. Enterprise always submits + compaction only; use optimize_async() to retain its durable job. compaction_options: CompactionOptions, optional Options that control file compaction. For large rows, derive a lower ``target_rows_per_fragment`` from the expected row size to bound later @@ -9667,6 +9643,7 @@ class AsyncTable: _optimize_cleanup_since_ms(cleanup_older_than, retrain), delete_unverified, compaction_options, + action, ) async def _do_optimize( @@ -9674,8 +9651,10 @@ class AsyncTable: cleanup_since_ms: Optional[int], delete_unverified: bool, compaction_options: Optional[CompactionOptions] = None, + action: Optional[Literal["rewrite_data"]] = None, ) -> OptimizeStats: return await self._inner.optimize( + action=action, cleanup_since_ms=cleanup_since_ms, delete_unverified=delete_unverified, compaction_options=compaction_options, diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index 9ef746ce1..25b3f09e6 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -70,7 +70,7 @@ async def test_maintenance_job_result_and_reopen_against_server( version = await table.version() if asynchronous else table.version if operation == "compact": job = await call( - table.compact_async, + table.optimize_async, compaction_options={ "target_rows_per_fragment": 100, "batch_size": 128, diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index a2a26b595..cef2b32e5 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -3611,7 +3611,7 @@ def test_remote_python_only_messages(): f"{method}() is not supported in LanceDB Enterprise. " f"Use table.search().{method}() instead." ) - for method in ["compact_files", "cleanup_old_versions"]: + for method in ["cleanup_old_versions"]: with pytest.warns(UserWarning) as warning: getattr(table, method)() assert ( @@ -8471,7 +8471,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): if asynchronous: db = await lancedb.connect_async(**kwargs) table = await db.create_table("test", [{"id": 1}]) - job = await table.compact_async( + job = await table.optimize_async( compaction_options={"target_rows_per_fragment": 100} ) assert job.id == "compacting-job" and not polls @@ -8492,7 +8492,7 @@ async def test_remote_compaction_job_result_and_reopen(asynchronous, outcome): else: db = lancedb.connect(**kwargs) table = db.create_table("test", [{"id": 1}]) - job = table.compact_async( + job = table.optimize_async( compaction_options={"target_rows_per_fragment": 100} ) assert job.id == "compacting-job" and not polls @@ -8547,11 +8547,11 @@ def test_remote_compaction_rejects_ambiguous_receipt_without_resubmission(ids): db = lancedb.connect(**kwargs) table = db.create_table("test", [{"id": 1}]) with pytest.raises(Exception, match="inspect jobs before retrying"): - table.compact_async() + table.optimize_async() assert server.calls == 1 -@pytest.mark.parametrize("method", ["compact_async", "optimize"]) +@pytest.mark.parametrize("method", ["optimize_async", "optimize"]) @pytest.mark.parametrize( "option", ["target_rows_per_fragment", "max_source_rows", "io_buffer_size", "batch_size"], diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 90ae62d1b..52d492df8 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -4841,10 +4841,10 @@ def test_compact_cleanup(tmp_db: DBConnection): assert len(table) == 3 assert table.version == 2 - stats = table.compact_files() + stats = table.optimize(action="rewrite_data").compaction assert len(table) == 3 - # Compact_files bump 2 versions. - assert table.version == 4 + optimized_version = table.version + assert optimized_version > 2 assert stats.fragments_removed > 0 assert stats.fragments_added == 1 @@ -4853,10 +4853,10 @@ def test_compact_cleanup(tmp_db: DBConnection): stats = table.cleanup_old_versions(older_than=timedelta(0), delete_unverified=True) assert stats.bytes_removed > 0 - assert table.version == 4 + assert table.version == optimized_version - with pytest.raises(Exception, match="Version 3 no longer exists"): - table.checkout(3) + with pytest.raises(Exception, match="Version 2 no longer exists"): + table.checkout(2) def test_count_rows(mem_db: DBConnection): @@ -6435,3 +6435,74 @@ async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, m NotImplementedError, match="only supported on remote tables" ): getattr(table, method)(filter="id > 0", concurrency=2) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_optimize_rewrite_only_preserves_versions_and_index( + tmp_path, asynchronous +): + """A rewrite must retain history and leave incremental indexing to full Optimize.""" + db = ( + (await lancedb.connect_async(str(tmp_path))) + if asynchronous + else lancedb.connect(str(tmp_path)) + ) + + async def call(obj, name, *args, **kwargs): + result = getattr(obj, name)(*args, **kwargs) + return await result if asynchronous else result + + table = await call(db, "create_table", "rewrite", [{"id": 1}]) + await call(table, "add", [{"id": 2}]) + await call(table, "create_index", "id", config=BTree()) + await call(table, "add", [{"id": 3}]) + await call(table, "add", [{"id": 4}]) + before = await call(table, "list_versions") + stats = await call(table, "optimize", action="rewrite_data") + assert stats.compaction.fragments_removed == 4 + assert stats.compaction.fragments_added == 2 + assert stats.prune.old_versions_removed == 0 + assert len(await call(table, "list_versions")) > len(before) + index_stats = await call(table, "index_stats", "id_idx") + assert ( + index_stats.num_unindexed_rows + if asynchronous + else index_stats["num_unindexed_rows"] + ) == 2 + await call(table, "optimize") + index_stats = await call(table, "index_stats", "id_idx") + assert ( + index_stats.num_unindexed_rows + if asynchronous + else index_stats["num_unindexed_rows"] + ) == 0 + await call(table, "checkout", 1) + assert await call(table, "count_rows") == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "kwargs", + [ + {"action": "unknown"}, + {"action": "rewrite_data", "cleanup_older_than": timedelta(days=1)}, + {"action": "rewrite_data", "delete_unverified": True}, + ], +) +async def test_optimize_action_validation(mem_db_async, kwargs): + table = await mem_db_async.create_table("rewrite_invalid", [{"id": 1}]) + with pytest.raises(ValueError, match="action"): + await table.optimize(**kwargs) + assert await table.version() == 1 + + +@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"): + 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"): + await async_table.optimize_async() + assert not hasattr(async_table, "compact_async") diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py index 41a688068..929fc50fe 100644 --- a/python/python/tests/test_table_signatures.py +++ b/python/python/tests/test_table_signatures.py @@ -25,7 +25,7 @@ import pytest "create_fts_index", "search", "cleanup_old_versions", - "compact_files", + "optimize_async", "optimize", "to_polars", ], @@ -179,7 +179,6 @@ def test_fts_unsupported_options(sync_table, kwargs, message): "cleanup_old_versions", {"older_than": timedelta(days=1), "delete_unverified": True}, ), - ("compact_files", {"target_rows_per_fragment": 1000}), ], ) def test_remote_maintenance_options_warn(method, kwargs): @@ -200,6 +199,7 @@ def test_remote_optimize_options(): delete_unverified=True, retrain=True, compaction_options=None, + action=None, ) @@ -258,3 +258,23 @@ def test_index_replacement_defaults(tmp_path): with pytest.warns(DeprecationWarning): sync.create_scalar_index("id") assert len(list(table.list_indices())) == 1 + + +@pytest.mark.parametrize("cls", [Table, LanceTable, RemoteTable]) +def test_optimize_has_no_legacy_compaction_aliases(cls): + assert not hasattr(cls, "compact_files") + assert not hasattr(cls, "compact_async") + + +def test_remote_optimize_rewrite_action(): + handle = MagicMock() + handle.optimize = AsyncMock(return_value="accepted") + table = RemoteTable(handle, "test_db") + assert table.optimize(action="rewrite_data") == "accepted" + handle.optimize.assert_awaited_once_with( + cleanup_older_than=None, + delete_unverified=False, + retrain=False, + compaction_options=None, + action="rewrite_data", + ) diff --git a/python/src/table.rs b/python/src/table.rs index c24b10405..4e962f20d 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -2297,7 +2297,7 @@ impl Table { /// Submit remote compaction and retain its durable job and actual result. #[pyo3(signature = (compaction_options=None))] - pub fn compact_async<'py>( + pub fn optimize_async<'py>( self_: PyRef<'py, Self>, compaction_options: Option<&Bound<'py, PyDict>>, ) -> PyResult> { @@ -2313,19 +2313,34 @@ impl Table { overrides.target_rows_per_fragment = None; } future_into_py(self_.py(), async move { - let job = inner.compact_async(overrides).await.infer_error()?; + let job = inner.optimize_async(overrides).await.infer_error()?; Ok(crate::job::Job::new_typed(job)) }) } /// Optimize the on-disk data by compacting and pruning old data, for better performance. - #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None))] + #[pyo3(signature = (cleanup_since_ms=None, delete_unverified=None, compaction_options=None, action=None))] pub fn optimize<'py>( self_: PyRef<'py, Self>, cleanup_since_ms: Option, delete_unverified: Option, compaction_options: Option<&Bound<'py, PyDict>>, + action: Option, ) -> PyResult> { + let rewrite_only = match action.as_deref() { + None => false, + Some("rewrite_data") => true, + Some(_) => { + return Err(PyValueError::new_err( + "action must be 'rewrite_data' or None", + )); + } + }; + if rewrite_only && (cleanup_since_ms.is_some() || delete_unverified == Some(true)) { + return Err(PyValueError::new_err( + "action='rewrite_data' cannot be combined with cleanup options", + )); + } let inner = self_.inner_ref()?.clone(); let target_specified = compaction_options .map(|options| options.contains("target_rows_per_fragment")) @@ -2346,9 +2361,18 @@ impl Table { }; future_into_py(self_.py(), async move { let stats = if inner.as_native().is_some() { - inner - .optimize_full(compaction_options, older_than, None, delete_unverified) - .await + if rewrite_only { + inner + .optimize(lancedb::table::OptimizeAction::Compact { + options: compaction_options, + remap_options: None, + }) + .await + } else { + inner + .optimize_full(compaction_options, older_than, None, delete_unverified) + .await + } } else { let mut overrides = lancedb::table::optimize::CompactionOverrides::try_from(compaction_options) @@ -2356,13 +2380,22 @@ impl Table { if !target_specified { overrides.target_rows_per_fragment = None; } - inner - .optimize_full_with_overrides(overrides, older_than, None, delete_unverified) - .await + if rewrite_only { + inner.optimize(overrides).await + } else { + inner + .optimize_full_with_overrides( + overrides, + older_than, + None, + delete_unverified, + ) + .await + } } .infer_error()?; let compaction_stats = stats.compaction.unwrap(); - let prune_stats = stats.prune.unwrap(); + let prune_stats = stats.prune.unwrap_or_default(); Ok(OptimizeStats { compaction: CompactionStats { files_added: compaction_stats.files_added as u64, diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index a8f39fc2e..61e456197 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -4352,7 +4352,10 @@ async fn remote_compact_preserves_omissions_and_explicit_default_values() { Default::default(), Some(sql_client), ); - table.compact(options).await.unwrap(); + table + .optimize(crate::table::OptimizeAction::RewriteData(options)) + .await + .unwrap(); assert_eq!( *statements.lock().unwrap(), [format!("OPTIMIZE \"events\" REWRITE DATA{suffix}")] @@ -4424,7 +4427,9 @@ async fn remote_optimize_parser_errors_are_clear_without_resubmission() { Some(sql_client), ); let error = table - .compact(CompactionOverrides::default()) + .optimize(crate::table::OptimizeAction::RewriteData( + CompactionOverrides::default(), + )) .await .unwrap_err(); assert_eq!( @@ -4462,10 +4467,12 @@ async fn remote_optimize_branch_options_are_not_dropped() { ) .with_branch(Some("exp".into())); let error = table - .compact(crate::table::optimize::CompactionOverrides { - io_buffer_size: Some(0), - ..Default::default() - }) + .optimize(crate::table::OptimizeAction::RewriteData( + crate::table::optimize::CompactionOverrides { + io_buffer_size: Some(0), + ..Default::default() + }, + )) .await .unwrap_err(); assert!(matches!(error, Error::NotSupported { .. })); @@ -4847,7 +4854,7 @@ async fn remote_compaction_tracks_registry_job_and_real_result() { ) .with_branch(Some("experiment".into())); let job = table - .compact_async(CompactionOverrides { + .optimize_async(CompactionOverrides { target_rows_per_fragment: Some(100), ..Default::default() }) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 54b7ea7b2..defaa77a0 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4040,7 +4040,7 @@ impl BaseTable for RemoteTable { Ok(()) } - /// Only `OptimizeAction::Compact` with supported `options` and no custom + /// `OptimizeAction::RewriteData`, or `OptimizeAction::Compact` with no custom /// `remap_options` is supported remotely: it submits a durable /// compaction job through the server's `OPTIMIZE ... REWRITE DATA` /// SQL statement, the same atomic, single-worker, index-safe path the @@ -4066,43 +4066,37 @@ impl BaseTable for RemoteTable { /// No settings are removed and the operation is never resubmitted. async fn optimize(&self, action: OptimizeAction) -> Result { self.check_mutable().await?; - let OptimizeAction::Compact { - options, - remap_options, - } = &action - else { - return Err(Error::NotSupported { - message: "optimize is only supported in LanceDB Enterprise for \ - OptimizeAction::Compact; version pruning and index \ - optimization are not yet supported remotely." - .into(), - }); + let overrides = match action { + OptimizeAction::RewriteData(options) => 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(), + }); + } + let target = options.target_rows_per_fragment; + let mut overrides = crate::table::optimize::CompactionOverrides::try_from(options)?; + if target == crate::table::CompactionOptions::default().target_rows_per_fragment { + overrides.target_rows_per_fragment = None; + } + overrides + } + _ => { + return 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::Compact." + .into(), + }); + } }; - 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(), - }); - } - let mut overrides = crate::table::optimize::CompactionOverrides::try_from(options.clone())?; - // The legacy Lance options type has no presence bit for this field. - // Use Table::compact to explicitly send a target equal to Lance's default. - if options.target_rows_per_fragment - == crate::table::CompactionOptions::default().target_rows_per_fragment - { - overrides.target_rows_per_fragment = None; - } - self.compact(overrides).await - } - - async fn compact( - &self, - options: crate::table::optimize::CompactionOverrides, - ) -> Result { - self.check_mutable().await?; - let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; + let statement = optimize::statement(&self.name, self.branch.as_deref(), &overrides)?; let sql_client = self.sql_client.clone().ok_or_else(|| Error::NotSupported { message: "SQL is unavailable for this remote table client".to_string(), })?; @@ -4122,7 +4116,7 @@ impl BaseTable for RemoteTable { prune: None, }) } - async fn compact_async( + async fn optimize_async( &self, options: crate::table::optimize::CompactionOverrides, ) -> Result> { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 775261bb5..2a63b02aa 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -902,7 +902,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Optimize the dataset. async fn optimize(&self, action: OptimizeAction) -> Result; /// Submit remote compaction and retain its durable job and actual outcome. - async fn compact_async( + async fn optimize_async( &self, _options: optimize::CompactionOverrides, ) -> Result> { @@ -910,14 +910,6 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "compaction jobs are only supported on remote tables".into(), }) } - /// Compact with optional fields, preserving remote policy inheritance. - async fn compact(&self, options: optimize::CompactionOverrides) -> Result { - self.optimize(OptimizeAction::Compact { - options: options.into_options(), - remap_options: None, - }) - .await - } /// Add columns to the table. async fn add_columns( &self, @@ -2067,31 +2059,27 @@ impl Table { /// /// # LanceDB Enterprise (remote tables) /// + /// [`OptimizeAction::RewriteData`] accepts [`optimize::CompactionOverrides`] + /// directly, preserving omitted options and explicit default values. /// [`OptimizeAction::Compact`] 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::Compact`] for /// what a remote call submits and what it does and does not wait for. - pub async fn optimize(&self, action: OptimizeAction) -> Result { - self.inner.optimize(action).await - } - - /// Compact data files with optional tuning fields. On remote tables, - /// omitted fields inherit table tuning, then deployment/built-in defaults. - /// Returns after job submission; remote statistics are placeholders. /// - /// ``` - /// use lancedb::{Table, table::optimize::CompactionOverrides}; - /// # async fn compact(table: &Table) -> lancedb::Result<()> { - /// table.compact(CompactionOverrides { - /// io_buffer_size: Some(64 * 1024 * 1024), + /// ```no_run + /// # async fn optimize(table: &lancedb::Table) -> lancedb::Result<()> { + /// use lancedb::table::CompactionOverrides; + /// // Rewrite only data; omitted settings retain remote table policy. + /// table.optimize(CompactionOverrides { + /// io_buffer_size: Some(0), /// ..Default::default() /// }).await?; /// # Ok(()) /// # } /// ``` - pub async fn compact(&self, options: optimize::CompactionOverrides) -> Result { - self.inner.compact(options).await + pub async fn optimize(&self, action: impl Into) -> Result { + self.inner.optimize(action.into()).await } /// Submit remote compaction and return its durable job after acceptance. @@ -2112,17 +2100,17 @@ impl Table { /// /// ```no_run /// # async fn compact(table: &lancedb::Table) -> lancedb::Result<()> { - /// let job = table.compact_async(Default::default()).await?; + /// let job = table.optimize_async(Default::default()).await?; /// let result = job.wait().await?; /// println!("Committed {} rows", result.rows_succeeded); /// # Ok(()) /// # } /// ``` - pub async fn compact_async( + pub async fn optimize_async( &self, options: optimize::CompactionOverrides, ) -> Result> { - self.inner.compact_async(options).await + self.inner.optimize_async(options).await } /// Language-binding entry point retaining optional compaction fields. @@ -2147,7 +2135,7 @@ impl Table { 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.compact(options).await?; + let stats = self.optimize(options).await?; Ok(OptimizeStats { compaction: stats.compaction, prune: Some(RemovalStats::default()), diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 0888ca4c4..d9c583ab4 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -260,6 +260,12 @@ impl TryFrom for CompactionOverrides { } } +impl From for OptimizeAction { + fn from(options: CompactionOverrides) -> Self { + Self::RewriteData(options) + } +} + /// Optimize the dataset. /// /// Similar to `VACUUM` in PostgreSQL, it offers different options to @@ -268,6 +274,10 @@ impl TryFrom for CompactionOverrides { /// 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(CompactionOverrides), /// Run all optimizations with default values #[default] All, @@ -298,9 +308,9 @@ pub enum OptimizeAction { /// 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 legacy Lance options type cannot distinguish an omitted fragment target + /// The Lance options type cannot distinguish an omitted fragment target /// from its default value; that default is treated as unspecified remotely. - /// Use [`crate::Table::compact`] with [`CompactionOverrides`] to explicitly + /// Use [`crate::Table::optimize`] with [`CompactionOverrides`] 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. @@ -528,6 +538,9 @@ pub(crate) async fn execute_optimize( ); optimize_indices(table, &OptimizeOptions::default()).await?; } + OptimizeAction::RewriteData(options) => { + stats.compaction = Some(compact_files_impl(table, options.into_options(), None).await?); + } OptimizeAction::Compact { options, remap_options, @@ -749,8 +762,11 @@ mod tests { assert_eq!(table.count_rows(None).await.unwrap(), ROWS as usize * 3); } + #[rstest] + #[case::lance_options(false)] + #[case::optional_overrides(true)] #[tokio::test] - async fn test_optimize_compact_simple() { + async fn test_optimize_compact_simple(#[case] optional_overrides: bool) { let conn = connect("memory://").execute().await.unwrap(); // Create a table with initial data @@ -783,17 +799,27 @@ mod tests { let initial_row_count = table.count_rows(None).await.unwrap(); assert_eq!(initial_row_count, 600); - // Run compaction - let stats = table - .optimize(OptimizeAction::Compact { - options: CompactionOptions { - target_rows_per_fragment: 1000, + // Both Optimize entry points rewrite only data and preserve history. + let stats = if optional_overrides { + table + .optimize(super::CompactionOverrides { + target_rows_per_fragment: Some(1000), ..Default::default() - }, - remap_options: None, - }) - .await - .unwrap(); + }) + .await + } else { + table + .optimize(OptimizeAction::Compact { + options: CompactionOptions { + target_rows_per_fragment: 1000, + ..Default::default() + }, + remap_options: None, + }) + .await + } + .unwrap(); + assert!(stats.prune.is_none()); // Verify compaction occurred assert!(stats.compaction.is_some()); @@ -826,6 +852,8 @@ mod tests { all_values.sort(); let expected: Vec = (0..600).collect(); assert_eq!(all_values, expected); + table.checkout(1).await.unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 100); } #[tokio::test] @@ -1684,6 +1712,7 @@ mod tests { } #[rstest] + #[case::rewrite_data(OptimizeAction::RewriteData(Default::default()))] #[case::all(OptimizeAction::All)] #[case::compact(OptimizeAction::Compact { options: CompactionOptions::default(),