diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index ad274b056..2ff43a226 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1085,13 +1085,13 @@ supported. Pruning old versions and index optimization are silently skipped there instead of being attempted, so this call resolves successfully with placeholder statistics (not completed work) once the compaction job has been submitted; it does not wait for that job to finish. -`dataOptions` can tune the four per-job settings documented in -[OptimizeDataOptions](../interfaces/OptimizeDataOptions.md). Older-server errors are propagated without +The flat options tune the four per-job settings documented in +[OptimizeOptions](../interfaces/OptimizeOptions.md). Older-server errors are propagated without retrying with the settings removed. #### Parameters -* **options?**: `Partial`<[`OptimizeOptions`](../interfaces/OptimizeOptions.md)> +* **options?**: [`OptimizeOptions`](../interfaces/OptimizeOptions.md) #### Returns @@ -1117,7 +1117,7 @@ Reopen with db.openJob(job.id!). A wait timeout does not cancel #### Parameters -* **\_options?**: [`OptimizeDataOptions`](../interfaces/OptimizeDataOptions.md) +* **\_options?**: [`OptimizeOptions`](../interfaces/OptimizeOptions.md) #### Returns diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index ae5223aec..f93c6898c 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -126,7 +126,6 @@ - [NativeOAuthConfig](interfaces/NativeOAuthConfig.md) - [OAuthConfig](interfaces/OAuthConfig.md) - [OpenTableOptions](interfaces/OpenTableOptions.md) -- [OptimizeDataOptions](interfaces/OptimizeDataOptions.md) - [OptimizeOptions](interfaces/OptimizeOptions.md) - [OptimizeResult](interfaces/OptimizeResult.md) - [OptimizeStats](interfaces/OptimizeStats.md) diff --git a/docs/src/js/interfaces/OptimizeDataOptions.md b/docs/src/js/interfaces/OptimizeDataOptions.md deleted file mode 100644 index 8d3ac6cc4..000000000 --- a/docs/src/js/interfaces/OptimizeDataOptions.md +++ /dev/null @@ -1,49 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / OptimizeDataOptions - -# Interface: OptimizeDataOptions - -Per-invocation compaction settings. Values must be safe integers. - -## Properties - -### batchSize? - -```ts -optional batchSize: number; -``` - -Positive scanner batch size in rows. - -*** - -### ioBufferSize? - -```ts -optional ioBufferSize: number; -``` - -Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure. - -*** - -### maxSourceRows? - -```ts -optional maxSourceRows: number; -``` - -Positive live-source-row budget across whole tasks; an oversized first task can produce no work. - -*** - -### targetRowsPerFragment? - -```ts -optional targetRowsPerFragment: number; -``` - -Positive target rows per output fragment; also affects candidate selection. diff --git a/docs/src/js/interfaces/OptimizeOptions.md b/docs/src/js/interfaces/OptimizeOptions.md index 01c9f5002..2eced7feb 100644 --- a/docs/src/js/interfaces/OptimizeOptions.md +++ b/docs/src/js/interfaces/OptimizeOptions.md @@ -6,6 +6,9 @@ # Interface: OptimizeOptions +Flat Optimize settings for submission and durable jobs. +Remote jobs support data rewrites; cleanup options are Embedded-only. + ## Properties ### action? @@ -14,70 +17,66 @@ 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. +Run only data rewriting, retaining history and skipping separate index maintenance. *** -### cleanupOlderThan +### batchSize? ```ts -cleanupOlderThan: Date; +optional batchSize: number; ``` -If set then all versions older than the given date -be removed. The current version will never be removed. -The default is 7 days - -#### Example - -```ts -// Delete all versions older than 1 day -const olderThan = new Date(); -olderThan.setDate(olderThan.getDate() - 1)); -tbl.optimize({cleanupOlderThan: olderThan}); - -// Delete versions committed before this point. Versions created by the -// optimize call itself are newer than the cutoff and will be retained. -tbl.optimize({cleanupOlderThan: new Date()}); -``` +Positive scanner batch size in rows. *** -### dataOptions? +### cleanupOlderThan? ```ts -optional dataOptions: OptimizeDataOptions; +optional cleanupOlderThan: Date; ``` -Compaction settings for this invocation. Omitted remote values inherit table -tuning, then deployment/built-in defaults. -Remote tables require a server supporting these SQL options; settings do -not change table policy. This is not a runtime or total-memory limit. - -#### Example - -```ts -await tbl.optimize({ dataOptions: { - targetRowsPerFragment: 1000, maxSourceRows: 5000, - ioBufferSize: 64 * 1024 * 1024, batchSize: 128, -} }); -``` +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. *** -### deleteUnverified +### deleteUnverified? ```ts -deleteUnverified: boolean; +optional deleteUnverified: boolean; ``` -Because they may be part of an in-progress transaction, files newer than -7 days old are not deleted by default. If you are sure that there are no -in-progress transactions, then you can set this to true to delete all -files older than `cleanupOlderThan`. +Embedded: also remove unverified files. Only enable when no other process +can be writing this dataset. Defaults to false; unavailable for durable jobs. -**WARNING**: This should only be set to true if you can guarantee that -no other process is currently working on this dataset. Otherwise the -dataset could be put into a corrupted state. +*** + +### ioBufferSize? + +```ts +optional ioBufferSize: number; +``` + +Scanner read-ahead budget in bytes; zero disables byte-based backpressure. + +*** + +### maxSourceRows? + +```ts +optional maxSourceRows: number; +``` + +Positive live-source-row budget across whole rewrite tasks. + +*** + +### targetRowsPerFragment? + +```ts +optional targetRowsPerFragment: number; +``` + +Positive target rows per output fragment. Omitted remote values inherit table policy. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index c1ef9605a..4fa06a501 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -377,7 +377,7 @@ warning-only no-op; the former `compact_files()` method is removed. `optimize` submits a durable compaction job and returns once that submission is accepted, not once compaction itself finishes. Pruning and index optimization are not yet supported remotely, so it silently skips them and returns with -zeroed pruning statistics. Remote `data_options` support per-job +zeroed pruning statistics. Remote Optimize supports per-job `target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and `batch_size` on compatible servers. Other non-default settings raise `NotImplementedError` before submission; older-server errors are returned without dropping options. @@ -390,12 +390,10 @@ unchanged. Table `enabled` controls automatic scheduling; explicit manual runs remain allowed. ```python -table.optimize(data_options={ - "target_rows_per_fragment": 100_000, - "max_source_rows": 1_000_000, - "io_buffer_size": 64 * 1024 * 1024, - "batch_size": 1024, -}) +table.optimize(target_rows_per_fragment=100_000, + max_source_rows=1_000_000, + io_buffer_size=64 * 1024 * 1024, + batch_size=1024) ``` Removed Tantivy options produce the same explanatory errors on both backends. @@ -409,7 +407,7 @@ code that used the former LanceDB Enterprise-only argument order. ::: lancedb.table.Table -::: lancedb.table.OptimizeDataOptions +::: lancedb.table.OptimizeOptions ::: lancedb.table.FragmentStatistics diff --git a/docs/web-tests/py/test_doc_storage_examples.py b/docs/web-tests/py/test_doc_storage_examples.py index eda38b38c..4bdcb263a 100644 --- a/docs/web-tests/py/test_doc_storage_examples.py +++ b/docs/web-tests/py/test_doc_storage_examples.py @@ -16,23 +16,23 @@ def test_compaction_tuning(mem_db): assert table.stats()["fragment_stats"]["num_fragments"] == 2 # --8<-- [start:storage_compaction_tuning] - from lancedb import OptimizeDataOptions + from lancedb import OptimizeOptions desired_fragment_bytes = 64 * 1024 average_row_bytes = 1024 # Estimate from representative rows. - options: OptimizeDataOptions = { + options: OptimizeOptions = { "target_rows_per_fragment": max(1, desired_fragment_bytes // average_row_bytes), "batch_size": 16, "num_threads": 1, } - table.optimize(data_options=options) + table.optimize(**options) # --8<-- [end:storage_compaction_tuning] assert table.stats()["fragment_stats"]["num_fragments"] == 1 assert table.count_rows() == 64 table.add([{"id": 64, "payload": payload}]) - table.optimize(data_options=options) + table.optimize(**options) assert table.stats()["fragment_stats"]["num_fragments"] == 2 assert sorted(table.to_arrow()["id"].to_pylist()) == list(range(65)) diff --git a/docs/web/basics/embedded-vs-enterprise.mdx b/docs/web/basics/embedded-vs-enterprise.mdx index 5d6c9455b..bb7512367 100644 --- a/docs/web/basics/embedded-vs-enterprise.mdx +++ b/docs/web/basics/embedded-vs-enterprise.mdx @@ -143,7 +143,7 @@ through separate background jobs and also accepts explicit compaction requests with compatible releases. Python sync/async `optimize_async()`, TypeScript `optimizeAsync()`, and Rust -`Table::optimize_async(OptimizeDataOverrides)` return durable compaction job handles; +`Table::optimize_async(OptimizeOverrides)` 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; diff --git a/docs/web/basics/lance.mdx b/docs/web/basics/lance.mdx index d1ebf1450..65117a933 100644 --- a/docs/web/basics/lance.mdx +++ b/docs/web/basics/lance.mdx @@ -65,7 +65,7 @@ boundaries). | `ds.to_batches(batch_size=k)` | `tbl.search().to_batches(k)` | | `ds.take(offsets)` | `tbl.__getitems__(offsets)` (preserves offset order) or `tbl.take_offsets(offsets).to_arrow()` (unordered) | | `ds.versions()`, `ds.checkout_version(v)`, `ds.restore()` | `tbl.list_versions()`, `tbl.checkout(v)`, `tbl.restore()` | -| `ds.optimize.compact_files(...)`, `ds.cleanup_old_versions(...)` | `tbl.optimize(data_options=..., cleanup_older_than=...)` | +| `ds.optimize.compact_files(...)`, `ds.cleanup_old_versions(...)` | `tbl.optimize(target_rows_per_fragment=1000, cleanup_older_than=...)` | ## Learn more {#next} diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 65936aa27..0fdc64d0d 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -78,7 +78,7 @@ use the job-returning API to wait for the actual rewrite and obtain its result. from datetime import timedelta job = table.optimize_async( - data_options={"target_rows_per_fragment": 1000, "batch_size": 128} + target_rows_per_fragment=1000, batch_size=128 ) result = job.wait(timeout=timedelta(minutes=10)) print(result.rows_succeeded, result.fragments_removed, result.fragments_added) @@ -102,9 +102,9 @@ if (job.id !== null) { ```rust Rust use std::time::Duration; use lancedb::job::JobWaitOptions; -use lancedb::table::{OptimizeResult, optimize::OptimizeDataOverrides}; +use lancedb::table::{OptimizeResult, optimize::OptimizeOverrides}; -let job = table.optimize_async(OptimizeDataOverrides { +let job = table.optimize_async(OptimizeOverrides { target_rows_per_fragment: Some(1000), batch_size: Some(128), ..Default::default() @@ -374,8 +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 -can use `Table::optimize(OptimizeDataOverrides)` or -`Table::optimize_async(OptimizeDataOverrides)` for that distinction: the legacy +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. @@ -444,7 +444,7 @@ table.optimize(cleanup_older_than=timedelta(days=1)) # reclaim space sooner The best practice is to run `optimize()` after large writes or on a schedule. It also bundles incremental index updates. See [Incremental Indexing](/indexing/incremental-indexing) for the breakdown. Updates also move rows out of the vector index, so they remain searchable but unindexed. Update or rebuild the index after large update batches. {/* -Draft for the Python data_options release. Keep this section unpublished +Draft for the Python Optimize tuning release. Keep this section unpublished until the first supported release is confirmed. ### Tune compaction for wide rows {#tune-wide-rows} @@ -467,8 +467,8 @@ The Rust example runs compaction only. Run pruning and index optimization separately when needed; Python's `optimize()` includes those steps. TypeScript's `optimize()` exposes the fragment row target through -`dataOptions.targetRowsPerFragment` and the scanner batch size through -`dataOptions.batchSize`. Compaction thread count is not exposed. The tuning +`targetRowsPerFragment` and the scanner batch size through +`batchSize`. Compaction thread count is not exposed. The tuning examples above use Python and Rust tables in LanceDB Embedded. Planning remains row based. The row target bounds later passes after existing @@ -478,7 +478,7 @@ limits output file size rather than compaction memory. The `max_source_rows` and `max_source_bytes` budgets admit whole planned tasks. If the first task exceeds a budget, that run performs no compaction. See the -[OptimizeDataOptions reference](https://lancedb.github.io/lancedb/python/python/#lancedb.table.OptimizeDataOptions) +[OptimizeOptions reference](https://lancedb.github.io/lancedb/python/python/#lancedb.table.OptimizeOptions) for all options and their limits. */} @@ -490,25 +490,25 @@ method to wait for actual results: ```python # Submit and discard the handle. -table.optimize(data_options={"target_rows_per_fragment": 1000}) +table.optimize(target_rows_per_fragment=1000) # Submit and retain status, cancellation, and actual results. -job = table.optimize_async(data_options={"target_rows_per_fragment": 1000}) +job = table.optimize_async(target_rows_per_fragment=1000) result = job.wait() # Async Python: job = await table.optimize_async(); result = await job.wait() ``` ```typescript -await table.optimize({ dataOptions: { targetRowsPerFragment: 1000 } }); +await table.optimize({ targetRowsPerFragment: 1000 }); const job = await table.optimizeAsync({ targetRowsPerFragment: 1000 }); const result = await job.wait(); ``` ```rust -use lancedb::table::OptimizeDataOverrides; +use lancedb::table::OptimizeOptions; async fn optimize_table(table: &lancedb::Table) -> lancedb::Result<()> { - table.optimize(OptimizeDataOverrides::default()).await?; - let job = table.optimize_async(OptimizeDataOverrides::default()).await?; + table.optimize(OptimizeOptions::default()).await?; + let job = table.optimize_async(OptimizeOptions::default()).await?; let result = job.wait().await?; println!("Committed {} rows", result.rows_succeeded); Ok(()) @@ -519,14 +519,14 @@ 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(OptimizeDataOverrides::default())`. Rewrite-only requests preserve old +`optimize(OptimizeOverrides::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", data_options=...)`, with rewrite metrics +`optimize(action="rewrite_data", target_rows_per_fragment=1000)`, with rewrite metrics under `stats.compaction`. The old names are removed without aliases. ### Optimize naming migration @@ -537,19 +537,49 @@ Data names for the settings specific to data rewrites: | Previous name | Current name | | --- | --- | | `CompactionResult` | `OptimizeResult` | -| `CompactionOptions` | `OptimizeDataOptions` | -| Rust `CompactionOverrides` | `OptimizeDataOverrides` | +| `CompactionOptions` | `OptimizeOptions` | +| Rust `CompactionOverrides` | `OptimizeOverrides` | | Rust `CompactionMode` | `OptimizeDataMode` | -| Python `compaction_options=` | `data_options=` | -| TypeScript `compactionOptions` | `dataOptions` | +| Rust index-maintenance `OptimizeOptions` | `IndexOptimizeOptions` | +| Python `compaction_options=` / `data_options=` | Flat keyword arguments | +| TypeScript `compactionOptions` / `dataOptions` | Flat `OptimizeOptions` fields | | Python `lancedb.compaction` | `lancedb.optimize` | | Rust `OptimizeAction::Compact` | `OptimizeAction::RewriteDataWithOptions` | These names are replaced without compatibility aliases. TypeScript rejects the -removed `compactionOptions` property before submission; Python rejects the old -keyword. This prevents a requested work limit from being silently ignored. +removed `compactionOptions` and `dataOptions` properties before submission. +Python rejects the old wrapper keywords. This prevents a requested work limit from being silently ignored. `CompactionStats` and `OptimizeStats.compaction` still identify the compaction phase within Embedded's broader maintenance cycle. 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: + +```python +from lancedb import OptimizeOptions + +options: OptimizeOptions = {"target_rows_per_fragment": 1000, "batch_size": 128} +table.optimize(**options) +job = table.optimize_async(**options) +``` + +```typescript +import type { OptimizeOptions } from "@lancedb/lancedb"; + +const options: OptimizeOptions = { targetRowsPerFragment: 1000, batchSize: 128 }; +await table.optimize(options); +const job = await table.optimizeAsync(options); +``` + +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. +Its separate index-maintenance options are `IndexOptimizeOptions`. +`OptimizeOverrides` retains omitted-versus-explicit values when inheriting remote +policy. No `data_options` or `dataOptions` wrapper is accepted. diff --git a/docs/web/snippets/doc_storage_examples.mdx b/docs/web/snippets/doc_storage_examples.mdx index 09390260d..c700f83ff 100644 --- a/docs/web/snippets/doc_storage_examples.mdx +++ b/docs/web/snippets/doc_storage_examples.mdx @@ -1,8 +1,8 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} -export const PyStorageCompactionTuning = "from lancedb import OptimizeDataOptions\n\ndesired_fragment_bytes = 64 * 1024\naverage_row_bytes = 1024 # Estimate from representative rows.\noptions: OptimizeDataOptions = {\n \"target_rows_per_fragment\": max(1, desired_fragment_bytes // average_row_bytes),\n \"batch_size\": 16,\n \"num_threads\": 1,\n}\ntable.optimize(data_options=options)\n"; +export const PyStorageCompactionTuning = "from lancedb import OptimizeOptions\n\ndesired_fragment_bytes = 64 * 1024\naverage_row_bytes = 1024 # Estimate from representative rows.\noptions: OptimizeOptions = {\n \"target_rows_per_fragment\": max(1, desired_fragment_bytes // average_row_bytes),\n \"batch_size\": 16,\n \"num_threads\": 1,\n}\ntable.optimize(**options)\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::{OptimizeDataOptions, OptimizeAction};\n\nlet desired_fragment_bytes: usize = 64 * 1024;\nlet average_row_bytes: usize = 1024; // Estimate from representative rows.\nlet options = OptimizeDataOptions {\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::{OptimizeOptions, OptimizeAction};\n\nlet desired_fragment_bytes: usize = 64 * 1024;\nlet average_row_bytes: usize = 1024; // Estimate from representative rows.\nlet options = OptimizeOptions {\n target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1),\n batch_size: Some(16),\n num_threads: Some(1),\n ..Default::default()\n};\ntable\n .optimize(OptimizeAction::RewriteDataWithOptions {\n options,\n remap_options: None,\n })\n .await?;\n"; diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 12f9317c1..c000ad149 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -13,7 +13,7 @@ import { type BlobMode, Connection, MatchQuery, - type OptimizeDataOptions, + type OptimizeOptions, PhraseQuery, Query, Table, @@ -4128,7 +4128,7 @@ it("forwards per-job compaction options to the native binding", async () => { ioBufferSize: 0, batchSize: 8, }; - await table.optimize({ dataOptions }); + await table.optimize({ ...dataOptions }); expect(optimize).toHaveBeenCalledWith( undefined, undefined, @@ -4142,11 +4142,11 @@ it("rejects unsupported JavaScript compaction options before native submission", const table = new LocalTable({ optimize } as never); await expect( table.optimize({ - dataOptions: { + ...({ maxSourceBytes: 1024, - } as unknown as OptimizeDataOptions, + } as unknown as OptimizeOptions), }), - ).rejects.toThrow("Unsupported Optimize data option: maxSourceBytes"); + ).rejects.toThrow("Unsupported Optimize option: maxSourceBytes"); expect(optimize).not.toHaveBeenCalled(); }); @@ -4171,12 +4171,10 @@ describe("per-job compaction options", () => { }); it("bounds source work and preserves zero I/O buffering", async () => { const stats = await table.optimize({ - dataOptions: { - targetRowsPerFragment: 20, - maxSourceRows: 25, - ioBufferSize: 0, - batchSize: 8, - }, + targetRowsPerFragment: 20, + maxSourceRows: 25, + ioBufferSize: 0, + batchSize: 8, }); expect(stats.compaction.fragmentsRemoved).toBe(2); expect(stats.compaction.fragmentsAdded).toBe(1); @@ -4186,7 +4184,7 @@ describe("per-job compaction options", () => { expect(defaults.compaction.fragmentsAdded).toBe(1); expect(await table.countRows()).toBe(80); }); - const invalid: OptimizeDataOptions[] = [ + const invalid: OptimizeOptions[] = [ { targetRowsPerFragment: 0 }, { maxSourceRows: 0 }, { batchSize: 0 }, @@ -4199,7 +4197,7 @@ describe("per-job compaction options", () => { { batchSize: 2 ** 32 }, ]; it.each(invalid)("rejects invalid settings %p", async (dataOptions) => { - await expect(table.optimize({ dataOptions })).rejects.toThrow( + await expect(table.optimize({ ...dataOptions })).rejects.toThrow( /safe integer/, ); expect(await table.countRows()).toBe(80); @@ -6011,7 +6009,7 @@ describe("durable compaction validation", () => { ); await expect( table.optimizeAsync({ unrecognizedLimit: 1 } as never), - ).rejects.toThrow("Unsupported Optimize data option"); + ).rejects.toThrow("Unsupported Optimize option"); await expect( table.optimizeAsync({ targetRowsPerFragment: 0 }), ).rejects.toThrow("safe integer"); @@ -6108,3 +6106,38 @@ test("rejects removed compactionOptions without silently submitting defaults", a ).rejects.toThrow("Unsupported Optimize option: compactionOptions"); expect(optimize).not.toHaveBeenCalled(); }); + +it("uses the same flat OptimizeOptions for durable submission", async () => { + const optimizeAsync = jest.fn().mockResolvedValue({}); + const table = new LocalTable({ optimizeAsync } as never); + await table.optimizeAsync({ + targetRowsPerFragment: 100, + ioBufferSize: 0, + action: "rewrite_data", + }); + expect(optimizeAsync).toHaveBeenCalledWith({ + targetRowsPerFragment: 100, + ioBufferSize: 0, + }); +}); + +it.each([{ cleanupOlderThan: new Date() }, { deleteUnverified: true }])( + "rejects unsupported durable maintenance before submission: %p", + async (options) => { + const optimizeAsync = jest.fn(); + const table = new LocalTable({ optimizeAsync } as never); + await expect(table.optimizeAsync(options)).rejects.toThrow( + "unsupported by Optimize jobs", + ); + expect(optimizeAsync).not.toHaveBeenCalled(); + }, +); + +it("rejects the removed dataOptions wrapper before submission", async () => { + const optimize = jest.fn(); + const table = new LocalTable({ optimize } as never); + await expect( + table.optimize({ dataOptions: { maxSourceRows: 1 } } as never), + ).rejects.toThrow("Unsupported Optimize option: dataOptions"); + expect(optimize).not.toHaveBeenCalled(); +}); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 29355382b..a7b43e15e 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -175,7 +175,6 @@ export { AddDataOptions, UpdateOptions, OptimizeOptions, - OptimizeDataOptions, PrewarmDataOptions, Version, WriteProgress, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index dde1c1095..8ff3ba265 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -186,62 +186,25 @@ export interface PrewarmDataOptions { concurrency?: number; } -/** Per-invocation compaction settings. Values must be safe integers. */ -export interface OptimizeDataOptions { - /** Positive target rows per output fragment; also affects candidate selection. */ +/** Flat Optimize settings for submission and durable jobs. + * Remote jobs support data rewrites; cleanup options are Embedded-only. */ +export interface OptimizeOptions { + /** Positive target rows per output fragment. Omitted remote values inherit table policy. */ targetRowsPerFragment?: number; - /** Positive live-source-row budget across whole tasks; an oversized first task can produce no work. */ + /** Positive live-source-row budget across whole rewrite tasks. */ maxSourceRows?: number; - /** Scanner I/O read-ahead budget in bytes; zero disables byte-based I/O backpressure. */ + /** Scanner read-ahead budget in bytes; zero disables byte-based backpressure. */ ioBufferSize?: number; /** Positive scanner batch size in rows. */ batchSize?: number; -} - -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. */ + /** Run only data rewriting, retaining history and skipping separate index maintenance. */ action?: "rewrite_data"; - - /** - * Compaction settings for this invocation. Omitted remote values inherit table - * tuning, then deployment/built-in defaults. - * Remote tables require a server supporting these SQL options; settings do - * not change table policy. This is not a runtime or total-memory limit. - * @example - * await tbl.optimize({ dataOptions: { - * targetRowsPerFragment: 1000, maxSourceRows: 5000, - * ioBufferSize: 64 * 1024 * 1024, batchSize: 128, - * } }); - */ - dataOptions?: OptimizeDataOptions; - /** - * If set then all versions older than the given date - * be removed. The current version will never be removed. - * The default is 7 days - * @example - * // Delete all versions older than 1 day - * const olderThan = new Date(); - * olderThan.setDate(olderThan.getDate() - 1)); - * tbl.optimize({cleanupOlderThan: olderThan}); - * - * // Delete versions committed before this point. Versions created by the - * // optimize call itself are newer than the cutoff and will be retained. - * tbl.optimize({cleanupOlderThan: new Date()}); - */ - cleanupOlderThan: Date; - /** - * Because they may be part of an in-progress transaction, files newer than - * 7 days old are not deleted by default. If you are sure that there are no - * in-progress transactions, then you can set this to true to delete all - * files older than `cleanupOlderThan`. - * - * **WARNING**: This should only be set to true if you can guarantee that - * no other process is currently working on this dataset. Otherwise the - * dataset could be put into a corrupted state. - */ - deleteUnverified: boolean; + /** 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. */ + cleanupOlderThan?: Date; + /** Embedded: also remove unverified files. Only enable when no other process + * can be writing this dataset. Defaults to false; unavailable for durable jobs. */ + deleteUnverified?: boolean; } export interface Version { @@ -1363,7 +1326,7 @@ export abstract class Table { * console.log(result.rowsSucceeded, result.fragmentsRemoved); */ async optimizeAsync( - _options?: OptimizeDataOptions, + _options?: OptimizeOptions, ): Promise> { throw new Error("compaction jobs are only supported on remote tables"); } @@ -1391,11 +1354,11 @@ export abstract class Table { * skipped there instead of being attempted, so this call resolves * successfully with placeholder statistics (not completed work) once the * compaction job has been submitted; it does not wait for that job to finish. - * `dataOptions` can tune the four per-job settings documented in - * {@link OptimizeDataOptions}. Older-server errors are propagated without + * The flat options tune the four per-job settings documented in + * {@link OptimizeOptions}. Older-server errors are propagated without * retrying with the settings removed. */ - abstract optimize(options?: Partial): Promise; + abstract optimize(options?: OptimizeOptions): Promise; /** * List all indices that have been created with {@link Table.createIndex} * @@ -2086,34 +2049,20 @@ export class LocalTable extends Table { return this.inner.currentBranch() ?? null; } - async optimizeAsync( - options?: OptimizeDataOptions, - ): Promise> { - validateOptimizeDataOptions(options); + async optimizeAsync(options?: OptimizeOptions): Promise> { + validateOptimizeOptions(options, true); return new Job( - await this.inner.optimizeAsync(options), + await this.inner.optimizeAsync(optimizeRewriteSettings(options)), decodeOptimizeResult, ); } - async optimize(options?: Partial): Promise { + async optimize(options?: OptimizeOptions): Promise { validateOptimizeOptions(options); - 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?.dataOptions, + optimizeRewriteSettings(options), options?.action, ); } @@ -2411,35 +2360,52 @@ function rowIdsToBigInts(rowIds: readonly (bigint | number)[]): bigint[] { }); } -function validateOptimizeOptions(options?: Partial): void { - const supported = new Set([ - "action", - "dataOptions", - "cleanupOlderThan", - "deleteUnverified", - ]); - for (const key of Object.keys(options ?? {})) { - if (!supported.has(key)) { - throw new Error(`Unsupported Optimize option: ${key}`); - } - } - validateOptimizeDataOptions(options?.dataOptions); -} - -function validateOptimizeDataOptions(options?: OptimizeDataOptions): void { - // JavaScript callers can supply extra keys that TypeScript would reject. - // Refuse them before the native binding can silently discard a work limit. +function validateOptimizeOptions( + options?: OptimizeOptions, + durable = false, +): void { const supported = new Set([ "targetRowsPerFragment", "maxSourceRows", "ioBufferSize", "batchSize", + "action", + "cleanupOlderThan", + "deleteUnverified", ]); for (const key of Object.keys(options ?? {})) { - if (!supported.has(key)) { - throw new Error(`Unsupported Optimize data option: ${key}`); - } + if (!supported.has(key)) + throw new Error(`Unsupported Optimize option: ${key}`); } + if (options?.action !== undefined && options.action !== "rewrite_data") { + throw new Error('action must be "rewrite_data" or undefined'); + } + const cleanup = + options?.cleanupOlderThan !== undefined || + options?.deleteUnverified === true; + if (durable && cleanup) + throw new Error("cleanup options are unsupported by Optimize jobs"); + if (options?.action === "rewrite_data" && cleanup) { + throw new Error( + 'action="rewrite_data" cannot be combined with cleanup options', + ); + } +} + +function optimizeRewriteSettings( + options?: OptimizeOptions, +): OptimizeOptions | undefined { + const tuning: OptimizeOptions = {}; + for (const key of [ + "targetRowsPerFragment", + "maxSourceRows", + "ioBufferSize", + "batchSize", + ] as const) { + const value = options?.[key]; + if (value !== undefined) tuning[key] = value; + } + return Object.keys(tuning).length ? tuning : undefined; } async function toNativePrewarmDataOptions(options?: PrewarmDataOptions) { diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 5d93ccc3f..00bac0705 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -71,15 +71,15 @@ impl PrewarmDataOptions { /// Per-invocation file-compaction settings. All numbers must be safe integers. #[napi(object)] -pub struct OptimizeDataOptions { +pub struct OptimizeOptions { pub target_rows_per_fragment: Option, pub max_source_rows: Option, pub io_buffer_size: Option, pub batch_size: Option, } -impl OptimizeDataOptions { - fn into_overrides(self) -> napi::Result { +impl OptimizeOptions { + fn into_overrides(self) -> napi::Result { const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; fn integer( value: Option, @@ -103,7 +103,7 @@ impl OptimizeDataOptions { } Ok(Some(value as u64)) } - let mut options = lancedb::table::optimize::OptimizeDataOverrides::default(); + let mut options = lancedb::table::optimize::OptimizeOverrides::default(); if let Some(target) = integer( self.target_rows_per_fragment, "targetRowsPerFragment", @@ -1004,10 +1004,10 @@ impl Table { #[napi(catch_unwind)] pub async fn optimize_async( &self, - options: Option, + options: Option, ) -> napi::Result { let options = options - .map(OptimizeDataOptions::into_overrides) + .map(OptimizeOptions::into_overrides) .transpose()? .unwrap_or_default(); let job = self @@ -1023,7 +1023,7 @@ impl Table { &self, before_timestamp_ms: Option, delete_unverified: Option, - data_options: Option, + data_options: Option, action: Option, ) -> napi::Result { let rewrite_only = match action.as_deref() { @@ -1053,7 +1053,7 @@ impl Table { .transpose()?; let overrides = data_options - .map(OptimizeDataOptions::into_overrides) + .map(OptimizeOptions::into_overrides) .transpose()? .unwrap_or_default(); let stats = if rewrite_only { diff --git a/python/pyproject.toml b/python/pyproject.toml index ff64d9772..0363abc55 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -149,6 +149,7 @@ include = [ "python/lancedb/embeddings/__init__.py", "python/lancedb/_lancedb.pyi", "python/type_tests/connect.py", + "python/type_tests/optimize.py", ] exclude = ["python/tests/"] pythonVersion = "3.13" diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 57b5f3590..17c2823d9 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -78,7 +78,7 @@ from .materialized_view import ( ) from .view import ViewDescription as ViewDescription from .graph import PropertyGraph, PropertyGraphDescription -from .table import AsyncTable, OptimizeDataOptions, Table +from .table import AsyncTable, OptimizeOptions, Table from .types import BaseTokenizerType from ._lancedb import Session from .namespace import ( @@ -676,7 +676,7 @@ __all__ = [ "AsyncSqlQuery", "AsyncLanceNamespaceDBConnection", "AsyncTable", - "OptimizeDataOptions", + "OptimizeOptions", "FtsToken", "FunctionColumnAutoRefreshStatus", "FunctionColumnLastRefreshJob", diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 353adc757..3538c9e95 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -3,6 +3,8 @@ from __future__ import annotations +from typing_extensions import Unpack + from collections.abc import Mapping from datetime import timedelta import deprecation @@ -65,7 +67,11 @@ from lancedb.common import DATA, VEC, VECTOR_COLUMN_NAME from lancedb._blob import validate_blob_mode from lancedb.merge import LanceMergeInsertBuilder from lancedb.embeddings import EmbeddingFunctionRegistry -from lancedb.table import _normalize_progress +from lancedb.table import ( + _normalize_progress, + _split_optimize_options, + _optimize_cleanup_since_ms, +) from ..query import ( FullTextOperator, @@ -79,7 +85,7 @@ from ..table import ( AsyncTable, BlobMode, Branches, - OptimizeDataOptions, + OptimizeOptions, OptimizeResult, IndexStatistics, Query, @@ -1100,20 +1106,10 @@ class RemoteTable(Table): ) pass - def optimize_async( - self, *, data_options: Optional[OptimizeDataOptions] = None - ) -> Job[OptimizeResult]: - return Job(LOOP.run(self._table.optimize_async(data_options=data_options))) + def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]: + return Job(LOOP.run(self._table.optimize_async(**options))) - def optimize( - self, - *, - cleanup_older_than: Optional[timedelta] = None, - delete_unverified: bool = False, - retrain: bool = False, - data_options: Optional[OptimizeDataOptions] = None, - action: Optional[Literal["rewrite_data"]] = None, - ) -> OptimizeStats: + def optimize(self, **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 @@ -1126,13 +1122,15 @@ 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 + ) return LOOP.run( - self._table.optimize( - cleanup_older_than=cleanup_older_than, - delete_unverified=delete_unverified, - retrain=retrain, - data_options=data_options, - action=action, + self._table._do_optimize( + _optimize_cleanup_since_ms(cleanup, retrain), + delete_unverified, + tuning, + action, ) ) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 7138b8f09..4cdd769d7 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -31,6 +31,7 @@ from typing import ( overload, ) from urllib.parse import urlparse +from typing_extensions import Unpack from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable @@ -349,9 +350,11 @@ IndexConfigType = Union[ ] -class OptimizeDataOptions(TypedDict, total=False): - """Options that control file compaction during table optimization. +class OptimizeOptions(TypedDict, total=False): + """Flat settings for optimize() and optimize_async(), passed as keywords. + 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 forward ``target_rows_per_fragment``, ``max_source_rows``, ``io_buffer_size``, and ``batch_size`` as per-job SQL options; other non-default settings are @@ -373,12 +376,12 @@ class OptimizeDataOptions(TypedDict, total=False): >>> desired_fragment_bytes = 750 * 1024 * 1024 >>> average_row_bytes = 1_500_000 - >>> options: OptimizeDataOptions = { + >>> options: OptimizeOptions = { ... "target_rows_per_fragment": max( ... 1, desired_fragment_bytes // average_row_bytes ... ), ... } - >>> await table.optimize(data_options=options) # doctest: +SKIP + >>> await table.optimize(**options) # doctest: +SKIP """ target_rows_per_fragment: int @@ -440,6 +443,51 @@ class OptimizeDataOptions(TypedDict, total=False): data_storage_version: str """Data-file version or release selector for compacted output.""" + cleanup_older_than: Optional[timedelta] + """Embedded version-retention age; unsupported by remote 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.""" + + +def _split_optimize_options( + options: OptimizeOptions, *, durable: bool = False +) -> Tuple[ + Optional[Dict[str, Any]], + Optional[timedelta], + bool, + bool, + Optional[Literal["rewrite_data"]], +]: + """Validate the public flat request and extract maintenance controls.""" + unknown = set(options) - OptimizeOptions.__annotations__.keys() + if unknown: + raise TypeError(f"Unsupported Optimize option: {sorted(unknown)[0]}") + tuning: Dict[str, Any] = dict(options) + 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): + raise ValueError( + "cleanup and index-maintenance options are unsupported by Optimize jobs" + ) + if action == "rewrite_data" and ( + cleanup_older_than is not None or delete_unverified + ): + raise ValueError( + "action='rewrite_data' cannot be combined with cleanup options" + ) + return tuning or None, cleanup_older_than, delete_unverified, retrain, action + # Known distance metrics for legacy API detection KNOWN_METRICS = {"l2", "cosine", "dot", "hamming"} @@ -3114,14 +3162,12 @@ class Table(ABC): cleanup for you automatically. """ - def optimize_async( - self, *, data_options: Optional[OptimizeDataOptions] = None - ) -> Job[OptimizeResult]: + def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]: """Submit remote compaction 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 - [OptimizeDataOptions][lancedb.table.OptimizeDataOptions]. + [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. @@ -3135,22 +3181,14 @@ class Table(ABC): cancellation use generic HTTP job APIs and their existing permissions. >>> job = table.optimize_async( # doctest: +SKIP - ... data_options={"target_rows_per_fragment": 1000}) + ... target_rows_per_fragment=1000) >>> result = job.wait() # doctest: +SKIP >>> print(result.rows_succeeded) # doctest: +SKIP """ raise NotImplementedError("compaction jobs are only supported on remote tables") @abstractmethod - def optimize( - self, - *, - cleanup_older_than: Optional[timedelta] = None, - delete_unverified: bool = False, - retrain: bool = False, - data_options: Optional[OptimizeDataOptions] = None, - action: Optional[Literal["rewrite_data"]] = None, - ) -> OptimizeStats: + def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats: """ Optimize the on-disk data and indices for better performance. @@ -3209,11 +3247,12 @@ class Table(ABC): 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. - data_options: OptimizeDataOptions, optional - Options that control file compaction. For large rows, derive a lower + **options: Unpack[OptimizeOptions] + Flat Optimize settings, passed directly as keywords. + For large rows, derive a lower ``target_rows_per_fragment`` from the expected row size to bound later passes. This does not cap the first pass over an existing oversized - fragment; see [OptimizeDataOptions][lancedb.table.OptimizeDataOptions]. + fragment; see [OptimizeOptions][lancedb.table.OptimizeOptions]. Notes ----- @@ -5848,20 +5887,10 @@ class LanceTable(Table): older_than, delete_unverified=delete_unverified ) - def optimize_async( - self, *, data_options: Optional[OptimizeDataOptions] = None - ) -> Job[OptimizeResult]: - return Job(LOOP.run(self._table.optimize_async(data_options=data_options))) + def optimize_async(self, **options: Unpack[OptimizeOptions]) -> Job[OptimizeResult]: + return Job(LOOP.run(self._table.optimize_async(**options))) - def optimize( - self, - *, - cleanup_older_than: Optional[timedelta] = None, - delete_unverified: bool = False, - retrain: bool = False, - data_options: Optional[OptimizeDataOptions] = None, - action: Optional[Literal["rewrite_data"]] = None, - ) -> OptimizeStats: + def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats: """ Optimize the on-disk data and indices for better performance. @@ -5905,11 +5934,12 @@ class LanceTable(Table): 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. - data_options: OptimizeDataOptions, optional - Options that control file compaction. For large rows, derive a lower + **options: Unpack[OptimizeOptions] + Flat Optimize settings, passed directly as keywords. + For large rows, derive a lower ``target_rows_per_fragment`` from the expected row size to bound later passes. This does not cap the first pass over an existing oversized - fragment; see [OptimizeDataOptions][lancedb.table.OptimizeDataOptions]. + fragment; see [OptimizeOptions][lancedb.table.OptimizeOptions]. Notes ----- @@ -5919,11 +5949,14 @@ 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 + ) return LOOP.run( self._table._do_optimize( - _optimize_cleanup_since_ms(cleanup_older_than, retrain), + _optimize_cleanup_since_ms(cleanup, retrain), delete_unverified, - data_options, + tuning, action, ) ) @@ -9544,27 +9577,20 @@ class AsyncTable: return self._inner.current_branch() async def optimize_async( - self, *, data_options: Optional[OptimizeDataOptions] = None + self, **options: Unpack[OptimizeOptions] ) -> AsyncJob[OptimizeResult]: """Submit remote compaction; 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) return _typed_job( await self._inner.optimize_async(data_options), OptimizeResult.from_json, ) - async def optimize( - self, - *, - cleanup_older_than: Optional[timedelta] = None, - delete_unverified: bool = False, - retrain=False, - data_options: Optional[OptimizeDataOptions] = None, - action: Optional[Literal["rewrite_data"]] = None, - ) -> OptimizeStats: + async def optimize(self, **options: Unpack[OptimizeOptions]) -> OptimizeStats: """ Optimize the on-disk data and indices for better performance. @@ -9623,11 +9649,12 @@ class AsyncTable: 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. - data_options: OptimizeDataOptions, optional - Options that control file compaction. For large rows, derive a lower + **options: Unpack[OptimizeOptions] + Flat Optimize settings, passed directly as keywords. + For large rows, derive a lower ``target_rows_per_fragment`` from the expected row size to bound later passes. This does not cap the first pass over an existing oversized - fragment; see [OptimizeDataOptions][lancedb.table.OptimizeDataOptions]. + fragment; see [OptimizeOptions][lancedb.table.OptimizeOptions]. Notes ----- @@ -9637,6 +9664,9 @@ 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 = ( + _split_optimize_options(options) + ) return await self._do_optimize( _optimize_cleanup_since_ms(cleanup_older_than, retrain), delete_unverified, @@ -9648,7 +9678,7 @@ class AsyncTable: self, cleanup_since_ms: Optional[int], delete_unverified: bool, - data_options: Optional[OptimizeDataOptions] = None, + data_options: Optional[Dict[str, Any]] = None, action: Optional[Literal["rewrite_data"]] = None, ) -> OptimizeStats: return await self._inner.optimize( diff --git a/python/python/tests/test_e2e_remote_db.py b/python/python/tests/test_e2e_remote_db.py index 715eb1a6e..2de755591 100644 --- a/python/python/tests/test_e2e_remote_db.py +++ b/python/python/tests/test_e2e_remote_db.py @@ -71,11 +71,9 @@ async def test_maintenance_job_result_and_reopen_against_server( if operation == "compact": job = await call( table.optimize_async, - data_options={ - "target_rows_per_fragment": 100, - "batch_size": 128, - "io_buffer_size": 0, - }, + target_rows_per_fragment=100, + batch_size=128, + io_buffer_size=0, ) elif operation == "prewarm_legacy": assert ( diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 6bbeb51e3..42eaecdfd 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -7593,10 +7593,10 @@ async def test_remote_optimize_forwards_per_job_data_options( if asynchronous: db = await lancedb.connect_async(**kwargs) table = await db.create_table("test", [{"id": 1}]) - stats = await table.optimize(data_options=options) + stats = await table.optimize(**options) else: table = lancedb.connect(**kwargs).create_table("test", [{"id": 1}]) - stats = table.optimize(data_options=options) + stats = table.optimize(**options) assert len(server.tickets) == 1 assert b"OPTIMIZE" in server.tickets[0] assert all(option in server.tickets[0] for option in sql_options) @@ -7620,7 +7620,7 @@ def test_remote_optimize_does_not_drop_options_after_server_rejection(): server = OldServer() with _mock_remote_table_with_sql(server) as table: with pytest.raises(Exception, match="max_source_rows"): - table.optimize(data_options={"max_source_rows": 500}) + table.optimize(max_source_rows=500) assert server.tickets assert all(b"max_source_rows = 500" in ticket for ticket in server.tickets) @@ -7666,7 +7666,7 @@ def test_remote_optimize_rejects_unsupported_data_options_before_submitting(): non-default value was silently ignored -- the server-side guard against unsupported options never saw it. It should now reach that guard and raise before any SQL statement is submitted.""" - from lancedb.table import OptimizeDataOptions + from lancedb.table import OptimizeOptions flight = pytest.importorskip("pyarrow.flight") @@ -7682,10 +7682,10 @@ def test_remote_optimize_rejects_unsupported_data_options_before_submitting(): ) server = UnreachableServer() - options: OptimizeDataOptions = {"max_source_bytes": 1024} + options: OptimizeOptions = {"max_source_bytes": 1024} with _mock_remote_table_with_sql(server) as table: - with pytest.raises(NotImplementedError, match="OptimizeDataOptions"): - table.optimize(data_options=options) + with pytest.raises(NotImplementedError, match="OptimizeOptions"): + table.optimize(**options) assert server.tickets == [] @@ -8471,9 +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.optimize_async( - data_options={"target_rows_per_fragment": 100} - ) + job = await table.optimize_async(target_rows_per_fragment=100) assert job.id == "compacting-job" and not polls if outcome in ("missing", "FAILED", "CANCELLED"): with pytest.raises( @@ -8492,7 +8490,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.optimize_async(data_options={"target_rows_per_fragment": 100}) + job = table.optimize_async(target_rows_per_fragment=100) assert job.id == "compacting-job" and not polls if outcome in ("missing", "FAILED", "CANCELLED"): with pytest.raises( @@ -8572,7 +8570,7 @@ def test_remote_compaction_rejects_boolean_budgets_without_submitting( server = UnusedServer() with _mock_remote_table_with_sql(server) as table: with pytest.raises(ValueError, match="must be an integer, not a bool"): - getattr(table, method)(data_options={option: value}) + getattr(table, method)(**{option: value}) assert server.calls == 0 @@ -8696,3 +8694,51 @@ def test_remote_prewarm_preview_reports_old_server_format_support(): ): table.explain_prewarm_data() assert len(server.tickets) == 1 + + +@pytest.mark.parametrize("method", ["optimize", "optimize_async"]) +@pytest.mark.parametrize("key", ["data_options", "compaction_options"]) +def test_remote_optimize_rejects_wrapped_options_before_submission(method, key): + flight = pytest.importorskip("pyarrow.flight") + + class UnusedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = 0 + + def do_get(self, context, ticket): + self.calls += 1 + raise AssertionError("wrapped settings must not submit SQL") + + server = UnusedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(TypeError, match="Unsupported Optimize option"): + getattr(table, method)(**{key: {"max_source_rows": 1}}) + assert server.calls == 0 + + +@pytest.mark.parametrize( + "options", + [ + {"cleanup_older_than": timedelta(days=1)}, + {"delete_unverified": True}, + {"retrain": True}, + ], +) +def test_remote_optimize_job_rejects_maintenance_options_before_submission(options): + flight = pytest.importorskip("pyarrow.flight") + + class UnusedServer(flight.FlightServerBase): + def __init__(self): + super().__init__("grpc://127.0.0.1:0") + self.calls = 0 + + def do_get(self, context, ticket): + self.calls += 1 + raise AssertionError("unsupported maintenance must not submit SQL") + + server = UnusedServer() + with _mock_remote_table_with_sql(server) as table: + with pytest.raises(ValueError, match="unsupported by Optimize jobs"): + table.optimize_async(**options) + assert server.calls == 0 diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 90a30d3f1..a4e5828cf 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -5457,27 +5457,23 @@ async def test_optimize_data_options(mem_db_async: AsyncConnection): await table.add([{"x": 2}]) stats = await table.optimize( - data_options={ - "target_rows_per_fragment": 1, - "batch_size": 1, - "num_threads": 1, - } + target_rows_per_fragment=1, batch_size=1, num_threads=1 ) assert stats.compaction.fragments_removed == 0 assert stats.compaction.fragments_added == 0 - stats = await table.optimize(data_options={"target_rows_per_fragment": 3}) + stats = await table.optimize(target_rows_per_fragment=3) assert stats.compaction.fragments_removed == 2 assert stats.compaction.fragments_added == 1 - with pytest.raises(ValueError, match="Invalid compaction option: unknown"): - await table.optimize(data_options={"unknown": 1}) + with pytest.raises(TypeError, match="Unsupported Optimize option: unknown"): + await table.optimize(unknown=1) def test_optimize_data_options_sync(mem_db: DBConnection): table = mem_db.create_table("test", data=[{"x": 1}]) with pytest.raises(ValueError, match="target_rows_per_fragment must be between"): - table.optimize(data_options={"target_rows_per_fragment": 0}) + table.optimize(target_rows_per_fragment=0) @pytest.mark.parametrize("option", ["max_source_rows", "max_source_bytes"]) @@ -5489,7 +5485,7 @@ async def test_optimize_compaction_source_limits( await table.add([{"x": 2}]) stats = await table.optimize( - data_options={ + **{ "target_rows_per_fragment": 3, option: 1, } @@ -5505,24 +5501,14 @@ async def test_optimize_compaction_data_storage_version( table = await mem_db_async.create_table("test", data=[{"x": 1}]) await table.add([{"x": 2}]) - stats = await table.optimize( - data_options={ - "target_rows_per_fragment": 3, - "data_storage_version": "2.2", - } - ) + stats = await table.optimize(target_rows_per_fragment=3, data_storage_version="2.2") assert stats.compaction.fragments_removed == 2 assert stats.compaction.fragments_added == 1 table = await mem_db_async.create_table("cross_family", data=[{"x": 1}]) await table.add([{"x": 2}]) with pytest.raises(ValueError, match="V1 and V2 storage versions cannot be mixed"): - await table.optimize( - data_options={ - "target_rows_per_fragment": 3, - "data_storage_version": "legacy", - } - ) + await table.optimize(target_rows_per_fragment=3, data_storage_version="legacy") @pytest.mark.asyncio @@ -5530,16 +5516,11 @@ async def test_optimize_compaction_excluded_fragments(mem_db_async: AsyncConnect table = await mem_db_async.create_table("test", data=[{"x": 1}]) await table.add([{"x": 2}]) - stats = await table.optimize( - data_options={ - "target_rows_per_fragment": 3, - "excluded_fragment_ids": [0], - } - ) + stats = await table.optimize(target_rows_per_fragment=3, excluded_fragment_ids=[0]) assert stats.compaction.fragments_removed == 0 assert stats.compaction.fragments_added == 0 - stats = await table.optimize(data_options={"target_rows_per_fragment": 3}) + stats = await table.optimize(target_rows_per_fragment=3) assert stats.compaction.fragments_removed == 2 assert stats.compaction.fragments_added == 1 @@ -5576,7 +5557,7 @@ async def test_optimize_data_options_validation( ): table = await mem_db_async.create_table("test", data=[{"x": 1}]) with pytest.raises(ValueError, match=message): - await table.optimize(data_options={option: value}) + await table.optimize(**{option: value}) @pytest.mark.asyncio diff --git a/python/python/tests/test_table_signatures.py b/python/python/tests/test_table_signatures.py index 802b04626..735167a64 100644 --- a/python/python/tests/test_table_signatures.py +++ b/python/python/tests/test_table_signatures.py @@ -189,18 +189,12 @@ def test_remote_maintenance_options_warn(method, kwargs): def test_remote_optimize_options(): handle = MagicMock() - handle.optimize = AsyncMock(side_effect=NotImplementedError("remote optimize")) + handle._do_optimize = AsyncMock(side_effect=NotImplementedError("remote optimize")) table = RemoteTable(handle, "test_db") age = timedelta(days=1) with pytest.raises(NotImplementedError, match="remote optimize"): table.optimize(cleanup_older_than=age, delete_unverified=True, retrain=True) - handle.optimize.assert_awaited_once_with( - cleanup_older_than=age, - delete_unverified=True, - retrain=True, - data_options=None, - action=None, - ) + handle._do_optimize.assert_awaited_once_with(86_400_000, True, None, None) @pytest.mark.parametrize( @@ -268,36 +262,41 @@ def test_optimize_has_no_legacy_compaction_aliases(cls): def test_remote_optimize_rewrite_action(): handle = MagicMock() - handle.optimize = AsyncMock(return_value="accepted") + handle._do_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, - data_options=None, - action="rewrite_data", - ) + handle._do_optimize.assert_awaited_once_with(None, False, None, "rewrite_data") @pytest.mark.parametrize("cls", [Table, LanceTable, RemoteTable]) @pytest.mark.parametrize("method", ["optimize", "optimize_async"]) def test_optimize_public_options_names(cls, method): parameters = inspect.signature(getattr(cls, method)).parameters - assert "data_options" in parameters + assert parameters["options"].kind is inspect.Parameter.VAR_KEYWORD + assert "data_options" not in parameters assert "compaction_options" not in parameters def test_optimize_public_types(): import importlib.util from lancedb.optimize import OptimizeResult - from lancedb.table import OptimizeDataOptions + from lancedb.table import OptimizeOptions - assert lancedb.OptimizeDataOptions is OptimizeDataOptions + assert lancedb.OptimizeOptions is OptimizeOptions assert not hasattr(lancedb, "CompactionOptions") + assert not hasattr(lancedb, "OptimizeDataOptions") assert importlib.util.find_spec("lancedb.compaction") is None result = OptimizeResult.from_json( '{"partial_commit":false,"rows_succeeded":1,"rows_failed":0,' '"completion_percentage":100}' ) assert result.rows_succeeded == 1 + + +def test_flat_optimize_forwarding(sync_table): + table, handle = sync_table + handle._do_optimize = AsyncMock(return_value="accepted") + assert table.optimize(target_rows_per_fragment=100, io_buffer_size=0) == "accepted" + handle._do_optimize.assert_awaited_once_with( + None, False, {"target_rows_per_fragment": 100, "io_buffer_size": 0}, None + ) diff --git a/python/python/type_tests/optimize.py b/python/python/type_tests/optimize.py new file mode 100644 index 000000000..28e4ed2c0 --- /dev/null +++ b/python/python/type_tests/optimize.py @@ -0,0 +1,27 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors +# pyright: reportUnnecessaryTypeIgnoreComment=true + +from datetime import timedelta +from typing import assert_type + +from lancedb import AsyncTable, OptimizeOptions, Table +from lancedb._lancedb import OptimizeStats +from lancedb.job import AsyncJob, Job +from lancedb.optimize import OptimizeResult + + +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_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] + table.optimize_async(data_options={"max_source_rows": 1}) # pyright: ignore[reportCallIssue] + + +async def asynchronous(table: AsyncTable) -> None: + options: OptimizeOptions = {"target_rows_per_fragment": 100, "batch_size": 16} + assert_type(await table.optimize(**options), OptimizeStats) + assert_type(await table.optimize_async(**options), AsyncJob[OptimizeResult]) + await table.optimize(compaction_options={"max_source_rows": 1}) # pyright: ignore[reportCallIssue] diff --git a/python/src/table.rs b/python/src/table.rs index 5c76428e5..abdc425da 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -31,7 +31,7 @@ use lancedb::index::scalar::FtsIndexBuilder; use lancedb::table::{ AddDataMode, ColumnAlteration, Duration, FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig, FunctionRefreshPodResources, FunctionWorkerResourceBudget, - IndexRemapMode, NewColumnTransform, OptimizeDataMode, OptimizeDataOptions, Ref, + IndexRemapMode, NewColumnTransform, OptimizeDataMode, OptimizeOptions, Ref, RefreshColumnOptions, Table as LanceDbTable, }; use lancedb::tokenize as lancedb_tokenize; @@ -487,8 +487,8 @@ fn optional_i64_bounded_u64(value: &Bound<'_, PyAny>, name: &str) -> PyResult>) -> PyResult { - let mut parsed = OptimizeDataOptions::default(); +fn parse_data_options(options: Option<&Bound<'_, PyDict>>) -> PyResult { + let mut parsed = OptimizeOptions::default(); let Some(options) = options else { return Ok(parsed); }; @@ -2308,7 +2308,7 @@ impl Table { .unwrap_or(false); let options = parse_data_options(data_options)?; let mut overrides = - lancedb::table::optimize::OptimizeDataOverrides::try_from(options).infer_error()?; + lancedb::table::optimize::OptimizeOverrides::try_from(options).infer_error()?; if !target_specified { overrides.target_rows_per_fragment = None; } @@ -2375,7 +2375,7 @@ impl Table { } } else { let mut overrides = - lancedb::table::optimize::OptimizeDataOverrides::try_from(data_options) + lancedb::table::optimize::OptimizeOverrides::try_from(data_options) .infer_error()?; if !target_specified { overrides.target_rows_per_fragment = None; diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index fe0a2c653..bc2a55844 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -2701,7 +2701,7 @@ mod tests { )] async fn indexes_and_optimize_still_apply_to_a_view() { use crate::index::Index; - use crate::table::{OptimizeAction, OptimizeDataOptions}; + use crate::table::{OptimizeAction, OptimizeOptions}; let conn = connect("memory://").execute().await.unwrap(); let source = conn @@ -2722,7 +2722,7 @@ mod tests { assert_eq!(view.table().list_indices().await.unwrap().len(), 1); view.table() .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions::default(), + options: OptimizeOptions::default(), remap_options: None, }) .await diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 9a186f07c..4e9782533 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -2714,7 +2714,7 @@ async fn remote_optimize_submits_a_compaction_job_over_sql() { let stats = table .optimize( crate::table::optimize::OptimizeAction::RewriteDataWithOptions { - options: crate::table::optimize::OptimizeDataOptions::default(), + options: crate::table::optimize::OptimizeOptions::default(), remap_options: None, }, ) @@ -2769,7 +2769,7 @@ async fn remote_optimize_on_a_branch_submits_a_with_clause_over_sql() { table .optimize( crate::table::optimize::OptimizeAction::RewriteDataWithOptions { - options: crate::table::optimize::OptimizeDataOptions::default(), + options: crate::table::optimize::OptimizeOptions::default(), remap_options: None, }, ) @@ -2820,7 +2820,7 @@ async fn remote_optimize_full_skips_prune_and_index() { let stats = table .optimize_full( - crate::table::optimize::OptimizeDataOptions::default(), + crate::table::optimize::OptimizeOptions::default(), None, None, None, @@ -2880,7 +2880,7 @@ async fn remote_optimize_full_treats_delete_unverified_false_as_default() { let stats = table .optimize_full( - crate::table::optimize::OptimizeDataOptions::default(), + crate::table::optimize::OptimizeOptions::default(), None, None, Some(false), @@ -2901,7 +2901,7 @@ async fn remote_optimize_full_treats_delete_unverified_false_as_default() { /// `delete_unverified=True`) used to get a success result reporting zero /// bytes removed, even though no pruning was attempted at all -- silently /// dropping their storage-reclaim request. It must instead reject before -/// anything is submitted, the same way a non-default `OptimizeDataOptions` is. +/// anything is submitted, the same way a non-default `OptimizeOptions` is. #[tokio::test] async fn remote_optimize_full_rejects_explicit_pruning_options() { async fn assert_rejected_before_submission( @@ -2936,7 +2936,7 @@ async fn remote_optimize_full_rejects_explicit_pruning_options() { let error = table .optimize_full( - crate::table::optimize::OptimizeDataOptions::default(), + crate::table::optimize::OptimizeOptions::default(), older_than, before_timestamp, delete_unverified, @@ -4285,7 +4285,7 @@ async fn remote_optimize_forwards_per_job_options_on_main_and_branch() { table .optimize( crate::table::optimize::OptimizeAction::RewriteDataWithOptions { - options: crate::table::optimize::OptimizeDataOptions { + options: crate::table::optimize::OptimizeOptions { target_rows_per_fragment: 100, max_source_rows: Some(500), io_buffer_size: Some(0), @@ -4321,19 +4321,19 @@ async fn remote_optimize_forwards_per_job_options_on_main_and_branch() { #[tokio::test] async fn remote_compact_preserves_omissions_and_explicit_default_values() { - use crate::table::{OptimizeDataOptions, OptimizeDataOverrides}; - let target = OptimizeDataOptions::default().target_rows_per_fragment; + use crate::table::{OptimizeOptions, OptimizeOverrides}; + let target = OptimizeOptions::default().target_rows_per_fragment; for (options, suffix) in [ - (OptimizeDataOverrides::default(), String::new()), + (OptimizeOverrides::default(), String::new()), ( - OptimizeDataOverrides { + OptimizeOverrides { target_rows_per_fragment: Some(target), ..Default::default() }, format!(" WITH (target_rows_per_fragment = {target})"), ), ( - OptimizeDataOverrides { + OptimizeOverrides { io_buffer_size: Some(0), ..Default::default() }, @@ -4372,7 +4372,7 @@ async fn remote_compact_preserves_omissions_and_explicit_default_values() { #[tokio::test] async fn remote_optimize_parser_errors_are_clear_without_resubmission() { - use crate::table::optimize::OptimizeDataOverrides; + use crate::table::optimize::OptimizeOverrides; for (code, message, unsupported) in [ ( tonic::Code::InvalidArgument, @@ -4434,7 +4434,7 @@ async fn remote_optimize_parser_errors_are_clear_without_resubmission() { ); let error = table .optimize(crate::table::OptimizeAction::RewriteData( - OptimizeDataOverrides::default(), + OptimizeOverrides::default(), )) .await .unwrap_err(); @@ -4474,7 +4474,7 @@ 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::OptimizeDataOverrides { + crate::table::optimize::OptimizeOverrides { io_buffer_size: Some(0), ..Default::default() }, @@ -4817,7 +4817,7 @@ async fn remote_prewarm_rejects_historical_checkout_without_submitting() { #[tokio::test] async fn remote_compaction_tracks_registry_job_and_real_result() { - use crate::table::optimize::OptimizeDataOverrides; + use crate::table::optimize::OptimizeOverrides; let service = TestSqlService { adaptive: true, result: RecordBatch::try_from_iter([( @@ -4860,7 +4860,7 @@ async fn remote_compaction_tracks_registry_job_and_real_result() { ) .with_branch(Some("experiment".into())); let job = table - .optimize_async(OptimizeDataOverrides { + .optimize_async(OptimizeOverrides { 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 16564a56b..b1ce8b52c 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4066,37 +4066,7 @@ 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 overrides = match action { - OptimizeAction::RewriteData(options) => options, - OptimizeAction::RewriteDataWithOptions { - 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::OptimizeDataOverrides::try_from(options)?; - if target == crate::table::OptimizeDataOptions::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::RewriteDataWithOptions." - .into(), - }); - } - }; + let overrides = action.into_remote_overrides()?; 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(), @@ -4119,7 +4089,7 @@ impl BaseTable for RemoteTable { } async fn optimize_async( &self, - options: crate::table::optimize::OptimizeDataOverrides, + options: crate::table::optimize::OptimizeOverrides, ) -> Result> { self.check_mutable().await?; let statement = optimize::statement(&self.name, self.branch.as_deref(), &options)?; @@ -17871,7 +17841,7 @@ mod tests { }); let error = table .optimize(OptimizeAction::RewriteDataWithOptions { - options: crate::table::optimize::OptimizeDataOptions::default(), + options: crate::table::optimize::OptimizeOptions::default(), remap_options: None, }) .await @@ -17887,7 +17857,7 @@ mod tests { let error = table .optimize(OptimizeAction::RewriteDataWithOptions { - options: crate::table::optimize::OptimizeDataOptions::default(), + options: crate::table::optimize::OptimizeOptions::default(), remap_options: Some(Arc::new(lance::dataset::optimize::IgnoreRemap::default())), }) .await @@ -17905,7 +17875,7 @@ mod tests { let error = table .optimize(OptimizeAction::RewriteDataWithOptions { - options: crate::table::optimize::OptimizeDataOptions { + options: crate::table::optimize::OptimizeOptions { target_rows_per_fragment: 17, max_source_bytes: Some(1024), ..Default::default() @@ -17916,7 +17886,7 @@ mod tests { .unwrap_err(); assert!(matches!(error, Error::NotSupported { .. })); - assert!(error.to_string().contains("OptimizeDataOptions")); + assert!(error.to_string().contains("OptimizeOptions")); } #[tokio::test] @@ -17964,7 +17934,7 @@ mod tests { // a REST request (see `test_optimize_requires_sql`). let error = branch .optimize(OptimizeAction::RewriteDataWithOptions { - options: crate::table::optimize::OptimizeDataOptions::default(), + options: crate::table::optimize::OptimizeOptions::default(), remap_options: None, }) .await diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 8b33704f7..097932f57 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -7,7 +7,7 @@ use crate::error::{Error, Result}; pub(super) fn statement( table: &str, branch: Option<&str>, - options: &crate::table::optimize::OptimizeDataOverrides, + options: &crate::table::optimize::OptimizeOverrides, ) -> Result { let mut settings = compaction_sql_options(options)?; if let Some(branch) = branch { @@ -48,7 +48,7 @@ pub(super) fn receipt(batches: &[arrow_array::RecordBatch]) -> Result { } pub(super) fn compaction_sql_options( - options: &crate::table::optimize::OptimizeDataOverrides, + options: &crate::table::optimize::OptimizeOverrides, ) -> Result> { for (name, value) in [ ("target_rows_per_fragment", options.target_rows_per_fragment), @@ -129,7 +129,7 @@ pub(super) fn map_optimize_error(error: Error) -> Error { mod tests { use super::*; use crate::error::JobFailure; - use crate::table::{OptimizeDataOptions, OptimizeDataOverrides}; + use crate::table::{OptimizeOptions, OptimizeOverrides}; use std::sync::Arc; fn sql_error(code: tonic::Code, message: &str) -> Error { @@ -248,13 +248,13 @@ mod tests { #[test] fn omissions_and_explicit_default_target_are_distinct() { assert!( - compaction_sql_options(&OptimizeDataOverrides::default()) + compaction_sql_options(&OptimizeOverrides::default()) .unwrap() .is_empty() ); - let target = OptimizeDataOptions::default().target_rows_per_fragment; + let target = OptimizeOptions::default().target_rows_per_fragment; assert_eq!( - compaction_sql_options(&OptimizeDataOverrides { + compaction_sql_options(&OptimizeOverrides { target_rows_per_fragment: Some(target), io_buffer_size: Some(0), ..Default::default() @@ -270,7 +270,7 @@ mod tests { #[test] fn unsupported_settings_are_rejected() { assert!(matches!( - OptimizeDataOverrides::try_from(OptimizeDataOptions { + OptimizeOverrides::try_from(OptimizeOptions { max_source_bytes: Some(1024), ..Default::default() }), @@ -281,15 +281,15 @@ mod tests { #[test] fn invalid_row_settings_are_rejected() { for options in [ - OptimizeDataOverrides { + OptimizeOverrides { target_rows_per_fragment: Some(0), ..Default::default() }, - OptimizeDataOverrides { + OptimizeOverrides { max_source_rows: Some(0), ..Default::default() }, - OptimizeDataOverrides { + OptimizeOverrides { batch_size: Some(0), ..Default::default() }, diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index e60294395..e7a60b1de 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -118,9 +118,9 @@ pub use function_column_status::{ use futures::future::join_all; pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags}; pub use lance::dataset::scanner::DatasetRecordBatchStream; -pub use lance_index::optimize::OptimizeOptions; +pub use lance_index::optimize::OptimizeOptions as IndexOptimizeOptions; pub use optimize::{ - IndexRemapMode, OptimizeAction, OptimizeDataMode, OptimizeDataOptions, OptimizeDataOverrides, + IndexRemapMode, OptimizeAction, OptimizeDataMode, OptimizeOptions, OptimizeOverrides, OptimizeStats, }; pub use refresh::{ @@ -904,7 +904,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Submit remote compaction and retain its durable job and actual outcome. async fn optimize_async( &self, - _options: optimize::OptimizeDataOverrides, + _options: optimize::OptimizeOverrides, ) -> Result> { Err(Error::NotSupported { message: "compaction jobs are only supported on remote tables".into(), @@ -2059,7 +2059,7 @@ impl Table { /// /// # LanceDB Enterprise (remote tables) /// - /// [`OptimizeAction::RewriteData`] accepts [`optimize::OptimizeDataOverrides`] + /// [`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 @@ -2069,9 +2069,9 @@ impl Table { /// /// ```no_run /// # async fn optimize(table: &lancedb::Table) -> lancedb::Result<()> { - /// use lancedb::table::OptimizeDataOverrides; + /// use lancedb::table::OptimizeOverrides; /// // Rewrite only data; omitted settings retain remote table policy. - /// table.optimize(OptimizeDataOverrides { + /// table.optimize(OptimizeOverrides { /// io_buffer_size: Some(0), /// ..Default::default() /// }).await?; @@ -2085,7 +2085,7 @@ impl Table { /// Submit remote compaction 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::OptimizeDataOverrides`] retain + /// and branch. The four fields of [`optimize::OptimizeOverrides`] retain /// server defaults when omitted. Requires a compatible remote SQL server /// and table Ownership plus database/namespace Usage under Standard authorization. /// Historical-version and local handles are unsupported. @@ -2098,9 +2098,12 @@ impl Table { /// file counts, represented as `None`. Reopen with /// `connection.open_job(id).await?.into_typed::()?`. /// + /// Accepts flat [`OptimizeOptions`] directly, or [`optimize::OptimizeOverrides`] + /// when omitted values must be distinguished from explicit SDK defaults. + /// /// ```no_run /// # async fn compact(table: &lancedb::Table) -> lancedb::Result<()> { - /// let job = table.optimize_async(Default::default()).await?; + /// let job = table.optimize_async(lancedb::table::OptimizeOptions::default()).await?; /// let result = job.wait().await?; /// println!("Committed {} rows", result.rows_succeeded); /// # Ok(()) @@ -2108,8 +2111,9 @@ impl Table { /// ``` pub async fn optimize_async( &self, - options: optimize::OptimizeDataOverrides, + options: impl Into, ) -> Result> { + let options = options.into().into_remote_overrides()?; self.inner.optimize_async(options).await } @@ -2117,7 +2121,7 @@ impl Table { #[doc(hidden)] pub async fn optimize_full_with_overrides( &self, - options: optimize::OptimizeDataOverrides, + options: optimize::OptimizeOverrides, older_than: Option, before_timestamp: Option>, delete_unverified: Option, @@ -2178,7 +2182,7 @@ impl Table { /// 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 - /// unsupported `OptimizeDataOptions` are rejected -- rather than a + /// unsupported `OptimizeOptions` are rejected -- rather than a /// success that silently reports zero bytes pruned when nothing was /// pruned at all. A plain call with none of those set only compacts: /// `Prune` and `Index` are skipped here rather than attempted and @@ -2190,7 +2194,7 @@ impl Table { #[doc(hidden)] pub async fn optimize_full( &self, - data_options: OptimizeDataOptions, + data_options: OptimizeOptions, older_than: Option, before_timestamp: Option>, delete_unverified: Option, @@ -2235,7 +2239,7 @@ impl Table { .await? .prune }; - self.optimize(OptimizeAction::Index(OptimizeOptions::default())) + self.optimize(OptimizeAction::Index(IndexOptimizeOptions::default())) .await?; Ok(OptimizeStats { compaction, prune }) } @@ -7090,7 +7094,7 @@ mod tests { // Compaction materializes the deletions. table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { + options: OptimizeOptions { target_rows_per_fragment: 1000, ..Default::default() }, diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 05b34badb..a113cde6b 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -573,7 +573,7 @@ mod tests { IvfHnswFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, }; use crate::query::{ExecutableQuery, QueryBase}; - use crate::table::optimize::{OptimizeAction, OptimizeDataOptions}; + use crate::table::optimize::{OptimizeAction, OptimizeOptions}; use lance_index::scalar::FullTextSearchQuery; use lance_index::scalar::inverted::query::{FtsQuery, MatchQuery}; @@ -2560,7 +2560,7 @@ mod tests { table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { + options: OptimizeOptions { target_rows_per_fragment: 2_000, defer_index_remap: true, ..Default::default() diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 3c5ac4129..cba78ff11 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -22,14 +22,14 @@ use lance::index::{DatasetIndexExt, DatasetIndexInternalExt}; use lance_core::utils::tracing::{DATASET_COMPACTING_EVENT, TRACE_DATASET_EVENTS}; use lance_index::IndexType; use lance_index::metrics::NoOpMetricsCollector; -use lance_index::optimize::OptimizeOptions; +use lance_index::optimize::OptimizeOptions as IndexOptimizeOptions; 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 OptimizeDataOptions, IndexRemapMode, + CompactionMode as OptimizeDataMode, CompactionOptions as OptimizeOptions, IndexRemapMode, }; const MAX_ARROW_FIXED_SIZE_LIST_CHILD_INDEX: u64 = u32::MAX as u64; @@ -126,7 +126,7 @@ fn oversized_sq_partition( async fn validate_sq_index_remapping( dataset: &lance::Dataset, - options: &OptimizeDataOptions, + options: &OptimizeOptions, has_custom_remapper: bool, ) -> Result { let plan = plan_compaction(dataset, options).await?; @@ -219,7 +219,7 @@ async fn validate_sq_index_remapping( /// policy, then deployment/built-in defaults. Explicit values, including a zero /// I/O budget, take precedence. Local tables use Lance defaults for omissions. #[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct OptimizeDataOverrides { +pub struct OptimizeOverrides { pub target_rows_per_fragment: Option, pub max_source_rows: Option, /// Read-ahead budget in bytes; zero disables byte-based I/O backpressure. @@ -227,9 +227,9 @@ pub struct OptimizeDataOverrides { pub batch_size: Option, } -impl OptimizeDataOverrides { - pub(crate) fn into_options(self) -> OptimizeDataOptions { - let mut options = OptimizeDataOptions::default(); +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; } @@ -240,18 +240,18 @@ impl OptimizeDataOverrides { } } -impl TryFrom for OptimizeDataOverrides { +impl TryFrom for OptimizeOverrides { type Error = Error; - fn try_from(options: OptimizeDataOptions) -> Result { + fn try_from(options: OptimizeOptions) -> Result { let mut remaining = options.clone(); - let defaults = OptimizeDataOptions::default(); + let defaults = OptimizeOptions::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 OptimizeDataOptions 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: "remote 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), @@ -262,12 +262,21 @@ impl TryFrom for OptimizeDataOverrides { } } -impl From for OptimizeAction { - fn from(options: OptimizeDataOverrides) -> Self { +impl From for OptimizeAction { + fn from(options: OptimizeOverrides) -> Self { Self::RewriteData(options) } } +impl From for OptimizeAction { + fn from(options: OptimizeOptions) -> Self { + Self::RewriteDataWithOptions { + options, + remap_options: None, + } + } +} + /// Optimize the dataset. /// /// Similar to `VACUUM` in PostgreSQL, it offers different options to @@ -279,7 +288,7 @@ 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(OptimizeDataOverrides), + RewriteData(OptimizeOverrides), /// Run all optimizations with default values #[default] All, @@ -312,7 +321,7 @@ pub enum OptimizeAction { /// 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 [`OptimizeDataOverrides`] to explicitly + /// 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. @@ -326,10 +335,10 @@ pub enum OptimizeAction { /// placeholder rather than the real counts a local table reports. /// /// ``` - /// use lancedb::{Table, table::{OptimizeDataOptions, OptimizeAction}}; + /// use lancedb::{Table, table::{OptimizeOptions, OptimizeAction}}; /// # async fn compact(table: &Table) -> lancedb::Result<()> { /// table.optimize(OptimizeAction::RewriteDataWithOptions { - /// options: OptimizeDataOptions { + /// options: OptimizeOptions { /// target_rows_per_fragment: 100_000, /// max_source_rows: Some(1_000_000), /// io_buffer_size: Some(64 * 1024 * 1024), @@ -348,7 +357,7 @@ pub enum OptimizeAction { /// Older servers may accept submission and fail the compaction job /// asynchronously instead. RewriteDataWithOptions { - options: OptimizeDataOptions, + options: OptimizeOptions, remap_options: Option>, }, /// Prune old version of datasets @@ -395,7 +404,43 @@ pub enum OptimizeAction { /// /// For example, when using IVF, an index will create clusters. Optimizing an index assigns unindexed /// data to the existing clusters, but it does not move the clusters or create new clusters. - Index(OptimizeOptions), + Index(IndexOptimizeOptions), +} + +impl OptimizeAction { + /// Normalize an Enterprise data-rewrite request before any submission. + pub(crate) fn into_remote_overrides(self) -> Result { + match self { + OptimizeAction::RewriteData(options) => Ok(options), + OptimizeAction::RewriteDataWithOptions { + 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::OptimizeOverrides::try_from(options)?; + if target == crate::table::OptimizeOptions::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(), + }) + } + } + } } /// Statistics about the optimization. @@ -411,7 +456,10 @@ pub struct OptimizeStats { /// Internal implementation of optimize_indices /// /// This logic was moved from NativeTable to keep table.rs clean. -pub(crate) async fn optimize_indices(table: &NativeTable, options: &OptimizeOptions) -> Result<()> { +pub(crate) async fn optimize_indices( + table: &NativeTable, + options: &IndexOptimizeOptions, +) -> Result<()> { info!("LanceDB: optimizing indices: {:?}", options); table.dataset.ensure_mutable()?; let mut dataset = (*table.dataset.get().await?).clone(); @@ -500,7 +548,7 @@ pub(crate) async fn cleanup_old_versions_before( /// This calls into [lance::dataset::optimize::compact_files_with_planner]. pub(crate) async fn compact_files_impl( table: &NativeTable, - options: OptimizeDataOptions, + options: OptimizeOptions, remap_options: Option>, ) -> Result { table.dataset.ensure_mutable()?; @@ -528,7 +576,7 @@ pub(crate) async fn execute_optimize( OptimizeAction::All => { // Call helper functions directly to avoid async recursion issues stats.compaction = - Some(compact_files_impl(table, OptimizeDataOptions::default(), None).await?); + Some(compact_files_impl(table, OptimizeOptions::default(), None).await?); stats.prune = Some( cleanup_old_versions( table, @@ -538,7 +586,7 @@ pub(crate) async fn execute_optimize( ) .await?, ); - optimize_indices(table, &OptimizeOptions::default()).await?; + optimize_indices(table, &IndexOptimizeOptions::default()).await?; } OptimizeAction::RewriteData(options) => { stats.compaction = Some(compact_files_impl(table, options.into_options(), None).await?); @@ -595,7 +643,7 @@ mod tests { vector::{IvfHnswSqIndexBuilder, IvfRqIndexBuilder}, }; use crate::query::{ExecutableQuery, QueryBase}; - use crate::table::{OptimizeAction, OptimizeDataOptions, OptimizeStats}; + use crate::table::{OptimizeAction, OptimizeOptions, OptimizeStats}; use futures::TryStreamExt; /// Regression test for https://github.com/lancedb/lancedb/issues/2866. @@ -752,7 +800,7 @@ mod tests { let stats = table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { + options: OptimizeOptions { target_rows_per_fragment: 1_000, ..Default::default() }, @@ -804,19 +852,16 @@ mod tests { // Both Optimize entry points rewrite only data and preserve history. let stats = if optional_overrides { table - .optimize(super::OptimizeDataOverrides { + .optimize(super::OptimizeOverrides { target_rows_per_fragment: Some(1000), ..Default::default() }) .await } else { table - .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { - target_rows_per_fragment: 1000, - ..Default::default() - }, - remap_options: None, + .optimize(OptimizeOptions { + target_rows_per_fragment: 1000, + ..Default::default() }) .await } @@ -854,6 +899,15 @@ mod tests { all_values.sort(); let expected: Vec = (0..600).collect(); assert_eq!(all_values, expected); + let error = table + .optimize_async(OptimizeOptions::default()) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("only supported on remote tables") + ); table.checkout(1).await.unwrap(); assert_eq!(table.count_rows(None).await.unwrap(), 100); } @@ -898,7 +952,7 @@ mod tests { let version_before = table.version().await.unwrap(); let stats = table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { + options: OptimizeOptions { target_rows_per_fragment: 20, num_threads: Some(64), ..Default::default() @@ -966,7 +1020,7 @@ mod tests { let compact_task = tokio::spawn(async move { compact_table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { + options: OptimizeOptions { target_rows_per_fragment: 1_000, ..Default::default() }, @@ -996,7 +1050,7 @@ mod tests { // A second compaction exposed the original out-of-order row-id bug. table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { + options: OptimizeOptions { target_rows_per_fragment: 1_000, ..Default::default() }, @@ -1447,7 +1501,7 @@ mod tests { // Run compaction with deferred index remap let stats = table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { + options: OptimizeOptions { target_rows_per_fragment: 2000, defer_index_remap: true, ..Default::default() @@ -1562,7 +1616,7 @@ mod tests { let stats = table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions { + options: OptimizeOptions { target_rows_per_fragment: 256, defer_index_remap: true, ..Default::default() @@ -1654,7 +1708,7 @@ mod tests { // Run compaction table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions::default(), + options: OptimizeOptions::default(), remap_options: None, }) .await @@ -1717,7 +1771,7 @@ mod tests { #[case::rewrite_data(OptimizeAction::RewriteData(Default::default()))] #[case::all(OptimizeAction::All)] #[case::compact(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions::default(), + options: OptimizeOptions::default(), remap_options: None, })] #[case::prune(OptimizeAction::Prune { diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index eb8bb9bc8..ac569e0ff 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -1719,7 +1719,7 @@ mod tests { table .optimize(crate::table::OptimizeAction::RewriteDataWithOptions { - options: crate::table::OptimizeDataOptions::default(), + options: crate::table::OptimizeOptions::default(), remap_options: None, }) .await @@ -1835,7 +1835,7 @@ mod tests { .unwrap(); table .optimize(crate::table::OptimizeAction::RewriteDataWithOptions { - options: crate::table::OptimizeDataOptions::default(), + options: crate::table::OptimizeOptions::default(), remap_options: None, }) .await @@ -1892,7 +1892,7 @@ mod tests { table.checkout_latest().await.unwrap(); table .optimize(crate::table::OptimizeAction::RewriteDataWithOptions { - options: crate::table::OptimizeDataOptions::default(), + options: crate::table::OptimizeOptions::default(), remap_options: None, }) .await @@ -1921,7 +1921,7 @@ mod tests { append(&table, vec![5]).await; table .optimize(crate::table::OptimizeAction::RewriteDataWithOptions { - options: crate::table::OptimizeDataOptions::default(), + options: crate::table::OptimizeOptions::default(), remap_options: None, }) .await @@ -2227,7 +2227,7 @@ mod tests { append(&table, vec![2_000_000]).await; table .optimize(crate::table::OptimizeAction::RewriteDataWithOptions { - options: crate::table::OptimizeDataOptions::default(), + options: crate::table::OptimizeOptions::default(), remap_options: None, }) .await @@ -2557,7 +2557,7 @@ mod tests { .unwrap(); table .optimize(crate::table::OptimizeAction::RewriteDataWithOptions { - options: crate::table::OptimizeDataOptions::default(), + options: crate::table::OptimizeOptions::default(), remap_options: None, }) .await diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index f5567f967..01ff4f92a 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -23,7 +23,7 @@ use lancedb::{ OPT_NEW_TABLE_STORAGE_VERSION, }, query::{ExecutableQuery, QueryBase}, - table::{AddDataMode, OptimizeAction, OptimizeDataOptions, OptimizeStats, WriteOptions}, + table::{AddDataMode, OptimizeAction, OptimizeOptions, OptimizeStats, WriteOptions}, }; use tempfile::tempdir; @@ -1196,7 +1196,7 @@ async fn fetch_blobs_with_precompaction_row_ids_survives_compaction() -> Result< table .optimize(OptimizeAction::RewriteDataWithOptions { - options: OptimizeDataOptions::default(), + options: OptimizeOptions::default(), remap_options: None, }) .await?; diff --git a/rust/lancedb/tests/doc_storage_examples.rs b/rust/lancedb/tests/doc_storage_examples.rs index b9ba7967a..96d597029 100644 --- a/rust/lancedb/tests/doc_storage_examples.rs +++ b/rust/lancedb/tests/doc_storage_examples.rs @@ -31,11 +31,11 @@ fn wide_rows(ids: Range) -> anyhow::Result lancedb::Result<()> { // --8<-- [start:storage_compaction_tuning] - use lancedb::table::{OptimizeAction, OptimizeDataOptions}; + use lancedb::table::{OptimizeAction, OptimizeOptions}; let desired_fragment_bytes: usize = 64 * 1024; let average_row_bytes: usize = 1024; // Estimate from representative rows. - let options = OptimizeDataOptions { + let options = OptimizeOptions { target_rows_per_fragment: (desired_fragment_bytes / average_row_bytes).max(1), batch_size: Some(16), num_threads: Some(1), diff --git a/rust/lancedb/tests/duplicate_pairs.rs b/rust/lancedb/tests/duplicate_pairs.rs index 1eb651a5b..98ca9da1e 100644 --- a/rust/lancedb/tests/duplicate_pairs.rs +++ b/rust/lancedb/tests/duplicate_pairs.rs @@ -435,7 +435,7 @@ async fn dedup_query_materializes_blob_payloads_and_null_vectors() -> anyhow::Re table.delete("id = 5").await?; table .optimize(lancedb::table::OptimizeAction::RewriteDataWithOptions { - options: lancedb::table::OptimizeDataOptions::default(), + options: lancedb::table::OptimizeOptions::default(), remap_options: None, }) .await?;